commit ef24c0b67e7331e0b3754673376ca07f302ed5f677b2433733cc23029e86c233 Author: Mukan Erkin Törük Date: Mon May 11 03:18:27 2026 +0300 initial: sovereign Mukan Network fork diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..6e22f54 --- /dev/null +++ b/.clang-format @@ -0,0 +1,11 @@ +--- +Language: Proto +BasedOnStyle: Google +IndentWidth: 2 +ColumnLimit: 0 +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +SpacesInSquareBrackets: true +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3e38136 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +build +test/e2e/build +test/e2e/networks +test/logs +test/p2p/data \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4cb67e4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{sh,Makefile}] +indent_style = tab + +[*.proto] +indent_style = space +indent_size = 2 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..4c236c0 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,12 @@ +# CODEOWNERS: https://help.github.com/articles/about-codeowners/ + +# Everything goes through the following "global owners" by default. +# Unless a later match takes precedence, these three will be +# requested for review when someone opens a PR. +# Note that the last matching pattern takes precedence, so +# global owners are only requested if there isn't a more specific +# codeowner specified below. For this reason, the global codeowners +# are often repeated in package-level definitions. +* @cometbft/engineering @cometbft/devrel @cometbft/interchain-inc + +/spec @cometbft/research @cometbft/engineering @cometbft/interchain-inc diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 0000000..f7ec8fd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,83 @@ +--- +name: Bug report +about: Create a report to help us squash bugs! +labels: bug, needs-triage +--- + + +## Bug Report + +### Setup + +**CometBFT version** (use `cometbft version` or `git rev-parse --verify HEAD` if installed from source): + +**Have you tried the latest version**: yes/no + +**ABCI app** (name for built-in, URL for self-written if it's publicly available): + +**Environment**: +- **OS** (e.g. from /etc/os-release): +- **Install tools**: +- **Others**: + +**node command runtime flags**: + +### Config + + + +### What happened? + +### What did you expect to happen? + +### How to reproduce it + + + +### Logs + + + +### `dump_consensus_state` output + + + +### Anything else we need to know + + + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..fad07f9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Ask a question + url: https://github.com/cometbft/cometbft/discussions + about: Please ask and answer questions here diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md new file mode 100644 index 0000000..564af5b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -0,0 +1,29 @@ +--- +name: Feature request +about: Create a proposal to request a feature +labels: enhancement, needs-triage +--- + + + +## Feature Request + +### Summary + + + +### Problem Definition + + + +### Proposal + + diff --git a/.github/ISSUE_TEMPLATE/proposal.md b/.github/ISSUE_TEMPLATE/proposal.md new file mode 100644 index 0000000..af14605 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/proposal.md @@ -0,0 +1,28 @@ +--- +name: Protocol change proposal +about: Create a proposal to request a change to the protocol +labels: protocol-change, needs-triage +--- + + + +## Protocol Change Proposal + +### Summary + + + +### Problem Definition + + + +### Proposal + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..9a76aad --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +--- + +#### PR checklist + +- [ ] Tests written/updated +- [ ] Changelog entry added in `.changelog` (we use [unclog](https://github.com/informalsystems/unclog) to manage our changelog) +- [ ] Updated relevant documentation (`docs/` or `spec/`) and code comments + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..72f28f7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,69 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + target-branch: "main" + open-pull-requests-limit: 10 + labels: + - dependencies + - automerge + + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + target-branch: "v0.37.x" + open-pull-requests-limit: 10 + labels: + - dependencies + - automerge + + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + target-branch: "v0.34.x" + open-pull-requests-limit: 10 + labels: + - dependencies + - automerge + + ################################### + ## + ## Update All Go Dependencies + + - package-ecosystem: gomod + directory: "/" + schedule: + interval: weekly + target-branch: "main" + open-pull-requests-limit: 10 + labels: + - dependencies + - automerge + + - package-ecosystem: gomod + directory: "/" + schedule: + interval: daily + target-branch: "v0.37.x" + # Only allow automated security-related dependency updates on release + # branches. + open-pull-requests-limit: 0 + labels: + - dependencies + - automerge + + - package-ecosystem: gomod + directory: "/" + schedule: + interval: daily + target-branch: "v0.34.x" + # Only allow automated security-related dependency updates on release + # branches. + open-pull-requests-limit: 0 + labels: + - dependencies + - automerge diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 0000000..2bef2b3 --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1,10 @@ +--- +labels: needs-triage +--- + + diff --git a/.github/linters/markdownlint.yml b/.github/linters/markdownlint.yml new file mode 100644 index 0000000..07e3e92 --- /dev/null +++ b/.github/linters/markdownlint.yml @@ -0,0 +1,15 @@ +# markdownlint configuration for Super-Linter +# - https://github.com/DavidAnson/markdownlint +# - https://github.com/github/super-linter + +# Default state for all rules +default: true + +# See https://github.com/DavidAnson/markdownlint#rules--aliases for rules +MD007: {"indent": 4} +MD013: false +MD024: {siblings_only: true} +MD025: false +MD033: {no-inline-html: false} +no-hard-tabs: false +whitespace: false diff --git a/.github/linters/yaml-lint.yml b/.github/linters/yaml-lint.yml new file mode 100644 index 0000000..3a72ffd --- /dev/null +++ b/.github/linters/yaml-lint.yml @@ -0,0 +1,9 @@ +--- +# Default rules for YAML linting from super-linter. +# See: See https://yamllint.readthedocs.io/en/stable/rules.html +extends: default +rules: + document-end: disable + document-start: disable + line-length: disable + truthy: disable diff --git a/.github/mergify.yml b/.github/mergify.yml new file mode 100644 index 0000000..dde0182 --- /dev/null +++ b/.github/mergify.yml @@ -0,0 +1,35 @@ +queue_rules: + - name: default + conditions: + - base=main + - label=automerge + +pull_request_rules: + - name: Automerge to main + conditions: + - base=main + - label=automerge + actions: + queue: + method: squash + name: default + commit_message_template: | + {{ title }} (#{{ number }}) + + {{ body }} + - name: backport patches to v0.37.x branch + conditions: + - base=main + - label=backport-to-v0.37.x + actions: + backport: + branches: + - v0.37.x + - name: backport patches to v0.34.x branch + conditions: + - base=main + - label=backport-to-v0.34.x + actions: + backport: + branches: + - v0.34.x diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..cfcc25f --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,82 @@ +name: Build +# Tests runs different tests (test_abci_apps, test_abci_cli, test_apps) +# This workflow runs on every push to v0.38.x and every pull request +# All jobs will pass without running if no *{.go, .mod, .sum} files have been modified +on: + pull_request: + push: + branches: + - v0.38.x + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + goarch: ["arm", "amd64"] + goos: ["linux"] + timeout-minutes: 5 + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/*.go + "!test/" + go.mod + go.sum + Makefile + + - name: install + run: GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} make build + if: "env.GIT_DIFF != ''" + + test_abci_cli: + runs-on: ubuntu-latest + needs: build + timeout-minutes: 5 + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/*.go + go.mod + go.sum + - name: install + run: make install_abci + if: "env.GIT_DIFF != ''" + - run: abci/tests/test_cli/test.sh + shell: bash + if: "env.GIT_DIFF != ''" + + test_apps: + runs-on: ubuntu-latest + needs: build + timeout-minutes: 5 + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/*.go + go.mod + go.sum + - name: install + run: make install install_abci + if: "env.GIT_DIFF != ''" + - name: test_apps + run: test/app/test.sh + shell: bash + if: "env.GIT_DIFF != ''" diff --git a/.github/workflows/check-generated.yml b/.github/workflows/check-generated.yml new file mode 100644 index 0000000..c0f8cd5 --- /dev/null +++ b/.github/workflows/check-generated.yml @@ -0,0 +1,68 @@ +# Verify that generated code is up-to-date. +# +# Note that we run these checks regardless whether the input files have +# changed, because generated code can change in response to toolchain updates +# even if no files in the repository are modified. +name: Check generated code +on: + pull_request: + branches: + - v0.38.x + +permissions: + contents: read + +jobs: + check-mocks-metrics: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + + - uses: actions/checkout@v4 + + - name: "Check generated mocks and metrics" + run: | + set -euo pipefail + + make mockery metrics + + git add . + if ! git diff HEAD --stat --exit-code ; then + echo ">> ERROR:" + echo ">>" + echo ">> Generated mocks and/or metrics require update (either Mockery or source files may have changed)." + echo ">> Ensure your tools are up-to-date, re-run 'make mockery metrics' and update this PR." + echo ">>" + git diff + exit 1 + fi + + check-proto: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + + - uses: actions/checkout@v4 + with: + fetch-depth: 1 # we need a .git directory to run git diff + + - name: "Check protobuf generated code" + run: | + set -euo pipefail + + make proto-gen + + git add . + if ! git diff HEAD --stat --exit-code ; then + echo ">> ERROR:" + echo ">>" + echo ">> Protobuf generated code requires update (either tools or .proto files may have changed)." + echo ">> Ensure your tools are up-to-date, re-run 'make proto-gen' and update this PR." + echo ">>" + git diff + exit 1 + fi diff --git a/.github/workflows/docker-build-cometbft.yml b/.github/workflows/docker-build-cometbft.yml new file mode 100644 index 0000000..f7dd6ed --- /dev/null +++ b/.github/workflows/docker-build-cometbft.yml @@ -0,0 +1,98 @@ +name: docker-build-cometbft + +on: + workflow_dispatch: + push: + branches: + - main + - v0.38.x + - v1.x + - v2.x + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-alpha.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-beta.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + DOCKER_ORG: cometbft + DOCKER_IMAGE: cometbft + +jobs: + vars: + runs-on: ubuntu-latest + outputs: + repo: ${{ steps.set.outputs.repo }} + tags: ${{ steps.set.outputs.tags }} + steps: + - id: set + run: | + REPO="${DOCKER_ORG}/${DOCKER_IMAGE}" + VERSION="${GITHUB_REF_NAME}" + + TAGS="${REPO}:${VERSION}" + if [ "$VERSION" = "main" ]; then + TAGS="${TAGS:+$TAGS,}$REPO:latest" + fi + + echo "repo=${REPO}" >> $GITHUB_OUTPUT + echo "tags=${TAGS}" >> $GITHUB_OUTPUT + + build-images: + needs: vars + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + arch: amd64 + - os: ubuntu-24.04-arm + arch: arm64 + runs-on: ${{ matrix.os }} + outputs: + digest-amd64: ${{ steps.digest.outputs.digest-amd64 }} + digest-arm64: ${{ steps.digest.outputs.digest-arm64 }} + steps: + - id: tags + run: | + TAGS=$(echo "${{ needs.vars.outputs.tags }}" | sed "s/[^,]*/&-${{ matrix.arch }}/g") + echo "tags=${TAGS}" >> $GITHUB_OUTPUT + + - uses: actions/checkout@v4 + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - uses: docker/setup-buildx-action@v3 + - uses: docker/build-push-action@v6 + id: build + with: + platforms: linux/${{ matrix.arch }} + context: . + file: ./DOCKER/Dockerfile + push: true + tags: ${{ steps.tags.outputs.tags }} + + - id: digest + run: echo "digest-${{ matrix.arch }}=${{ steps.build.outputs.digest }}" >> $GITHUB_OUTPUT + + merge-images: + runs-on: ubuntu-latest + needs: + - vars + - build-images + steps: + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - run: | + TAGS="${{ needs.vars.outputs.tags }}" + docker buildx imagetools create \ + $(printf -- '--tag %s ' ${TAGS//,/ }) \ + ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-amd64 }} \ + ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-arm64 }} diff --git a/.github/workflows/docker-build-e2e-node.yml b/.github/workflows/docker-build-e2e-node.yml new file mode 100644 index 0000000..5f249da --- /dev/null +++ b/.github/workflows/docker-build-e2e-node.yml @@ -0,0 +1,98 @@ +name: docker-build-e2e-node + +on: + workflow_dispatch: + push: + branches: + - main + - v0.38.x + - v1.x + - v2.x + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-alpha.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-beta.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + DOCKER_ORG: cometbft + DOCKER_IMAGE: e2e-node + +jobs: + vars: + runs-on: ubuntu-latest + outputs: + repo: ${{ steps.set.outputs.repo }} + tags: ${{ steps.set.outputs.tags }} + steps: + - id: set + run: | + REPO="${DOCKER_ORG}/${DOCKER_IMAGE}" + VERSION="${GITHUB_REF_NAME}" + + TAGS="${REPO}:${VERSION}" + if [ "$VERSION" = "main" ]; then + TAGS="${TAGS:+$TAGS,}$REPO:latest" + fi + + echo "repo=${REPO}" >> $GITHUB_OUTPUT + echo "tags=${TAGS}" >> $GITHUB_OUTPUT + + build-images: + needs: vars + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + arch: amd64 + - os: ubuntu-24.04-arm + arch: arm64 + runs-on: ${{ matrix.os }} + outputs: + digest-amd64: ${{ steps.digest.outputs.digest-amd64 }} + digest-arm64: ${{ steps.digest.outputs.digest-arm64 }} + steps: + - id: tags + run: | + TAGS=$(echo "${{ needs.vars.outputs.tags }}" | sed "s/[^,]*/&-${{ matrix.arch }}/g") + echo "tags=${TAGS}" >> $GITHUB_OUTPUT + + - uses: actions/checkout@v4 + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - uses: docker/setup-buildx-action@v3 + - uses: docker/build-push-action@v6 + id: build + with: + platforms: linux/${{ matrix.arch }} + context: . + file: ./test/e2e/docker/Dockerfile + push: true + tags: ${{ steps.tags.outputs.tags }} + + - id: digest + run: echo "digest-${{ matrix.arch }}=${{ steps.build.outputs.digest }}" >> $GITHUB_OUTPUT + + merge-images: + runs-on: ubuntu-latest + needs: + - vars + - build-images + steps: + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - run: | + TAGS="${{ needs.vars.outputs.tags }}" + docker buildx imagetools create \ + $(printf -- '--tag %s ' ${TAGS//,/ }) \ + ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-amd64 }} \ + ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-arm64 }} diff --git a/.github/workflows/docs-toc.yml b/.github/workflows/docs-toc.yml new file mode 100644 index 0000000..38b7e23 --- /dev/null +++ b/.github/workflows/docs-toc.yml @@ -0,0 +1,20 @@ +# Verify that important design docs have ToC entries. +name: Check documentation ToC +on: + pull_request: + push: + branches: + - v0.38.x + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + docs/architecture/** + docs/rfc/** + - run: make check-docs-toc + if: env.GIT_DIFF diff --git a/.github/workflows/e2e-manual-multiversion.yml b/.github/workflows/e2e-manual-multiversion.yml new file mode 100644 index 0000000..85278a9 --- /dev/null +++ b/.github/workflows/e2e-manual-multiversion.yml @@ -0,0 +1,45 @@ +# Manually run the nightly E2E tests for a particular branch, but test with +# multiple versions. +name: e2e-manual-multiversion +on: + workflow_dispatch: + +jobs: + e2e-manual-multiversion-test: + # Run parallel jobs for the listed testnet groups (must match the + # ./build/generator -g flag) + strategy: + fail-fast: false + matrix: + group: ['00', '01', '02', '03', '04', '05'] + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + - uses: actions/checkout@v4 + + - name: Build + working-directory: test/e2e + # Run make jobs in parallel, since we can't run steps in parallel. + run: make -j2 docker generator runner tests + + - name: Generate testnets + if: matrix.group != 5 + working-directory: test/e2e + # When changing -g, also change the matrix groups above + # Generate multi-version tests with double the quantity of E2E nodes + # based on the current branch as compared to the latest version. + run: ./build/generator -g 5 -m "latest:1,local:2" -d networks/nightly/ -p + + - name: Run p2p testnets (${{ matrix.group }}) + if: matrix.group != 5 + working-directory: test/e2e + run: ./run-multiple.sh networks/nightly/*-group${{ matrix.group }}-*.toml + + - name: Run p2p testnets (regression) + if: matrix.group == 5 + working-directory: test/e2e + run: ./run-multiple.sh networks_regressions/*.toml diff --git a/.github/workflows/e2e-manual.yml b/.github/workflows/e2e-manual.yml new file mode 100644 index 0000000..735e3cf --- /dev/null +++ b/.github/workflows/e2e-manual.yml @@ -0,0 +1,43 @@ +# Runs randomly generated E2E testnets nightly on main +# manually run e2e tests +name: e2e-manual +on: + workflow_dispatch: + +jobs: + e2e-nightly-test: + # Run parallel jobs for the listed testnet groups (must match the + # ./build/generator -g flag) + strategy: + fail-fast: false + matrix: + group: ['00', '01', '02', '03', '04', '05'] + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + - uses: actions/checkout@v4 + + - name: Build + working-directory: test/e2e + # Run make jobs in parallel, since we can't run steps in parallel. + run: make -j2 docker generator runner tests + + - name: Generate testnets + if: matrix.group != 5 + working-directory: test/e2e + # When changing -g, also change the matrix groups above + run: ./build/generator -g 5 -d networks/nightly/ -p + + - name: Run p2p testnets (${{ matrix.group }}) + if: matrix.group != 5 + working-directory: test/e2e + run: ./run-multiple.sh networks/nightly/*-group${{ matrix.group }}-*.toml + + - name: Run p2p testnets (regression) + if: matrix.group == 5 + working-directory: test/e2e + run: ./run-multiple.sh networks_regressions/*.toml diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000..d291a2a --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,36 @@ +name: e2e +# Runs the CI end-to-end test network on all pushes to v0.38.x +# and every pull request, but only if any Go files have been changed. +on: + workflow_dispatch: # allow running workflow manually + pull_request: + push: + branches: + - v0.38.x + +jobs: + e2e-test: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/**.go + go.mod + go.sum + + - name: Build + working-directory: test/e2e + # Run two make jobs in parallel, since we can't run steps in parallel. + run: make -j2 docker runner tests + if: "env.GIT_DIFF != ''" + + - name: Run CI testnet + working-directory: test/e2e + run: ./run-multiple.sh networks/ci.toml + if: "env.GIT_DIFF != ''" diff --git a/.github/workflows/fuzz-nightly.yml b/.github/workflows/fuzz-nightly.yml new file mode 100644 index 0000000..0969b6d --- /dev/null +++ b/.github/workflows/fuzz-nightly.yml @@ -0,0 +1,93 @@ +# Runs fuzzing nightly. +name: Fuzz Tests +on: + workflow_dispatch: # allow running workflow manually + schedule: + - cron: '0 3 * * *' + pull_request: + branches: + - v0.38.x + paths: + - "test/fuzz/**/*.go" + +jobs: + fuzz-nightly-test: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + - uses: actions/checkout@v4 + + - name: Install go-fuzz + working-directory: test/fuzz + run: go install github.com/dvyukov/go-fuzz/go-fuzz@latest github.com/dvyukov/go-fuzz/go-fuzz-build@latest + + - name: Fuzz mempool + working-directory: test/fuzz + run: timeout -s SIGINT --preserve-status 10m make fuzz-mempool + continue-on-error: true + + - name: Fuzz p2p-addrbook + working-directory: test/fuzz + run: timeout -s SIGINT --preserve-status 10m make fuzz-p2p-addrbook + continue-on-error: true + + - name: Fuzz p2p-pex + working-directory: test/fuzz + run: timeout -s SIGINT --preserve-status 10m make fuzz-p2p-pex + continue-on-error: true + + - name: Fuzz p2p-sc + working-directory: test/fuzz + run: timeout -s SIGINT --preserve-status 10m make fuzz-p2p-sc + continue-on-error: true + + - name: Fuzz p2p-rpc-server + working-directory: test/fuzz + run: timeout -s SIGINT --preserve-status 10m make fuzz-rpc-server + continue-on-error: true + + - name: Archive crashers + uses: actions/upload-artifact@v4 + with: + name: crashers + path: test/fuzz/**/crashers + retention-days: 3 + + - name: Archive suppressions + uses: actions/upload-artifact@v4 + with: + name: suppressions + path: test/fuzz/**/suppressions + retention-days: 3 + + - name: Set crashers count + working-directory: test/fuzz + run: echo "count=$(find . -type d -name 'crashers' | xargs -I % sh -c 'ls % | wc -l' | awk '{total += $1} END {print total}')" >> $GITHUB_OUTPUT + id: set-crashers-count + + outputs: + crashers-count: ${{ steps.set-crashers-count.outputs.count }} + + fuzz-nightly-fail: + needs: fuzz-nightly-test + if: ${{ needs.fuzz-nightly-test.outputs.crashers-count != 0 }} + runs-on: ubuntu-latest + steps: + - name: Notify Slack on failure + uses: slackapi/slack-github-action@v2.0.0 + env: + BRANCH: ${{ github.ref_name }} + CRASHERS: ${{ needs.fuzz-nightly-test.outputs.crashers-count }} + RUN_URL: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" + with: + webhook: ${{ secrets.SLACK_WEBHOOK_URL }} + webhook-type: incoming-webhook + payload: | + blocks: + - type: "section" + text: + type: "mrkdwn" + text: ":skull: Nightly fuzz tests for `${{ env.BRANCH }}` failed with ${{ env.CRASHERS }} crasher(s). See the <${{ env.RUN_URL }}|run details>." diff --git a/.github/workflows/janitor.yml b/.github/workflows/janitor.yml new file mode 100644 index 0000000..64ec97c --- /dev/null +++ b/.github/workflows/janitor.yml @@ -0,0 +1,16 @@ +name: Janitor +# Janitor cleans up previous runs of various workflows +# To add more workflows to cancel visit https://api.github.com/repos/cometbft/cometbft/actions/workflows and find the actions name +on: + pull_request: + +jobs: + cancel: + name: "Cancel Previous Runs" + runs-on: ubuntu-latest + timeout-minutes: 3 + steps: + - uses: styfle/cancel-workflow-action@0.12.1 + with: + workflow_id: 1041851,1401230,2837803 + access_token: ${{ github.token }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..da09621 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,35 @@ +name: Golang Linter +# Lint runs golangci-lint over the entire CometBFT repository. +# +# This workflow is run on every pull request and push to v0.38.x. +# +# The `golangci` job will pass without running if no *.{go, mod, sum} +# files have been modified. +# +# To run this locally, simply run `make lint` from the root of the repo. + +on: + pull_request: + push: + branches: + - v0.38.x +jobs: + golangci: + name: golangci-lint + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.23' + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/**.go + go.mod + go.sum + - name: Run linting + if: env.GIT_DIFF + run: | + make lint diff --git a/.github/workflows/markdown-linter.yml b/.github/workflows/markdown-linter.yml new file mode 100644 index 0000000..11f1f39 --- /dev/null +++ b/.github/workflows/markdown-linter.yml @@ -0,0 +1,33 @@ +name: Markdown Linter +on: + push: + branches: + - v0.38.x + paths: + - "**.md" + - "**.yml" + - "**.yaml" + pull_request: + branches: + - v0.38.x + paths: + - "**.md" + - "**.yml" + +jobs: + build: + name: Super linter + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v4 + - name: Lint Code Base + uses: docker://github/super-linter:v4 + env: + VALIDATE_ALL_CODEBASE: true + DEFAULT_BRANCH: v0.38.x + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VALIDATE_MD: true + VALIDATE_OPENAPI: true + VALIDATE_YAML: true + YAML_CONFIG_FILE: yaml-lint.yml diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml new file mode 100644 index 0000000..46ac119 --- /dev/null +++ b/.github/workflows/pre-release.yml @@ -0,0 +1,71 @@ +name: "Pre-release" + +on: + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+-alpha.[0-9]+" # e.g. v0.37.0-alpha.1, v0.38.0-alpha.10 + - "v[0-9]+.[0-9]+.[0-9]+-beta.[0-9]+" # e.g. v0.37.0-beta.1, v0.38.0-beta.10 + - "v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+" # e.g. v0.37.0-rc1, v0.38.0-rc10 + +jobs: + prerelease: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + # Similar check to ./release-version.yml, but enforces this when pushing + # tags. The ./release-version.yml check can be bypassed and is mainly + # present for informational purposes. + - name: Check release version + run: | + # We strip the refs/tags/v prefix of the tag name. + TAG_VERSION=${GITHUB_REF#refs/tags/v} + # Get the version of the code, which has no "v" prefix. + CODE_VERSION=`go run ./cmd/cometbft/ version` + if [ "$TAG_VERSION" != "$CODE_VERSION" ]; then + echo "" + echo "Tag version ${TAG_VERSION} does not match code version ${CODE_VERSION}" + echo "" + echo "Please either fix the release tag or the version of the software in version/version.go." + exit 1 + fi + + - name: Generate release notes + run: | + VERSION="${GITHUB_REF#refs/tags/}" + CHANGELOG_URL="https://github.com/cometbft/cometbft/blob/${VERSION}/CHANGELOG.md" + echo "See the [CHANGELOG](${CHANGELOG_URL}) for changes available in this pre-release, but not yet officially released." > ../release_notes.md + + - name: Release + uses: goreleaser/goreleaser-action@v6 + with: + version: latest + args: release --clean --release-notes ../release_notes.md + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + prerelease-success: + needs: prerelease + if: ${{ success() }} + runs-on: ubuntu-latest + steps: + - name: Notify Slack upon pre-release + uses: slackapi/slack-github-action@v2.0.0 + env: + RELEASE_URL: "${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ github.ref_name }}" + with: + webhook: ${{ secrets.SLACK_WEBHOOK_URL }} + webhook-type: incoming-webhook + payload: | + blocks: + - type: "section" + text: + type: "mrkdwn" + text: ":sparkles: New CometBFT pre-release: <${{ env.RELEASE_URL }}|${{ github.ref_name }}>" diff --git a/.github/workflows/proto-lint.yml b/.github/workflows/proto-lint.yml new file mode 100644 index 0000000..4684267 --- /dev/null +++ b/.github/workflows/proto-lint.yml @@ -0,0 +1,21 @@ +name: Protobuf Lint +on: + pull_request: + paths: + - 'proto/**' + push: + branches: + - v0.38.x + paths: + - 'proto/**' + +jobs: + lint: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - uses: bufbuild/buf-setup-action@v1.50.0 + - uses: bufbuild/buf-lint-action@v1 + with: + input: 'proto' diff --git a/.github/workflows/release-version.yml b/.github/workflows/release-version.yml new file mode 100644 index 0000000..864ba8f --- /dev/null +++ b/.github/workflows/release-version.yml @@ -0,0 +1,33 @@ +# Checks that, if we're working on a release branch and are about to cut a +# release, we have set the version correctly. +name: Check release version + +on: + push: + branches: + - 'release/**' + +jobs: + check-version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + - name: Check version + run: | + # We strip the refs/heads/release/v prefix of the branch name. + BRANCH_VERSION=${GITHUB_REF#refs/heads/release/v} + # Get the version of the code, which has no "v" prefix. + CODE_VERSION=`go run ./cmd/cometbft/ version` + if [ "$BRANCH_VERSION" != "$CODE_VERSION" ]; then + echo "" + echo "Branch version ${BRANCH_VERSION} does not match code version ${CODE_VERSION}" + echo "" + echo "Please either fix the release branch naming (which must have a 'release/v' prefix)" + echo "or the version of the software in version/version.go." + exit 1 + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..b2336bd --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,72 @@ +name: "Release" + +on: + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+" # Push events to matching v*, i.e. v1.0, v20.15.10 + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + + # Similar check to ./release-version.yml, but enforces this when pushing + # tags. The ./release-version.yml check can be bypassed and is mainly + # present for informational purposes. + - name: Check release version + run: | + # We strip the refs/tags/v prefix of the tag name. + TAG_VERSION=${GITHUB_REF#refs/tags/v} + # Get the version of the code, which has no "v" prefix. + CODE_VERSION=`go run ./cmd/cometbft/ version` + if [ "$TAG_VERSION" != "$CODE_VERSION" ]; then + echo "" + echo "Tag version ${TAG_VERSION} does not match code version ${CODE_VERSION}" + echo "" + echo "Please either fix the release tag or the version of the software in version/version.go." + exit 1 + fi + + - name: Generate release notes + run: | + VERSION="${GITHUB_REF#refs/tags/}" + VERSION_REF="${VERSION//[\.]/}" + CHANGELOG_URL="https://github.com/cometbft/cometbft/blob/${VERSION}/CHANGELOG.md#${VERSION_REF}" + echo "See the [CHANGELOG](${CHANGELOG_URL}) for this release." > ../release_notes.md + + - name: Release + uses: goreleaser/goreleaser-action@v6 + with: + version: latest + args: release --clean --release-notes ../release_notes.md + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + release-success: + needs: release + if: ${{ success() }} + runs-on: ubuntu-latest + steps: + - name: Notify Slack upon release + uses: slackapi/slack-github-action@v2.0.0 + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK + RELEASE_URL: "${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ github.ref_name }}" + with: + webhook: ${{ secrets.SLACK_WEBHOOK_URL }} + webhook-type: incoming-webhook + payload: | + blocks: + - type: "section" + text: + type: "mrkdwn" + text: ":rocket: New CometBFT release: <${{ env.RELEASE_URL }}|${{ github.ref_name }}>" diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..f3007d2 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,20 @@ +name: "Close stale pull requests" +on: + schedule: + - cron: "0 0 * * *" + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-pr-message: "This pull request has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions." + days-before-stale: -1 + days-before-close: -1 + days-before-pr-stale: 10 + days-before-pr-close: 4 + exempt-pr-labels: "wip" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..907a239 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: Test +on: + pull_request: + push: + paths: + - "**.go" + branches: + - v0.38.x + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + part: ["00", "01", "02", "03", "04", "05"] + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + - uses: actions/checkout@v4 + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/**.go + "!test/" + go.mod + go.sum + Makefile + - name: Run Go Tests + run: | + make test-group-${{ matrix.part }} NUM_SPLIT=6 + if: env.GIT_DIFF diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6d3148b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +build/ +*.test +*.bench +.DS_Store +*.log diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..172fb89 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,167 @@ +version: "2" +linters: + enable: + - asciicheck + - bodyclose + - depguard + - dogsled + - dupl + - goconst + - misspell + - nakedret + - nolintlint + - prealloc + - staticcheck + - unconvert + settings: + depguard: + rules: + main: + files: + - $all + - '!$test' + allow: + - $gostd + - github.com/cometbft + - github.com/cosmos + - github.com/btcsuite/btcd/btcec/v2 + - github.com/BurntSushi/toml + - github.com/go-git/go-git/v5 + - github.com/go-kit + - github.com/go-logfmt/logfmt + - github.com/gofrs/uuid + - github.com/google + - github.com/gorilla/websocket + - github.com/informalsystems/tm-load-test/pkg/loadtest + - github.com/hashicorp/golang-lru/v2 + - github.com/lib/pq + - github.com/libp2p/go-buffer-pool + - github.com/Masterminds/semver/v3 + - github.com/minio/highwayhash + - github.com/oasisprotocol/curve25519-voi + - github.com/pkg/errors + - github.com/prometheus + - github.com/rcrowley/go-metrics + - github.com/rs/cors + - github.com/snikch/goodman + - github.com/spf13 + - github.com/stretchr/testify/require + - github.com/syndtr/goleveldb + - github.com/decred/dcrd/dcrec/secp256k1/v4 + - google.golang.org/grpc + - google.golang.org/protobuf/proto + - golang.org/x/sync + - golang.org/x/crypto + - golang.org/x/net + - gonum.org/v1/gonum/stat + - google.golang.org/protobuf/types/known/timestampp + test: + files: + - $test + allow: + - $gostd + - github.com/cosmos + - github.com/cometbft + - github.com/adlio/schema + - github.com/btcsuite/btcd + - github.com/fortytw2/leaktest + - github.com/go-kit + - github.com/google/uuid + - github.com/gorilla/websocket + - github.com/lib/pq + - github.com/oasisprotocol/curve25519-voi/primitives/merlin + - github.com/ory/dockertest + - github.com/pkg/errors + - github.com/prometheus/client_golang/prometheus/promhttp + - github.com/spf13 + - github.com/stretchr/testify + - github.com/decred/dcrd/dcrec/secp256k1/v4 + - google.golang.org/grpc + - google.golang.org/protobuf/proto + - google.golang.org/protobuf/types/known/timestampp + - gonum.org/v1/gonum/stat + - golang.org/x/sync + - golang.org/x/crypto + - golang.org/x/net + dogsled: + max-blank-identifiers: 3 + gosec: + excludes: + - G115 + misspell: + locale: US + revive: + enable-all-rules: true + rules: + - name: comment-spacings + disabled: true + - name: max-public-structs + disabled: true + - name: cognitive-complexity + disabled: true + - name: argument-limit + disabled: true + - name: cyclomatic + disabled: true + - name: deep-exit + disabled: true + - name: file-header + disabled: true + - name: function-length + disabled: true + - name: function-result-limit + disabled: true + - name: line-length-limit + disabled: true + - name: flag-parameter + disabled: true + - name: add-constant + disabled: true + - name: empty-lines + disabled: true + - name: import-shadowing + disabled: true + - name: modifies-value-receiver + disabled: true + - name: confusing-naming + disabled: true + - name: defer + disabled: true + - name: unchecked-type-assertion + disabled: true + - name: unhandled-error + arguments: + - fmt.Printf + - fmt.Print + - fmt.Println + disabled: true + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - gosec + path: _test\.go + - linters: + - goconst + path: (.+)_test\.go + paths: + - third_party$ + - builtin$ + - examples$ +issues: + max-same-issues: 50 +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..3efcd5e --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,37 @@ +project_name: cometbft + +env: + # Require use of Go modules. + - GO111MODULE=on + +builds: + - id: "cometbft" + main: ./cmd/cometbft/main.go + ldflags: + - -s -w -X github.com/cometbft/cometbft/version.TMCoreSemVer={{ .Version }} + env: + - CGO_ENABLED=0 + goos: + - darwin + - linux + - windows + goarch: + - amd64 + - arm + - arm64 + +checksum: + name_template: SHA256SUMS-{{.Version}}.txt + algorithm: sha256 + +release: + prerelease: auto + name_template: "v{{.Version}}" + +archives: + - files: + - LICENSE + - README.md + - UPGRADING.md + - SECURITY.md + - CHANGELOG.md diff --git a/.markdownlint.yml b/.markdownlint.yml new file mode 100644 index 0000000..ea698c8 --- /dev/null +++ b/.markdownlint.yml @@ -0,0 +1,17 @@ +# markdownlint configuration +# https://github.com/DavidAnson/markdownlint + +# Default state for all rules +default: true + +# See https://github.com/DavidAnson/markdownlint#rules--aliases for rules +MD001: false +MD007: {indent: 4} +MD013: false +MD024: {siblings_only: true} +MD025: false +MD033: false +MD036: false +MD010: false +MD012: false +MD028: false diff --git a/.markdownlintignore b/.markdownlintignore new file mode 100644 index 0000000..7e561af --- /dev/null +++ b/.markdownlintignore @@ -0,0 +1,6 @@ +docs/node_modules +CHANGELOG.md +docs/architecture/* +crypto/secp256k1/** +scripts/* +.github diff --git a/.md-link-check.json b/.md-link-check.json new file mode 100644 index 0000000..bbd3d09 --- /dev/null +++ b/.md-link-check.json @@ -0,0 +1,17 @@ +{ + "retryOn429": true, + "retryCount": 5, + "fallbackRetryDelay": "30s", + "aliveStatusCodes": [200, 206, 503], + "httpHeaders": [ + { + "urls": [ + "https://docs.github.com/", + "https://help.github.com/" + ], + "headers": { + "Accept-Encoding": "zstd, br, gzip, deflate" + } + } + ] +} diff --git a/.mockery.yml b/.mockery.yml new file mode 100644 index 0000000..b3ff88b --- /dev/null +++ b/.mockery.yml @@ -0,0 +1,4 @@ +issue-845-fix: True +resolve-type-alias: False +case: underscore # deprecated +replace-type: github.com/cometbft/cometbft/p2p/internal/nodekey.ID=github.com/cometbft/cometbft/p2p.ID diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..88aeed2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,932 @@ +# CHANGELOG + +## UNRELEASED + +### DEPENDENCIES + +### BUG FIXES + +### IMPROVEMENTS +- `[statesync]` Add configurable `max-snapshot-chunks` parameter to validate max amount of chunks in a `SnapshotResponse`. + ([\#5548](https://github.com/cometbft/cometbft/pull/5548)) + +### FEATURES + +### BUG-FIXES + +### STATE-BREAKING + +### API-BREAKING + +## v0.38.19 + +*October 14, 2025* + +This release fixes two security issues, including ([ASA-2025-003](https://github.com/cometbft/cometbft/security/advisories/GHSA-hrhf-2vcr-ghch)). +Users are encouraged to upgrade as soon as possible. + +Additionally included is a bug fix to properly prune extended commits (with +vote extensions). + +### BUG-FIXES + +- `[consensus]` Reject oversized proposals + ([\#5324](https://github.com/cometbft/cometbft/pull/5324)) +- `[store]` Prune extended commits properly + ([5275](https://github.com/cometbft/cometbft/issues/5275)) +- `[bits]` Validate BitArray mismatched Bits and Elems length + ([ASA-2025-003](https://github.com/cometbft/cometbft/security/advisories/GHSA-hrhf-2vcr-ghch)) + +## v0.38.18 + +*July 3, 2025* + +Adds precommit metrics and reindex CLI command. + +### IMPROVEMENTS + +- Adds metrics that emit precommit data; precommit quorum delay from proposal, and precommit vote count and stake weight within timeout commit period. + ([\#5251](https://github.com/cometbft/cometbft/issues/5251)) + +## v0.38.17 + +*February 3, 2025* + +This release fixes two security issues (ASA-2025-001, ASA-2025-002). Users are +encouraged to upgrade as soon as possible. + +### BUG FIXES + +- `[blocksync]` Ban peer if it reports height lower than what was previously reported + ([ASA-2025-001](https://github.com/cometbft/cometbft/security/advisories/GHSA-22qq-3xwm-r5x4)) +- `[types]` Check that `Part.Index` equals `Part.Proof.Index` + ([ASA-2025-001](https://github.com/cometbft/cometbft/security/advisories/GHSA-r3r4-g7hq-pq4f)) + +### DEPENDENCIES + +- `[go/runtime]` Bump minimum Go version to 1.22.11 + ([\#4891](https://github.com/cometbft/cometbft/pull/4891)) + +## v0.38.16 + +*December 20 2024* + +This release: +- fixes a bug that caused a node produce errors caused by the sending of next PEX requests too soon. +As a consequence of this incorrect behavior a node would be marked as BAD. +- Adds a proper description of `ExtendedVoteInfo` and `VoteInfo` in the spec. + +### BUG FIXES + +- `[mocks]` Mockery `v2.49.0` broke the mocks. We had to add a `.mockery.yaml` to +properly handle this change. + ([\#4521](https://github.com/cometbft/cometbft/pull/4521)) + +## v0.38.15 + +*November 6, 2024* + +This release supersedes [`v0.38.14`](#v03814), which mistakenly updated the Go version to +`1.23`, introducing an unintended breaking change. It sets the Go version back +to `1.22.7` by reverting [\#4297](https://github.com/cometbft/cometbft/pull/4297). + +The release includes the bug fixes, performance improvements, and importantly, +the fix for the security vulnerability in the vote extensions (VE) validation +logic that were part of `v0.38.14`. For more details, please refer to [ASA-2024-011](https://github.com/cometbft/cometbft/security/advisories/GHSA-p7mv-53f2-4cwj). + +## v0.38.14 + +*November 6, 2024* + +This release fixes a security vulnerability in the vote extensions (VE) +validation logic. For more details, please refer to +[ASA-2024-011](https://github.com/cometbft/cometbft/security/advisories/GHSA-p7mv-53f2-4cwj). + +We recommend upgrading ASAP if you’re using vote extensions (VE). + +### BUG FIXES + +- `[consensus]` Do not panic if the validator index of a `Vote` message is out + of bounds, when vote extensions are enabled + ([\#ABC-0021](https://github.com/cometbft/cometbft/security/advisories/GHSA-p7mv-53f2-4cwj)) + +### DEPENDENCIES + +- Bump cometbft-db version to v0.15.0 + ([\#4297](https://github.com/cometbft/cometbft/pull/4297)) +- `[go/runtime]` Bump Go version to 1.23 + ([\#4297](https://github.com/cometbft/cometbft/pull/4297)) + +### IMPROVEMENTS + +- `[p2p]` fix exponential backoff logic to increase reconnect retries close to 24 hours + ([\#3519](https://github.com/cometbft/cometbft/issues/3519)) + +## v0.38.13 + +*October 24, 2024* + +This patch release addresses the issue where tx_search was not returning all results, which only arises when upgrading +to CometBFT-DB version 0.13 or later. It includes a fix in the state indexer to resolve this problem. We recommend +upgrading to this patch release if you are affected by this issue. + +### BUG FIXES + +- `[metrics]` Call unused `rejected_txs` metric in mempool + ([\#4019](https://github.com/cometbft/cometbft/pull/4019)) +- `[state/indexer]` Fix the tx_search results not returning all results by changing the logic in the indexer to copy the key and values instead of reusing an iterator. This issue only arises when upgrading to cometbft-db v0.13 or later. + ([\#4295](https://github.com/cometbft/cometbft/issues/4295)). Special thanks to @faddat for reporting the issue. + +### DEPENDENCIES + +- `[go/runtime]` Bump Go version to 1.22 + ([\#4073](https://github.com/cometbft/cometbft/pull/4073)) +- Bump cometbft-db version to v0.14.1 + ([\#4321](https://github.com/cometbft/cometbft/pull/4321)) + +### FEATURES + +- `[crypto]` use decred secp256k1 directly ([#4294](https://github.com/cometbft/cometbft/pull/4294)) + +### IMPROVEMENTS + +- `[metrics]` Add `evicted_txs` metric to mempool + ([\#4019](https://github.com/cometbft/cometbft/pull/4019)) +- `[log]` Change "mempool is full" log to debug level + ([\#4123](https://github.com/cometbft/cometbft/pull/4123)) Special thanks to @yihuang. + +## v0.38.12 + +*September 3, 2024* + +This release includes a security fix for the light client and is recommended +for all users. + +### BUG FIXES + +- `[light]` Cross-check proposer priorities in retrieved validator sets + ([\#ASA-2024-009](https://github.com/cometbft/cometbft/security/advisories/GHSA-g5xx-c4hv-9ccc)) +- `[privval]` Ignore duplicate privval listen when already connected ([\#3828](https://github.com/cometbft/cometbft/issues/3828) + +### DEPENDENCIES + +- `[crypto/secp256k1]` Adjust to breaking interface changes in + `btcec/v2` latest release, while avoiding breaking changes to + local CometBFT functions + ([\#3728](https://github.com/cometbft/cometbft/pull/3728)) +- pinned mockery's version to v2.49.2 to prevent potential + changes in mocks after each new release of mockery + ([\#4605](https://github.com/cometbft/cometbft/pull/4605)) + +### IMPROVEMENTS + +- `[types]` Check that proposer is one of the validators in `ValidateBasic` + ([\#ASA-2024-009](https://github.com/cometbft/cometbft/security/advisories/GHSA-g5xx-c4hv-9ccc)) +- `[e2e]` Add `log_level` option to manifest file + ([#3819](https://github.com/cometbft/cometbft/pull/3819)). +- `[e2e]` Add `log_format` option to manifest file + ([#3836](https://github.com/cometbft/cometbft/issues/3836)). + +## v0.38.11 + +*August 12, 2024* + +This release fixes a panic in consensus where CometBFT would previously panic +if there's no extension signature in non-nil Precommit EVEN IF vote extensions +themselves are disabled. + +It also includes a few other bug fixes and performance improvements. + +### BUG FIXES + +- `[types]` Only check IFF vote is a non-nil Precommit if extensionsEnabled + types ([\#3565](https://github.com/cometbft/cometbft/issues/3565)) + +### IMPROVEMENTS + +- `[indexer]` Fixed ineffective select break statements; they now + point to their enclosing for loop label to exit + ([\#3544](https://github.com/cometbft/cometbft/issues/3544)) + +## v0.38.10 + +*July 16, 2024* + +This release fixes a bug in `v0.38.x` that prevented ABCI responses from being +correctly read when upgrading from `v0.37.x` or below. It also includes a few other +bug fixes and performance improvements. + +### BUG FIXES + +- `[p2p]` Node respects configured `max_num_outbound_peers` limit when dialing + peers provided by a seed node + ([\#486](https://github.com/cometbft/cometbft/issues/486)) +- `[rpc]` Fix an issue where a legacy ABCI response, created on `v0.37` or before, is not returned properly in `v0.38` and up + on the `/block_results` RPC endpoint. + ([\#3002](https://github.com/cometbft/cometbft/issues/3002)) +- `[blocksync]` Do not stay in blocksync if the node's validator voting power + is high enough to block the chain while it is not online + ([\#3406](https://github.com/cometbft/cometbft/pull/3406)) + +### IMPROVEMENTS + +- `[p2p/conn]` Update send monitor, used for sending rate limiting, once per batch of packets sent + ([\#3382](https://github.com/cometbft/cometbft/pull/3382)) +- `[libs/pubsub]` Allow dash (`-`) in event tags + ([\#3401](https://github.com/cometbft/cometbft/issues/3401)) +- `[p2p/conn]` Remove the usage of a synchronous pool of buffers in secret connection, storing instead the buffer in the connection struct. This reduces the synchronization primitive usage, speeding up the code. + ([\#3403](https://github.com/cometbft/cometbft/issues/3403)) + +## v0.38.9 + +*July 1, 2024* + +This release reverts the API-breaking change to the Mempool interface introduced in the last patch +release (v0.38.8) while still keeping the performance improvement added to the mempool. It also +includes a minor fix to the RPC endpoints /tx and /tx_search. + +### BREAKING CHANGES + +- `[mempool]` Revert adding the method `PreUpdate()` to the `Mempool` interface, recently introduced + in the previous patch release (v0.38.8). Its logic is now moved into the `Lock` method. With this change, + the `Mempool` interface is the same as in v0.38.7. + ([\#3361](https://github.com/cometbft/cometbft/pull/3361)) + +### BUG FIXES + +- `[rpc]` Fix nil pointer error in `/tx` and `/tx_search` when block is + absent ([\#3352](https://github.com/cometbft/cometbft/issues/3352)) + +## v0.38.8 + +*June 27, 2024* + +This release contains a few bug fixes and performance improvements. + +### BREAKING CHANGES + +- `[mempool]` Add to the `Mempool` interface a new method `PreUpdate()`. This method should be + called before acquiring the mempool lock, to signal that a new update is coming. Also add to + `ErrMempoolIsFull` a new field `RecheckFull`. + ([\#3314](https://github.com/cometbft/cometbft/pull/3314)) + +### BUG FIXES + +- `[blockstore]` Added peer banning in blockstore + ([\#ABC-0013](https://github.com/cometbft/cometbft/security/advisories/GHSA-hg58-rf2h-6rr7)) +- `[blockstore]` Send correct error message when vote extensions do not align with received packet + ([\#ABC-0014](https://github.com/cometbft/cometbft/security/advisories/GHSA-hg58-rf2h-6rr7)) +- [`mempool`] Fix data race when rechecking with async ABCI client + ([\#1827](https://github.com/cometbft/cometbft/issues/1827)) +- `[consensus]` Fix a race condition in the consensus timeout ticker. Race is caused by two timeouts being scheduled at the same time. + ([\#3092](https://github.com/cometbft/cometbft/pull/2136)) +- `[types]` Do not batch verify a commit if the validator set keys have different + types. ([\#3195](https://github.com/cometbft/cometbft/issues/3195) + +### IMPROVEMENTS + +- `[config]` Added `recheck_timeout` mempool parameter to set how much time to wait for recheck + responses from the app (only applies to non-local ABCI clients). + ([\#1827](https://github.com/cometbft/cometbft/issues/1827/)) +- `[rpc]` Add a configurable maximum batch size for RPC requests. + ([\#2867](https://github.com/cometbft/cometbft/pull/2867)). +- `[event-bus]` Remove the debug logs in PublishEventTx, which were noticed production slowdowns. + ([\#2911](https://github.com/cometbft/cometbft/pull/2911)) +- `[state/execution]` Cache the block hash computation inside of the Block Type, so we only compute it once. + ([\#2924](https://github.com/cometbft/cometbft/pull/2924)) +- `[consensus/state]` Remove a redundant `VerifyBlock` call in `FinalizeCommit` + ([\#2928](https://github.com/cometbft/cometbft/pull/2928)) +- `[p2p/channel]` Speedup `ProtoIO` writer creation time, and thereby speedup channel writing by 5%. + ([\#2949](https://github.com/cometbft/cometbft/pull/2949)) +- `[p2p/conn]` Minor speedup (3%) to connection.WritePacketMsgTo, by removing MinInt calls. + ([\#2952](https://github.com/cometbft/cometbft/pull/2952)) +- `[internal/bits]` 10x speedup creating initialized bitArrays, which speedsup extendedCommit.BitArray(). This is used in consensus vote gossip. + ([\#2959](https://github.com/cometbft/cometbft/pull/2841)). +- `[blockstore]` Remove a redundant `Header.ValidateBasic` call in `LoadBlockMeta`, 75% reducing this time. + ([\#2964](https://github.com/cometbft/cometbft/pull/2964)) +- `[p2p/conn]` Speedup connection.WritePacketMsgTo, by reusing internal buffers rather than re-allocating. + ([\#2986](https://github.com/cometbft/cometbft/pull/2986)) +- [`blockstore`] Use LRU caches in blockstore, significiantly improving consensus gossip routine performance + ([\#3003](https://github.com/cometbft/cometbft/issues/3003) +- [`consensus`] Improve performance of consensus metrics by lowering string operations + ([\#3017](https://github.com/cometbft/cometbft/issues/3017) +- [`protoio`] Remove one allocation and new object call from `ReadMsg`, + leading to a 4% p2p message reading performance gain. + ([\#3018](https://github.com/cometbft/cometbft/issues/3018) +- `[mempool]` Before updating the mempool, consider it as full if rechecking is still in progress. + This will stop accepting transactions in the mempool if the node can't keep up with re-CheckTx. + ([\#3314](https://github.com/cometbft/cometbft/pull/3314)) + +## v0.38.7 + +*April 26, 2024* + +This release contains a few bug fixes and performance improvements. + +### BUG FIXES + +- [`mempool`] Panic when a CheckTx request to the app returns an error + ([\#2225](https://github.com/cometbft/cometbft/pull/2225)) +- [`bits`] prevent `BitArray.UnmarshalJSON` from crashing on 0 bits + ([\#2774](https://github.com/cometbft/cometbft/pull/2774)) + +### FEATURES + +- [`node`] Add `BootstrapStateWithGenProvider` to boostrap state using a custom + genesis doc provider ([\#2793](https://github.com/cometbft/cometbft/pull/2793)) + +### IMPROVEMENTS + +- `[state/indexer]` Lower the heap allocation of transaction searches + ([\#2839](https://github.com/cometbft/cometbft/pull/2839)) +- `[internal/bits]` 10x speedup and remove heap overhead of bitArray.PickRandom (used extensively in consensus gossip) + ([\#2841](https://github.com/cometbft/cometbft/pull/2841)). +- `[libs/json]` Lower the memory overhead of JSON encoding by using JSON encoders internally + ([\#2846](https://github.com/cometbft/cometbft/pull/2846)). + +## v0.38.6 + +*March 12, 2024* + +This release fixes a security bug in the light client. It also introduces many +improvements to the block sync in collaboration with the +[Osmosis](https://osmosis.zone/) team. + +### BUG FIXES + +- `[privval]` Retry accepting a connection ([\#2047](https://github.com/cometbft/cometbft/pull/2047)) +- `[state]` Fix rollback to a specific height + ([\#2136](https://github.com/cometbft/cometbft/pull/2136)) + +### FEATURES + +- `[e2e]` Add `block_max_bytes` option to the manifest file. + ([\#2362](https://github.com/cometbft/cometbft/pull/2362)) + +### IMPROVEMENTS + +- `[blocksync]` Avoid double-calling `types.BlockFromProto` for performance + reasons ([\#2016](https://github.com/cometbft/cometbft/pull/2016)) +- `[e2e]` Add manifest option `load_max_txs` to limit the number of transactions generated by the + `load` command. ([\#2094](https://github.com/cometbft/cometbft/pull/2094)) +- `[jsonrpc]` enable HTTP basic auth in websocket client ([#2434](https://github.com/cometbft/cometbft/pull/2434)) +- `[blocksync]` make the max number of downloaded blocks dynamic. + Previously it was a const 600. Now it's `peersCount * maxPendingRequestsPerPeer (20)` + [\#2467](https://github.com/cometbft/cometbft/pull/2467) +- `[blocksync]` Request a block from peer B if we are approaching pool's height + (less than 50 blocks) and the current peer A is slow in sending us the + block [\#2475](https://github.com/cometbft/cometbft/pull/2475) +- `[blocksync]` Request the block N from peer B immediately after getting + `NoBlockResponse` from peer A + [\#2475](https://github.com/cometbft/cometbft/pull/2475) +- `[blocksync]` Sort peers by download rate (the fastest peer is picked first) + [\#2475](https://github.com/cometbft/cometbft/pull/2475) + +## v0.38.5 + +*January 24, 2024* + +This release fixes a problem introduced in `v0.38.3`: if an application +updates the value of ConsensusParam `VoteExtensionsEnableHeight` to the same value +(actually a "noop" update) this is accepted in `v0.38.2` but rejected under some +conditions in `v0.38.3` and `v0.38.4`. Even if rejecting a useless update would make sense +in general, in a point release we should not reject a set of inputs to +a function that was previuosly accepted (unless there is a good reason +for it). The goal of this release is to accept again all "noop" updates, like `v0.38.2` did. + +### IMPROVEMENTS + +- `[consensus]` Add `chain_size_bytes` metric for measuring the size of the blockchain in bytes + ([\#2093](https://github.com/cometbft/cometbft/pull/2093)) + +## v0.38.4 + +*January 22, 2024* + +This release is aimed at those projects that have a dependency on CometBFT, +release line `v0.38.x`, and make use of function `SaveBlockStoreState` in package +`github.com/cometbft/cometbft/store`. This function changed its signature in `v0.38.3`. +This new release reverts the signature change so that upgrading to the latest release +of CometBFT on `v0.38.x` does not require any change in the code depending on CometBFT. + +### IMPROVEMENTS + +- `[e2e]` Add manifest option `VoteExtensionsUpdateHeight` to test + vote extension activation via `InitChain` and `FinalizeBlock`. + Also, extend the manifest generator to produce different values + of this new option + ([\#2065](https://github.com/cometbft/cometbft/pull/2065)) + +## v0.38.3 + +*January 17, 2024* + +This release addresses a high impact security issue reported in advisory +([ASA-2024-001](https://github.com/cometbft/cometbft/security/advisories/GHSA-qr8r-m495-7hc4)). +There are other non-security bugs fixes that have been addressed since +`v0.38.2` was released, as well as some improvements. +Please check the list below for further details. + +### BUG FIXES + +- `[consensus]` Fix for "Validation of `VoteExtensionsEnableHeight` can cause chain halt" + ([ASA-2024-001](https://github.com/cometbft/cometbft/security/advisories/GHSA-qr8r-m495-7hc4)) +- `[mempool]` Fix data races in `CListMempool` by making atomic the types of `height`, `txsBytes`, and + `notifiedTxsAvailable`. ([\#642](https://github.com/cometbft/cometbft/pull/642)) +- `[mempool]` The calculation method of tx size returned by calling proxyapp should be consistent with that of mempool + ([\#1687](https://github.com/cometbft/cometbft/pull/1687)) +- `[evidence]` When `VerifyCommitLight` & `VerifyCommitLightTrusting` are called as part + of evidence verification, all signatures present in the evidence must be verified + ([\#1749](https://github.com/cometbft/cometbft/pull/1749)) +- `[crypto]` `SupportsBatchVerifier` returns false + if public key is nil instead of dereferencing nil. + ([\#1825](https://github.com/cometbft/cometbft/pull/1825)) +- `[blocksync]` wait for `poolRoutine` to stop in `(*Reactor).OnStop` + ([\#1879](https://github.com/cometbft/cometbft/pull/1879)) + +### IMPROVEMENTS + +- `[types]` Validate `Validator#Address` in `ValidateBasic` ([\#1715](https://github.com/cometbft/cometbft/pull/1715)) +- `[abci]` Increase ABCI socket message size limit to 2GB ([\#1730](https://github.com/cometbft/cometbft/pull/1730): @troykessler) +- `[state]` Save the state using a single DB batch ([\#1735](https://github.com/cometbft/cometbft/pull/1735)) +- `[store]` Save block using a single DB batch if block is less than 640kB, otherwise each block part is saved individually + ([\#1755](https://github.com/cometbft/cometbft/pull/1755)) +- `[rpc]` Support setting proxy from env to `DefaultHttpClient`. + ([\#1900](https://github.com/cometbft/cometbft/pull/1900)) +- `[rpc]` Use default port for HTTP(S) URLs when there is no explicit port ([\#1903](https://github.com/cometbft/cometbft/pull/1903)) +- `[crypto/merkle]` faster calculation of hashes ([#1921](https://github.com/cometbft/cometbft/pull/1921)) + +## v0.38.2 + +*November 27, 2023* + +This release provides the **nop** mempool for applications that want to build their own mempool. +Using this mempool effectively disables all mempool functionality in CometBFT, including transaction dissemination and the `broadcast_tx_*` endpoints. + +Also fixes a small bug in the mempool for an experimental feature. + +### BUG FIXES + +- `[mempool]` Avoid infinite wait in transaction sending routine when + using experimental parameters to limiting transaction gossiping to peers + ([\#1654](https://github.com/cometbft/cometbft/pull/1654)) + +### FEATURES + +- `[mempool]` Add `nop` mempool ([\#1643](https://github.com/cometbft/cometbft/pull/1643)) + + If you want to use it, change mempool's `type` to `nop`: + + ```toml + [mempool] + + # The type of mempool for this node to use. + # + # Possible types: + # - "flood" : concurrent linked list mempool with flooding gossip protocol + # (default) + # - "nop" : nop-mempool (short for no operation; the ABCI app is responsible + # for storing, disseminating and proposing txs). "create_empty_blocks=false" + # is not supported. + type = "nop" + ``` + +## v0.38.1 + +*November 17, 2023* + +This release contains, among other things, an opt-in, experimental feature to +help reduce the bandwidth consumption associated with the mempool's transaction +gossip. + +### BUG FIXES + +- `[state/indexer]` Respect both height params while querying for events + ([\#1529](https://github.com/cometbft/cometbft/pull/1529)) + +### FEATURES + +- `[metrics]` Add metric for mempool size in bytes `SizeBytes`. + ([\#1512](https://github.com/cometbft/cometbft/pull/1512)) + +### IMPROVEMENTS + +- `[mempool]` Add experimental feature to limit the number of persistent peers and non-persistent + peers to which the node gossip transactions. + ([\#1558](https://github.com/cometbft/cometbft/pull/1558)) + ([\#1584](https://github.com/cometbft/cometbft/pull/1584)) +- `[config]` Add mempool parameters `experimental_max_gossip_connections_to_persistent_peers` and + `experimental_max_gossip_connections_to_non_persistent_peers` for limiting the number of peers to + which the node gossip transactions. + ([\#1558](https://github.com/cometbft/cometbft/pull/1558)) + ([\#1584](https://github.com/cometbft/cometbft/pull/1584)) + +## v0.38.0 + +*September 12, 2023* + +This release includes the second part of ABCI++, called ABCI 2.0. +ABCI 2.0 introduces ABCI methods `ExtendVote` and `VerifyVoteExtension`. +These new methods allow the application to add data (opaque to CometBFT), +called _vote extensions_ to precommit votes sent by validators. +These vote extensions are made available to the proposer(s) of the next height. +Additionally, ABCI 2.0 coalesces `BeginBlock`, `DeliverTx`, and `EndBlock` +into one method, `FinalizeBlock`, whose `Request*` and `Response*` +data structures contain the sum of all data previously contained +in the respective `Request*` and `Response*` data structures in +`BeginBlock`, `DeliverTx`, and `EndBlock`. +See the [specification](./spec/abci/) for more details on ABCI 2.0. + +### BREAKING CHANGES + +- `[mempool]` Remove priority mempool. + ([\#260](https://github.com/cometbft/cometbft/issues/260)) +- `[config]` Remove `Version` field from `MempoolConfig`. + ([\#260](https://github.com/cometbft/cometbft/issues/260)) +- `[protobuf]` Remove fields `sender`, `priority`, and `mempool_error` from + `ResponseCheckTx`. ([\#260](https://github.com/cometbft/cometbft/issues/260)) +- `[crypto/merkle]` Do not allow verification of Merkle Proofs against empty trees (`nil` root). `Proof.ComputeRootHash` now panics when it encounters an error, but `Proof.Verify` does not panic + ([\#558](https://github.com/cometbft/cometbft/issues/558)) +- `[state/kvindexer]` Remove the function type from the event key stored in the database. This should be breaking only +for people who forked CometBFT and interact directly with the indexers kvstore. + ([\#774](https://github.com/cometbft/cometbft/pull/774)) +- `[rpc]` Removed `begin_block_events` and `end_block_events` from `BlockResultsResponse`. + The events are merged into one field called `finalize_block_events`. + ([\#9427](https://github.com/tendermint/tendermint/issues/9427)) +- `[pubsub]` Added support for big integers and big floats in the pubsub event query system. + Breaking changes: function `Number` in package `libs/pubsub/query/syntax` changed its return value. + ([\#797](https://github.com/cometbft/cometbft/pull/797)) +- `[kvindexer]` Added support for big integers and big floats in the kvindexer. + Breaking changes: function `Number` in package `libs/pubsub/query/syntax` changed its return value. + ([\#797](https://github.com/cometbft/cometbft/pull/797)) +- `[mempool]` Application can now set `ConsensusParams.Block.MaxBytes` to -1 + to have visibility on all transactions in the + mempool at `PrepareProposal` time. + This means that the total size of transactions sent via `RequestPrepareProposal` + might exceed `RequestPrepareProposal.max_tx_bytes`. + If that is the case, the application MUST make sure that the total size of transactions + returned in `ResponsePrepareProposal.txs` does not exceed `RequestPrepareProposal.max_tx_bytes`, + otherwise CometBFT will panic. + ([\#980](https://github.com/cometbft/cometbft/issues/980)) +- `[node/state]` Add Go API to bootstrap block store and state store to a height. Make sure block sync starts syncing from bootstrapped height. + ([\#1057](https://github.com/tendermint/tendermint/pull/#1057)) (@yihuang) +- `[state/store]` Added Go functions to save height at which offline state sync is performed. + ([\#1057](https://github.com/tendermint/tendermint/pull/#1057)) (@jmalicevic) +- `[p2p]` Remove UPnP functionality + ([\#1113](https://github.com/cometbft/cometbft/issues/1113)) +- `[node]` Removed `ConsensusState()` accessor from `Node` + struct - all access to consensus state should go via the reactor + ([\#1120](https://github.com/cometbft/cometbft/pull/1120)) +- `[state]` Signature of `ExtendVote` changed in `BlockExecutor`. + It now includes the block whose precommit will be extended, an the state object. + ([\#1270](https://github.com/cometbft/cometbft/pull/1270)) +- `[state]` Move pruneBlocks from node/state to state/execution. + ([\#6541](https://github.com/tendermint/tendermint/pull/6541)) +- `[abci]` Move `app_hash` parameter from `Commit` to `FinalizeBlock` + ([\#8664](https://github.com/tendermint/tendermint/pull/8664)) +- `[abci]` Introduce `FinalizeBlock` which condenses `BeginBlock`, `DeliverTx` + and `EndBlock` into a single method call + ([\#9468](https://github.com/tendermint/tendermint/pull/9468)) +- `[p2p]` Remove unused p2p/trust package + ([\#9625](https://github.com/tendermint/tendermint/pull/9625)) +- `[rpc]` Remove global environment and replace with constructor + ([\#9655](https://github.com/tendermint/tendermint/pull/9655)) +- `[node]` Move DBContext and DBProvider from the node package to the config + package. ([\#9655](https://github.com/tendermint/tendermint/pull/9655)) +- `[inspect]` Add a new `inspect` command for introspecting + the state and block store of a crashed tendermint node. + ([\#9655](https://github.com/tendermint/tendermint/pull/9655)) +- `[metrics]` Move state-syncing and block-syncing metrics to + their respective packages. Move labels from block_syncing + -> blocksync_syncing and state_syncing -> statesync_syncing + ([\#9682](https://github.com/tendermint/tendermint/pull/9682)) + +### BUG FIXES + +- `[kvindexer]` Forward porting the fixes done to the kvindexer in 0.37 in PR \#77 + ([\#423](https://github.com/cometbft/cometbft/pull/423)) +- `[consensus]` Unexpected error conditions in `ApplyBlock` are non-recoverable, so ignoring the error and carrying on is a bug. We replaced a `return` that disregarded the error by a `panic`. + ([\#496](https://github.com/cometbft/cometbft/pull/496)) +- `[consensus]` Rename `(*PeerState).ToJSON` to `MarshalJSON` to fix a logging data race + ([\#524](https://github.com/cometbft/cometbft/pull/524)) +- `[light]` Fixed an edge case where a light client would panic when attempting + to query a node that (1) has started from a non-zero height and (2) does + not yet have any data. The light client will now, correctly, not panic + _and_ keep the node in its list of providers in the same way it would if + it queried a node starting from height zero that does not yet have data + ([\#575](https://github.com/cometbft/cometbft/issues/575)) +- `[abci]` Restore the snake_case naming in JSON serialization of + `ExecTxResult` ([\#855](https://github.com/cometbft/cometbft/issues/855)). +- `[consensus]` Avoid recursive call after rename to (*PeerState).MarshalJSON + ([\#863](https://github.com/cometbft/cometbft/pull/863)) +- `[mempool/clist_mempool]` Prevent a transaction to appear twice in the mempool + ([\#890](https://github.com/cometbft/cometbft/pull/890): @otrack) +- `[docker]` Ensure Docker image uses consistent version of Go. + ([\#9462](https://github.com/tendermint/tendermint/pull/9462)) +- `[abci-cli]` Fix broken abci-cli help command. + ([\#9717](https://github.com/tendermint/tendermint/pull/9717)) + +### DEPRECATIONS + +- `[rpc/grpc]` Mark the gRPC broadcast API as deprecated. + It will be superseded by a broader API as part of + [\#81](https://github.com/cometbft/cometbft/issues/81) + ([\#650](https://github.com/cometbft/cometbft/issues/650)) + +### FEATURES + +- `[node/state]` Add Go API to bootstrap block store and state store to a height + ([\#1057](https://github.com/tendermint/tendermint/pull/#1057)) (@yihuang) +- `[proxy]` Introduce `NewConnSyncLocalClientCreator`, which allows local ABCI + clients to have the same concurrency model as remote clients (i.e. one mutex + per client "connection", for each of the four ABCI "connections"). + ([tendermint/tendermint\#9830](https://github.com/tendermint/tendermint/pull/9830) + and [\#1145](https://github.com/cometbft/cometbft/pull/1145)) +- `[proxy]` Introduce `NewUnsyncLocalClientCreator`, which allows local ABCI + clients to have the same concurrency model as remote clients (i.e. one + mutex per client "connection", for each of the four ABCI "connections"). + ([\#9830](https://github.com/tendermint/tendermint/pull/9830)) +- `[abci]` New ABCI methods `VerifyVoteExtension` and `ExtendVote` allow validators to validate the vote extension data attached to a pre-commit message and allow applications to let their validators do more than just validate within consensus ([\#9836](https://github.com/tendermint/tendermint/pull/9836)) + +### IMPROVEMENTS + +- `[blocksync]` Generate new metrics during BlockSync + ([\#543](https://github.com/cometbft/cometbft/pull/543)) +- `[jsonrpc/client]` Improve the error message for client errors stemming from + bad HTTP responses. + ([cometbft/cometbft\#638](https://github.com/cometbft/cometbft/pull/638)) +- `[rpc]` Remove response data from response failure logs in order + to prevent large quantities of log data from being produced + ([\#654](https://github.com/cometbft/cometbft/issues/654)) +- `[pubsub/kvindexer]` Numeric query conditions and event values are represented as big floats with default precision of 125. + Integers are read as "big ints" and represented with as many bits as they need when converting to floats. + ([\#797](https://github.com/cometbft/cometbft/pull/797)) +- `[node]` Make handshake cancelable ([cometbft/cometbft\#857](https://github.com/cometbft/cometbft/pull/857)) +- `[consensus]` New metrics (counters) to track duplicate votes and block parts. + ([\#896](https://github.com/cometbft/cometbft/pull/896)) +- `[mempool]` Application can now set `ConsensusParams.Block.MaxBytes` to -1 + to gain more control on the max size of transactions in a block. + It also allows the application to have visibility on all transactions in the + mempool at `PrepareProposal` time. + ([\#980](https://github.com/cometbft/cometbft/pull/980)) +- `[node]` Close evidence.db OnStop ([cometbft/cometbft\#1210](https://github.com/cometbft/cometbft/pull/1210): @chillyvee) +- `[state]` Make logging `block_app_hash` and `app_hash` consistent by logging them both as hex. + ([\#1264](https://github.com/cometbft/cometbft/pull/1264)) +- `[crypto/merkle]` Improve HashAlternatives performance + ([\#6443](https://github.com/tendermint/tendermint/pull/6443)) +- `[p2p/pex]` Improve addrBook.hash performance + ([\#6509](https://github.com/tendermint/tendermint/pull/6509)) +- `[crypto/merkle]` Improve HashAlternatives performance + ([\#6513](https://github.com/tendermint/tendermint/pull/6513)) +- `[pubsub]` Performance improvements for the event query API + ([\#7319](https://github.com/tendermint/tendermint/pull/7319)) + +## v0.37.0 + +*March 6, 2023* + +This is the first CometBFT release with ABCI 1.0, which introduces the +`PrepareProposal` and `ProcessProposal` methods, with the aim of expanding the +range of use cases that application developers can address. This is the first +change to ABCI towards ABCI++, and the full range of ABCI++ functionality will +only become available in the next major release with ABCI 2.0. See the +[specification](./spec/abci/) for more details. + +In the v0.34.27 release, the CometBFT Go module is still +`github.com/tendermint/tendermint` to facilitate ease of upgrading for users, +but in this release we have changed this to `github.com/cometbft/cometbft`. + +Please also see our [upgrading guidelines](./UPGRADING.md) for more details on +upgrading from the v0.34 release series. + +Also see our [QA results](https://docs.cometbft.com/v0.37/qa/v037/cometbft) for +the v0.37 release. + +We'd love your feedback on this release! Please reach out to us via one of our +communication channels, such as [GitHub +Discussions](https://github.com/cometbft/cometbft/discussions), with any of your +questions, comments and/or concerns. + +See below for more details. + +### BREAKING CHANGES + +- The `TMHOME` environment variable was renamed to `CMTHOME`, and all environment variables starting with `TM_` are instead prefixed with `CMT_` + ([\#211](https://github.com/cometbft/cometbft/issues/211)) +- `[p2p]` Reactor `Send`, `TrySend` and `Receive` renamed to `SendEnvelope`, + `TrySendEnvelope` and `ReceiveEnvelope` to allow metrics to be appended to + messages and measure bytes sent/received. + ([\#230](https://github.com/cometbft/cometbft/pull/230)) +- Bump minimum Go version to 1.20 + ([\#385](https://github.com/cometbft/cometbft/issues/385)) +- [config] The boolean key `fastsync` is deprecated and replaced by + `block_sync`. ([\#9259](https://github.com/tendermint/tendermint/pull/9259)) + At the same time, `block_sync` is also deprecated. In the next release, + BlocSync will always be enabled and `block_sync` will be removed. + ([\#409](https://github.com/cometbft/cometbft/issues/409)) +- `[abci]` Make length delimiter encoding consistent + (`uint64`) between ABCI and P2P wire-level protocols + ([\#5783](https://github.com/tendermint/tendermint/pull/5783)) +- `[abci]` Change the `key` and `value` fields from + `[]byte` to `string` in the `EventAttribute` type. + ([\#6403](https://github.com/tendermint/tendermint/pull/6403)) +- `[abci/counter]` Delete counter example app + ([\#6684](https://github.com/tendermint/tendermint/pull/6684)) +- `[abci]` Renamed `EvidenceType` to `MisbehaviorType` and `Evidence` + to `Misbehavior` as a more accurate label of their contents. + ([\#8216](https://github.com/tendermint/tendermint/pull/8216)) +- `[abci]` Added cli commands for `PrepareProposal` and `ProcessProposal`. + ([\#8656](https://github.com/tendermint/tendermint/pull/8656)) +- `[abci]` Added cli commands for `PrepareProposal` and `ProcessProposal`. + ([\#8901](https://github.com/tendermint/tendermint/pull/8901)) +- `[abci]` Renamed `LastCommitInfo` to `CommitInfo` in preparation for vote + extensions. ([\#9122](https://github.com/tendermint/tendermint/pull/9122)) +- Change spelling from British English to American. Rename + `Subscription.Cancelled()` to `Subscription.Canceled()` in `libs/pubsub` + ([\#9144](https://github.com/tendermint/tendermint/pull/9144)) +- `[abci]` Removes unused Response/Request `SetOption` from ABCI + ([\#9145](https://github.com/tendermint/tendermint/pull/9145)) +- `[config]` Rename the fastsync section and the + fast\_sync key blocksync and block\_sync respectively + ([\#9259](https://github.com/tendermint/tendermint/pull/9259)) +- `[types]` Reduce the use of protobuf types in core logic. `ConsensusParams`, + `BlockParams`, `ValidatorParams`, `EvidenceParams`, `VersionParams` have + become native types. They still utilize protobuf when being sent over + the wire or written to disk. Moved `ValidateConsensusParams` inside + (now native type) `ConsensusParams`, and renamed it to `ValidateBasic`. + ([\#9287](https://github.com/tendermint/tendermint/pull/9287)) +- `[abci/params]` Deduplicate `ConsensusParams` and `BlockParams` so + only `types` proto definitions are use. Remove `TimeIotaMs` and use + a hard-coded 1 millisecond value to ensure monotonically increasing + block times. Rename `AppVersion` to `App` so as to not stutter. + ([\#9287](https://github.com/tendermint/tendermint/pull/9287)) +- `[abci]` New ABCI methods `PrepareProposal` and `ProcessProposal` which give + the app control over transactions proposed and allows for verification of + proposed blocks. ([\#9301](https://github.com/tendermint/tendermint/pull/9301)) + +### BUG FIXES + +- `[consensus]` Fixed a busy loop that happened when sending of a block part failed by sleeping in case of error. + ([\#4](https://github.com/informalsystems/tendermint/pull/4)) +- `[state/kvindexer]` Fixed the default behaviour of the kvindexer to index and + query attributes by events in which they occur. In 0.34.25 this was mitigated + by a separated RPC flag. @jmalicevic + ([\#77](https://github.com/cometbft/cometbft/pull/77)) +- `[state/kvindexer]` Resolved crashes when event values contained slashes, + introduced after adding event sequences in + [\#77](https://github.com/cometbft/cometbft/pull/77). @jmalicevic + ([\#382](https://github.com/cometbft/cometbft/pull/382)) +- `[consensus]` ([\#386](https://github.com/cometbft/cometbft/pull/386)) Short-term fix for the case when `needProofBlock` cannot find previous block meta by defaulting to the creation of a new proof block. (@adizere) + - Special thanks to the [Vega.xyz](https://vega.xyz/) team, and in particular to Zohar (@ze97286), for reporting the problem and working with us to get to a fix. +- `[docker]` enable cross platform build using docker buildx + ([\#9073](https://github.com/tendermint/tendermint/pull/9073)) +- `[consensus]` fix round number of `enterPropose` + when handling `RoundStepNewRound` timeout. + ([\#9229](https://github.com/tendermint/tendermint/pull/9229)) +- `[docker]` ensure Docker image uses consistent version of Go + ([\#9462](https://github.com/tendermint/tendermint/pull/9462)) +- `[p2p]` prevent peers who have errored from being added to `peer_set` + ([\#9500](https://github.com/tendermint/tendermint/pull/9500)) +- `[blocksync]` handle the case when the sending + queue is full: retry block request after a timeout + ([\#9518](https://github.com/tendermint/tendermint/pull/9518)) + +### FEATURES + +- `[abci]` New ABCI methods `PrepareProposal` and `ProcessProposal` which give + the app control over transactions proposed and allows for verification of + proposed blocks. ([\#9301](https://github.com/tendermint/tendermint/pull/9301)) + +### IMPROVEMENTS + +- `[e2e]` Add functionality for uncoordinated (minor) upgrades + ([\#56](https://github.com/tendermint/tendermint/pull/56)) +- `[tools/tm-signer-harness]` Remove the folder as it is unused + ([\#136](https://github.com/cometbft/cometbft/issues/136)) +- `[p2p]` Reactor `Send`, `TrySend` and `Receive` renamed to `SendEnvelope`, + `TrySendEnvelope` and `ReceiveEnvelope` to allow metrics to be appended to + messages and measure bytes sent/received. + ([\#230](https://github.com/cometbft/cometbft/pull/230)) +- `[abci]` Added `AbciVersion` to `RequestInfo` allowing + applications to check ABCI version when connecting to CometBFT. + ([\#5706](https://github.com/tendermint/tendermint/pull/5706)) +- `[cli]` add `--hard` flag to rollback command (and a boolean to the `RollbackState` method). This will rollback + state and remove the last block. This command can be triggered multiple times. The application must also rollback + state to the same height. + ([\#9171](https://github.com/tendermint/tendermint/pull/9171)) +- `[crypto]` Update to use btcec v2 and the latest btcutil. + ([\#9250](https://github.com/tendermint/tendermint/pull/9250)) +- `[rpc]` Added `header` and `header_by_hash` queries to the RPC client + ([\#9276](https://github.com/tendermint/tendermint/pull/9276)) +- `[proto]` Migrate from `gogo/protobuf` to `cosmos/gogoproto` + ([\#9356](https://github.com/tendermint/tendermint/pull/9356)) +- `[rpc]` Enable caching of RPC responses + ([\#9650](https://github.com/tendermint/tendermint/pull/9650)) +- `[consensus]` Save peer LastCommit correctly to achieve 50% reduction in gossiped precommits. + ([\#9760](https://github.com/tendermint/tendermint/pull/9760)) + +## v0.34.27 + +*Feb 27, 2023* + +This is the first official release of CometBFT - a fork of [Tendermint +Core](https://github.com/tendermint/tendermint). This particular release is +intended to be compatible with the Tendermint Core v0.34 release series. + +For details as to how to upgrade to CometBFT from Tendermint Core, please see +our [upgrading guidelines](./UPGRADING.md). + +If you have any questions, comments, concerns or feedback on this release, we +would love to hear from you! Please contact us via [GitHub +Discussions](https://github.com/cometbft/cometbft/discussions), +[Discord](https://discord.gg/cosmosnetwork) (in the `#cometbft` channel) or +[Telegram](https://t.me/CometBFT). + +Special thanks to @wcsiu, @ze97286, @faddat and @JayT106 for their contributions +to this release! + +### BREAKING CHANGES + +- Rename binary to `cometbft` and Docker image to `cometbft/cometbft` + ([\#152](https://github.com/cometbft/cometbft/pull/152)) +- The `TMHOME` environment variable was renamed to `CMTHOME`, and all + environment variables starting with `TM_` are instead prefixed with `CMT_` + ([\#211](https://github.com/cometbft/cometbft/issues/211)) +- Use Go 1.19 to build CometBFT, since Go 1.18 has reached end-of-life. + ([\#360](https://github.com/cometbft/cometbft/issues/360)) + +### BUG FIXES + +- `[consensus]` Fixed a busy loop that happened when sending of a block part + failed by sleeping in case of error. + ([\#4](https://github.com/informalsystems/tendermint/pull/4)) +- `[state/kvindexer]` Resolved crashes when event values contained slashes, + introduced after adding event sequences. + (\#[383](https://github.com/cometbft/cometbft/pull/383): @jmalicevic) +- `[consensus]` Short-term fix for the case when `needProofBlock` cannot find + previous block meta by defaulting to the creation of a new proof block. + ([\#386](https://github.com/cometbft/cometbft/pull/386): @adizere) + - Special thanks to the [Vega.xyz](https://vega.xyz/) team, and in particular + to Zohar (@ze97286), for reporting the problem and working with us to get to + a fix. +- `[p2p]` Correctly use non-blocking `TrySendEnvelope` method when attempting to + send messages, as opposed to the blocking `SendEnvelope` method. It is unclear + whether this has a meaningful impact on P2P performance, but this patch does + correct the underlying behaviour to what it should be + ([tendermint/tendermint\#9936](https://github.com/tendermint/tendermint/pull/9936)) + +### DEPENDENCIES + +- Replace [tm-db](https://github.com/tendermint/tm-db) with + [cometbft-db](https://github.com/cometbft/cometbft-db) + ([\#160](https://github.com/cometbft/cometbft/pull/160)) +- Bump tm-load-test to v1.3.0 to remove implicit dependency on Tendermint Core + ([\#165](https://github.com/cometbft/cometbft/pull/165)) +- `[crypto]` Update to use btcec v2 and the latest btcutil + ([tendermint/tendermint\#9787](https://github.com/tendermint/tendermint/pull/9787): + @wcsiu) + +### FEATURES + +- `[rpc]` Add `match_event` query parameter to indicate to the RPC that it + should match events _within_ attributes, not only within a height + ([tendermint/tendermint\#9759](https://github.com/tendermint/tendermint/pull/9759)) + +### IMPROVEMENTS + +- `[e2e]` Add functionality for uncoordinated (minor) upgrades + ([\#56](https://github.com/tendermint/tendermint/pull/56)) +- `[tools/tm-signer-harness]` Remove the folder as it is unused + ([\#136](https://github.com/cometbft/cometbft/issues/136)) +- Append the commit hash to the version of CometBFT being built + ([\#204](https://github.com/cometbft/cometbft/pull/204)) +- `[mempool/v1]` Suppress "rejected bad transaction" in priority mempool logs by + reducing log level from info to debug + ([\#314](https://github.com/cometbft/cometbft/pull/314): @JayT106) +- `[consensus]` Add `consensus_block_gossip_parts_received` and + `consensus_step_duration_seconds` metrics in order to aid in investigating the + impact of database compaction on consensus performance + ([tendermint/tendermint\#9733](https://github.com/tendermint/tendermint/pull/9733)) +- `[state/kvindexer]` Add `match.event` keyword to support condition evaluation + based on the event the attributes belong to + ([tendermint/tendermint\#9759](https://github.com/tendermint/tendermint/pull/9759)) +- `[p2p]` Reduce log spam through reducing log level of "Dialing peer" and + "Added peer" messages from info to debug + ([tendermint/tendermint\#9764](https://github.com/tendermint/tendermint/pull/9764): + @faddat) +- `[consensus]` Reduce bandwidth consumption of consensus votes by roughly 50% + through fixing a small logic bug + ([tendermint/tendermint\#9776](https://github.com/tendermint/tendermint/pull/9776)) + +--- + +CometBFT is a fork of [Tendermint Core](https://github.com/tendermint/tendermint) as of late December 2022. + +## Bug bounty + +Friendly reminder, we have a [bug bounty program](https://hackerone.com/cosmos). + +## Previous changes + +For changes released before the creation of CometBFT, please refer to the Tendermint Core [CHANGELOG.md](https://github.com/tendermint/tendermint/blob/a9feb1c023e172b542c972605311af83b777855b/CHANGELOG.md). + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..7344abd --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,109 @@ +# The CometBFT Code of Conduct + +This code of conduct applies to all projects run by the CometBFT team and +hence to CometBFT. + +---- + +# Conduct + +## Contact: conduct@informal.systems + +* We are committed to providing a friendly, safe and welcoming environment for + all, regardless of level of experience, gender, gender identity and + expression, sexual orientation, disability, personal appearance, body size, + race, ethnicity, age, religion, nationality, or other similar characteristics. + +* On Slack, please avoid using overtly sexual nicknames or other nicknames that + might detract from a friendly, safe and welcoming environment for all. + +* Please be kind and courteous. There’s no need to be mean or rude. + +* Respect that people have differences of opinion and that every design or + implementation choice carries a trade-off and numerous costs. There is seldom + a right answer. + +* Please keep unstructured critique to a minimum. If you have solid ideas you + want to experiment with, make a fork and see how it works. + +* We will exclude you from interaction if you insult, demean or harass anyone. + That is not welcome behavior. We interpret the term “harassment” as including + the definition in the [Citizen Code of Conduct][ccoc]; if you have any lack of + clarity about what might be included in that concept, please read their + definition. In particular, we don’t tolerate behavior that excludes people in + socially marginalized groups. + +* Private harassment is also unacceptable. No matter who you are, if you feel + you have been or are being harassed or made uncomfortable by a community + member, please get in touch with one of the channel admins or the contact address above + immediately. Whether you’re a regular contributor or a newcomer, we care about + making this community a safe place for you and we’ve got your back. + +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing + behavior is not welcome. + +---- + +# Moderation + +These are the policies for upholding our community’s standards of conduct. If +you feel that a thread needs moderation, please contact the above mentioned +person. + +1. Remarks that violate the CometBFT/Cosmos standards of conduct, including + hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. + (Cursing is allowed, but never targeting another user, and never in a hateful + manner.) + +2. Remarks that moderators find inappropriate, whether listed in the code of + conduct or not, are also not allowed. + +3. Moderators will first respond to such remarks with a warning. + +4. If the warning is unheeded, the user will be “kicked,” i.e., kicked out of + the communication channel to cool off. + +5. If the user comes back and continues to make trouble, they will be banned, + i.e., indefinitely excluded. + +6. Moderators may choose at their discretion to un-ban the user if it was a + first offense and they offer the offended party a genuine apology. + +7. If a moderator bans someone and you think it was unjustified, please take it + up with that moderator, or with a different moderator, in private. Complaints + about bans in-channel are not allowed. + +8. Moderators are held to a higher standard than other community members. If a + moderator creates an inappropriate situation, they should expect less leeway + than others. + +In the CometBFT/Cosmos community we strive to go the extra step to look out +for each other. Don’t just aim to be technically unimpeachable, try to be your +best self. In particular, avoid flirting with offensive or sensitive issues, +particularly if they’re off-topic; this all too often leads to unnecessary +fights, hurt feelings, and damaged trust; worse, it can drive people away +from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be +defensive. Just stop doing what it was they complained about and apologize. Even +if you feel you were misinterpreted or unfairly accused, chances are good there +was something you could’ve communicated better — remember that it’s your +responsibility to make your fellow Cosmonauts comfortable. Everyone wants to +get along and we are all here first and foremost because we want to talk +about cool technology. You will find that people will be eager to assume +good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official CometBFT/Cosmos +venues. For other projects adopting the CometBFT/Cosmos Code of Conduct, +please contact the maintainers of those projects for enforcement. If you wish to +use this code of conduct for your own project, consider explicitly mentioning +your moderation policy or making a copy with your own moderation policy so as to +avoid confusion. + +\*Adapted from the [Node.js Policy on Trolling][node-trolling-policy], the +[Contributor Covenant v1.3.0][ccov] and the [Rust Code of Conduct][rust-coc]. + +[ccoc]: https://github.com/stumpsyn/policies/blob/master/citizen_code_of_conduct.md +[node-trolling-policy]: http://blog.izs.me/post/30036893703/policy-on-trolling +[ccov]: http://contributor-covenant.org/version/1/3/0/ +[rust-coc]: https://www.rust-lang.org/en-US/conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..67206ab --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,381 @@ +# Contributing + +Thank you for your interest in contributing to CometBFT! Before contributing, it +may be helpful to understand the goal of the project. The goal of CometBFT is to +develop a BFT consensus engine robust enough to support permissionless +value-carrying networks. While all contributions are welcome, contributors +should bear this goal in mind in deciding if they should target the main +CometBFT project or a potential fork. When targeting the main CometBFT project, +the following process leads to the best chance of landing changes in `main`. + +All work on the code base should be motivated by a [GitHub +Issue](https://github.com/cometbft/cometbft/issues). +[Search](https://github.com/cometbft/cometbft/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) +is a good place to start when looking for places to contribute. If you would +like to work on an issue which already exists, please indicate so by leaving a +comment. + +All new contributions should start with a [GitHub +Issue](https://github.com/cometbft/cometbft/issues/new/choose). The issue helps +capture the problem you're trying to solve and allows for early feedback. Once +the issue is created the process can proceed in different directions depending +on how well defined the problem and potential solution are. If the change is +simple and well understood, maintainers will indicate their support with a +heartfelt emoji. + +If the issue would benefit from thorough discussion, maintainers may request +that you create a [Request For +Comment](https://github.com/cometbft/cometbft/tree/main/docs/rfc) in the +CometBFT repo. Discussion at the RFC stage will build collective +understanding of the dimensions of the problems and help structure conversations +around trade-offs. + +When the problem is well understood but the solution leads to large structural +changes to the code base, these changes should be proposed in the form of an +[Architectural Decision Record (ADR)](./docs/architecture/). The ADR will help +build consensus on an overall strategy to ensure the code base maintains +coherence in the larger context. If you are not comfortable with writing an ADR, +you can open a less-formal issue and the maintainers will help you turn it into +an ADR. + +> How to pick a number for the ADR? + +Find the largest existing ADR number and bump it by 1. + +When the problem as well as proposed solution are well understood, +changes should start with a [draft +pull request](https://github.blog/2019-02-14-introducing-draft-pull-requests/) +against `main`. The draft signals that work is underway. When the work +is ready for feedback, hitting "Ready for Review" will signal to the +maintainers to take a look. + +![Contributing flow](./docs/imgs/contributing.png) + +Each stage of the process is aimed at creating feedback cycles which align contributors and maintainers to make sure: + +- Contributors don’t waste their time implementing/proposing features which won’t land in `main`. +- Maintainers have the necessary context in order to support and review contributions. + + +## Forking + +Please note that Go requires code to live under absolute paths, which complicates forking. +While my fork lives at `https://github.com/ebuchman/cometbft`, +the code should never exist at `$GOPATH/src/github.com/ebuchman/cometbft`. +Instead, we use `git remote` to add the fork as a new remote for the original repo, +`$GOPATH/src/github.com/cometbft/cometbft`, and do all the work there. + +For instance, to create a fork and work on a branch of it, I would: + +- Create the fork on GitHub, using the fork button. +- Go to the original repo checked out locally (i.e. `$GOPATH/src/github.com/cometbft/cometbft`) +- `git remote rename origin upstream` +- `git remote add origin git@github.com:ebuchman/basecoin.git` + +Now `origin` refers to my fork and `upstream` refers to the CometBFT version. +So I can `git push -u origin main` to update my fork, and make pull requests to CometBFT from there. +Of course, replace `ebuchman` with your git handle. + +To pull in updates from the origin repo, run + +- `git fetch upstream` +- `git rebase upstream/main` (or whatever branch you want) + +## Dependencies + +We use [go modules](https://github.com/golang/go/wiki/Modules) to manage dependencies. + +That said, the `main` branch of every CometBFT repository should just build +with `go get`, which means they should be kept up-to-date with their +dependencies so we can get away with telling people they can just `go get` our +software. + +Since some dependencies are not under our control, a third party may break our +build, in which case we can fall back on `go mod tidy`. Even for dependencies under our control, go helps us to +keep multiple repos in sync as they evolve. Anything with an executable, such +as apps, tools, and the core, should use dep. + +Run `go list -u -m all` to get a list of dependencies that may not be +up-to-date. + +When updating dependencies, please only update the particular dependencies you +need. Instead of running `go get -u=patch`, which will update anything, +specify exactly the dependency you want to update. + +## Protobuf + +We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along +with [`gogoproto`](https://github.com/cosmos/gogoproto) to generate code for use +across CometBFT. + +To generate proto stubs, lint, and check protos for breaking changes, you will +need to install [buf](https://buf.build/) and `gogoproto`. Then, from the root +of the repository, run: + +```bash +# Lint all of the .proto files +make proto-lint + +# Check if any of your local changes (prior to committing to the Git repository) +# are breaking +make proto-check-breaking + +# Generate Go code from the .proto files +make proto-gen +``` + +To automatically format `.proto` files, you will need +[`clang-format`](https://clang.llvm.org/docs/ClangFormat.html) installed. Once +installed, you can run: + +```bash +make proto-format +``` + +### Visual Studio Code + +If you are a VS Code user, you may want to add the following to your `.vscode/settings.json`: + +```json +{ + "protoc": { + "options": [ + "--proto_path=${workspaceRoot}/proto", + ] + } +} +``` + +## Changelog + +Every PR with types `fix`, `feat`, `deps`, and `refactor` should include an entry in `CHANGELOG.md`. Commits on the +`main` branch should be placed under `UNRELEASED` within the correct category. +The categories include `DEPENDENCIES`, `IMPROVEMENTS`, `FEATURES`, `BUG-FIXES`, `STATE-BREAKING`, `API-BREAKING`. + +For examples, see the [CHANGELOG.md](CHANGELOG.md) file. + +A feature can also be worked on a feature branch, if its size and/or risk +justifies it (see [below](#branching-model-and-release)). + +### What does a good changelog entry look like? + +Changelog entries should answer the question: "what is important about this +change for users to know?" or "what problem does this solve for users?". It +should not simply be a reiteration of the title of the associated PR, unless the +title of the PR _very_ clearly explains the benefit of a change to a user. + +Some good examples of changelog entry descriptions: + +```md +- [consensus] \#1111 Small transaction throughput improvement (approximately + 3-5\% from preliminary tests) through refactoring the way we use channels +- [mempool] \#1112 Refactor Go API to be able to easily swap out the current + mempool implementation in CometBFT forks +- [p2p] \#1113 Automatically ban peers when their messages are unsolicited or + are received too frequently +``` + +Some bad examples of changelog entry descriptions: + +```md +- [consensus] \#1111 Refactor channel usage +- [mempool] \#1112 Make API generic +- [p2p] \#1113 Ban for PEX message abuse +``` + +For more on how to write good changelog entries, see: + +- +- +- + +### Changelog entry format + +Changelog entries should be formatted as follows: + +```md +- [module] \#xxx Some description of the change (@contributor) +``` + +Here, `module` is the part of the code that changed (typically a top-level Go +package), `xxx` is the pull-request number, and `contributor` is the author/s of +the change. + +It's also acceptable for `xxx` to refer to the relevant issue number, but +pull-request numbers are preferred. Note this means pull-requests should be +opened first so the changelog can then be updated with the pull-request's +number. There is no need to include the full link, as this will be added +automatically during release. But please include the backslash and pound, eg. +`\#2313`. + +Changelog entries should be ordered alphabetically according to the `module`, +and numerically according to the pull-request number. + +Changes with multiple classifications should be doubly included (eg. a bug fix +that is also a breaking change should be recorded under both). + +Breaking changes are further subdivided according to the APIs/users they impact. +Any change that affects multiple APIs/users should be recorded multiply - for +instance, a change to the `Blockchain Protocol` that removes a field from the +header should also be recorded under `CLI/RPC/Config` since the field will be +removed from the header in RPC responses as well. + +## Branching Model and Release + +The main development branch is `main`. + +Every release is maintained in a release branch named `vX.Y.Z`. + +Pending minor releases have long-lived release candidate ("RC") branches. Minor +release changes should be merged to these long-lived RC branches at the same +time that the changes are merged to `main`. + +If a feature's size is big and/or its risk is high, it can be implemented in a +feature branch. While the feature work is in progress, pull requests are open +and squash merged against the feature branch. Branch `main` is periodically +merged (merge commit) into the feature branch, to reduce branch divergence. When +the feature is complete, the feature branch is merged back (merge commit) into +`main`. The moment of the final merge can be carefully chosen so as to land +different features in different releases. + +Note, all pull requests should be squash merged except for merging to a release +branch (named `vX.Y`). This keeps the commit history clean and makes it easy to +reference the pull request where a change was introduced. + +### Development Procedure + +The latest state of development is on `main`, which must never fail `make test`. +_Never_ force push `main`, unless fixing broken git history (which we rarely do +anyways). + +To begin contributing, create a development branch either on +`github.com/cometbft/cometbft`, or your fork (using `git remote add origin`). + +Make changes, and before submitting a pull request, update the changelog to +record your change. Also, run either `git rebase` or `git merge` on top of the +latest `main`. (Since pull requests are squash-merged, either is fine!) + +Update the `UPGRADING.md` if the change you've made is breaking and the +instructions should be in place for a user on how he/she can upgrade its +software (ABCI application, CometBFT blockchain, light client, wallet). + +Sometimes (often!) pull requests get out-of-date with `main`, as other people +merge different pull requests to `main`. It is our convention that pull request +authors are responsible for updating their branches with `main`. (This also +means that you shouldn't update someone else's branch for them; even if it seems +like you're doing them a favor, you may be interfering with their git flow in +some way!) + +#### Merging Pull Requests + +It is also our convention that authors merge their own pull requests, when +possible. External contributors may not have the necessary permissions to do +this, in which case, a member of the core team will merge the pull request once +it's been approved. + +Before merging a pull request: + +- Ensure pull branch is up-to-date with a recent `main` (GitHub won't let you + merge without this!) +- Run `make test` to ensure that all tests pass +- [Squash](https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git) + merge pull request + +#### Pull Requests for Minor Releases + +If your change should be included in a minor release, please also open a PR +against the long-lived minor release candidate branch (e.g., `rc1/v0.33.5`) +_immediately after your change has been merged to main_. + +You can do this by cherry-picking your commit off `main`: + +```sh +$ git checkout rc1/v0.33.5 +$ git checkout -b {new branch name} +$ git cherry-pick {commit SHA from main} +# may need to fix conflicts, and then use git add and git cherry-pick --continue +$ git push origin {new branch name} +``` + +After this, you can open a PR. Please note in the PR body if there were merge +conflicts so that reviewers can be sure to take a thorough look. + +### Git Commit Style + +We follow the [Go style guide on commit +messages](https://tip.golang.org/doc/contribute.html#commit_messages). Write +concise commits that start with the package name and have a description that +finishes the sentence "This change modifies CometBFT to...". For example, + +```sh +cmd/debug: execute p.Signal only when p is not nil + +[potentially longer description in the body] + +Fixes #nnnn +``` + +Each PR should have one commit once it lands on `main`; this can be accomplished +by using the "squash and merge" button on GitHub. Be sure to edit your commit +message, though! + +## Testing + +### Unit tests + +Unit tests are located in `_test.go` files as directed by [the Go testing +package](https://golang.org/pkg/testing/). If you're adding or removing a +function, please check there's a `TestType_Method` test for it. + +Run: `make test` + +### Integration tests + +Integration tests are also located in `_test.go` files. What differentiates +them is a more complicated setup, which usually involves setting up two or more +components. + +Run: `make test_integrations` + +### End-to-end tests + +End-to-end tests are used to verify a fully integrated CometBFT network. + +See [README](./test/e2e/README.md) for details. + +Run: + +```sh +cd test/e2e && \ + make && \ + ./build/runner -f networks/ci.toml +``` + +### Fuzz tests (ADVANCED) + +*NOTE: if you're just submitting your first PR, you won't need to touch these +most probably (99.9%)*. + +[Fuzz tests](https://en.wikipedia.org/wiki/Fuzzing) can be found inside the +`./test/fuzz` directory. See [README.md](./test/fuzz/README.md) for details. + +Run: `cd test/fuzz && make fuzz-{PACKAGE-COMPONENT}` + +### RPC Testing + +**If you contribute to the RPC endpoints it's important to document your +changes in the [Openapi file](./rpc/openapi/openapi.yaml)**. + +To test your changes you must install `nodejs` and run: + +```bash +npm i -g dredd +make build-linux build-contract-tests-hooks +make contract-tests +``` + +**WARNING: these are currently broken due to +not supporting complete OpenAPI 3**. + +This command will popup a network and check every endpoint against what has +been documented. diff --git a/DOCKER/.gitignore b/DOCKER/.gitignore new file mode 100644 index 0000000..1f61891 --- /dev/null +++ b/DOCKER/.gitignore @@ -0,0 +1 @@ +cometbft diff --git a/DOCKER/Dockerfile b/DOCKER/Dockerfile new file mode 100644 index 0000000..7298345 --- /dev/null +++ b/DOCKER/Dockerfile @@ -0,0 +1,61 @@ +# Use a build arg to ensure that both stages use the same, +# hopefully current, go version. +ARG GOLANG_BASE_IMAGE=golang:1.22-alpine + +# stage 1 Generate CometBFT Binary +FROM --platform=$BUILDPLATFORM $GOLANG_BASE_IMAGE as builder +RUN apk update && \ + apk upgrade && \ + apk --no-cache add make git +COPY / /cometbft +WORKDIR /cometbft + +RUN TARGETPLATFORM=$TARGETPLATFORM make build-linux + +# stage 2 +FROM $GOLANG_BASE_IMAGE +LABEL maintainer="hello@informal.systems" + +# CometBFT will be looking for the genesis file in /cometbft/config/genesis.json +# (unless you change `genesis_file` in config.toml). You can put your config.toml and +# private validator file into /cometbft/config. +# +# The /cometbft/data dir is used by CometBFT to store state. +ENV CMTHOME /cometbft + +# OS environment setup +# Set user right away for determinism, create directory for persistence and give our user ownership +# jq and curl used for extracting `pub_key` from private validator while +# deploying CometBFT with Kubernetes. It is nice to have bash so the users +# could execute bash commands. +RUN apk update && \ + apk upgrade && \ + apk --no-cache add curl jq bash && \ + addgroup tmuser && \ + adduser -S -G tmuser tmuser -h "$CMTHOME" + +# Run the container with tmuser by default. (UID=100, GID=1000) +USER tmuser + +WORKDIR $CMTHOME + +# p2p, rpc and prometheus port +EXPOSE 26656 26657 26660 + +STOPSIGNAL SIGTERM + +COPY --from=builder /cometbft/build/cometbft /usr/bin/cometbft + +# You can overwrite these before the first run to influence +# config.json and genesis.json. Additionally, you can override +# CMD to add parameters to `cometbft node`. +ENV PROXY_APP=kvstore MONIKER=dockernode CHAIN_ID=dockerchain + +COPY ./DOCKER/docker-entrypoint.sh /usr/local/bin/ + +ENTRYPOINT ["docker-entrypoint.sh"] +CMD ["node"] + +# Expose the data directory as a volume since there's mutable state in there +VOLUME [ "$CMTHOME" ] + diff --git a/DOCKER/Dockerfile.build_c-amazonlinux b/DOCKER/Dockerfile.build_c-amazonlinux new file mode 100644 index 0000000..0c6ea41 --- /dev/null +++ b/DOCKER/Dockerfile.build_c-amazonlinux @@ -0,0 +1,28 @@ +FROM amazonlinux:2 + +RUN yum -y update && \ + yum -y install wget + +RUN wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm && \ + rpm -ivh epel-release-latest-7.noarch.rpm + +RUN yum -y groupinstall "Development Tools" +RUN yum -y install leveldb-devel which + +ENV GOVERSION=1.12.9 + +RUN cd /tmp && \ + wget https://dl.google.com/go/go${GOVERSION}.linux-amd64.tar.gz && \ + tar -C /usr/local -xf go${GOVERSION}.linux-amd64.tar.gz && \ + mkdir -p /go/src && \ + mkdir -p /go/bin + +ENV PATH=$PATH:/usr/local/go/bin:/go/bin +ENV GOBIN=/go/bin +ENV GOPATH=/go/src + +RUN mkdir -p /cometbft +WORKDIR /cometbft + +CMD ["/usr/bin/make", "build", "COMETBFT_BUILD_OPTIONS=cleveldb"] + diff --git a/DOCKER/Dockerfile.testing b/DOCKER/Dockerfile.testing new file mode 100644 index 0000000..ad14c9c --- /dev/null +++ b/DOCKER/Dockerfile.testing @@ -0,0 +1,16 @@ +FROM golang:latest + +# Grab deps (jq, hexdump, xxd, killall) +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + jq bsdmainutils vim-common psmisc netcat + +# Add testing deps for curl +RUN echo 'deb http://httpredir.debian.org/debian testing main non-free contrib' >> /etc/apt/sources.list && \ + apt-get update && \ + apt-get install -y --no-install-recommends curl + +VOLUME /go + +EXPOSE 26656 +EXPOSE 26657 diff --git a/DOCKER/Makefile b/DOCKER/Makefile new file mode 100644 index 0000000..a86cee6 --- /dev/null +++ b/DOCKER/Makefile @@ -0,0 +1,13 @@ +build: + @sh -c "'$(CURDIR)/build.sh'" + +push: + @sh -c "'$(CURDIR)/push.sh'" + +build_testing: + docker build --tag cometbft/testing -f ./Dockerfile.testing . + +build_amazonlinux_buildimage: + docker build -t "cometbft/cometbft:build_c-amazonlinux" -f Dockerfile.build_c-amazonlinux . + +.PHONY: build push build_testing build_amazonlinux_buildimage diff --git a/DOCKER/README.md b/DOCKER/README.md new file mode 100644 index 0000000..29ae61b --- /dev/null +++ b/DOCKER/README.md @@ -0,0 +1,56 @@ +# Docker + +## Supported tags and respective `Dockerfile` links + +DockerHub tags for official releases are [here](https://hub.docker.com/r/cometbft/cometbft/tags/). The "latest" tag will always point to the highest version number. + +Official releases can be found [here](https://github.com/cometbft/cometbft/releases). + +The Dockerfile for CometBFT is not expected to change in the near future. The main file used for all builds can be found [here](https://raw.githubusercontent.com/cometbft/cometbft/main/DOCKER/Dockerfile). + +Respective versioned files can be found at `https://raw.githubusercontent.com/cometbft/cometbft/vX.XX.XX/DOCKER/Dockerfile` (replace the Xs with the version number). + +## Quick reference + +- **Where to get help:** +- **Where to file issues:** +- **Supported Docker versions:** [the latest release](https://github.com/moby/moby/releases) (down to 1.6 on a best-effort basis) + +## CometBFT + +CometBFT is Byzantine Fault Tolerant (BFT) middleware that takes a state transition machine, written in any programming language, and securely replicates it on many machines. + +For more background, see the [the docs](https://docs.cometbft.com/v0.38.x/introduction/#quick-start). + +To get started developing applications, see the [application developers guide](https://docs.cometbft.com/v0.38.x/introduction/quick-start.html). + +## How to use this image + +### Start one instance of the CometBFT with the `kvstore` app + +A quick example of a built-in app and CometBFT in one container. + +```sh +docker run -it --rm -v "/tmp:/cometbft" cometbft/cometbft init +docker run -it --rm -v "/tmp:/cometbft" cometbft/cometbft node --proxy_app=kvstore +``` + +## Local cluster + +To run a 4-node network, see the `Makefile` in the root of [the repo](https://github.com/cometbft/cometbft/blob/v0.38.x/Makefile) and run: + +```sh +make build-linux +make build-docker-localnode +make localnet-start +``` + +Note that this will build and use a different image than the ones provided here. + +## License + +- CometBFT's license is [Apache 2.0](https://github.com/cometbft/cometbft/blob/v0.38.x/LICENSE). + +## Contributing + +Contributions are most welcome! See the [contributing file](https://github.com/cometbft/cometbft/blob/v0.38.x/CONTRIBUTING.md) for more information. diff --git a/DOCKER/build.sh b/DOCKER/build.sh new file mode 100755 index 0000000..ec3226d --- /dev/null +++ b/DOCKER/build.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -e + +# Get the tag from the version, or try to figure it out. +if [ -z "$TAG" ]; then + TAG=$(awk -F\" '/TMCoreSemVer =/ { print $2; exit }' < ../version/version.go) +fi +if [ -z "$TAG" ]; then + echo "Please specify a tag." + exit 1 +fi + +TAG_NO_PATCH=${TAG%.*} + +read -p "==> Build 3 docker images with the following tags (latest, $TAG, $TAG_NO_PATCH)? y/n" -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]] +then + docker build \ + -t "cometbft/cometbft" \ + -t "cometbft/cometbft:$TAG" \ + -t "cometbft/cometbft:$TAG_NO_PATCH" . +fi diff --git a/DOCKER/docker-entrypoint.sh b/DOCKER/docker-entrypoint.sh new file mode 100755 index 0000000..5bc2269 --- /dev/null +++ b/DOCKER/docker-entrypoint.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -e + +if [ ! -d "$CMTHOME/config" ]; then + echo "Running cometbft init to create (default) configuration for docker run." + cometbft init + + sed -i \ + -e "s/^proxy_app\s*=.*/proxy_app = \"$PROXY_APP\"/" \ + -e "s/^moniker\s*=.*/moniker = \"$MONIKER\"/" \ + -e 's/^addr_book_strict\s*=.*/addr_book_strict = false/' \ + -e 's/^timeout_commit\s*=.*/timeout_commit = "500ms"/' \ + -e 's/^index_all_tags\s*=.*/index_all_tags = true/' \ + -e 's,^laddr = "tcp://127.0.0.1:26657",laddr = "tcp://0.0.0.0:26657",' \ + -e 's/^prometheus\s*=.*/prometheus = true/' \ + "$CMTHOME/config/config.toml" + + jq ".chain_id = \"$CHAIN_ID\" | .consensus_params.block.time_iota_ms = \"500\"" \ + "$CMTHOME/config/genesis.json" > "$CMTHOME/config/genesis.json.new" + mv "$CMTHOME/config/genesis.json.new" "$CMTHOME/config/genesis.json" +fi + +exec cometbft "$@" diff --git a/DOCKER/push.sh b/DOCKER/push.sh new file mode 100755 index 0000000..a952c05 --- /dev/null +++ b/DOCKER/push.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -e + +# Get the tag from the version, or try to figure it out. +if [ -z "$TAG" ]; then + TAG=$(awk -F\" '/TMCoreSemVer =/ { print $2; exit }' < ../version/version.go) +fi +if [ -z "$TAG" ]; then + echo "Please specify a tag." + exit 1 +fi + +TAG_NO_PATCH=${TAG%.*} + +read -p "==> Push 3 docker images with the following tags (latest, $TAG, $TAG_NO_PATCH)? y/n" -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]] +then + docker push "cometbft/cometbft:latest" + docker push "cometbft/cometbft:$TAG" + docker push "cometbft/cometbft:$TAG_NO_PATCH" +fi diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a5cec31 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f7395e0 --- /dev/null +++ b/Makefile @@ -0,0 +1,376 @@ +include common.mk + +PACKAGES=$(shell go list ./...) +BUILDDIR?=$(CURDIR)/build +OUTPUT?=$(BUILDDIR)/cometbft + +HTTPS_GIT := https://github.com/cometbft/cometbft.git +CGO_ENABLED ?= 0 + +# Process Docker environment varible TARGETPLATFORM +# in order to build binary with correspondent ARCH +# by default will always build for linux/amd64 +TARGETPLATFORM ?= +GOOS ?= linux +GOARCH ?= amd64 +GOARM ?= + +ifeq (linux/arm,$(findstring linux/arm,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=arm + GOARM=7 +endif + +ifeq (linux/arm/v6,$(findstring linux/arm/v6,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=arm + GOARM=6 +endif + +ifeq (linux/arm64,$(findstring linux/arm64,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=arm64 + GOARM=7 +endif + +ifeq (linux/386,$(findstring linux/386,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=386 +endif + +ifeq (linux/amd64,$(findstring linux/amd64,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=amd64 +endif + +ifeq (linux/mips,$(findstring linux/mips,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=mips +endif + +ifeq (linux/mipsle,$(findstring linux/mipsle,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=mipsle +endif + +ifeq (linux/mips64,$(findstring linux/mips64,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=mips64 +endif + +ifeq (linux/mips64le,$(findstring linux/mips64le,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=mips64le +endif + +ifeq (linux/riscv64,$(findstring linux/riscv64,$(TARGETPLATFORM))) + GOOS=linux + GOARCH=riscv64 +endif + +#? all: Run target build, test and install +all: build test install +.PHONY: all + +include tests.mk + +############################################################################### +### Build CometBFT ### +############################################################################### + +#? build: Build CometBFT +build: + CGO_ENABLED=$(CGO_ENABLED) go build $(BUILD_FLAGS) -tags '$(BUILD_TAGS)' -o $(OUTPUT) ./cmd/cometbft/ +.PHONY: build + +#? install: Install CometBFT to GOBIN +install: + CGO_ENABLED=$(CGO_ENABLED) go install $(BUILD_FLAGS) -tags $(BUILD_TAGS) ./cmd/cometbft +.PHONY: install + +############################################################################### +### Metrics ### +############################################################################### + +#? metrics: Generate metrics +metrics: testdata-metrics + go generate -run="scripts/metricsgen" ./... +.PHONY: metrics + +# By convention, the go tool ignores subdirectories of directories named +# 'testdata'. This command invokes the generate command on the folder directly +# to avoid this. +#? testdata-metrics: Generate test data for metrics +testdata-metrics: + ls ./scripts/metricsgen/testdata | xargs -I{} go generate -v -run="scripts/metricsgen" ./scripts/metricsgen/testdata/{} +.PHONY: testdata-metrics + +############################################################################### +### Mocks ### +############################################################################### + +#? mockery: Generate test mocks +mockery: + go generate -run="./scripts/mockery_generate.sh" ./... +.PHONY: mockery + +############################################################################### +### Protobuf ### +############################################################################### + +#? check-proto-deps: Check protobuf deps +check-proto-deps: +ifeq (,$(shell which protoc-gen-gogofaster)) + @go install github.com/cosmos/gogoproto/protoc-gen-gogofaster@latest +endif +.PHONY: check-proto-deps + +#? check-proto-format-deps: Check protobuf format deps +check-proto-format-deps: +ifeq (,$(shell which clang-format)) + $(error "clang-format is required for Protobuf formatting. See instructions for your platform on how to install it.") +endif +.PHONY: check-proto-format-deps + +#? proto-gen: Generate protobuf files +proto-gen: check-proto-deps + @echo "Generating Protobuf files" + @go run github.com/bufbuild/buf/cmd/buf@latest generate + @mv ./proto/tendermint/abci/types.pb.go ./abci/types/ + @cp ./proto/tendermint/rpc/grpc/types.pb.go ./rpc/grpc +.PHONY: proto-gen + +# These targets are provided for convenience and are intended for local +# execution only. +#? proto-lint: Lint protobuf files +proto-lint: check-proto-deps + @echo "Linting Protobuf files" + @go run github.com/bufbuild/buf/cmd/buf@latest lint +.PHONY: proto-lint + +#? proto-format: Format protobuf files +proto-format: check-proto-format-deps + @echo "Formatting Protobuf files" + @find . -name '*.proto' -path "./proto/*" -exec clang-format -i {} \; +.PHONY: proto-format + +#? proto-check-breaking: Check for breaking changes in Protobuf files against local branch. This is only useful if your changes have not yet been committed +proto-check-breaking: check-proto-deps + @echo "Checking for breaking changes in Protobuf files against local branch" + @echo "Note: This is only useful if your changes have not yet been committed." + @echo " Otherwise read up on buf's \"breaking\" command usage:" + @echo " https://docs.buf.build/breaking/usage" + @go run github.com/bufbuild/buf/cmd/buf@latest breaking --against ".git" +.PHONY: proto-check-breaking + +proto-check-breaking-ci: + @go run github.com/bufbuild/buf/cmd/buf@latest breaking --against $(HTTPS_GIT)#branch=v0.34.x +.PHONY: proto-check-breaking-ci + +############################################################################### +### Build ABCI ### +############################################################################### + +#? build_abci: Build abci +build_abci: + @go build -mod=readonly -i ./abci/cmd/... +.PHONY: build_abci + +#? install_abci: Install abci +install_abci: + @go install -mod=readonly ./abci/cmd/... +.PHONY: install_abci + +############################################################################### +### Distribution ### +############################################################################### + +# dist builds binaries for all platforms and packages them for distribution +# TODO add abci to these scripts +#? dist: Build binaries for all platforms and package them for distribution +dist: + @BUILD_TAGS=$(BUILD_TAGS) sh -c "'$(CURDIR)/scripts/dist.sh'" +.PHONY: dist + +#? go-mod-cache: Download go modules to local cache +go-mod-cache: go.sum + @echo "--> Download go modules to local cache" + @go mod download +.PHONY: go-mod-cache + +#? go.sum: Ensure dependencies have not been modified +go.sum: go.mod + @echo "--> Ensure dependencies have not been modified" + @go mod verify + @go mod tidy + +#? draw_deps: Generate deps graph +draw_deps: + @# requires brew install graphviz or apt-get install graphviz + go get github.com/RobotsAndPencils/goviz + @goviz -i github.com/cometbft/cometbft/cmd/cometbft -d 3 | dot -Tpng -o dependency-graph.png +.PHONY: draw_deps + +get_deps_bin_size: + @# Copy of build recipe with additional flags to perform binary size analysis + $(eval $(shell go build -work -a $(BUILD_FLAGS) -tags $(BUILD_TAGS) -o $(OUTPUT) ./cmd/cometbft/ 2>&1)) + @find $(WORK) -type f -name "*.a" | xargs -I{} du -hxs "{}" | sort -rh | sed -e s:${WORK}/::g > deps_bin_size.log + @echo "Results can be found here: $(CURDIR)/deps_bin_size.log" +.PHONY: get_deps_bin_size + +############################################################################### +### Libs ### +############################################################################### + +#? gen_certs: Generate certificates for TLS testing in remotedb and RPC server +gen_certs: clean_certs + certstrap init --common-name "cometbft.com" --passphrase "" + certstrap request-cert --common-name "server" -ip "127.0.0.1" --passphrase "" + certstrap sign "server" --CA "cometbft.com" --passphrase "" + mv out/server.crt rpc/jsonrpc/server/test.crt + mv out/server.key rpc/jsonrpc/server/test.key + rm -rf out +.PHONY: gen_certs + +#? clean_certs: Delete generated certificates +clean_certs: + rm -f rpc/jsonrpc/server/test.crt + rm -f rpc/jsonrpc/server/test.key +.PHONY: clean_certs + +############################################################################### +### Formatting, linting, and vetting ### +############################################################################### + +format: + find . -name '*.go' -type f -not -path "*.git*" -not -name '*.pb.go' -not -name '*pb_test.go' | xargs gofmt -w -s + find . -name '*.go' -type f -not -path "*.git*" -not -name '*.pb.go' -not -name '*pb_test.go' | xargs goimports -w -local github.com/cometbft/cometbft +.PHONY: format + +#? lint: Run latest golangci-lint linter +lint: + @echo "--> Running linter" + @go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest run +.PHONY: lint + +#? lint: Run latest golangci-lint linter and apply fixes +lint-fix: + @echo "--> Running linter" + @go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest run --fix +.PHONY: lint-fix + +#? lint-typo: Run codespell to check typos +lint-typo: + which codespell || pip3 install codespell + @codespell +.PHONY: lint-typo + +#? lint-typo: Run codespell to auto fix typos +lint-fix-typo: + @codespell -w +.PHONY: lint-fix-typo + +DESTINATION = ./index.html.md + + +############################################################################### +### Documentation ### +############################################################################### + +#? check-docs-toc: Verify that important design docs have ToC entries. +check-docs-toc: + @./docs/presubmit.sh +.PHONY: check-docs-toc + +############################################################################### +### Docker image ### +############################################################################### + +# On Linux, you may need to run `DOCKER_BUILDKIT=1 make build-docker` for this +# to work. +#? build-docker: Build docker image cometbft/cometbft +build-docker: + docker build \ + --label=cometbft \ + --tag="cometbft/cometbft" \ + -f DOCKER/Dockerfile . +.PHONY: build-docker + +############################################################################### +### Local testnet using docker ### +############################################################################### + +#? build-linux: Build linux binary on other platforms +build-linux: + GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) $(MAKE) build +.PHONY: build-linux + +#? build-docker-localnode: Build the "localnode" docker image +build-docker-localnode: + @cd networks/local && make +.PHONY: build-docker-localnode + +# Runs `make build COMETBFT_BUILD_OPTIONS=cleveldb` from within an Amazon +# Linux (v2)-based Docker build container in order to build an Amazon +# Linux-compatible binary. Produces a compatible binary at ./build/cometbft +build_c-amazonlinux: + $(MAKE) -C ./DOCKER build_amazonlinux_buildimage + docker run --rm -it -v `pwd`:/cometbft cometbft/cometbft:build_c-amazonlinux +.PHONY: build_c-amazonlinux + +#? localnet-start: Run a 4-node testnet locally +localnet-start: localnet-stop build-docker-localnode + @if ! [ -f build/node0/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/cometbft:Z cometbft/localnode testnet --config /etc/cometbft/config-template.toml --o . --starting-ip-address 192.167.10.2; fi + docker compose up -d +.PHONY: localnet-start + +#? localnet-stop: Stop testnet +localnet-stop: + docker compose down +.PHONY: localnet-stop + +#? build-contract-tests-hooks: Build hooks for dredd, to skip or add information on some steps +build-contract-tests-hooks: +ifeq ($(OS),Windows_NT) + go build -mod=readonly $(BUILD_FLAGS) -o build/contract_tests.exe ./cmd/contract_tests +else + go build -mod=readonly $(BUILD_FLAGS) -o build/contract_tests ./cmd/contract_tests +endif +.PHONY: build-contract-tests-hooks + +#? contract-tests: Run a nodejs tool to test endpoints against a localnet +# The command takes care of starting and stopping the network +# prerequisits: build-contract-tests-hooks build-linux +# the two build commands were not added to let this command run from generic containers or machines. +# The binaries should be built beforehand +contract-tests: + dredd +.PHONY: contract-tests + +# Implements test splitting and running. This is pulled directly from +# the github action workflows for better local reproducibility. + +GO_TEST_FILES != find $(CURDIR) -name "*_test.go" + +# default to four splits by default +NUM_SPLIT ?= 4 + +$(BUILDDIR): + mkdir -p $@ + +# The format statement filters out all packages that don't have tests. +# Note we need to check for both in-package tests (.TestGoFiles) and +# out-of-package tests (.XTestGoFiles). +$(BUILDDIR)/packages.txt:$(GO_TEST_FILES) $(BUILDDIR) + go list -f "{{ if (or .TestGoFiles .XTestGoFiles) }}{{ .ImportPath }}{{ end }}" ./... | sort > $@ + +split-test-packages:$(BUILDDIR)/packages.txt + split -d -n l/$(NUM_SPLIT) $< $<. +test-group-%:split-test-packages + cat $(BUILDDIR)/packages.txt.$* | xargs go test -mod=readonly -timeout=15m -race -coverprofile=$(BUILDDIR)/$*.profile.out + +#? help: Get more info on make commands. +help: Makefile + @echo " Choose a command run in comebft:" + @sed -n 's/^#?//p' $< | column -t -s ':' | sort | sed -e 's/^/ /' +.PHONY: help diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..bd7cbe8 --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +NOTICE + +About Cosmos Labs + +Cosmos Labs is the development and growth organization behind the Cosmos stack of technologies and ecosystem, the world leading blockchain platform powering more than 200 production chains in finance, payments, and real-world assets. Cosmos Labs leads the development of the Cosmos technology stack, including the Cosmos SDK, CometBFT, and IBC protocols that enable sovereign, interoperable blockchains, in tandem with the Interchain Foundation. Cosmos Labs offers blockchain solutions for enterprises and finance, learn more by visiting: https://cosmos.network/, https://cosmoslabs.io/ + +Licence + +This product This product includes software developed by Cosmos Labs and is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +Attribution + +If you distribute this software or derivative works, you must include a copy of this NOTICE file (or equivalent attribution) in your distribution, as required by Section 4(d) of the Apache License, Version 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fb0b78d --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +

+ Mukan Consensus +

+ +

+ The sovereign consensus engine of the Mukan Network, forked from CometBFT. +

+ +## Overview + +**Mukan Consensus** is the Byzantine Fault Tolerant (BFT) consensus engine powering the Mukan Network. It is a permanent hard-fork of [CometBFT v0.38.21](https://github.com/cometbft/cometbft), evolved to support Mukan Network's unique **PoW/PoJ (Proof of Justice)** hybrid consensus model. + +### Key Differences from CometBFT + +- All upstream dependencies updated to reference the sovereign Mukan Network stack (`git.cw.tr/mukan-network/...`) instead of the original Cosmos GitHub paths. +- Future: Native integration with the PoJ mining protocol and Mukan-specific block validation rules. + +## Integration + +Mukan Consensus is the consensus core used by the [Mukan SDK](https://git.cw.tr/mukan-network/mukan-sdk). + +```go +require git.cw.tr/mukan-network/mukan-consensus v0.38.21-mukan.1 +``` + +## License + +Licensed under the **GNU General Public License v3.0 (GPLv3)**. + +*Original CometBFT components remain under their respective Apache 2.0 licenses where applicable.* diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 0000000..22bfbf7 --- /dev/null +++ b/RELEASES.md @@ -0,0 +1,385 @@ +# Releases + +CometBFT uses modified [semantic versioning](https://semver.org/) with each +release following a `vX.Y.Z` format. CometBFT is currently on major version 0 +and uses the minor version to signal breaking changes. The `main` branch is +used for active development and thus it is not advisable to build against it. + +The latest changes are always initially merged into `main`. Releases are +specified using tags and are built from long-lived "backport" branches that are +cut from `main` when the release process begins. Each release "line" (e.g. +0.34 or 0.33) has its own long-lived backport branch, and the backport branches +have names like `v0.34.x` or `v0.33.x` (literally, `x`; it is not a placeholder +in this case). CometBFT only maintains the last two releases at a time (the +oldest release is predominantly just security patches). + +## Backporting + +As non-breaking changes land on `main`, they should also be backported to +these backport branches. + +We use Mergify's [backport feature](https://mergify.io/features/backports) to +automatically backport to the needed branch. There should be a label for any +backport branch that you'll be targeting. To notify the bot to backport a pull +request, mark the pull request with the label corresponding to the correct +backport branch. For example, to backport to v0.38.x, add the label +`S:backport-to-v0.38.x`. Once the original pull request is merged, the bot will +try to cherry-pick the pull request to the backport branch. If the bot fails to +backport, it will open a pull request. The author of the original pull request +is responsible for solving the conflicts and merging the pull request. + +### Creating a backport branch + +If this is the first release candidate for a minor version release, e.g. +v0.25.0, you get to have the honor of creating the backport branch! + +Note that, after creating the backport branch, you'll also need to update the +tags on `main` so that `go mod` is able to order the branches correctly. You +should tag `main` with a "dev" tag that is "greater than" the backport +branches tags. Otherwise, `go mod` does not 'know' whether commits on `main` +come before or after the release. + +In the following example, we'll assume that we're making a backport branch for +the 0.38.x line. + +1. Start on `main` + +2. Ensure that there is a [branch protection + rule](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/managing-a-branch-protection-rule) for the + branch you are about to create (you will need admin access to the repository + in order to do this). + +3. Create and push the backport branch: + + ```sh + git checkout -b v0.38.x + git push origin v0.38.x + ``` + +4. Create a PR to update the documentation directory for the backport branch. + + We rewrite any URLs pointing to `main` to point to the backport branch, + so that generated documentation will link to the correct versions of files + elsewhere in the repository. The following files are to be excluded from this + search: + + * [`README.md`](./README.md) + * [`CHANGELOG.md`](./CHANGELOG.md) + * [`UPGRADING.md`](./UPGRADING.md) + + The following links are to always point to `main`, regardless of where they + occur in the codebase: + + * `https://github.com/cometbft/cometbft/blob/main/LICENSE` + + Be sure to search for all of the following links and replace `main` with your + corresponding branch label or version (e.g. `v0.38.x` or `v0.38`): + + * `github.com/cometbft/cometbft/blob/main` -> + `github.com/cometbft/cometbft/blob/v0.38.x` + * `github.com/cometbft/cometbft/tree/main` -> + `github.com/cometbft/cometbft/tree/v0.38.x` + * `docs.cometbft.com/main` -> `docs.cometbft.com/v0.38` + + Once you have updated all of the relevant documentation: + + ```sh + # Create and push the PR. + git checkout -b update-docs-v038x + git commit -m "Update docs for v0.38.x backport branch." + git push -u origin update-docs-v038x + ``` + + Be sure to merge this PR before making other changes on the newly-created + backport branch. + +5. Ensure that the RPC docs' `version` field in `rpc/openapi/openapi.yaml` has + been updated from `main` to the backport branch version. + +6. Prepare the [CometBFT documentation + repository](https://github.com/cometbft/cometbft-docs) to build the release + branch's version by updating the + [VERSIONS](https://github.com/cometbft/cometbft-docs/blob/main/VERSIONS) + file. + +After doing these steps, go back to `main` and do the following: + +1. Create a new workflow to run e2e nightlies for the new backport branch. (See + [e2e-nightly-main.yml][e2e] for an example.) + +2. Add a new section to the Mergify config (`.github/mergify.yml`) to enable the + backport bot to work on this branch, and add a corresponding `backport-to-v0.38.x` + [label](https://github.com/cometbft/cometbft/labels) so the bot can be triggered. + +3. Add a new section to the Dependabot config (`.github/dependabot.yml`) to + enable automatic update of Go dependencies on this branch. Copy and edit one + of the existing branch configurations to set the correct `target-branch`. + +[e2e]: https://github.com/cometbft/cometbft/blob/main/.github/workflows/e2e-nightly-main.yml + +## Pre-releases + +Before creating an official release, especially a minor release, we may want to +create an alpha or beta version, or release candidate (RC) for our friends and +partners to test out. We use git tags to create pre-releases, and we build them +off of backport branches, for example: + +* `v0.38.0-alpha.1` - The first alpha release of `v0.38.0`. Subsequent alpha + releases will be numbered `v0.38.0-alpha.2`, `v0.38.0-alpha.3`, etc. + + Alpha releases are to be considered the _most_ unstable of pre-releases, and + are most likely not yet properly QA'd. These are made available to allow early + adopters to start integrating and testing new functionality before we're done + with QA. + +* `v0.38.0-beta.1` - The first beta release of `v0.38.0`. Subsequent beta + releases will be numbered `v0.38.0-beta.2`, `v0.38.0-beta.3`, etc. + + Beta releases can be considered more stable than alpha releases in that we + will have QA'd them better than alpha releases, but there still may be + minor breaking API changes if users have strong demands for such changes. + +* `v0.38.0-rc1` - The first release candidate (RC) of `v0.38.0`. Subsequent RCs + will be numbered `v0.38.0-rc2`, `v0.38.0-rc3`, etc. + + RCs are considered more stable than beta releases in that we will have + completed our QA on them. APIs will most likely be stable at this point. The + difference between an RC and a release is that there may still be small + changes (bug fixes, features) that may make their way into the series before + cutting a final release. + +(Note that branches and tags _cannot_ have the same names, so it's important +that these branches have distinct names from the tags/release names.) + +If this is the first pre-release for a minor release, you'll have to make a new +backport branch (see above). Otherwise: + +1. Start from the backport branch (e.g. `v0.38.x`). +2. Run the integration tests and the E2E nightlies + (which can be triggered from the GitHub UI; + e.g., ). +3. Prepare the pre-release documentation: + * Build the changelog with [unclog] _without_ doing an unclog release, and + commit the built changelog. This ensures that all changelog entries appear + under an "Unreleased" heading in the pre-release's changelog. The changes + are only considered officially "released" once we cut a regular (final) + release. + * Ensure that `UPGRADING.md` is up-to-date and includes notes on any breaking + changes or other upgrading flows. +4. Prepare the versioning: + * Bump TMVersionDefault version in `version.go` + * Bump P2P and block protocol versions in `version.go`, if necessary. + Check the changelog for breaking changes in these components. + * Bump ABCI protocol version in `version.go`, if necessary +5. Open a PR with these changes against the backport branch. +6. Once these changes have landed on the backport branch, be sure to pull them back down locally. +7. Once you have the changes locally, create the new tag, specifying a name and a tag "message": + `git tag -a v0.38.0-rc1 -m "Release Candidate v0.38.0-rc1` +8. Push the tag back up to origin: + `git push origin v0.38.0-rc1` + Now the tag should be available on the repo's releases page. +9. Future pre-releases will continue to be built off of this branch. + +## Minor release + +This minor release process assumes that this release was preceded by release +candidates. If there were no release candidates, begin by creating a backport +branch, as described above. + +Before performing these steps, be sure the +[Minor Release Checklist](#minor-release-checklist) has been completed. + +1. Start on the backport branch (e.g. `v0.38.x`) +2. Run integration tests (`make test_integrations`) and the e2e nightlies. +3. Prepare the release: + * Do a [release][unclog-release] with [unclog] for the desired version, + ensuring that you write up a good summary of the major highlights of the + release that users would be interested in. + * Build the changelog using unclog, and commit the built changelog. + * Ensure that `UPGRADING.md` is up-to-date and includes notes on any breaking changes + or other upgrading flows. + * Bump TMVersionDefault version in `version.go` + * Bump P2P and block protocol versions in `version.go`, if necessary + * Bump ABCI protocol version in `version.go`, if necessary +4. Open a PR with these changes against the backport branch. +5. Once these changes are on the backport branch, push a tag with prepared release details. + This will trigger the actual release `v0.38.0`. + * `git tag -a v0.38.0 -m 'Release v0.38.0'` + * `git push origin v0.38.0` +6. Make sure that `main` is updated with the latest `CHANGELOG.md`, `CHANGELOG_PENDING.md`, and `UPGRADING.md`. + +## Patch release + +Patch releases are done differently from minor releases: They are built off of +long-lived backport branches, rather than from main. As non-breaking changes +land on `main`, they should also be backported into these backport branches. + +Patch releases don't have release candidates by default, although any tricky +changes may merit a release candidate. + +To create a patch release: + +1. Checkout the long-lived backport branch: `git checkout v0.38.x` +2. Run integration tests (`make test_integrations`) and the nightlies. +3. Check out a new branch and prepare the release: + * Do a [release][unclog-release] with [unclog] for the desired version, + ensuring that you write up a good summary of the major highlights of the + release that users would be interested in. + * Build the changelog using unclog, and commit the built changelog. + * Bump the TMDefaultVersion in `version.go` + * Bump the ABCI version number, if necessary. (Note that ABCI follows semver, + and that ABCI versions are the only versions which can change during patch + releases, and only field additions are valid patch changes.) +4. Open a PR with these changes that will land them back on `v0.38.x` +5. Once this change has landed on the backport branch, make sure to pull it locally, then push a tag. + * `git tag -a v0.38.1 -m 'Release v0.38.1'` + * `git push origin v0.38.1` +6. Create a pull request back to main with the CHANGELOG & version changes from the latest release. + * Remove all `R:patch` labels from the pull requests that were included in the release. + * Do not merge the backport branch into main. + +## Minor Release Checklist + +The following set of steps are performed on all releases that increment the +_minor_ version, e.g. v0.25 to v0.26. These steps ensure that CometBFT is well +tested, stable, and suitable for adoption by the various diverse projects that +rely on CometBFT. + +### Feature Freeze + +Ahead of any minor version release of CometBFT, the software enters 'Feature +Freeze' for at least two weeks. A feature freeze means that _no_ new features +are added to the code being prepared for release. No code changes should be made +to the code being released that do not directly improve pressing issues of code +quality. The following must not be merged during a feature freeze: + +* Refactors that are not related to specific bug fixes. +* Dependency upgrades. +* New test code that does not test a discovered regression. +* New features of any kind. +* Documentation or spec improvements that are not related to the newly developed + code. + +This period directly follows the creation of the [backport +branch](#creating-a-backport-branch). The CometBFT team instead directs all +attention to ensuring that the existing code is stable and reliable. Broken +tests are fixed, flakey-tests are remedied, end-to-end test failures are +thoroughly diagnosed and all efforts of the team are aimed at improving the +quality of the code. During this period, the upgrade harness tests are run +repeatedly and a variety of in-house testnets are run to ensure CometBFT +functions at the scale it will be used by application developers and node +operators. + +### Nightly End-To-End Tests + +The CometBFT team maintains [a set of end-to-end +tests](https://github.com/cometbft/cometbft/blob/main/test/e2e/README.md#L1) +that run each night on the latest commit of the project and on the code in the +tip of each supported backport branch. These tests start a network of +containerized CometBFT processes and run automated checks that the network +functions as expected in both stable and unstable conditions. During the feature +freeze, these tests are run nightly and must pass consistently for a release of +CometBFT to be considered stable. + +### Upgrade Harness + +The CometBFT team is creating an upgrade test harness to exercise the workflow +of stopping an instance of CometBFT running one version of the software and +starting up the same application running the next version. To support upgrade +testing, we will add the ability to terminate the CometBFT process at specific +pre-defined points in its execution so that we can verify upgrades work in a +representative sample of stop conditions. + +### Large Scale Testnets + +The CometBFT end-to-end tests run a small network (~10s of nodes) to exercise +basic consensus interactions. Real world deployments of CometBFT often have +over a hundred nodes just in the validator set, with many others acting as full +nodes and sentry nodes. To gain more assurance before a release, we will also +run larger-scale test networks to shake out emergent behaviors at scale. + +Large-scale test networks are run on a set of virtual machines (VMs). Each VM is +equipped with 4 Gigabytes of RAM and 2 CPU cores. The network runs a very simple +key-value store application. The application adds artificial delays to different +ABCI calls to simulate a slow application. Each testnet is briefly run with no +load being generated to collect a baseline performance. Once baseline is +captured, a consistent load is applied across the network. This load takes the +form of 10% of the running nodes all receiving a consistent stream of two +hundred transactions per minute each. + +During each test net, the following metrics are monitored and collected on each +node: + +* Consensus rounds per height +* Maximum connected peers, Minimum connected peers, Rate of change of peer connections +* Memory resident set size +* CPU utilization +* Blocks produced per minute +* Seconds for each step of consensus (Propose, Prevote, Precommit, Commit) +* Latency to receive block proposals + +For these tests we intentionally target low-powered host machines (with low core +counts and limited memory) to ensure we observe similar kinds of resource contention +and limitation that real-world deployments of CometBFT experience in production. + +#### 200 Node Testnet + +To test the stability and performance of CometBFT in a real world scenario, +a 200 node test network is run. The network comprises 5 seed nodes, 175 +validators and 20 non-validating full nodes. All nodes begin by dialing +a subset of the seed nodes to discover peers. The network is run for several +days, with metrics being collected continuously. In cases of changes to performance +critical systems, testnets of larger sizes should be considered. + +#### Rotating Node Testnet + +Real-world deployments of CometBFT frequently see new nodes arrive and old +nodes exit the network. The rotating node testnet ensures that CometBFT is +able to handle this reliably. In this test, a network with 10 validators and +3 seed nodes is started. A rolling set of 25 full nodes are started and each +connects to the network by dialing one of the seed nodes. Once the node is able +to blocksync to the head of the chain and begins producing blocks using +consensus it is stopped. Once stopped, a new node is started and +takes its place. This network is run for several days. + +#### Vote-extension Testnet + +CometBFT v0.38.0 introduced **vote-extensions**, which are added as the name suggests, to precommit votes sent by validators. +The Vote-extension Testnet is used to determine how vote-extensions affect the performance of CometBFT, under various settings. +The application used in the experiment is the same used on the (#200-node-testnet), but is configured differently to gauge de effects of varying vote extension sizes. +In the (#200-node-testnet) the application extends pre-commit votes with a 64 bit number encoded with variable compression. +In the Vote-extension Testnet, pre-commit votes are extended with a non-compressed extension of configurable size. +Experiments are run with multiple sizes to determine their impact and, for comparison sake, we include a run with the same settings as in the (#200-node-testnet). + +The testnet consists of 175 validators, 20 non-validator full-nodes, and 5 seed nodes. +All 195 full-nodes begin by dialing a subset of the seed nodes to discover peers. +Once all full-nodes are started, a 5 minute period is waited before starting an experiment. +For each experiment, the load generators issue requests at a constant rate during 150 seconds, then wait for 5 minutes to allow the system to quiesce, then repeat the load generation; the load generation step is repeated 5 times for each experiment. + +#### Network Partition Testnet + +CometBFT is expected to recover from network partitions. A partition where no +subset of the nodes is left with the super-majority of the stake is expected to +stop making blocks. Upon alleviation of the partition, the network is expected +to once again become fully connected and capable of producing blocks. The +network partition testnet ensures that CometBFT is able to handle this +reliably at scale. In this test, a network with 100 validators and 95 full +nodes is started. All validators have equal stake. Once the network is +producing blocks, a set of firewall rules is deployed to create a partitioned +network with 50% of the stake on one side and 50% on the other. Once the +network stops producing blocks, the firewall rules are removed and the nodes +are monitored to ensure they reconnect and that the network again begins +producing blocks. + +#### Absent Stake Testnet + +CometBFT networks often run with _some_ portion of the voting power offline. +The absent stake testnet ensures that large networks are able to handle this +reliably. A set of 150 validator nodes and three seed nodes is started. The set +of 150 validators is configured to only possess a cumulative stake of 67% of +the total stake. The remaining 33% of the stake is configured to belong to +a validator that is never actually run in the test network. The network is run +for multiple days, ensuring that it is able to produce blocks without issue. + +[unclog]: https://github.com/informalsystems/unclog +[unclog-release]: https://github.com/informalsystems/unclog#releasing-a-new-versions-change-set diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..bf81964 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,33 @@ +# How to Report a Security Bug + +If you believe you have found a security vulnerability in the Interchain Stack, +you can report it to our primary vulnerability disclosure channel, the [Cosmos +HackerOne Bug Bounty program][h1]. + +If you prefer to report an issue via email, you may send a bug report to + with the issue details, reproduction, impact, and other +information. Please submit only one unique email thread per vulnerability. Any +issues reported via email are ineligible for bounty rewards. + +Artifacts from an email report are saved at the time the email is triaged. +Please note: our team is not able to monitor dynamic content (e.g. a Google Docs +link that is edited after receipt) throughout the lifecycle of a report. If you +would like to share additional information or modify previous information, +please include it in an additional reply as an additional attachment. + +Please **DO NOT** file a public issue in this repository to report a security +vulnerability. + +## Coordinated Vulnerability Disclosure Policy and Safe Harbor + +For the most up-to-date version of the policies that govern vulnerability +disclosure, please consult the [HackerOne program page][h1-policy]. + +The policy hosted on HackerOne is the official Coordinated Vulnerability +Disclosure policy and Safe Harbor for the Interchain Stack, and the teams and +infrastructure it supports, and it supersedes previous security policies that +have been used in the past by individual teams and projects with targets in +scope of the program. + +[h1]: https://hackerone.com/cosmos?type=team +[h1-policy]: https://hackerone.com/cosmos?type=team&view_policy=true diff --git a/STYLE_GUIDE.md b/STYLE_GUIDE.md new file mode 100644 index 0000000..35de523 --- /dev/null +++ b/STYLE_GUIDE.md @@ -0,0 +1,162 @@ +# Go Coding Style Guide + +In order to keep our code looking good with lots of programmers working on it, it helps to have a "style guide", so all +the code generally looks quite similar. This doesn't mean there is only one "right way" to write code, or even that this +standard is better than your style. But if we agree to a number of stylistic practices, it makes it much easier to read +and modify new code. Please feel free to make suggestions if there's something you would like to add or modify. + +We expect all contributors to be familiar with [Effective Go](https://golang.org/doc/effective_go.html) +(and it's recommended reading for all Go programmers anyways). Additionally, we generally agree with the suggestions + in [Uber's style guide](https://github.com/uber-go/guide/blob/master/style.md) and use that as a starting point. + + +## Code Structure + +Perhaps more key for code readability than good commenting is having the right structure. As a rule of thumb, try to write +in a logical order of importance, taking a little time to think how to order and divide the code such that someone could +scroll down and understand the functionality of it just as well as you do. A loose example of such order would be: + +* Constants, global and package-level variables +* Main Struct +* Options (only if they are seen as critical to the struct else they should be placed in another file) +* Initialization / Start and stop of the service +* Msgs/Events +* Public Functions (In order of most important) +* Private/helper functions +* Auxiliary structs and function (can also be above private functions or in a separate file) + +## General + +* Use `gofmt` (or `goimport`) to format all code upon saving it. (If you use VIM, check out vim-go). +* Use a linter (see below) and generally try to keep the linter happy (where it makes sense). +* Think about documentation, and try to leave godoc comments, when it will help new developers. +* Every package should have a high level doc.go file to describe the purpose of that package, its main functions, and any other relevant information. +* `TODO` should not be used. If important enough should be recorded as an issue. +* `BUG` / `FIXME` should be used sparingly to guide future developers on some of the vulnerabilities of the code. +* `XXX` can be used in work-in-progress (prefixed with "WIP:" on github) branches but they must be removed before approving a PR. +* Applications (e.g. clis/servers) *should* panic on unexpected unrecoverable errors and print a stack trace. + +## Comments + +* Use a space after comment deliminter (ex. `// your comment`). +* Many comments are not sentences. These should begin with a lower case letter and end without a period. +* Conversely, sentences in comments should be sentenced-cased and end with a period. + +## Linters + +These must be applied to all (Go) repos. + +* [shellcheck](https://github.com/koalaman/shellcheck) +* [golangci-lint](https://github.com/golangci/golangci-lint) (covers all important linters) + * See the `.golangci.yml` file in each repo for linter configuration. + +## Various + +* Reserve "Save" and "Load" for long-running persistence operations. When parsing bytes, use "Encode" or "Decode". +* Maintain consistency across the codebase. +* Functions that return functions should have the suffix `Fn` +* Names should not [stutter](https://blog.golang.org/package-names). For example, a struct generally shouldn’t have + a field named after itself; e.g., this shouldn't occur: + +``` golang +type middleware struct { + middleware Middleware +} +``` + +* In comments, use "iff" to mean, "if and only if". +* Product names are capitalized, like "CometBFT", "Basecoin", "Protobuf", etc except in command lines: `cometbft --help` +* Acronyms are all capitalized, like "RPC", "gRPC", "API". "MyID", rather than "MyId". +* Prefer errors.New() instead of fmt.Errorf() unless you're actually using the format feature with arguments. + +## Importing Libraries + +Sometimes it's necessary to rename libraries to avoid naming collisions or ambiguity. + +* Use [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) +* Separate imports into blocks - one for the standard lib, one for external libs and one for application libs. +* Here are some common library labels for consistency: + * dbm "github.com/cometbft/cometbft-db" + * cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" + * cmtcfg "github.com/cometbft/cometbft/config" + * cmttypes "github.com/cometbft/cometbft/types" +* Never use anonymous imports (the `.`), for example, `cmtlibs/common` or anything else. +* When importing a pkg from the `cmt/libs` directory, prefix the pkg alias with cmt. + * cmtbits "github.com/cometbft/cometbft/libs/bits" +* tip: Use the `_` library import to import a library for initialization effects (side effects) + +## Dependencies + +* Dependencies should be pinned by a release tag, or specific commit, to avoid breaking `go get` when external dependencies are updated. +* Refer to the [contributing](CONTRIBUTING.md) document for more details + +## Testing + +* The first rule of testing is: we add tests to our code +* The second rule of testing is: we add tests to our code +* For Golang testing: + * Make use of table driven testing where possible and not-cumbersome + * [Inspiration](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) + * Make use of [assert](https://godoc.org/github.com/stretchr/testify/assert) and [require](https://godoc.org/github.com/stretchr/testify/require) +* When using mocks, it is recommended to use Testify [mock]( + ) along with [Mockery](https://github.com/vektra/mockery) for autogeneration + +## Errors + +* Ensure that errors are concise, clear and traceable. +* Use stdlib errors package. +* For wrapping errors, use `fmt.Errorf()` with `%w`. +* Panic is appropriate when an internal invariant of a system is broken, while all other cases (in particular, + incorrect or invalid usage) should return errors. + +## Config + +* Currently the TOML filetype is being used for config files +* A good practice is to store per-user config files under `~/.[yourAppName]/config.toml` + +## CLI + +* When implementing a CLI use [Cobra](https://github.com/spf13/cobra) and [Viper](https://github.com/spf13/viper). +* Helper messages for commands and flags must be all lowercase. +* Instead of using pointer flags (eg. `FlagSet().StringVar`) use Viper to retrieve flag values (eg. `viper.GetString`) + * The flag key used when setting and getting the flag should always be stored in a + variable taking the form `FlagXxx` or `flagXxx`. + * Flag short variable descriptions should always start with a lower case character as to remain consistent with + the description provided in the default `--help` flag. + +## Version + +* Every repo should have a version/version.go file that mimics the CometBFT repo +* We read the value of the constant version in our build scripts and hence it has to be a string + +## Non-Go Code + +* All non-Go code (`*.proto`, `Makefile`, `*.sh`), where there is no common + agreement on style, should be formatted according to + [EditorConfig](http://editorconfig.org/) config: + + ```toml + # top-most EditorConfig file + root = true + + # Unix-style newlines with a newline ending every file + [*] + charset = utf-8 + end_of_line = lf + insert_final_newline = true + trim_trailing_whitespace = true + + [Makefile] + indent_style = tab + + [*.sh] + indent_style = tab + + [*.proto] + indent_style = space + indent_size = 2 + ``` + + Make sure the file above (`.editorconfig`) are in the root directory of your + repo and you have a [plugin for your + editor](http://editorconfig.org/#download) installed. diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..f943fec --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,156 @@ +# Upgrading CometBFT + +This guide provides instructions for upgrading to specific versions of CometBFT. + +## v0.38.13 + +It is recommended that CometBFT be built with Go v1.22+ since v1.21 is no longer +supported. + +## v0.38.0 + +This release introduces state machine-breaking changes, as well as substantial changes +on the ABCI interface and indexing. It therefore requires a +coordinated upgrade. + +### Config Changes + +* The field `Version` in the mempool section has been removed. The priority + mempool (what was called version `v1`) has been removed (see below), thus + there is only one implementation of the mempool available (what was called + `v0`). +* Config fields `TTLDuration` and `TTLNumBlocks`, which were only used by the + priority mempool, have been removed. + +### Mempool Changes + +* The priority mempool (what was referred in the code as version `v1`) has been + removed. There is now only one mempool (what was called version `v0`), that + is, the default implementation as a queue of transactions. +* In the protobuf message `ResponseCheckTx`, fields `sender`, `priority`, and + `mempool_error`, which were only used by the priority mempool, were removed + but still kept in the message as "reserved". + +### ABCI Changes + +* The `ABCIVersion` is now `2.0.0`. +* Added new ABCI methods `ExtendVote`, and `VerifyVoteExtension`. + Applications upgrading to v0.38.0 must implement these methods as described + [here](./spec/abci/abci%2B%2B_comet_expected_behavior.md#adapting-existing-applications-that-use-abci) +* Removed methods `BeginBlock`, `DeliverTx`, `EndBlock`, and replaced them by + method `FinalizeBlock`. Applications upgrading to `v0.38.0` must refactor + the logic handling the methods removed to handle `FinalizeBlock`. +* The Application's hash (or any data representing the Application's current state) + is known by the time `FinalizeBlock` finishes its execution. + Accordingly, the `app_hash` parameter has been moved from `ResponseCommit` + to `ResponseFinalizeBlock`. +* Field `signed_last_block` in structure `VoteInfo` has been replaced by the + more expressive `block_id_flag`. Applications willing to keep the semantics + of `signed_last_block` can now use the following predicate + * `voteInfo.block_id_flag != BlockIDFlagAbsent` +* For further details, please see the updated [specification](spec/abci/README.md) + +## v0.37.0 + +This release introduces state machine-breaking changes, and therefore requires a +coordinated upgrade. + +### Go API + +When upgrading from the v0.34 release series, please note that the Go module has +now changed to `github.com/cometbft/cometbft`. + +### ABCI Changes + +* The `ABCIVersion` is now `1.0.0`. +* Added new ABCI methods `PrepareProposal` and `ProcessProposal`. For details, + please see the [spec](spec/abci/README.md). Applications upgrading to + v0.37.0 must implement these methods, at the very minimum, as described + [here](./spec/abci/abci++_app_requirements.md) +* Deduplicated `ConsensusParams` and `BlockParams`. + In the v0.34 branch they are defined both in `abci/types.proto` and `types/params.proto`. + The definitions in `abci/types.proto` have been removed. + In-process applications should make sure they are not using the deleted + version of those structures. +* In v0.34, messages on the wire used to be length-delimited with `int64` varint + values, which was inconsistent with the `uint64` varint length delimiters used + in the P2P layer. Both now consistently use `uint64` varint length delimiters. +* Added `AbciVersion` to `RequestInfo`. + Applications should check that CometBFT's ABCI version matches the one they expect + in order to ensure compatibility. +* The `SetOption` method has been removed from the ABCI `Client` interface. + The corresponding Protobuf types have been deprecated. +* The `key` and `value` fields in the `EventAttribute` type have been changed + from type `bytes` to `string`. As per the [Protocol Buffers updating + guidelines](https://developers.google.com/protocol-buffers/docs/proto3#updating), + this should have no effect on the wire-level encoding for UTF8-encoded + strings. + +### RPC + +If you rely on the `/tx_search` or `/block_search` endpoints for event querying, +please note that the default behaviour of these endpoints has changed in a way +that might break your queries. The original behaviour was poorly specified, +which did not respect event boundaries. + +Please see +[tendermint/tendermint\#9712](https://github.com/tendermint/tendermint/issues/9712) +for context on the bug that was addressed that resulted in this behaviour +change. + +## v0.34.27 + +This is the first official release of CometBFT, forked originally from +[Tendermint Core v0.34.24][v03424] and subsequently updated in Informal Systems' +public fork of Tendermint Core for [v0.34.25][v03425] and [v0.34.26][v03426]. + +### Upgrading from Tendermint Core + +If you already make use of Tendermint Core (either the original Tendermint Core +v0.34.24, or Informal Systems' public fork), you can upgrade to CometBFT +v0.34.27 by replacing your dependency in your `go.mod` file: + +```bash +go mod edit -replace github.com/tendermint/tendermint=github.com/cometbft/cometbft@v0.34.27 +``` + +We make use of the original module URL in order to minimize the impact of +switching to CometBFT. This is only possible in our v0.34 release series, and we +will be switching our module URL to `github.com/cometbft/cometbft` in the next +major release. + +### Home directory + +CometBFT, by default, will consider its home directory in `~/.cometbft` from now +on instead of `~/.tendermint`. + +### Environment variables + +The environment variable prefixes have now changed from `TM` to `CMT`. For +example, `TMHOME` becomes `CMTHOME`. + +We have implemented a fallback check in case `TMHOME` is still set and `CMTHOME` +is not, but you will start to see a warning message in the logs if the old +`TMHOME` variable is set. This fallback check will be removed entirely in a +subsequent major release of CometBFT. + +### Building CometBFT + +CometBFT must be compiled using Go 1.19 or higher. The use of Go 1.18 is not +supported, since this version has reached end-of-life with the release of [Go 1.20][go120]. + +### Troubleshooting + +If you run into any trouble with this upgrade, please [contact us][discussions]. + +--- + +For historical upgrading instructions for Tendermint Core v0.34.24 and earlier, +please see the [Tendermint Core upgrading instructions][tmupgrade]. + +[v03424]: https://github.com/tendermint/tendermint/releases/tag/v0.34.24 +[v03425]: https://github.com/informalsystems/tendermint/releases/tag/v0.34.25 +[v03426]: https://github.com/informalsystems/tendermint/releases/tag/v0.34.26 +[discussions]: https://github.com/cometbft/cometbft/discussions +[tmupgrade]: https://github.com/tendermint/tendermint/blob/35581cf54ec436b8c37fabb43fdaa3f48339a170/UPGRADING.md +[go120]: https://go.dev/blog/go1.20 diff --git a/abci/README.md b/abci/README.md new file mode 100644 index 0000000..c9572c1 --- /dev/null +++ b/abci/README.md @@ -0,0 +1,35 @@ +# Application BlockChain Interface (ABCI) + +Blockchains are systems for multi-master state machine replication. +**ABCI** is an interface that defines the boundary between the replication engine (the blockchain), +and the state machine (the application). +Using a socket protocol, a consensus engine running in one process +can manage an application state running in another. + +Previously, the ABCI was referred to as TMSP. + + + +## Installation & Usage + +To get up and running quickly, see the [getting started guide](../docs/app-dev/getting-started.md) along with the [abci-cli documentation](../docs/app-dev/abci-cli.md) which will go through the examples found in the [examples](./example/) directory. + +## Specification + +A detailed description of the ABCI methods and message types is contained in: + +- [The main spec](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/README.md) +- [A protobuf file](../proto/tendermint/types/types.proto) +- [A Go interface](./types/application.go) + +## Protocol Buffers + +To compile the protobuf file, run (from the root of the repo): + +```sh +make protoc_abci +``` + +See `protoc --help` and [the Protocol Buffers site](https://developers.google.com/protocol-buffers) +for details on compiling for other languages. Note we also include a [GRPC](https://www.grpc.io/docs) +service definition. diff --git a/abci/client/client.go b/abci/client/client.go new file mode 100644 index 0000000..6e46391 --- /dev/null +++ b/abci/client/client.go @@ -0,0 +1,133 @@ +package abcicli + +import ( + "context" + "fmt" + "sync" + + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +const ( + dialRetryIntervalSeconds = 3 + echoRetryIntervalSeconds = 1 +) + +//go:generate ../../scripts/mockery_generate.sh Client + +// Client defines the interface for an ABCI client. +// +// NOTE these are client errors, eg. ABCI socket connectivity issues. +// Application-related errors are reflected in response via ABCI error codes +// and (potentially) error response. +type Client interface { + service.Service + types.Application + + // TODO: remove as each method now returns an error + Error() error + // TODO: remove as this is not implemented + Flush(context.Context) error + Echo(context.Context, string) (*types.ResponseEcho, error) + + // FIXME: All other operations are run synchronously and rely + // on the caller to dictate concurrency (i.e. run a go routine), + // with the exception of `CheckTxAsync` which we maintain + // for the v0 mempool. We should explore refactoring the + // mempool to remove this vestige behavior. + SetResponseCallback(Callback) + CheckTxAsync(context.Context, *types.RequestCheckTx) (*ReqRes, error) +} + +//---------------------------------------- + +// NewClient returns a new ABCI client of the specified transport type. +// It returns an error if the transport is not "socket" or "grpc" +func NewClient(addr, transport string, mustConnect bool) (client Client, err error) { + switch transport { + case "socket": + client = NewSocketClient(addr, mustConnect) + case "grpc": + client = NewGRPCClient(addr, mustConnect) + default: + err = fmt.Errorf("unknown abci transport %s", transport) + } + return +} + +type Callback func(*types.Request, *types.Response) + +type ReqRes struct { + *types.Request + *sync.WaitGroup + *types.Response // Not set atomically, so be sure to use WaitGroup. + + mtx cmtsync.Mutex + + // callbackInvoked as a variable to track if the callback was already + // invoked during the regular execution of the request. This variable + // allows clients to set the callback simultaneously without potentially + // invoking the callback twice by accident, once when 'SetCallback' is + // called and once during the normal request. + callbackInvoked bool + cb func(*types.Response) // A single callback that may be set. +} + +func NewReqRes(req *types.Request) *ReqRes { + return &ReqRes{ + Request: req, + WaitGroup: waitGroup1(), + Response: nil, + + callbackInvoked: false, + cb: nil, + } +} + +// Sets sets the callback. If reqRes is already done, it will call the cb +// immediately. Note, reqRes.cb should not change if reqRes.done and only one +// callback is supported. +func (r *ReqRes) SetCallback(cb func(res *types.Response)) { + r.mtx.Lock() + + if r.callbackInvoked { + r.mtx.Unlock() + cb(r.Response) + return + } + + r.cb = cb + r.mtx.Unlock() +} + +// InvokeCallback invokes a thread-safe execution of the configured callback +// if non-nil. +func (r *ReqRes) InvokeCallback() { + r.mtx.Lock() + defer r.mtx.Unlock() + + if r.cb != nil { + r.cb(r.Response) + } + r.callbackInvoked = true +} + +// GetCallback returns the configured callback of the ReqRes object which may be +// nil. Note, it is not safe to concurrently call this in cases where it is +// marked done and SetCallback is called before calling GetCallback as that +// will invoke the callback twice and create a potential race condition. +// +// ref: https://github.com/tendermint/tendermint/issues/5439 +func (r *ReqRes) GetCallback() func(*types.Response) { + r.mtx.Lock() + defer r.mtx.Unlock() + return r.cb +} + +func waitGroup1() (wg *sync.WaitGroup) { + wg = &sync.WaitGroup{} + wg.Add(1) + return +} diff --git a/abci/client/grpc_client.go b/abci/client/grpc_client.go new file mode 100644 index 0000000..bb7a6a2 --- /dev/null +++ b/abci/client/grpc_client.go @@ -0,0 +1,247 @@ +package abcicli + +import ( + "context" + "fmt" + "net" + "sync" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/libs/service" +) + +var _ Client = (*grpcClient)(nil) + +// A stripped copy of the remoteClient that makes +// synchronous calls using grpc +type grpcClient struct { + service.BaseService + mustConnect bool + + client types.ABCIClient + conn *grpc.ClientConn + chReqRes chan *ReqRes // dispatches "async" responses to callbacks *in order*, needed by mempool + + mtx sync.Mutex + addr string + err error + resCb func(*types.Request, *types.Response) // listens to all callbacks +} + +func NewGRPCClient(addr string, mustConnect bool) Client { + cli := &grpcClient{ + addr: addr, + mustConnect: mustConnect, + // Buffering the channel is needed to make calls appear asynchronous, + // which is required when the caller makes multiple async calls before + // processing callbacks (e.g. due to holding locks). 64 means that a + // caller can make up to 64 async calls before a callback must be + // processed (otherwise it deadlocks). It also means that we can make 64 + // gRPC calls while processing a slow callback at the channel head. + chReqRes: make(chan *ReqRes, 64), + } + cli.BaseService = *service.NewBaseService(nil, "grpcClient", cli) + return cli +} + +func dialerFunc(_ context.Context, addr string) (net.Conn, error) { + return cmtnet.Connect(addr) +} + +func (cli *grpcClient) OnStart() error { + if err := cli.BaseService.OnStart(); err != nil { + return err + } + + // This processes asynchronous request/response messages and dispatches + // them to callbacks. + go func() { + // Use a separate function to use defer for mutex unlocks (this handles panics) + callCb := func(reqres *ReqRes) { + cli.mtx.Lock() + defer cli.mtx.Unlock() + + reqres.Done() + + // Notify client listener if set + if cli.resCb != nil { + cli.resCb(reqres.Request, reqres.Response) + } + + // Notify reqRes listener if set + reqres.InvokeCallback() + } + for reqres := range cli.chReqRes { + if reqres != nil { + callCb(reqres) + } else { + cli.Logger.Error("Received nil reqres") + } + } + }() + +RETRY_LOOP: + for { + conn, err := grpc.NewClient(cli.addr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(dialerFunc), + ) + if err != nil { + if cli.mustConnect { + return err + } + cli.Logger.Error(fmt.Sprintf("abci.grpcClient failed to connect to %v. Retrying...\n", cli.addr), "err", err) + time.Sleep(time.Second * dialRetryIntervalSeconds) + continue RETRY_LOOP + } + + cli.Logger.Info("Dialed server. Waiting for echo.", "addr", cli.addr) + client := types.NewABCIClient(conn) + cli.conn = conn + + ENSURE_CONNECTED: + for { + _, err := client.Echo(context.Background(), &types.RequestEcho{Message: "hello"}, grpc.WaitForReady(true)) + if err == nil { + break ENSURE_CONNECTED + } + cli.Logger.Error("Echo failed", "err", err) + time.Sleep(time.Second * echoRetryIntervalSeconds) + } + + cli.client = client + return nil + } +} + +func (cli *grpcClient) OnStop() { + cli.BaseService.OnStop() + + if cli.conn != nil { + cli.conn.Close() + } + close(cli.chReqRes) +} + +func (cli *grpcClient) StopForError(err error) { + if !cli.IsRunning() { + return + } + + cli.mtx.Lock() + if cli.err == nil { + cli.err = err + } + cli.mtx.Unlock() + + cli.Logger.Error(fmt.Sprintf("Stopping abci.grpcClient for error: %v", err.Error())) + if err := cli.Stop(); err != nil { + cli.Logger.Error("Error stopping abci.grpcClient", "err", err) + } +} + +func (cli *grpcClient) Error() error { + cli.mtx.Lock() + defer cli.mtx.Unlock() + return cli.err +} + +// Set listener for all responses +// NOTE: callback may get internally generated flush responses. +func (cli *grpcClient) SetResponseCallback(resCb Callback) { + cli.mtx.Lock() + cli.resCb = resCb + cli.mtx.Unlock() +} + +//---------------------------------------- + +func (cli *grpcClient) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*ReqRes, error) { + res, err := cli.client.CheckTx(ctx, req, grpc.WaitForReady(true)) + if err != nil { + cli.StopForError(err) + return nil, err + } + return cli.finishAsyncCall(types.ToRequestCheckTx(req), &types.Response{Value: &types.Response_CheckTx{CheckTx: res}}), nil +} + +// finishAsyncCall creates a ReqRes for an async call, and immediately populates it +// with the response. We don't complete it until it's been ordered via the channel. +func (cli *grpcClient) finishAsyncCall(req *types.Request, res *types.Response) *ReqRes { + reqres := NewReqRes(req) + reqres.Response = res + cli.chReqRes <- reqres // use channel for async responses, since they must be ordered + return reqres +} + +//---------------------------------------- + +func (cli *grpcClient) Flush(ctx context.Context) error { + _, err := cli.client.Flush(ctx, types.ToRequestFlush().GetFlush(), grpc.WaitForReady(true)) + return err +} + +func (cli *grpcClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) { + return cli.client.Echo(ctx, types.ToRequestEcho(msg).GetEcho(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) { + return cli.client.Info(ctx, req, grpc.WaitForReady(true)) +} + +func (cli *grpcClient) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + return cli.client.CheckTx(ctx, req, grpc.WaitForReady(true)) +} + +func (cli *grpcClient) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) { + return cli.client.Query(ctx, types.ToRequestQuery(req).GetQuery(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) Commit(ctx context.Context, _ *types.RequestCommit) (*types.ResponseCommit, error) { + return cli.client.Commit(ctx, types.ToRequestCommit().GetCommit(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) { + return cli.client.InitChain(ctx, types.ToRequestInitChain(req).GetInitChain(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + return cli.client.ListSnapshots(ctx, types.ToRequestListSnapshots(req).GetListSnapshots(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + return cli.client.OfferSnapshot(ctx, types.ToRequestOfferSnapshot(req).GetOfferSnapshot(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) LoadSnapshotChunk(ctx context.Context, req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + return cli.client.LoadSnapshotChunk(ctx, types.ToRequestLoadSnapshotChunk(req).GetLoadSnapshotChunk(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) ApplySnapshotChunk(ctx context.Context, req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + return cli.client.ApplySnapshotChunk(ctx, types.ToRequestApplySnapshotChunk(req).GetApplySnapshotChunk(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) PrepareProposal(ctx context.Context, req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + return cli.client.PrepareProposal(ctx, types.ToRequestPrepareProposal(req).GetPrepareProposal(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + return cli.client.ProcessProposal(ctx, types.ToRequestProcessProposal(req).GetProcessProposal(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + return cli.client.ExtendVote(ctx, types.ToRequestExtendVote(req).GetExtendVote(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + return cli.client.VerifyVoteExtension(ctx, types.ToRequestVerifyVoteExtension(req).GetVerifyVoteExtension(), grpc.WaitForReady(true)) +} + +func (cli *grpcClient) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + return cli.client.FinalizeBlock(ctx, types.ToRequestFinalizeBlock(req).GetFinalizeBlock(), grpc.WaitForReady(true)) +} diff --git a/abci/client/grpc_client_test.go b/abci/client/grpc_client_test.go new file mode 100644 index 0000000..68a97dd --- /dev/null +++ b/abci/client/grpc_client_test.go @@ -0,0 +1,80 @@ +package abcicli_test + +import ( + "fmt" + "math/rand" + "net" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "google.golang.org/grpc" + + "golang.org/x/net/context" + + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + + abciserver "github.com/cometbft/cometbft/abci/server" + "github.com/cometbft/cometbft/abci/types" +) + +func TestGRPC(t *testing.T) { + app := types.NewBaseApplication() + numCheckTxs := 2000 + socketFile := fmt.Sprintf("/tmp/test-%08x.sock", rand.Int31n(1<<30)) + defer os.Remove(socketFile) + socket := fmt.Sprintf("unix://%v", socketFile) + + // Start the listener + server := abciserver.NewGRPCServer(socket, app) + server.SetLogger(log.TestingLogger().With("module", "abci-server")) + err := server.Start() + require.NoError(t, err) + + t.Cleanup(func() { + if err := server.Stop(); err != nil { + t.Error(err) + } + }) + + // Connect to the socket + //nolint:staticcheck // SA1019 Existing use of deprecated but supported dial option. + conn, err := grpc.Dial(socket, grpc.WithInsecure(), grpc.WithContextDialer(dialerFunc)) + require.NoError(t, err) + + t.Cleanup(func() { + if err := conn.Close(); err != nil { + t.Error(err) + } + }) + + client := types.NewABCIClient(conn) + + // Write requests + for counter := 0; counter < numCheckTxs; counter++ { + // Send request + response, err := client.CheckTx(context.Background(), &types.RequestCheckTx{Tx: []byte("test")}) + require.NoError(t, err) + counter++ + if response.Code != 0 { + t.Error("CheckTx failed with ret_code", response.Code) + } + if counter > numCheckTxs { + t.Fatal("Too many CheckTx responses") + } + t.Log("response", counter) + if counter == numCheckTxs { + go func() { + time.Sleep(time.Second * 1) // Wait for a bit to allow counter overflow + }() + } + + } +} + +func dialerFunc(_ context.Context, addr string) (net.Conn, error) { + return cmtnet.Connect(addr) +} diff --git a/abci/client/local_client.go b/abci/client/local_client.go new file mode 100644 index 0000000..25cb36c --- /dev/null +++ b/abci/client/local_client.go @@ -0,0 +1,186 @@ +package abcicli + +import ( + "context" + + types "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// NOTE: use defer to unlock mutex because Application might panic (e.g., in +// case of malicious tx or query). It only makes sense for publicly exposed +// methods like CheckTx (/broadcast_tx_* RPC endpoint) or Query (/abci_query +// RPC endpoint), but defers are used everywhere for the sake of consistency. +type localClient struct { + service.BaseService + + mtx *cmtsync.Mutex + types.Application + Callback +} + +var _ Client = (*localClient)(nil) + +// NewLocalClient creates a local client, which wraps the application interface that +// Tendermint as the client will call to the application as the server. The only +// difference, is that the local client has a global mutex which enforces serialization +// of all the ABCI calls from Tendermint to the Application. +func NewLocalClient(mtx *cmtsync.Mutex, app types.Application) Client { + if mtx == nil { + mtx = new(cmtsync.Mutex) + } + cli := &localClient{ + mtx: mtx, + Application: app, + } + cli.BaseService = *service.NewBaseService(nil, "localClient", cli) + return cli +} + +func (app *localClient) SetResponseCallback(cb Callback) { + app.mtx.Lock() + app.Callback = cb + app.mtx.Unlock() +} + +func (app *localClient) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*ReqRes, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + res, err := app.Application.CheckTx(ctx, req) + if err != nil { + return nil, err + } + return app.callback( + types.ToRequestCheckTx(req), + types.ToResponseCheckTx(res), + ), nil +} + +func (app *localClient) callback(req *types.Request, res *types.Response) *ReqRes { + app.Callback(req, res) + rr := newLocalReqRes(req, res) + rr.callbackInvoked = true + return rr +} + +func newLocalReqRes(req *types.Request, res *types.Response) *ReqRes { + reqRes := NewReqRes(req) + reqRes.Response = res + return reqRes +} + +//------------------------------------------------------- + +func (app *localClient) Error() error { + return nil +} + +func (app *localClient) Flush(context.Context) error { + return nil +} + +func (app *localClient) Echo(_ context.Context, msg string) (*types.ResponseEcho, error) { + return &types.ResponseEcho{Message: msg}, nil +} + +func (app *localClient) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.Info(ctx, req) +} + +func (app *localClient) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.CheckTx(ctx, req) +} + +func (app *localClient) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.Query(ctx, req) +} + +func (app *localClient) Commit(ctx context.Context, req *types.RequestCommit) (*types.ResponseCommit, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.Commit(ctx, req) +} + +func (app *localClient) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.InitChain(ctx, req) +} + +func (app *localClient) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.ListSnapshots(ctx, req) +} + +func (app *localClient) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.OfferSnapshot(ctx, req) +} + +func (app *localClient) LoadSnapshotChunk(ctx context.Context, + req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.LoadSnapshotChunk(ctx, req) +} + +func (app *localClient) ApplySnapshotChunk(ctx context.Context, + req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.ApplySnapshotChunk(ctx, req) +} + +func (app *localClient) PrepareProposal(ctx context.Context, req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.PrepareProposal(ctx, req) +} + +func (app *localClient) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.ProcessProposal(ctx, req) +} + +func (app *localClient) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.ExtendVote(ctx, req) +} + +func (app *localClient) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.VerifyVoteExtension(ctx, req) +} + +func (app *localClient) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + app.mtx.Lock() + defer app.mtx.Unlock() + + return app.Application.FinalizeBlock(ctx, req) +} diff --git a/abci/client/mocks/client.go b/abci/client/mocks/client.go new file mode 100644 index 0000000..82c6a67 --- /dev/null +++ b/abci/client/mocks/client.go @@ -0,0 +1,711 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + abcicli "github.com/cometbft/cometbft/abci/client" + + log "github.com/cometbft/cometbft/libs/log" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/abci/types" +) + +// Client is an autogenerated mock type for the Client type +type Client struct { + mock.Mock +} + +// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *Client) ApplySnapshotChunk(_a0 context.Context, _a1 *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ApplySnapshotChunk") + } + + var r0 *types.ResponseApplySnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) *types.ResponseApplySnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseApplySnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestApplySnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckTx provides a mock function with given fields: _a0, _a1 +func (_m *Client) CheckTx(_a0 context.Context, _a1 *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for CheckTx") + } + + var r0 *types.ResponseCheckTx + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) *types.ResponseCheckTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCheckTx) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCheckTx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckTxAsync provides a mock function with given fields: _a0, _a1 +func (_m *Client) CheckTxAsync(_a0 context.Context, _a1 *types.RequestCheckTx) (*abcicli.ReqRes, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for CheckTxAsync") + } + + var r0 *abcicli.ReqRes + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) (*abcicli.ReqRes, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) *abcicli.ReqRes); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*abcicli.ReqRes) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCheckTx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Commit provides a mock function with given fields: _a0, _a1 +func (_m *Client) Commit(_a0 context.Context, _a1 *types.RequestCommit) (*types.ResponseCommit, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Commit") + } + + var r0 *types.ResponseCommit + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCommit) (*types.ResponseCommit, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCommit) *types.ResponseCommit); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCommit) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCommit) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Echo provides a mock function with given fields: _a0, _a1 +func (_m *Client) Echo(_a0 context.Context, _a1 string) (*types.ResponseEcho, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Echo") + } + + var r0 *types.ResponseEcho + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string) (*types.ResponseEcho, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, string) *types.ResponseEcho); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseEcho) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Error provides a mock function with no fields +func (_m *Client) Error() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Error") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ExtendVote provides a mock function with given fields: _a0, _a1 +func (_m *Client) ExtendVote(_a0 context.Context, _a1 *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ExtendVote") + } + + var r0 *types.ResponseExtendVote + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) (*types.ResponseExtendVote, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) *types.ResponseExtendVote); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseExtendVote) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestExtendVote) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FinalizeBlock provides a mock function with given fields: _a0, _a1 +func (_m *Client) FinalizeBlock(_a0 context.Context, _a1 *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for FinalizeBlock") + } + + var r0 *types.ResponseFinalizeBlock + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) *types.ResponseFinalizeBlock); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseFinalizeBlock) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestFinalizeBlock) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Flush provides a mock function with given fields: _a0 +func (_m *Client) Flush(_a0 context.Context) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Flush") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Info provides a mock function with given fields: _a0, _a1 +func (_m *Client) Info(_a0 context.Context, _a1 *types.RequestInfo) (*types.ResponseInfo, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Info") + } + + var r0 *types.ResponseInfo + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) (*types.ResponseInfo, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) *types.ResponseInfo); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInfo) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInfo) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// InitChain provides a mock function with given fields: _a0, _a1 +func (_m *Client) InitChain(_a0 context.Context, _a1 *types.RequestInitChain) (*types.ResponseInitChain, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for InitChain") + } + + var r0 *types.ResponseInitChain + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) (*types.ResponseInitChain, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) *types.ResponseInitChain); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInitChain) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInitChain) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// IsRunning provides a mock function with no fields +func (_m *Client) IsRunning() bool { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for IsRunning") + } + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// ListSnapshots provides a mock function with given fields: _a0, _a1 +func (_m *Client) ListSnapshots(_a0 context.Context, _a1 *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ListSnapshots") + } + + var r0 *types.ResponseListSnapshots + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) (*types.ResponseListSnapshots, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) *types.ResponseListSnapshots); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseListSnapshots) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestListSnapshots) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *Client) LoadSnapshotChunk(_a0 context.Context, _a1 *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for LoadSnapshotChunk") + } + + var r0 *types.ResponseLoadSnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) *types.ResponseLoadSnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseLoadSnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestLoadSnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OfferSnapshot provides a mock function with given fields: _a0, _a1 +func (_m *Client) OfferSnapshot(_a0 context.Context, _a1 *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for OfferSnapshot") + } + + var r0 *types.ResponseOfferSnapshot + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) *types.ResponseOfferSnapshot); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseOfferSnapshot) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestOfferSnapshot) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OnReset provides a mock function with no fields +func (_m *Client) OnReset() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for OnReset") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStart provides a mock function with no fields +func (_m *Client) OnStart() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for OnStart") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStop provides a mock function with no fields +func (_m *Client) OnStop() { + _m.Called() +} + +// PrepareProposal provides a mock function with given fields: _a0, _a1 +func (_m *Client) PrepareProposal(_a0 context.Context, _a1 *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for PrepareProposal") + } + + var r0 *types.ResponsePrepareProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) *types.ResponsePrepareProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponsePrepareProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestPrepareProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ProcessProposal provides a mock function with given fields: _a0, _a1 +func (_m *Client) ProcessProposal(_a0 context.Context, _a1 *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ProcessProposal") + } + + var r0 *types.ResponseProcessProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) (*types.ResponseProcessProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) *types.ResponseProcessProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseProcessProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestProcessProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Query provides a mock function with given fields: _a0, _a1 +func (_m *Client) Query(_a0 context.Context, _a1 *types.RequestQuery) (*types.ResponseQuery, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Query") + } + + var r0 *types.ResponseQuery + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) (*types.ResponseQuery, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) *types.ResponseQuery); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseQuery) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestQuery) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Quit provides a mock function with no fields +func (_m *Client) Quit() <-chan struct{} { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Quit") + } + + var r0 <-chan struct{} + if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan struct{}) + } + } + + return r0 +} + +// Reset provides a mock function with no fields +func (_m *Client) Reset() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Reset") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SetLogger provides a mock function with given fields: _a0 +func (_m *Client) SetLogger(_a0 log.Logger) { + _m.Called(_a0) +} + +// SetResponseCallback provides a mock function with given fields: _a0 +func (_m *Client) SetResponseCallback(_a0 abcicli.Callback) { + _m.Called(_a0) +} + +// Start provides a mock function with no fields +func (_m *Client) Start() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Start") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Stop provides a mock function with no fields +func (_m *Client) Stop() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Stop") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// String provides a mock function with no fields +func (_m *Client) String() string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for String") + } + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 +func (_m *Client) VerifyVoteExtension(_a0 context.Context, _a1 *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for VerifyVoteExtension") + } + + var r0 *types.ResponseVerifyVoteExtension + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) *types.ResponseVerifyVoteExtension); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseVerifyVoteExtension) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestVerifyVoteExtension) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClient(t interface { + mock.TestingT + Cleanup(func()) +}) *Client { + mock := &Client{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/abci/client/socket_client.go b/abci/client/socket_client.go new file mode 100644 index 0000000..91aed1f --- /dev/null +++ b/abci/client/socket_client.go @@ -0,0 +1,515 @@ +package abcicli + +import ( + "bufio" + "container/list" + "context" + "errors" + "fmt" + "io" + "net" + "sync" + "time" + + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/libs/timer" +) + +const ( + reqQueueSize = 256 // TODO make configurable + flushThrottleMS = 20 // Don't wait longer than... +) + +// socketClient is the client side implementation of the Tendermint +// Socket Protocol (TSP). It is used by an instance of Tendermint to pass +// ABCI requests to an out of process application running the socketServer. +// +// This is goroutine-safe. All calls are serialized to the server through an unbuffered queue. The socketClient +// tracks responses and expects them to respect the order of the requests sent. +type socketClient struct { + service.BaseService + + addr string + mustConnect bool + conn net.Conn + + reqQueue chan *ReqRes + flushTimer *timer.ThrottleTimer + + mtx sync.Mutex + err error + reqSent *list.List // list of requests sent, waiting for response + resCb func(*types.Request, *types.Response) // called on all requests, if set. +} + +var _ Client = (*socketClient)(nil) + +// NewSocketClient creates a new socket client, which connects to a given +// address. If mustConnect is true, the client will return an error upon start +// if it fails to connect else it will continue to retry. +func NewSocketClient(addr string, mustConnect bool) Client { + cli := &socketClient{ + reqQueue: make(chan *ReqRes, reqQueueSize), + flushTimer: timer.NewThrottleTimer("socketClient", flushThrottleMS), + mustConnect: mustConnect, + + addr: addr, + reqSent: list.New(), + resCb: nil, + } + cli.BaseService = *service.NewBaseService(nil, "socketClient", cli) + return cli +} + +// OnStart implements Service by connecting to the server and spawning reading +// and writing goroutines. +func (cli *socketClient) OnStart() error { + var ( + err error + conn net.Conn + ) + + for { + conn, err = cmtnet.Connect(cli.addr) + if err != nil { + if cli.mustConnect { + return err + } + cli.Logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying after %vs...", + cli.addr, dialRetryIntervalSeconds), "err", err) + time.Sleep(time.Second * dialRetryIntervalSeconds) + continue + } + cli.conn = conn + + go cli.sendRequestsRoutine(conn) + go cli.recvResponseRoutine(conn) + + return nil + } +} + +// OnStop implements Service by closing connection and flushing all queues. +func (cli *socketClient) OnStop() { + if cli.conn != nil { + cli.conn.Close() + } + + cli.flushQueue() + cli.flushTimer.Stop() +} + +// Error returns an error if the client was stopped abruptly. +func (cli *socketClient) Error() error { + cli.mtx.Lock() + defer cli.mtx.Unlock() + return cli.err +} + +//---------------------------------------- + +// SetResponseCallback sets a callback, which will be executed for each +// non-error & non-empty response from the server. +// +// NOTE: callback may get internally generated flush responses. +func (cli *socketClient) SetResponseCallback(resCb Callback) { + cli.mtx.Lock() + cli.resCb = resCb + cli.mtx.Unlock() +} + +func (cli *socketClient) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*ReqRes, error) { + return cli.queueRequest(ctx, types.ToRequestCheckTx(req)) +} + +//---------------------------------------- + +func (cli *socketClient) sendRequestsRoutine(conn io.Writer) { + w := bufio.NewWriter(conn) + for { + select { + case reqres := <-cli.reqQueue: + // N.B. We must enqueue before sending out the request, otherwise the + // server may reply before we do it, and the receiver will fail for an + // unsolicited reply. + cli.trackRequest(reqres) + + err := types.WriteMessage(reqres.Request, w) + if err != nil { + cli.stopForError(fmt.Errorf("write to buffer: %w", err)) + return + } + + // If it's a flush request, flush the current buffer. + if _, ok := reqres.Request.Value.(*types.Request_Flush); ok { + err = w.Flush() + if err != nil { + cli.stopForError(fmt.Errorf("flush buffer: %w", err)) + return + } + } + case <-cli.flushTimer.Ch: // flush queue + select { + case cli.reqQueue <- NewReqRes(types.ToRequestFlush()): + default: + // Probably will fill the buffer, or retry later. + } + case <-cli.Quit(): + return + } + } +} + +func (cli *socketClient) recvResponseRoutine(conn io.Reader) { + r := bufio.NewReader(conn) + for { + if !cli.IsRunning() { + return + } + + res := &types.Response{} + err := types.ReadMessage(r, res) + if err != nil { + cli.stopForError(fmt.Errorf("read message: %w", err)) + return + } + + switch r := res.Value.(type) { + case *types.Response_Exception: // app responded with error + // XXX After setting cli.err, release waiters (e.g. reqres.Done()) + cli.stopForError(errors.New(r.Exception.Error)) + return + default: + err := cli.didRecvResponse(res) + if err != nil { + cli.stopForError(err) + return + } + } + } +} + +func (cli *socketClient) trackRequest(reqres *ReqRes) { + // N.B. We must NOT hold the client state lock while checking this, or we + // may deadlock with shutdown. + if !cli.IsRunning() { + return + } + + cli.mtx.Lock() + defer cli.mtx.Unlock() + cli.reqSent.PushBack(reqres) +} + +func (cli *socketClient) didRecvResponse(res *types.Response) error { + cli.mtx.Lock() + defer cli.mtx.Unlock() + + // Get the first ReqRes. + next := cli.reqSent.Front() + if next == nil { + return fmt.Errorf("unexpected response %T when no call was made", res.Value) + } + + reqres := next.Value.(*ReqRes) + if !resMatchesReq(reqres.Request, res) { + return fmt.Errorf("unexpected response %T to the request %T", res.Value, reqres.Request.Value) + } + + reqres.Response = res + reqres.Done() // release waiters + cli.reqSent.Remove(next) // pop first item from linked list + + // Notify client listener if set (global callback). + if cli.resCb != nil { + cli.resCb(reqres.Request, res) + } + + // Notify reqRes listener if set (request specific callback). + // + // NOTE: It is possible this callback isn't set on the reqres object. At this + // point, in which case it will be called after, when it is set. + reqres.InvokeCallback() + + return nil +} + +//---------------------------------------- + +func (cli *socketClient) Flush(ctx context.Context) error { + reqRes, err := cli.queueRequest(ctx, types.ToRequestFlush()) + if err != nil { + return err + } + reqRes.Wait() + return nil +} + +func (cli *socketClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestEcho(msg)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetEcho(), cli.Error() +} + +func (cli *socketClient) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestInfo(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetInfo(), cli.Error() +} + +func (cli *socketClient) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestCheckTx(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetCheckTx(), cli.Error() +} + +func (cli *socketClient) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestQuery(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetQuery(), cli.Error() +} + +func (cli *socketClient) Commit(ctx context.Context, _ *types.RequestCommit) (*types.ResponseCommit, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestCommit()) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetCommit(), cli.Error() +} + +func (cli *socketClient) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestInitChain(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetInitChain(), cli.Error() +} + +func (cli *socketClient) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestListSnapshots(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetListSnapshots(), cli.Error() +} + +func (cli *socketClient) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestOfferSnapshot(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetOfferSnapshot(), cli.Error() +} + +func (cli *socketClient) LoadSnapshotChunk(ctx context.Context, req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestLoadSnapshotChunk(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetLoadSnapshotChunk(), cli.Error() +} + +func (cli *socketClient) ApplySnapshotChunk(ctx context.Context, req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestApplySnapshotChunk(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetApplySnapshotChunk(), cli.Error() +} + +func (cli *socketClient) PrepareProposal(ctx context.Context, req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestPrepareProposal(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetPrepareProposal(), cli.Error() +} + +func (cli *socketClient) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestProcessProposal(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetProcessProposal(), cli.Error() +} + +func (cli *socketClient) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestExtendVote(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetExtendVote(), cli.Error() +} + +func (cli *socketClient) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestVerifyVoteExtension(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetVerifyVoteExtension(), cli.Error() +} + +func (cli *socketClient) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + reqRes, err := cli.queueRequest(ctx, types.ToRequestFinalizeBlock(req)) + if err != nil { + return nil, err + } + if err := cli.Flush(ctx); err != nil { + return nil, err + } + return reqRes.Response.GetFinalizeBlock(), cli.Error() +} + +func (cli *socketClient) queueRequest(ctx context.Context, req *types.Request) (*ReqRes, error) { + reqres := NewReqRes(req) + + // TODO: set cli.err if reqQueue times out + select { + case cli.reqQueue <- reqres: + case <-ctx.Done(): + return nil, ctx.Err() + } + + // Maybe auto-flush, or unset auto-flush + switch req.Value.(type) { + case *types.Request_Flush: + cli.flushTimer.Unset() + default: + cli.flushTimer.Set() + } + + return reqres, nil +} + +// flushQueue marks as complete and discards all remaining pending requests +// from the queue. +func (cli *socketClient) flushQueue() { + cli.mtx.Lock() + defer cli.mtx.Unlock() + + // mark all in-flight messages as resolved (they will get cli.Error()) + for req := cli.reqSent.Front(); req != nil; req = req.Next() { + reqres := req.Value.(*ReqRes) + reqres.Done() + } + + // mark all queued messages as resolved +LOOP: + for { + select { + case reqres := <-cli.reqQueue: + reqres.Done() + default: + break LOOP + } + } +} + +//---------------------------------------- + +func resMatchesReq(req *types.Request, res *types.Response) (ok bool) { + switch req.Value.(type) { + case *types.Request_Echo: + _, ok = res.Value.(*types.Response_Echo) + case *types.Request_Flush: + _, ok = res.Value.(*types.Response_Flush) + case *types.Request_Info: + _, ok = res.Value.(*types.Response_Info) + case *types.Request_CheckTx: + _, ok = res.Value.(*types.Response_CheckTx) + case *types.Request_Commit: + _, ok = res.Value.(*types.Response_Commit) + case *types.Request_Query: + _, ok = res.Value.(*types.Response_Query) + case *types.Request_InitChain: + _, ok = res.Value.(*types.Response_InitChain) + case *types.Request_ApplySnapshotChunk: + _, ok = res.Value.(*types.Response_ApplySnapshotChunk) + case *types.Request_LoadSnapshotChunk: + _, ok = res.Value.(*types.Response_LoadSnapshotChunk) + case *types.Request_ListSnapshots: + _, ok = res.Value.(*types.Response_ListSnapshots) + case *types.Request_OfferSnapshot: + _, ok = res.Value.(*types.Response_OfferSnapshot) + case *types.Request_ExtendVote: + _, ok = res.Value.(*types.Response_ExtendVote) + case *types.Request_VerifyVoteExtension: + _, ok = res.Value.(*types.Response_VerifyVoteExtension) + case *types.Request_PrepareProposal: + _, ok = res.Value.(*types.Response_PrepareProposal) + case *types.Request_ProcessProposal: + _, ok = res.Value.(*types.Response_ProcessProposal) + case *types.Request_FinalizeBlock: + _, ok = res.Value.(*types.Response_FinalizeBlock) + } + return ok +} + +func (cli *socketClient) stopForError(err error) { + if !cli.IsRunning() { + return + } + + cli.mtx.Lock() + if cli.err == nil { + cli.err = err + } + cli.mtx.Unlock() + + cli.Logger.Error(fmt.Sprintf("Stopping abci.socketClient for error: %v", err.Error())) + if err := cli.Stop(); err != nil { + cli.Logger.Error("Error stopping abci.socketClient", "err", err) + } +} diff --git a/abci/client/socket_client_test.go b/abci/client/socket_client_test.go new file mode 100644 index 0000000..17e5d0f --- /dev/null +++ b/abci/client/socket_client_test.go @@ -0,0 +1,239 @@ +package abcicli_test + +import ( + "context" + "fmt" + "math/rand" + "os" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/server" + "github.com/cometbft/cometbft/abci/types" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/service" +) + +func TestCalls(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + app := types.BaseApplication{} + + _, c := setupClientServer(t, app) + + resp := make(chan error, 1) + go func() { + res, err := c.Echo(ctx, "hello") + require.NoError(t, err) + require.NotNil(t, res) + resp <- c.Error() + }() + + select { + case <-time.After(time.Second): + require.Fail(t, "No response arrived") + case err, ok := <-resp: + require.True(t, ok, "Must not close channel") + assert.NoError(t, err, "This should return success") + } +} + +func TestHangingAsyncCalls(t *testing.T) { + app := slowApp{} + + s, c := setupClientServer(t, app) + + resp := make(chan error, 1) + go func() { + // Call CheckTx + reqres, err := c.CheckTxAsync(context.Background(), &types.RequestCheckTx{}) + require.NoError(t, err) + // wait 50 ms for all events to travel socket, but + // no response yet from server + time.Sleep(50 * time.Millisecond) + // kill the server, so the connections break + err = s.Stop() + require.NoError(t, err) + + // wait for the response from CheckTx + reqres.Wait() + resp <- c.Error() + }() + + select { + case <-time.After(time.Second): + require.Fail(t, "No response arrived") + case err, ok := <-resp: + require.True(t, ok, "Must not close channel") + assert.Error(t, err, "We should get EOF error") + } +} + +func TestBulk(t *testing.T) { + const numTxs = 700000 + // use a socket instead of a port + socketFile := fmt.Sprintf("test-%08x.sock", rand.Int31n(1<<30)) + defer os.Remove(socketFile) + socket := fmt.Sprintf("unix://%v", socketFile) + app := types.NewBaseApplication() + // Start the listener + server := server.NewSocketServer(socket, app) + t.Cleanup(func() { + if err := server.Stop(); err != nil { + t.Log(err) + } + }) + err := server.Start() + require.NoError(t, err) + + // Connect to the socket + client := abcicli.NewSocketClient(socket, false) + + t.Cleanup(func() { + if err := client.Stop(); err != nil { + t.Log(err) + } + }) + + err = client.Start() + require.NoError(t, err) + + // Construct request + rfb := &types.RequestFinalizeBlock{Txs: make([][]byte, numTxs)} + for counter := 0; counter < numTxs; counter++ { + rfb.Txs[counter] = []byte("test") + } + // Send bulk request + res, err := client.FinalizeBlock(context.Background(), rfb) + require.NoError(t, err) + require.Equal(t, numTxs, len(res.TxResults), "Number of txs doesn't match") + for _, tx := range res.TxResults { + require.Equal(t, uint32(0), tx.Code, "Tx failed") + } + + // Send final flush message + err = client.Flush(context.Background()) + require.NoError(t, err) +} + +func setupClientServer(t *testing.T, app types.Application) ( + service.Service, abcicli.Client, +) { + t.Helper() + + // some port between 20k and 30k + port := 20000 + cmtrand.Int32()%10000 + addr := fmt.Sprintf("localhost:%d", port) + + s := server.NewSocketServer(addr, app) + err := s.Start() + require.NoError(t, err) + + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Log(err) + } + }) + + c := abcicli.NewSocketClient(addr, true) + err = c.Start() + require.NoError(t, err) + + t.Cleanup(func() { + if err := c.Stop(); err != nil { + t.Log(err) + } + }) + + return s, c +} + +type slowApp struct { + types.BaseApplication +} + +func (slowApp) CheckTx(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + time.Sleep(time.Second) + return &types.ResponseCheckTx{}, nil +} + +// TestCallbackInvokedWhenSetLaet ensures that the callback is invoked when +// set after the client completes the call into the app. Currently this +// test relies on the callback being allowed to be invoked twice if set multiple +// times, once when set early and once when set late. +func TestCallbackInvokedWhenSetLate(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + wg := &sync.WaitGroup{} + wg.Add(1) + app := blockedABCIApplication{ + wg: wg, + } + _, c := setupClientServer(t, app) + reqRes, err := c.CheckTxAsync(ctx, &types.RequestCheckTx{}) + require.NoError(t, err) + + done := make(chan struct{}) + cb := func(_ *types.Response) { + close(done) + } + reqRes.SetCallback(cb) + app.wg.Done() + <-done + + var called bool + cb = func(_ *types.Response) { + called = true + } + reqRes.SetCallback(cb) + require.True(t, called) +} + +type blockedABCIApplication struct { + wg *sync.WaitGroup + types.BaseApplication +} + +func (b blockedABCIApplication) CheckTxAsync(ctx context.Context, r *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + b.wg.Wait() + return b.CheckTx(ctx, r) +} + +// TestCallbackInvokedWhenSetEarly ensures that the callback is invoked when +// set before the client completes the call into the app. +func TestCallbackInvokedWhenSetEarly(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + wg := &sync.WaitGroup{} + wg.Add(1) + app := blockedABCIApplication{ + wg: wg, + } + _, c := setupClientServer(t, app) + reqRes, err := c.CheckTxAsync(ctx, &types.RequestCheckTx{}) + require.NoError(t, err) + + done := make(chan struct{}) + cb := func(_ *types.Response) { + close(done) + } + reqRes.SetCallback(cb) + app.wg.Done() + + called := func() bool { + select { + case <-done: + return true + default: + return false + } + } + require.Eventually(t, called, time.Second, time.Millisecond*25) +} diff --git a/abci/cmd/abci-cli/abci-cli.go b/abci/cmd/abci-cli/abci-cli.go new file mode 100644 index 0000000..a23485b --- /dev/null +++ b/abci/cmd/abci-cli/abci-cli.go @@ -0,0 +1,797 @@ +package main + +import ( + "bufio" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/abci/server" + servertest "github.com/cometbft/cometbft/abci/tests/server" + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/abci/version" + "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +// client is a global variable so it can be reused by the console +var ( + client abcicli.Client + logger log.Logger +) + +// flags +var ( + // global + flagAddress string + flagAbci string + flagVerbose bool // for the println output + flagLogLevel string // for the logger + + // query + flagPath string + flagHeight int + flagProve bool + + // kvstore + flagPersist string +) + +var RootCmd = &cobra.Command{ + Use: "abci-cli", + Short: "the ABCI CLI tool wraps an ABCI client", + Long: "the ABCI CLI tool wraps an ABCI client and is used for testing ABCI servers", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + switch cmd.Use { + case "kvstore", "version", "help [command]": + return nil + } + + if logger == nil { + allowLevel, err := log.AllowLevel(flagLogLevel) + if err != nil { + return err + } + logger = log.NewFilter(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), allowLevel) + } + if client == nil { + var err error + client, err = abcicli.NewClient(flagAddress, flagAbci, false) + if err != nil { + return err + } + client.SetLogger(logger.With("module", "abci-client")) + if err := client.Start(); err != nil { + return err + } + } + return nil + }, +} + +// Structure for data passed to print response. +type response struct { + // generic abci response + Data []byte + Code uint32 + Info string + Log string + Status int32 + + Query *queryResponse +} + +type queryResponse struct { + Key []byte + Value []byte + Height int64 + ProofOps *crypto.ProofOps +} + +func Execute() error { + addGlobalFlags() + addCommands() + return RootCmd.Execute() +} + +func addGlobalFlags() { + RootCmd.PersistentFlags().StringVarP(&flagAddress, + "address", + "", + "tcp://0.0.0.0:26658", + "address of application socket") + RootCmd.PersistentFlags().StringVarP(&flagAbci, "abci", "", "socket", "either socket or grpc") + RootCmd.PersistentFlags().BoolVarP(&flagVerbose, + "verbose", + "v", + false, + "print the command and results as if it were a console session") + RootCmd.PersistentFlags().StringVarP(&flagLogLevel, "log_level", "", "debug", "set the logger level") +} + +func addQueryFlags() { + queryCmd.PersistentFlags().StringVarP(&flagPath, "path", "", "/store", "path to prefix query with") + queryCmd.PersistentFlags().IntVarP(&flagHeight, "height", "", 0, "height to query the blockchain at") + queryCmd.PersistentFlags().BoolVarP(&flagProve, + "prove", + "", + false, + "whether or not to return a merkle proof of the query result") +} + +func addKVStoreFlags() { + kvstoreCmd.PersistentFlags().StringVarP(&flagPersist, "persist", "", "", "directory to use for a database") +} + +func addCommands() { + RootCmd.AddCommand(batchCmd) + RootCmd.AddCommand(consoleCmd) + RootCmd.AddCommand(echoCmd) + RootCmd.AddCommand(infoCmd) + RootCmd.AddCommand(checkTxCmd) + RootCmd.AddCommand(commitCmd) + RootCmd.AddCommand(versionCmd) + RootCmd.AddCommand(testCmd) + RootCmd.AddCommand(prepareProposalCmd) + RootCmd.AddCommand(processProposalCmd) + addQueryFlags() + RootCmd.AddCommand(queryCmd) + RootCmd.AddCommand(finalizeBlockCmd) + + // examples + addKVStoreFlags() + RootCmd.AddCommand(kvstoreCmd) +} + +var batchCmd = &cobra.Command{ + Use: "batch", + Short: "run a batch of abci commands against an application", + Long: `run a batch of abci commands against an application + +This command is run by piping in a file containing a series of commands +you'd like to run: + + abci-cli batch < example.file + +where example.file looks something like: + + check_tx 0x00 + check_tx 0xff + finalize_block 0x00 + check_tx 0x00 + finalize_block 0x01 0x04 0xff + info +`, + Args: cobra.ExactArgs(0), + RunE: cmdBatch, +} + +var consoleCmd = &cobra.Command{ + Use: "console", + Short: "start an interactive ABCI console for multiple commands", + Long: `start an interactive ABCI console for multiple commands + +This command opens an interactive console for running any of the other commands +without opening a new connection each time +`, + Args: cobra.ExactArgs(0), + ValidArgs: []string{"echo", "info", "finalize_block", "check_tx", "prepare_proposal", "process_proposal", "commit", "query"}, + RunE: cmdConsole, +} + +var echoCmd = &cobra.Command{ + Use: "echo", + Short: "have the application echo a message", + Long: "have the application echo a message", + Args: cobra.ExactArgs(1), + RunE: cmdEcho, +} + +var infoCmd = &cobra.Command{ + Use: "info", + Short: "get some info about the application", + Long: "get some info about the application", + Args: cobra.ExactArgs(0), + RunE: cmdInfo, +} + +var finalizeBlockCmd = &cobra.Command{ + Use: "finalize_block", + Short: "deliver a block of transactions to the application", + Long: "deliver a block of transactions to the application", + Args: cobra.MinimumNArgs(1), + RunE: cmdFinalizeBlock, +} + +var checkTxCmd = &cobra.Command{ + Use: "check_tx", + Short: "validate a transaction", + Long: "validate a transaction", + Args: cobra.ExactArgs(1), + RunE: cmdCheckTx, +} + +var commitCmd = &cobra.Command{ + Use: "commit", + Short: "commit the application state and return the Merkle root hash", + Long: "commit the application state and return the Merkle root hash", + Args: cobra.ExactArgs(0), + RunE: cmdCommit, +} + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "print ABCI console version", + Long: "print ABCI console version", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + fmt.Println(version.Version) + return nil + }, +} + +var prepareProposalCmd = &cobra.Command{ + Use: "prepare_proposal", + Short: "prepare proposal", + Long: "prepare proposal", + Args: cobra.MinimumNArgs(0), + RunE: cmdPrepareProposal, +} + +var processProposalCmd = &cobra.Command{ + Use: "process_proposal", + Short: "process proposal", + Long: "process proposal", + Args: cobra.MinimumNArgs(0), + RunE: cmdProcessProposal, +} + +var queryCmd = &cobra.Command{ + Use: "query", + Short: "query the application state", + Long: "query the application state", + Args: cobra.ExactArgs(1), + RunE: cmdQuery, +} + +var kvstoreCmd = &cobra.Command{ + Use: "kvstore", + Short: "ABCI demo example", + Long: "ABCI demo example", + Args: cobra.ExactArgs(0), + RunE: cmdKVStore, +} + +var testCmd = &cobra.Command{ + Use: "test", + Short: "run integration tests", + Long: "run integration tests", + Args: cobra.ExactArgs(0), + RunE: cmdTest, +} + +// Generates new Args array based off of previous call args to maintain flag persistence +func persistentArgs(line []byte) []string { + // generate the arguments to run from original os.Args + // to maintain flag arguments + args := os.Args + args = args[:len(args)-1] // remove the previous command argument + + if len(line) > 0 { // prevents introduction of extra space leading to argument parse errors + args = append(args, strings.Split(string(line), " ")...) + } + return args +} + +//-------------------------------------------------------------------------------- + +func compose(fs []func() error) error { + if len(fs) == 0 { + return nil + } + + err := fs[0]() + if err == nil { + return compose(fs[1:]) + } + + return err +} + +func cmdTest(cmd *cobra.Command, _ []string) error { + ctx := cmd.Context() + return compose( + []func() error{ + func() error { return servertest.InitChain(ctx, client) }, + func() error { return servertest.Commit(ctx, client) }, + func() error { + return servertest.FinalizeBlock(ctx, client, [][]byte{ + []byte("abc"), + }, []uint32{ + kvstore.CodeTypeInvalidTxFormat, + }, nil, nil) + }, + func() error { return servertest.Commit(ctx, client) }, + func() error { + return servertest.FinalizeBlock(ctx, client, [][]byte{ + {0x00}, + }, []uint32{ + kvstore.CodeTypeOK, + }, nil, []byte{0, 0, 0, 0, 0, 0, 0, 1}) + }, + func() error { return servertest.Commit(ctx, client) }, + func() error { + return servertest.FinalizeBlock(ctx, client, [][]byte{ + {0x00}, + {0x01}, + {0x00, 0x02}, + {0x00, 0x03}, + {0x00, 0x00, 0x04}, + {0x00, 0x00, 0x06}, + }, []uint32{ + kvstore.CodeTypeInvalidTxFormat, + kvstore.CodeTypeOK, + kvstore.CodeTypeOK, + kvstore.CodeTypeOK, + kvstore.CodeTypeOK, + kvstore.CodeTypeInvalidTxFormat, + }, nil, []byte{0, 0, 0, 0, 0, 0, 0, 5}) + }, + func() error { return servertest.Commit(ctx, client) }, + func() error { + return servertest.PrepareProposal(ctx, client, [][]byte{ + {0x01}, + }, [][]byte{{0x01}}, nil) + }, + func() error { + return servertest.ProcessProposal(ctx, client, [][]byte{ + {0x01}, + }, types.ResponseProcessProposal_ACCEPT) + }, + }) +} + +func cmdBatch(cmd *cobra.Command, _ []string) error { + bufReader := bufio.NewReader(os.Stdin) +LOOP: + for { + + line, more, err := bufReader.ReadLine() + switch { + case more: + return errors.New("input line is too long") + case err == io.EOF: + break LOOP + case len(line) == 0: + continue + case err != nil: + return err + } + + cmdArgs := persistentArgs(line) + if err := muxOnCommands(cmd, cmdArgs); err != nil { + return err + } + fmt.Println() + } + return nil +} + +func cmdConsole(cmd *cobra.Command, _ []string) error { + for { + fmt.Printf("> ") + bufReader := bufio.NewReader(os.Stdin) + line, more, err := bufReader.ReadLine() + if more { + return errors.New("input is too long") + } else if err != nil { + return err + } + + pArgs := persistentArgs(line) + if err := muxOnCommands(cmd, pArgs); err != nil { + return err + } + } +} + +func muxOnCommands(cmd *cobra.Command, pArgs []string) error { + if len(pArgs) < 2 { + return errors.New("expecting persistent args of the form: abci-cli [command] <...>") + } + + // TODO: this parsing is fragile + args := []string{} + for i := 0; i < len(pArgs); i++ { + arg := pArgs[i] + + // check for flags + if strings.HasPrefix(arg, "-") { + // if it has an equal, we can just skip + if strings.Contains(arg, "=") { + continue + } + // if its a boolean, we can just skip + _, err := cmd.Flags().GetBool(strings.TrimLeft(arg, "-")) + if err == nil { + continue + } + + // otherwise, we need to skip the next one too + i++ + continue + } + + // append the actual arg + args = append(args, arg) + } + var subCommand string + var actualArgs []string + if len(args) > 1 { + subCommand = args[1] + } + if len(args) > 2 { + actualArgs = args[2:] + } + cmd.Use = subCommand // for later print statements ... + + switch strings.ToLower(subCommand) { + case "check_tx": + return cmdCheckTx(cmd, actualArgs) + case "commit": + return cmdCommit(cmd, actualArgs) + case "finalize_block": + return cmdFinalizeBlock(cmd, actualArgs) + case "echo": + return cmdEcho(cmd, actualArgs) + case "info": + return cmdInfo(cmd, actualArgs) + case "query": + return cmdQuery(cmd, actualArgs) + case "prepare_proposal": + return cmdPrepareProposal(cmd, actualArgs) + case "process_proposal": + return cmdProcessProposal(cmd, actualArgs) + default: + return cmdUnimplemented(cmd, pArgs) + } +} + +func cmdUnimplemented(cmd *cobra.Command, args []string) error { + msg := "unimplemented command" + + if len(args) > 0 { + msg += fmt.Sprintf(" args: [%s]", strings.Join(args, " ")) + } + printResponse(cmd, args, response{ + Code: codeBad, + Log: msg, + }) + + fmt.Println("Available commands:") + fmt.Printf("%s: %s\n", echoCmd.Use, echoCmd.Short) + fmt.Printf("%s: %s\n", checkTxCmd.Use, checkTxCmd.Short) + fmt.Printf("%s: %s\n", commitCmd.Use, commitCmd.Short) + fmt.Printf("%s: %s\n", finalizeBlockCmd.Use, finalizeBlockCmd.Short) + fmt.Printf("%s: %s\n", infoCmd.Use, infoCmd.Short) + fmt.Printf("%s: %s\n", queryCmd.Use, queryCmd.Short) + fmt.Printf("%s: %s\n", prepareProposalCmd.Use, prepareProposalCmd.Short) + fmt.Printf("%s: %s\n", processProposalCmd.Use, processProposalCmd.Short) + + fmt.Println("Use \"[command] --help\" for more information about a command.") + + return nil +} + +// Have the application echo a message +func cmdEcho(cmd *cobra.Command, args []string) error { + msg := "" + if len(args) > 0 { + msg = args[0] + } + res, err := client.Echo(cmd.Context(), msg) + if err != nil { + return err + } + + printResponse(cmd, args, response{ + Data: []byte(res.Message), + }) + + return nil +} + +// Get some info from the application +func cmdInfo(cmd *cobra.Command, args []string) error { + var version string + if len(args) == 1 { + version = args[0] + } + res, err := client.Info(cmd.Context(), &types.RequestInfo{Version: version}) + if err != nil { + return err + } + printResponse(cmd, args, response{ + Data: []byte(res.Data), + }) + return nil +} + +const codeBad uint32 = 10 + +// Append new txs to application +func cmdFinalizeBlock(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + printResponse(cmd, args, response{ + Code: codeBad, + Log: "Must provide at least one transaction", + }) + return nil + } + txs := make([][]byte, len(args)) + for i, arg := range args { + txBytes, err := stringOrHexToBytes(arg) + if err != nil { + return err + } + txs[i] = txBytes + } + res, err := client.FinalizeBlock(cmd.Context(), &types.RequestFinalizeBlock{Txs: txs}) + if err != nil { + return err + } + resps := make([]response, 0, len(res.TxResults)+1) + for _, tx := range res.TxResults { + resps = append(resps, response{ + Code: tx.Code, + Data: tx.Data, + Info: tx.Info, + Log: tx.Log, + }) + } + resps = append(resps, response{ + Data: res.AppHash, + }) + printResponse(cmd, args, resps...) + return nil +} + +// Validate a tx +func cmdCheckTx(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + printResponse(cmd, args, response{ + Code: codeBad, + Info: "want the tx", + }) + return nil + } + txBytes, err := stringOrHexToBytes(args[0]) + if err != nil { + return err + } + res, err := client.CheckTx(cmd.Context(), &types.RequestCheckTx{Tx: txBytes}) + if err != nil { + return err + } + printResponse(cmd, args, response{ + Code: res.Code, + Data: res.Data, + Info: res.Info, + Log: res.Log, + }) + return nil +} + +// Get application Merkle root hash +func cmdCommit(cmd *cobra.Command, args []string) error { + _, err := client.Commit(cmd.Context(), &types.RequestCommit{}) + if err != nil { + return err + } + printResponse(cmd, args, response{}) + return nil +} + +// Query application state +func cmdQuery(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + printResponse(cmd, args, response{ + Code: codeBad, + Info: "want the query", + Log: "", + }) + return nil + } + queryBytes, err := stringOrHexToBytes(args[0]) + if err != nil { + return err + } + + resQuery, err := client.Query(cmd.Context(), &types.RequestQuery{ + Data: queryBytes, + Path: flagPath, + Height: int64(flagHeight), + Prove: flagProve, + }) + if err != nil { + return err + } + printResponse(cmd, args, response{ + Code: resQuery.Code, + Info: resQuery.Info, + Log: resQuery.Log, + Query: &queryResponse{ + Key: resQuery.Key, + Value: resQuery.Value, + Height: resQuery.Height, + ProofOps: resQuery.ProofOps, + }, + }) + return nil +} + +func cmdPrepareProposal(cmd *cobra.Command, args []string) error { + txsBytesArray := make([][]byte, len(args)) + + for i, arg := range args { + txBytes, err := stringOrHexToBytes(arg) + if err != nil { + return err + } + txsBytesArray[i] = txBytes + } + + res, err := client.PrepareProposal(cmd.Context(), &types.RequestPrepareProposal{ + Txs: txsBytesArray, + // kvstore has to have this parameter in order not to reject a tx as the default value is 0 + MaxTxBytes: 65536, + }) + if err != nil { + return err + } + resps := make([]response, 0, len(res.Txs)) + for _, tx := range res.Txs { + resps = append(resps, response{ + Code: 0, // CodeOK + Log: "Succeeded. Tx: " + string(tx), + }) + } + + printResponse(cmd, args, resps...) + return nil +} + +func cmdProcessProposal(cmd *cobra.Command, args []string) error { + txsBytesArray := make([][]byte, len(args)) + + for i, arg := range args { + txBytes, err := stringOrHexToBytes(arg) + if err != nil { + return err + } + txsBytesArray[i] = txBytes + } + + res, err := client.ProcessProposal(cmd.Context(), &types.RequestProcessProposal{ + Txs: txsBytesArray, + }) + if err != nil { + return err + } + + printResponse(cmd, args, response{ + Status: int32(res.Status), + }) + return nil +} + +func cmdKVStore(*cobra.Command, []string) error { + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + + // Create the application - in memory or persisted to disk + var app types.Application + if flagPersist == "" { + var err error + flagPersist, err = os.MkdirTemp("", "persistent_kvstore_tmp") + if err != nil { + return err + } + } + app = kvstore.NewPersistentApplication(flagPersist) + + // Start the listener + srv, err := server.NewServer(flagAddress, flagAbci, app) + if err != nil { + return err + } + srv.SetLogger(logger.With("module", "abci-server")) + if err := srv.Start(); err != nil { + return err + } + + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(logger, func() { + // Cleanup + if err := srv.Stop(); err != nil { + logger.Error("Error while stopping server", "err", err) + } + }) + + // Run forever. + select {} +} + +//-------------------------------------------------------------------------------- + +func printResponse(cmd *cobra.Command, args []string, rsps ...response) { + if flagVerbose { + fmt.Println(">", cmd.Use, strings.Join(args, " ")) + } + + for _, rsp := range rsps { + // Always print the status code. + if rsp.Code == types.CodeTypeOK { + fmt.Printf("-> code: OK\n") + } else { + fmt.Printf("-> code: %d\n", rsp.Code) + } + + if len(rsp.Data) != 0 { + // Do no print this line when using the finalize_block command + // because the string comes out as gibberish + if cmd.Use != "finalize_block" { + fmt.Printf("-> data: %s\n", rsp.Data) + } + fmt.Printf("-> data.hex: 0x%X\n", rsp.Data) + } + if rsp.Log != "" { + fmt.Printf("-> log: %s\n", rsp.Log) + } + if cmd.Use == "process_proposal" { + fmt.Printf("-> status: %s\n", types.ResponseProcessProposal_ProposalStatus_name[rsp.Status]) + } + + if rsp.Query != nil { + fmt.Printf("-> height: %d\n", rsp.Query.Height) + if rsp.Query.Key != nil { + fmt.Printf("-> key: %s\n", rsp.Query.Key) + fmt.Printf("-> key.hex: %X\n", rsp.Query.Key) + } + if rsp.Query.Value != nil { + fmt.Printf("-> value: %s\n", rsp.Query.Value) + fmt.Printf("-> value.hex: %X\n", rsp.Query.Value) + } + if rsp.Query.ProofOps != nil { + fmt.Printf("-> proof: %#v\n", rsp.Query.ProofOps) + } + } + } +} + +// NOTE: s is interpreted as a string unless prefixed with 0x +func stringOrHexToBytes(s string) ([]byte, error) { + if len(s) > 2 && strings.ToLower(s[:2]) == "0x" { + b, err := hex.DecodeString(s[2:]) + if err != nil { + err = fmt.Errorf("error decoding hex argument: %s", err.Error()) + return nil, err + } + return b, nil + } + + if !strings.HasPrefix(s, "\"") || !strings.HasSuffix(s, "\"") { + err := fmt.Errorf("invalid string arg: \"%s\". Must be quoted or a \"0x\"-prefixed hex string", s) + return nil, err + } + + return []byte(s[1 : len(s)-1]), nil +} diff --git a/abci/cmd/abci-cli/main.go b/abci/cmd/abci-cli/main.go new file mode 100644 index 0000000..55ffcf7 --- /dev/null +++ b/abci/cmd/abci-cli/main.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + err := Execute() + if err != nil { + fmt.Print(err) + os.Exit(1) + } +} diff --git a/abci/example/kvstore/README.md b/abci/example/kvstore/README.md new file mode 100644 index 0000000..321aa1a --- /dev/null +++ b/abci/example/kvstore/README.md @@ -0,0 +1,17 @@ +# KVStore + +The KVStoreApplication is a simple merkle key-value store. +Transactions of the form `key=value` are stored as key-value pairs in the tree. +Transactions without an `=` sign set the value to the key. +The app has no replay protection (other than what the mempool provides). + +Validator set changes are effected using the following transaction format: + +```md +"val:pubkeytype1!pubkey1!power1,pubkeytype2!pubkey2!power2,pubkeytype3!pubkey3!power3" +``` + +where `pubkeyN` is a base64-encoded 32-byte key, `pubkeytypeN` is a string representing the key type, +and `powerN` is a new voting power for the validator with `pubkeyN` (possibly a new one). +To remove a validator from the validator set, set power to `0`. +There is no sybil protection against new validators joining. diff --git a/abci/example/kvstore/code.go b/abci/example/kvstore/code.go new file mode 100644 index 0000000..f8f2781 --- /dev/null +++ b/abci/example/kvstore/code.go @@ -0,0 +1,10 @@ +package kvstore + +// Return codes for the examples +const ( + CodeTypeOK uint32 = 0 + CodeTypeEncodingError uint32 = 1 + CodeTypeInvalidTxFormat uint32 = 2 + CodeTypeUnauthorized uint32 = 3 + CodeTypeExecuted uint32 = 5 +) diff --git a/abci/example/kvstore/helpers.go b/abci/example/kvstore/helpers.go new file mode 100644 index 0000000..72bd5a0 --- /dev/null +++ b/abci/example/kvstore/helpers.go @@ -0,0 +1,80 @@ +package kvstore + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + + "github.com/cometbft/cometbft/abci/types" + cryptoencoding "github.com/cometbft/cometbft/crypto/encoding" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +// RandVal creates one random validator, with a key derived +// from the input value +func RandVal() types.ValidatorUpdate { + pubkey := cmtrand.Bytes(32) + power := cmtrand.Uint16() + 1 + v := types.UpdateValidator(pubkey, int64(power), "") + return v +} + +// RandVals returns a list of cnt validators for initializing +// the application. Note that the keys are deterministically +// derived from the index in the array, while the power is +// random (Change this if not desired) +func RandVals(cnt int) []types.ValidatorUpdate { + res := make([]types.ValidatorUpdate, cnt) + for i := 0; i < cnt; i++ { + res[i] = RandVal() + } + return res +} + +// InitKVStore initializes the kvstore app with some data, +// which allows tests to pass and is fine as long as you +// don't make any tx that modify the validator state +func InitKVStore(ctx context.Context, app *Application) error { + _, err := app.InitChain(ctx, &types.RequestInitChain{ + Validators: RandVals(1), + }) + return err +} + +// Create a new transaction +func NewTx(key, value string) []byte { + return []byte(strings.Join([]string{key, value}, "=")) +} + +func NewRandomTx(size int) []byte { + if size < 4 { + panic("random tx size must be greater than 3") + } + return NewTx(cmtrand.Str(2), cmtrand.Str(size-3)) +} + +func NewRandomTxs(n int) [][]byte { + txs := make([][]byte, n) + for i := 0; i < n; i++ { + txs[i] = NewRandomTx(10) + } + return txs +} + +func NewTxFromID(i int) []byte { + return []byte(fmt.Sprintf("%d=%d", i, i)) +} + +// Create a transaction to add/remove/update a validator +// To remove, set power to 0. +func MakeValSetChangeTx(pubkey crypto.PublicKey, power int64) []byte { + pk, err := cryptoencoding.PubKeyFromProto(pubkey) + if err != nil { + panic(err) + } + pubStr := base64.StdEncoding.EncodeToString(pk.Bytes()) + pubTypeStr := pk.Type() + return []byte(fmt.Sprintf("%s%s!%s!%d", ValidatorPrefix, pubTypeStr, pubStr, power)) +} diff --git a/abci/example/kvstore/kvstore.go b/abci/example/kvstore/kvstore.go new file mode 100644 index 0000000..15673d7 --- /dev/null +++ b/abci/example/kvstore/kvstore.go @@ -0,0 +1,553 @@ +package kvstore + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "encoding/json" + "fmt" + "strconv" + "strings" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/types" + cryptoencoding "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/libs/log" + cryptoproto "github.com/cometbft/cometbft/proto/tendermint/crypto" + "github.com/cometbft/cometbft/version" +) + +var ( + stateKey = []byte("stateKey") + kvPairPrefixKey = []byte("kvPairKey:") +) + +const ( + ValidatorPrefix = "val=" + AppVersion uint64 = 1 +) + +var _ types.Application = (*Application)(nil) + +// Application is the kvstore state machine. It complies with the abci.Application interface. +// It takes transactions in the form of key=value and saves them in a database. This is +// a somewhat trivial example as there is no real state execution +type Application struct { + types.BaseApplication + + state State + RetainBlocks int64 // blocks to retain after commit (via ResponseCommit.RetainHeight) + stagedTxs [][]byte + logger log.Logger + + // validator set + valUpdates []types.ValidatorUpdate + valAddrToPubKeyMap map[string]cryptoproto.PublicKey + + // If true, the app will generate block events in BeginBlock. Used to test the event indexer + // Should be false by default to avoid generating too much data. + genBlockEvents bool +} + +// NewApplication creates an instance of the kvstore from the provided database +func NewApplication(db dbm.DB) *Application { + return &Application{ + logger: log.NewNopLogger(), + state: loadState(db), + valAddrToPubKeyMap: make(map[string]cryptoproto.PublicKey), + } +} + +// NewPersistentApplication creates a new application using the goleveldb database engine +func NewPersistentApplication(dbDir string) *Application { + name := "kvstore" + db, err := dbm.NewGoLevelDB(name, dbDir) + if err != nil { + panic(fmt.Errorf("failed to create persistent app at %s: %w", dbDir, err)) + } + return NewApplication(db) +} + +// NewInMemoryApplication creates a new application from an in memory database. +// Nothing will be persisted. +func NewInMemoryApplication() *Application { + return NewApplication(dbm.NewMemDB()) +} + +func (app *Application) SetGenBlockEvents() { + app.genBlockEvents = true +} + +// Info returns information about the state of the application. This is generally used everytime a Tendermint instance +// begins and let's the application know what Tendermint versions it's interacting with. Based from this information, +// Tendermint will ensure it is in sync with the application by potentially replaying the blocks it has. If the +// Application returns a 0 appBlockHeight, Tendermint will call InitChain to initialize the application with consensus related data +func (app *Application) Info(context.Context, *types.RequestInfo) (*types.ResponseInfo, error) { + // Tendermint expects the application to persist validators, on start-up we need to reload them to memory if they exist + if len(app.valAddrToPubKeyMap) == 0 && app.state.Height > 0 { + validators := app.getValidators() + for _, v := range validators { + pubkey, err := cryptoencoding.PubKeyFromProto(v.PubKey) + if err != nil { + panic(fmt.Errorf("can't decode public key: %w", err)) + } + app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey + } + } + + return &types.ResponseInfo{ + Data: fmt.Sprintf("{\"size\":%v}", app.state.Size), + Version: version.ABCIVersion, + AppVersion: AppVersion, + LastBlockHeight: app.state.Height, + LastBlockAppHash: app.state.Hash(), + }, nil +} + +// InitChain takes the genesis validators and stores them in the kvstore. It returns the application hash in the +// case that the application starts prepopulated with values. This method is called whenever a new instance of the application +// starts (i.e. app height = 0). +func (app *Application) InitChain(_ context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) { + for _, v := range req.Validators { + app.updateValidator(v) + } + appHash := make([]byte, 8) + binary.PutVarint(appHash, app.state.Size) + return &types.ResponseInitChain{ + AppHash: appHash, + }, nil +} + +// CheckTx handles inbound transactions or in the case of recheckTx assesses old transaction validity after a state transition. +// As this is called frequently, it's preferably to keep the check as stateless and as quick as possible. +// Here we check that the transaction has the correctly key=value format. +// For the KVStore we check that each transaction has the valid tx format: +// - Contains one and only one `=` +// - `=` is not the first or last byte. +// - if key is `val` that the validator update transaction is also valid +func (app *Application) CheckTx(_ context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + // If it is a validator update transaction, check that it is correctly formatted + if isValidatorTx(req.Tx) { + if _, _, _, err := parseValidatorTx(req.Tx); err != nil { + //nolint:nilerr + return &types.ResponseCheckTx{Code: CodeTypeInvalidTxFormat}, nil + } + } else if !isValidTx(req.Tx) { + return &types.ResponseCheckTx{Code: CodeTypeInvalidTxFormat}, nil + } + + return &types.ResponseCheckTx{Code: CodeTypeOK, GasWanted: 1}, nil +} + +// Tx must have a format like key:value or key=value. That is: +// - it must have one and only one ":" or "=" +// - It must not begin or end with these special characters +func isValidTx(tx []byte) bool { + if bytes.Count(tx, []byte(":")) == 1 && bytes.Count(tx, []byte("=")) == 0 { + if !bytes.HasPrefix(tx, []byte(":")) && !bytes.HasSuffix(tx, []byte(":")) { + return true + } + } else if bytes.Count(tx, []byte("=")) == 1 && bytes.Count(tx, []byte(":")) == 0 { + if !bytes.HasPrefix(tx, []byte("=")) && !bytes.HasSuffix(tx, []byte("=")) { + return true + } + } + return false +} + +// PrepareProposal is called when the node is a proposer. CometBFT stages a set of transactions to the application. As the +// KVStore has two accepted formats, `:` and `=`, we modify all instances of `:` with `=` to make it consistent. Note: this is +// quite a trivial example of transaction modification. +// NOTE: we assume that CometBFT will never provide more transactions than can fit in a block. +func (app *Application) PrepareProposal(ctx context.Context, req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + return &types.ResponsePrepareProposal{Txs: app.formatTxs(ctx, req.Txs)}, nil +} + +// formatTxs validates and excludes invalid transactions +// also substitutes all the transactions with x:y to x=y +func (app *Application) formatTxs(ctx context.Context, blockData [][]byte) [][]byte { + txs := make([][]byte, 0, len(blockData)) + for _, tx := range blockData { + if resp, err := app.CheckTx(ctx, &types.RequestCheckTx{Tx: tx}); err == nil && resp.Code == CodeTypeOK { + txs = append(txs, bytes.Replace(tx, []byte(":"), []byte("="), 1)) + } + } + return txs +} + +// ProcessProposal is called whenever a node receives a complete proposal. It allows the application to validate the proposal. +// Only validators who can vote will have this method called. For the KVstore we reuse CheckTx. +func (app *Application) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + for _, tx := range req.Txs { + // As CheckTx is a full validity check we can simply reuse this + if resp, err := app.CheckTx(ctx, &types.RequestCheckTx{Tx: tx}); err != nil || resp.Code != CodeTypeOK { + return &types.ResponseProcessProposal{Status: types.ResponseProcessProposal_REJECT}, nil + } + } + return &types.ResponseProcessProposal{Status: types.ResponseProcessProposal_ACCEPT}, nil +} + +// FinalizeBlock executes the block against the application state. It punishes validators who equivocated and +// updates validators according to transactions in a block. The rest of the transactions are regular key value +// updates and are cached in memory and will be persisted once Commit is called. +// ConsensusParams are never changed. +func (app *Application) FinalizeBlock(_ context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + // reset valset changes + app.valUpdates = make([]types.ValidatorUpdate, 0) + app.stagedTxs = make([][]byte, 0) + + // Punish validators who committed equivocation. + for _, ev := range req.Misbehavior { + if ev.Type == types.MisbehaviorType_DUPLICATE_VOTE { + addr := string(ev.Validator.Address) + if pubKey, ok := app.valAddrToPubKeyMap[addr]; ok { + app.valUpdates = append(app.valUpdates, types.ValidatorUpdate{ + PubKey: pubKey, + Power: ev.Validator.Power - 1, + }) + app.logger.Info("Decreased val power by 1 because of the equivocation", + "val", addr) + } else { + panic(fmt.Errorf("wanted to punish val %q but can't find it", addr)) + } + } + } + + respTxs := make([]*types.ExecTxResult, len(req.Txs)) + for i, tx := range req.Txs { + if isValidatorTx(tx) { + keyType, pubKey, power, err := parseValidatorTx(tx) + if err != nil { + panic(err) + } + app.valUpdates = append(app.valUpdates, types.UpdateValidator(pubKey, power, keyType)) + } else { + app.stagedTxs = append(app.stagedTxs, tx) + } + + var key, value string + parts := bytes.Split(tx, []byte("=")) + if len(parts) == 2 { + key, value = string(parts[0]), string(parts[1]) + } else { + key, value = string(tx), string(tx) + } + respTxs[i] = &types.ExecTxResult{ + Code: CodeTypeOK, + // With every transaction we can emit a series of events. To make it simple, we just emit the same events. + Events: []types.Event{ + { + Type: "app", + Attributes: []types.EventAttribute{ + {Key: "creator", Value: "Cosmoshi Netowoko", Index: true}, + {Key: "key", Value: key, Index: true}, + {Key: "index_key", Value: "index is working", Index: true}, + {Key: "noindex_key", Value: "index is working", Index: false}, + }, + }, + { + Type: "app", + Attributes: []types.EventAttribute{ + {Key: "creator", Value: "Cosmoshi", Index: true}, + {Key: "key", Value: value, Index: true}, + {Key: "index_key", Value: "index is working", Index: true}, + {Key: "noindex_key", Value: "index is working", Index: false}, + }, + }, + }, + } + app.state.Size++ + } + + app.state.Height = req.Height + + response := &types.ResponseFinalizeBlock{TxResults: respTxs, ValidatorUpdates: app.valUpdates, AppHash: app.state.Hash()} + if !app.genBlockEvents { + return response, nil + } + if app.state.Height%2 == 0 { + response.Events = []types.Event{ + { + Type: "begin_event", + Attributes: []types.EventAttribute{ + { + Key: "foo", + Value: "100", + Index: true, + }, + { + Key: "bar", + Value: "200", + Index: true, + }, + }, + }, + { + Type: "begin_event", + Attributes: []types.EventAttribute{ + { + Key: "foo", + Value: "200", + Index: true, + }, + { + Key: "bar", + Value: "300", + Index: true, + }, + }, + }, + } + } else { + response.Events = []types.Event{ + { + Type: "begin_event", + Attributes: []types.EventAttribute{ + { + Key: "foo", + Value: "400", + Index: true, + }, + { + Key: "bar", + Value: "300", + Index: true, + }, + }, + }, + } + } + return response, nil +} + +// Commit is called after FinalizeBlock and after Tendermint state which includes the updates to +// AppHash, ConsensusParams and ValidatorSet has occurred. +// The KVStore persists the validator updates and the new key values +func (app *Application) Commit(context.Context, *types.RequestCommit) (*types.ResponseCommit, error) { + // apply the validator updates to state (note this is really the validator set at h + 2) + for _, valUpdate := range app.valUpdates { + app.updateValidator(valUpdate) + } + + // persist all the staged txs in the kvstore + for _, tx := range app.stagedTxs { + parts := bytes.Split(tx, []byte("=")) + if len(parts) != 2 { + panic(fmt.Sprintf("unexpected tx format. Expected 2 got %d: %s", len(parts), parts)) + } + key, value := string(parts[0]), string(parts[1]) + err := app.state.db.Set(prefixKey([]byte(key)), []byte(value)) + if err != nil { + panic(err) + } + } + + // persist the state (i.e. size and height) + saveState(app.state) + + resp := &types.ResponseCommit{} + if app.RetainBlocks > 0 && app.state.Height >= app.RetainBlocks { + resp.RetainHeight = app.state.Height - app.RetainBlocks + 1 + } + return resp, nil +} + +// Returns an associated value or nil if missing. +func (app *Application) Query(_ context.Context, reqQuery *types.RequestQuery) (*types.ResponseQuery, error) { + resQuery := &types.ResponseQuery{} + + if reqQuery.Path == "/val" { + key := []byte(ValidatorPrefix + string(reqQuery.Data)) + value, err := app.state.db.Get(key) + if err != nil { + panic(err) + } + + return &types.ResponseQuery{ + Key: reqQuery.Data, + Value: value, + }, nil + } + + if reqQuery.Prove { + value, err := app.state.db.Get(prefixKey(reqQuery.Data)) + if err != nil { + panic(err) + } + + if value == nil { + resQuery.Log = "does not exist" + } else { + resQuery.Log = "exists" + } + resQuery.Index = -1 // TODO make Proof return index + resQuery.Key = reqQuery.Data + resQuery.Value = value + resQuery.Height = app.state.Height + + return resQuery, nil + } + + resQuery.Key = reqQuery.Data + value, err := app.state.db.Get(prefixKey(reqQuery.Data)) + if err != nil { + panic(err) + } + if value == nil { + resQuery.Log = "does not exist" + } else { + resQuery.Log = "exists" + } + resQuery.Value = value + resQuery.Height = app.state.Height + + return resQuery, nil +} + +func (app *Application) Close() error { + return app.state.db.Close() +} + +func isValidatorTx(tx []byte) bool { + return strings.HasPrefix(string(tx), ValidatorPrefix) +} + +func parseValidatorTx(tx []byte) (string, []byte, int64, error) { + tx = tx[len(ValidatorPrefix):] + + // get the pubkey and power + typePubKeyAndPower := strings.Split(string(tx), "!") + if len(typePubKeyAndPower) != 3 { + return "", nil, 0, fmt.Errorf("expected 'pubkeytype!pubkey!power'. Got %v", typePubKeyAndPower) + } + keyType, pubkeyS, powerS := typePubKeyAndPower[0], typePubKeyAndPower[1], typePubKeyAndPower[2] + + // decode the pubkey + pubkey, err := base64.StdEncoding.DecodeString(pubkeyS) + if err != nil { + return "", nil, 0, fmt.Errorf("pubkey (%s) is invalid base64", pubkeyS) + } + + // decode the power + power, err := strconv.ParseInt(powerS, 10, 64) + if err != nil { + return "", nil, 0, fmt.Errorf("power (%s) is not an int", powerS) + } + + if power < 0 { + return "", nil, 0, fmt.Errorf("power can not be less than 0, got %d", power) + } + + return keyType, pubkey, power, nil +} + +// add, update, or remove a validator +func (app *Application) updateValidator(v types.ValidatorUpdate) { + pubkey, err := cryptoencoding.PubKeyFromProto(v.PubKey) + if err != nil { + panic(fmt.Errorf("can't decode public key: %w", err)) + } + key := []byte(ValidatorPrefix + string(pubkey.Bytes())) + + if v.Power == 0 { + // remove validator + hasKey, err := app.state.db.Has(key) + if err != nil { + panic(err) + } + if !hasKey { + pubStr := base64.StdEncoding.EncodeToString(pubkey.Bytes()) + app.logger.Info("tried to remove non existent validator. Skipping...", "pubKey", pubStr) + } + if err = app.state.db.Delete(key); err != nil { + panic(err) + } + delete(app.valAddrToPubKeyMap, string(pubkey.Address())) + } else { + // add or update validator + value := bytes.NewBuffer(make([]byte, 0)) + if err := types.WriteMessage(&v, value); err != nil { + panic(err) + } + if err = app.state.db.Set(key, value.Bytes()); err != nil { + panic(err) + } + app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey + } +} + +func (app *Application) getValidators() (validators []types.ValidatorUpdate) { + itr, err := app.state.db.Iterator(nil, nil) + if err != nil { + panic(err) + } + for ; itr.Valid(); itr.Next() { + if isValidatorTx(itr.Key()) { + validator := new(types.ValidatorUpdate) + err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator) + if err != nil { + panic(err) + } + validators = append(validators, *validator) + } + } + if err = itr.Error(); err != nil { + panic(err) + } + return +} + +// ----------------------------- + +type State struct { + db dbm.DB + // Size is essentially the amount of transactions that have been processes. + // This is used for the appHash + Size int64 `json:"size"` + Height int64 `json:"height"` +} + +func loadState(db dbm.DB) State { + var state State + state.db = db + stateBytes, err := db.Get(stateKey) + if err != nil { + panic(err) + } + if len(stateBytes) == 0 { + return state + } + err = json.Unmarshal(stateBytes, &state) + if err != nil { + panic(err) + } + return state +} + +func saveState(state State) { + stateBytes, err := json.Marshal(state) + if err != nil { + panic(err) + } + err = state.db.Set(stateKey, stateBytes) + if err != nil { + panic(err) + } +} + +// Hash returns the hash of the application state. This is computed +// as the size or number of transactions processed within the state. Note that this isn't +// a strong guarantee of state machine replication because states could +// have different kv values but still have the same size. +// This function is used as the "AppHash" +func (s State) Hash() []byte { + appHash := make([]byte, 8) + binary.PutVarint(appHash, s.Size) + return appHash +} + +func prefixKey(key []byte) []byte { + return append(kvPairPrefixKey, key...) +} diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go new file mode 100644 index 0000000..e87c90b --- /dev/null +++ b/abci/example/kvstore/kvstore_test.go @@ -0,0 +1,337 @@ +package kvstore + +import ( + "context" + "fmt" + "sort" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + + abcicli "github.com/cometbft/cometbft/abci/client" + abciserver "github.com/cometbft/cometbft/abci/server" + "github.com/cometbft/cometbft/abci/types" +) + +const ( + testKey = "abc" + testValue = "def" +) + +func TestKVStoreKV(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + kvstore := NewInMemoryApplication() + tx := []byte(testKey + ":" + testValue) + testKVStore(ctx, t, kvstore, tx, testKey, testValue) + tx = []byte(testKey + "=" + testValue) + testKVStore(ctx, t, kvstore, tx, testKey, testValue) +} + +func testKVStore(ctx context.Context, t *testing.T, app types.Application, tx []byte, key, value string) { + checkTxResp, err := app.CheckTx(ctx, &types.RequestCheckTx{Tx: tx}) + require.NoError(t, err) + require.Equal(t, uint32(0), checkTxResp.Code) + + ppResp, err := app.PrepareProposal(ctx, &types.RequestPrepareProposal{Txs: [][]byte{tx}}) + require.NoError(t, err) + require.Len(t, ppResp.Txs, 1) + req := &types.RequestFinalizeBlock{Height: 1, Txs: ppResp.Txs} + ar, err := app.FinalizeBlock(ctx, req) + require.NoError(t, err) + require.Equal(t, 1, len(ar.TxResults)) + require.False(t, ar.TxResults[0].IsErr()) + // commit + _, err = app.Commit(ctx, &types.RequestCommit{}) + require.NoError(t, err) + + info, err := app.Info(ctx, &types.RequestInfo{}) + require.NoError(t, err) + require.NotZero(t, info.LastBlockHeight) + + // make sure query is fine + resQuery, err := app.Query(ctx, &types.RequestQuery{ + Path: "/store", + Data: []byte(key), + }) + require.NoError(t, err) + require.Equal(t, CodeTypeOK, resQuery.Code) + require.Equal(t, key, string(resQuery.Key)) + require.Equal(t, value, string(resQuery.Value)) + require.EqualValues(t, info.LastBlockHeight, resQuery.Height) + + // make sure proof is fine + resQuery, err = app.Query(ctx, &types.RequestQuery{ + Path: "/store", + Data: []byte(key), + Prove: true, + }) + require.NoError(t, err) + require.EqualValues(t, CodeTypeOK, resQuery.Code) + require.Equal(t, key, string(resQuery.Key)) + require.Equal(t, value, string(resQuery.Value)) + require.EqualValues(t, info.LastBlockHeight, resQuery.Height) +} + +func TestPersistentKVStoreEmptyTX(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + kvstore := NewPersistentApplication(t.TempDir()) + tx := []byte("") + reqCheck := types.RequestCheckTx{Tx: tx} + resCheck, err := kvstore.CheckTx(ctx, &reqCheck) + require.NoError(t, err) + require.Equal(t, resCheck.Code, CodeTypeInvalidTxFormat) + + txs := make([][]byte, 0, 4) + txs = append(txs, []byte("key=value"), []byte("key:val"), []byte(""), []byte("kee=value")) + reqPrepare := types.RequestPrepareProposal{Txs: txs, MaxTxBytes: 10 * 1024} + resPrepare, err := kvstore.PrepareProposal(ctx, &reqPrepare) + require.NoError(t, err) + require.Equal(t, len(reqPrepare.Txs)-1, len(resPrepare.Txs), "Empty transaction not properly removed") +} + +func TestPersistentKVStoreKV(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + kvstore := NewPersistentApplication(t.TempDir()) + key := testKey + value := testValue + testKVStore(ctx, t, kvstore, NewTx(key, value), key, value) +} + +func TestPersistentKVStoreInfo(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + kvstore := NewPersistentApplication(t.TempDir()) + require.NoError(t, InitKVStore(ctx, kvstore)) + height := int64(0) + + resInfo, err := kvstore.Info(ctx, &types.RequestInfo{}) + require.NoError(t, err) + if resInfo.LastBlockHeight != height { + t.Fatalf("expected height of %d, got %d", height, resInfo.LastBlockHeight) + } + + // make and apply block + height = int64(1) + hash := []byte("foo") + if _, err := kvstore.FinalizeBlock(ctx, &types.RequestFinalizeBlock{Hash: hash, Height: height}); err != nil { + t.Fatal(err) + } + + _, err = kvstore.Commit(ctx, &types.RequestCommit{}) + require.NoError(t, err) + + resInfo, err = kvstore.Info(ctx, &types.RequestInfo{}) + require.NoError(t, err) + require.Equal(t, height, resInfo.LastBlockHeight) +} + +// add a validator, remove a validator, update a validator +func TestValUpdates(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + kvstore := NewInMemoryApplication() + + // init with some validators + total := 10 + nInit := 5 + vals := RandVals(total) + // initialize with the first nInit + _, err := kvstore.InitChain(ctx, &types.RequestInitChain{ + Validators: vals[:nInit], + }) + require.NoError(t, err) + + vals1, vals2 := vals[:nInit], kvstore.getValidators() + valsEqual(t, vals1, vals2) + + var v1, v2, v3 types.ValidatorUpdate + + // add some validators + v1, v2 = vals[nInit], vals[nInit+1] + diff := []types.ValidatorUpdate{v1, v2} + tx1 := MakeValSetChangeTx(v1.PubKey, v1.Power) + tx2 := MakeValSetChangeTx(v2.PubKey, v2.Power) + + makeApplyBlock(ctx, t, kvstore, 1, diff, tx1, tx2) + + vals1, vals2 = vals[:nInit+2], kvstore.getValidators() + valsEqual(t, vals1, vals2) + + // remove some validators + v1, v2, v3 = vals[nInit-2], vals[nInit-1], vals[nInit] + v1.Power = 0 + v2.Power = 0 + v3.Power = 0 + diff = []types.ValidatorUpdate{v1, v2, v3} + tx1 = MakeValSetChangeTx(v1.PubKey, v1.Power) + tx2 = MakeValSetChangeTx(v2.PubKey, v2.Power) + tx3 := MakeValSetChangeTx(v3.PubKey, v3.Power) + + makeApplyBlock(ctx, t, kvstore, 2, diff, tx1, tx2, tx3) + + vals1 = append(vals[:nInit-2], vals[nInit+1]) //nolint: gocritic + vals2 = kvstore.getValidators() + valsEqual(t, vals1, vals2) + + // update some validators + v1 = vals[0] + if v1.Power == 5 { + v1.Power = 6 + } else { + v1.Power = 5 + } + diff = []types.ValidatorUpdate{v1} + tx1 = MakeValSetChangeTx(v1.PubKey, v1.Power) + + makeApplyBlock(ctx, t, kvstore, 3, diff, tx1) + + vals1 = append([]types.ValidatorUpdate{v1}, vals1[1:]...) + vals2 = kvstore.getValidators() + valsEqual(t, vals1, vals2) +} + +func TestCheckTx(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + kvstore := NewInMemoryApplication() + + val := RandVal() + + testCases := []struct { + expCode uint32 + tx []byte + }{ + {CodeTypeOK, NewTx("hello", "world")}, + {CodeTypeInvalidTxFormat, []byte("hello")}, + {CodeTypeOK, []byte("space:jam")}, + {CodeTypeInvalidTxFormat, []byte("=hello")}, + {CodeTypeInvalidTxFormat, []byte("hello=")}, + {CodeTypeOK, []byte("a=b")}, + {CodeTypeInvalidTxFormat, []byte("val=hello")}, + {CodeTypeInvalidTxFormat, []byte("val=hi!5")}, + {CodeTypeOK, MakeValSetChangeTx(val.PubKey, 10)}, + } + + for idx, tc := range testCases { + resp, err := kvstore.CheckTx(ctx, &types.RequestCheckTx{Tx: tc.tx}) + require.NoError(t, err, idx) + fmt.Println(string(tc.tx)) + require.Equal(t, tc.expCode, resp.Code, idx) + } +} + +func TestClientServer(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // set up socket app + kvstore := NewInMemoryApplication() + client, _, err := makeClientServer(t, kvstore, "kvstore-socket", "socket") + require.NoError(t, err) + runClientTests(ctx, t, client) + + // set up grpc app + kvstore = NewInMemoryApplication() + gclient, _, err := makeClientServer(t, kvstore, t.TempDir(), "grpc") + require.NoError(t, err) + runClientTests(ctx, t, gclient) +} + +func makeApplyBlock( + ctx context.Context, + t *testing.T, + kvstore types.Application, + heightInt int, + diff []types.ValidatorUpdate, + txs ...[]byte, +) { + // make and apply block + height := int64(heightInt) + hash := []byte("foo") + resFinalizeBlock, err := kvstore.FinalizeBlock(ctx, &types.RequestFinalizeBlock{ + Hash: hash, + Height: height, + Txs: txs, + }) + require.NoError(t, err) + + _, err = kvstore.Commit(ctx, &types.RequestCommit{}) + require.NoError(t, err) + + valsEqual(t, diff, resFinalizeBlock.ValidatorUpdates) +} + +// order doesn't matter +func valsEqual(t *testing.T, vals1, vals2 []types.ValidatorUpdate) { + t.Helper() + if len(vals1) != len(vals2) { + t.Fatalf("vals dont match in len. got %d, expected %d", len(vals2), len(vals1)) + } + sort.Sort(types.ValidatorUpdates(vals1)) + sort.Sort(types.ValidatorUpdates(vals2)) + for i, v1 := range vals1 { + v2 := vals2[i] + if !v1.PubKey.Equal(v2.PubKey) || + v1.Power != v2.Power { + t.Fatalf("vals dont match at index %d. got %X/%d , expected %X/%d", i, v2.PubKey, v2.Power, v1.PubKey, v1.Power) + } + } +} + +func makeClientServer(t *testing.T, app types.Application, name, transport string) (abcicli.Client, service.Service, error) { + // Start the listener + addr := fmt.Sprintf("unix://%s.sock", name) + logger := log.TestingLogger() + + server, err := abciserver.NewServer(addr, transport, app) + require.NoError(t, err) + server.SetLogger(logger.With("module", "abci-server")) + if err := server.Start(); err != nil { + return nil, nil, err + } + + t.Cleanup(func() { + if err := server.Stop(); err != nil { + t.Error(err) + } + }) + + // Connect to the client + client, err := abcicli.NewClient(addr, transport, false) + require.NoError(t, err) + client.SetLogger(logger.With("module", "abci-client")) + if err := client.Start(); err != nil { + return nil, nil, err + } + + t.Cleanup(func() { + if err := client.Stop(); err != nil { + t.Error(err) + } + }) + + return client, server, nil +} + +func runClientTests(ctx context.Context, t *testing.T, client abcicli.Client) { + // run some tests.... + tx := []byte(testKey + ":" + testValue) + testKVStore(ctx, t, client, tx, testKey, testValue) + tx = []byte(testKey + "=" + testValue) + testKVStore(ctx, t, client, tx, testKey, testValue) +} + +func TestTxGeneration(t *testing.T) { + require.Len(t, NewRandomTx(20), 20) + require.Len(t, NewRandomTxs(10), 10) +} diff --git a/abci/server/grpc_server.go b/abci/server/grpc_server.go new file mode 100644 index 0000000..6dd9750 --- /dev/null +++ b/abci/server/grpc_server.go @@ -0,0 +1,76 @@ +package server + +import ( + "context" + "net" + + "google.golang.org/grpc" + + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/libs/service" +) + +type GRPCServer struct { + service.BaseService + + proto string + addr string + listener net.Listener + server *grpc.Server + + app types.Application +} + +// NewGRPCServer returns a new gRPC ABCI server +func NewGRPCServer(protoAddr string, app types.Application) service.Service { + proto, addr := cmtnet.ProtocolAndAddress(protoAddr) + s := &GRPCServer{ + proto: proto, + addr: addr, + listener: nil, + app: app, + } + s.BaseService = *service.NewBaseService(nil, "ABCIServer", s) + return s +} + +// OnStart starts the gRPC service. +func (s *GRPCServer) OnStart() error { + ln, err := net.Listen(s.proto, s.addr) + if err != nil { + return err + } + + s.listener = ln + s.server = grpc.NewServer() + types.RegisterABCIServer(s.server, &gRPCApplication{s.app}) + + s.Logger.Info("Listening", "proto", s.proto, "addr", s.addr) + go func() { + if err := s.server.Serve(s.listener); err != nil { + s.Logger.Error("Error serving gRPC server", "err", err) + } + }() + return nil +} + +// OnStop stops the gRPC server. +func (s *GRPCServer) OnStop() { + s.server.Stop() +} + +//------------------------------------------------------- + +// gRPCApplication is a gRPC shim for Application +type gRPCApplication struct { + types.Application +} + +func (app *gRPCApplication) Echo(_ context.Context, req *types.RequestEcho) (*types.ResponseEcho, error) { + return &types.ResponseEcho{Message: req.Message}, nil +} + +func (app *gRPCApplication) Flush(context.Context, *types.RequestFlush) (*types.ResponseFlush, error) { + return &types.ResponseFlush{}, nil +} diff --git a/abci/server/server.go b/abci/server/server.go new file mode 100644 index 0000000..f6c2584 --- /dev/null +++ b/abci/server/server.go @@ -0,0 +1,31 @@ +/* +Package server is used to start a new ABCI server. + +It contains two server implementation: + - gRPC server + - socket server +*/ +package server + +import ( + "fmt" + + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/service" +) + +// NewServer is a utility function for out of process applications to set up either a socket or +// grpc server that can listen to requests from the equivalent Tendermint client +func NewServer(protoAddr, transport string, app types.Application) (service.Service, error) { + var s service.Service + var err error + switch transport { + case "socket": + s = NewSocketServer(protoAddr, app) + case "grpc": + s = NewGRPCServer(protoAddr, app) + default: + err = fmt.Errorf("unknown server type %s", transport) + } + return s, err +} diff --git a/abci/server/socket_server.go b/abci/server/socket_server.go new file mode 100644 index 0000000..d33a3f6 --- /dev/null +++ b/abci/server/socket_server.go @@ -0,0 +1,335 @@ +package server + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net" + "os" + "runtime" + + "github.com/cometbft/cometbft/abci/types" + cmtlog "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// SocketServer is the server-side implementation of the TSP (Tendermint Socket Protocol) +// for out-of-process go applications. Note, in the case of an application written in golang, +// the developer may also run both Tendermint and the application within the same process. +// +// The socket server deliver +type SocketServer struct { + service.BaseService + isLoggerSet bool + + proto string + addr string + listener net.Listener + + connsMtx cmtsync.Mutex + conns map[int]net.Conn + nextConnID int + + appMtx cmtsync.Mutex + app types.Application +} + +const responseBufferSize = 1000 + +// NewSocketServer creates a server from a golang-based out-of-process application. +func NewSocketServer(protoAddr string, app types.Application) service.Service { + proto, addr := cmtnet.ProtocolAndAddress(protoAddr) + s := &SocketServer{ + proto: proto, + addr: addr, + listener: nil, + app: app, + conns: make(map[int]net.Conn), + } + s.BaseService = *service.NewBaseService(nil, "ABCIServer", s) + return s +} + +func (s *SocketServer) SetLogger(l cmtlog.Logger) { + s.BaseService.SetLogger(l) + s.isLoggerSet = true +} + +func (s *SocketServer) OnStart() error { + ln, err := net.Listen(s.proto, s.addr) + if err != nil { + return err + } + + s.listener = ln + go s.acceptConnectionsRoutine() + + return nil +} + +func (s *SocketServer) OnStop() { + if err := s.listener.Close(); err != nil { + s.Logger.Error("Error closing listener", "err", err) + } + + s.connsMtx.Lock() + defer s.connsMtx.Unlock() + for id, conn := range s.conns { + delete(s.conns, id) + if err := conn.Close(); err != nil { + s.Logger.Error("Error closing connection", "id", id, "conn", conn, "err", err) + } + } +} + +func (s *SocketServer) addConn(conn net.Conn) int { + s.connsMtx.Lock() + defer s.connsMtx.Unlock() + + connID := s.nextConnID + s.nextConnID++ + s.conns[connID] = conn + + return connID +} + +// deletes conn even if close errs +func (s *SocketServer) rmConn(connID int) error { + s.connsMtx.Lock() + defer s.connsMtx.Unlock() + + conn, ok := s.conns[connID] + if !ok { + return fmt.Errorf("connection %d does not exist", connID) + } + + delete(s.conns, connID) + return conn.Close() +} + +func (s *SocketServer) acceptConnectionsRoutine() { + for { + // Accept a connection + s.Logger.Info("Waiting for new connection...") + conn, err := s.listener.Accept() + if err != nil { + if !s.IsRunning() { + return // Ignore error from listener closing. + } + s.Logger.Error("Failed to accept connection", "err", err) + continue + } + + s.Logger.Info("Accepted a new connection") + + connID := s.addConn(conn) + + closeConn := make(chan error, 2) // Push to signal connection closed + responses := make(chan *types.Response, responseBufferSize) // A channel to buffer responses + + // Read requests from conn and deal with them + go s.handleRequests(closeConn, conn, responses) + // Pull responses from 'responses' and write them to conn. + go s.handleResponses(closeConn, conn, responses) + + // Wait until signal to close connection + go s.waitForClose(closeConn, connID) + } +} + +func (s *SocketServer) waitForClose(closeConn chan error, connID int) { + err := <-closeConn + switch { + case err == io.EOF: + s.Logger.Error("Connection was closed by client") + case err != nil: + s.Logger.Error("Connection error", "err", err) + default: + // never happens + s.Logger.Error("Connection was closed") + } + + // Close the connection + if err := s.rmConn(connID); err != nil { + s.Logger.Error("Error closing connection", "err", err) + } +} + +// Read requests from conn and deal with them +func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, responses chan<- *types.Response) { + var count int + var bufReader = bufio.NewReader(conn) + + defer func() { + // make sure to recover from any app-related panics to allow proper socket cleanup. + // In the case of a panic, we do not notify the client by passing an exception so + // presume that the client is still running and retying to connect + r := recover() + if r != nil { + const size = 64 << 10 + buf := make([]byte, size) + buf = buf[:runtime.Stack(buf, false)] + err := fmt.Errorf("recovered from panic: %v\n%s", r, buf) + if !s.isLoggerSet { + fmt.Fprintln(os.Stderr, err) + } + closeConn <- err + s.appMtx.Unlock() + } + }() + + for { + + var req = &types.Request{} + err := types.ReadMessage(bufReader, req) + if err != nil { + if err == io.EOF { + closeConn <- err + } else { + closeConn <- fmt.Errorf("error reading message: %w", err) + } + return + } + s.appMtx.Lock() + count++ + resp, err := s.handleRequest(context.TODO(), req) + if err != nil { + // any error either from the application or because of an unknown request + // throws an exception back to the client. This will stop the server and + // should also halt the client. + responses <- types.ToResponseException(err.Error()) + } else { + responses <- resp + } + s.appMtx.Unlock() + } +} + +// handleRequests takes a request and calls the application passing the returned +func (s *SocketServer) handleRequest(ctx context.Context, req *types.Request) (*types.Response, error) { + switch r := req.Value.(type) { + case *types.Request_Echo: + return types.ToResponseEcho(r.Echo.Message), nil + case *types.Request_Flush: + return types.ToResponseFlush(), nil + case *types.Request_Info: + res, err := s.app.Info(ctx, r.Info) + if err != nil { + return nil, err + } + return types.ToResponseInfo(res), nil + case *types.Request_CheckTx: + res, err := s.app.CheckTx(ctx, r.CheckTx) + if err != nil { + return nil, err + } + return types.ToResponseCheckTx(res), nil + case *types.Request_Commit: + res, err := s.app.Commit(ctx, r.Commit) + if err != nil { + return nil, err + } + return types.ToResponseCommit(res), nil + case *types.Request_Query: + res, err := s.app.Query(ctx, r.Query) + if err != nil { + return nil, err + } + return types.ToResponseQuery(res), nil + case *types.Request_InitChain: + res, err := s.app.InitChain(ctx, r.InitChain) + if err != nil { + return nil, err + } + return types.ToResponseInitChain(res), nil + case *types.Request_FinalizeBlock: + res, err := s.app.FinalizeBlock(ctx, r.FinalizeBlock) + if err != nil { + return nil, err + } + return types.ToResponseFinalizeBlock(res), nil + case *types.Request_ListSnapshots: + res, err := s.app.ListSnapshots(ctx, r.ListSnapshots) + if err != nil { + return nil, err + } + return types.ToResponseListSnapshots(res), nil + case *types.Request_OfferSnapshot: + res, err := s.app.OfferSnapshot(ctx, r.OfferSnapshot) + if err != nil { + return nil, err + } + return types.ToResponseOfferSnapshot(res), nil + case *types.Request_PrepareProposal: + res, err := s.app.PrepareProposal(ctx, r.PrepareProposal) + if err != nil { + return nil, err + } + return types.ToResponsePrepareProposal(res), nil + case *types.Request_ProcessProposal: + res, err := s.app.ProcessProposal(ctx, r.ProcessProposal) + if err != nil { + return nil, err + } + return types.ToResponseProcessProposal(res), nil + case *types.Request_LoadSnapshotChunk: + res, err := s.app.LoadSnapshotChunk(ctx, r.LoadSnapshotChunk) + if err != nil { + return nil, err + } + return types.ToResponseLoadSnapshotChunk(res), nil + case *types.Request_ApplySnapshotChunk: + res, err := s.app.ApplySnapshotChunk(ctx, r.ApplySnapshotChunk) + if err != nil { + return nil, err + } + return types.ToResponseApplySnapshotChunk(res), nil + case *types.Request_ExtendVote: + res, err := s.app.ExtendVote(ctx, r.ExtendVote) + if err != nil { + return nil, err + } + return types.ToResponseExtendVote(res), nil + case *types.Request_VerifyVoteExtension: + res, err := s.app.VerifyVoteExtension(ctx, r.VerifyVoteExtension) + if err != nil { + return nil, err + } + return types.ToResponseVerifyVoteExtension(res), nil + default: + return nil, fmt.Errorf("unknown request from client: %T", req) + } +} + +// Pull responses from 'responses' and write them to conn. +func (s *SocketServer) handleResponses(closeConn chan error, conn io.Writer, responses <-chan *types.Response) { + var count int + var bufWriter = bufio.NewWriter(conn) + for { + var res = <-responses + err := types.WriteMessage(res, bufWriter) + if err != nil { + closeConn <- fmt.Errorf("error writing message: %w", err) + return + } + if _, ok := res.Value.(*types.Response_Flush); ok { + err = bufWriter.Flush() + if err != nil { + closeConn <- fmt.Errorf("error flushing write buffer: %w", err) + return + } + } + + // If the application has responded with an exception, the server returns the error + // back to the client and closes the connection. The receiving Tendermint client should + // log the error and gracefully terminate + if e, ok := res.Value.(*types.Response_Exception); ok { + closeConn <- errors.New(e.Exception.Error) + } + count++ + } +} diff --git a/abci/tests/benchmarks/blank.go b/abci/tests/benchmarks/blank.go new file mode 100644 index 0000000..9798caa --- /dev/null +++ b/abci/tests/benchmarks/blank.go @@ -0,0 +1 @@ +package benchmarks diff --git a/abci/tests/benchmarks/parallel/parallel.go b/abci/tests/benchmarks/parallel/parallel.go new file mode 100644 index 0000000..5834651 --- /dev/null +++ b/abci/tests/benchmarks/parallel/parallel.go @@ -0,0 +1,55 @@ +package main + +import ( + "bufio" + "fmt" + "log" + + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/libs/net" +) + +func main() { + + conn, err := cmtnet.Connect("unix://test.sock") + if err != nil { + log.Fatal(err.Error()) + } + + // Read a bunch of responses + go func() { + counter := 0 + for { + var res = &types.Response{} + err := types.ReadMessage(conn, res) + if err != nil { + log.Fatal(err.Error()) + } + counter++ + if counter%1000 == 0 { + fmt.Println("Read", counter) + } + } + }() + + // Write a bunch of requests + counter := 0 + for i := 0; ; i++ { + var bufWriter = bufio.NewWriter(conn) + var req = types.ToRequestEcho("foobar") + + err := types.WriteMessage(req, bufWriter) + if err != nil { + log.Fatal(err.Error()) + } + err = bufWriter.Flush() + if err != nil { + log.Fatal(err.Error()) + } + + counter++ + if counter%1000 == 0 { + fmt.Println("Write", counter) + } + } +} diff --git a/abci/tests/benchmarks/simple/simple.go b/abci/tests/benchmarks/simple/simple.go new file mode 100644 index 0000000..13b9747 --- /dev/null +++ b/abci/tests/benchmarks/simple/simple.go @@ -0,0 +1,69 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "log" + "reflect" + + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/libs/net" +) + +func main() { + + conn, err := cmtnet.Connect("unix://test.sock") + if err != nil { + log.Fatal(err.Error()) + } + + // Make a bunch of requests + counter := 0 + for i := 0; ; i++ { + req := types.ToRequestEcho("foobar") + _, err := makeRequest(conn, req) + if err != nil { + log.Fatal(err.Error()) + } + counter++ + if counter%1000 == 0 { + fmt.Println(counter) + } + } +} + +func makeRequest(conn io.ReadWriter, req *types.Request) (*types.Response, error) { + var bufWriter = bufio.NewWriter(conn) + + // Write desired request + err := types.WriteMessage(req, bufWriter) + if err != nil { + return nil, err + } + err = types.WriteMessage(types.ToRequestFlush(), bufWriter) + if err != nil { + return nil, err + } + err = bufWriter.Flush() + if err != nil { + return nil, err + } + + // Read desired response + var res = &types.Response{} + err = types.ReadMessage(conn, res) + if err != nil { + return nil, err + } + var resFlush = &types.Response{} + err = types.ReadMessage(conn, resFlush) + if err != nil { + return nil, err + } + if _, ok := resFlush.Value.(*types.Response_Flush); !ok { + return nil, fmt.Errorf("expected flush response but got something else: %v", reflect.TypeOf(resFlush)) + } + + return res, nil +} diff --git a/abci/tests/client_server_test.go b/abci/tests/client_server_test.go new file mode 100644 index 0000000..e5229b3 --- /dev/null +++ b/abci/tests/client_server_test.go @@ -0,0 +1,39 @@ +package tests + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + abciclient "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + abciserver "github.com/cometbft/cometbft/abci/server" +) + +func TestClientServerNoAddrPrefix(t *testing.T) { + t.Helper() + + addr := "localhost:26658" + transport := "socket" + app := kvstore.NewInMemoryApplication() + + server, err := abciserver.NewServer(addr, transport, app) + assert.NoError(t, err, "expected no error on NewServer") + err = server.Start() + assert.NoError(t, err, "expected no error on server.Start") + t.Cleanup(func() { + if err := server.Stop(); err != nil { + t.Error(err) + } + }) + + client, err := abciclient.NewClient(addr, transport, true) + assert.NoError(t, err, "expected no error on NewClient") + err = client.Start() + assert.NoError(t, err, "expected no error on client.Start") + t.Cleanup(func() { + if err := client.Stop(); err != nil { + t.Error(err) + } + }) +} diff --git a/abci/tests/server/client.go b/abci/tests/server/client.go new file mode 100644 index 0000000..166e330 --- /dev/null +++ b/abci/tests/server/client.go @@ -0,0 +1,114 @@ +package testsuite + +import ( + "bytes" + "context" + "errors" + "fmt" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/types" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func InitChain(ctx context.Context, client abcicli.Client) error { + total := 10 + vals := make([]types.ValidatorUpdate, total) + for i := 0; i < total; i++ { + pubkey := cmtrand.Bytes(33) + power := cmtrand.Int() + vals[i] = types.UpdateValidator(pubkey, int64(power), "") + } + _, err := client.InitChain(ctx, &types.RequestInitChain{ + Validators: vals, + }) + if err != nil { + fmt.Printf("Failed test: InitChain - %v\n", err) + return err + } + fmt.Println("Passed test: InitChain") + return nil +} + +func Commit(ctx context.Context, client abcicli.Client) error { + _, err := client.Commit(ctx, &types.RequestCommit{}) + if err != nil { + fmt.Println("Failed test: Commit") + fmt.Printf("error while committing: %v\n", err) + return err + } + fmt.Println("Passed test: Commit") + return nil +} + +func FinalizeBlock(ctx context.Context, client abcicli.Client, txBytes [][]byte, codeExp []uint32, dataExp []byte, hashExp []byte) error { + res, _ := client.FinalizeBlock(ctx, &types.RequestFinalizeBlock{Txs: txBytes}) + appHash := res.AppHash + for i, tx := range res.TxResults { + code, data, log := tx.Code, tx.Data, tx.Log + if code != codeExp[i] { + fmt.Println("Failed test: FinalizeBlock") + fmt.Printf("FinalizeBlock response code was unexpected. Got %v expected %v. Log: %v\n", + code, codeExp, log) + return errors.New("FinalizeBlock error") + } + if !bytes.Equal(data, dataExp) { + fmt.Println("Failed test: FinalizeBlock") + fmt.Printf("FinalizeBlock response data was unexpected. Got %X expected %X\n", + data, dataExp) + return errors.New("FinalizeBlock error") + } + } + if !bytes.Equal(appHash, hashExp) { + fmt.Println("Failed test: FinalizeBlock") + fmt.Printf("Application hash was unexpected. Got %X expected %X\n", appHash, hashExp) + return errors.New("FinalizeBlock error") + } + fmt.Println("Passed test: FinalizeBlock") + return nil +} + +func PrepareProposal(ctx context.Context, client abcicli.Client, txBytes [][]byte, txExpected [][]byte, _ []byte) error { + res, _ := client.PrepareProposal(ctx, &types.RequestPrepareProposal{Txs: txBytes}) + for i, tx := range res.Txs { + if !bytes.Equal(tx, txExpected[i]) { + fmt.Println("Failed test: PrepareProposal") + fmt.Printf("PrepareProposal transaction was unexpected. Got %x expected %x.", + tx, txExpected[i]) + return errors.New("PrepareProposal error") + } + } + fmt.Println("Passed test: PrepareProposal") + return nil +} + +func ProcessProposal(ctx context.Context, client abcicli.Client, txBytes [][]byte, statusExp types.ResponseProcessProposal_ProposalStatus) error { + res, _ := client.ProcessProposal(ctx, &types.RequestProcessProposal{Txs: txBytes}) + if res.Status != statusExp { + fmt.Println("Failed test: ProcessProposal") + fmt.Printf("ProcessProposal response status was unexpected. Got %v expected %v.", + res.Status, statusExp) + return errors.New("ProcessProposal error") + } + fmt.Println("Passed test: ProcessProposal") + return nil +} + +func CheckTx(ctx context.Context, client abcicli.Client, txBytes []byte, codeExp uint32, dataExp []byte) error { + res, _ := client.CheckTx(ctx, &types.RequestCheckTx{Tx: txBytes}) + code, data, log := res.Code, res.Data, res.Log + if code != codeExp { + fmt.Println("Failed test: CheckTx") + fmt.Printf("CheckTx response code was unexpected. Got %v expected %v. Log: %v\n", + code, codeExp, log) + return errors.New("checkTx") + } + if !bytes.Equal(data, dataExp) { + fmt.Println("Failed test: CheckTx") + fmt.Printf("CheckTx response data was unexpected. Got %X expected %X\n", + data, dataExp) + return errors.New("checkTx") + } + fmt.Println("Passed test: CheckTx") + return nil +} diff --git a/abci/tests/test_cli/ex1.abci b/abci/tests/test_cli/ex1.abci new file mode 100644 index 0000000..f184c36 --- /dev/null +++ b/abci/tests/test_cli/ex1.abci @@ -0,0 +1,13 @@ +echo hello +info +prepare_proposal "abc=123" +process_proposal "abc==456" +process_proposal "abc=123" +finalize_block "abc=123" +commit +info +query "abc" +finalize_block "def=xyz" "ghi=123" +commit +query "def" + diff --git a/abci/tests/test_cli/ex1.abci.out b/abci/tests/test_cli/ex1.abci.out new file mode 100644 index 0000000..e182e6f --- /dev/null +++ b/abci/tests/test_cli/ex1.abci.out @@ -0,0 +1,62 @@ +> echo hello +-> code: OK +-> data: hello +-> data.hex: 0x68656C6C6F + +> info +-> code: OK +-> data: {"size":0} +-> data.hex: 0x7B2273697A65223A307D + +> prepare_proposal "abc=123" +-> code: OK +-> log: Succeeded. Tx: abc=123 + +> process_proposal "abc==456" +-> code: OK +-> status: REJECT + +> process_proposal "abc=123" +-> code: OK +-> status: ACCEPT + +> finalize_block "abc=123" +-> code: OK +-> code: OK +-> data.hex: 0x0200000000000000 + +> commit +-> code: OK + +> info +-> code: OK +-> data: {"size":1} +-> data.hex: 0x7B2273697A65223A317D + +> query "abc" +-> code: OK +-> log: exists +-> height: 0 +-> key: abc +-> key.hex: 616263 +-> value: 123 +-> value.hex: 313233 + +> finalize_block "def=xyz" "ghi=123" +-> code: OK +-> code: OK +-> code: OK +-> data.hex: 0x0600000000000000 + +> commit +-> code: OK + +> query "def" +-> code: OK +-> log: exists +-> height: 0 +-> key: def +-> key.hex: 646566 +-> value: xyz +-> value.hex: 78797A + diff --git a/abci/tests/test_cli/ex2.abci b/abci/tests/test_cli/ex2.abci new file mode 100644 index 0000000..726d17d --- /dev/null +++ b/abci/tests/test_cli/ex2.abci @@ -0,0 +1,9 @@ +check_tx "abc" +check_tx "def=567" +finalize_block "def=567" +commit +finalize_block "hello=world" +commit +finalize_block "first=second" +commit +info diff --git a/abci/tests/test_cli/ex2.abci.out b/abci/tests/test_cli/ex2.abci.out new file mode 100644 index 0000000..7364569 --- /dev/null +++ b/abci/tests/test_cli/ex2.abci.out @@ -0,0 +1,35 @@ +> check_tx "abc" +-> code: 2 + +> check_tx "def=567" +-> code: OK + +> finalize_block "def=567" +-> code: OK +-> code: OK +-> data.hex: 0x0200000000000000 + +> commit +-> code: OK + +> finalize_block "hello=world" +-> code: OK +-> code: OK +-> data.hex: 0x0400000000000000 + +> commit +-> code: OK + +> finalize_block "first=second" +-> code: OK +-> code: OK +-> data.hex: 0x0600000000000000 + +> commit +-> code: OK + +> info +-> code: OK +-> data: {"size":3} +-> data.hex: 0x7B2273697A65223A337D + diff --git a/abci/tests/test_cli/test.sh b/abci/tests/test_cli/test.sh new file mode 100755 index 0000000..1ed5e21 --- /dev/null +++ b/abci/tests/test_cli/test.sh @@ -0,0 +1,71 @@ +#! /bin/bash +set -e + +# Get the root directory. +export PATH="$GOBIN:$PATH" +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done +DIR="$( cd -P "$( dirname "$SOURCE" )/../.." && pwd )" + +# Change into that dir because we expect that. +cd "$DIR" || exit + +function testExample() { + N=$1 + INPUT=$2 + APP="$3 $4" + + echo "Example $N: $APP" + $APP &> /dev/null & + sleep 2 + abci-cli --log_level=error --verbose batch < "$INPUT" > "${INPUT}.out.new" + killall "$3" + + pre=$(shasum < "${INPUT}.out") + post=$(shasum < "${INPUT}.out.new") + + if [[ "$pre" != "$post" ]]; then + echo "You broke the tutorial" + echo "Got:" + cat "${INPUT}.out.new" + echo "Expected:" + cat "${INPUT}.out" + echo "Diff:" + diff -u "${INPUT}.out" "${INPUT}.out.new" + exit 1 + fi + + rm "${INPUT}".out.new +} + +function testHelp() { + INPUT=$1 + APP="$2 $3" + + echo "Test: $APP" + $APP &> "${INPUT}.new" & + sleep 2 + + pre=$(shasum < "${INPUT}") + post=$(shasum < "${INPUT}.new") + + if [[ "$pre" != "$post" ]]; then + echo "You broke the tutorial" + echo "Got:" + cat "${INPUT}.new" + echo "Expected:" + cat "${INPUT}" + echo "Diff:" + diff "${INPUT}" "${INPUT}.new" + exit 1 + fi + + rm "${INPUT}".new +} + +testExample 1 tests/test_cli/ex1.abci abci-cli kvstore +testExample 2 tests/test_cli/ex2.abci abci-cli kvstore +testHelp tests/test_cli/testHelp.out abci-cli help + +echo "" +echo "PASS" diff --git a/abci/tests/test_cli/testHelp.out b/abci/tests/test_cli/testHelp.out new file mode 100644 index 0000000..d4bf8bb --- /dev/null +++ b/abci/tests/test_cli/testHelp.out @@ -0,0 +1,30 @@ +the ABCI CLI tool wraps an ABCI client and is used for testing ABCI servers + +Usage: + abci-cli [command] + +Available Commands: + batch run a batch of abci commands against an application + check_tx validate a transaction + commit commit the application state and return the Merkle root hash + completion Generate the autocompletion script for the specified shell + console start an interactive ABCI console for multiple commands + echo have the application echo a message + finalize_block deliver a block of transactions to the application + help Help about any command + info get some info about the application + kvstore ABCI demo example + prepare_proposal prepare proposal + process_proposal process proposal + query query the application state + test run integration tests + version print ABCI console version + +Flags: + --abci string either socket or grpc (default "socket") + --address string address of application socket (default "tcp://0.0.0.0:26658") + -h, --help help for abci-cli + --log_level string set the logger level (default "debug") + -v, --verbose print the command and results as if it were a console session + +Use "abci-cli [command] --help" for more information about a command. diff --git a/abci/tests/tests.go b/abci/tests/tests.go new file mode 100644 index 0000000..93e83a1 --- /dev/null +++ b/abci/tests/tests.go @@ -0,0 +1 @@ +package tests diff --git a/abci/types/application.go b/abci/types/application.go new file mode 100644 index 0000000..7917232 --- /dev/null +++ b/abci/types/application.go @@ -0,0 +1,119 @@ +package types + +import "context" + +//go:generate ../../scripts/mockery_generate.sh Application + +// Application is an interface that enables any finite, deterministic state machine +// to be driven by a blockchain-based replication engine via the ABCI. +type Application interface { + // Info/Query Connection + Info(context.Context, *RequestInfo) (*ResponseInfo, error) // Return application info + Query(context.Context, *RequestQuery) (*ResponseQuery, error) // Query for state + + // Mempool Connection + CheckTx(context.Context, *RequestCheckTx) (*ResponseCheckTx, error) // Validate a tx for the mempool + + // Consensus Connection + InitChain(context.Context, *RequestInitChain) (*ResponseInitChain, error) // Initialize blockchain w validators/other info from CometBFT + PrepareProposal(context.Context, *RequestPrepareProposal) (*ResponsePrepareProposal, error) + ProcessProposal(context.Context, *RequestProcessProposal) (*ResponseProcessProposal, error) + // Deliver the decided block with its txs to the Application + FinalizeBlock(context.Context, *RequestFinalizeBlock) (*ResponseFinalizeBlock, error) + // Create application specific vote extension + ExtendVote(context.Context, *RequestExtendVote) (*ResponseExtendVote, error) + // Verify application's vote extension data + VerifyVoteExtension(context.Context, *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error) + // Commit the state and return the application Merkle root hash + Commit(context.Context, *RequestCommit) (*ResponseCommit, error) + + // State Sync Connection + ListSnapshots(context.Context, *RequestListSnapshots) (*ResponseListSnapshots, error) // List available snapshots + OfferSnapshot(context.Context, *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) // Offer a snapshot to the application + LoadSnapshotChunk(context.Context, *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) // Load a snapshot chunk + ApplySnapshotChunk(context.Context, *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) // Apply a shapshot chunk +} + +//------------------------------------------------------- +// BaseApplication is a base form of Application + +var _ Application = (*BaseApplication)(nil) + +type BaseApplication struct{} + +func NewBaseApplication() *BaseApplication { + return &BaseApplication{} +} + +func (BaseApplication) Info(context.Context, *RequestInfo) (*ResponseInfo, error) { + return &ResponseInfo{}, nil +} + +func (BaseApplication) CheckTx(context.Context, *RequestCheckTx) (*ResponseCheckTx, error) { + return &ResponseCheckTx{Code: CodeTypeOK}, nil +} + +func (BaseApplication) Commit(context.Context, *RequestCommit) (*ResponseCommit, error) { + return &ResponseCommit{}, nil +} + +func (BaseApplication) Query(context.Context, *RequestQuery) (*ResponseQuery, error) { + return &ResponseQuery{Code: CodeTypeOK}, nil +} + +func (BaseApplication) InitChain(context.Context, *RequestInitChain) (*ResponseInitChain, error) { + return &ResponseInitChain{}, nil +} + +func (BaseApplication) ListSnapshots(context.Context, *RequestListSnapshots) (*ResponseListSnapshots, error) { + return &ResponseListSnapshots{}, nil +} + +func (BaseApplication) OfferSnapshot(context.Context, *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) { + return &ResponseOfferSnapshot{}, nil +} + +func (BaseApplication) LoadSnapshotChunk(context.Context, *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) { + return &ResponseLoadSnapshotChunk{}, nil +} + +func (BaseApplication) ApplySnapshotChunk(context.Context, *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) { + return &ResponseApplySnapshotChunk{}, nil +} + +func (BaseApplication) PrepareProposal(_ context.Context, req *RequestPrepareProposal) (*ResponsePrepareProposal, error) { + txs := make([][]byte, 0, len(req.Txs)) + var totalBytes int64 + for _, tx := range req.Txs { + totalBytes += int64(len(tx)) + if totalBytes > req.MaxTxBytes { + break + } + txs = append(txs, tx) + } + return &ResponsePrepareProposal{Txs: txs}, nil +} + +func (BaseApplication) ProcessProposal(context.Context, *RequestProcessProposal) (*ResponseProcessProposal, error) { + return &ResponseProcessProposal{Status: ResponseProcessProposal_ACCEPT}, nil +} + +func (BaseApplication) ExtendVote(context.Context, *RequestExtendVote) (*ResponseExtendVote, error) { + return &ResponseExtendVote{}, nil +} + +func (BaseApplication) VerifyVoteExtension(context.Context, *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error) { + return &ResponseVerifyVoteExtension{ + Status: ResponseVerifyVoteExtension_ACCEPT, + }, nil +} + +func (BaseApplication) FinalizeBlock(_ context.Context, req *RequestFinalizeBlock) (*ResponseFinalizeBlock, error) { + txs := make([]*ExecTxResult, len(req.Txs)) + for i := range req.Txs { + txs[i] = &ExecTxResult{Code: CodeTypeOK} + } + return &ResponseFinalizeBlock{ + TxResults: txs, + }, nil +} diff --git a/abci/types/messages.go b/abci/types/messages.go new file mode 100644 index 0000000..bed8b51 --- /dev/null +++ b/abci/types/messages.go @@ -0,0 +1,229 @@ +package types + +import ( + "io" + "math" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/libs/protoio" +) + +const ( + maxMsgSize = math.MaxInt32 // 2GB +) + +// WriteMessage writes a varint length-delimited protobuf message. +func WriteMessage(msg proto.Message, w io.Writer) error { + protoWriter := protoio.NewDelimitedWriter(w) + _, err := protoWriter.WriteMsg(msg) + return err +} + +// ReadMessage reads a varint length-delimited protobuf message. +func ReadMessage(r io.Reader, msg proto.Message) error { + _, err := protoio.NewDelimitedReader(r, maxMsgSize).ReadMsg(msg) + return err +} + +//---------------------------------------- + +func ToRequestEcho(message string) *Request { + return &Request{ + Value: &Request_Echo{&RequestEcho{Message: message}}, + } +} + +func ToRequestFlush() *Request { + return &Request{ + Value: &Request_Flush{&RequestFlush{}}, + } +} + +func ToRequestInfo(req *RequestInfo) *Request { + return &Request{ + Value: &Request_Info{req}, + } +} + +func ToRequestCheckTx(req *RequestCheckTx) *Request { + return &Request{ + Value: &Request_CheckTx{req}, + } +} + +func ToRequestCommit() *Request { + return &Request{ + Value: &Request_Commit{&RequestCommit{}}, + } +} + +func ToRequestQuery(req *RequestQuery) *Request { + return &Request{ + Value: &Request_Query{req}, + } +} + +func ToRequestInitChain(req *RequestInitChain) *Request { + return &Request{ + Value: &Request_InitChain{req}, + } +} + +func ToRequestListSnapshots(req *RequestListSnapshots) *Request { + return &Request{ + Value: &Request_ListSnapshots{req}, + } +} + +func ToRequestOfferSnapshot(req *RequestOfferSnapshot) *Request { + return &Request{ + Value: &Request_OfferSnapshot{req}, + } +} + +func ToRequestLoadSnapshotChunk(req *RequestLoadSnapshotChunk) *Request { + return &Request{ + Value: &Request_LoadSnapshotChunk{req}, + } +} + +func ToRequestApplySnapshotChunk(req *RequestApplySnapshotChunk) *Request { + return &Request{ + Value: &Request_ApplySnapshotChunk{req}, + } +} + +func ToRequestPrepareProposal(req *RequestPrepareProposal) *Request { + return &Request{ + Value: &Request_PrepareProposal{req}, + } +} + +func ToRequestProcessProposal(req *RequestProcessProposal) *Request { + return &Request{ + Value: &Request_ProcessProposal{req}, + } +} + +func ToRequestExtendVote(req *RequestExtendVote) *Request { + return &Request{ + Value: &Request_ExtendVote{req}, + } +} + +func ToRequestVerifyVoteExtension(req *RequestVerifyVoteExtension) *Request { + return &Request{ + Value: &Request_VerifyVoteExtension{req}, + } +} + +func ToRequestFinalizeBlock(req *RequestFinalizeBlock) *Request { + return &Request{ + Value: &Request_FinalizeBlock{req}, + } +} + +//---------------------------------------- + +func ToResponseException(errStr string) *Response { + return &Response{ + Value: &Response_Exception{&ResponseException{Error: errStr}}, + } +} + +func ToResponseEcho(message string) *Response { + return &Response{ + Value: &Response_Echo{&ResponseEcho{Message: message}}, + } +} + +func ToResponseFlush() *Response { + return &Response{ + Value: &Response_Flush{&ResponseFlush{}}, + } +} + +func ToResponseInfo(res *ResponseInfo) *Response { + return &Response{ + Value: &Response_Info{res}, + } +} + +func ToResponseCheckTx(res *ResponseCheckTx) *Response { + return &Response{ + Value: &Response_CheckTx{res}, + } +} + +func ToResponseCommit(res *ResponseCommit) *Response { + return &Response{ + Value: &Response_Commit{res}, + } +} + +func ToResponseQuery(res *ResponseQuery) *Response { + return &Response{ + Value: &Response_Query{res}, + } +} + +func ToResponseInitChain(res *ResponseInitChain) *Response { + return &Response{ + Value: &Response_InitChain{res}, + } +} + +func ToResponseListSnapshots(res *ResponseListSnapshots) *Response { + return &Response{ + Value: &Response_ListSnapshots{res}, + } +} + +func ToResponseOfferSnapshot(res *ResponseOfferSnapshot) *Response { + return &Response{ + Value: &Response_OfferSnapshot{res}, + } +} + +func ToResponseLoadSnapshotChunk(res *ResponseLoadSnapshotChunk) *Response { + return &Response{ + Value: &Response_LoadSnapshotChunk{res}, + } +} + +func ToResponseApplySnapshotChunk(res *ResponseApplySnapshotChunk) *Response { + return &Response{ + Value: &Response_ApplySnapshotChunk{res}, + } +} + +func ToResponsePrepareProposal(res *ResponsePrepareProposal) *Response { + return &Response{ + Value: &Response_PrepareProposal{res}, + } +} + +func ToResponseProcessProposal(res *ResponseProcessProposal) *Response { + return &Response{ + Value: &Response_ProcessProposal{res}, + } +} + +func ToResponseExtendVote(res *ResponseExtendVote) *Response { + return &Response{ + Value: &Response_ExtendVote{res}, + } +} + +func ToResponseVerifyVoteExtension(res *ResponseVerifyVoteExtension) *Response { + return &Response{ + Value: &Response_VerifyVoteExtension{res}, + } +} + +func ToResponseFinalizeBlock(res *ResponseFinalizeBlock) *Response { + return &Response{ + Value: &Response_FinalizeBlock{res}, + } +} diff --git a/abci/types/messages_test.go b/abci/types/messages_test.go new file mode 100644 index 0000000..2919778 --- /dev/null +++ b/abci/types/messages_test.go @@ -0,0 +1,114 @@ +package types + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +func TestMarshalJSON(t *testing.T) { + b, err := json.Marshal(&ExecTxResult{Code: 1}) + assert.NoError(t, err) + // include empty fields. + assert.True(t, strings.Contains(string(b), "code")) + r1 := ResponseCheckTx{ + Code: 1, + Data: []byte("hello"), + GasWanted: 43, + Events: []Event{ + { + Type: "testEvent", + Attributes: []EventAttribute{ + {Key: "pho", Value: "bo"}, + }, + }, + }, + } + b, err = json.Marshal(&r1) + assert.Nil(t, err) + + var r2 ResponseCheckTx + err = json.Unmarshal(b, &r2) + assert.Nil(t, err) + assert.Equal(t, r1, r2) +} + +func TestWriteReadMessageSimple(t *testing.T) { + cases := []proto.Message{ + &RequestEcho{ + Message: "Hello", + }, + } + + for _, c := range cases { + buf := new(bytes.Buffer) + err := WriteMessage(c, buf) + assert.Nil(t, err) + + msg := new(RequestEcho) + err = ReadMessage(buf, msg) + assert.Nil(t, err) + + assert.True(t, proto.Equal(c, msg)) + } +} + +func TestWriteReadMessage(t *testing.T) { + cases := []proto.Message{ + &cmtproto.Header{ + Height: 4, + ChainID: "test", + }, + // TODO: add the rest + } + + for _, c := range cases { + buf := new(bytes.Buffer) + err := WriteMessage(c, buf) + assert.Nil(t, err) + + msg := new(cmtproto.Header) + err = ReadMessage(buf, msg) + assert.Nil(t, err) + + assert.True(t, proto.Equal(c, msg)) + } +} + +func TestWriteReadMessage2(t *testing.T) { + phrase := "hello-world" + cases := []proto.Message{ + &ResponseCheckTx{ + Data: []byte(phrase), + Log: phrase, + GasWanted: 10, + Events: []Event{ + { + Type: "testEvent", + Attributes: []EventAttribute{ + {Key: "abc", Value: "def"}, + }, + }, + }, + }, + // TODO: add the rest + } + + for _, c := range cases { + buf := new(bytes.Buffer) + err := WriteMessage(c, buf) + assert.Nil(t, err) + + msg := new(ResponseCheckTx) + err = ReadMessage(buf, msg) + assert.Nil(t, err) + + assert.True(t, proto.Equal(c, msg)) + } +} diff --git a/abci/types/mocks/application.go b/abci/types/mocks/application.go new file mode 100644 index 0000000..a8ad98d --- /dev/null +++ b/abci/types/mocks/application.go @@ -0,0 +1,449 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + types "github.com/cometbft/cometbft/abci/types" + mock "github.com/stretchr/testify/mock" +) + +// Application is an autogenerated mock type for the Application type +type Application struct { + mock.Mock +} + +// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *Application) ApplySnapshotChunk(_a0 context.Context, _a1 *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ApplySnapshotChunk") + } + + var r0 *types.ResponseApplySnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) *types.ResponseApplySnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseApplySnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestApplySnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckTx provides a mock function with given fields: _a0, _a1 +func (_m *Application) CheckTx(_a0 context.Context, _a1 *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for CheckTx") + } + + var r0 *types.ResponseCheckTx + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) *types.ResponseCheckTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCheckTx) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCheckTx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Commit provides a mock function with given fields: _a0, _a1 +func (_m *Application) Commit(_a0 context.Context, _a1 *types.RequestCommit) (*types.ResponseCommit, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Commit") + } + + var r0 *types.ResponseCommit + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCommit) (*types.ResponseCommit, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCommit) *types.ResponseCommit); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCommit) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCommit) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ExtendVote provides a mock function with given fields: _a0, _a1 +func (_m *Application) ExtendVote(_a0 context.Context, _a1 *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ExtendVote") + } + + var r0 *types.ResponseExtendVote + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) (*types.ResponseExtendVote, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) *types.ResponseExtendVote); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseExtendVote) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestExtendVote) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FinalizeBlock provides a mock function with given fields: _a0, _a1 +func (_m *Application) FinalizeBlock(_a0 context.Context, _a1 *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for FinalizeBlock") + } + + var r0 *types.ResponseFinalizeBlock + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) *types.ResponseFinalizeBlock); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseFinalizeBlock) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestFinalizeBlock) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Info provides a mock function with given fields: _a0, _a1 +func (_m *Application) Info(_a0 context.Context, _a1 *types.RequestInfo) (*types.ResponseInfo, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Info") + } + + var r0 *types.ResponseInfo + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) (*types.ResponseInfo, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) *types.ResponseInfo); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInfo) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInfo) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// InitChain provides a mock function with given fields: _a0, _a1 +func (_m *Application) InitChain(_a0 context.Context, _a1 *types.RequestInitChain) (*types.ResponseInitChain, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for InitChain") + } + + var r0 *types.ResponseInitChain + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) (*types.ResponseInitChain, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) *types.ResponseInitChain); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInitChain) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInitChain) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ListSnapshots provides a mock function with given fields: _a0, _a1 +func (_m *Application) ListSnapshots(_a0 context.Context, _a1 *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ListSnapshots") + } + + var r0 *types.ResponseListSnapshots + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) (*types.ResponseListSnapshots, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) *types.ResponseListSnapshots); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseListSnapshots) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestListSnapshots) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *Application) LoadSnapshotChunk(_a0 context.Context, _a1 *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for LoadSnapshotChunk") + } + + var r0 *types.ResponseLoadSnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) *types.ResponseLoadSnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseLoadSnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestLoadSnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OfferSnapshot provides a mock function with given fields: _a0, _a1 +func (_m *Application) OfferSnapshot(_a0 context.Context, _a1 *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for OfferSnapshot") + } + + var r0 *types.ResponseOfferSnapshot + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) *types.ResponseOfferSnapshot); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseOfferSnapshot) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestOfferSnapshot) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PrepareProposal provides a mock function with given fields: _a0, _a1 +func (_m *Application) PrepareProposal(_a0 context.Context, _a1 *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for PrepareProposal") + } + + var r0 *types.ResponsePrepareProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) *types.ResponsePrepareProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponsePrepareProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestPrepareProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ProcessProposal provides a mock function with given fields: _a0, _a1 +func (_m *Application) ProcessProposal(_a0 context.Context, _a1 *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ProcessProposal") + } + + var r0 *types.ResponseProcessProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) (*types.ResponseProcessProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) *types.ResponseProcessProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseProcessProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestProcessProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Query provides a mock function with given fields: _a0, _a1 +func (_m *Application) Query(_a0 context.Context, _a1 *types.RequestQuery) (*types.ResponseQuery, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Query") + } + + var r0 *types.ResponseQuery + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) (*types.ResponseQuery, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) *types.ResponseQuery); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseQuery) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestQuery) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 +func (_m *Application) VerifyVoteExtension(_a0 context.Context, _a1 *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for VerifyVoteExtension") + } + + var r0 *types.ResponseVerifyVoteExtension + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) *types.ResponseVerifyVoteExtension); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseVerifyVoteExtension) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestVerifyVoteExtension) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewApplication creates a new instance of Application. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewApplication(t interface { + mock.TestingT + Cleanup(func()) +}) *Application { + mock := &Application{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/abci/types/pubkey.go b/abci/types/pubkey.go new file mode 100644 index 0000000..638c36b --- /dev/null +++ b/abci/types/pubkey.go @@ -0,0 +1,44 @@ +package types + +import ( + fmt "fmt" + + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/secp256k1" +) + +func Ed25519ValidatorUpdate(pk []byte, power int64) ValidatorUpdate { + pke := ed25519.PubKey(pk) + + pkp, err := cryptoenc.PubKeyToProto(pke) + if err != nil { + panic(err) + } + + return ValidatorUpdate{ + // Address: + PubKey: pkp, + Power: power, + } +} + +func UpdateValidator(pk []byte, power int64, keyType string) ValidatorUpdate { + switch keyType { + case "", ed25519.KeyType: + return Ed25519ValidatorUpdate(pk, power) + case secp256k1.KeyType: + pke := secp256k1.PubKey(pk) + pkp, err := cryptoenc.PubKeyToProto(pke) + if err != nil { + panic(err) + } + return ValidatorUpdate{ + // Address: + PubKey: pkp, + Power: power, + } + default: + panic(fmt.Sprintf("key type %s not supported", keyType)) + } +} diff --git a/abci/types/types.go b/abci/types/types.go new file mode 100644 index 0000000..9156731 --- /dev/null +++ b/abci/types/types.go @@ -0,0 +1,170 @@ +package types + +import ( + "bytes" + "encoding/json" + + "github.com/cosmos/gogoproto/jsonpb" +) + +const ( + CodeTypeOK uint32 = 0 +) + +// IsOK returns true if Code is OK. +func (r ResponseCheckTx) IsOK() bool { + return r.Code == CodeTypeOK +} + +// IsErr returns true if Code is something other than OK. +func (r ResponseCheckTx) IsErr() bool { + return r.Code != CodeTypeOK +} + +// IsOK returns true if Code is OK. +func (r ExecTxResult) IsOK() bool { + return r.Code == CodeTypeOK +} + +// IsErr returns true if Code is something other than OK. +func (r ExecTxResult) IsErr() bool { + return r.Code != CodeTypeOK +} + +// IsOK returns true if Code is OK. +func (r ResponseQuery) IsOK() bool { + return r.Code == CodeTypeOK +} + +// IsErr returns true if Code is something other than OK. +func (r ResponseQuery) IsErr() bool { + return r.Code != CodeTypeOK +} + +// IsAccepted returns true if Code is ACCEPT +func (r ResponseProcessProposal) IsAccepted() bool { + return r.Status == ResponseProcessProposal_ACCEPT +} + +// IsStatusUnknown returns true if Code is UNKNOWN +func (r ResponseProcessProposal) IsStatusUnknown() bool { + return r.Status == ResponseProcessProposal_UNKNOWN +} + +func (r ResponseVerifyVoteExtension) IsAccepted() bool { + return r.Status == ResponseVerifyVoteExtension_ACCEPT +} + +// IsStatusUnknown returns true if Code is Unknown +func (r ResponseVerifyVoteExtension) IsStatusUnknown() bool { + return r.Status == ResponseVerifyVoteExtension_UNKNOWN +} + +//--------------------------------------------------------------------------- +// override JSON marshaling so we emit defaults (ie. disable omitempty) + +var ( + jsonpbMarshaller = jsonpb.Marshaler{ + EnumsAsInts: true, + EmitDefaults: true, + } + jsonpbUnmarshaller = jsonpb.Unmarshaler{} +) + +func (r *ResponseCheckTx) MarshalJSON() ([]byte, error) { + s, err := jsonpbMarshaller.MarshalToString(r) + return []byte(s), err +} + +func (r *ResponseCheckTx) UnmarshalJSON(b []byte) error { + reader := bytes.NewBuffer(b) + return jsonpbUnmarshaller.Unmarshal(reader, r) +} + +func (r *ExecTxResult) MarshalJSON() ([]byte, error) { + s, err := jsonpbMarshaller.MarshalToString(r) + return []byte(s), err +} + +func (r *ExecTxResult) UnmarshalJSON(b []byte) error { + reader := bytes.NewBuffer(b) + return jsonpbUnmarshaller.Unmarshal(reader, r) +} + +func (r *ResponseQuery) MarshalJSON() ([]byte, error) { + s, err := jsonpbMarshaller.MarshalToString(r) + return []byte(s), err +} + +func (r *ResponseQuery) UnmarshalJSON(b []byte) error { + reader := bytes.NewBuffer(b) + return jsonpbUnmarshaller.Unmarshal(reader, r) +} + +func (r *ResponseCommit) MarshalJSON() ([]byte, error) { + s, err := jsonpbMarshaller.MarshalToString(r) + return []byte(s), err +} + +func (r *ResponseCommit) UnmarshalJSON(b []byte) error { + reader := bytes.NewBuffer(b) + return jsonpbUnmarshaller.Unmarshal(reader, r) +} + +func (r *EventAttribute) MarshalJSON() ([]byte, error) { + s, err := jsonpbMarshaller.MarshalToString(r) + return []byte(s), err +} + +func (r *EventAttribute) UnmarshalJSON(b []byte) error { + reader := bytes.NewBuffer(b) + return jsonpbUnmarshaller.Unmarshal(reader, r) +} + +// Some compile time assertions to ensure we don't +// have accidental runtime surprises later on. + +// jsonEncodingRoundTripper ensures that asserted +// interfaces implement both MarshalJSON and UnmarshalJSON +type jsonRoundTripper interface { + json.Marshaler + json.Unmarshaler +} + +var _ jsonRoundTripper = (*ResponseCommit)(nil) +var _ jsonRoundTripper = (*ResponseQuery)(nil) +var _ jsonRoundTripper = (*ExecTxResult)(nil) +var _ jsonRoundTripper = (*ResponseCheckTx)(nil) + +var _ jsonRoundTripper = (*EventAttribute)(nil) + +// deterministicExecTxResult constructs a copy of response that omits +// non-deterministic fields. The input response is not modified. +func deterministicExecTxResult(response *ExecTxResult) *ExecTxResult { + return &ExecTxResult{ + Code: response.Code, + Data: response.Data, + GasWanted: response.GasWanted, + GasUsed: response.GasUsed, + } +} + +// MarshalTxResults encodes the the TxResults as a list of byte +// slices. It strips off the non-deterministic pieces of the TxResults +// so that the resulting data can be used for hash comparisons and used +// in Merkle proofs. +func MarshalTxResults(r []*ExecTxResult) ([][]byte, error) { + s := make([][]byte, len(r)) + for i, e := range r { + d := deterministicExecTxResult(e) + b, err := d.Marshal() + if err != nil { + return nil, err + } + s[i] = b + } + return s, nil +} + +// ----------------------------------------------- +// construct Result data diff --git a/abci/types/types.pb.go b/abci/types/types.pb.go new file mode 100644 index 0000000..450fb22 --- /dev/null +++ b/abci/types/types.pb.go @@ -0,0 +1,16606 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/abci/types.proto + +package types + +import ( + context "context" + fmt "fmt" + crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + types1 "github.com/cometbft/cometbft/proto/tendermint/types" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type CheckTxType int32 + +const ( + CheckTxType_New CheckTxType = 0 + CheckTxType_Recheck CheckTxType = 1 +) + +var CheckTxType_name = map[int32]string{ + 0: "NEW", + 1: "RECHECK", +} + +var CheckTxType_value = map[string]int32{ + "NEW": 0, + "RECHECK": 1, +} + +func (x CheckTxType) String() string { + return proto.EnumName(CheckTxType_name, int32(x)) +} + +func (CheckTxType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{0} +} + +type MisbehaviorType int32 + +const ( + MisbehaviorType_UNKNOWN MisbehaviorType = 0 + MisbehaviorType_DUPLICATE_VOTE MisbehaviorType = 1 + MisbehaviorType_LIGHT_CLIENT_ATTACK MisbehaviorType = 2 +) + +var MisbehaviorType_name = map[int32]string{ + 0: "UNKNOWN", + 1: "DUPLICATE_VOTE", + 2: "LIGHT_CLIENT_ATTACK", +} + +var MisbehaviorType_value = map[string]int32{ + "UNKNOWN": 0, + "DUPLICATE_VOTE": 1, + "LIGHT_CLIENT_ATTACK": 2, +} + +func (x MisbehaviorType) String() string { + return proto.EnumName(MisbehaviorType_name, int32(x)) +} + +func (MisbehaviorType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{1} +} + +type ResponseOfferSnapshot_Result int32 + +const ( + ResponseOfferSnapshot_UNKNOWN ResponseOfferSnapshot_Result = 0 + ResponseOfferSnapshot_ACCEPT ResponseOfferSnapshot_Result = 1 + ResponseOfferSnapshot_ABORT ResponseOfferSnapshot_Result = 2 + ResponseOfferSnapshot_REJECT ResponseOfferSnapshot_Result = 3 + ResponseOfferSnapshot_REJECT_FORMAT ResponseOfferSnapshot_Result = 4 + ResponseOfferSnapshot_REJECT_SENDER ResponseOfferSnapshot_Result = 5 +) + +var ResponseOfferSnapshot_Result_name = map[int32]string{ + 0: "UNKNOWN", + 1: "ACCEPT", + 2: "ABORT", + 3: "REJECT", + 4: "REJECT_FORMAT", + 5: "REJECT_SENDER", +} + +var ResponseOfferSnapshot_Result_value = map[string]int32{ + "UNKNOWN": 0, + "ACCEPT": 1, + "ABORT": 2, + "REJECT": 3, + "REJECT_FORMAT": 4, + "REJECT_SENDER": 5, +} + +func (x ResponseOfferSnapshot_Result) String() string { + return proto.EnumName(ResponseOfferSnapshot_Result_name, int32(x)) +} + +func (ResponseOfferSnapshot_Result) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{27, 0} +} + +type ResponseApplySnapshotChunk_Result int32 + +const ( + ResponseApplySnapshotChunk_UNKNOWN ResponseApplySnapshotChunk_Result = 0 + ResponseApplySnapshotChunk_ACCEPT ResponseApplySnapshotChunk_Result = 1 + ResponseApplySnapshotChunk_ABORT ResponseApplySnapshotChunk_Result = 2 + ResponseApplySnapshotChunk_RETRY ResponseApplySnapshotChunk_Result = 3 + ResponseApplySnapshotChunk_RETRY_SNAPSHOT ResponseApplySnapshotChunk_Result = 4 + ResponseApplySnapshotChunk_REJECT_SNAPSHOT ResponseApplySnapshotChunk_Result = 5 +) + +var ResponseApplySnapshotChunk_Result_name = map[int32]string{ + 0: "UNKNOWN", + 1: "ACCEPT", + 2: "ABORT", + 3: "RETRY", + 4: "RETRY_SNAPSHOT", + 5: "REJECT_SNAPSHOT", +} + +var ResponseApplySnapshotChunk_Result_value = map[string]int32{ + "UNKNOWN": 0, + "ACCEPT": 1, + "ABORT": 2, + "RETRY": 3, + "RETRY_SNAPSHOT": 4, + "REJECT_SNAPSHOT": 5, +} + +func (x ResponseApplySnapshotChunk_Result) String() string { + return proto.EnumName(ResponseApplySnapshotChunk_Result_name, int32(x)) +} + +func (ResponseApplySnapshotChunk_Result) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{29, 0} +} + +type ResponseProcessProposal_ProposalStatus int32 + +const ( + ResponseProcessProposal_UNKNOWN ResponseProcessProposal_ProposalStatus = 0 + ResponseProcessProposal_ACCEPT ResponseProcessProposal_ProposalStatus = 1 + ResponseProcessProposal_REJECT ResponseProcessProposal_ProposalStatus = 2 +) + +var ResponseProcessProposal_ProposalStatus_name = map[int32]string{ + 0: "UNKNOWN", + 1: "ACCEPT", + 2: "REJECT", +} + +var ResponseProcessProposal_ProposalStatus_value = map[string]int32{ + "UNKNOWN": 0, + "ACCEPT": 1, + "REJECT": 2, +} + +func (x ResponseProcessProposal_ProposalStatus) String() string { + return proto.EnumName(ResponseProcessProposal_ProposalStatus_name, int32(x)) +} + +func (ResponseProcessProposal_ProposalStatus) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{31, 0} +} + +type ResponseVerifyVoteExtension_VerifyStatus int32 + +const ( + ResponseVerifyVoteExtension_UNKNOWN ResponseVerifyVoteExtension_VerifyStatus = 0 + ResponseVerifyVoteExtension_ACCEPT ResponseVerifyVoteExtension_VerifyStatus = 1 + // Rejecting the vote extension will reject the entire precommit by the sender. + // Incorrectly implementing this thus has liveness implications as it may affect + // CometBFT's ability to receive 2/3+ valid votes to finalize the block. + // Honest nodes should never be rejected. + ResponseVerifyVoteExtension_REJECT ResponseVerifyVoteExtension_VerifyStatus = 2 +) + +var ResponseVerifyVoteExtension_VerifyStatus_name = map[int32]string{ + 0: "UNKNOWN", + 1: "ACCEPT", + 2: "REJECT", +} + +var ResponseVerifyVoteExtension_VerifyStatus_value = map[string]int32{ + "UNKNOWN": 0, + "ACCEPT": 1, + "REJECT": 2, +} + +func (x ResponseVerifyVoteExtension_VerifyStatus) String() string { + return proto.EnumName(ResponseVerifyVoteExtension_VerifyStatus_name, int32(x)) +} + +func (ResponseVerifyVoteExtension_VerifyStatus) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{33, 0} +} + +type Request struct { + // Types that are valid to be assigned to Value: + // *Request_Echo + // *Request_Flush + // *Request_Info + // *Request_InitChain + // *Request_Query + // *Request_CheckTx + // *Request_Commit + // *Request_ListSnapshots + // *Request_OfferSnapshot + // *Request_LoadSnapshotChunk + // *Request_ApplySnapshotChunk + // *Request_PrepareProposal + // *Request_ProcessProposal + // *Request_ExtendVote + // *Request_VerifyVoteExtension + // *Request_FinalizeBlock + Value isRequest_Value `protobuf_oneof:"value"` +} + +func (m *Request) Reset() { *m = Request{} } +func (m *Request) String() string { return proto.CompactTextString(m) } +func (*Request) ProtoMessage() {} +func (*Request) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{0} +} +func (m *Request) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Request.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Request) XXX_Merge(src proto.Message) { + xxx_messageInfo_Request.Merge(m, src) +} +func (m *Request) XXX_Size() int { + return m.Size() +} +func (m *Request) XXX_DiscardUnknown() { + xxx_messageInfo_Request.DiscardUnknown(m) +} + +var xxx_messageInfo_Request proto.InternalMessageInfo + +type isRequest_Value interface { + isRequest_Value() + MarshalTo([]byte) (int, error) + Size() int +} + +type Request_Echo struct { + Echo *RequestEcho `protobuf:"bytes,1,opt,name=echo,proto3,oneof" json:"echo,omitempty"` +} +type Request_Flush struct { + Flush *RequestFlush `protobuf:"bytes,2,opt,name=flush,proto3,oneof" json:"flush,omitempty"` +} +type Request_Info struct { + Info *RequestInfo `protobuf:"bytes,3,opt,name=info,proto3,oneof" json:"info,omitempty"` +} +type Request_InitChain struct { + InitChain *RequestInitChain `protobuf:"bytes,5,opt,name=init_chain,json=initChain,proto3,oneof" json:"init_chain,omitempty"` +} +type Request_Query struct { + Query *RequestQuery `protobuf:"bytes,6,opt,name=query,proto3,oneof" json:"query,omitempty"` +} +type Request_CheckTx struct { + CheckTx *RequestCheckTx `protobuf:"bytes,8,opt,name=check_tx,json=checkTx,proto3,oneof" json:"check_tx,omitempty"` +} +type Request_Commit struct { + Commit *RequestCommit `protobuf:"bytes,11,opt,name=commit,proto3,oneof" json:"commit,omitempty"` +} +type Request_ListSnapshots struct { + ListSnapshots *RequestListSnapshots `protobuf:"bytes,12,opt,name=list_snapshots,json=listSnapshots,proto3,oneof" json:"list_snapshots,omitempty"` +} +type Request_OfferSnapshot struct { + OfferSnapshot *RequestOfferSnapshot `protobuf:"bytes,13,opt,name=offer_snapshot,json=offerSnapshot,proto3,oneof" json:"offer_snapshot,omitempty"` +} +type Request_LoadSnapshotChunk struct { + LoadSnapshotChunk *RequestLoadSnapshotChunk `protobuf:"bytes,14,opt,name=load_snapshot_chunk,json=loadSnapshotChunk,proto3,oneof" json:"load_snapshot_chunk,omitempty"` +} +type Request_ApplySnapshotChunk struct { + ApplySnapshotChunk *RequestApplySnapshotChunk `protobuf:"bytes,15,opt,name=apply_snapshot_chunk,json=applySnapshotChunk,proto3,oneof" json:"apply_snapshot_chunk,omitempty"` +} +type Request_PrepareProposal struct { + PrepareProposal *RequestPrepareProposal `protobuf:"bytes,16,opt,name=prepare_proposal,json=prepareProposal,proto3,oneof" json:"prepare_proposal,omitempty"` +} +type Request_ProcessProposal struct { + ProcessProposal *RequestProcessProposal `protobuf:"bytes,17,opt,name=process_proposal,json=processProposal,proto3,oneof" json:"process_proposal,omitempty"` +} +type Request_ExtendVote struct { + ExtendVote *RequestExtendVote `protobuf:"bytes,18,opt,name=extend_vote,json=extendVote,proto3,oneof" json:"extend_vote,omitempty"` +} +type Request_VerifyVoteExtension struct { + VerifyVoteExtension *RequestVerifyVoteExtension `protobuf:"bytes,19,opt,name=verify_vote_extension,json=verifyVoteExtension,proto3,oneof" json:"verify_vote_extension,omitempty"` +} +type Request_FinalizeBlock struct { + FinalizeBlock *RequestFinalizeBlock `protobuf:"bytes,20,opt,name=finalize_block,json=finalizeBlock,proto3,oneof" json:"finalize_block,omitempty"` +} + +func (*Request_Echo) isRequest_Value() {} +func (*Request_Flush) isRequest_Value() {} +func (*Request_Info) isRequest_Value() {} +func (*Request_InitChain) isRequest_Value() {} +func (*Request_Query) isRequest_Value() {} +func (*Request_CheckTx) isRequest_Value() {} +func (*Request_Commit) isRequest_Value() {} +func (*Request_ListSnapshots) isRequest_Value() {} +func (*Request_OfferSnapshot) isRequest_Value() {} +func (*Request_LoadSnapshotChunk) isRequest_Value() {} +func (*Request_ApplySnapshotChunk) isRequest_Value() {} +func (*Request_PrepareProposal) isRequest_Value() {} +func (*Request_ProcessProposal) isRequest_Value() {} +func (*Request_ExtendVote) isRequest_Value() {} +func (*Request_VerifyVoteExtension) isRequest_Value() {} +func (*Request_FinalizeBlock) isRequest_Value() {} + +func (m *Request) GetValue() isRequest_Value { + if m != nil { + return m.Value + } + return nil +} + +func (m *Request) GetEcho() *RequestEcho { + if x, ok := m.GetValue().(*Request_Echo); ok { + return x.Echo + } + return nil +} + +func (m *Request) GetFlush() *RequestFlush { + if x, ok := m.GetValue().(*Request_Flush); ok { + return x.Flush + } + return nil +} + +func (m *Request) GetInfo() *RequestInfo { + if x, ok := m.GetValue().(*Request_Info); ok { + return x.Info + } + return nil +} + +func (m *Request) GetInitChain() *RequestInitChain { + if x, ok := m.GetValue().(*Request_InitChain); ok { + return x.InitChain + } + return nil +} + +func (m *Request) GetQuery() *RequestQuery { + if x, ok := m.GetValue().(*Request_Query); ok { + return x.Query + } + return nil +} + +func (m *Request) GetCheckTx() *RequestCheckTx { + if x, ok := m.GetValue().(*Request_CheckTx); ok { + return x.CheckTx + } + return nil +} + +func (m *Request) GetCommit() *RequestCommit { + if x, ok := m.GetValue().(*Request_Commit); ok { + return x.Commit + } + return nil +} + +func (m *Request) GetListSnapshots() *RequestListSnapshots { + if x, ok := m.GetValue().(*Request_ListSnapshots); ok { + return x.ListSnapshots + } + return nil +} + +func (m *Request) GetOfferSnapshot() *RequestOfferSnapshot { + if x, ok := m.GetValue().(*Request_OfferSnapshot); ok { + return x.OfferSnapshot + } + return nil +} + +func (m *Request) GetLoadSnapshotChunk() *RequestLoadSnapshotChunk { + if x, ok := m.GetValue().(*Request_LoadSnapshotChunk); ok { + return x.LoadSnapshotChunk + } + return nil +} + +func (m *Request) GetApplySnapshotChunk() *RequestApplySnapshotChunk { + if x, ok := m.GetValue().(*Request_ApplySnapshotChunk); ok { + return x.ApplySnapshotChunk + } + return nil +} + +func (m *Request) GetPrepareProposal() *RequestPrepareProposal { + if x, ok := m.GetValue().(*Request_PrepareProposal); ok { + return x.PrepareProposal + } + return nil +} + +func (m *Request) GetProcessProposal() *RequestProcessProposal { + if x, ok := m.GetValue().(*Request_ProcessProposal); ok { + return x.ProcessProposal + } + return nil +} + +func (m *Request) GetExtendVote() *RequestExtendVote { + if x, ok := m.GetValue().(*Request_ExtendVote); ok { + return x.ExtendVote + } + return nil +} + +func (m *Request) GetVerifyVoteExtension() *RequestVerifyVoteExtension { + if x, ok := m.GetValue().(*Request_VerifyVoteExtension); ok { + return x.VerifyVoteExtension + } + return nil +} + +func (m *Request) GetFinalizeBlock() *RequestFinalizeBlock { + if x, ok := m.GetValue().(*Request_FinalizeBlock); ok { + return x.FinalizeBlock + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Request) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Request_Echo)(nil), + (*Request_Flush)(nil), + (*Request_Info)(nil), + (*Request_InitChain)(nil), + (*Request_Query)(nil), + (*Request_CheckTx)(nil), + (*Request_Commit)(nil), + (*Request_ListSnapshots)(nil), + (*Request_OfferSnapshot)(nil), + (*Request_LoadSnapshotChunk)(nil), + (*Request_ApplySnapshotChunk)(nil), + (*Request_PrepareProposal)(nil), + (*Request_ProcessProposal)(nil), + (*Request_ExtendVote)(nil), + (*Request_VerifyVoteExtension)(nil), + (*Request_FinalizeBlock)(nil), + } +} + +type RequestEcho struct { + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (m *RequestEcho) Reset() { *m = RequestEcho{} } +func (m *RequestEcho) String() string { return proto.CompactTextString(m) } +func (*RequestEcho) ProtoMessage() {} +func (*RequestEcho) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{1} +} +func (m *RequestEcho) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestEcho) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestEcho.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestEcho) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestEcho.Merge(m, src) +} +func (m *RequestEcho) XXX_Size() int { + return m.Size() +} +func (m *RequestEcho) XXX_DiscardUnknown() { + xxx_messageInfo_RequestEcho.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestEcho proto.InternalMessageInfo + +func (m *RequestEcho) GetMessage() string { + if m != nil { + return m.Message + } + return "" +} + +type RequestFlush struct { +} + +func (m *RequestFlush) Reset() { *m = RequestFlush{} } +func (m *RequestFlush) String() string { return proto.CompactTextString(m) } +func (*RequestFlush) ProtoMessage() {} +func (*RequestFlush) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{2} +} +func (m *RequestFlush) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestFlush) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestFlush.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestFlush) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestFlush.Merge(m, src) +} +func (m *RequestFlush) XXX_Size() int { + return m.Size() +} +func (m *RequestFlush) XXX_DiscardUnknown() { + xxx_messageInfo_RequestFlush.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestFlush proto.InternalMessageInfo + +type RequestInfo struct { + Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` + BlockVersion uint64 `protobuf:"varint,2,opt,name=block_version,json=blockVersion,proto3" json:"block_version,omitempty"` + P2PVersion uint64 `protobuf:"varint,3,opt,name=p2p_version,json=p2pVersion,proto3" json:"p2p_version,omitempty"` + AbciVersion string `protobuf:"bytes,4,opt,name=abci_version,json=abciVersion,proto3" json:"abci_version,omitempty"` +} + +func (m *RequestInfo) Reset() { *m = RequestInfo{} } +func (m *RequestInfo) String() string { return proto.CompactTextString(m) } +func (*RequestInfo) ProtoMessage() {} +func (*RequestInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{3} +} +func (m *RequestInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestInfo.Merge(m, src) +} +func (m *RequestInfo) XXX_Size() int { + return m.Size() +} +func (m *RequestInfo) XXX_DiscardUnknown() { + xxx_messageInfo_RequestInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestInfo proto.InternalMessageInfo + +func (m *RequestInfo) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *RequestInfo) GetBlockVersion() uint64 { + if m != nil { + return m.BlockVersion + } + return 0 +} + +func (m *RequestInfo) GetP2PVersion() uint64 { + if m != nil { + return m.P2PVersion + } + return 0 +} + +func (m *RequestInfo) GetAbciVersion() string { + if m != nil { + return m.AbciVersion + } + return "" +} + +type RequestInitChain struct { + Time time.Time `protobuf:"bytes,1,opt,name=time,proto3,stdtime" json:"time"` + ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsensusParams *types1.ConsensusParams `protobuf:"bytes,3,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params,omitempty"` + Validators []ValidatorUpdate `protobuf:"bytes,4,rep,name=validators,proto3" json:"validators"` + AppStateBytes []byte `protobuf:"bytes,5,opt,name=app_state_bytes,json=appStateBytes,proto3" json:"app_state_bytes,omitempty"` + InitialHeight int64 `protobuf:"varint,6,opt,name=initial_height,json=initialHeight,proto3" json:"initial_height,omitempty"` +} + +func (m *RequestInitChain) Reset() { *m = RequestInitChain{} } +func (m *RequestInitChain) String() string { return proto.CompactTextString(m) } +func (*RequestInitChain) ProtoMessage() {} +func (*RequestInitChain) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{4} +} +func (m *RequestInitChain) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestInitChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestInitChain.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestInitChain) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestInitChain.Merge(m, src) +} +func (m *RequestInitChain) XXX_Size() int { + return m.Size() +} +func (m *RequestInitChain) XXX_DiscardUnknown() { + xxx_messageInfo_RequestInitChain.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestInitChain proto.InternalMessageInfo + +func (m *RequestInitChain) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *RequestInitChain) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +func (m *RequestInitChain) GetConsensusParams() *types1.ConsensusParams { + if m != nil { + return m.ConsensusParams + } + return nil +} + +func (m *RequestInitChain) GetValidators() []ValidatorUpdate { + if m != nil { + return m.Validators + } + return nil +} + +func (m *RequestInitChain) GetAppStateBytes() []byte { + if m != nil { + return m.AppStateBytes + } + return nil +} + +func (m *RequestInitChain) GetInitialHeight() int64 { + if m != nil { + return m.InitialHeight + } + return 0 +} + +type RequestQuery struct { + Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` + Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + Prove bool `protobuf:"varint,4,opt,name=prove,proto3" json:"prove,omitempty"` +} + +func (m *RequestQuery) Reset() { *m = RequestQuery{} } +func (m *RequestQuery) String() string { return proto.CompactTextString(m) } +func (*RequestQuery) ProtoMessage() {} +func (*RequestQuery) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{5} +} +func (m *RequestQuery) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestQuery) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestQuery.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestQuery) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestQuery.Merge(m, src) +} +func (m *RequestQuery) XXX_Size() int { + return m.Size() +} +func (m *RequestQuery) XXX_DiscardUnknown() { + xxx_messageInfo_RequestQuery.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestQuery proto.InternalMessageInfo + +func (m *RequestQuery) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *RequestQuery) GetPath() string { + if m != nil { + return m.Path + } + return "" +} + +func (m *RequestQuery) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestQuery) GetProve() bool { + if m != nil { + return m.Prove + } + return false +} + +type RequestCheckTx struct { + Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` + Type CheckTxType `protobuf:"varint,2,opt,name=type,proto3,enum=tendermint.abci.CheckTxType" json:"type,omitempty"` +} + +func (m *RequestCheckTx) Reset() { *m = RequestCheckTx{} } +func (m *RequestCheckTx) String() string { return proto.CompactTextString(m) } +func (*RequestCheckTx) ProtoMessage() {} +func (*RequestCheckTx) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{6} +} +func (m *RequestCheckTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestCheckTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestCheckTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestCheckTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestCheckTx.Merge(m, src) +} +func (m *RequestCheckTx) XXX_Size() int { + return m.Size() +} +func (m *RequestCheckTx) XXX_DiscardUnknown() { + xxx_messageInfo_RequestCheckTx.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestCheckTx proto.InternalMessageInfo + +func (m *RequestCheckTx) GetTx() []byte { + if m != nil { + return m.Tx + } + return nil +} + +func (m *RequestCheckTx) GetType() CheckTxType { + if m != nil { + return m.Type + } + return CheckTxType_New +} + +type RequestCommit struct { +} + +func (m *RequestCommit) Reset() { *m = RequestCommit{} } +func (m *RequestCommit) String() string { return proto.CompactTextString(m) } +func (*RequestCommit) ProtoMessage() {} +func (*RequestCommit) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{7} +} +func (m *RequestCommit) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestCommit.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestCommit) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestCommit.Merge(m, src) +} +func (m *RequestCommit) XXX_Size() int { + return m.Size() +} +func (m *RequestCommit) XXX_DiscardUnknown() { + xxx_messageInfo_RequestCommit.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestCommit proto.InternalMessageInfo + +// lists available snapshots +type RequestListSnapshots struct { +} + +func (m *RequestListSnapshots) Reset() { *m = RequestListSnapshots{} } +func (m *RequestListSnapshots) String() string { return proto.CompactTextString(m) } +func (*RequestListSnapshots) ProtoMessage() {} +func (*RequestListSnapshots) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{8} +} +func (m *RequestListSnapshots) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestListSnapshots) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestListSnapshots.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestListSnapshots) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestListSnapshots.Merge(m, src) +} +func (m *RequestListSnapshots) XXX_Size() int { + return m.Size() +} +func (m *RequestListSnapshots) XXX_DiscardUnknown() { + xxx_messageInfo_RequestListSnapshots.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestListSnapshots proto.InternalMessageInfo + +// offers a snapshot to the application +type RequestOfferSnapshot struct { + Snapshot *Snapshot `protobuf:"bytes,1,opt,name=snapshot,proto3" json:"snapshot,omitempty"` + AppHash []byte `protobuf:"bytes,2,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` +} + +func (m *RequestOfferSnapshot) Reset() { *m = RequestOfferSnapshot{} } +func (m *RequestOfferSnapshot) String() string { return proto.CompactTextString(m) } +func (*RequestOfferSnapshot) ProtoMessage() {} +func (*RequestOfferSnapshot) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{9} +} +func (m *RequestOfferSnapshot) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestOfferSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestOfferSnapshot.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestOfferSnapshot) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestOfferSnapshot.Merge(m, src) +} +func (m *RequestOfferSnapshot) XXX_Size() int { + return m.Size() +} +func (m *RequestOfferSnapshot) XXX_DiscardUnknown() { + xxx_messageInfo_RequestOfferSnapshot.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestOfferSnapshot proto.InternalMessageInfo + +func (m *RequestOfferSnapshot) GetSnapshot() *Snapshot { + if m != nil { + return m.Snapshot + } + return nil +} + +func (m *RequestOfferSnapshot) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +// loads a snapshot chunk +type RequestLoadSnapshotChunk struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"` + Chunk uint32 `protobuf:"varint,3,opt,name=chunk,proto3" json:"chunk,omitempty"` +} + +func (m *RequestLoadSnapshotChunk) Reset() { *m = RequestLoadSnapshotChunk{} } +func (m *RequestLoadSnapshotChunk) String() string { return proto.CompactTextString(m) } +func (*RequestLoadSnapshotChunk) ProtoMessage() {} +func (*RequestLoadSnapshotChunk) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{10} +} +func (m *RequestLoadSnapshotChunk) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestLoadSnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestLoadSnapshotChunk.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestLoadSnapshotChunk) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestLoadSnapshotChunk.Merge(m, src) +} +func (m *RequestLoadSnapshotChunk) XXX_Size() int { + return m.Size() +} +func (m *RequestLoadSnapshotChunk) XXX_DiscardUnknown() { + xxx_messageInfo_RequestLoadSnapshotChunk.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestLoadSnapshotChunk proto.InternalMessageInfo + +func (m *RequestLoadSnapshotChunk) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestLoadSnapshotChunk) GetFormat() uint32 { + if m != nil { + return m.Format + } + return 0 +} + +func (m *RequestLoadSnapshotChunk) GetChunk() uint32 { + if m != nil { + return m.Chunk + } + return 0 +} + +// Applies a snapshot chunk +type RequestApplySnapshotChunk struct { + Index uint32 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"` + Chunk []byte `protobuf:"bytes,2,opt,name=chunk,proto3" json:"chunk,omitempty"` + Sender string `protobuf:"bytes,3,opt,name=sender,proto3" json:"sender,omitempty"` +} + +func (m *RequestApplySnapshotChunk) Reset() { *m = RequestApplySnapshotChunk{} } +func (m *RequestApplySnapshotChunk) String() string { return proto.CompactTextString(m) } +func (*RequestApplySnapshotChunk) ProtoMessage() {} +func (*RequestApplySnapshotChunk) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{11} +} +func (m *RequestApplySnapshotChunk) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestApplySnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestApplySnapshotChunk.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestApplySnapshotChunk) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestApplySnapshotChunk.Merge(m, src) +} +func (m *RequestApplySnapshotChunk) XXX_Size() int { + return m.Size() +} +func (m *RequestApplySnapshotChunk) XXX_DiscardUnknown() { + xxx_messageInfo_RequestApplySnapshotChunk.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestApplySnapshotChunk proto.InternalMessageInfo + +func (m *RequestApplySnapshotChunk) GetIndex() uint32 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *RequestApplySnapshotChunk) GetChunk() []byte { + if m != nil { + return m.Chunk + } + return nil +} + +func (m *RequestApplySnapshotChunk) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +type RequestPrepareProposal struct { + // the modified transactions cannot exceed this size. + MaxTxBytes int64 `protobuf:"varint,1,opt,name=max_tx_bytes,json=maxTxBytes,proto3" json:"max_tx_bytes,omitempty"` + // txs is an array of transactions that will be included in a block, + // sent to the app for possible modifications. + Txs [][]byte `protobuf:"bytes,2,rep,name=txs,proto3" json:"txs,omitempty"` + LocalLastCommit ExtendedCommitInfo `protobuf:"bytes,3,opt,name=local_last_commit,json=localLastCommit,proto3" json:"local_last_commit"` + Misbehavior []Misbehavior `protobuf:"bytes,4,rep,name=misbehavior,proto3" json:"misbehavior"` + Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"` + Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"` + NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"` + // address of the public key of the validator proposing the block. + ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` +} + +func (m *RequestPrepareProposal) Reset() { *m = RequestPrepareProposal{} } +func (m *RequestPrepareProposal) String() string { return proto.CompactTextString(m) } +func (*RequestPrepareProposal) ProtoMessage() {} +func (*RequestPrepareProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{12} +} +func (m *RequestPrepareProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestPrepareProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestPrepareProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestPrepareProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestPrepareProposal.Merge(m, src) +} +func (m *RequestPrepareProposal) XXX_Size() int { + return m.Size() +} +func (m *RequestPrepareProposal) XXX_DiscardUnknown() { + xxx_messageInfo_RequestPrepareProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestPrepareProposal proto.InternalMessageInfo + +func (m *RequestPrepareProposal) GetMaxTxBytes() int64 { + if m != nil { + return m.MaxTxBytes + } + return 0 +} + +func (m *RequestPrepareProposal) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +func (m *RequestPrepareProposal) GetLocalLastCommit() ExtendedCommitInfo { + if m != nil { + return m.LocalLastCommit + } + return ExtendedCommitInfo{} +} + +func (m *RequestPrepareProposal) GetMisbehavior() []Misbehavior { + if m != nil { + return m.Misbehavior + } + return nil +} + +func (m *RequestPrepareProposal) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestPrepareProposal) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *RequestPrepareProposal) GetNextValidatorsHash() []byte { + if m != nil { + return m.NextValidatorsHash + } + return nil +} + +func (m *RequestPrepareProposal) GetProposerAddress() []byte { + if m != nil { + return m.ProposerAddress + } + return nil +} + +type RequestProcessProposal struct { + Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` + ProposedLastCommit CommitInfo `protobuf:"bytes,2,opt,name=proposed_last_commit,json=proposedLastCommit,proto3" json:"proposed_last_commit"` + Misbehavior []Misbehavior `protobuf:"bytes,3,rep,name=misbehavior,proto3" json:"misbehavior"` + // hash is the merkle root hash of the fields of the proposed block. + Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"` + Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"` + Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"` + NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"` + // address of the public key of the original proposer of the block. + ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` +} + +func (m *RequestProcessProposal) Reset() { *m = RequestProcessProposal{} } +func (m *RequestProcessProposal) String() string { return proto.CompactTextString(m) } +func (*RequestProcessProposal) ProtoMessage() {} +func (*RequestProcessProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{13} +} +func (m *RequestProcessProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestProcessProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestProcessProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestProcessProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestProcessProposal.Merge(m, src) +} +func (m *RequestProcessProposal) XXX_Size() int { + return m.Size() +} +func (m *RequestProcessProposal) XXX_DiscardUnknown() { + xxx_messageInfo_RequestProcessProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestProcessProposal proto.InternalMessageInfo + +func (m *RequestProcessProposal) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +func (m *RequestProcessProposal) GetProposedLastCommit() CommitInfo { + if m != nil { + return m.ProposedLastCommit + } + return CommitInfo{} +} + +func (m *RequestProcessProposal) GetMisbehavior() []Misbehavior { + if m != nil { + return m.Misbehavior + } + return nil +} + +func (m *RequestProcessProposal) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *RequestProcessProposal) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestProcessProposal) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *RequestProcessProposal) GetNextValidatorsHash() []byte { + if m != nil { + return m.NextValidatorsHash + } + return nil +} + +func (m *RequestProcessProposal) GetProposerAddress() []byte { + if m != nil { + return m.ProposerAddress + } + return nil +} + +// Extends a vote with application-injected data +type RequestExtendVote struct { + // the hash of the block that this vote may be referring to + Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + // the height of the extended vote + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + // info of the block that this vote may be referring to + Time time.Time `protobuf:"bytes,3,opt,name=time,proto3,stdtime" json:"time"` + Txs [][]byte `protobuf:"bytes,4,rep,name=txs,proto3" json:"txs,omitempty"` + ProposedLastCommit CommitInfo `protobuf:"bytes,5,opt,name=proposed_last_commit,json=proposedLastCommit,proto3" json:"proposed_last_commit"` + Misbehavior []Misbehavior `protobuf:"bytes,6,rep,name=misbehavior,proto3" json:"misbehavior"` + NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"` + // address of the public key of the original proposer of the block. + ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` +} + +func (m *RequestExtendVote) Reset() { *m = RequestExtendVote{} } +func (m *RequestExtendVote) String() string { return proto.CompactTextString(m) } +func (*RequestExtendVote) ProtoMessage() {} +func (*RequestExtendVote) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{14} +} +func (m *RequestExtendVote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestExtendVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestExtendVote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestExtendVote) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestExtendVote.Merge(m, src) +} +func (m *RequestExtendVote) XXX_Size() int { + return m.Size() +} +func (m *RequestExtendVote) XXX_DiscardUnknown() { + xxx_messageInfo_RequestExtendVote.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestExtendVote proto.InternalMessageInfo + +func (m *RequestExtendVote) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *RequestExtendVote) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestExtendVote) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *RequestExtendVote) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +func (m *RequestExtendVote) GetProposedLastCommit() CommitInfo { + if m != nil { + return m.ProposedLastCommit + } + return CommitInfo{} +} + +func (m *RequestExtendVote) GetMisbehavior() []Misbehavior { + if m != nil { + return m.Misbehavior + } + return nil +} + +func (m *RequestExtendVote) GetNextValidatorsHash() []byte { + if m != nil { + return m.NextValidatorsHash + } + return nil +} + +func (m *RequestExtendVote) GetProposerAddress() []byte { + if m != nil { + return m.ProposerAddress + } + return nil +} + +// Verify the vote extension +type RequestVerifyVoteExtension struct { + // the hash of the block that this received vote corresponds to + Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + // the validator that signed the vote extension + ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + VoteExtension []byte `protobuf:"bytes,4,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"` +} + +func (m *RequestVerifyVoteExtension) Reset() { *m = RequestVerifyVoteExtension{} } +func (m *RequestVerifyVoteExtension) String() string { return proto.CompactTextString(m) } +func (*RequestVerifyVoteExtension) ProtoMessage() {} +func (*RequestVerifyVoteExtension) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{15} +} +func (m *RequestVerifyVoteExtension) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestVerifyVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestVerifyVoteExtension.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestVerifyVoteExtension) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestVerifyVoteExtension.Merge(m, src) +} +func (m *RequestVerifyVoteExtension) XXX_Size() int { + return m.Size() +} +func (m *RequestVerifyVoteExtension) XXX_DiscardUnknown() { + xxx_messageInfo_RequestVerifyVoteExtension.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestVerifyVoteExtension proto.InternalMessageInfo + +func (m *RequestVerifyVoteExtension) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *RequestVerifyVoteExtension) GetValidatorAddress() []byte { + if m != nil { + return m.ValidatorAddress + } + return nil +} + +func (m *RequestVerifyVoteExtension) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestVerifyVoteExtension) GetVoteExtension() []byte { + if m != nil { + return m.VoteExtension + } + return nil +} + +type RequestFinalizeBlock struct { + Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` + DecidedLastCommit CommitInfo `protobuf:"bytes,2,opt,name=decided_last_commit,json=decidedLastCommit,proto3" json:"decided_last_commit"` + Misbehavior []Misbehavior `protobuf:"bytes,3,rep,name=misbehavior,proto3" json:"misbehavior"` + // hash is the merkle root hash of the fields of the decided block. + Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"` + Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"` + Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"` + NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"` + // proposer_address is the address of the public key of the original proposer of the block. + ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` +} + +func (m *RequestFinalizeBlock) Reset() { *m = RequestFinalizeBlock{} } +func (m *RequestFinalizeBlock) String() string { return proto.CompactTextString(m) } +func (*RequestFinalizeBlock) ProtoMessage() {} +func (*RequestFinalizeBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{16} +} +func (m *RequestFinalizeBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestFinalizeBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestFinalizeBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestFinalizeBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestFinalizeBlock.Merge(m, src) +} +func (m *RequestFinalizeBlock) XXX_Size() int { + return m.Size() +} +func (m *RequestFinalizeBlock) XXX_DiscardUnknown() { + xxx_messageInfo_RequestFinalizeBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestFinalizeBlock proto.InternalMessageInfo + +func (m *RequestFinalizeBlock) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +func (m *RequestFinalizeBlock) GetDecidedLastCommit() CommitInfo { + if m != nil { + return m.DecidedLastCommit + } + return CommitInfo{} +} + +func (m *RequestFinalizeBlock) GetMisbehavior() []Misbehavior { + if m != nil { + return m.Misbehavior + } + return nil +} + +func (m *RequestFinalizeBlock) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *RequestFinalizeBlock) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *RequestFinalizeBlock) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *RequestFinalizeBlock) GetNextValidatorsHash() []byte { + if m != nil { + return m.NextValidatorsHash + } + return nil +} + +func (m *RequestFinalizeBlock) GetProposerAddress() []byte { + if m != nil { + return m.ProposerAddress + } + return nil +} + +type Response struct { + // Types that are valid to be assigned to Value: + // + // *Response_Exception + // *Response_Echo + // *Response_Flush + // *Response_Info + // *Response_InitChain + // *Response_Query + // *Response_CheckTx + // *Response_Commit + // *Response_ListSnapshots + // *Response_OfferSnapshot + // *Response_LoadSnapshotChunk + // *Response_ApplySnapshotChunk + // *Response_PrepareProposal + // *Response_ProcessProposal + // *Response_ExtendVote + // *Response_VerifyVoteExtension + // *Response_FinalizeBlock + Value isResponse_Value `protobuf_oneof:"value"` +} + +func (m *Response) Reset() { *m = Response{} } +func (m *Response) String() string { return proto.CompactTextString(m) } +func (*Response) ProtoMessage() {} +func (*Response) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{17} +} +func (m *Response) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Response.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Response) XXX_Merge(src proto.Message) { + xxx_messageInfo_Response.Merge(m, src) +} +func (m *Response) XXX_Size() int { + return m.Size() +} +func (m *Response) XXX_DiscardUnknown() { + xxx_messageInfo_Response.DiscardUnknown(m) +} + +var xxx_messageInfo_Response proto.InternalMessageInfo + +type isResponse_Value interface { + isResponse_Value() + MarshalTo([]byte) (int, error) + Size() int +} + +type Response_Exception struct { + Exception *ResponseException `protobuf:"bytes,1,opt,name=exception,proto3,oneof" json:"exception,omitempty"` +} +type Response_Echo struct { + Echo *ResponseEcho `protobuf:"bytes,2,opt,name=echo,proto3,oneof" json:"echo,omitempty"` +} +type Response_Flush struct { + Flush *ResponseFlush `protobuf:"bytes,3,opt,name=flush,proto3,oneof" json:"flush,omitempty"` +} +type Response_Info struct { + Info *ResponseInfo `protobuf:"bytes,4,opt,name=info,proto3,oneof" json:"info,omitempty"` +} +type Response_InitChain struct { + InitChain *ResponseInitChain `protobuf:"bytes,6,opt,name=init_chain,json=initChain,proto3,oneof" json:"init_chain,omitempty"` +} +type Response_Query struct { + Query *ResponseQuery `protobuf:"bytes,7,opt,name=query,proto3,oneof" json:"query,omitempty"` +} +type Response_CheckTx struct { + CheckTx *ResponseCheckTx `protobuf:"bytes,9,opt,name=check_tx,json=checkTx,proto3,oneof" json:"check_tx,omitempty"` +} +type Response_Commit struct { + Commit *ResponseCommit `protobuf:"bytes,12,opt,name=commit,proto3,oneof" json:"commit,omitempty"` +} +type Response_ListSnapshots struct { + ListSnapshots *ResponseListSnapshots `protobuf:"bytes,13,opt,name=list_snapshots,json=listSnapshots,proto3,oneof" json:"list_snapshots,omitempty"` +} +type Response_OfferSnapshot struct { + OfferSnapshot *ResponseOfferSnapshot `protobuf:"bytes,14,opt,name=offer_snapshot,json=offerSnapshot,proto3,oneof" json:"offer_snapshot,omitempty"` +} +type Response_LoadSnapshotChunk struct { + LoadSnapshotChunk *ResponseLoadSnapshotChunk `protobuf:"bytes,15,opt,name=load_snapshot_chunk,json=loadSnapshotChunk,proto3,oneof" json:"load_snapshot_chunk,omitempty"` +} +type Response_ApplySnapshotChunk struct { + ApplySnapshotChunk *ResponseApplySnapshotChunk `protobuf:"bytes,16,opt,name=apply_snapshot_chunk,json=applySnapshotChunk,proto3,oneof" json:"apply_snapshot_chunk,omitempty"` +} +type Response_PrepareProposal struct { + PrepareProposal *ResponsePrepareProposal `protobuf:"bytes,17,opt,name=prepare_proposal,json=prepareProposal,proto3,oneof" json:"prepare_proposal,omitempty"` +} +type Response_ProcessProposal struct { + ProcessProposal *ResponseProcessProposal `protobuf:"bytes,18,opt,name=process_proposal,json=processProposal,proto3,oneof" json:"process_proposal,omitempty"` +} +type Response_ExtendVote struct { + ExtendVote *ResponseExtendVote `protobuf:"bytes,19,opt,name=extend_vote,json=extendVote,proto3,oneof" json:"extend_vote,omitempty"` +} +type Response_VerifyVoteExtension struct { + VerifyVoteExtension *ResponseVerifyVoteExtension `protobuf:"bytes,20,opt,name=verify_vote_extension,json=verifyVoteExtension,proto3,oneof" json:"verify_vote_extension,omitempty"` +} +type Response_FinalizeBlock struct { + FinalizeBlock *ResponseFinalizeBlock `protobuf:"bytes,21,opt,name=finalize_block,json=finalizeBlock,proto3,oneof" json:"finalize_block,omitempty"` +} + +func (*Response_Exception) isResponse_Value() {} +func (*Response_Echo) isResponse_Value() {} +func (*Response_Flush) isResponse_Value() {} +func (*Response_Info) isResponse_Value() {} +func (*Response_InitChain) isResponse_Value() {} +func (*Response_Query) isResponse_Value() {} +func (*Response_CheckTx) isResponse_Value() {} +func (*Response_Commit) isResponse_Value() {} +func (*Response_ListSnapshots) isResponse_Value() {} +func (*Response_OfferSnapshot) isResponse_Value() {} +func (*Response_LoadSnapshotChunk) isResponse_Value() {} +func (*Response_ApplySnapshotChunk) isResponse_Value() {} +func (*Response_PrepareProposal) isResponse_Value() {} +func (*Response_ProcessProposal) isResponse_Value() {} +func (*Response_ExtendVote) isResponse_Value() {} +func (*Response_VerifyVoteExtension) isResponse_Value() {} +func (*Response_FinalizeBlock) isResponse_Value() {} + +func (m *Response) GetValue() isResponse_Value { + if m != nil { + return m.Value + } + return nil +} + +func (m *Response) GetException() *ResponseException { + if x, ok := m.GetValue().(*Response_Exception); ok { + return x.Exception + } + return nil +} + +func (m *Response) GetEcho() *ResponseEcho { + if x, ok := m.GetValue().(*Response_Echo); ok { + return x.Echo + } + return nil +} + +func (m *Response) GetFlush() *ResponseFlush { + if x, ok := m.GetValue().(*Response_Flush); ok { + return x.Flush + } + return nil +} + +func (m *Response) GetInfo() *ResponseInfo { + if x, ok := m.GetValue().(*Response_Info); ok { + return x.Info + } + return nil +} + +func (m *Response) GetInitChain() *ResponseInitChain { + if x, ok := m.GetValue().(*Response_InitChain); ok { + return x.InitChain + } + return nil +} + +func (m *Response) GetQuery() *ResponseQuery { + if x, ok := m.GetValue().(*Response_Query); ok { + return x.Query + } + return nil +} + +func (m *Response) GetCheckTx() *ResponseCheckTx { + if x, ok := m.GetValue().(*Response_CheckTx); ok { + return x.CheckTx + } + return nil +} + +func (m *Response) GetCommit() *ResponseCommit { + if x, ok := m.GetValue().(*Response_Commit); ok { + return x.Commit + } + return nil +} + +func (m *Response) GetListSnapshots() *ResponseListSnapshots { + if x, ok := m.GetValue().(*Response_ListSnapshots); ok { + return x.ListSnapshots + } + return nil +} + +func (m *Response) GetOfferSnapshot() *ResponseOfferSnapshot { + if x, ok := m.GetValue().(*Response_OfferSnapshot); ok { + return x.OfferSnapshot + } + return nil +} + +func (m *Response) GetLoadSnapshotChunk() *ResponseLoadSnapshotChunk { + if x, ok := m.GetValue().(*Response_LoadSnapshotChunk); ok { + return x.LoadSnapshotChunk + } + return nil +} + +func (m *Response) GetApplySnapshotChunk() *ResponseApplySnapshotChunk { + if x, ok := m.GetValue().(*Response_ApplySnapshotChunk); ok { + return x.ApplySnapshotChunk + } + return nil +} + +func (m *Response) GetPrepareProposal() *ResponsePrepareProposal { + if x, ok := m.GetValue().(*Response_PrepareProposal); ok { + return x.PrepareProposal + } + return nil +} + +func (m *Response) GetProcessProposal() *ResponseProcessProposal { + if x, ok := m.GetValue().(*Response_ProcessProposal); ok { + return x.ProcessProposal + } + return nil +} + +func (m *Response) GetExtendVote() *ResponseExtendVote { + if x, ok := m.GetValue().(*Response_ExtendVote); ok { + return x.ExtendVote + } + return nil +} + +func (m *Response) GetVerifyVoteExtension() *ResponseVerifyVoteExtension { + if x, ok := m.GetValue().(*Response_VerifyVoteExtension); ok { + return x.VerifyVoteExtension + } + return nil +} + +func (m *Response) GetFinalizeBlock() *ResponseFinalizeBlock { + if x, ok := m.GetValue().(*Response_FinalizeBlock); ok { + return x.FinalizeBlock + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Response) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Response_Exception)(nil), + (*Response_Echo)(nil), + (*Response_Flush)(nil), + (*Response_Info)(nil), + (*Response_InitChain)(nil), + (*Response_Query)(nil), + (*Response_CheckTx)(nil), + (*Response_Commit)(nil), + (*Response_ListSnapshots)(nil), + (*Response_OfferSnapshot)(nil), + (*Response_LoadSnapshotChunk)(nil), + (*Response_ApplySnapshotChunk)(nil), + (*Response_PrepareProposal)(nil), + (*Response_ProcessProposal)(nil), + (*Response_ExtendVote)(nil), + (*Response_VerifyVoteExtension)(nil), + (*Response_FinalizeBlock)(nil), + } +} + +// nondeterministic +type ResponseException struct { + Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` +} + +func (m *ResponseException) Reset() { *m = ResponseException{} } +func (m *ResponseException) String() string { return proto.CompactTextString(m) } +func (*ResponseException) ProtoMessage() {} +func (*ResponseException) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{18} +} +func (m *ResponseException) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseException) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseException.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseException) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseException.Merge(m, src) +} +func (m *ResponseException) XXX_Size() int { + return m.Size() +} +func (m *ResponseException) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseException.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseException proto.InternalMessageInfo + +func (m *ResponseException) GetError() string { + if m != nil { + return m.Error + } + return "" +} + +type ResponseEcho struct { + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (m *ResponseEcho) Reset() { *m = ResponseEcho{} } +func (m *ResponseEcho) String() string { return proto.CompactTextString(m) } +func (*ResponseEcho) ProtoMessage() {} +func (*ResponseEcho) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{19} +} +func (m *ResponseEcho) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseEcho) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseEcho.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseEcho) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseEcho.Merge(m, src) +} +func (m *ResponseEcho) XXX_Size() int { + return m.Size() +} +func (m *ResponseEcho) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseEcho.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseEcho proto.InternalMessageInfo + +func (m *ResponseEcho) GetMessage() string { + if m != nil { + return m.Message + } + return "" +} + +type ResponseFlush struct { +} + +func (m *ResponseFlush) Reset() { *m = ResponseFlush{} } +func (m *ResponseFlush) String() string { return proto.CompactTextString(m) } +func (*ResponseFlush) ProtoMessage() {} +func (*ResponseFlush) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{20} +} +func (m *ResponseFlush) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseFlush) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseFlush.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseFlush) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseFlush.Merge(m, src) +} +func (m *ResponseFlush) XXX_Size() int { + return m.Size() +} +func (m *ResponseFlush) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseFlush.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseFlush proto.InternalMessageInfo + +type ResponseInfo struct { + Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` + AppVersion uint64 `protobuf:"varint,3,opt,name=app_version,json=appVersion,proto3" json:"app_version,omitempty"` + LastBlockHeight int64 `protobuf:"varint,4,opt,name=last_block_height,json=lastBlockHeight,proto3" json:"last_block_height,omitempty"` + LastBlockAppHash []byte `protobuf:"bytes,5,opt,name=last_block_app_hash,json=lastBlockAppHash,proto3" json:"last_block_app_hash,omitempty"` +} + +func (m *ResponseInfo) Reset() { *m = ResponseInfo{} } +func (m *ResponseInfo) String() string { return proto.CompactTextString(m) } +func (*ResponseInfo) ProtoMessage() {} +func (*ResponseInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{21} +} +func (m *ResponseInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseInfo.Merge(m, src) +} +func (m *ResponseInfo) XXX_Size() int { + return m.Size() +} +func (m *ResponseInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseInfo proto.InternalMessageInfo + +func (m *ResponseInfo) GetData() string { + if m != nil { + return m.Data + } + return "" +} + +func (m *ResponseInfo) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *ResponseInfo) GetAppVersion() uint64 { + if m != nil { + return m.AppVersion + } + return 0 +} + +func (m *ResponseInfo) GetLastBlockHeight() int64 { + if m != nil { + return m.LastBlockHeight + } + return 0 +} + +func (m *ResponseInfo) GetLastBlockAppHash() []byte { + if m != nil { + return m.LastBlockAppHash + } + return nil +} + +type ResponseInitChain struct { + ConsensusParams *types1.ConsensusParams `protobuf:"bytes,1,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params,omitempty"` + Validators []ValidatorUpdate `protobuf:"bytes,2,rep,name=validators,proto3" json:"validators"` + AppHash []byte `protobuf:"bytes,3,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` +} + +func (m *ResponseInitChain) Reset() { *m = ResponseInitChain{} } +func (m *ResponseInitChain) String() string { return proto.CompactTextString(m) } +func (*ResponseInitChain) ProtoMessage() {} +func (*ResponseInitChain) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{22} +} +func (m *ResponseInitChain) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseInitChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseInitChain.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseInitChain) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseInitChain.Merge(m, src) +} +func (m *ResponseInitChain) XXX_Size() int { + return m.Size() +} +func (m *ResponseInitChain) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseInitChain.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseInitChain proto.InternalMessageInfo + +func (m *ResponseInitChain) GetConsensusParams() *types1.ConsensusParams { + if m != nil { + return m.ConsensusParams + } + return nil +} + +func (m *ResponseInitChain) GetValidators() []ValidatorUpdate { + if m != nil { + return m.Validators + } + return nil +} + +func (m *ResponseInitChain) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +type ResponseQuery struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + // bytes data = 2; // use "value" instead. + Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"` + Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"` + Index int64 `protobuf:"varint,5,opt,name=index,proto3" json:"index,omitempty"` + Key []byte `protobuf:"bytes,6,opt,name=key,proto3" json:"key,omitempty"` + Value []byte `protobuf:"bytes,7,opt,name=value,proto3" json:"value,omitempty"` + ProofOps *crypto.ProofOps `protobuf:"bytes,8,opt,name=proof_ops,json=proofOps,proto3" json:"proof_ops,omitempty"` + Height int64 `protobuf:"varint,9,opt,name=height,proto3" json:"height,omitempty"` + Codespace string `protobuf:"bytes,10,opt,name=codespace,proto3" json:"codespace,omitempty"` +} + +func (m *ResponseQuery) Reset() { *m = ResponseQuery{} } +func (m *ResponseQuery) String() string { return proto.CompactTextString(m) } +func (*ResponseQuery) ProtoMessage() {} +func (*ResponseQuery) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{23} +} +func (m *ResponseQuery) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseQuery) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseQuery.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseQuery) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseQuery.Merge(m, src) +} +func (m *ResponseQuery) XXX_Size() int { + return m.Size() +} +func (m *ResponseQuery) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseQuery.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseQuery proto.InternalMessageInfo + +func (m *ResponseQuery) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *ResponseQuery) GetLog() string { + if m != nil { + return m.Log + } + return "" +} + +func (m *ResponseQuery) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *ResponseQuery) GetIndex() int64 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *ResponseQuery) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func (m *ResponseQuery) GetValue() []byte { + if m != nil { + return m.Value + } + return nil +} + +func (m *ResponseQuery) GetProofOps() *crypto.ProofOps { + if m != nil { + return m.ProofOps + } + return nil +} + +func (m *ResponseQuery) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ResponseQuery) GetCodespace() string { + if m != nil { + return m.Codespace + } + return "" +} + +type ResponseCheckTx struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` + Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"` + Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"` + GasWanted int64 `protobuf:"varint,5,opt,name=gas_wanted,proto3" json:"gas_wanted,omitempty"` + GasUsed int64 `protobuf:"varint,6,opt,name=gas_used,proto3" json:"gas_used,omitempty"` + Events []Event `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"` + Codespace string `protobuf:"bytes,8,opt,name=codespace,proto3" json:"codespace,omitempty"` +} + +func (m *ResponseCheckTx) Reset() { *m = ResponseCheckTx{} } +func (m *ResponseCheckTx) String() string { return proto.CompactTextString(m) } +func (*ResponseCheckTx) ProtoMessage() {} +func (*ResponseCheckTx) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{24} +} +func (m *ResponseCheckTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseCheckTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseCheckTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseCheckTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseCheckTx.Merge(m, src) +} +func (m *ResponseCheckTx) XXX_Size() int { + return m.Size() +} +func (m *ResponseCheckTx) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseCheckTx.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseCheckTx proto.InternalMessageInfo + +func (m *ResponseCheckTx) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *ResponseCheckTx) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *ResponseCheckTx) GetLog() string { + if m != nil { + return m.Log + } + return "" +} + +func (m *ResponseCheckTx) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *ResponseCheckTx) GetGasWanted() int64 { + if m != nil { + return m.GasWanted + } + return 0 +} + +func (m *ResponseCheckTx) GetGasUsed() int64 { + if m != nil { + return m.GasUsed + } + return 0 +} + +func (m *ResponseCheckTx) GetEvents() []Event { + if m != nil { + return m.Events + } + return nil +} + +func (m *ResponseCheckTx) GetCodespace() string { + if m != nil { + return m.Codespace + } + return "" +} + +type ResponseCommit struct { + RetainHeight int64 `protobuf:"varint,3,opt,name=retain_height,json=retainHeight,proto3" json:"retain_height,omitempty"` +} + +func (m *ResponseCommit) Reset() { *m = ResponseCommit{} } +func (m *ResponseCommit) String() string { return proto.CompactTextString(m) } +func (*ResponseCommit) ProtoMessage() {} +func (*ResponseCommit) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{25} +} +func (m *ResponseCommit) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseCommit.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseCommit) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseCommit.Merge(m, src) +} +func (m *ResponseCommit) XXX_Size() int { + return m.Size() +} +func (m *ResponseCommit) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseCommit.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseCommit proto.InternalMessageInfo + +func (m *ResponseCommit) GetRetainHeight() int64 { + if m != nil { + return m.RetainHeight + } + return 0 +} + +type ResponseListSnapshots struct { + Snapshots []*Snapshot `protobuf:"bytes,1,rep,name=snapshots,proto3" json:"snapshots,omitempty"` +} + +func (m *ResponseListSnapshots) Reset() { *m = ResponseListSnapshots{} } +func (m *ResponseListSnapshots) String() string { return proto.CompactTextString(m) } +func (*ResponseListSnapshots) ProtoMessage() {} +func (*ResponseListSnapshots) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{26} +} +func (m *ResponseListSnapshots) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseListSnapshots) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseListSnapshots.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseListSnapshots) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseListSnapshots.Merge(m, src) +} +func (m *ResponseListSnapshots) XXX_Size() int { + return m.Size() +} +func (m *ResponseListSnapshots) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseListSnapshots.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseListSnapshots proto.InternalMessageInfo + +func (m *ResponseListSnapshots) GetSnapshots() []*Snapshot { + if m != nil { + return m.Snapshots + } + return nil +} + +type ResponseOfferSnapshot struct { + Result ResponseOfferSnapshot_Result `protobuf:"varint,1,opt,name=result,proto3,enum=tendermint.abci.ResponseOfferSnapshot_Result" json:"result,omitempty"` +} + +func (m *ResponseOfferSnapshot) Reset() { *m = ResponseOfferSnapshot{} } +func (m *ResponseOfferSnapshot) String() string { return proto.CompactTextString(m) } +func (*ResponseOfferSnapshot) ProtoMessage() {} +func (*ResponseOfferSnapshot) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{27} +} +func (m *ResponseOfferSnapshot) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseOfferSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseOfferSnapshot.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseOfferSnapshot) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseOfferSnapshot.Merge(m, src) +} +func (m *ResponseOfferSnapshot) XXX_Size() int { + return m.Size() +} +func (m *ResponseOfferSnapshot) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseOfferSnapshot.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseOfferSnapshot proto.InternalMessageInfo + +func (m *ResponseOfferSnapshot) GetResult() ResponseOfferSnapshot_Result { + if m != nil { + return m.Result + } + return ResponseOfferSnapshot_UNKNOWN +} + +type ResponseLoadSnapshotChunk struct { + Chunk []byte `protobuf:"bytes,1,opt,name=chunk,proto3" json:"chunk,omitempty"` +} + +func (m *ResponseLoadSnapshotChunk) Reset() { *m = ResponseLoadSnapshotChunk{} } +func (m *ResponseLoadSnapshotChunk) String() string { return proto.CompactTextString(m) } +func (*ResponseLoadSnapshotChunk) ProtoMessage() {} +func (*ResponseLoadSnapshotChunk) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{28} +} +func (m *ResponseLoadSnapshotChunk) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseLoadSnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseLoadSnapshotChunk.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseLoadSnapshotChunk) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseLoadSnapshotChunk.Merge(m, src) +} +func (m *ResponseLoadSnapshotChunk) XXX_Size() int { + return m.Size() +} +func (m *ResponseLoadSnapshotChunk) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseLoadSnapshotChunk.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseLoadSnapshotChunk proto.InternalMessageInfo + +func (m *ResponseLoadSnapshotChunk) GetChunk() []byte { + if m != nil { + return m.Chunk + } + return nil +} + +type ResponseApplySnapshotChunk struct { + Result ResponseApplySnapshotChunk_Result `protobuf:"varint,1,opt,name=result,proto3,enum=tendermint.abci.ResponseApplySnapshotChunk_Result" json:"result,omitempty"` + RefetchChunks []uint32 `protobuf:"varint,2,rep,packed,name=refetch_chunks,json=refetchChunks,proto3" json:"refetch_chunks,omitempty"` + RejectSenders []string `protobuf:"bytes,3,rep,name=reject_senders,json=rejectSenders,proto3" json:"reject_senders,omitempty"` +} + +func (m *ResponseApplySnapshotChunk) Reset() { *m = ResponseApplySnapshotChunk{} } +func (m *ResponseApplySnapshotChunk) String() string { return proto.CompactTextString(m) } +func (*ResponseApplySnapshotChunk) ProtoMessage() {} +func (*ResponseApplySnapshotChunk) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{29} +} +func (m *ResponseApplySnapshotChunk) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseApplySnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseApplySnapshotChunk.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseApplySnapshotChunk) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseApplySnapshotChunk.Merge(m, src) +} +func (m *ResponseApplySnapshotChunk) XXX_Size() int { + return m.Size() +} +func (m *ResponseApplySnapshotChunk) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseApplySnapshotChunk.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseApplySnapshotChunk proto.InternalMessageInfo + +func (m *ResponseApplySnapshotChunk) GetResult() ResponseApplySnapshotChunk_Result { + if m != nil { + return m.Result + } + return ResponseApplySnapshotChunk_UNKNOWN +} + +func (m *ResponseApplySnapshotChunk) GetRefetchChunks() []uint32 { + if m != nil { + return m.RefetchChunks + } + return nil +} + +func (m *ResponseApplySnapshotChunk) GetRejectSenders() []string { + if m != nil { + return m.RejectSenders + } + return nil +} + +type ResponsePrepareProposal struct { + Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` +} + +func (m *ResponsePrepareProposal) Reset() { *m = ResponsePrepareProposal{} } +func (m *ResponsePrepareProposal) String() string { return proto.CompactTextString(m) } +func (*ResponsePrepareProposal) ProtoMessage() {} +func (*ResponsePrepareProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{30} +} +func (m *ResponsePrepareProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponsePrepareProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponsePrepareProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponsePrepareProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponsePrepareProposal.Merge(m, src) +} +func (m *ResponsePrepareProposal) XXX_Size() int { + return m.Size() +} +func (m *ResponsePrepareProposal) XXX_DiscardUnknown() { + xxx_messageInfo_ResponsePrepareProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponsePrepareProposal proto.InternalMessageInfo + +func (m *ResponsePrepareProposal) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +type ResponseProcessProposal struct { + Status ResponseProcessProposal_ProposalStatus `protobuf:"varint,1,opt,name=status,proto3,enum=tendermint.abci.ResponseProcessProposal_ProposalStatus" json:"status,omitempty"` +} + +func (m *ResponseProcessProposal) Reset() { *m = ResponseProcessProposal{} } +func (m *ResponseProcessProposal) String() string { return proto.CompactTextString(m) } +func (*ResponseProcessProposal) ProtoMessage() {} +func (*ResponseProcessProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{31} +} +func (m *ResponseProcessProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseProcessProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseProcessProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseProcessProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseProcessProposal.Merge(m, src) +} +func (m *ResponseProcessProposal) XXX_Size() int { + return m.Size() +} +func (m *ResponseProcessProposal) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseProcessProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseProcessProposal proto.InternalMessageInfo + +func (m *ResponseProcessProposal) GetStatus() ResponseProcessProposal_ProposalStatus { + if m != nil { + return m.Status + } + return ResponseProcessProposal_UNKNOWN +} + +type ResponseExtendVote struct { + VoteExtension []byte `protobuf:"bytes,1,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"` +} + +func (m *ResponseExtendVote) Reset() { *m = ResponseExtendVote{} } +func (m *ResponseExtendVote) String() string { return proto.CompactTextString(m) } +func (*ResponseExtendVote) ProtoMessage() {} +func (*ResponseExtendVote) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{32} +} +func (m *ResponseExtendVote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseExtendVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseExtendVote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseExtendVote) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseExtendVote.Merge(m, src) +} +func (m *ResponseExtendVote) XXX_Size() int { + return m.Size() +} +func (m *ResponseExtendVote) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseExtendVote.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseExtendVote proto.InternalMessageInfo + +func (m *ResponseExtendVote) GetVoteExtension() []byte { + if m != nil { + return m.VoteExtension + } + return nil +} + +type ResponseVerifyVoteExtension struct { + Status ResponseVerifyVoteExtension_VerifyStatus `protobuf:"varint,1,opt,name=status,proto3,enum=tendermint.abci.ResponseVerifyVoteExtension_VerifyStatus" json:"status,omitempty"` +} + +func (m *ResponseVerifyVoteExtension) Reset() { *m = ResponseVerifyVoteExtension{} } +func (m *ResponseVerifyVoteExtension) String() string { return proto.CompactTextString(m) } +func (*ResponseVerifyVoteExtension) ProtoMessage() {} +func (*ResponseVerifyVoteExtension) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{33} +} +func (m *ResponseVerifyVoteExtension) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseVerifyVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseVerifyVoteExtension.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseVerifyVoteExtension) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseVerifyVoteExtension.Merge(m, src) +} +func (m *ResponseVerifyVoteExtension) XXX_Size() int { + return m.Size() +} +func (m *ResponseVerifyVoteExtension) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseVerifyVoteExtension.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseVerifyVoteExtension proto.InternalMessageInfo + +func (m *ResponseVerifyVoteExtension) GetStatus() ResponseVerifyVoteExtension_VerifyStatus { + if m != nil { + return m.Status + } + return ResponseVerifyVoteExtension_UNKNOWN +} + +type ResponseFinalizeBlock struct { + // set of block events emmitted as part of executing the block + Events []Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` + // the result of executing each transaction including the events + // the particular transction emitted. This should match the order + // of the transactions delivered in the block itself + TxResults []*ExecTxResult `protobuf:"bytes,2,rep,name=tx_results,json=txResults,proto3" json:"tx_results,omitempty"` + // a list of updates to the validator set. These will reflect the validator set at current height + 2. + ValidatorUpdates []ValidatorUpdate `protobuf:"bytes,3,rep,name=validator_updates,json=validatorUpdates,proto3" json:"validator_updates"` + // updates to the consensus params, if any. + ConsensusParamUpdates *types1.ConsensusParams `protobuf:"bytes,4,opt,name=consensus_param_updates,json=consensusParamUpdates,proto3" json:"consensus_param_updates,omitempty"` + // app_hash is the hash of the applications' state which is used to confirm that execution of the transactions was deterministic. It is up to the application to decide which algorithm to use. + AppHash []byte `protobuf:"bytes,5,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` +} + +func (m *ResponseFinalizeBlock) Reset() { *m = ResponseFinalizeBlock{} } +func (m *ResponseFinalizeBlock) String() string { return proto.CompactTextString(m) } +func (*ResponseFinalizeBlock) ProtoMessage() {} +func (*ResponseFinalizeBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{34} +} +func (m *ResponseFinalizeBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseFinalizeBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseFinalizeBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseFinalizeBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseFinalizeBlock.Merge(m, src) +} +func (m *ResponseFinalizeBlock) XXX_Size() int { + return m.Size() +} +func (m *ResponseFinalizeBlock) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseFinalizeBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseFinalizeBlock proto.InternalMessageInfo + +func (m *ResponseFinalizeBlock) GetEvents() []Event { + if m != nil { + return m.Events + } + return nil +} + +func (m *ResponseFinalizeBlock) GetTxResults() []*ExecTxResult { + if m != nil { + return m.TxResults + } + return nil +} + +func (m *ResponseFinalizeBlock) GetValidatorUpdates() []ValidatorUpdate { + if m != nil { + return m.ValidatorUpdates + } + return nil +} + +func (m *ResponseFinalizeBlock) GetConsensusParamUpdates() *types1.ConsensusParams { + if m != nil { + return m.ConsensusParamUpdates + } + return nil +} + +func (m *ResponseFinalizeBlock) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +type CommitInfo struct { + Round int32 `protobuf:"varint,1,opt,name=round,proto3" json:"round,omitempty"` + Votes []VoteInfo `protobuf:"bytes,2,rep,name=votes,proto3" json:"votes"` +} + +func (m *CommitInfo) Reset() { *m = CommitInfo{} } +func (m *CommitInfo) String() string { return proto.CompactTextString(m) } +func (*CommitInfo) ProtoMessage() {} +func (*CommitInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{35} +} +func (m *CommitInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CommitInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CommitInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CommitInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_CommitInfo.Merge(m, src) +} +func (m *CommitInfo) XXX_Size() int { + return m.Size() +} +func (m *CommitInfo) XXX_DiscardUnknown() { + xxx_messageInfo_CommitInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_CommitInfo proto.InternalMessageInfo + +func (m *CommitInfo) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *CommitInfo) GetVotes() []VoteInfo { + if m != nil { + return m.Votes + } + return nil +} + +// ExtendedCommitInfo is similar to CommitInfo except that it is only used in +// the PrepareProposal request such that CometBFT can provide vote extensions +// to the application. +type ExtendedCommitInfo struct { + // The round at which the block proposer decided in the previous height. + Round int32 `protobuf:"varint,1,opt,name=round,proto3" json:"round,omitempty"` + // List of validators' addresses in the last validator set with their voting + // information, including vote extensions. + Votes []ExtendedVoteInfo `protobuf:"bytes,2,rep,name=votes,proto3" json:"votes"` +} + +func (m *ExtendedCommitInfo) Reset() { *m = ExtendedCommitInfo{} } +func (m *ExtendedCommitInfo) String() string { return proto.CompactTextString(m) } +func (*ExtendedCommitInfo) ProtoMessage() {} +func (*ExtendedCommitInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{36} +} +func (m *ExtendedCommitInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ExtendedCommitInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ExtendedCommitInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ExtendedCommitInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtendedCommitInfo.Merge(m, src) +} +func (m *ExtendedCommitInfo) XXX_Size() int { + return m.Size() +} +func (m *ExtendedCommitInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ExtendedCommitInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtendedCommitInfo proto.InternalMessageInfo + +func (m *ExtendedCommitInfo) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *ExtendedCommitInfo) GetVotes() []ExtendedVoteInfo { + if m != nil { + return m.Votes + } + return nil +} + +// Event allows application developers to attach additional information to +// ResponseFinalizeBlock and ResponseCheckTx. +// Later, transactions may be queried using these events. +type Event struct { + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + Attributes []EventAttribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes,omitempty"` +} + +func (m *Event) Reset() { *m = Event{} } +func (m *Event) String() string { return proto.CompactTextString(m) } +func (*Event) ProtoMessage() {} +func (*Event) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{37} +} +func (m *Event) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Event.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Event) XXX_Merge(src proto.Message) { + xxx_messageInfo_Event.Merge(m, src) +} +func (m *Event) XXX_Size() int { + return m.Size() +} +func (m *Event) XXX_DiscardUnknown() { + xxx_messageInfo_Event.DiscardUnknown(m) +} + +var xxx_messageInfo_Event proto.InternalMessageInfo + +func (m *Event) GetType() string { + if m != nil { + return m.Type + } + return "" +} + +func (m *Event) GetAttributes() []EventAttribute { + if m != nil { + return m.Attributes + } + return nil +} + +// EventAttribute is a single key-value pair, associated with an event. +type EventAttribute struct { + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + Index bool `protobuf:"varint,3,opt,name=index,proto3" json:"index,omitempty"` +} + +func (m *EventAttribute) Reset() { *m = EventAttribute{} } +func (m *EventAttribute) String() string { return proto.CompactTextString(m) } +func (*EventAttribute) ProtoMessage() {} +func (*EventAttribute) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{38} +} +func (m *EventAttribute) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EventAttribute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EventAttribute.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *EventAttribute) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventAttribute.Merge(m, src) +} +func (m *EventAttribute) XXX_Size() int { + return m.Size() +} +func (m *EventAttribute) XXX_DiscardUnknown() { + xxx_messageInfo_EventAttribute.DiscardUnknown(m) +} + +var xxx_messageInfo_EventAttribute proto.InternalMessageInfo + +func (m *EventAttribute) GetKey() string { + if m != nil { + return m.Key + } + return "" +} + +func (m *EventAttribute) GetValue() string { + if m != nil { + return m.Value + } + return "" +} + +func (m *EventAttribute) GetIndex() bool { + if m != nil { + return m.Index + } + return false +} + +// ExecTxResult contains results of executing one individual transaction. +// +// * Its structure is equivalent to #ResponseDeliverTx which will be deprecated/deleted +type ExecTxResult struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` + Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"` + Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"` + GasWanted int64 `protobuf:"varint,5,opt,name=gas_wanted,proto3" json:"gas_wanted,omitempty"` + GasUsed int64 `protobuf:"varint,6,opt,name=gas_used,proto3" json:"gas_used,omitempty"` + Events []Event `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"` + Codespace string `protobuf:"bytes,8,opt,name=codespace,proto3" json:"codespace,omitempty"` +} + +func (m *ExecTxResult) Reset() { *m = ExecTxResult{} } +func (m *ExecTxResult) String() string { return proto.CompactTextString(m) } +func (*ExecTxResult) ProtoMessage() {} +func (*ExecTxResult) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{39} +} +func (m *ExecTxResult) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ExecTxResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ExecTxResult.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ExecTxResult) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExecTxResult.Merge(m, src) +} +func (m *ExecTxResult) XXX_Size() int { + return m.Size() +} +func (m *ExecTxResult) XXX_DiscardUnknown() { + xxx_messageInfo_ExecTxResult.DiscardUnknown(m) +} + +var xxx_messageInfo_ExecTxResult proto.InternalMessageInfo + +func (m *ExecTxResult) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *ExecTxResult) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *ExecTxResult) GetLog() string { + if m != nil { + return m.Log + } + return "" +} + +func (m *ExecTxResult) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *ExecTxResult) GetGasWanted() int64 { + if m != nil { + return m.GasWanted + } + return 0 +} + +func (m *ExecTxResult) GetGasUsed() int64 { + if m != nil { + return m.GasUsed + } + return 0 +} + +func (m *ExecTxResult) GetEvents() []Event { + if m != nil { + return m.Events + } + return nil +} + +func (m *ExecTxResult) GetCodespace() string { + if m != nil { + return m.Codespace + } + return "" +} + +// TxResult contains results of executing the transaction. +// +// One usage is indexing transaction results. +type TxResult struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Index uint32 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"` + Tx []byte `protobuf:"bytes,3,opt,name=tx,proto3" json:"tx,omitempty"` + Result ExecTxResult `protobuf:"bytes,4,opt,name=result,proto3" json:"result"` +} + +func (m *TxResult) Reset() { *m = TxResult{} } +func (m *TxResult) String() string { return proto.CompactTextString(m) } +func (*TxResult) ProtoMessage() {} +func (*TxResult) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{40} +} +func (m *TxResult) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TxResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TxResult.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *TxResult) XXX_Merge(src proto.Message) { + xxx_messageInfo_TxResult.Merge(m, src) +} +func (m *TxResult) XXX_Size() int { + return m.Size() +} +func (m *TxResult) XXX_DiscardUnknown() { + xxx_messageInfo_TxResult.DiscardUnknown(m) +} + +var xxx_messageInfo_TxResult proto.InternalMessageInfo + +func (m *TxResult) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *TxResult) GetIndex() uint32 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *TxResult) GetTx() []byte { + if m != nil { + return m.Tx + } + return nil +} + +func (m *TxResult) GetResult() ExecTxResult { + if m != nil { + return m.Result + } + return ExecTxResult{} +} + +type Validator struct { + Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + // PubKey pub_key = 2 [(gogoproto.nullable)=false]; + Power int64 `protobuf:"varint,3,opt,name=power,proto3" json:"power,omitempty"` +} + +func (m *Validator) Reset() { *m = Validator{} } +func (m *Validator) String() string { return proto.CompactTextString(m) } +func (*Validator) ProtoMessage() {} +func (*Validator) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{41} +} +func (m *Validator) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Validator) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Validator.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Validator) XXX_Merge(src proto.Message) { + xxx_messageInfo_Validator.Merge(m, src) +} +func (m *Validator) XXX_Size() int { + return m.Size() +} +func (m *Validator) XXX_DiscardUnknown() { + xxx_messageInfo_Validator.DiscardUnknown(m) +} + +var xxx_messageInfo_Validator proto.InternalMessageInfo + +func (m *Validator) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + +func (m *Validator) GetPower() int64 { + if m != nil { + return m.Power + } + return 0 +} + +type ValidatorUpdate struct { + PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` + Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"` +} + +func (m *ValidatorUpdate) Reset() { *m = ValidatorUpdate{} } +func (m *ValidatorUpdate) String() string { return proto.CompactTextString(m) } +func (*ValidatorUpdate) ProtoMessage() {} +func (*ValidatorUpdate) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{42} +} +func (m *ValidatorUpdate) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValidatorUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValidatorUpdate.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValidatorUpdate) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValidatorUpdate.Merge(m, src) +} +func (m *ValidatorUpdate) XXX_Size() int { + return m.Size() +} +func (m *ValidatorUpdate) XXX_DiscardUnknown() { + xxx_messageInfo_ValidatorUpdate.DiscardUnknown(m) +} + +var xxx_messageInfo_ValidatorUpdate proto.InternalMessageInfo + +func (m *ValidatorUpdate) GetPubKey() crypto.PublicKey { + if m != nil { + return m.PubKey + } + return crypto.PublicKey{} +} + +func (m *ValidatorUpdate) GetPower() int64 { + if m != nil { + return m.Power + } + return 0 +} + +type VoteInfo struct { + Validator Validator `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator"` + BlockIdFlag types1.BlockIDFlag `protobuf:"varint,3,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"` +} + +func (m *VoteInfo) Reset() { *m = VoteInfo{} } +func (m *VoteInfo) String() string { return proto.CompactTextString(m) } +func (*VoteInfo) ProtoMessage() {} +func (*VoteInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{43} +} +func (m *VoteInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *VoteInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_VoteInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *VoteInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_VoteInfo.Merge(m, src) +} +func (m *VoteInfo) XXX_Size() int { + return m.Size() +} +func (m *VoteInfo) XXX_DiscardUnknown() { + xxx_messageInfo_VoteInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_VoteInfo proto.InternalMessageInfo + +func (m *VoteInfo) GetValidator() Validator { + if m != nil { + return m.Validator + } + return Validator{} +} + +func (m *VoteInfo) GetBlockIdFlag() types1.BlockIDFlag { + if m != nil { + return m.BlockIdFlag + } + return types1.BlockIDFlagUnknown +} + +type ExtendedVoteInfo struct { + // The validator that sent the vote. + Validator Validator `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator"` + // Non-deterministic extension provided by the sending validator's application. + VoteExtension []byte `protobuf:"bytes,3,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"` + // Vote extension signature created by CometBFT + ExtensionSignature []byte `protobuf:"bytes,4,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"` + // block_id_flag indicates whether the validator voted for a block, nil, or did not vote at all + BlockIdFlag types1.BlockIDFlag `protobuf:"varint,5,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"` +} + +func (m *ExtendedVoteInfo) Reset() { *m = ExtendedVoteInfo{} } +func (m *ExtendedVoteInfo) String() string { return proto.CompactTextString(m) } +func (*ExtendedVoteInfo) ProtoMessage() {} +func (*ExtendedVoteInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{44} +} +func (m *ExtendedVoteInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ExtendedVoteInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ExtendedVoteInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ExtendedVoteInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtendedVoteInfo.Merge(m, src) +} +func (m *ExtendedVoteInfo) XXX_Size() int { + return m.Size() +} +func (m *ExtendedVoteInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ExtendedVoteInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtendedVoteInfo proto.InternalMessageInfo + +func (m *ExtendedVoteInfo) GetValidator() Validator { + if m != nil { + return m.Validator + } + return Validator{} +} + +func (m *ExtendedVoteInfo) GetVoteExtension() []byte { + if m != nil { + return m.VoteExtension + } + return nil +} + +func (m *ExtendedVoteInfo) GetExtensionSignature() []byte { + if m != nil { + return m.ExtensionSignature + } + return nil +} + +func (m *ExtendedVoteInfo) GetBlockIdFlag() types1.BlockIDFlag { + if m != nil { + return m.BlockIdFlag + } + return types1.BlockIDFlagUnknown +} + +type Misbehavior struct { + Type MisbehaviorType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.abci.MisbehaviorType" json:"type,omitempty"` + // The offending validator + Validator Validator `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator"` + // The height when the offense occurred + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + // The corresponding time where the offense occurred + Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"` + // Total voting power of the validator set in case the ABCI application does + // not store historical validators. + // https://github.com/tendermint/tendermint/issues/4581 + TotalVotingPower int64 `protobuf:"varint,5,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` +} + +func (m *Misbehavior) Reset() { *m = Misbehavior{} } +func (m *Misbehavior) String() string { return proto.CompactTextString(m) } +func (*Misbehavior) ProtoMessage() {} +func (*Misbehavior) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{45} +} +func (m *Misbehavior) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Misbehavior) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Misbehavior.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Misbehavior) XXX_Merge(src proto.Message) { + xxx_messageInfo_Misbehavior.Merge(m, src) +} +func (m *Misbehavior) XXX_Size() int { + return m.Size() +} +func (m *Misbehavior) XXX_DiscardUnknown() { + xxx_messageInfo_Misbehavior.DiscardUnknown(m) +} + +var xxx_messageInfo_Misbehavior proto.InternalMessageInfo + +func (m *Misbehavior) GetType() MisbehaviorType { + if m != nil { + return m.Type + } + return MisbehaviorType_UNKNOWN +} + +func (m *Misbehavior) GetValidator() Validator { + if m != nil { + return m.Validator + } + return Validator{} +} + +func (m *Misbehavior) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Misbehavior) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *Misbehavior) GetTotalVotingPower() int64 { + if m != nil { + return m.TotalVotingPower + } + return 0 +} + +type Snapshot struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"` + Chunks uint32 `protobuf:"varint,3,opt,name=chunks,proto3" json:"chunks,omitempty"` + Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"` + Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"` +} + +func (m *Snapshot) Reset() { *m = Snapshot{} } +func (m *Snapshot) String() string { return proto.CompactTextString(m) } +func (*Snapshot) ProtoMessage() {} +func (*Snapshot) Descriptor() ([]byte, []int) { + return fileDescriptor_252557cfdd89a31a, []int{46} +} +func (m *Snapshot) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Snapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Snapshot.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Snapshot) XXX_Merge(src proto.Message) { + xxx_messageInfo_Snapshot.Merge(m, src) +} +func (m *Snapshot) XXX_Size() int { + return m.Size() +} +func (m *Snapshot) XXX_DiscardUnknown() { + xxx_messageInfo_Snapshot.DiscardUnknown(m) +} + +var xxx_messageInfo_Snapshot proto.InternalMessageInfo + +func (m *Snapshot) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Snapshot) GetFormat() uint32 { + if m != nil { + return m.Format + } + return 0 +} + +func (m *Snapshot) GetChunks() uint32 { + if m != nil { + return m.Chunks + } + return 0 +} + +func (m *Snapshot) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *Snapshot) GetMetadata() []byte { + if m != nil { + return m.Metadata + } + return nil +} + +func init() { + proto.RegisterEnum("tendermint.abci.CheckTxType", CheckTxType_name, CheckTxType_value) + proto.RegisterEnum("tendermint.abci.MisbehaviorType", MisbehaviorType_name, MisbehaviorType_value) + proto.RegisterEnum("tendermint.abci.ResponseOfferSnapshot_Result", ResponseOfferSnapshot_Result_name, ResponseOfferSnapshot_Result_value) + proto.RegisterEnum("tendermint.abci.ResponseApplySnapshotChunk_Result", ResponseApplySnapshotChunk_Result_name, ResponseApplySnapshotChunk_Result_value) + proto.RegisterEnum("tendermint.abci.ResponseProcessProposal_ProposalStatus", ResponseProcessProposal_ProposalStatus_name, ResponseProcessProposal_ProposalStatus_value) + proto.RegisterEnum("tendermint.abci.ResponseVerifyVoteExtension_VerifyStatus", ResponseVerifyVoteExtension_VerifyStatus_name, ResponseVerifyVoteExtension_VerifyStatus_value) + proto.RegisterType((*Request)(nil), "tendermint.abci.Request") + proto.RegisterType((*RequestEcho)(nil), "tendermint.abci.RequestEcho") + proto.RegisterType((*RequestFlush)(nil), "tendermint.abci.RequestFlush") + proto.RegisterType((*RequestInfo)(nil), "tendermint.abci.RequestInfo") + proto.RegisterType((*RequestInitChain)(nil), "tendermint.abci.RequestInitChain") + proto.RegisterType((*RequestQuery)(nil), "tendermint.abci.RequestQuery") + proto.RegisterType((*RequestCheckTx)(nil), "tendermint.abci.RequestCheckTx") + proto.RegisterType((*RequestCommit)(nil), "tendermint.abci.RequestCommit") + proto.RegisterType((*RequestListSnapshots)(nil), "tendermint.abci.RequestListSnapshots") + proto.RegisterType((*RequestOfferSnapshot)(nil), "tendermint.abci.RequestOfferSnapshot") + proto.RegisterType((*RequestLoadSnapshotChunk)(nil), "tendermint.abci.RequestLoadSnapshotChunk") + proto.RegisterType((*RequestApplySnapshotChunk)(nil), "tendermint.abci.RequestApplySnapshotChunk") + proto.RegisterType((*RequestPrepareProposal)(nil), "tendermint.abci.RequestPrepareProposal") + proto.RegisterType((*RequestProcessProposal)(nil), "tendermint.abci.RequestProcessProposal") + proto.RegisterType((*RequestExtendVote)(nil), "tendermint.abci.RequestExtendVote") + proto.RegisterType((*RequestVerifyVoteExtension)(nil), "tendermint.abci.RequestVerifyVoteExtension") + proto.RegisterType((*RequestFinalizeBlock)(nil), "tendermint.abci.RequestFinalizeBlock") + proto.RegisterType((*Response)(nil), "tendermint.abci.Response") + proto.RegisterType((*ResponseException)(nil), "tendermint.abci.ResponseException") + proto.RegisterType((*ResponseEcho)(nil), "tendermint.abci.ResponseEcho") + proto.RegisterType((*ResponseFlush)(nil), "tendermint.abci.ResponseFlush") + proto.RegisterType((*ResponseInfo)(nil), "tendermint.abci.ResponseInfo") + proto.RegisterType((*ResponseInitChain)(nil), "tendermint.abci.ResponseInitChain") + proto.RegisterType((*ResponseQuery)(nil), "tendermint.abci.ResponseQuery") + proto.RegisterType((*ResponseCheckTx)(nil), "tendermint.abci.ResponseCheckTx") + proto.RegisterType((*ResponseCommit)(nil), "tendermint.abci.ResponseCommit") + proto.RegisterType((*ResponseListSnapshots)(nil), "tendermint.abci.ResponseListSnapshots") + proto.RegisterType((*ResponseOfferSnapshot)(nil), "tendermint.abci.ResponseOfferSnapshot") + proto.RegisterType((*ResponseLoadSnapshotChunk)(nil), "tendermint.abci.ResponseLoadSnapshotChunk") + proto.RegisterType((*ResponseApplySnapshotChunk)(nil), "tendermint.abci.ResponseApplySnapshotChunk") + proto.RegisterType((*ResponsePrepareProposal)(nil), "tendermint.abci.ResponsePrepareProposal") + proto.RegisterType((*ResponseProcessProposal)(nil), "tendermint.abci.ResponseProcessProposal") + proto.RegisterType((*ResponseExtendVote)(nil), "tendermint.abci.ResponseExtendVote") + proto.RegisterType((*ResponseVerifyVoteExtension)(nil), "tendermint.abci.ResponseVerifyVoteExtension") + proto.RegisterType((*ResponseFinalizeBlock)(nil), "tendermint.abci.ResponseFinalizeBlock") + proto.RegisterType((*CommitInfo)(nil), "tendermint.abci.CommitInfo") + proto.RegisterType((*ExtendedCommitInfo)(nil), "tendermint.abci.ExtendedCommitInfo") + proto.RegisterType((*Event)(nil), "tendermint.abci.Event") + proto.RegisterType((*EventAttribute)(nil), "tendermint.abci.EventAttribute") + proto.RegisterType((*ExecTxResult)(nil), "tendermint.abci.ExecTxResult") + proto.RegisterType((*TxResult)(nil), "tendermint.abci.TxResult") + proto.RegisterType((*Validator)(nil), "tendermint.abci.Validator") + proto.RegisterType((*ValidatorUpdate)(nil), "tendermint.abci.ValidatorUpdate") + proto.RegisterType((*VoteInfo)(nil), "tendermint.abci.VoteInfo") + proto.RegisterType((*ExtendedVoteInfo)(nil), "tendermint.abci.ExtendedVoteInfo") + proto.RegisterType((*Misbehavior)(nil), "tendermint.abci.Misbehavior") + proto.RegisterType((*Snapshot)(nil), "tendermint.abci.Snapshot") +} + +func init() { proto.RegisterFile("tendermint/abci/types.proto", fileDescriptor_252557cfdd89a31a) } + +var fileDescriptor_252557cfdd89a31a = []byte{ + // 3167 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x5a, 0xcb, 0x73, 0x23, 0xd5, + 0xd5, 0x57, 0xeb, 0xad, 0xa3, 0x87, 0xdb, 0xd7, 0x9e, 0x41, 0x23, 0x06, 0xdb, 0x34, 0x05, 0x0c, + 0x03, 0xd8, 0x7c, 0x9e, 0x6f, 0x78, 0xd4, 0xc0, 0x57, 0x25, 0x6b, 0x34, 0x9f, 0xec, 0x31, 0xb6, + 0x69, 0xcb, 0x43, 0x91, 0x07, 0x4d, 0x5b, 0xba, 0xb2, 0x9a, 0x91, 0xd4, 0x4d, 0xf7, 0x95, 0x91, + 0x59, 0xa5, 0x42, 0x52, 0x95, 0x62, 0x45, 0x55, 0xb2, 0x60, 0x11, 0x16, 0x59, 0x64, 0x93, 0xbf, + 0x20, 0xab, 0x64, 0x93, 0x05, 0x8b, 0x2c, 0x58, 0x66, 0x45, 0x52, 0xb0, 0x63, 0x9b, 0x45, 0xb6, + 0xa9, 0xfb, 0xe8, 0x97, 0xa4, 0xb6, 0xa4, 0x81, 0x2c, 0x52, 0xc9, 0xae, 0xef, 0xe9, 0x73, 0xce, + 0xed, 0x7b, 0xee, 0xb9, 0xe7, 0xf1, 0xeb, 0x0b, 0x8f, 0x13, 0x3c, 0x68, 0x63, 0xbb, 0x6f, 0x0c, + 0xc8, 0x96, 0x7e, 0xda, 0x32, 0xb6, 0xc8, 0x85, 0x85, 0x9d, 0x4d, 0xcb, 0x36, 0x89, 0x89, 0x96, + 0xfc, 0x97, 0x9b, 0xf4, 0x65, 0xe5, 0x89, 0x00, 0x77, 0xcb, 0xbe, 0xb0, 0x88, 0xb9, 0x65, 0xd9, + 0xa6, 0xd9, 0xe1, 0xfc, 0x95, 0xeb, 0x93, 0xaf, 0x1f, 0xe2, 0x0b, 0xa1, 0x2d, 0x24, 0xcc, 0x66, + 0xd9, 0xb2, 0x74, 0x5b, 0xef, 0xbb, 0xaf, 0x37, 0x26, 0x5e, 0x9f, 0xeb, 0x3d, 0xa3, 0xad, 0x13, + 0xd3, 0x16, 0x1c, 0xeb, 0x67, 0xa6, 0x79, 0xd6, 0xc3, 0x5b, 0x6c, 0x74, 0x3a, 0xec, 0x6c, 0x11, + 0xa3, 0x8f, 0x1d, 0xa2, 0xf7, 0x2d, 0xc1, 0xb0, 0x7a, 0x66, 0x9e, 0x99, 0xec, 0x71, 0x8b, 0x3e, + 0x71, 0xaa, 0xf2, 0xc7, 0x1c, 0x64, 0x54, 0xfc, 0xc1, 0x10, 0x3b, 0x04, 0x6d, 0x43, 0x12, 0xb7, + 0xba, 0x66, 0x59, 0xda, 0x90, 0x6e, 0xe4, 0xb7, 0xaf, 0x6f, 0x8e, 0x2d, 0x70, 0x53, 0xf0, 0xd5, + 0x5b, 0x5d, 0xb3, 0x11, 0x53, 0x19, 0x2f, 0xba, 0x0d, 0xa9, 0x4e, 0x6f, 0xe8, 0x74, 0xcb, 0x71, + 0x26, 0xf4, 0x44, 0x94, 0xd0, 0x3d, 0xca, 0xd4, 0x88, 0xa9, 0x9c, 0x9b, 0x4e, 0x65, 0x0c, 0x3a, + 0x66, 0x39, 0x71, 0xf9, 0x54, 0xbb, 0x83, 0x0e, 0x9b, 0x8a, 0xf2, 0xa2, 0x1d, 0x00, 0x63, 0x60, + 0x10, 0xad, 0xd5, 0xd5, 0x8d, 0x41, 0x39, 0xc5, 0x24, 0x9f, 0x8c, 0x96, 0x34, 0x48, 0x8d, 0x32, + 0x36, 0x62, 0x6a, 0xce, 0x70, 0x07, 0xf4, 0x73, 0x3f, 0x18, 0x62, 0xfb, 0xa2, 0x9c, 0xbe, 0xfc, + 0x73, 0xdf, 0xa2, 0x4c, 0xf4, 0x73, 0x19, 0x37, 0x7a, 0x1d, 0xb2, 0xad, 0x2e, 0x6e, 0x3d, 0xd4, + 0xc8, 0xa8, 0x9c, 0x65, 0x92, 0xeb, 0x51, 0x92, 0x35, 0xca, 0xd7, 0x1c, 0x35, 0x62, 0x6a, 0xa6, + 0xc5, 0x1f, 0xd1, 0xab, 0x90, 0x6e, 0x99, 0xfd, 0xbe, 0x41, 0xca, 0x79, 0x26, 0xbb, 0x16, 0x29, + 0xcb, 0xb8, 0x1a, 0x31, 0x55, 0xf0, 0xa3, 0x03, 0x28, 0xf5, 0x0c, 0x87, 0x68, 0xce, 0x40, 0xb7, + 0x9c, 0xae, 0x49, 0x9c, 0x72, 0x81, 0x69, 0x78, 0x3a, 0x4a, 0xc3, 0xbe, 0xe1, 0x90, 0x63, 0x97, + 0xb9, 0x11, 0x53, 0x8b, 0xbd, 0x20, 0x81, 0xea, 0x33, 0x3b, 0x1d, 0x6c, 0x7b, 0x0a, 0xcb, 0xc5, + 0xcb, 0xf5, 0x1d, 0x52, 0x6e, 0x57, 0x9e, 0xea, 0x33, 0x83, 0x04, 0xf4, 0x43, 0x58, 0xe9, 0x99, + 0x7a, 0xdb, 0x53, 0xa7, 0xb5, 0xba, 0xc3, 0xc1, 0xc3, 0x72, 0x89, 0x29, 0x7d, 0x2e, 0xf2, 0x23, + 0x4d, 0xbd, 0xed, 0xaa, 0xa8, 0x51, 0x81, 0x46, 0x4c, 0x5d, 0xee, 0x8d, 0x13, 0xd1, 0xbb, 0xb0, + 0xaa, 0x5b, 0x56, 0xef, 0x62, 0x5c, 0xfb, 0x12, 0xd3, 0x7e, 0x33, 0x4a, 0x7b, 0x95, 0xca, 0x8c, + 0xab, 0x47, 0xfa, 0x04, 0x15, 0x35, 0x41, 0xb6, 0x6c, 0x6c, 0xe9, 0x36, 0xd6, 0x2c, 0xdb, 0xb4, + 0x4c, 0x47, 0xef, 0x95, 0x65, 0xa6, 0xfb, 0xd9, 0x28, 0xdd, 0x47, 0x9c, 0xff, 0x48, 0xb0, 0x37, + 0x62, 0xea, 0x92, 0x15, 0x26, 0x71, 0xad, 0x66, 0x0b, 0x3b, 0x8e, 0xaf, 0x75, 0x79, 0x96, 0x56, + 0xc6, 0x1f, 0xd6, 0x1a, 0x22, 0xa1, 0x3a, 0xe4, 0xf1, 0x88, 0x8a, 0x6b, 0xe7, 0x26, 0xc1, 0x65, + 0xc4, 0x14, 0x2a, 0x91, 0x27, 0x94, 0xb1, 0x3e, 0x30, 0x09, 0x6e, 0xc4, 0x54, 0xc0, 0xde, 0x08, + 0xe9, 0x70, 0xe5, 0x1c, 0xdb, 0x46, 0xe7, 0x82, 0xa9, 0xd1, 0xd8, 0x1b, 0xc7, 0x30, 0x07, 0xe5, + 0x15, 0xa6, 0xf0, 0xf9, 0x28, 0x85, 0x0f, 0x98, 0x10, 0x55, 0x51, 0x77, 0x45, 0x1a, 0x31, 0x75, + 0xe5, 0x7c, 0x92, 0x4c, 0x5d, 0xac, 0x63, 0x0c, 0xf4, 0x9e, 0xf1, 0x11, 0xd6, 0x4e, 0x7b, 0x66, + 0xeb, 0x61, 0x79, 0xf5, 0x72, 0x17, 0xbb, 0x27, 0xb8, 0x77, 0x28, 0x33, 0x75, 0xb1, 0x4e, 0x90, + 0xb0, 0x93, 0x81, 0xd4, 0xb9, 0xde, 0x1b, 0xe2, 0xbd, 0x64, 0x36, 0x29, 0xa7, 0xf6, 0x92, 0xd9, + 0x8c, 0x9c, 0xdd, 0x4b, 0x66, 0x73, 0x32, 0xec, 0x25, 0xb3, 0x20, 0xe7, 0x95, 0x67, 0x21, 0x1f, + 0x08, 0x4c, 0xa8, 0x0c, 0x99, 0x3e, 0x76, 0x1c, 0xfd, 0x0c, 0xb3, 0x38, 0x96, 0x53, 0xdd, 0xa1, + 0x52, 0x82, 0x42, 0x30, 0x18, 0x29, 0x9f, 0x4a, 0x9e, 0x24, 0x8d, 0x33, 0x54, 0xf2, 0x1c, 0xdb, + 0xcc, 0x1c, 0x42, 0x52, 0x0c, 0xd1, 0x53, 0x50, 0x64, 0x4b, 0xd1, 0xdc, 0xf7, 0x34, 0xd8, 0x25, + 0xd5, 0x02, 0x23, 0x3e, 0x10, 0x4c, 0xeb, 0x90, 0xb7, 0xb6, 0x2d, 0x8f, 0x25, 0xc1, 0x58, 0xc0, + 0xda, 0xb6, 0x5c, 0x86, 0x27, 0xa1, 0x40, 0xd7, 0xed, 0x71, 0x24, 0xd9, 0x24, 0x79, 0x4a, 0x13, + 0x2c, 0xca, 0x9f, 0xe3, 0x20, 0x8f, 0x07, 0x30, 0xf4, 0x2a, 0x24, 0x69, 0x2c, 0x17, 0x61, 0xb9, + 0xb2, 0xc9, 0x03, 0xfd, 0xa6, 0x1b, 0xe8, 0x37, 0x9b, 0x6e, 0xa0, 0xdf, 0xc9, 0x7e, 0xf1, 0xd5, + 0x7a, 0xec, 0xd3, 0xbf, 0xae, 0x4b, 0x2a, 0x93, 0x40, 0xd7, 0x68, 0xd8, 0xd2, 0x8d, 0x81, 0x66, + 0xb4, 0xd9, 0x27, 0xe7, 0x68, 0x4c, 0xd2, 0x8d, 0xc1, 0x6e, 0x1b, 0xed, 0x83, 0xdc, 0x32, 0x07, + 0x0e, 0x1e, 0x38, 0x43, 0x47, 0xe3, 0xa9, 0x46, 0x04, 0xe3, 0x50, 0x48, 0xe5, 0x09, 0xaf, 0xe6, + 0x72, 0x1e, 0x31, 0x46, 0x75, 0xa9, 0x15, 0x26, 0xa0, 0x7b, 0x00, 0x5e, 0x3e, 0x72, 0xca, 0xc9, + 0x8d, 0xc4, 0x8d, 0xfc, 0xf6, 0xc6, 0xc4, 0x86, 0x3f, 0x70, 0x59, 0x4e, 0xac, 0xb6, 0x4e, 0xf0, + 0x4e, 0x92, 0x7e, 0xae, 0x1a, 0x90, 0x44, 0xcf, 0xc0, 0x92, 0x6e, 0x59, 0x9a, 0x43, 0x74, 0x82, + 0xb5, 0xd3, 0x0b, 0x82, 0x1d, 0x16, 0xe7, 0x0b, 0x6a, 0x51, 0xb7, 0xac, 0x63, 0x4a, 0xdd, 0xa1, + 0x44, 0xf4, 0x34, 0x94, 0x68, 0x4c, 0x37, 0xf4, 0x9e, 0xd6, 0xc5, 0xc6, 0x59, 0x97, 0xb0, 0x78, + 0x9e, 0x50, 0x8b, 0x82, 0xda, 0x60, 0x44, 0xa5, 0xed, 0xed, 0x38, 0x8b, 0xe7, 0x08, 0x41, 0xb2, + 0xad, 0x13, 0x9d, 0x59, 0xb2, 0xa0, 0xb2, 0x67, 0x4a, 0xb3, 0x74, 0xd2, 0x15, 0xf6, 0x61, 0xcf, + 0xe8, 0x2a, 0xa4, 0x85, 0xda, 0x04, 0x53, 0x2b, 0x46, 0x68, 0x15, 0x52, 0x96, 0x6d, 0x9e, 0x63, + 0xb6, 0x75, 0x59, 0x95, 0x0f, 0x14, 0x15, 0x4a, 0xe1, 0xd8, 0x8f, 0x4a, 0x10, 0x27, 0x23, 0x31, + 0x4b, 0x9c, 0x8c, 0xd0, 0x4b, 0x90, 0xa4, 0x86, 0x64, 0x73, 0x94, 0xa6, 0x64, 0x3b, 0x21, 0xd7, + 0xbc, 0xb0, 0xb0, 0xca, 0x38, 0x95, 0x25, 0x28, 0x86, 0x72, 0x82, 0x72, 0x15, 0x56, 0xa7, 0x85, + 0x78, 0xa5, 0xeb, 0xd1, 0x43, 0xa1, 0x1a, 0xdd, 0x86, 0xac, 0x17, 0xe3, 0xb9, 0xe3, 0x5c, 0x9b, + 0x98, 0xd6, 0x65, 0x56, 0x3d, 0x56, 0xea, 0x31, 0x74, 0x03, 0xba, 0xba, 0xc8, 0xe8, 0x05, 0x35, + 0xa3, 0x5b, 0x56, 0x43, 0x77, 0xba, 0xca, 0x7b, 0x50, 0x8e, 0x8a, 0xdf, 0x01, 0x83, 0x49, 0xcc, + 0xed, 0x5d, 0x83, 0x5d, 0x85, 0x74, 0xc7, 0xb4, 0xfb, 0x3a, 0x61, 0xca, 0x8a, 0xaa, 0x18, 0x51, + 0x43, 0xf2, 0x58, 0x9e, 0x60, 0x64, 0x3e, 0x50, 0x34, 0xb8, 0x16, 0x19, 0xc3, 0xa9, 0x88, 0x31, + 0x68, 0x63, 0x6e, 0xd6, 0xa2, 0xca, 0x07, 0xbe, 0x22, 0xfe, 0xb1, 0x7c, 0x40, 0xa7, 0x75, 0xd8, + 0x5a, 0x99, 0xfe, 0x9c, 0x2a, 0x46, 0xca, 0x67, 0x09, 0xb8, 0x3a, 0x3d, 0x92, 0xa3, 0x0d, 0x28, + 0xf4, 0xf5, 0x91, 0x46, 0x46, 0xc2, 0xed, 0x24, 0xb6, 0xf1, 0xd0, 0xd7, 0x47, 0xcd, 0x11, 0xf7, + 0x39, 0x19, 0x12, 0x64, 0xe4, 0x94, 0xe3, 0x1b, 0x89, 0x1b, 0x05, 0x95, 0x3e, 0xa2, 0x13, 0x58, + 0xee, 0x99, 0x2d, 0xbd, 0xa7, 0xf5, 0x74, 0x87, 0x68, 0x22, 0xc5, 0xf3, 0x43, 0xf4, 0xd4, 0x84, + 0xb1, 0x79, 0x4c, 0xc6, 0x6d, 0xbe, 0x9f, 0x34, 0xe0, 0x08, 0xff, 0x5f, 0x62, 0x3a, 0xf6, 0x75, + 0x77, 0xab, 0xd1, 0x5d, 0xc8, 0xf7, 0x0d, 0xe7, 0x14, 0x77, 0xf5, 0x73, 0xc3, 0xb4, 0xc5, 0x69, + 0x9a, 0x74, 0x9a, 0x37, 0x7d, 0x1e, 0xa1, 0x29, 0x28, 0x16, 0xd8, 0x92, 0x54, 0xc8, 0x87, 0xdd, + 0x68, 0x92, 0x5e, 0x38, 0x9a, 0xbc, 0x04, 0xab, 0x03, 0x3c, 0x22, 0x9a, 0x7f, 0x5e, 0xb9, 0x9f, + 0x64, 0x98, 0xe9, 0x11, 0x7d, 0xe7, 0x9d, 0x70, 0x87, 0xba, 0x0c, 0x7a, 0x8e, 0xe5, 0x42, 0xcb, + 0x74, 0xb0, 0xad, 0xe9, 0xed, 0xb6, 0x8d, 0x1d, 0x87, 0x95, 0x4f, 0x05, 0x96, 0xe0, 0x18, 0xbd, + 0xca, 0xc9, 0xca, 0x2f, 0x82, 0x5b, 0x13, 0xce, 0x7d, 0xc2, 0xf0, 0x92, 0x6f, 0xf8, 0x63, 0x58, + 0x15, 0xf2, 0xed, 0x90, 0xed, 0x79, 0x0d, 0xfa, 0xf8, 0xe4, 0xf9, 0x1a, 0xb7, 0x39, 0x72, 0xc5, + 0xa3, 0xcd, 0x9e, 0x78, 0x34, 0xb3, 0x23, 0x48, 0x32, 0xa3, 0x24, 0x79, 0x88, 0xa1, 0xcf, 0xff, + 0x6e, 0x5b, 0xf1, 0x71, 0x02, 0x96, 0x27, 0x0a, 0x09, 0x6f, 0x61, 0xd2, 0xd4, 0x85, 0xc5, 0xa7, + 0x2e, 0x2c, 0xb1, 0xf0, 0xc2, 0xc4, 0x5e, 0x27, 0x67, 0xef, 0x75, 0xea, 0x7b, 0xdc, 0xeb, 0xf4, + 0xa3, 0xed, 0xf5, 0xbf, 0x74, 0x17, 0x7e, 0x2d, 0x41, 0x25, 0xba, 0xfa, 0x9a, 0xba, 0x1d, 0xcf, + 0xc3, 0xb2, 0xf7, 0x29, 0x9e, 0x7a, 0x1e, 0x18, 0x65, 0xef, 0x85, 0xd0, 0x1f, 0x99, 0xe3, 0x9e, + 0x86, 0xd2, 0x58, 0x6d, 0xc8, 0x5d, 0xb9, 0x78, 0x1e, 0x9c, 0x5f, 0xf9, 0x59, 0xc2, 0x4b, 0x3c, + 0xa1, 0x02, 0x6e, 0xca, 0x69, 0x7d, 0x0b, 0x56, 0xda, 0xb8, 0x65, 0xb4, 0x1f, 0xf5, 0xb0, 0x2e, + 0x0b, 0xe9, 0xff, 0x9e, 0xd5, 0x49, 0x2f, 0xf9, 0x15, 0x40, 0x56, 0xc5, 0x8e, 0x45, 0xeb, 0x31, + 0xb4, 0x03, 0x39, 0x3c, 0x6a, 0x61, 0x8b, 0xb8, 0x25, 0xec, 0xf4, 0x16, 0x81, 0x73, 0xd7, 0x5d, + 0x4e, 0xda, 0x20, 0x7b, 0x62, 0xe8, 0x96, 0xc0, 0x00, 0xa2, 0xdb, 0x79, 0x21, 0x1e, 0x04, 0x01, + 0x5e, 0x76, 0x41, 0x80, 0x44, 0x64, 0x7f, 0xcb, 0xa5, 0xc6, 0x50, 0x80, 0x5b, 0x02, 0x05, 0x48, + 0xce, 0x98, 0x2c, 0x04, 0x03, 0xd4, 0x42, 0x30, 0x40, 0x7a, 0xc6, 0x32, 0x23, 0x70, 0x80, 0x97, + 0x5d, 0x1c, 0x20, 0x33, 0xe3, 0x8b, 0xc7, 0x80, 0x80, 0x37, 0x02, 0x40, 0x40, 0x8e, 0x89, 0x6e, + 0x44, 0x8a, 0x4e, 0x41, 0x02, 0x5e, 0xf3, 0x90, 0x80, 0x42, 0x24, 0x8a, 0x20, 0x84, 0xc7, 0xa1, + 0x80, 0xc3, 0x09, 0x28, 0x80, 0xb7, 0xee, 0xcf, 0x44, 0xaa, 0x98, 0x81, 0x05, 0x1c, 0x4e, 0x60, + 0x01, 0xa5, 0x19, 0x0a, 0x67, 0x80, 0x01, 0x3f, 0x9a, 0x0e, 0x06, 0x44, 0xb7, 0xeb, 0xe2, 0x33, + 0xe7, 0x43, 0x03, 0xb4, 0x08, 0x34, 0x40, 0x8e, 0xec, 0x5c, 0xb9, 0xfa, 0xb9, 0xe1, 0x80, 0x93, + 0x29, 0x70, 0x00, 0x6f, 0xdc, 0x6f, 0x44, 0x2a, 0x9f, 0x03, 0x0f, 0x38, 0x99, 0x82, 0x07, 0xa0, + 0x99, 0x6a, 0x67, 0x02, 0x02, 0xf7, 0xc2, 0x80, 0xc0, 0x4a, 0x44, 0xd5, 0xe9, 0x9f, 0xf6, 0x08, + 0x44, 0xe0, 0x34, 0x0a, 0x11, 0xe0, 0x5d, 0xfb, 0x0b, 0x91, 0x1a, 0x17, 0x80, 0x04, 0x0e, 0x27, + 0x20, 0x81, 0x2b, 0x33, 0x3c, 0x6d, 0x7e, 0x4c, 0x20, 0x25, 0xa7, 0xf7, 0x92, 0xd9, 0xac, 0x9c, + 0xe3, 0x68, 0xc0, 0x5e, 0x32, 0x9b, 0x97, 0x0b, 0xca, 0x73, 0xb4, 0x82, 0x19, 0x8b, 0x73, 0xb4, + 0x57, 0xc0, 0xb6, 0x6d, 0xda, 0xa2, 0xbb, 0xe7, 0x03, 0xe5, 0x06, 0xed, 0x11, 0xfd, 0x98, 0x76, + 0x09, 0x7e, 0xc0, 0x7a, 0xb2, 0x40, 0x1c, 0x53, 0x7e, 0x2f, 0xf9, 0xb2, 0x0c, 0x41, 0x08, 0xf6, + 0x97, 0x39, 0xd1, 0x5f, 0x06, 0x50, 0x85, 0x78, 0x18, 0x55, 0x58, 0x87, 0x3c, 0xed, 0xb5, 0xc6, + 0x00, 0x03, 0xdd, 0xf2, 0x00, 0x83, 0x9b, 0xb0, 0xcc, 0x12, 0x26, 0xc7, 0x1e, 0x44, 0x5a, 0x4a, + 0xb2, 0xb4, 0xb4, 0x44, 0x5f, 0x70, 0xeb, 0xf0, 0xfc, 0xf4, 0x22, 0xac, 0x04, 0x78, 0xbd, 0x1e, + 0x8e, 0x77, 0xcf, 0xb2, 0xc7, 0x5d, 0x15, 0xcd, 0xdc, 0x9f, 0x24, 0xdf, 0x42, 0x3e, 0xd2, 0x30, + 0x0d, 0x14, 0x90, 0xbe, 0x27, 0x50, 0x20, 0xfe, 0xc8, 0xa0, 0x40, 0xb0, 0x27, 0x4d, 0x84, 0x7b, + 0xd2, 0x7f, 0x48, 0xfe, 0x9e, 0x78, 0x2d, 0x7e, 0xcb, 0x6c, 0x63, 0xd1, 0x25, 0xb2, 0x67, 0x5a, + 0x92, 0xf4, 0xcc, 0x33, 0xd1, 0x0b, 0xd2, 0x47, 0xca, 0xe5, 0x25, 0x9e, 0x9c, 0xc8, 0x2b, 0x5e, + 0x83, 0xc9, 0x13, 0xbf, 0x68, 0x30, 0x65, 0x48, 0x3c, 0xc4, 0x1c, 0x2e, 0x2e, 0xa8, 0xf4, 0x91, + 0xf2, 0x31, 0xe7, 0x13, 0x09, 0x9c, 0x0f, 0xd0, 0xab, 0x90, 0x63, 0x60, 0xbf, 0x66, 0x5a, 0x8e, + 0x80, 0x88, 0x43, 0xa5, 0x0d, 0x47, 0xfc, 0x37, 0x8f, 0x28, 0xcf, 0xa1, 0xe5, 0xa8, 0x59, 0x4b, + 0x3c, 0x05, 0x2a, 0x8e, 0x5c, 0xa8, 0xe2, 0xb8, 0x0e, 0x39, 0xfa, 0xf5, 0x8e, 0xa5, 0xb7, 0x70, + 0x19, 0xd8, 0x87, 0xfa, 0x04, 0xe5, 0x77, 0x71, 0x58, 0x1a, 0x4b, 0x34, 0x53, 0xd7, 0xee, 0xba, + 0x64, 0x3c, 0x00, 0x79, 0xcc, 0x67, 0x8f, 0x35, 0x80, 0x33, 0xdd, 0xd1, 0x3e, 0xd4, 0x07, 0x04, + 0xb7, 0x85, 0x51, 0x02, 0x14, 0x54, 0x81, 0x2c, 0x1d, 0x0d, 0x1d, 0xdc, 0x16, 0xe8, 0x8b, 0x37, + 0x46, 0x0d, 0x48, 0xe3, 0x73, 0x3c, 0x20, 0x4e, 0x39, 0xc3, 0xb6, 0xfd, 0xea, 0x64, 0x3b, 0x4c, + 0x5f, 0xef, 0x94, 0xe9, 0x66, 0x7f, 0xfb, 0xd5, 0xba, 0xcc, 0xb9, 0x5f, 0x30, 0xfb, 0x06, 0xc1, + 0x7d, 0x8b, 0x5c, 0xa8, 0x42, 0x3e, 0x6c, 0x85, 0xec, 0x98, 0x15, 0x18, 0x0e, 0x58, 0x70, 0xdb, + 0x7b, 0x6a, 0x53, 0xc3, 0xb4, 0x0d, 0x72, 0xa1, 0x16, 0xfb, 0xb8, 0x6f, 0x99, 0x66, 0x4f, 0xe3, + 0x67, 0xbc, 0x0a, 0xa5, 0x70, 0x5e, 0x45, 0x4f, 0x41, 0xd1, 0xc6, 0x44, 0x37, 0x06, 0x5a, 0xa8, + 0x08, 0x2e, 0x70, 0x22, 0x3f, 0x53, 0x7b, 0xc9, 0xac, 0x24, 0xc7, 0xf7, 0x92, 0xd9, 0xb8, 0x9c, + 0x50, 0x8e, 0xe0, 0xca, 0xd4, 0xbc, 0x8a, 0x5e, 0x81, 0x9c, 0x9f, 0x92, 0x25, 0xb6, 0xda, 0x4b, + 0x90, 0x16, 0x9f, 0x57, 0xf9, 0x83, 0xe4, 0xab, 0x0c, 0x63, 0x37, 0x75, 0x48, 0xdb, 0xd8, 0x19, + 0xf6, 0x38, 0x9a, 0x52, 0xda, 0x7e, 0x71, 0xbe, 0x8c, 0x4c, 0xa9, 0xc3, 0x1e, 0x51, 0x85, 0xb0, + 0xf2, 0x2e, 0xa4, 0x39, 0x05, 0xe5, 0x21, 0x73, 0x72, 0x70, 0xff, 0xe0, 0xf0, 0xed, 0x03, 0x39, + 0x86, 0x00, 0xd2, 0xd5, 0x5a, 0xad, 0x7e, 0xd4, 0x94, 0x25, 0x94, 0x83, 0x54, 0x75, 0xe7, 0x50, + 0x6d, 0xca, 0x71, 0x4a, 0x56, 0xeb, 0x7b, 0xf5, 0x5a, 0x53, 0x4e, 0xa0, 0x65, 0x28, 0xf2, 0x67, + 0xed, 0xde, 0xa1, 0xfa, 0x66, 0xb5, 0x29, 0x27, 0x03, 0xa4, 0xe3, 0xfa, 0xc1, 0xdd, 0xba, 0x2a, + 0xa7, 0x94, 0xff, 0x81, 0x6b, 0x91, 0x39, 0xdc, 0x07, 0x66, 0xa4, 0x00, 0x30, 0xa3, 0x7c, 0x16, + 0xa7, 0x4d, 0x4d, 0x54, 0x62, 0x46, 0x7b, 0x63, 0x0b, 0xdf, 0x5e, 0x20, 0xab, 0x8f, 0xad, 0x9e, + 0xf6, 0x31, 0x36, 0xee, 0x60, 0xd2, 0xea, 0xf2, 0x42, 0x81, 0x47, 0xa0, 0xa2, 0x5a, 0x14, 0x54, + 0x26, 0xe4, 0x70, 0xb6, 0xf7, 0x71, 0x8b, 0x68, 0xdc, 0x89, 0x1c, 0xd6, 0x4c, 0xe4, 0x28, 0x1b, + 0xa5, 0x1e, 0x73, 0xa2, 0xf2, 0xde, 0x42, 0xb6, 0xcc, 0x41, 0x4a, 0xad, 0x37, 0xd5, 0x77, 0xe4, + 0x04, 0x42, 0x50, 0x62, 0x8f, 0xda, 0xf1, 0x41, 0xf5, 0xe8, 0xb8, 0x71, 0x48, 0x6d, 0xb9, 0x02, + 0x4b, 0xae, 0x2d, 0x5d, 0x62, 0x4a, 0x79, 0x1e, 0x1e, 0x8b, 0xa8, 0x2a, 0x26, 0x5b, 0x2a, 0xe5, + 0x37, 0x52, 0x90, 0x3b, 0x5c, 0x19, 0x1c, 0x42, 0xda, 0x21, 0x3a, 0x19, 0x3a, 0xc2, 0x88, 0xaf, + 0xcc, 0x5b, 0x66, 0x6c, 0xba, 0x0f, 0xc7, 0x4c, 0x5c, 0x15, 0x6a, 0x94, 0xdb, 0x50, 0x0a, 0xbf, + 0x89, 0xb6, 0x81, 0xef, 0x44, 0x71, 0xe5, 0x0e, 0xa0, 0xc9, 0xea, 0x63, 0x4a, 0x7b, 0x29, 0x4d, + 0x6b, 0x2f, 0x7f, 0x2b, 0xc1, 0xe3, 0x97, 0x54, 0x1a, 0xe8, 0xad, 0xb1, 0x45, 0xbe, 0xb6, 0x48, + 0x9d, 0xb2, 0xc9, 0x69, 0x63, 0xcb, 0xbc, 0x05, 0x85, 0x20, 0x7d, 0xbe, 0x45, 0x7e, 0x1b, 0xf7, + 0x0f, 0x71, 0xb8, 0x0f, 0xf6, 0x43, 0xa0, 0xf4, 0x1d, 0x43, 0xe0, 0xeb, 0x00, 0x64, 0xa4, 0x71, + 0xb7, 0x76, 0xf3, 0xe8, 0x13, 0x53, 0xf0, 0x45, 0xdc, 0x6a, 0x8e, 0xc4, 0x21, 0xc8, 0x11, 0xf1, + 0xe4, 0xa0, 0xe3, 0x20, 0x28, 0x30, 0x64, 0x39, 0xd6, 0x11, 0x0d, 0xf3, 0xbc, 0xc9, 0xd8, 0x07, + 0x0f, 0x38, 0xd9, 0x41, 0xef, 0xc0, 0x63, 0x63, 0x85, 0x82, 0xa7, 0x3a, 0x39, 0x6f, 0xbd, 0x70, + 0x25, 0x5c, 0x2f, 0xb8, 0xaa, 0x83, 0xd9, 0x3e, 0x15, 0xce, 0xf6, 0xef, 0x00, 0xf8, 0xe0, 0x00, + 0x8d, 0x30, 0xb6, 0x39, 0x1c, 0xb4, 0x99, 0x07, 0xa4, 0x54, 0x3e, 0x40, 0xb7, 0x21, 0x45, 0x3d, + 0xc9, 0xb5, 0xd3, 0x64, 0x28, 0xa6, 0x9e, 0x10, 0x00, 0x17, 0x38, 0xb7, 0x62, 0x00, 0x9a, 0x04, + 0x68, 0x23, 0xa6, 0x78, 0x23, 0x3c, 0xc5, 0x93, 0x91, 0x50, 0xef, 0xf4, 0xa9, 0x3e, 0x82, 0x14, + 0xdb, 0x79, 0x9a, 0x74, 0xd9, 0x5f, 0x01, 0x51, 0x2d, 0xd2, 0x67, 0xf4, 0x63, 0x00, 0x9d, 0x10, + 0xdb, 0x38, 0x1d, 0xfa, 0x13, 0xac, 0x4f, 0xf7, 0x9c, 0xaa, 0xcb, 0xb7, 0x73, 0x5d, 0xb8, 0xd0, + 0xaa, 0x2f, 0x1a, 0x70, 0xa3, 0x80, 0x42, 0xe5, 0x00, 0x4a, 0x61, 0x59, 0xb7, 0xbe, 0xe1, 0xdf, + 0x10, 0xae, 0x6f, 0x78, 0xb9, 0x2a, 0xea, 0x1b, 0xaf, 0x3a, 0x4a, 0xf0, 0x5f, 0x1f, 0x6c, 0xa0, + 0xfc, 0x24, 0x0e, 0x85, 0xa0, 0xe3, 0xfd, 0xe7, 0x95, 0x20, 0xca, 0xcf, 0x25, 0xc8, 0x7a, 0xcb, + 0x0f, 0xff, 0x07, 0x09, 0xfd, 0x38, 0xe2, 0xd6, 0x8b, 0x07, 0x7f, 0x5e, 0xf0, 0xdf, 0x44, 0x09, + 0xef, 0x37, 0xd1, 0x1d, 0x2f, 0xfd, 0x45, 0x01, 0x22, 0x41, 0x5b, 0x0b, 0xaf, 0x72, 0xb3, 0xfd, + 0x1d, 0xc8, 0x79, 0xa7, 0x97, 0x36, 0x1d, 0x2e, 0x70, 0x24, 0x89, 0x33, 0x24, 0x60, 0xbf, 0x55, + 0x48, 0x59, 0xe6, 0x87, 0xe2, 0xcf, 0x48, 0x42, 0xe5, 0x03, 0xa5, 0x0d, 0x4b, 0x63, 0x47, 0x1f, + 0xdd, 0x81, 0x8c, 0x35, 0x3c, 0xd5, 0x5c, 0xe7, 0x18, 0x83, 0xd7, 0xdc, 0x72, 0x76, 0x78, 0xda, + 0x33, 0x5a, 0xf7, 0xf1, 0x85, 0xfb, 0x31, 0xd6, 0xf0, 0xf4, 0x3e, 0xf7, 0x21, 0x3e, 0x4b, 0x3c, + 0x38, 0xcb, 0x2f, 0x25, 0xc8, 0xba, 0x67, 0x02, 0xfd, 0x1f, 0xe4, 0xbc, 0xb0, 0xe2, 0xfd, 0xda, + 0x8c, 0x8c, 0x47, 0x42, 0xbf, 0x2f, 0x82, 0xaa, 0xee, 0x3f, 0x59, 0xa3, 0xad, 0x75, 0x7a, 0x3a, + 0xf7, 0xa5, 0x52, 0xd8, 0x66, 0x3c, 0xf0, 0xb0, 0x78, 0xbc, 0x7b, 0xf7, 0x5e, 0x4f, 0x3f, 0x53, + 0xf3, 0x4c, 0x66, 0xb7, 0x4d, 0x07, 0xa2, 0xb2, 0xfb, 0xbb, 0x04, 0xf2, 0xf8, 0x89, 0xfd, 0xce, + 0x5f, 0x37, 0x99, 0xe6, 0x12, 0x53, 0xd2, 0x1c, 0xda, 0x82, 0x15, 0x8f, 0x43, 0x73, 0x8c, 0xb3, + 0x81, 0x4e, 0x86, 0x36, 0x16, 0x80, 0x24, 0xf2, 0x5e, 0x1d, 0xbb, 0x6f, 0x26, 0x57, 0x9d, 0x7a, + 0xc4, 0x55, 0x7f, 0x1c, 0x87, 0x7c, 0x00, 0x1e, 0x45, 0xff, 0x1b, 0x08, 0x46, 0xa5, 0x29, 0x99, + 0x21, 0xc0, 0xeb, 0xff, 0xa6, 0x0c, 0x9b, 0x29, 0xbe, 0xb8, 0x99, 0xa2, 0x40, 0x68, 0x17, 0x6d, + 0x4d, 0x2e, 0x8c, 0xb6, 0xbe, 0x00, 0x88, 0x98, 0x44, 0xef, 0x69, 0xe7, 0x26, 0x31, 0x06, 0x67, + 0x1a, 0x77, 0x43, 0x1e, 0x3a, 0x64, 0xf6, 0xe6, 0x01, 0x7b, 0x71, 0xc4, 0x3c, 0xf2, 0xa7, 0x12, + 0x64, 0xbd, 0xb2, 0x7b, 0xd1, 0x9f, 0x98, 0x57, 0x21, 0x2d, 0x2a, 0x4b, 0xfe, 0x17, 0x53, 0x8c, + 0xa6, 0xc2, 0xca, 0x15, 0xc8, 0xf6, 0x31, 0xd1, 0x59, 0x1c, 0xe4, 0x59, 0xcd, 0x1b, 0xdf, 0x7c, + 0x0d, 0xf2, 0x81, 0x1f, 0xc0, 0x34, 0x34, 0x1e, 0xd4, 0xdf, 0x96, 0x63, 0x95, 0xcc, 0x27, 0x9f, + 0x6f, 0x24, 0x0e, 0xf0, 0x87, 0xf4, 0x34, 0xab, 0xf5, 0x5a, 0xa3, 0x5e, 0xbb, 0x2f, 0x4b, 0x95, + 0xfc, 0x27, 0x9f, 0x6f, 0x64, 0x54, 0xcc, 0x10, 0xc5, 0x9b, 0xf7, 0x61, 0x69, 0x6c, 0x63, 0xc2, + 0x65, 0x0b, 0x82, 0xd2, 0xdd, 0x93, 0xa3, 0xfd, 0xdd, 0x5a, 0xb5, 0x59, 0xd7, 0x1e, 0x1c, 0x36, + 0xeb, 0xb2, 0x84, 0x1e, 0x83, 0x95, 0xfd, 0xdd, 0xff, 0x6f, 0x34, 0xb5, 0xda, 0xfe, 0x6e, 0xfd, + 0xa0, 0xa9, 0x55, 0x9b, 0xcd, 0x6a, 0xed, 0xbe, 0x1c, 0xdf, 0xfe, 0x3c, 0x0f, 0xc9, 0xea, 0x4e, + 0x6d, 0x17, 0xd5, 0x20, 0xc9, 0xa0, 0x90, 0x4b, 0x6f, 0x80, 0x55, 0x2e, 0xc7, 0x86, 0xd1, 0x3d, + 0x48, 0x31, 0x94, 0x04, 0x5d, 0x7e, 0x25, 0xac, 0x32, 0x03, 0x2c, 0xa6, 0x1f, 0xc3, 0x4e, 0xe4, + 0xa5, 0x77, 0xc4, 0x2a, 0x97, 0x63, 0xc7, 0x68, 0x1f, 0x32, 0x6e, 0x93, 0x3c, 0xeb, 0xe2, 0x56, + 0x65, 0x26, 0xa0, 0x4b, 0x97, 0xc6, 0xc1, 0x86, 0xcb, 0xaf, 0x8f, 0x55, 0x66, 0xa0, 0xca, 0x68, + 0x17, 0xd2, 0xa2, 0x1d, 0x9d, 0x71, 0x23, 0xac, 0x32, 0x0b, 0x27, 0x46, 0x2a, 0xe4, 0x7c, 0x18, + 0x67, 0xf6, 0xa5, 0xb8, 0xca, 0x1c, 0x80, 0x39, 0x7a, 0x17, 0x8a, 0xe1, 0x56, 0x77, 0xbe, 0x5b, + 0x67, 0x95, 0x39, 0x11, 0x69, 0xaa, 0x3f, 0xdc, 0xf7, 0xce, 0x77, 0x0b, 0xad, 0x32, 0x27, 0x40, + 0x8d, 0xde, 0x87, 0xe5, 0xc9, 0xbe, 0x74, 0xfe, 0x4b, 0x69, 0x95, 0x05, 0x20, 0x6b, 0xd4, 0x07, + 0x34, 0xa5, 0x9f, 0x5d, 0xe0, 0x8e, 0x5a, 0x65, 0x11, 0x04, 0x1b, 0xb5, 0x61, 0x69, 0xbc, 0x49, + 0x9c, 0xf7, 0xce, 0x5a, 0x65, 0x6e, 0x34, 0x9b, 0xcf, 0x12, 0x6e, 0x2e, 0xe7, 0xbd, 0xc3, 0x56, + 0x99, 0x1b, 0xdc, 0x46, 0x27, 0x00, 0x81, 0xfe, 0x70, 0x8e, 0x3b, 0x6d, 0x95, 0x79, 0x60, 0x6e, + 0x64, 0xc1, 0xca, 0xb4, 0xc6, 0x71, 0x91, 0x2b, 0x6e, 0x95, 0x85, 0xd0, 0x6f, 0xea, 0xcf, 0xe1, + 0x16, 0x70, 0xbe, 0x2b, 0x6f, 0x95, 0x39, 0x61, 0xf0, 0x9d, 0xea, 0x17, 0x5f, 0xaf, 0x49, 0x5f, + 0x7e, 0xbd, 0x26, 0xfd, 0xed, 0xeb, 0x35, 0xe9, 0xd3, 0x6f, 0xd6, 0x62, 0x5f, 0x7e, 0xb3, 0x16, + 0xfb, 0xcb, 0x37, 0x6b, 0xb1, 0x1f, 0x3c, 0x7b, 0x66, 0x90, 0xee, 0xf0, 0x74, 0xb3, 0x65, 0xf6, + 0xb7, 0x5a, 0x66, 0x1f, 0x93, 0xd3, 0x0e, 0xf1, 0x1f, 0xfc, 0x9b, 0xcb, 0xa7, 0x69, 0x96, 0x41, + 0x6f, 0xfd, 0x33, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd0, 0x90, 0x6e, 0xd9, 0x2c, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// ABCIClient is the client API for ABCI service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type ABCIClient interface { + Echo(ctx context.Context, in *RequestEcho, opts ...grpc.CallOption) (*ResponseEcho, error) + Flush(ctx context.Context, in *RequestFlush, opts ...grpc.CallOption) (*ResponseFlush, error) + Info(ctx context.Context, in *RequestInfo, opts ...grpc.CallOption) (*ResponseInfo, error) + CheckTx(ctx context.Context, in *RequestCheckTx, opts ...grpc.CallOption) (*ResponseCheckTx, error) + Query(ctx context.Context, in *RequestQuery, opts ...grpc.CallOption) (*ResponseQuery, error) + Commit(ctx context.Context, in *RequestCommit, opts ...grpc.CallOption) (*ResponseCommit, error) + InitChain(ctx context.Context, in *RequestInitChain, opts ...grpc.CallOption) (*ResponseInitChain, error) + ListSnapshots(ctx context.Context, in *RequestListSnapshots, opts ...grpc.CallOption) (*ResponseListSnapshots, error) + OfferSnapshot(ctx context.Context, in *RequestOfferSnapshot, opts ...grpc.CallOption) (*ResponseOfferSnapshot, error) + LoadSnapshotChunk(ctx context.Context, in *RequestLoadSnapshotChunk, opts ...grpc.CallOption) (*ResponseLoadSnapshotChunk, error) + ApplySnapshotChunk(ctx context.Context, in *RequestApplySnapshotChunk, opts ...grpc.CallOption) (*ResponseApplySnapshotChunk, error) + PrepareProposal(ctx context.Context, in *RequestPrepareProposal, opts ...grpc.CallOption) (*ResponsePrepareProposal, error) + ProcessProposal(ctx context.Context, in *RequestProcessProposal, opts ...grpc.CallOption) (*ResponseProcessProposal, error) + ExtendVote(ctx context.Context, in *RequestExtendVote, opts ...grpc.CallOption) (*ResponseExtendVote, error) + VerifyVoteExtension(ctx context.Context, in *RequestVerifyVoteExtension, opts ...grpc.CallOption) (*ResponseVerifyVoteExtension, error) + FinalizeBlock(ctx context.Context, in *RequestFinalizeBlock, opts ...grpc.CallOption) (*ResponseFinalizeBlock, error) +} + +type aBCIClient struct { + cc grpc1.ClientConn +} + +func NewABCIClient(cc grpc1.ClientConn) ABCIClient { + return &aBCIClient{cc} +} + +func (c *aBCIClient) Echo(ctx context.Context, in *RequestEcho, opts ...grpc.CallOption) (*ResponseEcho, error) { + out := new(ResponseEcho) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Echo", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) Flush(ctx context.Context, in *RequestFlush, opts ...grpc.CallOption) (*ResponseFlush, error) { + out := new(ResponseFlush) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Flush", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) Info(ctx context.Context, in *RequestInfo, opts ...grpc.CallOption) (*ResponseInfo, error) { + out := new(ResponseInfo) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Info", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) CheckTx(ctx context.Context, in *RequestCheckTx, opts ...grpc.CallOption) (*ResponseCheckTx, error) { + out := new(ResponseCheckTx) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/CheckTx", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) Query(ctx context.Context, in *RequestQuery, opts ...grpc.CallOption) (*ResponseQuery, error) { + out := new(ResponseQuery) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Query", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) Commit(ctx context.Context, in *RequestCommit, opts ...grpc.CallOption) (*ResponseCommit, error) { + out := new(ResponseCommit) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Commit", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) InitChain(ctx context.Context, in *RequestInitChain, opts ...grpc.CallOption) (*ResponseInitChain, error) { + out := new(ResponseInitChain) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/InitChain", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) ListSnapshots(ctx context.Context, in *RequestListSnapshots, opts ...grpc.CallOption) (*ResponseListSnapshots, error) { + out := new(ResponseListSnapshots) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ListSnapshots", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) OfferSnapshot(ctx context.Context, in *RequestOfferSnapshot, opts ...grpc.CallOption) (*ResponseOfferSnapshot, error) { + out := new(ResponseOfferSnapshot) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/OfferSnapshot", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) LoadSnapshotChunk(ctx context.Context, in *RequestLoadSnapshotChunk, opts ...grpc.CallOption) (*ResponseLoadSnapshotChunk, error) { + out := new(ResponseLoadSnapshotChunk) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/LoadSnapshotChunk", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) ApplySnapshotChunk(ctx context.Context, in *RequestApplySnapshotChunk, opts ...grpc.CallOption) (*ResponseApplySnapshotChunk, error) { + out := new(ResponseApplySnapshotChunk) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ApplySnapshotChunk", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) PrepareProposal(ctx context.Context, in *RequestPrepareProposal, opts ...grpc.CallOption) (*ResponsePrepareProposal, error) { + out := new(ResponsePrepareProposal) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/PrepareProposal", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) ProcessProposal(ctx context.Context, in *RequestProcessProposal, opts ...grpc.CallOption) (*ResponseProcessProposal, error) { + out := new(ResponseProcessProposal) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ProcessProposal", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) ExtendVote(ctx context.Context, in *RequestExtendVote, opts ...grpc.CallOption) (*ResponseExtendVote, error) { + out := new(ResponseExtendVote) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ExtendVote", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) VerifyVoteExtension(ctx context.Context, in *RequestVerifyVoteExtension, opts ...grpc.CallOption) (*ResponseVerifyVoteExtension, error) { + out := new(ResponseVerifyVoteExtension) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/VerifyVoteExtension", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *aBCIClient) FinalizeBlock(ctx context.Context, in *RequestFinalizeBlock, opts ...grpc.CallOption) (*ResponseFinalizeBlock, error) { + out := new(ResponseFinalizeBlock) + err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/FinalizeBlock", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ABCIServer is the server API for ABCI service. +type ABCIServer interface { + Echo(context.Context, *RequestEcho) (*ResponseEcho, error) + Flush(context.Context, *RequestFlush) (*ResponseFlush, error) + Info(context.Context, *RequestInfo) (*ResponseInfo, error) + CheckTx(context.Context, *RequestCheckTx) (*ResponseCheckTx, error) + Query(context.Context, *RequestQuery) (*ResponseQuery, error) + Commit(context.Context, *RequestCommit) (*ResponseCommit, error) + InitChain(context.Context, *RequestInitChain) (*ResponseInitChain, error) + ListSnapshots(context.Context, *RequestListSnapshots) (*ResponseListSnapshots, error) + OfferSnapshot(context.Context, *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) + LoadSnapshotChunk(context.Context, *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) + ApplySnapshotChunk(context.Context, *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) + PrepareProposal(context.Context, *RequestPrepareProposal) (*ResponsePrepareProposal, error) + ProcessProposal(context.Context, *RequestProcessProposal) (*ResponseProcessProposal, error) + ExtendVote(context.Context, *RequestExtendVote) (*ResponseExtendVote, error) + VerifyVoteExtension(context.Context, *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error) + FinalizeBlock(context.Context, *RequestFinalizeBlock) (*ResponseFinalizeBlock, error) +} + +// UnimplementedABCIServer can be embedded to have forward compatible implementations. +type UnimplementedABCIServer struct { +} + +func (*UnimplementedABCIServer) Echo(ctx context.Context, req *RequestEcho) (*ResponseEcho, error) { + return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") +} +func (*UnimplementedABCIServer) Flush(ctx context.Context, req *RequestFlush) (*ResponseFlush, error) { + return nil, status.Errorf(codes.Unimplemented, "method Flush not implemented") +} +func (*UnimplementedABCIServer) Info(ctx context.Context, req *RequestInfo) (*ResponseInfo, error) { + return nil, status.Errorf(codes.Unimplemented, "method Info not implemented") +} +func (*UnimplementedABCIServer) CheckTx(ctx context.Context, req *RequestCheckTx) (*ResponseCheckTx, error) { + return nil, status.Errorf(codes.Unimplemented, "method CheckTx not implemented") +} +func (*UnimplementedABCIServer) Query(ctx context.Context, req *RequestQuery) (*ResponseQuery, error) { + return nil, status.Errorf(codes.Unimplemented, "method Query not implemented") +} +func (*UnimplementedABCIServer) Commit(ctx context.Context, req *RequestCommit) (*ResponseCommit, error) { + return nil, status.Errorf(codes.Unimplemented, "method Commit not implemented") +} +func (*UnimplementedABCIServer) InitChain(ctx context.Context, req *RequestInitChain) (*ResponseInitChain, error) { + return nil, status.Errorf(codes.Unimplemented, "method InitChain not implemented") +} +func (*UnimplementedABCIServer) ListSnapshots(ctx context.Context, req *RequestListSnapshots) (*ResponseListSnapshots, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListSnapshots not implemented") +} +func (*UnimplementedABCIServer) OfferSnapshot(ctx context.Context, req *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) { + return nil, status.Errorf(codes.Unimplemented, "method OfferSnapshot not implemented") +} +func (*UnimplementedABCIServer) LoadSnapshotChunk(ctx context.Context, req *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) { + return nil, status.Errorf(codes.Unimplemented, "method LoadSnapshotChunk not implemented") +} +func (*UnimplementedABCIServer) ApplySnapshotChunk(ctx context.Context, req *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) { + return nil, status.Errorf(codes.Unimplemented, "method ApplySnapshotChunk not implemented") +} +func (*UnimplementedABCIServer) PrepareProposal(ctx context.Context, req *RequestPrepareProposal) (*ResponsePrepareProposal, error) { + return nil, status.Errorf(codes.Unimplemented, "method PrepareProposal not implemented") +} +func (*UnimplementedABCIServer) ProcessProposal(ctx context.Context, req *RequestProcessProposal) (*ResponseProcessProposal, error) { + return nil, status.Errorf(codes.Unimplemented, "method ProcessProposal not implemented") +} +func (*UnimplementedABCIServer) ExtendVote(ctx context.Context, req *RequestExtendVote) (*ResponseExtendVote, error) { + return nil, status.Errorf(codes.Unimplemented, "method ExtendVote not implemented") +} +func (*UnimplementedABCIServer) VerifyVoteExtension(ctx context.Context, req *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error) { + return nil, status.Errorf(codes.Unimplemented, "method VerifyVoteExtension not implemented") +} +func (*UnimplementedABCIServer) FinalizeBlock(ctx context.Context, req *RequestFinalizeBlock) (*ResponseFinalizeBlock, error) { + return nil, status.Errorf(codes.Unimplemented, "method FinalizeBlock not implemented") +} + +func RegisterABCIServer(s grpc1.Server, srv ABCIServer) { + s.RegisterService(&_ABCI_serviceDesc, srv) +} + +func _ABCI_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestEcho) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).Echo(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/Echo", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).Echo(ctx, req.(*RequestEcho)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_Flush_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestFlush) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).Flush(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/Flush", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).Flush(ctx, req.(*RequestFlush)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_Info_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestInfo) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).Info(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/Info", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).Info(ctx, req.(*RequestInfo)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_CheckTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestCheckTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).CheckTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/CheckTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).CheckTx(ctx, req.(*RequestCheckTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestQuery) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).Query(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/Query", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).Query(ctx, req.(*RequestQuery)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_Commit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestCommit) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).Commit(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/Commit", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).Commit(ctx, req.(*RequestCommit)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_InitChain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestInitChain) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).InitChain(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/InitChain", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).InitChain(ctx, req.(*RequestInitChain)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_ListSnapshots_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestListSnapshots) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).ListSnapshots(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/ListSnapshots", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).ListSnapshots(ctx, req.(*RequestListSnapshots)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_OfferSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestOfferSnapshot) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).OfferSnapshot(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/OfferSnapshot", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).OfferSnapshot(ctx, req.(*RequestOfferSnapshot)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_LoadSnapshotChunk_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestLoadSnapshotChunk) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).LoadSnapshotChunk(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/LoadSnapshotChunk", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).LoadSnapshotChunk(ctx, req.(*RequestLoadSnapshotChunk)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_ApplySnapshotChunk_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestApplySnapshotChunk) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).ApplySnapshotChunk(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/ApplySnapshotChunk", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).ApplySnapshotChunk(ctx, req.(*RequestApplySnapshotChunk)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_PrepareProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestPrepareProposal) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).PrepareProposal(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/PrepareProposal", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).PrepareProposal(ctx, req.(*RequestPrepareProposal)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_ProcessProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestProcessProposal) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).ProcessProposal(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/ProcessProposal", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).ProcessProposal(ctx, req.(*RequestProcessProposal)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_ExtendVote_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestExtendVote) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).ExtendVote(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/ExtendVote", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).ExtendVote(ctx, req.(*RequestExtendVote)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_VerifyVoteExtension_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestVerifyVoteExtension) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).VerifyVoteExtension(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/VerifyVoteExtension", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).VerifyVoteExtension(ctx, req.(*RequestVerifyVoteExtension)) + } + return interceptor(ctx, in, info, handler) +} + +func _ABCI_FinalizeBlock_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestFinalizeBlock) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ABCIServer).FinalizeBlock(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.abci.ABCI/FinalizeBlock", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ABCIServer).FinalizeBlock(ctx, req.(*RequestFinalizeBlock)) + } + return interceptor(ctx, in, info, handler) +} + +var ABCI_serviceDesc = _ABCI_serviceDesc +var _ABCI_serviceDesc = grpc.ServiceDesc{ + ServiceName: "tendermint.abci.ABCI", + HandlerType: (*ABCIServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Echo", + Handler: _ABCI_Echo_Handler, + }, + { + MethodName: "Flush", + Handler: _ABCI_Flush_Handler, + }, + { + MethodName: "Info", + Handler: _ABCI_Info_Handler, + }, + { + MethodName: "CheckTx", + Handler: _ABCI_CheckTx_Handler, + }, + { + MethodName: "Query", + Handler: _ABCI_Query_Handler, + }, + { + MethodName: "Commit", + Handler: _ABCI_Commit_Handler, + }, + { + MethodName: "InitChain", + Handler: _ABCI_InitChain_Handler, + }, + { + MethodName: "ListSnapshots", + Handler: _ABCI_ListSnapshots_Handler, + }, + { + MethodName: "OfferSnapshot", + Handler: _ABCI_OfferSnapshot_Handler, + }, + { + MethodName: "LoadSnapshotChunk", + Handler: _ABCI_LoadSnapshotChunk_Handler, + }, + { + MethodName: "ApplySnapshotChunk", + Handler: _ABCI_ApplySnapshotChunk_Handler, + }, + { + MethodName: "PrepareProposal", + Handler: _ABCI_PrepareProposal_Handler, + }, + { + MethodName: "ProcessProposal", + Handler: _ABCI_ProcessProposal_Handler, + }, + { + MethodName: "ExtendVote", + Handler: _ABCI_ExtendVote_Handler, + }, + { + MethodName: "VerifyVoteExtension", + Handler: _ABCI_VerifyVoteExtension_Handler, + }, + { + MethodName: "FinalizeBlock", + Handler: _ABCI_FinalizeBlock_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "tendermint/abci/types.proto", +} + +func (m *Request) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Request) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Value != nil { + { + size := m.Value.Size() + i -= size + if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Request_Echo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_Echo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Echo != nil { + { + size, err := m.Echo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Request_Flush) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_Flush) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Flush != nil { + { + size, err := m.Flush.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Request_Info) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_Info) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Info != nil { + { + size, err := m.Info.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Request_InitChain) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_InitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.InitChain != nil { + { + size, err := m.InitChain.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + return len(dAtA) - i, nil +} +func (m *Request_Query) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_Query) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Query != nil { + { + size, err := m.Query.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + return len(dAtA) - i, nil +} +func (m *Request_CheckTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_CheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.CheckTx != nil { + { + size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + return len(dAtA) - i, nil +} +func (m *Request_Commit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Commit != nil { + { + size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x5a + } + return len(dAtA) - i, nil +} +func (m *Request_ListSnapshots) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_ListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ListSnapshots != nil { + { + size, err := m.ListSnapshots.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x62 + } + return len(dAtA) - i, nil +} +func (m *Request_OfferSnapshot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_OfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.OfferSnapshot != nil { + { + size, err := m.OfferSnapshot.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x6a + } + return len(dAtA) - i, nil +} +func (m *Request_LoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_LoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.LoadSnapshotChunk != nil { + { + size, err := m.LoadSnapshotChunk.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x72 + } + return len(dAtA) - i, nil +} +func (m *Request_ApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_ApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ApplySnapshotChunk != nil { + { + size, err := m.ApplySnapshotChunk.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x7a + } + return len(dAtA) - i, nil +} +func (m *Request_PrepareProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_PrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PrepareProposal != nil { + { + size, err := m.PrepareProposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x82 + } + return len(dAtA) - i, nil +} +func (m *Request_ProcessProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_ProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ProcessProposal != nil { + { + size, err := m.ProcessProposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x8a + } + return len(dAtA) - i, nil +} +func (m *Request_ExtendVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_ExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ExtendVote != nil { + { + size, err := m.ExtendVote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x92 + } + return len(dAtA) - i, nil +} +func (m *Request_VerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_VerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.VerifyVoteExtension != nil { + { + size, err := m.VerifyVoteExtension.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x9a + } + return len(dAtA) - i, nil +} +func (m *Request_FinalizeBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Request_FinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.FinalizeBlock != nil { + { + size, err := m.FinalizeBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xa2 + } + return len(dAtA) - i, nil +} +func (m *RequestEcho) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestEcho) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestEcho) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Message) > 0 { + i -= len(m.Message) + copy(dAtA[i:], m.Message) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Message))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestFlush) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestFlush) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestFlush) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *RequestInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AbciVersion) > 0 { + i -= len(m.AbciVersion) + copy(dAtA[i:], m.AbciVersion) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AbciVersion))) + i-- + dAtA[i] = 0x22 + } + if m.P2PVersion != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.P2PVersion)) + i-- + dAtA[i] = 0x18 + } + if m.BlockVersion != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockVersion)) + i-- + dAtA[i] = 0x10 + } + if len(m.Version) > 0 { + i -= len(m.Version) + copy(dAtA[i:], m.Version) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Version))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestInitChain) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestInitChain) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestInitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.InitialHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.InitialHeight)) + i-- + dAtA[i] = 0x30 + } + if len(m.AppStateBytes) > 0 { + i -= len(m.AppStateBytes) + copy(dAtA[i:], m.AppStateBytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppStateBytes))) + i-- + dAtA[i] = 0x2a + } + if len(m.Validators) > 0 { + for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if m.ConsensusParams != nil { + { + size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x12 + } + n18, err18 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err18 != nil { + return 0, err18 + } + i -= n18 + i = encodeVarintTypes(dAtA, i, uint64(n18)) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *RequestQuery) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestQuery) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestQuery) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Prove { + i-- + if m.Prove { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x18 + } + if len(m.Path) > 0 { + i -= len(m.Path) + copy(dAtA[i:], m.Path) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Path))) + i-- + dAtA[i] = 0x12 + } + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestCheckTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestCheckTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestCheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x10 + } + if len(m.Tx) > 0 { + i -= len(m.Tx) + copy(dAtA[i:], m.Tx) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestCommit) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestCommit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *RequestListSnapshots) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestListSnapshots) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *RequestOfferSnapshot) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestOfferSnapshot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestOfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x12 + } + if m.Snapshot != nil { + { + size, err := m.Snapshot.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestLoadSnapshotChunk) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestLoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestLoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Chunk != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Chunk)) + i-- + dAtA[i] = 0x18 + } + if m.Format != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Format)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *RequestApplySnapshotChunk) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0x1a + } + if len(m.Chunk) > 0 { + i -= len(m.Chunk) + copy(dAtA[i:], m.Chunk) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Chunk))) + i-- + dAtA[i] = 0x12 + } + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *RequestPrepareProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestPrepareProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestPrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ProposerAddress) > 0 { + i -= len(m.ProposerAddress) + copy(dAtA[i:], m.ProposerAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress))) + i-- + dAtA[i] = 0x42 + } + if len(m.NextValidatorsHash) > 0 { + i -= len(m.NextValidatorsHash) + copy(dAtA[i:], m.NextValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash))) + i-- + dAtA[i] = 0x3a + } + n20, err20 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err20 != nil { + return 0, err20 + } + i -= n20 + i = encodeVarintTypes(dAtA, i, uint64(n20)) + i-- + dAtA[i] = 0x32 + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x28 + } + if len(m.Misbehavior) > 0 { + for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + { + size, err := m.LocalLastCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if m.MaxTxBytes != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.MaxTxBytes)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *RequestProcessProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestProcessProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ProposerAddress) > 0 { + i -= len(m.ProposerAddress) + copy(dAtA[i:], m.ProposerAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress))) + i-- + dAtA[i] = 0x42 + } + if len(m.NextValidatorsHash) > 0 { + i -= len(m.NextValidatorsHash) + copy(dAtA[i:], m.NextValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash))) + i-- + dAtA[i] = 0x3a + } + n22, err22 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err22 != nil { + return 0, err22 + } + i -= n22 + i = encodeVarintTypes(dAtA, i, uint64(n22)) + i-- + dAtA[i] = 0x32 + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x28 + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x22 + } + if len(m.Misbehavior) > 0 { + for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + { + size, err := m.ProposedLastCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *RequestExtendVote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestExtendVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ProposerAddress) > 0 { + i -= len(m.ProposerAddress) + copy(dAtA[i:], m.ProposerAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress))) + i-- + dAtA[i] = 0x42 + } + if len(m.NextValidatorsHash) > 0 { + i -= len(m.NextValidatorsHash) + copy(dAtA[i:], m.NextValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash))) + i-- + dAtA[i] = 0x3a + } + if len(m.Misbehavior) > 0 { + for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + } + { + size, err := m.ProposedLastCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0x22 + } + } + n25, err25 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err25 != nil { + return 0, err25 + } + i -= n25 + i = encodeVarintTypes(dAtA, i, uint64(n25)) + i-- + dAtA[i] = 0x1a + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestVerifyVoteExtension) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestVerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestVerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.VoteExtension) > 0 { + i -= len(m.VoteExtension) + copy(dAtA[i:], m.VoteExtension) + i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension))) + i-- + dAtA[i] = 0x22 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x18 + } + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *RequestFinalizeBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestFinalizeBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestFinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ProposerAddress) > 0 { + i -= len(m.ProposerAddress) + copy(dAtA[i:], m.ProposerAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress))) + i-- + dAtA[i] = 0x42 + } + if len(m.NextValidatorsHash) > 0 { + i -= len(m.NextValidatorsHash) + copy(dAtA[i:], m.NextValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash))) + i-- + dAtA[i] = 0x3a + } + n26, err26 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err26 != nil { + return 0, err26 + } + i -= n26 + i = encodeVarintTypes(dAtA, i, uint64(n26)) + i-- + dAtA[i] = 0x32 + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x28 + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x22 + } + if len(m.Misbehavior) > 0 { + for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + { + size, err := m.DecidedLastCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Response) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Response) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Value != nil { + { + size := m.Value.Size() + i -= size + if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Response_Exception) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Exception) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Exception != nil { + { + size, err := m.Exception.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Response_Echo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Echo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Echo != nil { + { + size, err := m.Echo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Response_Flush) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Flush) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Flush != nil { + { + size, err := m.Flush.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Response_Info) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Info) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Info != nil { + { + size, err := m.Info.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *Response_InitChain) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_InitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.InitChain != nil { + { + size, err := m.InitChain.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + return len(dAtA) - i, nil +} +func (m *Response_Query) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Query) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Query != nil { + { + size, err := m.Query.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + return len(dAtA) - i, nil +} +func (m *Response_CheckTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_CheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.CheckTx != nil { + { + size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + return len(dAtA) - i, nil +} +func (m *Response_Commit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Commit != nil { + { + size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x62 + } + return len(dAtA) - i, nil +} +func (m *Response_ListSnapshots) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_ListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ListSnapshots != nil { + { + size, err := m.ListSnapshots.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x6a + } + return len(dAtA) - i, nil +} +func (m *Response_OfferSnapshot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_OfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.OfferSnapshot != nil { + { + size, err := m.OfferSnapshot.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x72 + } + return len(dAtA) - i, nil +} +func (m *Response_LoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_LoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.LoadSnapshotChunk != nil { + { + size, err := m.LoadSnapshotChunk.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x7a + } + return len(dAtA) - i, nil +} +func (m *Response_ApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_ApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ApplySnapshotChunk != nil { + { + size, err := m.ApplySnapshotChunk.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x82 + } + return len(dAtA) - i, nil +} +func (m *Response_PrepareProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_PrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PrepareProposal != nil { + { + size, err := m.PrepareProposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x8a + } + return len(dAtA) - i, nil +} +func (m *Response_ProcessProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_ProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ProcessProposal != nil { + { + size, err := m.ProcessProposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x92 + } + return len(dAtA) - i, nil +} +func (m *Response_ExtendVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_ExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ExtendVote != nil { + { + size, err := m.ExtendVote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x9a + } + return len(dAtA) - i, nil +} +func (m *Response_VerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_VerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.VerifyVoteExtension != nil { + { + size, err := m.VerifyVoteExtension.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xa2 + } + return len(dAtA) - i, nil +} +func (m *Response_FinalizeBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Response_FinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.FinalizeBlock != nil { + { + size, err := m.FinalizeBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xaa + } + return len(dAtA) - i, nil +} +func (m *ResponseException) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseException) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseException) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Error) > 0 { + i -= len(m.Error) + copy(dAtA[i:], m.Error) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Error))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseEcho) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseEcho) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseEcho) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Message) > 0 { + i -= len(m.Message) + copy(dAtA[i:], m.Message) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Message))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseFlush) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseFlush) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseFlush) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *ResponseInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.LastBlockAppHash) > 0 { + i -= len(m.LastBlockAppHash) + copy(dAtA[i:], m.LastBlockAppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LastBlockAppHash))) + i-- + dAtA[i] = 0x2a + } + if m.LastBlockHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastBlockHeight)) + i-- + dAtA[i] = 0x20 + } + if m.AppVersion != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.AppVersion)) + i-- + dAtA[i] = 0x18 + } + if len(m.Version) > 0 { + i -= len(m.Version) + copy(dAtA[i:], m.Version) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Version))) + i-- + dAtA[i] = 0x12 + } + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseInitChain) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseInitChain) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseInitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x1a + } + if len(m.Validators) > 0 { + for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.ConsensusParams != nil { + { + size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseQuery) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseQuery) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseQuery) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Codespace) > 0 { + i -= len(m.Codespace) + copy(dAtA[i:], m.Codespace) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace))) + i-- + dAtA[i] = 0x52 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x48 + } + if m.ProofOps != nil { + { + size, err := m.ProofOps.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + if len(m.Value) > 0 { + i -= len(m.Value) + copy(dAtA[i:], m.Value) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) + i-- + dAtA[i] = 0x3a + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0x32 + } + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x28 + } + if len(m.Info) > 0 { + i -= len(m.Info) + copy(dAtA[i:], m.Info) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Info))) + i-- + dAtA[i] = 0x22 + } + if len(m.Log) > 0 { + i -= len(m.Log) + copy(dAtA[i:], m.Log) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Log))) + i-- + dAtA[i] = 0x1a + } + if m.Code != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponseCheckTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseCheckTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseCheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Codespace) > 0 { + i -= len(m.Codespace) + copy(dAtA[i:], m.Codespace) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace))) + i-- + dAtA[i] = 0x42 + } + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + } + if m.GasUsed != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.GasUsed)) + i-- + dAtA[i] = 0x30 + } + if m.GasWanted != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.GasWanted)) + i-- + dAtA[i] = 0x28 + } + if len(m.Info) > 0 { + i -= len(m.Info) + copy(dAtA[i:], m.Info) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Info))) + i-- + dAtA[i] = 0x22 + } + if len(m.Log) > 0 { + i -= len(m.Log) + copy(dAtA[i:], m.Log) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Log))) + i-- + dAtA[i] = 0x1a + } + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x12 + } + if m.Code != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponseCommit) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseCommit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.RetainHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.RetainHeight)) + i-- + dAtA[i] = 0x18 + } + return len(dAtA) - i, nil +} + +func (m *ResponseListSnapshots) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseListSnapshots) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Snapshots) > 0 { + for iNdEx := len(m.Snapshots) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Snapshots[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ResponseOfferSnapshot) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseOfferSnapshot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseOfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Result != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Result)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponseLoadSnapshotChunk) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseLoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseLoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Chunk) > 0 { + i -= len(m.Chunk) + copy(dAtA[i:], m.Chunk) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Chunk))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseApplySnapshotChunk) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.RejectSenders) > 0 { + for iNdEx := len(m.RejectSenders) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.RejectSenders[iNdEx]) + copy(dAtA[i:], m.RejectSenders[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.RejectSenders[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if len(m.RefetchChunks) > 0 { + dAtA48 := make([]byte, len(m.RefetchChunks)*10) + var j47 int + for _, num := range m.RefetchChunks { + for num >= 1<<7 { + dAtA48[j47] = uint8(uint64(num)&0x7f | 0x80) + num >>= 7 + j47++ + } + dAtA48[j47] = uint8(num) + j47++ + } + i -= j47 + copy(dAtA[i:], dAtA48[:j47]) + i = encodeVarintTypes(dAtA, i, uint64(j47)) + i-- + dAtA[i] = 0x12 + } + if m.Result != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Result)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponsePrepareProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponsePrepareProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponsePrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ResponseProcessProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseProcessProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Status != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Status)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponseExtendVote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseExtendVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.VoteExtension) > 0 { + i -= len(m.VoteExtension) + copy(dAtA[i:], m.VoteExtension) + i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponseVerifyVoteExtension) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseVerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseVerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Status != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Status)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ResponseFinalizeBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseFinalizeBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseFinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x2a + } + if m.ConsensusParamUpdates != nil { + { + size, err := m.ConsensusParamUpdates.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if len(m.ValidatorUpdates) > 0 { + for iNdEx := len(m.ValidatorUpdates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ValidatorUpdates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.TxResults) > 0 { + for iNdEx := len(m.TxResults) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.TxResults[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *CommitInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CommitInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CommitInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Votes) > 0 { + for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ExtendedCommitInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExtendedCommitInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ExtendedCommitInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Votes) > 0 { + for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Event) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Event) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Event) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Attributes) > 0 { + for iNdEx := len(m.Attributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Attributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Type) > 0 { + i -= len(m.Type) + copy(dAtA[i:], m.Type) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Type))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *EventAttribute) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EventAttribute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EventAttribute) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Index { + i-- + if m.Index { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + } + if len(m.Value) > 0 { + i -= len(m.Value) + copy(dAtA[i:], m.Value) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) + i-- + dAtA[i] = 0x12 + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ExecTxResult) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExecTxResult) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ExecTxResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Codespace) > 0 { + i -= len(m.Codespace) + copy(dAtA[i:], m.Codespace) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace))) + i-- + dAtA[i] = 0x42 + } + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + } + if m.GasUsed != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.GasUsed)) + i-- + dAtA[i] = 0x30 + } + if m.GasWanted != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.GasWanted)) + i-- + dAtA[i] = 0x28 + } + if len(m.Info) > 0 { + i -= len(m.Info) + copy(dAtA[i:], m.Info) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Info))) + i-- + dAtA[i] = 0x22 + } + if len(m.Log) > 0 { + i -= len(m.Log) + copy(dAtA[i:], m.Log) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Log))) + i-- + dAtA[i] = 0x1a + } + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x12 + } + if m.Code != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *TxResult) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxResult) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TxResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Result.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.Tx) > 0 { + i -= len(m.Tx) + copy(dAtA[i:], m.Tx) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx))) + i-- + dAtA[i] = 0x1a + } + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Validator) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Validator) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Validator) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Power != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Power)) + i-- + dAtA[i] = 0x18 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ValidatorUpdate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorUpdate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValidatorUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Power != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Power)) + i-- + dAtA[i] = 0x10 + } + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *VoteInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VoteInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VoteInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.BlockIdFlag != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag)) + i-- + dAtA[i] = 0x18 + } + { + size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ExtendedVoteInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExtendedVoteInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ExtendedVoteInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.BlockIdFlag != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag)) + i-- + dAtA[i] = 0x28 + } + if len(m.ExtensionSignature) > 0 { + i -= len(m.ExtensionSignature) + copy(dAtA[i:], m.ExtensionSignature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature))) + i-- + dAtA[i] = 0x22 + } + if len(m.VoteExtension) > 0 { + i -= len(m.VoteExtension) + copy(dAtA[i:], m.VoteExtension) + i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension))) + i-- + dAtA[i] = 0x1a + } + { + size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Misbehavior) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Misbehavior) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Misbehavior) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TotalVotingPower != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.TotalVotingPower)) + i-- + dAtA[i] = 0x28 + } + n54, err54 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err54 != nil { + return 0, err54 + } + i -= n54 + i = encodeVarintTypes(dAtA, i, uint64(n54)) + i-- + dAtA[i] = 0x22 + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x18 + } + { + size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Snapshot) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Snapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Metadata) > 0 { + i -= len(m.Metadata) + copy(dAtA[i:], m.Metadata) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Metadata))) + i-- + dAtA[i] = 0x2a + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x22 + } + if m.Chunks != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Chunks)) + i-- + dAtA[i] = 0x18 + } + if m.Format != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Format)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Request) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Value != nil { + n += m.Value.Size() + } + return n +} + +func (m *Request_Echo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Echo != nil { + l = m.Echo.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_Flush) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Flush != nil { + l = m.Flush.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_Info) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Info != nil { + l = m.Info.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_InitChain) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.InitChain != nil { + l = m.InitChain.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_Query) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Query != nil { + l = m.Query.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_CheckTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CheckTx != nil { + l = m.CheckTx.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_Commit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Commit != nil { + l = m.Commit.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_ListSnapshots) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ListSnapshots != nil { + l = m.ListSnapshots.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_OfferSnapshot) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.OfferSnapshot != nil { + l = m.OfferSnapshot.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_LoadSnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.LoadSnapshotChunk != nil { + l = m.LoadSnapshotChunk.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_ApplySnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ApplySnapshotChunk != nil { + l = m.ApplySnapshotChunk.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_PrepareProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PrepareProposal != nil { + l = m.PrepareProposal.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_ProcessProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ProcessProposal != nil { + l = m.ProcessProposal.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_ExtendVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ExtendVote != nil { + l = m.ExtendVote.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_VerifyVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VerifyVoteExtension != nil { + l = m.VerifyVoteExtension.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Request_FinalizeBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.FinalizeBlock != nil { + l = m.FinalizeBlock.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *RequestEcho) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Message) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestFlush) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *RequestInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Version) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.BlockVersion != 0 { + n += 1 + sovTypes(uint64(m.BlockVersion)) + } + if m.P2PVersion != 0 { + n += 1 + sovTypes(uint64(m.P2PVersion)) + } + l = len(m.AbciVersion) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestInitChain) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.ConsensusParams != nil { + l = m.ConsensusParams.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Validators) > 0 { + for _, e := range m.Validators { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.AppStateBytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.InitialHeight != 0 { + n += 1 + sovTypes(uint64(m.InitialHeight)) + } + return n +} + +func (m *RequestQuery) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Path) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Prove { + n += 2 + } + return n +} + +func (m *RequestCheckTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Tx) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + return n +} + +func (m *RequestCommit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *RequestListSnapshots) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *RequestOfferSnapshot) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Snapshot != nil { + l = m.Snapshot.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestLoadSnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Format != 0 { + n += 1 + sovTypes(uint64(m.Format)) + } + if m.Chunk != 0 { + n += 1 + sovTypes(uint64(m.Chunk)) + } + return n +} + +func (m *RequestApplySnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + l = len(m.Chunk) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestPrepareProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MaxTxBytes != 0 { + n += 1 + sovTypes(uint64(m.MaxTxBytes)) + } + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + l = m.LocalLastCommit.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.Misbehavior) > 0 { + for _, e := range m.Misbehavior { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.NextValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ProposerAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestProcessProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + l = m.ProposedLastCommit.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.Misbehavior) > 0 { + for _, e := range m.Misbehavior { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.NextValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ProposerAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestExtendVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + l = m.ProposedLastCommit.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.Misbehavior) > 0 { + for _, e := range m.Misbehavior { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.NextValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ProposerAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestVerifyVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = len(m.VoteExtension) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *RequestFinalizeBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + l = m.DecidedLastCommit.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.Misbehavior) > 0 { + for _, e := range m.Misbehavior { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.NextValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ProposerAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Response) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Value != nil { + n += m.Value.Size() + } + return n +} + +func (m *Response_Exception) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Exception != nil { + l = m.Exception.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_Echo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Echo != nil { + l = m.Echo.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_Flush) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Flush != nil { + l = m.Flush.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_Info) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Info != nil { + l = m.Info.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_InitChain) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.InitChain != nil { + l = m.InitChain.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_Query) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Query != nil { + l = m.Query.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_CheckTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CheckTx != nil { + l = m.CheckTx.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_Commit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Commit != nil { + l = m.Commit.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_ListSnapshots) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ListSnapshots != nil { + l = m.ListSnapshots.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_OfferSnapshot) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.OfferSnapshot != nil { + l = m.OfferSnapshot.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_LoadSnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.LoadSnapshotChunk != nil { + l = m.LoadSnapshotChunk.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_ApplySnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ApplySnapshotChunk != nil { + l = m.ApplySnapshotChunk.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_PrepareProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PrepareProposal != nil { + l = m.PrepareProposal.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_ProcessProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ProcessProposal != nil { + l = m.ProcessProposal.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_ExtendVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ExtendVote != nil { + l = m.ExtendVote.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_VerifyVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VerifyVoteExtension != nil { + l = m.VerifyVoteExtension.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Response_FinalizeBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.FinalizeBlock != nil { + l = m.FinalizeBlock.Size() + n += 2 + l + sovTypes(uint64(l)) + } + return n +} +func (m *ResponseException) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Error) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseEcho) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Message) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseFlush) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *ResponseInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Version) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.AppVersion != 0 { + n += 1 + sovTypes(uint64(m.AppVersion)) + } + if m.LastBlockHeight != 0 { + n += 1 + sovTypes(uint64(m.LastBlockHeight)) + } + l = len(m.LastBlockAppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseInitChain) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ConsensusParams != nil { + l = m.ConsensusParams.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Validators) > 0 { + for _, e := range m.Validators { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseQuery) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Code != 0 { + n += 1 + sovTypes(uint64(m.Code)) + } + l = len(m.Log) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Info) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + l = len(m.Key) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Value) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.ProofOps != nil { + l = m.ProofOps.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = len(m.Codespace) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseCheckTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Code != 0 { + n += 1 + sovTypes(uint64(m.Code)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Log) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Info) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.GasWanted != 0 { + n += 1 + sovTypes(uint64(m.GasWanted)) + } + if m.GasUsed != 0 { + n += 1 + sovTypes(uint64(m.GasUsed)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.Codespace) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseCommit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.RetainHeight != 0 { + n += 1 + sovTypes(uint64(m.RetainHeight)) + } + return n +} + +func (m *ResponseListSnapshots) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Snapshots) > 0 { + for _, e := range m.Snapshots { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ResponseOfferSnapshot) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Result != 0 { + n += 1 + sovTypes(uint64(m.Result)) + } + return n +} + +func (m *ResponseLoadSnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Chunk) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseApplySnapshotChunk) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Result != 0 { + n += 1 + sovTypes(uint64(m.Result)) + } + if len(m.RefetchChunks) > 0 { + l = 0 + for _, e := range m.RefetchChunks { + l += sovTypes(uint64(e)) + } + n += 1 + sovTypes(uint64(l)) + l + } + if len(m.RejectSenders) > 0 { + for _, s := range m.RejectSenders { + l = len(s) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ResponsePrepareProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ResponseProcessProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Status != 0 { + n += 1 + sovTypes(uint64(m.Status)) + } + return n +} + +func (m *ResponseExtendVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.VoteExtension) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseVerifyVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Status != 0 { + n += 1 + sovTypes(uint64(m.Status)) + } + return n +} + +func (m *ResponseFinalizeBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if len(m.TxResults) > 0 { + for _, e := range m.TxResults { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if len(m.ValidatorUpdates) > 0 { + for _, e := range m.ValidatorUpdates { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if m.ConsensusParamUpdates != nil { + l = m.ConsensusParamUpdates.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *CommitInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if len(m.Votes) > 0 { + for _, e := range m.Votes { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ExtendedCommitInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if len(m.Votes) > 0 { + for _, e := range m.Votes { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *Event) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Type) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Attributes) > 0 { + for _, e := range m.Attributes { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *EventAttribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Value) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Index { + n += 2 + } + return n +} + +func (m *ExecTxResult) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Code != 0 { + n += 1 + sovTypes(uint64(m.Code)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Log) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Info) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.GasWanted != 0 { + n += 1 + sovTypes(uint64(m.GasWanted)) + } + if m.GasUsed != 0 { + n += 1 + sovTypes(uint64(m.GasUsed)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.Codespace) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *TxResult) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + l = len(m.Tx) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.Result.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *Validator) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Power != 0 { + n += 1 + sovTypes(uint64(m.Power)) + } + return n +} + +func (m *ValidatorUpdate) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.PubKey.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Power != 0 { + n += 1 + sovTypes(uint64(m.Power)) + } + return n +} + +func (m *VoteInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Validator.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.BlockIdFlag != 0 { + n += 1 + sovTypes(uint64(m.BlockIdFlag)) + } + return n +} + +func (m *ExtendedVoteInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Validator.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.VoteExtension) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ExtensionSignature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.BlockIdFlag != 0 { + n += 1 + sovTypes(uint64(m.BlockIdFlag)) + } + return n +} + +func (m *Misbehavior) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + l = m.Validator.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + if m.TotalVotingPower != 0 { + n += 1 + sovTypes(uint64(m.TotalVotingPower)) + } + return n +} + +func (m *Snapshot) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Format != 0 { + n += 1 + sovTypes(uint64(m.Format)) + } + if m.Chunks != 0 { + n += 1 + sovTypes(uint64(m.Chunks)) + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Metadata) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Request) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Request: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Request: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Echo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestEcho{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_Echo{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Flush", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestFlush{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_Flush{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestInfo{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_Info{v} + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitChain", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestInitChain{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_InitChain{v} + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestQuery{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_Query{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestCheckTx{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_CheckTx{v} + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestCommit{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_Commit{v} + iNdEx = postIndex + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListSnapshots", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestListSnapshots{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_ListSnapshots{v} + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OfferSnapshot", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestOfferSnapshot{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_OfferSnapshot{v} + iNdEx = postIndex + case 14: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LoadSnapshotChunk", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestLoadSnapshotChunk{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_LoadSnapshotChunk{v} + iNdEx = postIndex + case 15: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ApplySnapshotChunk", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestApplySnapshotChunk{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_ApplySnapshotChunk{v} + iNdEx = postIndex + case 16: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PrepareProposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestPrepareProposal{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_PrepareProposal{v} + iNdEx = postIndex + case 17: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProcessProposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestProcessProposal{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_ProcessProposal{v} + iNdEx = postIndex + case 18: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtendVote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestExtendVote{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_ExtendVote{v} + iNdEx = postIndex + case 19: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VerifyVoteExtension", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestVerifyVoteExtension{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_VerifyVoteExtension{v} + iNdEx = postIndex + case 20: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FinalizeBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &RequestFinalizeBlock{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Request_FinalizeBlock{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestEcho) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestEcho: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestEcho: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestFlush) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestFlush: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestFlush: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockVersion", wireType) + } + m.BlockVersion = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockVersion |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field P2PVersion", wireType) + } + m.P2PVersion = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.P2PVersion |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AbciVersion", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AbciVersion = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestInitChain) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestInitChain: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestInitChain: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ConsensusParams == nil { + m.ConsensusParams = &types1.ConsensusParams{} + } + if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validators = append(m.Validators, ValidatorUpdate{}) + if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppStateBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppStateBytes = append(m.AppStateBytes[:0], dAtA[iNdEx:postIndex]...) + if m.AppStateBytes == nil { + m.AppStateBytes = []byte{} + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field InitialHeight", wireType) + } + m.InitialHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.InitialHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestQuery) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestQuery: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestQuery: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Path", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Path = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Prove", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Prove = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestCheckTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestCheckTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestCheckTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...) + if m.Tx == nil { + m.Tx = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= CheckTxType(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestCommit) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestCommit: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestCommit: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestListSnapshots) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestListSnapshots: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestListSnapshots: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestOfferSnapshot) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestOfferSnapshot: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestOfferSnapshot: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Snapshot", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Snapshot == nil { + m.Snapshot = &Snapshot{} + } + if err := m.Snapshot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestLoadSnapshotChunk) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestLoadSnapshotChunk: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestLoadSnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType) + } + m.Format = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Format |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType) + } + m.Chunk = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Chunk |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestApplySnapshotChunk) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestApplySnapshotChunk: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestApplySnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Chunk = append(m.Chunk[:0], dAtA[iNdEx:postIndex]...) + if m.Chunk == nil { + m.Chunk = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestPrepareProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestPrepareProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestPrepareProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxTxBytes", wireType) + } + m.MaxTxBytes = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxTxBytes |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LocalLastCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LocalLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Misbehavior = append(m.Misbehavior, Misbehavior{}) + if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.NextValidatorsHash == nil { + m.NextValidatorsHash = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ProposerAddress == nil { + m.ProposerAddress = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestProcessProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestProcessProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestProcessProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposedLastCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ProposedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Misbehavior = append(m.Misbehavior, Misbehavior{}) + if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.NextValidatorsHash == nil { + m.NextValidatorsHash = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ProposerAddress == nil { + m.ProposerAddress = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestExtendVote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestExtendVote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestExtendVote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposedLastCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ProposedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Misbehavior = append(m.Misbehavior, Misbehavior{}) + if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.NextValidatorsHash == nil { + m.NextValidatorsHash = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ProposerAddress == nil { + m.ProposerAddress = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestVerifyVoteExtension) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestVerifyVoteExtension: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestVerifyVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorAddress == nil { + m.ValidatorAddress = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...) + if m.VoteExtension == nil { + m.VoteExtension = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestFinalizeBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestFinalizeBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestFinalizeBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DecidedLastCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.DecidedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Misbehavior = append(m.Misbehavior, Misbehavior{}) + if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.NextValidatorsHash == nil { + m.NextValidatorsHash = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ProposerAddress == nil { + m.ProposerAddress = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Response) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Response: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Response: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Exception", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseException{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Exception{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Echo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseEcho{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Echo{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Flush", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseFlush{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Flush{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseInfo{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Info{v} + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitChain", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseInitChain{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_InitChain{v} + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseQuery{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Query{v} + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseCheckTx{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_CheckTx{v} + iNdEx = postIndex + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseCommit{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_Commit{v} + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListSnapshots", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseListSnapshots{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_ListSnapshots{v} + iNdEx = postIndex + case 14: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OfferSnapshot", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseOfferSnapshot{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_OfferSnapshot{v} + iNdEx = postIndex + case 15: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LoadSnapshotChunk", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseLoadSnapshotChunk{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_LoadSnapshotChunk{v} + iNdEx = postIndex + case 16: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ApplySnapshotChunk", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseApplySnapshotChunk{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_ApplySnapshotChunk{v} + iNdEx = postIndex + case 17: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PrepareProposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponsePrepareProposal{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_PrepareProposal{v} + iNdEx = postIndex + case 18: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProcessProposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseProcessProposal{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_ProcessProposal{v} + iNdEx = postIndex + case 19: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtendVote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseExtendVote{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_ExtendVote{v} + iNdEx = postIndex + case 20: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VerifyVoteExtension", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseVerifyVoteExtension{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_VerifyVoteExtension{v} + iNdEx = postIndex + case 21: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FinalizeBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ResponseFinalizeBlock{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Value = &Response_FinalizeBlock{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseException) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseException: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseException: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Error = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseEcho) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseEcho: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseEcho: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseFlush) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseFlush: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseFlush: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AppVersion", wireType) + } + m.AppVersion = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AppVersion |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockHeight", wireType) + } + m.LastBlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastBlockHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockAppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LastBlockAppHash = append(m.LastBlockAppHash[:0], dAtA[iNdEx:postIndex]...) + if m.LastBlockAppHash == nil { + m.LastBlockAppHash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseInitChain) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseInitChain: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseInitChain: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ConsensusParams == nil { + m.ConsensusParams = &types1.ConsensusParams{} + } + if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validators = append(m.Validators, ValidatorUpdate{}) + if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseQuery) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseQuery: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseQuery: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Log = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Info = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) + if m.Value == nil { + m.Value = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProofOps", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ProofOps == nil { + m.ProofOps = &crypto.ProofOps{} + } + if err := m.ProofOps.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Codespace = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseCheckTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseCheckTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseCheckTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Log = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Info = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType) + } + m.GasWanted = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasWanted |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + } + m.GasUsed = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasUsed |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Codespace = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseCommit) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseCommit: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseCommit: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RetainHeight", wireType) + } + m.RetainHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RetainHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseListSnapshots) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseListSnapshots: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseListSnapshots: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Snapshots", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Snapshots = append(m.Snapshots, &Snapshot{}) + if err := m.Snapshots[len(m.Snapshots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseOfferSnapshot) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseOfferSnapshot: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseOfferSnapshot: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + } + m.Result = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Result |= ResponseOfferSnapshot_Result(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseLoadSnapshotChunk) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseLoadSnapshotChunk: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseLoadSnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Chunk = append(m.Chunk[:0], dAtA[iNdEx:postIndex]...) + if m.Chunk == nil { + m.Chunk = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseApplySnapshotChunk) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseApplySnapshotChunk: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseApplySnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + } + m.Result = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Result |= ResponseApplySnapshotChunk_Result(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType == 0 { + var v uint32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.RefetchChunks = append(m.RefetchChunks, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ + } + } + elementCount = count + if elementCount != 0 && len(m.RefetchChunks) == 0 { + m.RefetchChunks = make([]uint32, 0, elementCount) + } + for iNdEx < postIndex { + var v uint32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.RefetchChunks = append(m.RefetchChunks, v) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field RefetchChunks", wireType) + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RejectSenders", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RejectSenders = append(m.RejectSenders, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponsePrepareProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponsePrepareProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponsePrepareProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseProcessProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseProcessProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseProcessProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + m.Status = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Status |= ResponseProcessProposal_ProposalStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseExtendVote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseExtendVote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseExtendVote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...) + if m.VoteExtension == nil { + m.VoteExtension = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseVerifyVoteExtension) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseVerifyVoteExtension: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseVerifyVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + m.Status = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Status |= ResponseVerifyVoteExtension_VerifyStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseFinalizeBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseFinalizeBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseFinalizeBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxResults", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TxResults = append(m.TxResults, &ExecTxResult{}) + if err := m.TxResults[len(m.TxResults)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorUpdates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorUpdates = append(m.ValidatorUpdates, ValidatorUpdate{}) + if err := m.ValidatorUpdates[len(m.ValidatorUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParamUpdates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ConsensusParamUpdates == nil { + m.ConsensusParamUpdates = &types1.ConsensusParams{} + } + if err := m.ConsensusParamUpdates.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CommitInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CommitInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CommitInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Votes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Votes = append(m.Votes, VoteInfo{}) + if err := m.Votes[len(m.Votes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExtendedCommitInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExtendedCommitInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExtendedCommitInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Votes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Votes = append(m.Votes, ExtendedVoteInfo{}) + if err := m.Votes[len(m.Votes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Event) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Event: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Event: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Type = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Attributes = append(m.Attributes, EventAttribute{}) + if err := m.Attributes[len(m.Attributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EventAttribute) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EventAttribute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EventAttribute: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Index = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExecTxResult) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExecTxResult: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExecTxResult: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Log = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Info = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType) + } + m.GasWanted = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasWanted |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + } + m.GasUsed = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasUsed |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Codespace = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxResult) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxResult: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxResult: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...) + if m.Tx == nil { + m.Tx = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Validator) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Validator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Validator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorUpdate) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorUpdate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorUpdate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VoteInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VoteInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VoteInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType) + } + m.BlockIdFlag = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockIdFlag |= types1.BlockIDFlag(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExtendedVoteInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExtendedVoteInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExtendedVoteInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...) + if m.VoteExtension == nil { + m.VoteExtension = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...) + if m.ExtensionSignature == nil { + m.ExtensionSignature = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType) + } + m.BlockIdFlag = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockIdFlag |= types1.BlockIDFlag(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Misbehavior) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Misbehavior: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Misbehavior: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= MisbehaviorType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType) + } + m.TotalVotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TotalVotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Snapshot) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Snapshot: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Snapshot: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType) + } + m.Format = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Format |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunks", wireType) + } + m.Chunks = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Chunks |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Metadata = append(m.Metadata[:0], dAtA[iNdEx:postIndex]...) + if m.Metadata == nil { + m.Metadata = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/abci/types/types_test.go b/abci/types/types_test.go new file mode 100644 index 0000000..bf07c29 --- /dev/null +++ b/abci/types/types_test.go @@ -0,0 +1,74 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/merkle" +) + +func TestHashAndProveResults(t *testing.T) { + trs := []*abci.ExecTxResult{ + // Note, these tests rely on the first two entries being in this order. + {Code: 0, Data: nil}, + {Code: 0, Data: []byte{}}, + + {Code: 0, Data: []byte("one")}, + {Code: 14, Data: nil}, + {Code: 14, Data: []byte("foo")}, + {Code: 14, Data: []byte("bar")}, + } + + // Nil and []byte{} should produce the same bytes + bz0, err := trs[0].Marshal() + require.NoError(t, err) + bz1, err := trs[1].Marshal() + require.NoError(t, err) + require.Equal(t, bz0, bz1) + + // Make sure that we can get a root hash from results and verify proofs. + rs, err := abci.MarshalTxResults(trs) + require.NoError(t, err) + root := merkle.HashFromByteSlices(rs) + assert.NotEmpty(t, root) + + _, proofs := merkle.ProofsFromByteSlices(rs) + for i, tr := range trs { + bz, err := tr.Marshal() + require.NoError(t, err) + + valid := proofs[i].Verify(root, bz) + assert.NoError(t, valid, "%d", i) + } +} + +func TestHashDeterministicFieldsOnly(t *testing.T) { + tr1 := abci.ExecTxResult{ + Code: 1, + Data: []byte("transaction"), + Log: "nondeterministic data: abc", + Info: "nondeterministic data: abc", + GasWanted: 1000, + GasUsed: 1000, + Events: []abci.Event{}, + Codespace: "nondeterministic.data.abc", + } + tr2 := abci.ExecTxResult{ + Code: 1, + Data: []byte("transaction"), + Log: "nondeterministic data: def", + Info: "nondeterministic data: def", + GasWanted: 1000, + GasUsed: 1000, + Events: []abci.Event{}, + Codespace: "nondeterministic.data.def", + } + r1, err := abci.MarshalTxResults([]*abci.ExecTxResult{&tr1}) + require.NoError(t, err) + r2, err := abci.MarshalTxResults([]*abci.ExecTxResult{&tr2}) + require.NoError(t, err) + require.Equal(t, merkle.HashFromByteSlices(r1), merkle.HashFromByteSlices(r2)) +} diff --git a/abci/types/util.go b/abci/types/util.go new file mode 100644 index 0000000..70fd90c --- /dev/null +++ b/abci/types/util.go @@ -0,0 +1,31 @@ +package types + +import ( + "sort" +) + +//------------------------------------------------------------------------------ + +// ValidatorUpdates is a list of validators that implements the Sort interface +type ValidatorUpdates []ValidatorUpdate + +var _ sort.Interface = (ValidatorUpdates)(nil) + +// All these methods for ValidatorUpdates: +// Len, Less and Swap +// are for ValidatorUpdates to implement sort.Interface +// which will be used by the sort package. +// See Issue https://github.com/tendermint/abci/issues/212 + +func (v ValidatorUpdates) Len() int { + return len(v) +} + +// XXX: doesn't distinguish same validator with different power +func (v ValidatorUpdates) Less(i, j int) bool { + return v[i].PubKey.Compare(v[j].PubKey) <= 0 +} + +func (v ValidatorUpdates) Swap(i, j int) { + v[i], v[j] = v[j], v[i] +} diff --git a/abci/version/version.go b/abci/version/version.go new file mode 100644 index 0000000..85a2824 --- /dev/null +++ b/abci/version/version.go @@ -0,0 +1,9 @@ +package version + +import ( + "github.com/cometbft/cometbft/version" +) + +// TODO: eliminate this after some version refactor + +const Version = version.ABCISemVer diff --git a/blocksync/errors.go b/blocksync/errors.go new file mode 100644 index 0000000..ea893ae --- /dev/null +++ b/blocksync/errors.go @@ -0,0 +1,53 @@ +package blocksync + +import ( + "errors" + "fmt" + + "github.com/cosmos/gogoproto/proto" +) + +var ( + // ErrNilMessage is returned when provided message is empty + ErrNilMessage = errors.New("message cannot be nil") +) + +// ErrInvalidBase is returned when peer informs of a status with invalid height +type ErrInvalidHeight struct { + Height int64 + Reason string +} + +func (e ErrInvalidHeight) Error() string { + return fmt.Sprintf("invalid height %v: %s", e.Height, e.Reason) +} + +// ErrInvalidBase is returned when peer informs of a status with invalid base +type ErrInvalidBase struct { + Base int64 + Reason string +} + +func (e ErrInvalidBase) Error() string { + return fmt.Sprintf("invalid base %v: %s", e.Base, e.Reason) +} + +type ErrUnknownMessageType struct { + Msg proto.Message +} + +func (e ErrUnknownMessageType) Error() string { + return fmt.Sprintf("unknown message type %T", e.Msg) +} + +type ErrReactorValidation struct { + Err error +} + +func (e ErrReactorValidation) Error() string { + return fmt.Sprintf("reactor validation error: %v", e.Err) +} + +func (e ErrReactorValidation) Unwrap() error { + return e.Err +} diff --git a/blocksync/metrics.gen.go b/blocksync/metrics.gen.go new file mode 100644 index 0000000..619664f --- /dev/null +++ b/blocksync/metrics.gen.go @@ -0,0 +1,58 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package blocksync + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Syncing: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "syncing", + Help: "Whether or not a node is block syncing. 1 if yes, 0 if no.", + }, labels).With(labelsAndValues...), + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "num_txs", + Help: "Number of transactions in the latest block.", + }, labels).With(labelsAndValues...), + TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "total_txs", + Help: "Total number of transactions.", + }, labels).With(labelsAndValues...), + BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_size_bytes", + Help: "Size of the latest block.", + }, labels).With(labelsAndValues...), + LatestBlockHeight: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "latest_block_height", + Help: "The height of the latest block.", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Syncing: discard.NewGauge(), + NumTxs: discard.NewGauge(), + TotalTxs: discard.NewGauge(), + BlockSizeBytes: discard.NewGauge(), + LatestBlockHeight: discard.NewGauge(), + } +} diff --git a/blocksync/metrics.go b/blocksync/metrics.go new file mode 100644 index 0000000..5ef5568 --- /dev/null +++ b/blocksync/metrics.go @@ -0,0 +1,35 @@ +package blocksync + +import ( + "github.com/cometbft/cometbft/types" + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "blocksync" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Whether or not a node is block syncing. 1 if yes, 0 if no. + Syncing metrics.Gauge + // Number of transactions in the latest block. + NumTxs metrics.Gauge + // Total number of transactions. + TotalTxs metrics.Gauge + // Size of the latest block. + BlockSizeBytes metrics.Gauge + // The height of the latest block. + LatestBlockHeight metrics.Gauge +} + +func (m *Metrics) recordBlockMetrics(block *types.Block) { + m.NumTxs.Set(float64(len(block.Txs))) + m.TotalTxs.Add(float64(len(block.Txs))) + m.BlockSizeBytes.Set(float64(block.Size())) + m.LatestBlockHeight.Set(float64(block.Height)) +} diff --git a/blocksync/msgs.go b/blocksync/msgs.go new file mode 100644 index 0000000..eddd73a --- /dev/null +++ b/blocksync/msgs.go @@ -0,0 +1,56 @@ +package blocksync + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + bcproto "github.com/cometbft/cometbft/proto/tendermint/blocksync" + "github.com/cometbft/cometbft/types" +) + +const ( + // NOTE: keep up to date with bcproto.BlockResponse + BlockResponseMessagePrefixSize = 4 + BlockResponseMessageFieldKeySize = 1 + MaxMsgSize = types.MaxBlockSizeBytes + + BlockResponseMessagePrefixSize + + BlockResponseMessageFieldKeySize +) + +// ValidateMsg validates a message. +func ValidateMsg(pb proto.Message) error { + if pb == nil { + return ErrNilMessage + } + + switch msg := pb.(type) { + case *bcproto.BlockRequest: + if msg.Height < 0 { + return ErrInvalidHeight{Height: msg.Height, Reason: "negative height"} + } + case *bcproto.BlockResponse: + // Avoid double-calling `types.BlockFromProto` for performance reasons. + // See https://github.com/cometbft/cometbft/issues/1964 + return nil + case *bcproto.NoBlockResponse: + if msg.Height < 0 { + return ErrInvalidHeight{Height: msg.Height, Reason: "negative height"} + } + case *bcproto.StatusResponse: + if msg.Base < 0 { + return ErrInvalidBase{Base: msg.Base, Reason: "negative base"} + } + if msg.Height < 0 { + return ErrInvalidHeight{Height: msg.Height, Reason: "negative height"} + } + if msg.Base > msg.Height { + return ErrInvalidHeight{Height: msg.Height, Reason: fmt.Sprintf("base %v cannot be greater than height", msg.Base)} + } + case *bcproto.StatusRequest: + return nil + default: + return ErrUnknownMessageType{Msg: msg} + } + return nil +} diff --git a/blocksync/msgs_test.go b/blocksync/msgs_test.go new file mode 100644 index 0000000..1c17d43 --- /dev/null +++ b/blocksync/msgs_test.go @@ -0,0 +1,126 @@ +package blocksync_test + +import ( + "encoding/hex" + "math" + "testing" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/blocksync" + bcproto "github.com/cometbft/cometbft/proto/tendermint/blocksync" + "github.com/cometbft/cometbft/types" +) + +func TestBcBlockRequestMessageValidateBasic(t *testing.T) { + testCases := []struct { + testName string + requestHeight int64 + expectErr bool + }{ + {"Valid Request Message", 0, false}, + {"Valid Request Message", 1, false}, + {"Invalid Request Message", -1, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + request := bcproto.BlockRequest{Height: tc.requestHeight} + assert.Equal(t, tc.expectErr, blocksync.ValidateMsg(&request) != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestBcNoBlockResponseMessageValidateBasic(t *testing.T) { + testCases := []struct { + testName string + nonResponseHeight int64 + expectErr bool + }{ + {"Valid Non-Response Message", 0, false}, + {"Valid Non-Response Message", 1, false}, + {"Invalid Non-Response Message", -1, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + nonResponse := bcproto.NoBlockResponse{Height: tc.nonResponseHeight} + assert.Equal(t, tc.expectErr, blocksync.ValidateMsg(&nonResponse) != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestBcStatusRequestMessageValidateBasic(t *testing.T) { + request := bcproto.StatusRequest{} + assert.NoError(t, blocksync.ValidateMsg(&request)) +} + +func TestBcStatusResponseMessageValidateBasic(t *testing.T) { + testCases := []struct { + testName string + responseHeight int64 + expectErr bool + }{ + {"Valid Response Message", 0, false}, + {"Valid Response Message", 1, false}, + {"Invalid Response Message", -1, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + response := bcproto.StatusResponse{Height: tc.responseHeight} + assert.Equal(t, tc.expectErr, blocksync.ValidateMsg(&response) != nil, "Validate Basic had an unexpected result") + }) + } +} + +//nolint:lll // ignore line length in tests +func TestBlocksyncMessageVectors(t *testing.T) { + block := types.MakeBlock(int64(3), []types.Tx{types.Tx("Hello World")}, nil, nil) + block.Version.Block = 11 // overwrite updated protocol version + + bpb, err := block.ToProto() + require.NoError(t, err) + + testCases := []struct { + testName string + bmsg proto.Message + expBytes string + }{ + {"BlockRequestMessage", &bcproto.Message{Sum: &bcproto.Message_BlockRequest{ + BlockRequest: &bcproto.BlockRequest{Height: 1}}}, "0a020801"}, + {"BlockRequestMessage", &bcproto.Message{Sum: &bcproto.Message_BlockRequest{ + BlockRequest: &bcproto.BlockRequest{Height: math.MaxInt64}}}, + "0a0a08ffffffffffffffff7f"}, + {"BlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_BlockResponse{ + BlockResponse: &bcproto.BlockResponse{Block: bpb}}}, "1a700a6e0a5b0a02080b1803220b088092b8c398feffffff012a0212003a20c4da88e876062aa1543400d50d0eaa0dac88096057949cfb7bca7f3a48c04bf96a20e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855120d0a0b48656c6c6f20576f726c641a00"}, + {"NoBlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_NoBlockResponse{ + NoBlockResponse: &bcproto.NoBlockResponse{Height: 1}}}, "12020801"}, + {"NoBlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_NoBlockResponse{ + NoBlockResponse: &bcproto.NoBlockResponse{Height: math.MaxInt64}}}, + "120a08ffffffffffffffff7f"}, + {"StatusRequestMessage", &bcproto.Message{Sum: &bcproto.Message_StatusRequest{ + StatusRequest: &bcproto.StatusRequest{}}}, + "2200"}, + {"StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ + StatusResponse: &bcproto.StatusResponse{Height: 1, Base: 2}}}, + "2a0408011002"}, + {"StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ + StatusResponse: &bcproto.StatusResponse{Height: math.MaxInt64, Base: math.MaxInt64}}}, + "2a1408ffffffffffffffff7f10ffffffffffffffff7f"}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + bz, _ := proto.Marshal(tc.bmsg) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz)) + }) + } +} diff --git a/blocksync/pool.go b/blocksync/pool.go new file mode 100644 index 0000000..656fd83 --- /dev/null +++ b/blocksync/pool.go @@ -0,0 +1,909 @@ +package blocksync + +import ( + "errors" + "fmt" + "math" + "sort" + "sync/atomic" + "time" + + flow "github.com/cometbft/cometbft/libs/flowrate" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +/* +eg, L = latency = 0.1s + P = num peers = 10 + FN = num full nodes + BS = 1kB block size + CB = 1 Mbit/s = 128 kB/s + CB/P = 12.8 kB + B/S = CB/P/BS = 12.8 blocks/s + + 12.8 * 0.1 = 1.28 blocks on conn +*/ + +const ( + requestIntervalMS = 2 + maxPendingRequestsPerPeer = 20 + requestRetrySeconds = 30 + + // Minimum recv rate to ensure we're receiving blocks from a peer fast + // enough. If a peer is not sending us data at at least that rate, we + // consider them to have timedout and we disconnect. + // + // Based on the experiments with [Osmosis](https://osmosis.zone/), the + // minimum rate could be as high as 500 KB/s. However, we're setting it to + // 128 KB/s for now to be conservative. + minRecvRate = 128 * 1024 // 128 KB/s + + // peerConnWait is the time that must have elapsed since the pool routine + // was created before we start making requests. This is to give the peer + // routine time to connect to peers. + peerConnWait = 3 * time.Second + + // If we're within minBlocksForSingleRequest blocks of the pool's height, we + // send 2 parallel requests to 2 peers for the same block. If we're further + // away, we send a single request. + minBlocksForSingleRequest = 50 +) + +var peerTimeout = 15 * time.Second // not const so we can override with tests + +/* + Peers self report their heights when we join the block pool. + Starting from our latest pool.height, we request blocks + in sequence from peers that reported higher heights than ours. + Every so often we ask peers what height they're on so we can keep going. + + Requests are continuously made for blocks of higher heights until + the limit is reached. If most of the requests have no available peers, and we + are not at peer limits, we can probably switch to consensus reactor +*/ + +// BlockPool keeps track of the block sync peers, block requests and block responses. +type BlockPool struct { + service.BaseService + startTime time.Time + startHeight int64 + + mtx cmtsync.Mutex + // block requests + requesters map[int64]*bpRequester + height int64 // the lowest key in requesters. + // peers + peers map[p2p.ID]*bpPeer + bannedPeers map[p2p.ID]time.Time + sortedPeers []*bpPeer // sorted by curRate, highest first + maxPeerHeight int64 // the biggest reported height + + // atomic + numPending int32 // number of requests pending assignment or block response + + requestsCh chan<- BlockRequest + errorsCh chan<- peerError +} + +// NewBlockPool returns a new BlockPool with the height equal to start. Block +// requests and errors will be sent to requestsCh and errorsCh accordingly. +func NewBlockPool(start int64, requestsCh chan<- BlockRequest, errorsCh chan<- peerError) *BlockPool { + bp := &BlockPool{ + peers: make(map[p2p.ID]*bpPeer), + bannedPeers: make(map[p2p.ID]time.Time), + requesters: make(map[int64]*bpRequester), + height: start, + startHeight: start, + numPending: 0, + + requestsCh: requestsCh, + errorsCh: errorsCh, + } + bp.BaseService = *service.NewBaseService(nil, "BlockPool", bp) + return bp +} + +// OnStart implements service.Service by spawning requesters routine and recording +// pool's start time. +func (pool *BlockPool) OnStart() error { + pool.startTime = time.Now() + go pool.makeRequestersRoutine() + return nil +} + +// spawns requesters as needed +func (pool *BlockPool) makeRequestersRoutine() { + for { + if !pool.IsRunning() { + return + } + + // Check if we are within peerConnWait seconds of start time + // This gives us some time to connect to peers before starting a wave of requests + if time.Since(pool.startTime) < peerConnWait { + // Calculate the duration to sleep until peerConnWait seconds have passed since pool.startTime + sleepDuration := peerConnWait - time.Since(pool.startTime) + time.Sleep(sleepDuration) + } + + pool.mtx.Lock() + var ( + maxRequestersCreated = len(pool.requesters) >= len(pool.peers)*maxPendingRequestsPerPeer + + nextHeight = pool.height + int64(len(pool.requesters)) + maxPeerHeightReached = nextHeight > pool.maxPeerHeight + ) + pool.mtx.Unlock() + + switch { + case maxRequestersCreated: // If we have enough requesters, wait for them to finish. + time.Sleep(requestIntervalMS * time.Millisecond) + pool.removeTimedoutPeers() + case maxPeerHeightReached: // If we're caught up, wait for a bit so reactor could finish or a higher height is reported. + time.Sleep(requestIntervalMS * time.Millisecond) + default: + // request for more blocks. + pool.makeNextRequester(nextHeight) + // Sleep for a bit to make the requests more ordered. + time.Sleep(requestIntervalMS * time.Millisecond) + } + } +} + +func (pool *BlockPool) removeTimedoutPeers() { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + for _, peer := range pool.peers { + if !peer.didTimeout && peer.numPending > 0 { + curRate := peer.recvMonitor.Status().CurRate + // curRate can be 0 on start + if curRate != 0 && curRate < minRecvRate { + err := errors.New("peer is not sending us data fast enough") + pool.sendError(err, peer.id) + pool.Logger.Error("SendTimeout", "peer", peer.id, + "reason", err, + "curRate", fmt.Sprintf("%d KB/s", curRate/1024), + "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024)) + peer.didTimeout = true + } + + peer.curRate = curRate + } + + if peer.didTimeout { + pool.removePeer(peer.id) + } + } + + for peerID := range pool.bannedPeers { + if !pool.isPeerBanned(peerID) { + delete(pool.bannedPeers, peerID) + } + } + + pool.sortPeers() +} + +// GetStatus returns pool's height, numPending requests and the number of +// requesters. +func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters) +} + +// IsCaughtUp returns true if this node is caught up, false - otherwise. +// TODO: relax conditions, prevent abuse. +func (pool *BlockPool) IsCaughtUp() bool { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + // Need at least 1 peer to be considered caught up. + if len(pool.peers) == 0 { + pool.Logger.Debug("Blockpool has no peers") + return false + } + + // Some conditions to determine if we're caught up. + // Ensures we've either received a block or waited some amount of time, + // and that we're synced to the highest known height. + // Note we use maxPeerHeight - 1 because to sync block H requires block H+1 + // to verify the LastCommit. + receivedBlockOrTimedOut := pool.height > 0 || time.Since(pool.startTime) > 5*time.Second + ourChainIsLongestAmongPeers := pool.maxPeerHeight == 0 || pool.height >= (pool.maxPeerHeight-1) + isCaughtUp := receivedBlockOrTimedOut && ourChainIsLongestAmongPeers + return isCaughtUp +} + +// PeekTwoBlocks returns blocks at pool.height and pool.height+1. We need to +// see the second block's Commit to validate the first block. So we peek two +// blocks at a time. We return an extended commit, containing vote extensions +// and their associated signatures, as this is critical to consensus in ABCI++ +// as we switch from block sync to consensus mode. +// +// The caller will verify the commit. +func (pool *BlockPool) PeekTwoBlocks() (first, second *types.Block, firstExtCommit *types.ExtendedCommit) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + if r := pool.requesters[pool.height]; r != nil { + first = r.getBlock() + firstExtCommit = r.getExtendedCommit() + } + if r := pool.requesters[pool.height+1]; r != nil { + second = r.getBlock() + } + return +} + +// PopRequest removes the requester at pool.height and increments pool.height. +func (pool *BlockPool) PopRequest() { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + r := pool.requesters[pool.height] + if r == nil { + panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height)) + } + + if err := r.Stop(); err != nil { + pool.Logger.Error("Error stopping requester", "err", err) + } + delete(pool.requesters, pool.height) + pool.height++ + + // Notify the next minBlocksForSingleRequest requesters about new height, so + // they can potentially request a block from the second peer. + for i := int64(0); i < minBlocksForSingleRequest && i < int64(len(pool.requesters)); i++ { + pool.requesters[pool.height+i].newHeight(pool.height) + } +} + +// RemovePeerAndRedoAllPeerRequests retries the request at the given height and +// all the requests made to the same peer. The peer is removed from the pool. +// Returns the ID of the removed peer. +func (pool *BlockPool) RemovePeerAndRedoAllPeerRequests(height int64) p2p.ID { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + request := pool.requesters[height] + peerID := request.gotBlockFromPeerID() + // RemovePeer will redo all requesters associated with this peer. + pool.removePeer(peerID) + pool.banPeer(peerID) + return peerID +} + +// RedoRequestFrom retries the request at the given height. It does not remove the +// peer. +func (pool *BlockPool) RedoRequestFrom(height int64, peerID p2p.ID) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + if requester, ok := pool.requesters[height]; ok { // If we requested this block + if requester.didRequestFrom(peerID) { // From this specific peer + requester.redo(peerID) + } + } +} + +// Deprecated: use RemovePeerAndRedoAllPeerRequests instead. +func (pool *BlockPool) RedoRequest(height int64) p2p.ID { + return pool.RemovePeerAndRedoAllPeerRequests(height) +} + +// AddBlock validates that the block comes from the peer it was expected from +// and calls the requester to store it. +// +// This requires an extended commit at the same height as the supplied block - +// the block contains the last commit, but we need the latest commit in case we +// need to switch over from block sync to consensus at this height. If the +// height of the extended commit and the height of the block do not match, we +// do not add the block and return an error. +// TODO: ensure that blocks come in order for each peer. +func (pool *BlockPool) AddBlock(peerID p2p.ID, block *types.Block, extCommit *types.ExtendedCommit, blockSize int) error { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + if extCommit != nil && block.Height != extCommit.Height { + err := fmt.Errorf("block height %d != extCommit height %d", block.Height, extCommit.Height) + // Peer sent us an invalid block => remove it. + pool.sendError(err, peerID) + return err + } + + requester := pool.requesters[block.Height] + if requester == nil { + // Because we're issuing 2nd requests for closer blocks, it's possible to + // receive a block we've already processed from a second peer. Hence, we + // can't punish it. But if the peer sent us a block we clearly didn't + // request, we disconnect. + if block.Height > pool.height || block.Height < pool.startHeight { + err := fmt.Errorf("peer sent us block #%d we didn't expect (current height: %d, start height: %d)", + block.Height, pool.height, pool.startHeight) + pool.sendError(err, peerID) + return err + } + + return fmt.Errorf("got an already committed block #%d (possibly from the slow peer %s)", block.Height, peerID) + } + + if !requester.setBlock(block, extCommit, peerID) { + err := fmt.Errorf("requested block #%d from %v, not %s", block.Height, requester.requestedFrom(), peerID) + pool.sendError(err, peerID) + return err + } + + atomic.AddInt32(&pool.numPending, -1) + peer := pool.peers[peerID] + if peer != nil { + peer.decrPending(blockSize) + } + + return nil +} + +// Height returns the pool's height. +func (pool *BlockPool) Height() int64 { + pool.mtx.Lock() + defer pool.mtx.Unlock() + return pool.height +} + +// MaxPeerHeight returns the highest reported height. +func (pool *BlockPool) MaxPeerHeight() int64 { + pool.mtx.Lock() + defer pool.mtx.Unlock() + return pool.maxPeerHeight +} + +// SetPeerRange sets the peer's alleged blockchain base and height. +func (pool *BlockPool) SetPeerRange(peerID p2p.ID, base int64, height int64) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + peer := pool.peers[peerID] + if peer != nil { + if base < peer.base || height < peer.height { + pool.Logger.Info("Peer is reporting height/base that is lower than what it previously reported", + "peer", peerID, + "height", height, "base", base, + "prevHeight", peer.height, "prevBase", peer.base) + // RemovePeer will redo all requesters associated with this peer. + pool.removePeer(peerID) + pool.banPeer(peerID) + return + } + peer.base = base + peer.height = height + } else { + if pool.isPeerBanned(peerID) { + pool.Logger.Debug("Ignoring banned peer", "peer", peerID) + return + } + peer = newBPPeer(pool, peerID, base, height) + peer.setLogger(pool.Logger.With("peer", peerID)) + pool.peers[peerID] = peer + // no need to sort because curRate is 0 at start. + // just add to the beginning so it's picked first by pickIncrAvailablePeer. + pool.sortedPeers = append([]*bpPeer{peer}, pool.sortedPeers...) + } + + if height > pool.maxPeerHeight { + pool.maxPeerHeight = height + } +} + +// RemovePeer removes the peer with peerID from the pool. If there's no peer +// with peerID, function is a no-op. +func (pool *BlockPool) RemovePeer(peerID p2p.ID) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + pool.removePeer(peerID) +} + +// CONTRACT: pool.mtx must be locked. +func (pool *BlockPool) removePeer(peerID p2p.ID) { + for _, requester := range pool.requesters { + if requester.didRequestFrom(peerID) { + requester.redo(peerID) + } + } + + peer, ok := pool.peers[peerID] + if ok { + if peer.timeout != nil { + peer.timeout.Stop() + } + + delete(pool.peers, peerID) + for i, p := range pool.sortedPeers { + if p.id == peerID { + pool.sortedPeers = append(pool.sortedPeers[:i], pool.sortedPeers[i+1:]...) + break + } + } + + // Find a new peer with the biggest height and update maxPeerHeight if the + // peer's height was the biggest. + if peer.height == pool.maxPeerHeight { + pool.updateMaxPeerHeight() + } + } +} + +// If no peers are left, maxPeerHeight is set to 0. +func (pool *BlockPool) updateMaxPeerHeight() { + var max int64 + for _, peer := range pool.peers { + if peer.height > max { + max = peer.height + } + } + pool.maxPeerHeight = max +} + +// IsPeerBanned returns true if the peer is banned. +func (pool *BlockPool) IsPeerBanned(peerID p2p.ID) bool { + pool.mtx.Lock() + defer pool.mtx.Unlock() + return pool.isPeerBanned(peerID) +} + +// CONTRACT: pool.mtx must be locked. +func (pool *BlockPool) isPeerBanned(peerID p2p.ID) bool { + // Todo: replace with cmttime.Since in future versions + return time.Since(pool.bannedPeers[peerID]) < time.Second*60 +} + +// CONTRACT: pool.mtx must be locked. +func (pool *BlockPool) banPeer(peerID p2p.ID) { + pool.Logger.Debug("Banning peer", peerID) + pool.bannedPeers[peerID] = cmttime.Now() +} + +// Pick an available peer with the given height available. +// If no peers are available, returns nil. +func (pool *BlockPool) pickIncrAvailablePeer(height int64, excludePeerID p2p.ID) *bpPeer { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + for _, peer := range pool.sortedPeers { + if peer.id == excludePeerID { + continue + } + if peer.didTimeout { + pool.removePeer(peer.id) + continue + } + if peer.numPending >= maxPendingRequestsPerPeer { + continue + } + if height < peer.base || height > peer.height { + continue + } + peer.incrPending() + return peer + } + + return nil +} + +// Sort peers by curRate, highest first. +// +// CONTRACT: pool.mtx must be locked. +func (pool *BlockPool) sortPeers() { + sort.Slice(pool.sortedPeers, func(i, j int) bool { + return pool.sortedPeers[i].curRate > pool.sortedPeers[j].curRate + }) +} + +func (pool *BlockPool) makeNextRequester(nextHeight int64) { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + request := newBPRequester(pool, nextHeight) + + pool.requesters[nextHeight] = request + atomic.AddInt32(&pool.numPending, 1) + + if err := request.Start(); err != nil { + request.Logger.Error("Error starting request", "err", err) + } +} + +func (pool *BlockPool) sendRequest(height int64, peerID p2p.ID) { + if !pool.IsRunning() { + return + } + pool.requestsCh <- BlockRequest{height, peerID} +} + +func (pool *BlockPool) sendError(err error, peerID p2p.ID) { + if !pool.IsRunning() { + return + } + pool.errorsCh <- peerError{err, peerID} +} + +// for debugging purposes +// +//nolint:unused +func (pool *BlockPool) debug() string { + pool.mtx.Lock() + defer pool.mtx.Unlock() + + str := "" + nextHeight := pool.height + int64(len(pool.requesters)) + for h := pool.height; h < nextHeight; h++ { + if pool.requesters[h] == nil { + str += fmt.Sprintf("H(%v):X ", h) + } else { + str += fmt.Sprintf("H(%v):", h) + str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil) + str += fmt.Sprintf("C?(%v) ", pool.requesters[h].extCommit != nil) + } + } + return str +} + +//------------------------------------- + +type bpPeer struct { + didTimeout bool + curRate int64 + numPending int32 + height int64 + base int64 + pool *BlockPool + id p2p.ID + recvMonitor *flow.Monitor + + timeout *time.Timer + + logger log.Logger +} + +func newBPPeer(pool *BlockPool, peerID p2p.ID, base int64, height int64) *bpPeer { + peer := &bpPeer{ + pool: pool, + id: peerID, + base: base, + height: height, + numPending: 0, + logger: log.NewNopLogger(), + } + return peer +} + +func (peer *bpPeer) setLogger(l log.Logger) { + peer.logger = l +} + +func (peer *bpPeer) resetMonitor() { + peer.recvMonitor = flow.New(time.Second, time.Second*40) + initialValue := float64(minRecvRate) * math.E + peer.recvMonitor.SetREMA(initialValue) +} + +func (peer *bpPeer) resetTimeout() { + if peer.timeout == nil { + peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout) + } else { + peer.timeout.Reset(peerTimeout) + } +} + +func (peer *bpPeer) incrPending() { + if peer.numPending == 0 { + peer.resetMonitor() + peer.resetTimeout() + } + peer.numPending++ +} + +func (peer *bpPeer) decrPending(recvSize int) { + peer.numPending-- + if peer.numPending == 0 { + peer.timeout.Stop() + } else { + peer.recvMonitor.Update(recvSize) + peer.resetTimeout() + } +} + +func (peer *bpPeer) onTimeout() { + peer.pool.mtx.Lock() + defer peer.pool.mtx.Unlock() + + err := errors.New("peer did not send us anything") + peer.pool.sendError(err, peer.id) + peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout) + peer.didTimeout = true +} + +//------------------------------------- + +// bpRequester requests a block from a peer. +// +// If the height is within minBlocksForSingleRequest blocks of the pool's +// height, it will send an additional request to another peer. This is to avoid +// a situation where blocksync is stuck because of a single slow peer. Note +// that it's okay to send a single request when the requested height is far +// from the pool's height. If the peer is slow, it will timeout and be replaced +// with another peer. +type bpRequester struct { + service.BaseService + + pool *BlockPool + height int64 + gotBlockCh chan struct{} + redoCh chan p2p.ID // redo may got multiple messages, add peerId to identify repeat + newHeightCh chan int64 + + mtx cmtsync.Mutex + peerID p2p.ID + secondPeerID p2p.ID // alternative peer to request from (if close to pool's height) + gotBlockFrom p2p.ID + block *types.Block + extCommit *types.ExtendedCommit +} + +func newBPRequester(pool *BlockPool, height int64) *bpRequester { + bpr := &bpRequester{ + pool: pool, + height: height, + gotBlockCh: make(chan struct{}, 1), + redoCh: make(chan p2p.ID, 1), + newHeightCh: make(chan int64, 1), + + peerID: "", + secondPeerID: "", + block: nil, + } + bpr.BaseService = *service.NewBaseService(nil, "bpRequester", bpr) + return bpr +} + +func (bpr *bpRequester) OnStart() error { + go bpr.requestRoutine() + return nil +} + +// Returns true if the peer(s) match and block doesn't already exist. +func (bpr *bpRequester) setBlock(block *types.Block, extCommit *types.ExtendedCommit, peerID p2p.ID) bool { + bpr.mtx.Lock() + if bpr.peerID != peerID && bpr.secondPeerID != peerID { + bpr.mtx.Unlock() + return false + } + if bpr.block != nil { + bpr.mtx.Unlock() + return true // getting a block from both peers is not an error + } + + bpr.block = block + bpr.extCommit = extCommit + bpr.gotBlockFrom = peerID + bpr.mtx.Unlock() + + select { + case bpr.gotBlockCh <- struct{}{}: + default: + } + return true +} + +func (bpr *bpRequester) getBlock() *types.Block { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.block +} + +func (bpr *bpRequester) getExtendedCommit() *types.ExtendedCommit { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.extCommit +} + +// Returns the IDs of peers we've requested a block from. +func (bpr *bpRequester) requestedFrom() []p2p.ID { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + peerIDs := make([]p2p.ID, 0, 2) + if bpr.peerID != "" { + peerIDs = append(peerIDs, bpr.peerID) + } + if bpr.secondPeerID != "" { + peerIDs = append(peerIDs, bpr.secondPeerID) + } + return peerIDs +} + +// Returns true if we've requested a block from the given peer. +func (bpr *bpRequester) didRequestFrom(peerID p2p.ID) bool { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.peerID == peerID || bpr.secondPeerID == peerID +} + +// Returns the ID of the peer who sent us the block. +func (bpr *bpRequester) gotBlockFromPeerID() p2p.ID { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.gotBlockFrom +} + +// Removes the block (IF we got it from the given peer) and resets the peer. +func (bpr *bpRequester) reset(peerID p2p.ID) (removedBlock bool) { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + + // Only remove the block if we got it from that peer. + if bpr.gotBlockFrom == peerID { + bpr.block = nil + bpr.extCommit = nil + bpr.gotBlockFrom = "" + removedBlock = true + atomic.AddInt32(&bpr.pool.numPending, 1) + } + + if bpr.peerID == peerID { + bpr.peerID = "" + } else { + bpr.secondPeerID = "" + } + + return removedBlock +} + +// Tells bpRequester to pick another peer and try again. +// NOTE: Nonblocking, and does nothing if another redo +// was already requested. +func (bpr *bpRequester) redo(peerID p2p.ID) { + select { + case bpr.redoCh <- peerID: + default: + } +} + +func (bpr *bpRequester) pickPeerAndSendRequest() { + bpr.mtx.Lock() + secondPeerID := bpr.secondPeerID + bpr.mtx.Unlock() + + var peer *bpPeer +PICK_PEER_LOOP: + for { + if !bpr.IsRunning() || !bpr.pool.IsRunning() { + return + } + peer = bpr.pool.pickIncrAvailablePeer(bpr.height, secondPeerID) + if peer == nil { + bpr.Logger.Debug("No peers currently available; will retry shortly", "height", bpr.height) + time.Sleep(requestIntervalMS * time.Millisecond) + continue PICK_PEER_LOOP + } + break PICK_PEER_LOOP + } + bpr.mtx.Lock() + bpr.peerID = peer.id + bpr.mtx.Unlock() + + bpr.pool.sendRequest(bpr.height, peer.id) +} + +// Picks a second peer and sends a request to it. If the second peer is already +// set, does nothing. +func (bpr *bpRequester) pickSecondPeerAndSendRequest() (picked bool) { + bpr.mtx.Lock() + if bpr.secondPeerID != "" { + bpr.mtx.Unlock() + return false + } + peerID := bpr.peerID + bpr.mtx.Unlock() + + secondPeer := bpr.pool.pickIncrAvailablePeer(bpr.height, peerID) + if secondPeer != nil { + bpr.mtx.Lock() + bpr.secondPeerID = secondPeer.id + bpr.mtx.Unlock() + + bpr.pool.sendRequest(bpr.height, secondPeer.id) + return true + } + + return false +} + +// Informs the requester of a new pool's height. +func (bpr *bpRequester) newHeight(height int64) { + select { + case bpr.newHeightCh <- height: + default: + } +} + +// Responsible for making more requests as necessary +// Returns only when a block is found (e.g. AddBlock() is called) +func (bpr *bpRequester) requestRoutine() { + gotBlock := false + +OUTER_LOOP: + for { + bpr.pickPeerAndSendRequest() + + poolHeight := bpr.pool.Height() + if bpr.height-poolHeight < minBlocksForSingleRequest { + bpr.pickSecondPeerAndSendRequest() + } + + retryTimer := time.NewTimer(requestRetrySeconds * time.Second) + defer retryTimer.Stop() + + for { + select { + case <-bpr.pool.Quit(): + if err := bpr.Stop(); err != nil { + bpr.Logger.Error("Error stopped requester", "err", err) + } + return + case <-bpr.Quit(): + return + case <-retryTimer.C: + if !gotBlock { + bpr.Logger.Debug("Retrying block request(s) after timeout", "height", bpr.height, "peer", bpr.peerID, "secondPeerID", bpr.secondPeerID) + bpr.reset(bpr.peerID) + bpr.reset(bpr.secondPeerID) + continue OUTER_LOOP + } + case peerID := <-bpr.redoCh: + if bpr.didRequestFrom(peerID) { + removedBlock := bpr.reset(peerID) + if removedBlock { + gotBlock = false + } + } + // If both peers returned NoBlockResponse or bad block, reschedule both + // requests. If not, wait for the other peer. + if len(bpr.requestedFrom()) == 0 { + retryTimer.Stop() + continue OUTER_LOOP + } + case newHeight := <-bpr.newHeightCh: + if !gotBlock && bpr.height-newHeight < minBlocksForSingleRequest { + // The operation is a noop if the second peer is already set. The cost is checking a mutex. + // + // If the second peer was just set, reset the retryTimer to give the + // second peer a chance to respond. + if picked := bpr.pickSecondPeerAndSendRequest(); picked { + if !retryTimer.Stop() { + <-retryTimer.C + } + retryTimer.Reset(requestRetrySeconds * time.Second) + } + } + case <-bpr.gotBlockCh: + gotBlock = true + // We got a block! + // Continue the for-loop and wait til Quit. + } + } + } +} + +// BlockRequest stores a block request identified by the block Height and the PeerID responsible for +// delivering the block +type BlockRequest struct { + Height int64 + PeerID p2p.ID +} diff --git a/blocksync/pool_test.go b/blocksync/pool_test.go new file mode 100644 index 0000000..0573358 --- /dev/null +++ b/blocksync/pool_test.go @@ -0,0 +1,509 @@ +package blocksync + +import ( + "fmt" + "math" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/types" +) + +func init() { + peerTimeout = 2 * time.Second +} + +type testPeer struct { + id p2p.ID + base int64 + height int64 + inputChan chan inputData // make sure each peer's data is sequential + malicious bool +} + +type inputData struct { + t *testing.T + pool *BlockPool + request BlockRequest +} + +// Malicious nodes parameters +const MaliciousLie = 5 // This is how much the malicious node claims to be higher than the real height +const BlackholeSize = 3 // This is how many blocks the malicious node will not return (missing) above real height +const MaliciousTestMaximumLength = 5 * time.Minute + +func (p testPeer) runInputRoutine() { + go func() { + for input := range p.inputChan { + p.simulateInput(input) + } + }() +} + +// Request desired, pretend like we got the block immediately. +func (p testPeer) simulateInput(input inputData) { + block := &types.Block{Header: types.Header{Height: input.request.Height}, LastCommit: &types.Commit{}} // real blocks have LastCommit + extCommit := &types.ExtendedCommit{ + Height: input.request.Height, + } + // If this peer is malicious + if p.malicious { + realHeight := p.height - MaliciousLie + // And the requested height is above the real height + if input.request.Height > realHeight { + // Then provide a fake block + block.LastCommit = nil // Fake block, no LastCommit + // or provide no block at all, if we are close to the real height + if input.request.Height <= realHeight+BlackholeSize { + input.pool.RedoRequestFrom(input.request.Height, p.id) + return + } + } + } + err := input.pool.AddBlock(input.request.PeerID, block, extCommit, 123) + require.NoError(input.t, err) + // TODO: uncommenting this creates a race which is detected by: + // https://github.com/golang/go/blob/2bd767b1022dd3254bcec469f0ee164024726486/src/testing/testing.go#L854-L856 + // see: https://github.com/tendermint/tendermint/issues/3390#issue-418379890 + // input.t.Logf("Added block from peer %v (height: %v)", input.request.PeerID, input.request.Height) +} + +type testPeers map[p2p.ID]*testPeer + +func (ps testPeers) start() { + for _, v := range ps { + v.runInputRoutine() + } +} + +func (ps testPeers) stop() { + for _, v := range ps { + close(v.inputChan) + } +} + +func makePeers(numPeers int, minHeight, maxHeight int64) testPeers { + peers := make(testPeers, numPeers) + for i := 0; i < numPeers; i++ { + peerID := p2p.ID(cmtrand.Str(12)) + height := minHeight + cmtrand.Int63n(maxHeight-minHeight) + base := minHeight + int64(i) + if base > height { + base = height + } + peers[peerID] = &testPeer{peerID, base, height, make(chan inputData, 10), false} + } + return peers +} + +func TestBlockPoolBasic(t *testing.T) { + var ( + start = int64(42) + peers = makePeers(10, start, 1000) + errorsCh = make(chan peerError) + requestsCh = make(chan BlockRequest) + ) + pool := NewBlockPool(start, requestsCh, errorsCh) + pool.SetLogger(log.TestingLogger()) + + err := pool.Start() + if err != nil { + t.Error(err) + } + + t.Cleanup(func() { + if err := pool.Stop(); err != nil { + t.Error(err) + } + }) + + peers.start() + defer peers.stop() + + // Introduce each peer. + go func() { + for _, peer := range peers { + pool.SetPeerRange(peer.id, peer.base, peer.height) + } + }() + + // Start a goroutine to pull blocks + go func() { + for { + if !pool.IsRunning() { + return + } + first, second, _ := pool.PeekTwoBlocks() + if first != nil && second != nil { + pool.PopRequest() + } else { + time.Sleep(1 * time.Second) + } + } + }() + + // Pull from channels + for { + select { + case err := <-errorsCh: + t.Error(err) + case request := <-requestsCh: + t.Logf("Pulled new BlockRequest %v", request) + if request.Height == 300 { + return // Done! + } + + peers[request.PeerID].inputChan <- inputData{t, pool, request} + } + } +} + +func TestBlockPoolTimeout(t *testing.T) { + var ( + start = int64(42) + peers = makePeers(10, start, 1000) + errorsCh = make(chan peerError) + requestsCh = make(chan BlockRequest) + ) + + pool := NewBlockPool(start, requestsCh, errorsCh) + pool.SetLogger(log.TestingLogger()) + err := pool.Start() + if err != nil { + t.Error(err) + } + t.Cleanup(func() { + if err := pool.Stop(); err != nil { + t.Error(err) + } + }) + + for _, peer := range peers { + t.Logf("Peer %v", peer.id) + } + + // Introduce each peer. + go func() { + for _, peer := range peers { + pool.SetPeerRange(peer.id, peer.base, peer.height) + } + }() + + // Start a goroutine to pull blocks + go func() { + for { + if !pool.IsRunning() { + return + } + first, second, _ := pool.PeekTwoBlocks() + if first != nil && second != nil { + pool.PopRequest() + } else { + time.Sleep(1 * time.Second) + } + } + }() + + // Pull from channels + counter := 0 + timedOut := map[p2p.ID]struct{}{} + for { + select { + case err := <-errorsCh: + t.Log(err) + // consider error to be always timeout here + if _, ok := timedOut[err.peerID]; !ok { + counter++ + if counter == len(peers) { + return // Done! + } + } + case request := <-requestsCh: + t.Logf("Pulled new BlockRequest %+v", request) + } + } +} + +func TestBlockPoolRemovePeer(t *testing.T) { + peers := make(testPeers, 10) + for i := 0; i < 10; i++ { + peerID := p2p.ID(fmt.Sprintf("%d", i+1)) + height := int64(i + 1) + peers[peerID] = &testPeer{peerID, 0, height, make(chan inputData), false} + } + requestsCh := make(chan BlockRequest) + errorsCh := make(chan peerError) + + pool := NewBlockPool(1, requestsCh, errorsCh) + pool.SetLogger(log.TestingLogger()) + err := pool.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := pool.Stop(); err != nil { + t.Error(err) + } + }) + + // add peers + for peerID, peer := range peers { + pool.SetPeerRange(peerID, peer.base, peer.height) + } + assert.EqualValues(t, 10, pool.MaxPeerHeight()) + + // remove not-existing peer + assert.NotPanics(t, func() { pool.RemovePeer(p2p.ID("Superman")) }) + + // remove peer with biggest height + pool.RemovePeer(p2p.ID("10")) + assert.EqualValues(t, 9, pool.MaxPeerHeight()) + + // remove all peers + for peerID := range peers { + pool.RemovePeer(peerID) + } + + assert.EqualValues(t, 0, pool.MaxPeerHeight()) +} + +func TestBlockPoolMaliciousNode(t *testing.T) { + // Setup: + // * each peer has blocks 1..N but the malicious peer reports 1..N+5 (block N+1,N+2,N+3 missing, N+4,N+5 fake) + // * The malicious peer is ahead of the network but not by much, so it does not get dropped from the pool + // with a timeout error. (If a peer does not send blocks after 2 seconds, they are disconnected.) + // * The network creates new blocks every second. The malicious peer will also get ahead with another fake block. + // * The pool verifies blocks every half second. This ensures that the pool catches up with the network. + // * When the pool encounters a fake block sent by the malicious peer and has the previous block from a good peer, + // it can prove that the block is fake. The malicious peer gets banned, together with the sender of the previous (valid) block. + // Additional notes: + // * After a minute of ban, the malicious peer is unbanned. If the pool IsCaughtUp() by then and consensus started, + // there is no impact. If blocksync did not catch up yet, the malicious peer can continue its lie until the next ban. + // * The pool has an initial 3 seconds spin-up time before it starts verifying peers. (So peers have a chance to + // connect.) If the initial height is 7 and the block creation is 1/second, verification will start at height 10. + // * Testing with height 7, the main functionality of banning a malicious peer is tested. + // Testing with height 127, a malicious peer can reconnect and the subsequent banning is also tested. + // This takes a couple of minutes to complete, so we don't run it. + const InitialHeight = 7 + peers := testPeers{ + p2p.ID("good"): &testPeer{p2p.ID("good"), 1, InitialHeight, make(chan inputData), false}, + p2p.ID("bad"): &testPeer{p2p.ID("bad"), 1, InitialHeight + MaliciousLie, make(chan inputData), true}, + p2p.ID("good1"): &testPeer{p2p.ID("good1"), 1, InitialHeight, make(chan inputData), false}, + } + errorsCh := make(chan peerError) + requestsCh := make(chan BlockRequest) + + pool := NewBlockPool(1, requestsCh, errorsCh) + pool.SetLogger(log.TestingLogger()) + + err := pool.Start() + if err != nil { + t.Error(err) + } + + t.Cleanup(func() { + if err := pool.Stop(); err != nil { + t.Error(err) + } + }) + + peers.start() + t.Cleanup(func() { peers.stop() }) + + // Simulate blocks created on each peer regularly and update pool max height. + go func() { + // Introduce each peer + for _, peer := range peers { + pool.SetPeerRange(peer.id, peer.base, peer.height) + } + + ticker := time.NewTicker(1 * time.Second) // Speed of new block creation + defer ticker.Stop() + for { + select { + case <-pool.Quit(): + return + case <-ticker.C: + for _, peer := range peers { + peer.height++ // Network height increases on all peers + pool.SetPeerRange(peer.id, peer.base, peer.height) // Tell the pool that a new height is available + } + } + } + }() + + // Start a goroutine to verify blocks + go func() { + ticker := time.NewTicker(500 * time.Millisecond) // Speed of new block creation + defer ticker.Stop() + for { + select { + case <-pool.Quit(): + return + case <-ticker.C: + first, second, _ := pool.PeekTwoBlocks() + if first != nil && second != nil { + if second.LastCommit == nil { + // Second block is fake + pool.RemovePeerAndRedoAllPeerRequests(second.Height) + } else { + pool.PopRequest() + } + } + } + } + }() + + testTicker := time.NewTicker(200 * time.Millisecond) // speed of test execution + t.Cleanup(func() { testTicker.Stop() }) + + bannedOnce := false // true when the malicious peer was banned at least once + startTime := time.Now() + + // Pull from channels + for { + select { + case err := <-errorsCh: + t.Error(err) + case request := <-requestsCh: + // Process request + peers[request.PeerID].inputChan <- inputData{t, pool, request} + case <-testTicker.C: + banned := pool.IsPeerBanned("bad") + bannedOnce = bannedOnce || banned // Keep bannedOnce true, even if the malicious peer gets unbanned + caughtUp := pool.IsCaughtUp() + // Success: pool caught up and malicious peer was banned at least once + if caughtUp && bannedOnce { + t.Logf("Pool caught up, malicious peer was banned at least once, start consensus.") + return + } + // Failure: the pool caught up without banning the bad peer at least once + require.False(t, caughtUp, "Network caught up without banning the malicious peer at least once.") + // Failure: the network could not catch up in the allotted time + require.True(t, time.Since(startTime) < MaliciousTestMaximumLength, "Network ran too long, stopping test.") + } + } +} + +func TestBlockPoolMaliciousNodeMaxInt64(t *testing.T) { + // Setup: + // * each peer has blocks 1..N but the malicious peer reports 1..max(int64) (blocks N+1... do not exist) + // * The malicious peer then reports 1..N this time + // * Afterwards, it can choose to disconnect or stay connected to serve blocks that it has + // * The node ends up stuck in blocksync forever because max height is never reached (as of 63a2a6458) + // Additional notes: + // * When a peer is removed, we only update max height if it equals peer's + // height. The aforementioned scenario where peer reports its height twice + // lowering the height was not accounted for. + const initialHeight = 7 + peers := testPeers{ + p2p.ID("good"): &testPeer{p2p.ID("good"), 1, initialHeight, make(chan inputData), false}, + p2p.ID("bad"): &testPeer{p2p.ID("bad"), 1, math.MaxInt64, make(chan inputData), true}, + p2p.ID("good1"): &testPeer{p2p.ID("good1"), 1, initialHeight, make(chan inputData), false}, + } + errorsCh := make(chan peerError, 3) + requestsCh := make(chan BlockRequest) + + pool := NewBlockPool(1, requestsCh, errorsCh) + pool.SetLogger(log.TestingLogger()) + + err := pool.Start() + if err != nil { + t.Error(err) + } + + t.Cleanup(func() { + if err := pool.Stop(); err != nil { + t.Error(err) + } + }) + + peers.start() + t.Cleanup(func() { peers.stop() }) + + // Simulate blocks created on each peer regularly and update pool max height. + go func() { + // Introduce each peer + for _, peer := range peers { + pool.SetPeerRange(peer.id, peer.base, peer.height) + } + + // Report the lower height + peers["bad"].height = initialHeight + pool.SetPeerRange(p2p.ID("bad"), 1, initialHeight) + + ticker := time.NewTicker(1 * time.Second) // Speed of new block creation + defer ticker.Stop() + for { + select { + case <-pool.Quit(): + return + case <-ticker.C: + for _, peer := range peers { + peer.height++ // Network height increases on all peers + pool.SetPeerRange(peer.id, peer.base, peer.height) // Tell the pool that a new height is available + } + } + } + }() + + // Start a goroutine to verify blocks + go func() { + ticker := time.NewTicker(500 * time.Millisecond) // Speed of new block creation + defer ticker.Stop() + for { + select { + case <-pool.Quit(): + return + case <-ticker.C: + first, second, _ := pool.PeekTwoBlocks() + if first != nil && second != nil { + if second.LastCommit == nil { + // Second block is fake + pool.RemovePeerAndRedoAllPeerRequests(second.Height) + } else { + pool.PopRequest() + } + } + } + } + }() + + testTicker := time.NewTicker(200 * time.Millisecond) // speed of test execution + t.Cleanup(func() { testTicker.Stop() }) + + bannedOnce := false // true when the malicious peer was banned at least once + startTime := time.Now() + + // Pull from channels + for { + select { + case err := <-errorsCh: + if err.peerID == "bad" { // ignore errors from the malicious peer + t.Log(err) + } else { + t.Error(err) + } + case request := <-requestsCh: + // Process request + peers[request.PeerID].inputChan <- inputData{t, pool, request} + case <-testTicker.C: + banned := pool.IsPeerBanned("bad") + bannedOnce = bannedOnce || banned // Keep bannedOnce true, even if the malicious peer gets unbanned + caughtUp := pool.IsCaughtUp() + // Success: pool caught up and malicious peer was banned at least once + if caughtUp && bannedOnce { + t.Logf("Pool caught up, malicious peer was banned at least once, start consensus.") + return + } + // Failure: the pool caught up without banning the bad peer at least once + require.False(t, caughtUp, "Network caught up without banning the malicious peer at least once.") + // Failure: the network could not catch up in the allotted time + require.True(t, time.Since(startTime) < MaliciousTestMaximumLength, "Network ran too long, stopping test.") + } + } +} diff --git a/blocksync/reactor.go b/blocksync/reactor.go new file mode 100644 index 0000000..5c38fe3 --- /dev/null +++ b/blocksync/reactor.go @@ -0,0 +1,580 @@ +package blocksync + +import ( + "fmt" + "reflect" + "sync" + "time" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + bcproto "github.com/cometbft/cometbft/proto/tendermint/blocksync" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +const ( + // BlocksyncChannel is a channel for blocks and status updates (`BlockStore` height) + BlocksyncChannel = byte(0x40) + + trySyncIntervalMS = 10 + + // stop syncing when last block's time is + // within this much of the system time. + // stopSyncingDurationMinutes = 10 + + // ask for best height every 10s + statusUpdateIntervalSeconds = 10 + // check if we should switch to consensus reactor + switchToConsensusIntervalSeconds = 1 +) + +type consensusReactor interface { + // for when we switch from blocksync reactor and block sync to + // the consensus machine + SwitchToConsensus(state sm.State, skipWAL bool) +} + +type peerError struct { + err error + peerID p2p.ID +} + +func (e peerError) Error() string { + return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error()) +} + +// Reactor handles long-term catchup syncing. +type Reactor struct { + p2p.BaseReactor + + // immutable + initialState sm.State + + blockExec *sm.BlockExecutor + store sm.BlockStore + pool *BlockPool + blockSync bool + localAddr crypto.Address + poolRoutineWg sync.WaitGroup + + requestsCh <-chan BlockRequest + errorsCh <-chan peerError + + switchToConsensusMs int + + metrics *Metrics +} + +// NewReactor returns new reactor instance. +func NewReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, + blockSync bool, metrics *Metrics, offlineStateSyncHeight int64, +) *Reactor { + return NewReactorWithAddr(state, blockExec, store, blockSync, nil, metrics, offlineStateSyncHeight) +} + +// Function added to keep existing API. +func NewReactorWithAddr(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, + blockSync bool, localAddr crypto.Address, metrics *Metrics, offlineStateSyncHeight int64, +) *Reactor { + + storeHeight := store.Height() + if storeHeight == 0 { + // If state sync was performed offline and the stores were bootstrapped to height H + // the state store's lastHeight will be H while blockstore's Height and Base are still 0 + // 1. This scenario should not lead to a panic in this case, which is indicated by + // having a OfflineStateSyncHeight > 0 + // 2. We need to instruct the blocksync reactor to start fetching blocks from H+1 + // instead of 0. + storeHeight = offlineStateSyncHeight + } + if state.LastBlockHeight != storeHeight { + panic(fmt.Sprintf("state (%v) and store (%v) height mismatch, stores were left in an inconsistent state", state.LastBlockHeight, + storeHeight)) + } + + // It's okay to block since sendRequest is called from a separate goroutine + // (bpRequester#requestRoutine; 1 per each peer). + requestsCh := make(chan BlockRequest) + + const capacity = 1000 // must be bigger than peers count + errorsCh := make(chan peerError, capacity) // so we don't block in #Receive#pool.AddBlock + + startHeight := storeHeight + 1 + if startHeight == 1 { + startHeight = state.InitialHeight + } + pool := NewBlockPool(startHeight, requestsCh, errorsCh) + + bcR := &Reactor{ + initialState: state, + blockExec: blockExec, + store: store, + pool: pool, + blockSync: blockSync, + localAddr: localAddr, + requestsCh: requestsCh, + errorsCh: errorsCh, + metrics: metrics, + } + bcR.BaseReactor = *p2p.NewBaseReactor("Reactor", bcR) + return bcR +} + +// SetLogger implements service.Service by setting the logger on reactor and pool. +func (bcR *Reactor) SetLogger(l log.Logger) { + bcR.Logger = l + bcR.pool.Logger = l +} + +// OnStart implements service.Service. +func (bcR *Reactor) OnStart() error { + if bcR.blockSync { + err := bcR.pool.Start() + if err != nil { + return err + } + bcR.poolRoutineWg.Add(1) + go func() { + defer bcR.poolRoutineWg.Done() + bcR.poolRoutine(false) + }() + } + return nil +} + +// SwitchToBlockSync is called by the state sync reactor when switching to block sync. +func (bcR *Reactor) SwitchToBlockSync(state sm.State) error { + bcR.blockSync = true + bcR.initialState = state + + bcR.pool.height = state.LastBlockHeight + 1 + err := bcR.pool.Start() + if err != nil { + return err + } + bcR.poolRoutineWg.Add(1) + go func() { + defer bcR.poolRoutineWg.Done() + bcR.poolRoutine(true) + }() + return nil +} + +// OnStop implements service.Service. +func (bcR *Reactor) OnStop() { + if bcR.blockSync { + if err := bcR.pool.Stop(); err != nil { + bcR.Logger.Error("Error stopping pool", "err", err) + } + bcR.poolRoutineWg.Wait() + } +} + +// GetChannels implements Reactor +func (bcR *Reactor) GetChannels() []*p2p.ChannelDescriptor { + return []*p2p.ChannelDescriptor{ + { + ID: BlocksyncChannel, + Priority: 5, + SendQueueCapacity: 1000, + RecvBufferCapacity: 50 * 4096, + RecvMessageCapacity: MaxMsgSize, + MessageType: &bcproto.Message{}, + }, + } +} + +// AddPeer implements Reactor by sending our state to peer. +func (bcR *Reactor) AddPeer(peer p2p.Peer) { + peer.Send(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.StatusResponse{ + Base: bcR.store.Base(), + Height: bcR.store.Height(), + }, + }) + // it's OK if send fails. will try later in poolRoutine + + // peer is added to the pool once we receive the first + // bcStatusResponseMessage from the peer and call pool.SetPeerRange +} + +// RemovePeer implements Reactor by removing peer from the pool. +func (bcR *Reactor) RemovePeer(peer p2p.Peer, _ interface{}) { + bcR.pool.RemovePeer(peer.ID()) +} + +// respondToPeer loads a block and sends it to the requesting peer, +// if we have it. Otherwise, we'll respond saying we don't have it. +func (bcR *Reactor) respondToPeer(msg *bcproto.BlockRequest, src p2p.Peer) (queued bool) { + block := bcR.store.LoadBlock(msg.Height) + if block == nil { + bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height) + return src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.NoBlockResponse{Height: msg.Height}, + }) + } + + state, err := bcR.blockExec.Store().Load() + if err != nil { + bcR.Logger.Error("loading state", "err", err) + return false + } + var extCommit *types.ExtendedCommit + if state.ConsensusParams.ABCI.VoteExtensionsEnabled(msg.Height) { + extCommit = bcR.store.LoadBlockExtendedCommit(msg.Height) + if extCommit == nil { + bcR.Logger.Error("found block in store with no extended commit", "block", block) + return false + } + } + + bl, err := block.ToProto() + if err != nil { + bcR.Logger.Error("could not convert msg to protobuf", "err", err) + return false + } + + return src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.BlockResponse{ + Block: bl, + ExtCommit: extCommit.ToProto(), + }, + }) +} + +// Receive implements Reactor by handling 4 types of messages (look below). +func (bcR *Reactor) Receive(e p2p.Envelope) { //nolint: dupl // recreated in a test + if err := ValidateMsg(e.Message); err != nil { + bcR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", e.Message, "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + + bcR.Logger.Debug("Receive", "e.Src", e.Src, "chID", e.ChannelID, "msg", e.Message) + + switch msg := e.Message.(type) { + case *bcproto.BlockRequest: + bcR.respondToPeer(msg, e.Src) + case *bcproto.BlockResponse: + bi, err := types.BlockFromProto(msg.Block) + if err != nil { + bcR.Logger.Error("Peer sent us invalid block", "peer", e.Src, "msg", e.Message, "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + var extCommit *types.ExtendedCommit + if msg.ExtCommit != nil { + var err error + extCommit, err = types.ExtendedCommitFromProto(msg.ExtCommit) + if err != nil { + bcR.Logger.Error("failed to convert extended commit from proto", + "peer", e.Src, + "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + } + + if err := bcR.pool.AddBlock(e.Src.ID(), bi, extCommit, msg.Block.Size()); err != nil { + bcR.Logger.Error("failed to add block", "peer", e.Src, "err", err) + } + case *bcproto.StatusRequest: + // Send peer our state. + e.Src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.StatusResponse{ + Height: bcR.store.Height(), + Base: bcR.store.Base(), + }, + }) + case *bcproto.StatusResponse: + // Got a peer status. Unverified. + bcR.pool.SetPeerRange(e.Src.ID(), msg.Base, msg.Height) + case *bcproto.NoBlockResponse: + bcR.Logger.Debug("Peer does not have requested block", "peer", e.Src, "height", msg.Height) + bcR.pool.RedoRequestFrom(msg.Height, e.Src.ID()) + default: + bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } +} + +func (bcR *Reactor) localNodeBlocksTheChain(state sm.State) bool { + _, val := state.Validators.GetByAddress(bcR.localAddr) + if val == nil { + return false + } + total := state.Validators.TotalVotingPower() + return val.VotingPower >= total/3 +} + +// Handle messages from the poolReactor telling the reactor what to do. +// NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down! +func (bcR *Reactor) poolRoutine(stateSynced bool) { + bcR.metrics.Syncing.Set(1) + defer bcR.metrics.Syncing.Set(0) + + trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond) + defer trySyncTicker.Stop() + + statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second) + defer statusUpdateTicker.Stop() + + if bcR.switchToConsensusMs == 0 { + bcR.switchToConsensusMs = switchToConsensusIntervalSeconds * 1000 + } + switchToConsensusTicker := time.NewTicker(time.Duration(bcR.switchToConsensusMs) * time.Millisecond) + defer switchToConsensusTicker.Stop() + + blocksSynced := uint64(0) + + chainID := bcR.initialState.ChainID + state := bcR.initialState + + lastHundred := time.Now() + lastRate := 0.0 + + didProcessCh := make(chan struct{}, 1) + + initialCommitHasExtensions := (bcR.initialState.LastBlockHeight > 0 && bcR.store.LoadBlockExtendedCommit(bcR.initialState.LastBlockHeight) != nil) + + go func() { + for { + select { + case <-bcR.Quit(): + return + case <-bcR.pool.Quit(): + return + case request := <-bcR.requestsCh: + peer := bcR.Switch.Peers().Get(request.PeerID) + if peer == nil { + continue + } + queued := peer.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.BlockRequest{Height: request.Height}, + }) + if !queued { + bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height) + } + case err := <-bcR.errorsCh: + peer := bcR.Switch.Peers().Get(err.peerID) + if peer != nil { + bcR.Switch.StopPeerForError(peer, err) + } + + case <-statusUpdateTicker.C: + // ask for status updates + go bcR.BroadcastStatusRequest() + + } + } + }() + +FOR_LOOP: + for { + select { + case <-switchToConsensusTicker.C: + height, numPending, lenRequesters := bcR.pool.GetStatus() + outbound, inbound, _ := bcR.Switch.NumPeers() + bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters, + "outbound", outbound, "inbound", inbound, "lastHeight", state.LastBlockHeight) + + // The "if" statement below is a bit confusing, so here is a breakdown + // of its logic and purpose: + // + // If we are at genesis (no block in the chain), we don't need VoteExtensions + // because the first block's LastCommit is empty anyway. + // + // If VoteExtensions were disabled for the previous height then we don't need + // VoteExtensions. + // + // If we have sync'd at least one block, then we are guaranteed to have extensions + // if we need them by the logic inside loop FOR_LOOP: it requires that the blocks + // it fetches have extensions if extensions were enabled during the height. + // + // If we already had extensions for the initial height (e.g. we are recovering), + // then we are guaranteed to have extensions for the last block (if required) even + // if we did not blocksync any block. + // + missingExtension := true + if state.LastBlockHeight == 0 || + !state.ConsensusParams.ABCI.VoteExtensionsEnabled(state.LastBlockHeight) || + blocksSynced > 0 || + initialCommitHasExtensions { + missingExtension = false + } + + // If require extensions, but since we don't have them yet, then we cannot switch to consensus yet. + if missingExtension { + bcR.Logger.Info( + "no extended commit yet", + "height", height, + "last_block_height", state.LastBlockHeight, + "initial_height", state.InitialHeight, + "max_peer_height", bcR.pool.MaxPeerHeight(), + ) + continue FOR_LOOP + } + if bcR.pool.IsCaughtUp() || bcR.localNodeBlocksTheChain(state) { + bcR.Logger.Info("Time to switch to consensus reactor!", "height", height) + if err := bcR.pool.Stop(); err != nil { + bcR.Logger.Error("Error stopping pool", "err", err) + } + conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor) + if ok { + conR.SwitchToConsensus(state, blocksSynced > 0 || stateSynced) + } + // else { + // should only happen during testing + // } + + break FOR_LOOP + } + + case <-trySyncTicker.C: // chan time + select { + case didProcessCh <- struct{}{}: + default: + } + + case <-didProcessCh: + // NOTE: It is a subtle mistake to process more than a single block + // at a time (e.g. 10) here, because we only TrySend 1 request per + // loop. The ratio mismatch can result in starving of blocks, a + // sudden burst of requests and responses, and repeat. + // Consequently, it is better to split these routines rather than + // coupling them as it's written here. TODO uncouple from request + // routine. + + // See if there are any blocks to sync. + first, second, extCommit := bcR.pool.PeekTwoBlocks() + if first == nil || second == nil { + // we need to have fetched two consecutive blocks in order to + // perform blocksync verification + continue FOR_LOOP + } + // Some sanity checks on heights + if state.LastBlockHeight > 0 && state.LastBlockHeight+1 != first.Height { + // Panicking because the block pool's height MUST keep consistent with the state; the block pool is totally under our control + panic(fmt.Errorf("peeked first block has unexpected height; expected %d, got %d", state.LastBlockHeight+1, first.Height)) + } + if first.Height+1 != second.Height { + // Panicking because this is an obvious bug in the block pool, which is totally under our control + panic(fmt.Errorf("heights of first and second block are not consecutive; expected %d, got %d", state.LastBlockHeight, first.Height)) + } + + // Before priming didProcessCh for another check on the next + // iteration, break the loop if the BlockPool or the Reactor itself + // has quit. This avoids case ambiguity of the outer select when two + // channels are ready. + if !bcR.IsRunning() || !bcR.pool.IsRunning() { + break FOR_LOOP + } + // Try again quickly next loop. + didProcessCh <- struct{}{} + + firstParts, err := first.MakePartSet(types.BlockPartSizeBytes) + if err != nil { + bcR.Logger.Error("failed to make ", + "height", first.Height, + "err", err.Error()) + break FOR_LOOP + } + firstPartSetHeader := firstParts.Header() + firstID := types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader} + // Finally, verify the first block using the second's commit + // NOTE: we can probably make this more efficient, but note that calling + // first.Hash() doesn't verify the tx contents, so MakePartSet() is + // currently necessary. + // TODO(sergio): Should we also validate against the extended commit? + err = state.Validators.VerifyCommitLight( + chainID, firstID, first.Height, second.LastCommit) + + if err == nil { + // validate the block before we persist it + err = bcR.blockExec.ValidateBlock(state, first) + } + presentExtCommit := extCommit != nil + extensionsEnabled := state.ConsensusParams.ABCI.VoteExtensionsEnabled(first.Height) + if presentExtCommit != extensionsEnabled { + err = fmt.Errorf("non-nil extended commit must be received iff vote extensions are enabled for its height "+ + "(height %d, non-nil extended commit %t, extensions enabled %t)", + first.Height, presentExtCommit, extensionsEnabled, + ) + } + if err == nil && extensionsEnabled { + // if vote extensions were required at this height, ensure they exist. + err = extCommit.EnsureExtensions(true) + } + if err != nil { + bcR.Logger.Error("Error in validation", "err", err) + peerID := bcR.pool.RemovePeerAndRedoAllPeerRequests(first.Height) + peer := bcR.Switch.Peers().Get(peerID) + if peer != nil { + // NOTE: we've already removed the peer's request, but we + // still need to clean up the rest. + bcR.Switch.StopPeerForError(peer, ErrReactorValidation{Err: err}) + } + peerID2 := bcR.pool.RemovePeerAndRedoAllPeerRequests(second.Height) + peer2 := bcR.Switch.Peers().Get(peerID2) + if peer2 != nil && peer2 != peer { + // NOTE: we've already removed the peer's request, but we + // still need to clean up the rest. + bcR.Switch.StopPeerForError(peer2, ErrReactorValidation{Err: err}) + } + continue FOR_LOOP + } + + bcR.pool.PopRequest() + + // TODO: batch saves so we dont persist to disk every block + if extensionsEnabled { + bcR.store.SaveBlockWithExtendedCommit(first, firstParts, extCommit) + } else { + // We use LastCommit here instead of extCommit. extCommit is not + // guaranteed to be populated by the peer if extensions are not enabled. + // Currently, the peer should provide an extCommit even if the vote extension data are absent + // but this may change so using second.LastCommit is safer. + bcR.store.SaveBlock(first, firstParts, second.LastCommit) + } + + // TODO: same thing for app - but we would need a way to + // get the hash without persisting the state + state, err = bcR.blockExec.ApplyVerifiedBlock(state, firstID, first) + if err != nil { + // TODO This is bad, are we zombie? + panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err)) + } + bcR.metrics.recordBlockMetrics(first) + blocksSynced++ + + if blocksSynced%100 == 0 { + lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds()) + bcR.Logger.Info("Block Sync Rate", "height", bcR.pool.height, + "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate) + lastHundred = time.Now() + } + + continue FOR_LOOP + + case <-bcR.Quit(): + break FOR_LOOP + case <-bcR.pool.Quit(): + break FOR_LOOP + } + } +} + +// BroadcastStatusRequest broadcasts `BlockStore` base and height. +func (bcR *Reactor) BroadcastStatusRequest() { + bcR.Switch.Broadcast(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.StatusRequest{}, + }) +} diff --git a/blocksync/reactor_test.go b/blocksync/reactor_test.go new file mode 100644 index 0000000..9f0940b --- /dev/null +++ b/blocksync/reactor_test.go @@ -0,0 +1,573 @@ +package blocksync + +import ( + "fmt" + "os" + "reflect" + "sort" + "testing" + "time" + + bcproto "github.com/cometbft/cometbft/proto/tendermint/blocksync" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + mpmocks "github.com/cometbft/cometbft/mempool/mocks" + "github.com/cometbft/cometbft/p2p" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +var config *cfg.Config + +func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) { + validators := make([]types.GenesisValidator, numValidators) + privValidators := make([]types.PrivValidator, numValidators) + for i := 0; i < numValidators; i++ { + val, privVal := types.RandValidator(randPower, minPower) + validators[i] = types.GenesisValidator{ + PubKey: val.PubKey, + Power: val.VotingPower, + } + privValidators[i] = privVal + } + sort.Sort(types.PrivValidatorsByAddress(privValidators)) + + consPar := types.DefaultConsensusParams() + consPar.ABCI.VoteExtensionsEnableHeight = 1 + return &types.GenesisDoc{ + GenesisTime: cmttime.Now(), + ChainID: test.DefaultTestChainID, + Validators: validators, + ConsensusParams: consPar, + }, privValidators +} + +type ReactorPair struct { + reactor *ByzantineReactor + app proxy.AppConns +} + +func newReactor( + t *testing.T, + logger log.Logger, + genDoc *types.GenesisDoc, + privVals []types.PrivValidator, + maxBlockHeight int64, + incorrectData ...int64, +) ReactorPair { + if len(privVals) != 1 { + panic("only support one validator") + } + var incorrectBlock int64 = 0 + if len(incorrectData) > 0 { + incorrectBlock = incorrectData[0] + } + + app := abci.NewBaseApplication() + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + if err != nil { + panic(fmt.Errorf("error start app: %w", err)) + } + + blockDB := dbm.NewMemDB() + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + blockStore := store.NewBlockStore(blockDB) + + state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc) + if err != nil { + panic(fmt.Errorf("error constructing state from genesis file: %w", err)) + } + + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + // Make the Reactor itself. + // NOTE we have to create and commit the blocks first because + // pool.height is determined from the store. + blockSync := true + db := dbm.NewMemDB() + stateStore = sm.NewStore(db, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), + mp, sm.EmptyEvidencePool{}, blockStore) + if err = stateStore.Save(state); err != nil { + panic(err) + } + + // The commit we are building for the current height. + seenExtCommit := &types.ExtendedCommit{} + + pubKey, err := privVals[0].GetPubKey() + if err != nil { + panic(err) + } + addr := pubKey.Address() + idx, _ := state.Validators.GetByAddress(addr) + + // let's add some blocks in + for blockHeight := int64(1); blockHeight <= maxBlockHeight; blockHeight++ { + voteExtensionIsEnabled := genDoc.ConsensusParams.ABCI.VoteExtensionsEnabled(blockHeight) + + lastExtCommit := seenExtCommit.Clone() + + thisBlock, err := state.MakeBlock(blockHeight, nil, lastExtCommit.ToCommit(), nil, state.Validators.Proposer.Address) + require.NoError(t, err) + + thisParts, err := thisBlock.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + blockID := types.BlockID{Hash: thisBlock.Hash(), PartSetHeader: thisParts.Header()} + + // Simulate a commit for the current height + vote, err := types.MakeVote( + privVals[0], + thisBlock.ChainID, + idx, + thisBlock.Height, + 0, + cmtproto.PrecommitType, + blockID, + time.Now(), + ) + if err != nil { + panic(err) + } + seenExtCommit = &types.ExtendedCommit{ + Height: vote.Height, + Round: vote.Round, + BlockID: blockID, + ExtendedSignatures: []types.ExtendedCommitSig{vote.ExtendedCommitSig()}, + } + + state, err = blockExec.ApplyBlock(state, blockID, thisBlock) + if err != nil { + panic(fmt.Errorf("error apply block: %w", err)) + } + + saveCorrectVoteExtensions := blockHeight != incorrectBlock + if saveCorrectVoteExtensions == voteExtensionIsEnabled { + blockStore.SaveBlockWithExtendedCommit(thisBlock, thisParts, seenExtCommit) + } else { + blockStore.SaveBlock(thisBlock, thisParts, seenExtCommit.ToCommit()) + } + } + + bcReactor := NewByzantineReactor(incorrectBlock, NewReactor(state.Copy(), blockExec, blockStore, blockSync, NopMetrics(), 0)) + bcReactor.SetLogger(logger.With("module", "blocksync")) + + return ReactorPair{bcReactor, proxyApp} +} + +func TestNoBlockResponse(t *testing.T) { + config = test.ResetTestRoot("blocksync_reactor_test") + defer os.RemoveAll(config.RootDir) + genDoc, privVals := randGenesisDoc(1, false, 30) + + maxBlockHeight := int64(65) + + reactorPairs := make([]ReactorPair, 2) + + reactorPairs[0] = newReactor(t, log.TestingLogger(), genDoc, privVals, maxBlockHeight) + reactorPairs[1] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + + p2p.MakeConnectedSwitches(config.P2P, 2, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("BLOCKSYNC", reactorPairs[i].reactor) + return s + }, p2p.Connect2Switches) + + defer func() { + for _, r := range reactorPairs { + err := r.reactor.Stop() + require.NoError(t, err) + err = r.app.Stop() + require.NoError(t, err) + } + }() + + tests := []struct { + height int64 + existent bool + }{ + {maxBlockHeight + 2, false}, + {10, true}, + {1, true}, + {100, false}, + } + + for !reactorPairs[1].reactor.pool.IsCaughtUp() { + + time.Sleep(10 * time.Millisecond) + } + + assert.Equal(t, maxBlockHeight, reactorPairs[0].reactor.store.Height()) + + for _, tt := range tests { + block := reactorPairs[1].reactor.store.LoadBlock(tt.height) + if tt.existent { + assert.True(t, block != nil) + } else { + assert.True(t, block == nil) + } + } +} + +// NOTE: This is too hard to test without +// an easy way to add test peer to switch +// or without significant refactoring of the module. +// Alternatively we could actually dial a TCP conn but +// that seems extreme. +func TestBadBlockStopsPeer(t *testing.T) { + config = test.ResetTestRoot("blocksync_reactor_test") + defer os.RemoveAll(config.RootDir) + genDoc, privVals := randGenesisDoc(1, false, 30) + + maxBlockHeight := int64(148) + + // Other chain needs a different validator set + otherGenDoc, otherPrivVals := randGenesisDoc(1, false, 30) + otherChain := newReactor(t, log.TestingLogger(), otherGenDoc, otherPrivVals, maxBlockHeight) + + defer func() { + err := otherChain.reactor.Stop() + require.Error(t, err) + err = otherChain.app.Stop() + require.NoError(t, err) + }() + + reactorPairs := make([]ReactorPair, 4) + + reactorPairs[0] = newReactor(t, log.TestingLogger(), genDoc, privVals, maxBlockHeight) + reactorPairs[1] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + reactorPairs[2] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + reactorPairs[3] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + + switches := p2p.MakeConnectedSwitches(config.P2P, 4, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("BLOCKSYNC", reactorPairs[i].reactor) + return s + }, p2p.Connect2Switches) + + defer func() { + for _, r := range reactorPairs { + err := r.reactor.Stop() + require.NoError(t, err) + + err = r.app.Stop() + require.NoError(t, err) + } + }() + + for { + time.Sleep(1 * time.Second) + caughtUp := true + for _, r := range reactorPairs { + if !r.reactor.pool.IsCaughtUp() { + caughtUp = false + } + } + if caughtUp { + break + } + } + + // at this time, reactors[0-3] is the newest + assert.Equal(t, 3, reactorPairs[1].reactor.Switch.Peers().Size()) + + // Mark reactorPairs[3] as an invalid peer. Fiddling with .store without a mutex is a data + // race, but can't be easily avoided. + reactorPairs[3].reactor.store = otherChain.reactor.store + + lastReactorPair := newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + reactorPairs = append(reactorPairs, lastReactorPair) + + switches = append(switches, p2p.MakeConnectedSwitches(config.P2P, 1, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("BLOCKSYNC", reactorPairs[len(reactorPairs)-1].reactor) + return s + }, p2p.Connect2Switches)...) + + for i := 0; i < len(reactorPairs)-1; i++ { + p2p.Connect2Switches(switches, i, len(reactorPairs)-1) + } + + for !lastReactorPair.reactor.pool.IsCaughtUp() && lastReactorPair.reactor.Switch.Peers().Size() != 0 { + + time.Sleep(1 * time.Second) + } + + assert.True(t, lastReactorPair.reactor.Switch.Peers().Size() < len(reactorPairs)-1) +} + +func TestCheckSwitchToConsensusLastHeightZero(t *testing.T) { + const maxBlockHeight = int64(45) + + config = test.ResetTestRoot("blocksync_reactor_test") + defer os.RemoveAll(config.RootDir) + genDoc, privVals := randGenesisDoc(1, false, 30) + + reactorPairs := make([]ReactorPair, 1, 2) + reactorPairs[0] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + reactorPairs[0].reactor.switchToConsensusMs = 50 + defer func() { + for _, r := range reactorPairs { + err := r.reactor.Stop() + require.NoError(t, err) + err = r.app.Stop() + require.NoError(t, err) + } + }() + + reactorPairs = append(reactorPairs, newReactor(t, log.TestingLogger(), genDoc, privVals, maxBlockHeight)) + + var switches []*p2p.Switch + for _, r := range reactorPairs { + switches = append(switches, p2p.MakeConnectedSwitches(config.P2P, 1, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("BLOCKSYNC", r.reactor) + return s + }, p2p.Connect2Switches)...) + } + + time.Sleep(60 * time.Millisecond) + + // Connect both switches + p2p.Connect2Switches(switches, 0, 1) + + startTime := time.Now() + for { + time.Sleep(20 * time.Millisecond) + caughtUp := true + for _, r := range reactorPairs { + if !r.reactor.pool.IsCaughtUp() { + caughtUp = false + break + } + } + if caughtUp { + break + } + if time.Since(startTime) > 90*time.Second { + msg := "timeout: reactors didn't catch up;" + for i, r := range reactorPairs { + h, p, lr := r.reactor.pool.GetStatus() + c := r.reactor.pool.IsCaughtUp() + msg += fmt.Sprintf(" reactor#%d (h %d, p %d, lr %d, c %t);", i, h, p, lr, c) + } + require.Fail(t, msg) + } + } + + // -1 because of "-1" in IsCaughtUp + // -1 pool.height points to the _next_ height + // -1 because we measure height of block store + const maxDiff = 3 + for _, r := range reactorPairs { + assert.GreaterOrEqual(t, r.reactor.store.Height(), maxBlockHeight-maxDiff) + } +} + +func ExtendedCommitNetworkHelper(t *testing.T, maxBlockHeight int64, enableVoteExtensionAt int64, invalidBlockHeightAt int64) { + config = test.ResetTestRoot("blocksync_reactor_test") + defer os.RemoveAll(config.RootDir) + genDoc, privVals := randGenesisDoc(1, false, 30) + genDoc.ConsensusParams.ABCI.VoteExtensionsEnableHeight = enableVoteExtensionAt + + reactorPairs := make([]ReactorPair, 1, 2) + reactorPairs[0] = newReactor(t, log.TestingLogger(), genDoc, privVals, 0) + reactorPairs[0].reactor.switchToConsensusMs = 50 + defer func() { + for _, r := range reactorPairs { + err := r.reactor.Stop() + require.NoError(t, err) + err = r.app.Stop() + require.NoError(t, err) + } + }() + + reactorPairs = append(reactorPairs, newReactor(t, log.TestingLogger(), genDoc, privVals, maxBlockHeight, invalidBlockHeightAt)) + + var switches []*p2p.Switch + for _, r := range reactorPairs { + switches = append(switches, p2p.MakeConnectedSwitches(config.P2P, 1, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("BLOCKSYNC", r.reactor) + return s + }, p2p.Connect2Switches)...) + } + + time.Sleep(60 * time.Millisecond) + + // Connect both switches + p2p.Connect2Switches(switches, 0, 1) + + startTime := time.Now() + for { + time.Sleep(20 * time.Millisecond) + // The reactor can never catch up, because at one point it disconnects. + require.False(t, reactorPairs[0].reactor.pool.IsCaughtUp(), "node caught up when it should not have") + // After 5 seconds, the test should have executed. + if time.Since(startTime) > 5*time.Second { + assert.Equal(t, 0, reactorPairs[0].reactor.Switch.Peers().Size(), "node should have disconnected but didn't") + assert.Equal(t, 0, reactorPairs[1].reactor.Switch.Peers().Size(), "node should have disconnected but didn't") + break + } + } +} + +// TestCheckExtendedCommitExtra tests when VoteExtension is disabled but an ExtendedVote is present in the block. +func TestCheckExtendedCommitExtra(t *testing.T) { + const maxBlockHeight = 10 + const enableVoteExtension = 5 + const invalidBlockHeight = 3 + + ExtendedCommitNetworkHelper(t, maxBlockHeight, enableVoteExtension, invalidBlockHeight) +} + +// TestCheckExtendedCommitMissing tests when VoteExtension is enabled but the ExtendedVote is missing from the block. +func TestCheckExtendedCommitMissing(t *testing.T) { + const maxBlockHeight = 10 + const enableVoteExtension = 5 + const invalidBlockHeight = 8 + + ExtendedCommitNetworkHelper(t, maxBlockHeight, enableVoteExtension, invalidBlockHeight) +} + +// ByzantineReactor is a blockstore reactor implementation where a corrupted block can be sent to a peer. +// The corruption is that the block contains extended commit signatures when vote extensions are disabled or +// it has no extended commit signatures while vote extensions are enabled. +// If the corrupted block height is set to 0, the reactor behaves as normal. +type ByzantineReactor struct { + *Reactor + corruptedBlock int64 +} + +func NewByzantineReactor(invalidBlock int64, conR *Reactor) *ByzantineReactor { + return &ByzantineReactor{ + Reactor: conR, + corruptedBlock: invalidBlock, + } +} + +// respondToPeer (overridden method) loads a block and sends it to the requesting peer, +// if we have it. Otherwise, we'll respond saying we don't have it. +// Byzantine modification: if corruptedBlock is set, send the wrong Block. +func (bcR *ByzantineReactor) respondToPeer(msg *bcproto.BlockRequest, src p2p.Peer) (queued bool) { + block := bcR.store.LoadBlock(msg.Height) + if block == nil { + bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height) + return src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.NoBlockResponse{Height: msg.Height}, + }) + } + + state, err := bcR.blockExec.Store().Load() + if err != nil { + bcR.Logger.Error("loading state", "err", err) + return false + } + var extCommit *types.ExtendedCommit + voteExtensionEnabled := state.ConsensusParams.ABCI.VoteExtensionsEnabled(msg.Height) + incorrectBlock := bcR.corruptedBlock == msg.Height + if voteExtensionEnabled && !incorrectBlock || !voteExtensionEnabled && incorrectBlock { + extCommit = bcR.store.LoadBlockExtendedCommit(msg.Height) + if extCommit == nil { + bcR.Logger.Error("found block in store with no extended commit", "block", block) + return false + } + } + + bl, err := block.ToProto() + if err != nil { + bcR.Logger.Error("could not convert msg to protobuf", "err", err) + return false + } + + return src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.BlockResponse{ + Block: bl, + ExtCommit: extCommit.ToProto(), + }, + }) +} + +// Receive implements Reactor by handling 4 types of messages (look below). +// Copied unchanged from reactor.go so the correct respondToPeer is called. +func (bcR *ByzantineReactor) Receive(e p2p.Envelope) { //nolint: dupl + if err := ValidateMsg(e.Message); err != nil { + bcR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", e.Message, "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + + bcR.Logger.Debug("Receive", "e.Src", e.Src, "chID", e.ChannelID, "msg", e.Message) + + switch msg := e.Message.(type) { + case *bcproto.BlockRequest: + bcR.respondToPeer(msg, e.Src) + case *bcproto.BlockResponse: + bi, err := types.BlockFromProto(msg.Block) + if err != nil { + bcR.Logger.Error("Peer sent us invalid block", "peer", e.Src, "msg", e.Message, "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + var extCommit *types.ExtendedCommit + if msg.ExtCommit != nil { + var err error + extCommit, err = types.ExtendedCommitFromProto(msg.ExtCommit) + if err != nil { + bcR.Logger.Error("failed to convert extended commit from proto", + "peer", e.Src, + "err", err) + bcR.Switch.StopPeerForError(e.Src, err) + return + } + } + + if err := bcR.pool.AddBlock(e.Src.ID(), bi, extCommit, msg.Block.Size()); err != nil { + bcR.Logger.Error("failed to add block", "peer", e.Src, "err", err) + } + case *bcproto.StatusRequest: + // Send peer our state. + e.Src.TrySend(p2p.Envelope{ + ChannelID: BlocksyncChannel, + Message: &bcproto.StatusResponse{ + Height: bcR.store.Height(), + Base: bcR.store.Base(), + }, + }) + case *bcproto.StatusResponse: + // Got a peer status. Unverified. + bcR.pool.SetPeerRange(e.Src.ID(), msg.Base, msg.Height) + case *bcproto.NoBlockResponse: + bcR.Logger.Debug("Peer does not have requested block", "peer", e.Src, "height", msg.Height) + bcR.pool.RedoRequestFrom(msg.Height, e.Src.ID()) + default: + bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } +} diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..7390d1f --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,9 @@ +version: v1 +plugins: + - name: gogofaster + out: ./proto/ + opt: + - Mgoogle/protobuf/timestamp.proto=github.com/cosmos/gogoproto/types + - Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration + - plugins=grpc + - paths=source_relative diff --git a/buf.work.yaml b/buf.work.yaml new file mode 100644 index 0000000..a1a240d --- /dev/null +++ b/buf.work.yaml @@ -0,0 +1,3 @@ +version: v1 +directories: + - proto diff --git a/cmd/cometbft/commands/compact.go b/cmd/cometbft/commands/compact.go new file mode 100644 index 0000000..db6b52c --- /dev/null +++ b/cmd/cometbft/commands/compact.go @@ -0,0 +1,67 @@ +package commands + +import ( + "errors" + "path/filepath" + "sync" + + "github.com/spf13/cobra" + "github.com/syndtr/goleveldb/leveldb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" + + "github.com/cometbft/cometbft/libs/log" +) + +var CompactGoLevelDBCmd = &cobra.Command{ + Use: "experimental-compact-goleveldb", + Aliases: []string{"experimental_compact_goleveldb"}, + Short: "force compacts the CometBFT storage engine (only GoLevelDB supported)", + Long: ` +This is a temporary utility command that performs a force compaction on the state +and blockstores to reduce disk space for a pruning node. This should only be run +once the node has stopped. This command will likely be omitted in the future after +the planned refactor to the storage engine. + +Currently, only GoLevelDB is supported. + `, + RunE: func(cmd *cobra.Command, args []string) error { + if config.DBBackend != "goleveldb" { + return errors.New("compaction is currently only supported with goleveldb") + } + + compactGoLevelDBs(config.RootDir, logger) + return nil + }, +} + +func compactGoLevelDBs(rootDir string, logger log.Logger) { + dbNames := []string{"state", "blockstore"} + o := &opt.Options{ + DisableSeeksCompaction: true, + } + wg := sync.WaitGroup{} + + for _, dbName := range dbNames { + dbName := dbName + wg.Add(1) + go func() { + defer wg.Done() + dbPath := filepath.Join(rootDir, "data", dbName+".db") + store, err := leveldb.OpenFile(dbPath, o) + if err != nil { + logger.Error("failed to initialize cometbft db", "path", dbPath, "err", err) + return + } + defer store.Close() + + logger.Info("starting compaction...", "db", dbPath) + + err = store.CompactRange(util.Range{Start: nil, Limit: nil}) + if err != nil { + logger.Error("failed to compact cometbft db", "path", dbPath, "err", err) + } + }() + } + wg.Wait() +} diff --git a/cmd/cometbft/commands/debug/debug.go b/cmd/cometbft/commands/debug/debug.go new file mode 100644 index 0000000..fad1997 --- /dev/null +++ b/cmd/cometbft/commands/debug/debug.go @@ -0,0 +1,41 @@ +package debug + +import ( + "os" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/libs/log" +) + +var ( + nodeRPCAddr string + profAddr string + frequency uint + + flagNodeRPCAddr = "rpc-laddr" + flagProfAddr = "pprof-laddr" + flagFrequency = "frequency" + + logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) +) + +// DebugCmd defines the root command containing subcommands that assist in +// debugging running CometBFT processes. +var DebugCmd = &cobra.Command{ + Use: "debug", + Short: "A utility to kill or watch a CometBFT process while aggregating debugging data", +} + +func init() { + DebugCmd.PersistentFlags().SortFlags = true + DebugCmd.PersistentFlags().StringVar( + &nodeRPCAddr, + flagNodeRPCAddr, + "tcp://localhost:26657", + "the CometBFT node's RPC address (:)", + ) + + DebugCmd.AddCommand(killCmd) + DebugCmd.AddCommand(dumpCmd) +} diff --git a/cmd/cometbft/commands/debug/dump.go b/cmd/cometbft/commands/debug/dump.go new file mode 100644 index 0000000..3dd0a68 --- /dev/null +++ b/cmd/cometbft/commands/debug/dump.go @@ -0,0 +1,133 @@ +package debug + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cli" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" +) + +var dumpCmd = &cobra.Command{ + Use: "dump [output-directory]", + Short: "Continuously poll a CometBFT process and dump debugging data into a single location", + Long: `Continuously poll a CometBFT process and dump debugging data into a single +location at a specified frequency. At each frequency interval, an archived and compressed +file will contain node debugging information including the goroutine and heap profiles +if enabled.`, + Args: cobra.ExactArgs(1), + RunE: dumpCmdHandler, +} + +func init() { + dumpCmd.Flags().UintVar( + &frequency, + flagFrequency, + 30, + "the frequency (seconds) in which to poll, aggregate and dump CometBFT debug data", + ) + + dumpCmd.Flags().StringVar( + &profAddr, + flagProfAddr, + "", + "the profiling server address (:)", + ) +} + +func dumpCmdHandler(_ *cobra.Command, args []string) error { + outDir := args[0] + if outDir == "" { + return errors.New("invalid output directory") + } + + if frequency == 0 { + return errors.New("frequency must be positive") + } + + if _, err := os.Stat(outDir); os.IsNotExist(err) { + if err := os.Mkdir(outDir, os.ModePerm); err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } + } + + rpc, err := rpchttp.New(nodeRPCAddr, "/websocket") + if err != nil { + return fmt.Errorf("failed to create new http client: %w", err) + } + + home := viper.GetString(cli.HomeFlag) + conf := cfg.DefaultConfig() + conf = conf.SetRoot(home) + cfg.EnsureRoot(conf.RootDir) + + dumpDebugData(outDir, conf, rpc) + + ticker := time.NewTicker(time.Duration(frequency) * time.Second) + for range ticker.C { + dumpDebugData(outDir, conf, rpc) + } + + return nil +} + +func dumpDebugData(outDir string, conf *cfg.Config, rpc *rpchttp.HTTP) { + start := time.Now().UTC() + + tmpDir, err := os.MkdirTemp(outDir, "cometbft_debug_tmp") + if err != nil { + logger.Error("failed to create temporary directory", "dir", tmpDir, "error", err) + return + } + defer os.RemoveAll(tmpDir) + + logger.Info("getting node status...") + if err := dumpStatus(rpc, tmpDir, "status.json"); err != nil { + logger.Error("failed to dump node status", "error", err) + return + } + + logger.Info("getting node network info...") + if err := dumpNetInfo(rpc, tmpDir, "net_info.json"); err != nil { + logger.Error("failed to dump node network info", "error", err) + return + } + + logger.Info("getting node consensus state...") + if err := dumpConsensusState(rpc, tmpDir, "consensus_state.json"); err != nil { + logger.Error("failed to dump node consensus state", "error", err) + return + } + + logger.Info("copying node WAL...") + if err := copyWAL(conf, tmpDir); err != nil { + logger.Error("failed to copy node WAL", "error", err) + return + } + + if profAddr != "" { + logger.Info("getting node goroutine profile...") + if err := dumpProfile(tmpDir, profAddr, "goroutine", 2); err != nil { + logger.Error("failed to dump goroutine profile", "error", err) + return + } + + logger.Info("getting node heap profile...") + if err := dumpProfile(tmpDir, profAddr, "heap", 2); err != nil { + logger.Error("failed to dump heap profile", "error", err) + return + } + } + + outFile := filepath.Join(outDir, fmt.Sprintf("%s.zip", start.Format(time.RFC3339))) + if err := zipDir(tmpDir, outFile); err != nil { + logger.Error("failed to create and compress archive", "file", outFile, "error", err) + } +} diff --git a/cmd/cometbft/commands/debug/io.go b/cmd/cometbft/commands/debug/io.go new file mode 100644 index 0000000..f344943 --- /dev/null +++ b/cmd/cometbft/commands/debug/io.go @@ -0,0 +1,114 @@ +package debug + +import ( + "archive/zip" + "encoding/json" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" +) + +// zipDir zips all the contents found in src, including both files and +// directories, into a destination file dest. It returns an error upon failure. +// It assumes src is a directory. +func zipDir(src, dest string) error { + zipFile, err := os.Create(dest) + if err != nil { + return err + } + defer zipFile.Close() + + zipWriter := zip.NewWriter(zipFile) + defer zipWriter.Close() + + dirName := filepath.Base(dest) + baseDir := strings.TrimSuffix(dirName, filepath.Ext(dirName)) + + return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + header, err := zip.FileInfoHeader(info) + if err != nil { + return err + } + + // Each execution of this utility on a CometBFT process will result in a + // unique file. + header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, src)) + + // Handle cases where the content to be zipped is a file or a directory, + // where a directory must have a '/' suffix. + if info.IsDir() { + header.Name += "/" + } else { + header.Method = zip.Deflate + } + + headerWriter, err := zipWriter.CreateHeader(header) + if err != nil { + return err + } + + if info.IsDir() { + return nil + } + + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + _, err = io.Copy(headerWriter, file) + return err + }) + +} + +// copyFile copies a file from src to dest and returns an error upon failure. The +// copied file retains the source file's permissions. +func copyFile(src, dest string) error { + if _, err := os.Stat(src); os.IsNotExist(err) { + return err + } + + srcFile, err := os.Open(src) + if err != nil { + return err + } + defer srcFile.Close() + + destFile, err := os.Create(dest) + if err != nil { + return err + } + defer destFile.Close() + + if _, err = io.Copy(destFile, srcFile); err != nil { + return err + } + + srcInfo, err := os.Stat(src) + if err != nil { + return err + } + + return os.Chmod(dest, srcInfo.Mode()) +} + +// writeStateToFile pretty JSON encodes an object and writes it to file composed +// of dir and filename. It returns an error upon failure to encode or write to +// file. +func writeStateJSONToFile(state interface{}, dir, filename string) error { + stateJSON, err := json.MarshalIndent(state, "", " ") + if err != nil { + return fmt.Errorf("failed to encode state dump: %w", err) + } + + return os.WriteFile(path.Join(dir, filename), stateJSON, 0o600) +} diff --git a/cmd/cometbft/commands/debug/kill.go b/cmd/cometbft/commands/debug/kill.go new file mode 100644 index 0000000..50370cc --- /dev/null +++ b/cmd/cometbft/commands/debug/kill.go @@ -0,0 +1,152 @@ +package debug + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "syscall" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cli" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" +) + +var killCmd = &cobra.Command{ + Use: "kill [pid] [compressed-output-file]", + Short: "Kill a CometBFT process while aggregating and packaging debugging data", + Long: `Kill a CometBFT process while also aggregating CometBFT process data +such as the latest node state, including consensus and networking state, +go-routine state, and the node's WAL and config information. This aggregated data +is packaged into a compressed archive. + +Example: +$ cometbft debug 34255 /path/to/cmt-debug.zip`, + Args: cobra.ExactArgs(2), + RunE: killCmdHandler, +} + +func killCmdHandler(_ *cobra.Command, args []string) error { + pid, err := strconv.Atoi(args[0]) + if err != nil { + return err + } + + outFile := args[1] + if outFile == "" { + return errors.New("invalid output file") + } + + rpc, err := rpchttp.New(nodeRPCAddr, "/websocket") + if err != nil { + return fmt.Errorf("failed to create new http client: %w", err) + } + + home := viper.GetString(cli.HomeFlag) + conf := cfg.DefaultConfig() + conf = conf.SetRoot(home) + cfg.EnsureRoot(conf.RootDir) + + // Create a temporary directory which will contain all the state dumps and + // relevant files and directories that will be compressed into a file. + tmpDir, err := os.MkdirTemp(os.TempDir(), "cometbft_debug_tmp") + if err != nil { + return fmt.Errorf("failed to create temporary directory: %w", err) + } + defer os.RemoveAll(tmpDir) + + logger.Info("getting node status...") + if err := dumpStatus(rpc, tmpDir, "status.json"); err != nil { + return err + } + + logger.Info("getting node network info...") + if err := dumpNetInfo(rpc, tmpDir, "net_info.json"); err != nil { + return err + } + + logger.Info("getting node consensus state...") + if err := dumpConsensusState(rpc, tmpDir, "consensus_state.json"); err != nil { + return err + } + + logger.Info("copying node WAL...") + if err := copyWAL(conf, tmpDir); err != nil { + return err + } + + logger.Info("copying node configuration...") + if err := copyConfig(home, tmpDir); err != nil { + return err + } + + logger.Info("killing CometBFT process") + if err := killProc(pid, tmpDir); err != nil { + return err + } + + logger.Info("archiving and compressing debug directory...") + return zipDir(tmpDir, outFile) +} + +// killProc attempts to kill the CometBFT process with a given PID with an +// ABORT signal which should result in a goroutine stacktrace. The PID's STDERR +// is tailed and piped to a file under the directory dir. An error is returned +// if the output file cannot be created or the tail command cannot be started. +// An error is not returned if any subsequent syscall fails. +func killProc(pid int, dir string) error { + // pipe STDERR output from tailing the CometBFT process to a file + // + // NOTE: This will only work on UNIX systems. + cmd := exec.Command("tail", "-f", fmt.Sprintf("/proc/%d/fd/2", pid)) //nolint: gosec + + outFile, err := os.Create(filepath.Join(dir, "stacktrace.out")) + if err != nil { + return err + } + defer outFile.Close() + + cmd.Stdout = outFile + cmd.Stderr = outFile + + if err := cmd.Start(); err != nil { + return err + } + + // kill the underlying CometBFT process and subsequent tailing process + go func() { + // Killing the CometBFT process with the '-ABRT|-6' signal will result in + // a goroutine stacktrace. + p, err := os.FindProcess(pid) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to find PID to kill CometBFT process: %s", err) + } else if err = p.Signal(syscall.SIGABRT); err != nil { + fmt.Fprintf(os.Stderr, "failed to kill CometBFT process: %s", err) + } + + // allow some time to allow the CometBFT process to be killed + // + // TODO: We should 'wait' for a kill to succeed (e.g. poll for PID until it + // cannot be found). Regardless, this should be ample time. + time.Sleep(5 * time.Second) + + if err := cmd.Process.Kill(); err != nil { + fmt.Fprintf(os.Stderr, "failed to kill CometBFT process output redirection: %s", err) + } + }() + + if err := cmd.Wait(); err != nil { + // only return an error not invoked by a manual kill + if _, ok := err.(*exec.ExitError); !ok { + return err + } + } + + return nil +} diff --git a/cmd/cometbft/commands/debug/util.go b/cmd/cometbft/commands/debug/util.go new file mode 100644 index 0000000..7fdc5ad --- /dev/null +++ b/cmd/cometbft/commands/debug/util.go @@ -0,0 +1,83 @@ +package debug + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + + cfg "github.com/cometbft/cometbft/config" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" +) + +// dumpStatus gets node status state dump from the CometBFT RPC and writes it +// to file. It returns an error upon failure. +func dumpStatus(rpc *rpchttp.HTTP, dir, filename string) error { + status, err := rpc.Status(context.Background()) + if err != nil { + return fmt.Errorf("failed to get node status: %w", err) + } + + return writeStateJSONToFile(status, dir, filename) +} + +// dumpNetInfo gets network information state dump from the CometBFT RPC and +// writes it to file. It returns an error upon failure. +func dumpNetInfo(rpc *rpchttp.HTTP, dir, filename string) error { + netInfo, err := rpc.NetInfo(context.Background()) + if err != nil { + return fmt.Errorf("failed to get node network information: %w", err) + } + + return writeStateJSONToFile(netInfo, dir, filename) +} + +// dumpConsensusState gets consensus state dump from the CometBFT RPC and +// writes it to file. It returns an error upon failure. +func dumpConsensusState(rpc *rpchttp.HTTP, dir, filename string) error { + consDump, err := rpc.DumpConsensusState(context.Background()) + if err != nil { + return fmt.Errorf("failed to get node consensus dump: %w", err) + } + + return writeStateJSONToFile(consDump, dir, filename) +} + +// copyWAL copies the CometBFT node's WAL file. It returns an error if the +// WAL file cannot be read or copied. +func copyWAL(conf *cfg.Config, dir string) error { + walPath := conf.Consensus.WalFile() + walFile := filepath.Base(walPath) + + return copyFile(walPath, filepath.Join(dir, walFile)) +} + +// copyConfig copies the CometBFT node's config file. It returns an error if +// the config file cannot be read or copied. +func copyConfig(home, dir string) error { + configFile := "config.toml" + configPath := filepath.Join(home, "config", configFile) + + return copyFile(configPath, filepath.Join(dir, configFile)) +} + +func dumpProfile(dir, addr, profile string, debug int) error { + endpoint := fmt.Sprintf("%s/debug/pprof/%s?debug=%d", addr, profile, debug) + + //nolint:gosec,nolintlint + resp, err := http.Get(endpoint) + if err != nil { + return fmt.Errorf("failed to query for %s profile: %w", profile, err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read %s profile response body: %w", profile, err) + } + + return os.WriteFile(path.Join(dir, fmt.Sprintf("%s.out", profile)), body, 0o600) +} diff --git a/cmd/cometbft/commands/gen_node_key.go b/cmd/cometbft/commands/gen_node_key.go new file mode 100644 index 0000000..6bbf0e1 --- /dev/null +++ b/cmd/cometbft/commands/gen_node_key.go @@ -0,0 +1,33 @@ +package commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/p2p" +) + +// GenNodeKeyCmd allows the generation of a node key. It prints node's ID to +// the standard output. +var GenNodeKeyCmd = &cobra.Command{ + Use: "gen-node-key", + Aliases: []string{"gen_node_key"}, + Short: "Generate a node key for this node and print its ID", + RunE: genNodeKey, +} + +func genNodeKey(*cobra.Command, []string) error { + nodeKeyFile := config.NodeKeyFile() + if cmtos.FileExists(nodeKeyFile) { + return fmt.Errorf("node key at %s already exists", nodeKeyFile) + } + + nodeKey, err := p2p.LoadOrGenNodeKey(nodeKeyFile) + if err != nil { + return err + } + fmt.Println(nodeKey.ID()) + return nil +} diff --git a/cmd/cometbft/commands/gen_validator.go b/cmd/cometbft/commands/gen_validator.go new file mode 100644 index 0000000..d2b6979 --- /dev/null +++ b/cmd/cometbft/commands/gen_validator.go @@ -0,0 +1,29 @@ +package commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/privval" +) + +// GenValidatorCmd allows the generation of a keypair for a +// validator. +var GenValidatorCmd = &cobra.Command{ + Use: "gen-validator", + Aliases: []string{"gen_validator"}, + Short: "Generate new validator keypair", + Run: genValidator, +} + +func genValidator(*cobra.Command, []string) { + pv := privval.GenFilePV("", "") + jsbz, err := cmtjson.Marshal(pv) + if err != nil { + panic(err) + } + fmt.Printf(`%v +`, string(jsbz)) +} diff --git a/cmd/cometbft/commands/init.go b/cmd/cometbft/commands/init.go new file mode 100644 index 0000000..239da31 --- /dev/null +++ b/cmd/cometbft/commands/init.go @@ -0,0 +1,81 @@ +package commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + cfg "github.com/cometbft/cometbft/config" + cmtos "github.com/cometbft/cometbft/libs/os" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +// InitFilesCmd initializes a fresh CometBFT instance. +var InitFilesCmd = &cobra.Command{ + Use: "init", + Short: "Initialize CometBFT", + RunE: initFiles, +} + +func initFiles(*cobra.Command, []string) error { + return initFilesWithConfig(config) +} + +func initFilesWithConfig(config *cfg.Config) error { + // private validator + privValKeyFile := config.PrivValidatorKeyFile() + privValStateFile := config.PrivValidatorStateFile() + var pv *privval.FilePV + if cmtos.FileExists(privValKeyFile) { + pv = privval.LoadFilePV(privValKeyFile, privValStateFile) + logger.Info("Found private validator", "keyFile", privValKeyFile, + "stateFile", privValStateFile) + } else { + pv = privval.GenFilePV(privValKeyFile, privValStateFile) + pv.Save() + logger.Info("Generated private validator", "keyFile", privValKeyFile, + "stateFile", privValStateFile) + } + + nodeKeyFile := config.NodeKeyFile() + if cmtos.FileExists(nodeKeyFile) { + logger.Info("Found node key", "path", nodeKeyFile) + } else { + if _, err := p2p.LoadOrGenNodeKey(nodeKeyFile); err != nil { + return err + } + logger.Info("Generated node key", "path", nodeKeyFile) + } + + // genesis file + genFile := config.GenesisFile() + if cmtos.FileExists(genFile) { + logger.Info("Found genesis file", "path", genFile) + } else { + genDoc := types.GenesisDoc{ + ChainID: fmt.Sprintf("test-chain-%v", cmtrand.Str(6)), + GenesisTime: cmttime.Now(), + ConsensusParams: types.DefaultConsensusParams(), + } + pubKey, err := pv.GetPubKey() + if err != nil { + return fmt.Errorf("can't get pubkey: %w", err) + } + genDoc.Validators = []types.GenesisValidator{{ + Address: pubKey.Address(), + PubKey: pubKey, + Power: 10, + }} + + if err := genDoc.SaveAs(genFile); err != nil { + return err + } + logger.Info("Generated genesis file", "path", genFile) + } + + return nil +} diff --git a/cmd/cometbft/commands/inspect.go b/cmd/cometbft/commands/inspect.go new file mode 100644 index 0000000..fec3385 --- /dev/null +++ b/cmd/cometbft/commands/inspect.go @@ -0,0 +1,84 @@ +package commands + +import ( + "context" + "os" + "os/signal" + "syscall" + + "github.com/spf13/cobra" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/inspect" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer/block" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +// InspectCmd is the command for starting an inspect server. +var InspectCmd = &cobra.Command{ + Use: "inspect", + Short: "Run an inspect server for investigating CometBFT state", + Long: ` + inspect runs a subset of CometBFT's RPC endpoints that are useful for debugging + issues with CometBFT. + + When the CometBFT detects inconsistent state, it will crash the + CometBFT process. CometBFT will not start up while in this inconsistent state. + The inspect command can be used to query the block and state store using CometBFT + RPC calls to debug issues of inconsistent state. + `, + + RunE: runInspect, +} + +func init() { + InspectCmd.Flags(). + String("rpc.laddr", + config.RPC.ListenAddress, "RPC listenener address. Port required") + InspectCmd.Flags(). + String("db-backend", + config.DBBackend, "database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb") + InspectCmd.Flags(). + String("db-dir", config.DBPath, "database directory") +} + +func runInspect(cmd *cobra.Command, _ []string) error { + ctx, cancel := context.WithCancel(cmd.Context()) + defer cancel() + + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGTERM, syscall.SIGINT) + go func() { + <-c + cancel() + }() + + blockStoreDB, err := cfg.DefaultDBProvider(&cfg.DBContext{ID: "blockstore", Config: config}) + if err != nil { + return err + } + blockStore := store.NewBlockStore(blockStoreDB) + defer blockStore.Close() + + stateDB, err := cfg.DefaultDBProvider(&cfg.DBContext{ID: "state", Config: config}) + if err != nil { + return err + } + stateStore := state.NewStore(stateDB, state.StoreOptions{DiscardABCIResponses: false}) + defer stateStore.Close() + + genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) + if err != nil { + return err + } + txIndexer, blockIndexer, err := block.IndexerFromConfig(config, cfg.DefaultDBProvider, genDoc.ChainID) + if err != nil { + return err + } + ins := inspect.New(config.RPC, blockStore, stateStore, txIndexer, blockIndexer) + + logger.Info("starting inspect server") + return ins.Run(ctx) +} diff --git a/cmd/cometbft/commands/light.go b/cmd/cometbft/commands/light.go new file mode 100644 index 0000000..7458645 --- /dev/null +++ b/cmd/cometbft/commands/light.go @@ -0,0 +1,257 @@ +package commands + +import ( + "bufio" + "context" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/spf13/cobra" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/light" + lproxy "github.com/cometbft/cometbft/light/proxy" + lrpc "github.com/cometbft/cometbft/light/rpc" + dbs "github.com/cometbft/cometbft/light/store/db" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" +) + +// LightCmd represents the base command when called without any subcommands +var LightCmd = &cobra.Command{ + Use: "light [chainID]", + Short: "Run a light client proxy server, verifying CometBFT rpc", + Long: `Run a light client proxy server, verifying CometBFT rpc. + +All calls that can be tracked back to a block header by a proof +will be verified before passing them back to the caller. Other than +that, it will present the same interface as a full CometBFT node. + +Furthermore to the chainID, a fresh instance of a light client will +need a primary RPC address, a trusted hash and height and witness RPC addresses +(if not using sequential verification). To restart the node, thereafter +only the chainID is required. + +When /abci_query is called, the Merkle key path format is: + + /{store name}/{key} + +Please verify with your application that this Merkle key format is used (true +for applications built w/ Cosmos SDK). +`, + RunE: runProxy, + Args: cobra.ExactArgs(1), + Example: `light cosmoshub-3 -p http://52.57.29.196:26657 -w http://public-seed-node.cosmoshub.certus.one:26657 + --height 962118 --hash 28B97BE9F6DE51AC69F70E0B7BFD7E5C9CD1A595B7DC31AFF27C50D4948020CD`, +} + +var ( + listenAddr string + primaryAddr string + witnessAddrsJoined string + chainID string + home string + maxOpenConnections int + + sequential bool + trustingPeriod time.Duration + trustedHeight int64 + trustedHash []byte + trustLevelStr string + + verbose bool + + primaryKey = []byte("primary") + witnessesKey = []byte("witnesses") +) + +func init() { + LightCmd.Flags().StringVar(&listenAddr, "laddr", "tcp://localhost:8888", + "serve the proxy on the given address") + LightCmd.Flags().StringVarP(&primaryAddr, "primary", "p", "", + "connect to a CometBFT node at this address") + LightCmd.Flags().StringVarP(&witnessAddrsJoined, "witnesses", "w", "", + "CometBFT nodes to cross-check the primary node, comma-separated") + LightCmd.Flags().StringVar(&home, "home-dir", os.ExpandEnv(filepath.Join("$HOME", ".cometbft-light")), + "specify the home directory") + LightCmd.Flags().IntVar( + &maxOpenConnections, + "max-open-connections", + 900, + "maximum number of simultaneous connections (including WebSocket).") + LightCmd.Flags().DurationVar(&trustingPeriod, "trusting-period", 168*time.Hour, + "trusting period that headers can be verified within. Should be significantly less than the unbonding period") + LightCmd.Flags().Int64Var(&trustedHeight, "height", 1, "Trusted header's height") + LightCmd.Flags().BytesHexVar(&trustedHash, "hash", []byte{}, "Trusted header's hash") + LightCmd.Flags().BoolVar(&verbose, "verbose", false, "Verbose output") + LightCmd.Flags().StringVar(&trustLevelStr, "trust-level", "1/3", + "trust level. Must be between 1/3 and 3/3", + ) + LightCmd.Flags().BoolVar(&sequential, "sequential", false, + "sequential verification. Verify all headers sequentially as opposed to using skipping verification", + ) +} + +func runProxy(_ *cobra.Command, args []string) error { + // Initialize logger. + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + var option log.Option + if verbose { + option, _ = log.AllowLevel("debug") + } else { + option, _ = log.AllowLevel("info") + } + logger = log.NewFilter(logger, option) + + chainID = args[0] + logger.Info("Creating client...", "chainID", chainID) + + witnessesAddrs := []string{} + if witnessAddrsJoined != "" { + witnessesAddrs = strings.Split(witnessAddrsJoined, ",") + } + + db, err := dbm.NewGoLevelDB("light-client-db", home) + if err != nil { + return fmt.Errorf("can't create a db: %w", err) + } + + if primaryAddr == "" { // check to see if we can start from an existing state + var err error + primaryAddr, witnessesAddrs, err = checkForExistingProviders(db) + if err != nil { + return fmt.Errorf("failed to retrieve primary or witness from db: %w", err) + } + if primaryAddr == "" { + return errors.New("no primary address was provided nor found. Please provide a primary (using -p)." + + " Run the command: cometbft light --help for more information") + } + } else { + err := saveProviders(db, primaryAddr, witnessAddrsJoined) + if err != nil { + logger.Error("Unable to save primary and or witness addresses", "err", err) + } + } + + trustLevel, err := cmtmath.ParseFraction(trustLevelStr) + if err != nil { + return fmt.Errorf("can't parse trust level: %w", err) + } + + options := []light.Option{ + light.Logger(logger), + light.ConfirmationFunction(func(action string) bool { + fmt.Println(action) + scanner := bufio.NewScanner(os.Stdin) + for { + scanner.Scan() + response := scanner.Text() + switch response { + case "y", "Y": + return true + case "n", "N": + return false + default: + fmt.Println("please input 'Y' or 'n' and press ENTER") + } + } + }), + } + + if sequential { + options = append(options, light.SequentialVerification()) + } else { + options = append(options, light.SkippingVerification(trustLevel)) + } + + var c *light.Client + if trustedHeight > 0 && len(trustedHash) > 0 { // fresh installation + c, err = light.NewHTTPClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: trustingPeriod, + Height: trustedHeight, + Hash: trustedHash, + }, + primaryAddr, + witnessesAddrs, + dbs.New(db, chainID), + options..., + ) + } else { // continue from latest state + c, err = light.NewHTTPClientFromTrustedStore( + chainID, + trustingPeriod, + primaryAddr, + witnessesAddrs, + dbs.New(db, chainID), + options..., + ) + } + if err != nil { + return err + } + + cfg := rpcserver.DefaultConfig() + cfg.MaxBodyBytes = config.RPC.MaxBodyBytes + cfg.MaxHeaderBytes = config.RPC.MaxHeaderBytes + cfg.MaxOpenConnections = maxOpenConnections + // If necessary adjust global WriteTimeout to ensure it's greater than + // TimeoutBroadcastTxCommit. + // See https://github.com/tendermint/tendermint/issues/3435 + if cfg.WriteTimeout <= config.RPC.TimeoutBroadcastTxCommit { + cfg.WriteTimeout = config.RPC.TimeoutBroadcastTxCommit + 1*time.Second + } + + p, err := lproxy.NewProxy(c, listenAddr, primaryAddr, cfg, logger, lrpc.KeyPathFn(lrpc.DefaultMerkleKeyPathFn())) + if err != nil { + return err + } + + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(logger, func() { + p.Listener.Close() + }) + + logger.Info("Starting proxy...", "laddr", listenAddr) + if err := p.ListenAndServe(); err != http.ErrServerClosed { + // Error starting or closing listener: + logger.Error("proxy ListenAndServe", "err", err) + } + + return nil +} + +func checkForExistingProviders(db dbm.DB) (string, []string, error) { + primaryBytes, err := db.Get(primaryKey) + if err != nil { + return "", []string{""}, err + } + witnessesBytes, err := db.Get(witnessesKey) + if err != nil { + return "", []string{""}, err + } + witnessesAddrs := strings.Split(string(witnessesBytes), ",") + return string(primaryBytes), witnessesAddrs, nil +} + +func saveProviders(db dbm.DB, primaryAddr, witnessesAddrs string) error { + err := db.Set(primaryKey, []byte(primaryAddr)) + if err != nil { + return fmt.Errorf("failed to save primary provider: %w", err) + } + err = db.Set(witnessesKey, []byte(witnessesAddrs)) + if err != nil { + return fmt.Errorf("failed to save witness providers: %w", err) + } + return nil +} diff --git a/cmd/cometbft/commands/reindex_event.go b/cmd/cometbft/commands/reindex_event.go new file mode 100644 index 0000000..68261a7 --- /dev/null +++ b/cmd/cometbft/commands/reindex_event.go @@ -0,0 +1,240 @@ +package commands + +import ( + "errors" + "fmt" + "strings" + + "github.com/spf13/cobra" + + dbm "github.com/cometbft/cometbft-db" + + abcitypes "github.com/cometbft/cometbft/abci/types" + cmtcfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/progressbar" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + blockidxkv "github.com/cometbft/cometbft/state/indexer/block/kv" + "github.com/cometbft/cometbft/state/indexer/sink/psql" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/state/txindex/kv" + "github.com/cometbft/cometbft/types" +) + +const ( + reindexFailed = "event re-index failed: " +) + +var ( + ErrHeightNotAvailable = errors.New("height is not available") + ErrInvalidRequest = errors.New("invalid request") +) + +// ReIndexEventCmd constructs a command to re-index events in a block height interval. +var ReIndexEventCmd = &cobra.Command{ + Use: "reindex-event", + Aliases: []string{"reindex_event"}, + Short: "reindex events to the event store backends", + Long: ` +reindex-event is an offline tooling to re-index block and tx events to the eventsinks, +you can run this command when the event store backend dropped/disconnected or you want to +replace the backend. The default start-height is 0, meaning the tooling will start +reindex from the base block height(inclusive); and the default end-height is 0, meaning +the tooling will reindex until the latest block height(inclusive). User can omit +either or both arguments. + +Note: This operation requires ABCI Responses. Do not set DiscardABCIResponses to true if you +want to use this command. + `, + Example: ` + cometbft reindex-event + cometbft reindex-event --start-height 2 + cometbft reindex-event --end-height 10 + cometbft reindex-event --start-height 2 --end-height 10 + `, + Run: func(cmd *cobra.Command, args []string) { + bs, ss, err := loadStateAndBlockStore(config) + if err != nil { + fmt.Println(reindexFailed, err) + return + } + + state, err := ss.Load() + if err != nil { + fmt.Println(reindexFailed, err) + return + } + + if err := checkValidHeight(bs); err != nil { + fmt.Println(reindexFailed, err) + return + } + + bi, ti, err := loadEventSinks(config, state.ChainID) + if err != nil { + fmt.Println(reindexFailed, err) + return + } + + riArgs := eventReIndexArgs{ + startHeight: startHeight, + endHeight: endHeight, + blockIndexer: bi, + txIndexer: ti, + blockStore: bs, + stateStore: ss, + } + if err := eventReIndex(cmd, riArgs); err != nil { + panic(fmt.Errorf("%s: %w", reindexFailed, err)) + } + + fmt.Println("event re-index finished") + }, +} + +var ( + startHeight int64 + endHeight int64 +) + +func init() { + ReIndexEventCmd.Flags().Int64Var(&startHeight, "start-height", 0, "the block height would like to start for re-index") + ReIndexEventCmd.Flags().Int64Var(&endHeight, "end-height", 0, "the block height would like to finish for re-index") +} + +func loadEventSinks(cfg *cmtcfg.Config, chainID string) (indexer.BlockIndexer, txindex.TxIndexer, error) { + switch strings.ToLower(cfg.TxIndex.Indexer) { + case "null": + return nil, nil, errors.New("found null event sink, please check the tx-index section in the config.toml") + case "psql": + conn := cfg.TxIndex.PsqlConn + if conn == "" { + return nil, nil, errors.New("the psql connection settings cannot be empty") + } + es, err := psql.NewEventSink(conn, chainID) + if err != nil { + return nil, nil, err + } + return es.BlockIndexer(), es.TxIndexer(), nil + case "kv": + store, err := dbm.NewDB("tx_index", dbm.BackendType(cfg.DBBackend), cfg.DBDir()) + if err != nil { + return nil, nil, err + } + + txIndexer := kv.NewTxIndex(store) + blockIndexer := blockidxkv.New(dbm.NewPrefixDB(store, []byte("block_events"))) + return blockIndexer, txIndexer, nil + default: + return nil, nil, fmt.Errorf("unsupported event sink type: %s", cfg.TxIndex.Indexer) + } +} + +type eventReIndexArgs struct { + startHeight int64 + endHeight int64 + blockIndexer indexer.BlockIndexer + txIndexer txindex.TxIndexer + blockStore state.BlockStore + stateStore state.Store +} + +func eventReIndex(cmd *cobra.Command, args eventReIndexArgs) error { + var bar progressbar.Bar + bar.NewOption(args.startHeight-1, args.endHeight) + + fmt.Println("start re-indexing events:") + defer bar.Finish() + for height := args.startHeight; height <= args.endHeight; height++ { + select { + case <-cmd.Context().Done(): + return fmt.Errorf("event re-index terminated at height %d: %w", height, cmd.Context().Err()) + default: + block := args.blockStore.LoadBlock(height) + if block == nil { + return fmt.Errorf("not able to load block at height %d from the blockstore", height) + } + + resp, err := args.stateStore.LoadFinalizeBlockResponse(height) + if err != nil { + return fmt.Errorf("not able to load ABCI Response at height %d from the statestore", height) + } + + e := types.EventDataNewBlockEvents{ + Height: height, + Events: resp.Events, + } + + numTxs := len(resp.TxResults) + + var batch *txindex.Batch + if numTxs > 0 { + batch = txindex.NewBatch(int64(numTxs)) + + for idx, txResult := range resp.TxResults { + tr := abcitypes.TxResult{ + Height: height, + Index: uint32(idx), + Tx: block.Txs[idx], + Result: *txResult, + } + + if err = batch.Add(&tr); err != nil { + return fmt.Errorf("adding tx to batch: %w", err) + } + } + + if err := args.txIndexer.AddBatch(batch); err != nil { + return fmt.Errorf("tx event re-index at height %d failed: %w", height, err) + } + } + + if err := args.blockIndexer.Index(e); err != nil { + return fmt.Errorf("block event re-index at height %d failed: %w", height, err) + } + } + + bar.Play(height) + } + + return nil +} + +func checkValidHeight(bs state.BlockStore) error { + base := bs.Base() + + if startHeight == 0 { + startHeight = base + fmt.Printf("set the start block height to the base height of the blockstore %d \n", base) + } + + if startHeight < base { + return fmt.Errorf("%s (requested start height: %d, base height: %d)", + ErrHeightNotAvailable, startHeight, base) + } + + height := bs.Height() + + if startHeight > height { + return fmt.Errorf( + "%s (requested start height: %d, store height: %d)", ErrHeightNotAvailable, startHeight, height) + } + + if endHeight == 0 || endHeight > height { + endHeight = height + fmt.Printf("set the end block height to the latest height of the blockstore %d \n", height) + } + + if endHeight < base { + return fmt.Errorf( + "%s (requested end height: %d, base height: %d)", ErrHeightNotAvailable, endHeight, base) + } + + if endHeight < startHeight { + return fmt.Errorf( + "%s (requested the end height: %d is less than the start height: %d)", + ErrInvalidRequest, startHeight, endHeight) + } + + return nil +} diff --git a/cmd/cometbft/commands/reindex_event_test.go b/cmd/cometbft/commands/reindex_event_test.go new file mode 100644 index 0000000..a20c6dd --- /dev/null +++ b/cmd/cometbft/commands/reindex_event_test.go @@ -0,0 +1,191 @@ +package commands + +import ( + "context" + "errors" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abcitypes "github.com/cometbft/cometbft/abci/types" + cmtcfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/internal/test" + blockmocks "github.com/cometbft/cometbft/state/indexer/mocks" + "github.com/cometbft/cometbft/state/mocks" + txmocks "github.com/cometbft/cometbft/state/txindex/mocks" + "github.com/cometbft/cometbft/types" +) + +const ( + height int64 = 10 + base int64 = 2 +) + +func setupReIndexEventCmd() *cobra.Command { + reIndexEventCmd := &cobra.Command{ + Use: ReIndexEventCmd.Use, + Run: func(cmd *cobra.Command, args []string) {}, + } + + _ = reIndexEventCmd.ExecuteContext(context.Background()) + + return reIndexEventCmd +} + +func TestReIndexEventCheckHeight(t *testing.T) { + mockBlockStore := &mocks.BlockStore{} + mockBlockStore. + On("Base").Return(base). + On("Height").Return(height) + + testCases := []struct { + startHeight int64 + endHeight int64 + validHeight bool + }{ + {0, 0, true}, + {0, base, true}, + {0, base - 1, false}, + {0, height, true}, + {0, height + 1, true}, + {0, 0, true}, + {base - 1, 0, false}, + {base, 0, true}, + {base, base, true}, + {base, base - 1, false}, + {base, height, true}, + {base, height + 1, true}, + {height, 0, true}, + {height, base, false}, + {height, height - 1, false}, + {height, height, true}, + {height, height + 1, true}, + {height + 1, 0, false}, + } + + for _, tc := range testCases { + startHeight = tc.startHeight + endHeight = tc.endHeight + + err := checkValidHeight(mockBlockStore) + if tc.validHeight { + require.NoError(t, err) + } else { + require.Error(t, err) + } + } +} + +func TestLoadEventSink(t *testing.T) { + testCases := []struct { + sinks string + connURL string + loadErr bool + }{ + {"", "", true}, + {"NULL", "", true}, + {"KV", "", false}, + {"PSQL", "", true}, // true because empty connect url + // skip to test PSQL connect with correct url + {"UnsupportedSinkType", "wrongUrl", true}, + } + + for idx, tc := range testCases { + cfg := cmtcfg.TestConfig() + cfg.TxIndex.Indexer = tc.sinks + cfg.TxIndex.PsqlConn = tc.connURL + _, _, err := loadEventSinks(cfg, test.DefaultTestChainID) + if tc.loadErr { + require.Error(t, err, idx) + } else { + require.NoError(t, err, idx) + } + } +} + +func TestLoadBlockStore(t *testing.T) { + cfg := cmtcfg.TestConfig() + cfg.DBPath = t.TempDir() + _, _, err := loadStateAndBlockStore(cfg) + require.Error(t, err) + + _, err = dbm.NewDB("blockstore", dbm.GoLevelDBBackend, cfg.DBDir()) + require.NoError(t, err) + + // Get StateStore + _, err = dbm.NewDB("state", dbm.GoLevelDBBackend, cfg.DBDir()) + require.NoError(t, err) + + bs, ss, err := loadStateAndBlockStore(cfg) + require.NoError(t, err) + require.NotNil(t, bs) + require.NotNil(t, ss) +} + +func TestReIndexEvent(t *testing.T) { + mockBlockStore := &mocks.BlockStore{} + mockStateStore := &mocks.Store{} + mockBlockIndexer := &blockmocks.BlockIndexer{} + mockTxIndexer := &txmocks.TxIndexer{} + + mockBlockStore. + On("Base").Return(base). + On("Height").Return(height). + On("LoadBlock", base).Return(nil).Once(). + On("LoadBlock", base).Return(&types.Block{Data: types.Data{Txs: types.Txs{make(types.Tx, 1)}}}). + On("LoadBlock", height).Return(&types.Block{Data: types.Data{Txs: types.Txs{make(types.Tx, 1)}}}) + + abciResp := &abcitypes.ResponseFinalizeBlock{ + TxResults: []*abcitypes.ExecTxResult{ + {Code: 1}, + }, + } + + mockBlockIndexer. + On("Index", mock.AnythingOfType("types.EventDataNewBlockEvents")).Return(errors.New("")).Once(). + On("Index", mock.AnythingOfType("types.EventDataNewBlockEvents")).Return(nil) + + mockTxIndexer. + On("AddBatch", mock.AnythingOfType("*txindex.Batch")).Return(errors.New("")).Once(). + On("AddBatch", mock.AnythingOfType("*txindex.Batch")).Return(nil) + + mockStateStore. + On("LoadFinalizeBlockResponse", base).Return(nil, errors.New("")).Once(). + On("LoadFinalizeBlockResponse", base).Return(abciResp, nil). + On("LoadFinalizeBlockResponse", height).Return(abciResp, nil) + + testCases := []struct { + startHeight int64 + endHeight int64 + reIndexErr bool + }{ + {base, height, true}, // LoadBlock error + {base, height, true}, // LoadFinalizeBlockResponse error + {base, height, true}, // index block event error + {base, height, true}, // index tx event error + {base, base, false}, + {height, height, false}, + } + + for _, tc := range testCases { + args := eventReIndexArgs{ + startHeight: tc.startHeight, + endHeight: tc.endHeight, + blockIndexer: mockBlockIndexer, + txIndexer: mockTxIndexer, + blockStore: mockBlockStore, + stateStore: mockStateStore, + } + + err := eventReIndex(setupReIndexEventCmd(), args) + if tc.reIndexErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + } +} diff --git a/cmd/cometbft/commands/replay.go b/cmd/cometbft/commands/replay.go new file mode 100644 index 0000000..a04ed48 --- /dev/null +++ b/cmd/cometbft/commands/replay.go @@ -0,0 +1,27 @@ +package commands + +import ( + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/consensus" +) + +// ReplayCmd allows replaying of messages from the WAL. +var ReplayCmd = &cobra.Command{ + Use: "replay", + Short: "Replay messages from WAL", + Run: func(cmd *cobra.Command, args []string) { + consensus.RunReplayFile(config.BaseConfig, config.Consensus, false) + }, +} + +// ReplayConsoleCmd allows replaying of messages from the WAL in a +// console. +var ReplayConsoleCmd = &cobra.Command{ + Use: "replay-console", + Aliases: []string{"replay_console"}, + Short: "Replay messages from WAL in a console", + Run: func(cmd *cobra.Command, args []string) { + consensus.RunReplayFile(config.BaseConfig, config.Consensus, true) + }, +} diff --git a/cmd/cometbft/commands/reset.go b/cmd/cometbft/commands/reset.go new file mode 100644 index 0000000..b85fecc --- /dev/null +++ b/cmd/cometbft/commands/reset.go @@ -0,0 +1,184 @@ +package commands + +import ( + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/privval" +) + +// ResetAllCmd removes the database of this CometBFT core +// instance. +var ResetAllCmd = &cobra.Command{ + Use: "unsafe-reset-all", + Aliases: []string{"unsafe_reset_all"}, + Short: "(unsafe) Remove all the data and WAL, reset this node's validator to genesis state", + RunE: resetAllCmd, +} + +var keepAddrBook bool + +// ResetStateCmd removes the database of the specified CometBFT core instance. +var ResetStateCmd = &cobra.Command{ + Use: "reset-state", + Aliases: []string{"reset_state"}, + Short: "Remove all the data and WAL", + RunE: func(cmd *cobra.Command, args []string) (err error) { + config, err = ParseConfig(cmd) + if err != nil { + return err + } + + return resetState(config.DBDir(), logger) + }, +} + +func init() { + ResetAllCmd.Flags().BoolVar(&keepAddrBook, "keep-addr-book", false, "keep the address book intact") +} + +// ResetPrivValidatorCmd resets the private validator files. +var ResetPrivValidatorCmd = &cobra.Command{ + Use: "unsafe-reset-priv-validator", + Aliases: []string{"unsafe_reset_priv_validator"}, + Short: "(unsafe) Reset this node's validator to genesis state", + RunE: resetPrivValidator, +} + +// XXX: this is totally unsafe. +// it's only suitable for testnets. +func resetAllCmd(cmd *cobra.Command, _ []string) (err error) { + config, err = ParseConfig(cmd) + if err != nil { + return err + } + + return resetAll( + config.DBDir(), + config.P2P.AddrBookFile(), + config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile(), + logger, + ) +} + +// XXX: this is totally unsafe. +// it's only suitable for testnets. +func resetPrivValidator(cmd *cobra.Command, _ []string) (err error) { + config, err = ParseConfig(cmd) + if err != nil { + return err + } + + resetFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile(), logger) + return nil +} + +// resetAll removes address book files plus all data, and resets the privValdiator data. +func resetAll(dbDir, addrBookFile, privValKeyFile, privValStateFile string, logger log.Logger) error { + if keepAddrBook { + logger.Info("The address book remains intact") + } else { + removeAddrBook(addrBookFile, logger) + } + + if err := os.RemoveAll(dbDir); err == nil { + logger.Info("Removed all blockchain history", "dir", dbDir) + } else { + logger.Error("Error removing all blockchain history", "dir", dbDir, "err", err) + } + + if err := cmtos.EnsureDir(dbDir, 0o700); err != nil { + logger.Error("unable to recreate dbDir", "err", err) + } + + // recreate the dbDir since the privVal state needs to live there + resetFilePV(privValKeyFile, privValStateFile, logger) + return nil +} + +// resetState removes address book files plus all databases. +func resetState(dbDir string, logger log.Logger) error { + blockdb := filepath.Join(dbDir, "blockstore.db") + state := filepath.Join(dbDir, "state.db") + wal := filepath.Join(dbDir, "cs.wal") + evidence := filepath.Join(dbDir, "evidence.db") + txIndex := filepath.Join(dbDir, "tx_index.db") + + if cmtos.FileExists(blockdb) { + if err := os.RemoveAll(blockdb); err == nil { + logger.Info("Removed all blockstore.db", "dir", blockdb) + } else { + logger.Error("error removing all blockstore.db", "dir", blockdb, "err", err) + } + } + + if cmtos.FileExists(state) { + if err := os.RemoveAll(state); err == nil { + logger.Info("Removed all state.db", "dir", state) + } else { + logger.Error("error removing all state.db", "dir", state, "err", err) + } + } + + if cmtos.FileExists(wal) { + if err := os.RemoveAll(wal); err == nil { + logger.Info("Removed all cs.wal", "dir", wal) + } else { + logger.Error("error removing all cs.wal", "dir", wal, "err", err) + } + } + + if cmtos.FileExists(evidence) { + if err := os.RemoveAll(evidence); err == nil { + logger.Info("Removed all evidence.db", "dir", evidence) + } else { + logger.Error("error removing all evidence.db", "dir", evidence, "err", err) + } + } + + if cmtos.FileExists(txIndex) { + if err := os.RemoveAll(txIndex); err == nil { + logger.Info("Removed tx_index.db", "dir", txIndex) + } else { + logger.Error("error removing tx_index.db", "dir", txIndex, "err", err) + } + } + + if err := cmtos.EnsureDir(dbDir, 0o700); err != nil { + logger.Error("unable to recreate dbDir", "err", err) + } + return nil +} + +func resetFilePV(privValKeyFile, privValStateFile string, logger log.Logger) { + if _, err := os.Stat(privValKeyFile); err == nil { + pv := privval.LoadFilePVEmptyState(privValKeyFile, privValStateFile) + pv.Reset() + logger.Info( + "Reset private validator file to genesis state", + "keyFile", privValKeyFile, + "stateFile", privValStateFile, + ) + } else { + pv := privval.GenFilePV(privValKeyFile, privValStateFile) + pv.Save() + logger.Info( + "Generated private validator file", + "keyFile", privValKeyFile, + "stateFile", privValStateFile, + ) + } +} + +func removeAddrBook(addrBookFile string, logger log.Logger) { + if err := os.Remove(addrBookFile); err == nil { + logger.Info("Removed existing address book", "file", addrBookFile) + } else if !os.IsNotExist(err) { + logger.Info("Error removing address book", "file", addrBookFile, "err", err) + } +} diff --git a/cmd/cometbft/commands/reset_test.go b/cmd/cometbft/commands/reset_test.go new file mode 100644 index 0000000..e80dbf0 --- /dev/null +++ b/cmd/cometbft/commands/reset_test.go @@ -0,0 +1,53 @@ +package commands + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/privval" +) + +func Test_ResetAll(t *testing.T) { + config := cfg.TestConfig() + dir := t.TempDir() + config.SetRoot(dir) + cfg.EnsureRoot(dir) + require.NoError(t, initFilesWithConfig(config)) + pv := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + pv.LastSignState.Height = 10 + pv.Save() + require.NoError(t, resetAll(config.DBDir(), config.P2P.AddrBookFile(), config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile(), logger)) + require.DirExists(t, config.DBDir()) + require.NoFileExists(t, filepath.Join(config.DBDir(), "block.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "state.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "evidence.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "tx_index.db")) + require.FileExists(t, config.PrivValidatorStateFile()) + pv = privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + require.Equal(t, int64(0), pv.LastSignState.Height) +} + +func Test_ResetState(t *testing.T) { + config := cfg.TestConfig() + dir := t.TempDir() + config.SetRoot(dir) + cfg.EnsureRoot(dir) + require.NoError(t, initFilesWithConfig(config)) + pv := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + pv.LastSignState.Height = 10 + pv.Save() + require.NoError(t, resetState(config.DBDir(), logger)) + require.DirExists(t, config.DBDir()) + require.NoFileExists(t, filepath.Join(config.DBDir(), "block.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "state.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "evidence.db")) + require.NoFileExists(t, filepath.Join(config.DBDir(), "tx_index.db")) + require.FileExists(t, config.PrivValidatorStateFile()) + pv = privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + // private validator state should still be in tact. + require.Equal(t, int64(10), pv.LastSignState.Height) +} diff --git a/cmd/cometbft/commands/rollback.go b/cmd/cometbft/commands/rollback.go new file mode 100644 index 0000000..9258f21 --- /dev/null +++ b/cmd/cometbft/commands/rollback.go @@ -0,0 +1,97 @@ +package commands + +import ( + "fmt" + "path/filepath" + + "github.com/spf13/cobra" + + dbm "github.com/cometbft/cometbft-db" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" +) + +var removeBlock = false + +func init() { + RollbackStateCmd.Flags().BoolVar(&removeBlock, "hard", false, "remove last block as well as state") +} + +var RollbackStateCmd = &cobra.Command{ + Use: "rollback", + Short: "rollback CometBFT state by one height", + Long: ` +A state rollback is performed to recover from an incorrect application state transition, +when CometBFT has persisted an incorrect app hash and is thus unable to make +progress. Rollback overwrites a state at height n with the state at height n - 1. +The application should also roll back to height n - 1. If the --hard flag is not used, +no blocks will be removed so upon restarting CometBFT the transactions in block n will be +re-executed against the application. Using --hard will also remove block n. This can +be done multiple times. +`, + RunE: func(cmd *cobra.Command, args []string) error { + height, hash, err := RollbackState(config, removeBlock) + if err != nil { + return fmt.Errorf("failed to rollback state: %w", err) + } + + if removeBlock { + fmt.Printf("Rolled back both state and block to height %d and hash %X\n", height, hash) + } else { + fmt.Printf("Rolled back state to height %d and hash %X\n", height, hash) + } + + return nil + }, +} + +// RollbackState takes the state at the current height n and overwrites it with the state +// at height n - 1. Note state here refers to CometBFT state not application state. +// Returns the latest state height and app hash alongside an error if there was one. +func RollbackState(config *cfg.Config, removeBlock bool) (int64, []byte, error) { + // use the parsed config to load the block and state store + blockStore, stateStore, err := loadStateAndBlockStore(config) + if err != nil { + return -1, nil, err + } + defer func() { + _ = blockStore.Close() + _ = stateStore.Close() + }() + + // rollback the last state + return state.Rollback(blockStore, stateStore, removeBlock) +} + +func loadStateAndBlockStore(config *cfg.Config) (*store.BlockStore, state.Store, error) { + dbType := dbm.BackendType(config.DBBackend) + + if !os.FileExists(filepath.Join(config.DBDir(), "blockstore.db")) { + return nil, nil, fmt.Errorf("no blockstore found in %v", config.DBDir()) + } + + // Get BlockStore + blockStoreDB, err := dbm.NewDB("blockstore", dbType, config.DBDir()) + if err != nil { + return nil, nil, err + } + blockStore := store.NewBlockStore(blockStoreDB) + + if !os.FileExists(filepath.Join(config.DBDir(), "state.db")) { + return nil, nil, fmt.Errorf("no statestore found in %v", config.DBDir()) + } + + // Get StateStore + stateDB, err := dbm.NewDB("state", dbType, config.DBDir()) + if err != nil { + return nil, nil, err + } + stateStore := state.NewStore(stateDB, state.StoreOptions{ + DiscardABCIResponses: config.Storage.DiscardABCIResponses, + }) + + return blockStore, stateStore, nil +} diff --git a/cmd/cometbft/commands/root.go b/cmd/cometbft/commands/root.go new file mode 100644 index 0000000..a873508 --- /dev/null +++ b/cmd/cometbft/commands/root.go @@ -0,0 +1,97 @@ +package commands + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cli" + cmtflags "github.com/cometbft/cometbft/libs/cli/flags" + "github.com/cometbft/cometbft/libs/log" +) + +var ( + config = cfg.DefaultConfig() + logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) +) + +func init() { + registerFlagsRootCmd(RootCmd) +} + +func registerFlagsRootCmd(cmd *cobra.Command) { + cmd.PersistentFlags().String("log_level", config.LogLevel, "log level") +} + +// ParseConfig retrieves the default environment configuration, +// sets up the CometBFT root and ensures that the root exists +func ParseConfig(cmd *cobra.Command) (*cfg.Config, error) { + conf := cfg.DefaultConfig() + err := viper.Unmarshal(conf) + if err != nil { + return nil, err + } + + var home string + if os.Getenv("CMTHOME") != "" { + home = os.Getenv("CMTHOME") + } else if os.Getenv("TMHOME") != "" { + // XXX: Deprecated. + home = os.Getenv("TMHOME") + logger.Error("Deprecated environment variable TMHOME identified. CMTHOME should be used instead.") + } else { + home, err = cmd.Flags().GetString(cli.HomeFlag) + if err != nil { + return nil, err + } + } + + conf.RootDir = home + + conf.SetRoot(conf.RootDir) + cfg.EnsureRoot(conf.RootDir) + if err := conf.ValidateBasic(); err != nil { + return nil, fmt.Errorf("error in config file: %v", err) + } + if warnings := conf.CheckDeprecated(); len(warnings) > 0 { + for _, warning := range warnings { + logger.Info("deprecated usage found in configuration file", "usage", warning) + } + } + return conf, nil +} + +// RootCmd is the root command for CometBFT core. +var RootCmd = &cobra.Command{ + Use: "cometbft", + Short: "BFT state machine replication for applications in any programming languages", + PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) { + if cmd.Name() == VersionCmd.Name() { + return nil + } + + config, err = ParseConfig(cmd) + if err != nil { + return err + } + + if config.LogFormat == cfg.LogFormatJSON { + logger = log.NewTMJSONLogger(log.NewSyncWriter(os.Stdout)) + } + + logger, err = cmtflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel) + if err != nil { + return err + } + + if viper.GetBool(cli.TraceFlag) { + logger = log.NewTracingLogger(logger) + } + + logger = logger.With("module", "main") + return nil + }, +} diff --git a/cmd/cometbft/commands/root_test.go b/cmd/cometbft/commands/root_test.go new file mode 100644 index 0000000..333002b --- /dev/null +++ b/cmd/cometbft/commands/root_test.go @@ -0,0 +1,172 @@ +package commands + +import ( + "fmt" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cli" + cmtos "github.com/cometbft/cometbft/libs/os" +) + +// clearConfig clears env vars, the given root dir, and resets viper. +func clearConfig(t *testing.T, dir string) { + os.Clearenv() + err := os.RemoveAll(dir) + require.NoError(t, err) + + viper.Reset() + config = cfg.DefaultConfig() +} + +// prepare new rootCmd +func testRootCmd() *cobra.Command { + rootCmd := &cobra.Command{ + Use: RootCmd.Use, + PersistentPreRunE: RootCmd.PersistentPreRunE, + Run: func(cmd *cobra.Command, args []string) {}, + } + registerFlagsRootCmd(rootCmd) + var l string + rootCmd.PersistentFlags().String("log", l, "Log") + return rootCmd +} + +func testSetup(t *testing.T, root string, args []string, env map[string]string) error { + clearConfig(t, root) + + rootCmd := testRootCmd() + cmd := cli.PrepareBaseCmd(rootCmd, "CMT", root) + + // run with the args and env + args = append([]string{rootCmd.Use}, args...) + return cli.RunWithArgs(cmd, args, env) +} + +func TestRootHome(t *testing.T) { + tmpDir := os.TempDir() + root := filepath.Join(tmpDir, "adir") + newRoot := filepath.Join(tmpDir, "something-else") + defer clearConfig(t, root) + defer clearConfig(t, newRoot) + + cases := []struct { + args []string + env map[string]string + root string + }{ + {nil, nil, root}, + {[]string{"--home", newRoot}, nil, newRoot}, + {nil, map[string]string{"TMHOME": newRoot}, newRoot}, // XXX: Deprecated. + {nil, map[string]string{"CMTHOME": newRoot}, newRoot}, + } + + for i, tc := range cases { + idxString := "idx: " + strconv.Itoa(i) + + err := testSetup(t, root, tc.args, tc.env) + require.Nil(t, err, idxString) + + assert.Equal(t, tc.root, config.RootDir, idxString) + assert.Equal(t, tc.root, config.P2P.RootDir, idxString) + assert.Equal(t, tc.root, config.Consensus.RootDir, idxString) + assert.Equal(t, tc.root, config.Mempool.RootDir, idxString) + } +} + +func TestRootFlagsEnv(t *testing.T) { + // defaults + defaults := cfg.DefaultConfig() + defaultLogLvl := defaults.LogLevel + + cases := []struct { + args []string + env map[string]string + logLevel string + }{ + {[]string{"--log", "debug"}, nil, defaultLogLvl}, // wrong flag + {[]string{"--log_level", "debug"}, nil, "debug"}, // right flag + {nil, map[string]string{"TM_LOW": "debug"}, defaultLogLvl}, // wrong env flag + {nil, map[string]string{"MT_LOG_LEVEL": "debug"}, defaultLogLvl}, // wrong env prefix + {nil, map[string]string{"TM_LOG_LEVEL": "debug"}, defaultLogLvl}, // right, but deprecated env + {nil, map[string]string{"CMT_LOW": "debug"}, defaultLogLvl}, // wrong env flag + {nil, map[string]string{"TMC_LOG_LEVEL": "debug"}, defaultLogLvl}, // wrong env prefix + {nil, map[string]string{"CMT_LOG_LEVEL": "debug"}, "debug"}, // right env + } + + for i, tc := range cases { + idxString := strconv.Itoa(i) + root := filepath.Join(os.TempDir(), "adir2_"+idxString) + idxString = "idx: " + idxString + defer clearConfig(t, root) + err := testSetup(t, root, tc.args, tc.env) + require.Nil(t, err, idxString) + + assert.Equal(t, tc.logLevel, config.LogLevel, idxString) + } +} + +func TestRootConfig(t *testing.T) { + // write non-default config + nonDefaultLogLvl := "abc:debug" + cvals := map[string]string{ + "log_level": nonDefaultLogLvl, + } + + cases := []struct { + args []string + env map[string]string + + logLvl string + }{ + {nil, nil, nonDefaultLogLvl}, // should load config + {[]string{"--log_level=abc:info"}, nil, "abc:info"}, // flag over rides + {nil, map[string]string{"TM_LOG_LEVEL": "abc:info"}, nonDefaultLogLvl}, // env over rides //XXX: Deprecated + {nil, map[string]string{"CMT_LOG_LEVEL": "abc:info"}, "abc:info"}, // env over rides + } + + for i, tc := range cases { + idxString := strconv.Itoa(i) + root := filepath.Join(os.TempDir(), "adir3_"+idxString) + idxString = "idx: " + idxString + defer clearConfig(t, root) + // XXX: path must match cfg.defaultConfigPath + configFilePath := filepath.Join(root, "config") + err := cmtos.EnsureDir(configFilePath, 0o700) + require.Nil(t, err) + + // write the non-defaults to a different path + // TODO: support writing sub configs so we can test that too + err = WriteConfigVals(configFilePath, cvals) + require.Nil(t, err) + + rootCmd := testRootCmd() + cmd := cli.PrepareBaseCmd(rootCmd, "CMT", root) + + // run with the args and env + tc.args = append([]string{rootCmd.Use}, tc.args...) + err = cli.RunWithArgs(cmd, tc.args, tc.env) + require.Nil(t, err, idxString) + + assert.Equal(t, tc.logLvl, config.LogLevel, idxString) + } +} + +// WriteConfigVals writes a toml file with the given values. +// It returns an error if writing was impossible. +func WriteConfigVals(dir string, vals map[string]string) error { + data := "" + for k, v := range vals { + data += fmt.Sprintf("%s = \"%s\"\n", k, v) + } + cfile := filepath.Join(dir, "config.toml") + return os.WriteFile(cfile, []byte(data), 0o600) +} diff --git a/cmd/cometbft/commands/run_node.go b/cmd/cometbft/commands/run_node.go new file mode 100644 index 0000000..1034016 --- /dev/null +++ b/cmd/cometbft/commands/run_node.go @@ -0,0 +1,161 @@ +package commands + +import ( + "bytes" + "crypto/sha256" + "fmt" + "io" + "os" + + "github.com/spf13/cobra" + + cfg "github.com/cometbft/cometbft/config" + cmtos "github.com/cometbft/cometbft/libs/os" + nm "github.com/cometbft/cometbft/node" +) + +var ( + genesisHash []byte +) + +// AddNodeFlags exposes some common configuration options on the command-line +// These are exposed for convenience of commands embedding a CometBFT node +func AddNodeFlags(cmd *cobra.Command) { + // bind flags + cmd.Flags().String("moniker", config.Moniker, "node name") + + // priv val flags + cmd.Flags().String( + "priv_validator_laddr", + config.PrivValidatorListenAddr, + "socket address to listen on for connections from external priv_validator process") + + // node flags + cmd.Flags().BytesHexVar( + &genesisHash, + "genesis_hash", + []byte{}, + "optional SHA-256 hash of the genesis file") + cmd.Flags().Int64("consensus.double_sign_check_height", config.Consensus.DoubleSignCheckHeight, + "how many blocks to look back to check existence of the node's "+ + "consensus votes before joining consensus") + + // abci flags + cmd.Flags().String( + "proxy_app", + config.ProxyApp, + "proxy app address, or one of: 'kvstore',"+ + " 'persistent_kvstore' or 'noop' for local testing.") + cmd.Flags().String("abci", config.ABCI, "specify abci transport (socket | grpc)") + + // rpc flags + cmd.Flags().String("rpc.laddr", config.RPC.ListenAddress, "RPC listen address. Port required") + cmd.Flags().String( + "rpc.grpc_laddr", + config.RPC.GRPCListenAddress, + "GRPC listen address (BroadcastTx only). Port required") + cmd.Flags().Bool("rpc.unsafe", config.RPC.Unsafe, "enabled unsafe rpc methods") + cmd.Flags().String("rpc.pprof_laddr", config.RPC.PprofListenAddress, "pprof listen address (https://golang.org/pkg/net/http/pprof)") + + // p2p flags + cmd.Flags().String( + "p2p.laddr", + config.P2P.ListenAddress, + "node listen address. (0.0.0.0:0 means any interface, any port)") + cmd.Flags().String("p2p.external-address", config.P2P.ExternalAddress, "ip:port address to advertise to peers for them to dial") + cmd.Flags().String("p2p.seeds", config.P2P.Seeds, "comma-delimited ID@host:port seed nodes") + cmd.Flags().String("p2p.persistent_peers", config.P2P.PersistentPeers, "comma-delimited ID@host:port persistent peers") + cmd.Flags().String("p2p.unconditional_peer_ids", + config.P2P.UnconditionalPeerIDs, "comma-delimited IDs of unconditional peers") + cmd.Flags().Bool("p2p.pex", config.P2P.PexReactor, "enable/disable Peer-Exchange") + cmd.Flags().Bool("p2p.seed_mode", config.P2P.SeedMode, "enable/disable seed mode") + cmd.Flags().String("p2p.private_peer_ids", config.P2P.PrivatePeerIDs, "comma-delimited private peer IDs") + + // consensus flags + cmd.Flags().Bool( + "consensus.create_empty_blocks", + config.Consensus.CreateEmptyBlocks, + "set this to false to only produce blocks when there are txs or when the AppHash changes") + cmd.Flags().String( + "consensus.create_empty_blocks_interval", + config.Consensus.CreateEmptyBlocksInterval.String(), + "the possible interval between empty blocks") + + // db flags + cmd.Flags().String( + "db_backend", + config.DBBackend, + "database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb") + cmd.Flags().String( + "db_dir", + config.DBPath, + "database directory") +} + +// NewRunNodeCmd returns the command that allows the CLI to start a node. +// It can be used with a custom PrivValidator and in-process ABCI application. +func NewRunNodeCmd(nodeProvider nm.Provider) *cobra.Command { + cmd := &cobra.Command{ + Use: "start", + Aliases: []string{"node", "run"}, + Short: "Run the CometBFT node", + RunE: func(cmd *cobra.Command, args []string) error { + if err := checkGenesisHash(config); err != nil { + return err + } + + n, err := nodeProvider(config, logger) + if err != nil { + return fmt.Errorf("failed to create node: %w", err) + } + + if err := n.Start(); err != nil { + return fmt.Errorf("failed to start node: %w", err) + } + + logger.Info("Started node", "nodeInfo", n.Switch().NodeInfo()) + + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(logger, func() { + if n.IsRunning() { + if err := n.Stop(); err != nil { + logger.Error("unable to stop the node", "error", err) + } + } + }) + + // Run forever. + select {} + }, + } + + AddNodeFlags(cmd) + return cmd +} + +func checkGenesisHash(config *cfg.Config) error { + if len(genesisHash) == 0 || config.Genesis == "" { + return nil + } + + // Calculate SHA-256 hash of the genesis file. + f, err := os.Open(config.GenesisFile()) + if err != nil { + return fmt.Errorf("can't open genesis file: %w", err) + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return fmt.Errorf("error when hashing genesis file: %w", err) + } + actualHash := h.Sum(nil) + + // Compare with the flag. + if !bytes.Equal(genesisHash, actualHash) { + return fmt.Errorf( + "--genesis_hash=%X does not match %s hash: %X", + genesisHash, config.GenesisFile(), actualHash) + } + + return nil +} diff --git a/cmd/cometbft/commands/show_node_id.go b/cmd/cometbft/commands/show_node_id.go new file mode 100644 index 0000000..3ce6f81 --- /dev/null +++ b/cmd/cometbft/commands/show_node_id.go @@ -0,0 +1,27 @@ +package commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/p2p" +) + +// ShowNodeIDCmd dumps node's ID to the standard output. +var ShowNodeIDCmd = &cobra.Command{ + Use: "show-node-id", + Aliases: []string{"show_node_id"}, + Short: "Show this node's ID", + RunE: showNodeID, +} + +func showNodeID(*cobra.Command, []string) error { + nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) + if err != nil { + return err + } + + fmt.Println(nodeKey.ID()) + return nil +} diff --git a/cmd/cometbft/commands/show_validator.go b/cmd/cometbft/commands/show_validator.go new file mode 100644 index 0000000..43cd787 --- /dev/null +++ b/cmd/cometbft/commands/show_validator.go @@ -0,0 +1,41 @@ +package commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/privval" +) + +// ShowValidatorCmd adds capabilities for showing the validator info. +var ShowValidatorCmd = &cobra.Command{ + Use: "show-validator", + Aliases: []string{"show_validator"}, + Short: "Show this node's validator info", + RunE: showValidator, +} + +func showValidator(*cobra.Command, []string) error { + keyFilePath := config.PrivValidatorKeyFile() + if !cmtos.FileExists(keyFilePath) { + return fmt.Errorf("private validator file %s does not exist", keyFilePath) + } + + pv := privval.LoadFilePV(keyFilePath, config.PrivValidatorStateFile()) + + pubKey, err := pv.GetPubKey() + if err != nil { + return fmt.Errorf("can't get pubkey: %w", err) + } + + bz, err := cmtjson.Marshal(pubKey) + if err != nil { + return fmt.Errorf("failed to marshal private validator pubkey: %w", err) + } + + fmt.Println(string(bz)) + return nil +} diff --git a/cmd/cometbft/commands/testnet.go b/cmd/cometbft/commands/testnet.go new file mode 100644 index 0000000..ca754c8 --- /dev/null +++ b/cmd/cometbft/commands/testnet.go @@ -0,0 +1,278 @@ +package commands + +import ( + "fmt" + "net" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/bytes" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +var ( + nValidators int + nNonValidators int + initialHeight int64 + configFile string + outputDir string + nodeDirPrefix string + + populatePersistentPeers bool + hostnamePrefix string + hostnameSuffix string + startingIPAddress string + hostnames []string + p2pPort int + randomMonikers bool +) + +const ( + nodeDirPerm = 0o755 +) + +func init() { + TestnetFilesCmd.Flags().IntVar(&nValidators, "v", 4, + "number of validators to initialize the testnet with") + TestnetFilesCmd.Flags().StringVar(&configFile, "config", "", + "config file to use (note some options may be overwritten)") + TestnetFilesCmd.Flags().IntVar(&nNonValidators, "n", 0, + "number of non-validators to initialize the testnet with") + TestnetFilesCmd.Flags().StringVar(&outputDir, "o", "./mytestnet", + "directory to store initialization data for the testnet") + TestnetFilesCmd.Flags().StringVar(&nodeDirPrefix, "node-dir-prefix", "node", + "prefix the directory name for each node with (node results in node0, node1, ...)") + TestnetFilesCmd.Flags().Int64Var(&initialHeight, "initial-height", 0, + "initial height of the first block") + + TestnetFilesCmd.Flags().BoolVar(&populatePersistentPeers, "populate-persistent-peers", true, + "update config of each node with the list of persistent peers build using either"+ + " hostname-prefix or"+ + " starting-ip-address") + TestnetFilesCmd.Flags().StringVar(&hostnamePrefix, "hostname-prefix", "node", + "hostname prefix (\"node\" results in persistent peers list ID0@node0:26656, ID1@node1:26656, ...)") + TestnetFilesCmd.Flags().StringVar(&hostnameSuffix, "hostname-suffix", "", + "hostname suffix ("+ + "\".xyz.com\""+ + " results in persistent peers list ID0@node0.xyz.com:26656, ID1@node1.xyz.com:26656, ...)") + TestnetFilesCmd.Flags().StringVar(&startingIPAddress, "starting-ip-address", "", + "starting IP address ("+ + "\"192.168.0.1\""+ + " results in persistent peers list ID0@192.168.0.1:26656, ID1@192.168.0.2:26656, ...)") + TestnetFilesCmd.Flags().StringArrayVar(&hostnames, "hostname", []string{}, + "manually override all hostnames of validators and non-validators (use --hostname multiple times for multiple hosts)") + TestnetFilesCmd.Flags().IntVar(&p2pPort, "p2p-port", 26656, + "P2P Port") + TestnetFilesCmd.Flags().BoolVar(&randomMonikers, "random-monikers", false, + "randomize the moniker for each generated node") +} + +// TestnetFilesCmd allows initialisation of files for a CometBFT testnet. +var TestnetFilesCmd = &cobra.Command{ + Use: "testnet", + Short: "Initialize files for a CometBFT testnet", + Long: `testnet will create "v" + "n" number of directories and populate each with +necessary files (private validator, genesis, config, etc.). + +Note, strict routability for addresses is turned off in the config file. + +Optionally, it will fill in persistent_peers list in config file using either hostnames or IPs. + +Example: + + cometbft testnet --v 4 --o ./output --populate-persistent-peers --starting-ip-address 192.168.10.2 + `, + RunE: testnetFiles, +} + +func testnetFiles(*cobra.Command, []string) error { + if len(hostnames) > 0 && len(hostnames) != (nValidators+nNonValidators) { + return fmt.Errorf( + "testnet needs precisely %d hostnames (number of validators plus non-validators) if --hostname parameter is used", + nValidators+nNonValidators, + ) + } + + config := cfg.DefaultConfig() + + // overwrite default config if set and valid + if configFile != "" { + viper.SetConfigFile(configFile) + if err := viper.ReadInConfig(); err != nil { + return err + } + if err := viper.Unmarshal(config); err != nil { + return err + } + if err := config.ValidateBasic(); err != nil { + return err + } + } + + genVals := make([]types.GenesisValidator, nValidators) + + for i := 0; i < nValidators; i++ { + nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) + nodeDir := filepath.Join(outputDir, nodeDirName) + config.SetRoot(nodeDir) + + err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outputDir) + return err + } + err = os.MkdirAll(filepath.Join(nodeDir, "data"), nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outputDir) + return err + } + + if err := initFilesWithConfig(config); err != nil { + return err + } + + pvKeyFile := filepath.Join(nodeDir, config.PrivValidatorKey) + pvStateFile := filepath.Join(nodeDir, config.PrivValidatorState) + pv := privval.LoadFilePV(pvKeyFile, pvStateFile) + + pubKey, err := pv.GetPubKey() + if err != nil { + return fmt.Errorf("can't get pubkey: %w", err) + } + genVals[i] = types.GenesisValidator{ + Address: pubKey.Address(), + PubKey: pubKey, + Power: 1, + Name: nodeDirName, + } + } + + for i := 0; i < nNonValidators; i++ { + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i+nValidators)) + config.SetRoot(nodeDir) + + err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outputDir) + return err + } + + err = os.MkdirAll(filepath.Join(nodeDir, "data"), nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outputDir) + return err + } + + if err := initFilesWithConfig(config); err != nil { + return err + } + } + + // Generate genesis doc from generated validators + genDoc := &types.GenesisDoc{ + ChainID: "chain-" + cmtrand.Str(6), + ConsensusParams: types.DefaultConsensusParams(), + GenesisTime: cmttime.Now(), + InitialHeight: initialHeight, + Validators: genVals, + } + + // Write genesis file. + for i := 0; i < nValidators+nNonValidators; i++ { + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) + if err := genDoc.SaveAs(filepath.Join(nodeDir, config.Genesis)); err != nil { + _ = os.RemoveAll(outputDir) + return err + } + } + + // Gather persistent peer addresses. + var ( + persistentPeers string + err error + ) + if populatePersistentPeers { + persistentPeers, err = persistentPeersString(config) + if err != nil { + _ = os.RemoveAll(outputDir) + return err + } + } + + // Overwrite default config. + for i := 0; i < nValidators+nNonValidators; i++ { + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) + config.SetRoot(nodeDir) + config.P2P.AddrBookStrict = false + config.P2P.AllowDuplicateIP = true + if populatePersistentPeers { + config.P2P.PersistentPeers = persistentPeers + } + config.Moniker = moniker(i) + + cfg.WriteConfigFile(filepath.Join(nodeDir, "config", "config.toml"), config) + } + + fmt.Printf("Successfully initialized %v node directories\n", nValidators+nNonValidators) + return nil +} + +func hostnameOrIP(i int) string { + if len(hostnames) > 0 && i < len(hostnames) { + return hostnames[i] + } + if startingIPAddress == "" { + return fmt.Sprintf("%s%d%s", hostnamePrefix, i, hostnameSuffix) + } + ip := net.ParseIP(startingIPAddress) + ip = ip.To4() + if ip == nil { + fmt.Printf("%v: non ipv4 address\n", startingIPAddress) + os.Exit(1) + } + + for j := 0; j < i; j++ { + ip[3]++ + } + return ip.String() +} + +func persistentPeersString(config *cfg.Config) (string, error) { + persistentPeers := make([]string, nValidators+nNonValidators) + for i := 0; i < nValidators+nNonValidators; i++ { + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) + config.SetRoot(nodeDir) + nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) + if err != nil { + return "", err + } + persistentPeers[i] = p2p.IDAddressString(nodeKey.ID(), fmt.Sprintf("%s:%d", hostnameOrIP(i), p2pPort)) + } + return strings.Join(persistentPeers, ","), nil +} + +func moniker(i int) string { + if randomMonikers { + return randomMoniker() + } + if len(hostnames) > 0 && i < len(hostnames) { + return hostnames[i] + } + if startingIPAddress == "" { + return fmt.Sprintf("%s%d%s", hostnamePrefix, i, hostnameSuffix) + } + return randomMoniker() +} + +func randomMoniker() string { + return bytes.HexBytes(cmtrand.Bytes(8)).String() +} diff --git a/cmd/cometbft/commands/version.go b/cmd/cometbft/commands/version.go new file mode 100644 index 0000000..8bdd456 --- /dev/null +++ b/cmd/cometbft/commands/version.go @@ -0,0 +1,43 @@ +package commands + +import ( + "encoding/json" + "fmt" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/version" +) + +// VersionCmd ... +var VersionCmd = &cobra.Command{ + Use: "version", + Short: "Show version info", + Run: func(cmd *cobra.Command, args []string) { + cmtVersion := version.TMCoreSemVer + if version.TMGitCommitHash != "" { + cmtVersion += "+" + version.TMGitCommitHash + } + + if verbose { + values, _ := json.MarshalIndent(struct { + CometBFT string `json:"cometbft"` + ABCI string `json:"abci"` + BlockProtocol uint64 `json:"block_protocol"` + P2PProtocol uint64 `json:"p2p_protocol"` + }{ + CometBFT: cmtVersion, + ABCI: version.ABCISemVer, + BlockProtocol: version.BlockProtocol, + P2PProtocol: version.P2PProtocol, + }, "", " ") + fmt.Println(string(values)) + } else { + fmt.Println(cmtVersion) + } + }, +} + +func init() { + VersionCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Show protocol and library versions") +} diff --git a/cmd/cometbft/main.go b/cmd/cometbft/main.go new file mode 100644 index 0000000..e52b985 --- /dev/null +++ b/cmd/cometbft/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "os" + "path/filepath" + + cmd "github.com/cometbft/cometbft/cmd/cometbft/commands" + "github.com/cometbft/cometbft/cmd/cometbft/commands/debug" + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cli" + nm "github.com/cometbft/cometbft/node" +) + +func main() { + rootCmd := cmd.RootCmd + rootCmd.AddCommand( + cmd.GenValidatorCmd, + cmd.InitFilesCmd, + cmd.LightCmd, + cmd.ReplayCmd, + cmd.ReplayConsoleCmd, + cmd.ResetAllCmd, + cmd.ResetPrivValidatorCmd, + cmd.ResetStateCmd, + cmd.ShowValidatorCmd, + cmd.TestnetFilesCmd, + cmd.ShowNodeIDCmd, + cmd.ReIndexEventCmd, + cmd.GenNodeKeyCmd, + cmd.VersionCmd, + cmd.RollbackStateCmd, + cmd.CompactGoLevelDBCmd, + cmd.InspectCmd, + debug.DebugCmd, + cli.NewCompletionCmd(rootCmd, true), + ) + + // NOTE: + // Users wishing to: + // * Use an external signer for their validators + // * Supply an in-proc abci app + // * Supply a genesis doc file from another source + // * Provide their own DB implementation + // can copy this file and use something other than the + // DefaultNewNode function + nodeFunc := nm.DefaultNewNode + + // Create & start node + rootCmd.AddCommand(cmd.NewRunNodeCmd(nodeFunc)) + + cmd := cli.PrepareBaseCmd(rootCmd, "CMT", os.ExpandEnv(filepath.Join("$HOME", cfg.DefaultTendermintDir))) + if err := cmd.Execute(); err != nil { + panic(err) + } +} diff --git a/cmd/contract_tests/main.go b/cmd/contract_tests/main.go new file mode 100644 index 0000000..3970ff9 --- /dev/null +++ b/cmd/contract_tests/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "strings" + + "github.com/snikch/goodman/hooks" + "github.com/snikch/goodman/transaction" +) + +func main() { + // This must be compiled beforehand and given to dredd as parameter, in the meantime the server should be running + h := hooks.NewHooks() + server := hooks.NewServer(hooks.NewHooksRunner(h)) + h.BeforeAll(func(t []*transaction.Transaction) { + fmt.Println(t[0].Name) + }) + h.BeforeEach(func(t *transaction.Transaction) { + if strings.HasPrefix(t.Name, "Tx") || + // We need a proper example of evidence to broadcast + strings.HasPrefix(t.Name, "Info > /broadcast_evidence") || + // We need a proper example of path and data + strings.HasPrefix(t.Name, "ABCI > /abci_query") || + // We need to find a way to make a transaction before starting the tests, + // that hash should replace the dummy one in the openapi file + strings.HasPrefix(t.Name, "Info > /tx") { + t.Skip = true + fmt.Printf("%s Has been skipped\n", t.Name) + } + }) + server.Serve() + defer server.Listener.Close() + fmt.Print("FINE") +} diff --git a/cmd/priv_val_server/main.go b/cmd/priv_val_server/main.go new file mode 100644 index 0000000..3abc3bc --- /dev/null +++ b/cmd/priv_val_server/main.go @@ -0,0 +1,70 @@ +package main + +import ( + "flag" + "os" + "time" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + cmtos "github.com/cometbft/cometbft/libs/os" + + "github.com/cometbft/cometbft/privval" +) + +func main() { + var ( + addr = flag.String("addr", ":26659", "Address of client to connect to") + chainID = flag.String("chain-id", "mychain", "chain id") + privValKeyPath = flag.String("priv-key", "", "priv val key file path") + privValStatePath = flag.String("priv-state", "", "priv val state file path") + + logger = log.NewTMLogger( + log.NewSyncWriter(os.Stdout), + ).With("module", "priv_val") + ) + flag.Parse() + + logger.Info( + "Starting private validator", + "addr", *addr, + "chainID", *chainID, + "privKeyPath", *privValKeyPath, + "privStatePath", *privValStatePath, + ) + + pv := privval.LoadFilePV(*privValKeyPath, *privValStatePath) + + var dialer privval.SocketDialer + protocol, address := cmtnet.ProtocolAndAddress(*addr) + switch protocol { + case "unix": + dialer = privval.DialUnixFn(address) + case "tcp": + connTimeout := 3 * time.Second // TODO + dialer = privval.DialTCPFn(address, connTimeout, ed25519.GenPrivKey()) + default: + logger.Error("Unknown protocol", "protocol", protocol) + os.Exit(1) + } + + sd := privval.NewSignerDialerEndpoint(logger, dialer) + ss := privval.NewSignerServer(sd, *chainID, pv) + + err := ss.Start() + if err != nil { + panic(err) + } + + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(logger, func() { + err := ss.Stop() + if err != nil { + panic(err) + } + }) + + // Run forever. + select {} +} diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..c02a43f --- /dev/null +++ b/codecov.yml @@ -0,0 +1,24 @@ +coverage: + precision: 2 + round: down + range: "70...100" + status: + project: + default: + threshold: 20% + patch: off + changes: off + +github_checks: + annotations: false + +comment: false + +ignore: + - "docs" + - "DOCKER" + - "scripts" + - "**/*.pb.go" + - "*.md" + - "*.rst" + - "*.yml" diff --git a/common.mk b/common.mk new file mode 100644 index 0000000..11fe6a7 --- /dev/null +++ b/common.mk @@ -0,0 +1,43 @@ +# This contains Makefile logic that is common to several makefiles + +BUILD_TAGS ?= cometbft + +COMMIT_HASH := $(shell git rev-parse --short HEAD) +LD_FLAGS = -X github.com/cometbft/cometbft/version.TMGitCommitHash=$(COMMIT_HASH) +BUILD_FLAGS = -mod=readonly -ldflags "$(LD_FLAGS)" +# allow users to pass additional flags via the conventional LDFLAGS variable +LD_FLAGS += $(LDFLAGS) + +# handle nostrip +ifeq (,$(findstring nostrip,$(COMETBFT_BUILD_OPTIONS))) + BUILD_FLAGS += -trimpath + LD_FLAGS += -s -w +endif + +# handle race +ifeq (race,$(findstring race,$(COMETBFT_BUILD_OPTIONS))) + CGO_ENABLED=1 + BUILD_FLAGS += -race +endif + +# handle cleveldb +ifeq (cleveldb,$(findstring cleveldb,$(COMETBFT_BUILD_OPTIONS))) + CGO_ENABLED=1 + BUILD_TAGS += cleveldb +endif + +# handle badgerdb +ifeq (badgerdb,$(findstring badgerdb,$(COMETBFT_BUILD_OPTIONS))) + BUILD_TAGS += badgerdb +endif + +# handle rocksdb +ifeq (rocksdb,$(findstring rocksdb,$(COMETBFT_BUILD_OPTIONS))) + CGO_ENABLED=1 + BUILD_TAGS += rocksdb +endif + +# handle boltdb +ifeq (boltdb,$(findstring boltdb,$(COMETBFT_BUILD_OPTIONS))) + BUILD_TAGS += boltdb +endif diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..5d01a3a --- /dev/null +++ b/config/config.go @@ -0,0 +1,1289 @@ +package config + +import ( + "encoding/hex" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "regexp" + "time" + + "github.com/cometbft/cometbft/version" +) + +const ( + // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep + FuzzModeDrop = iota + // FuzzModeDelay is a mode in which we randomly sleep + FuzzModeDelay + + // LogFormatPlain is a format for colored text + LogFormatPlain = "plain" + // LogFormatJSON is a format for json output + LogFormatJSON = "json" + + // DefaultLogLevel defines a default log level as INFO. + DefaultLogLevel = "info" + + DefaultTendermintDir = ".cometbft" + DefaultConfigDir = "config" + DefaultDataDir = "data" + + DefaultConfigFileName = "config.toml" + DefaultGenesisJSONName = "genesis.json" + + DefaultPrivValKeyName = "priv_validator_key.json" + DefaultPrivValStateName = "priv_validator_state.json" + + DefaultNodeKeyName = "node_key.json" + DefaultAddrBookName = "addrbook.json" + + MempoolTypeFlood = "flood" + MempoolTypeNop = "nop" +) + +// NOTE: Most of the structs & relevant comments + the +// default configuration options were used to manually +// generate the config.toml. Please reflect any changes +// made here in the defaultConfigTemplate constant in +// config/toml.go +// NOTE: libs/cli must know to look in the config dir! +var ( + defaultConfigFilePath = filepath.Join(DefaultConfigDir, DefaultConfigFileName) + defaultGenesisJSONPath = filepath.Join(DefaultConfigDir, DefaultGenesisJSONName) + defaultPrivValKeyPath = filepath.Join(DefaultConfigDir, DefaultPrivValKeyName) + defaultPrivValStatePath = filepath.Join(DefaultDataDir, DefaultPrivValStateName) + + defaultNodeKeyPath = filepath.Join(DefaultConfigDir, DefaultNodeKeyName) + defaultAddrBookPath = filepath.Join(DefaultConfigDir, DefaultAddrBookName) + + minSubscriptionBufferSize = 100 + defaultSubscriptionBufferSize = 200 + + // taken from https://semver.org/ + semverRegexp = regexp.MustCompile(`^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`) +) + +// Config defines the top level configuration for a CometBFT node +type Config struct { + // Top level options use an anonymous struct + BaseConfig `mapstructure:",squash"` + + // Options for services + RPC *RPCConfig `mapstructure:"rpc"` + P2P *P2PConfig `mapstructure:"p2p"` + Mempool *MempoolConfig `mapstructure:"mempool"` + StateSync *StateSyncConfig `mapstructure:"statesync"` + BlockSync *BlockSyncConfig `mapstructure:"blocksync"` + Consensus *ConsensusConfig `mapstructure:"consensus"` + Storage *StorageConfig `mapstructure:"storage"` + TxIndex *TxIndexConfig `mapstructure:"tx_index"` + Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"` +} + +// DefaultConfig returns a default configuration for a CometBFT node +func DefaultConfig() *Config { + return &Config{ + BaseConfig: DefaultBaseConfig(), + RPC: DefaultRPCConfig(), + P2P: DefaultP2PConfig(), + Mempool: DefaultMempoolConfig(), + StateSync: DefaultStateSyncConfig(), + BlockSync: DefaultBlockSyncConfig(), + Consensus: DefaultConsensusConfig(), + Storage: DefaultStorageConfig(), + TxIndex: DefaultTxIndexConfig(), + Instrumentation: DefaultInstrumentationConfig(), + } +} + +// TestConfig returns a configuration that can be used for testing +func TestConfig() *Config { + return &Config{ + BaseConfig: TestBaseConfig(), + RPC: TestRPCConfig(), + P2P: TestP2PConfig(), + Mempool: TestMempoolConfig(), + StateSync: TestStateSyncConfig(), + BlockSync: TestBlockSyncConfig(), + Consensus: TestConsensusConfig(), + Storage: TestStorageConfig(), + TxIndex: TestTxIndexConfig(), + Instrumentation: TestInstrumentationConfig(), + } +} + +// SetRoot sets the RootDir for all Config structs +func (cfg *Config) SetRoot(root string) *Config { + cfg.RootDir = root + cfg.RPC.RootDir = root + cfg.P2P.RootDir = root + cfg.Mempool.RootDir = root + cfg.Consensus.RootDir = root + return cfg +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *Config) ValidateBasic() error { + if err := cfg.BaseConfig.ValidateBasic(); err != nil { + return err + } + if err := cfg.RPC.ValidateBasic(); err != nil { + return fmt.Errorf("error in [rpc] section: %w", err) + } + if err := cfg.P2P.ValidateBasic(); err != nil { + return fmt.Errorf("error in [p2p] section: %w", err) + } + if err := cfg.Mempool.ValidateBasic(); err != nil { + return fmt.Errorf("error in [mempool] section: %w", err) + } + if err := cfg.StateSync.ValidateBasic(); err != nil { + return fmt.Errorf("error in [statesync] section: %w", err) + } + if err := cfg.BlockSync.ValidateBasic(); err != nil { + return fmt.Errorf("error in [blocksync] section: %w", err) + } + if err := cfg.Consensus.ValidateBasic(); err != nil { + return fmt.Errorf("error in [consensus] section: %w", err) + } + if err := cfg.Instrumentation.ValidateBasic(); err != nil { + return fmt.Errorf("error in [instrumentation] section: %w", err) + } + if !cfg.Consensus.CreateEmptyBlocks && cfg.Mempool.Type == MempoolTypeNop { + return fmt.Errorf("`nop` mempool does not support create_empty_blocks = false") + } + return nil +} + +// CheckDeprecated returns any deprecation warnings. These are printed to the operator on startup +func (cfg *Config) CheckDeprecated() []string { + var warnings []string + return warnings +} + +//----------------------------------------------------------------------------- +// BaseConfig + +// BaseConfig defines the base configuration for a CometBFT node +type BaseConfig struct { //nolint: maligned + + // The version of the CometBFT binary that created + // or last modified the config file + Version string `mapstructure:"version"` + + // The root directory for all data. + // This should be set in viper so it can unmarshal into this struct + RootDir string `mapstructure:"home"` + + // TCP or UNIX socket address of the ABCI application, + // or the name of an ABCI application compiled in with the CometBFT binary + ProxyApp string `mapstructure:"proxy_app"` + + // A custom human readable name for this node + Moniker string `mapstructure:"moniker"` + + // Database backend: goleveldb | cleveldb | boltdb | rocksdb + // * goleveldb (github.com/syndtr/goleveldb - most popular implementation) + // - pure go + // - stable + // * cleveldb (uses levigo wrapper) + // - fast + // - requires gcc + // - use cleveldb build tag (go build -tags cleveldb) + // * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) + // - EXPERIMENTAL + // - may be faster is some use-cases (random reads - indexer) + // - use boltdb build tag (go build -tags boltdb) + // * rocksdb (uses github.com/tecbot/gorocksdb) + // - EXPERIMENTAL + // - requires gcc + // - use rocksdb build tag (go build -tags rocksdb) + // * badgerdb (uses github.com/dgraph-io/badger) + // - EXPERIMENTAL + // - use badgerdb build tag (go build -tags badgerdb) + DBBackend string `mapstructure:"db_backend"` + + // Database directory + DBPath string `mapstructure:"db_dir"` + + // Output level for logging + LogLevel string `mapstructure:"log_level"` + + // Output format: 'plain' (colored text) or 'json' + LogFormat string `mapstructure:"log_format"` + + // Path to the JSON file containing the initial validator set and other meta data + Genesis string `mapstructure:"genesis_file"` + + // Path to the JSON file containing the private key to use as a validator in the consensus protocol + PrivValidatorKey string `mapstructure:"priv_validator_key_file"` + + // Path to the JSON file containing the last sign state of a validator + PrivValidatorState string `mapstructure:"priv_validator_state_file"` + + // TCP or UNIX socket address for CometBFT to listen on for + // connections from an external PrivValidator process + PrivValidatorListenAddr string `mapstructure:"priv_validator_laddr"` + + // A JSON file containing the private key to use for p2p authenticated encryption + NodeKey string `mapstructure:"node_key_file"` + + // Mechanism to connect to the ABCI application: socket | grpc + ABCI string `mapstructure:"abci"` + + // If true, query the ABCI app on connecting to a new peer + // so the app can decide if we should keep the connection or not + FilterPeers bool `mapstructure:"filter_peers"` // false +} + +// DefaultBaseConfig returns a default base configuration for a CometBFT node +func DefaultBaseConfig() BaseConfig { + return BaseConfig{ + Version: version.TMCoreSemVer, + Genesis: defaultGenesisJSONPath, + PrivValidatorKey: defaultPrivValKeyPath, + PrivValidatorState: defaultPrivValStatePath, + NodeKey: defaultNodeKeyPath, + Moniker: defaultMoniker, + ProxyApp: "tcp://127.0.0.1:26658", + ABCI: "socket", + LogLevel: DefaultLogLevel, + LogFormat: LogFormatPlain, + FilterPeers: false, + DBBackend: "goleveldb", + DBPath: DefaultDataDir, + } +} + +// TestBaseConfig returns a base configuration for testing a CometBFT node +func TestBaseConfig() BaseConfig { + cfg := DefaultBaseConfig() + cfg.ProxyApp = "kvstore" + cfg.DBBackend = "memdb" + return cfg +} + +// GenesisFile returns the full path to the genesis.json file +func (cfg BaseConfig) GenesisFile() string { + return rootify(cfg.Genesis, cfg.RootDir) +} + +// PrivValidatorKeyFile returns the full path to the priv_validator_key.json file +func (cfg BaseConfig) PrivValidatorKeyFile() string { + return rootify(cfg.PrivValidatorKey, cfg.RootDir) +} + +// PrivValidatorFile returns the full path to the priv_validator_state.json file +func (cfg BaseConfig) PrivValidatorStateFile() string { + return rootify(cfg.PrivValidatorState, cfg.RootDir) +} + +// NodeKeyFile returns the full path to the node_key.json file +func (cfg BaseConfig) NodeKeyFile() string { + return rootify(cfg.NodeKey, cfg.RootDir) +} + +// DBDir returns the full path to the database directory +func (cfg BaseConfig) DBDir() string { + return rootify(cfg.DBPath, cfg.RootDir) +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg BaseConfig) ValidateBasic() error { + // version on old config files aren't set so we can't expect it + // always to exist + if cfg.Version != "" && !semverRegexp.MatchString(cfg.Version) { + return fmt.Errorf("invalid version string: %s", cfg.Version) + } + + switch cfg.LogFormat { + case LogFormatPlain, LogFormatJSON: + default: + return errors.New("unknown log_format (must be 'plain' or 'json')") + } + return nil +} + +//----------------------------------------------------------------------------- +// RPCConfig + +// RPCConfig defines the configuration options for the CometBFT RPC server +type RPCConfig struct { + RootDir string `mapstructure:"home"` + + // TCP or UNIX socket address for the RPC server to listen on + ListenAddress string `mapstructure:"laddr"` + + // A list of origins a cross-domain request can be executed from. + // If the special '*' value is present in the list, all origins will be allowed. + // An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com). + // Only one wildcard can be used per origin. + CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"` + + // A list of methods the client is allowed to use with cross-domain requests. + CORSAllowedMethods []string `mapstructure:"cors_allowed_methods"` + + // A list of non simple headers the client is allowed to use with cross-domain requests. + CORSAllowedHeaders []string `mapstructure:"cors_allowed_headers"` + + // TCP or UNIX socket address for the gRPC server to listen on + // NOTE: This server only supports /broadcast_tx_commit + GRPCListenAddress string `mapstructure:"grpc_laddr"` + + // Maximum number of simultaneous connections. + // Does not include RPC (HTTP&WebSocket) connections. See max_open_connections + // If you want to accept a larger number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"` + + // Activate unsafe RPC commands like /dial_persistent_peers and /unsafe_flush_mempool + Unsafe bool `mapstructure:"unsafe"` + + // Maximum number of simultaneous connections (including WebSocket). + // Does not include gRPC connections. See grpc_max_open_connections + // If you want to accept a larger number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} + // 1024 - 40 - 10 - 50 = 924 = ~900 + MaxOpenConnections int `mapstructure:"max_open_connections"` + + // Maximum number of unique clientIDs that can /subscribe + // If you're using /broadcast_tx_commit, set to the estimated maximum number + // of broadcast_tx_commit calls per block. + MaxSubscriptionClients int `mapstructure:"max_subscription_clients"` + + // Maximum number of unique queries a given client can /subscribe to + // If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set + // to the estimated maximum number of broadcast_tx_commit calls per block. + MaxSubscriptionsPerClient int `mapstructure:"max_subscriptions_per_client"` + + // The number of events that can be buffered per subscription before + // returning `ErrOutOfCapacity`. + SubscriptionBufferSize int `mapstructure:"experimental_subscription_buffer_size"` + + // The maximum number of responses that can be buffered per WebSocket + // client. If clients cannot read from the WebSocket endpoint fast enough, + // they will be disconnected, so increasing this parameter may reduce the + // chances of them being disconnected (but will cause the node to use more + // memory). + // + // Must be at least the same as `SubscriptionBufferSize`, otherwise + // connections may be dropped unnecessarily. + WebSocketWriteBufferSize int `mapstructure:"experimental_websocket_write_buffer_size"` + + // If a WebSocket client cannot read fast enough, at present we may + // silently drop events instead of generating an error or disconnecting the + // client. + // + // Enabling this parameter will cause the WebSocket connection to be closed + // instead if it cannot read fast enough, allowing for greater + // predictability in subscription behavior. + CloseOnSlowClient bool `mapstructure:"experimental_close_on_slow_client"` + + // How long to wait for a tx to be committed during /broadcast_tx_commit + // WARNING: Using a value larger than 10s will result in increasing the + // global HTTP write timeout, which applies to all connections and endpoints. + // See https://github.com/tendermint/tendermint/issues/3435 + TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout_broadcast_tx_commit"` + + // Maximum number of requests that can be sent in a batch + // https://www.jsonrpc.org/specification#batch + MaxRequestBatchSize int `mapstructure:"max_request_batch_size"` + + // Maximum size of request body, in bytes + MaxBodyBytes int64 `mapstructure:"max_body_bytes"` + + // Maximum size of request header, in bytes + MaxHeaderBytes int `mapstructure:"max_header_bytes"` + + // The path to a file containing certificate that is used to create the HTTPS server. + // Might be either absolute path or path related to CometBFT's config directory. + // + // If the certificate is signed by a certificate authority, + // the certFile should be the concatenation of the server's certificate, any intermediates, + // and the CA's certificate. + // + // NOTE: both tls_cert_file and tls_key_file must be present for CometBFT to create HTTPS server. + // Otherwise, HTTP server is run. + TLSCertFile string `mapstructure:"tls_cert_file"` + + // The path to a file containing matching private key that is used to create the HTTPS server. + // Might be either absolute path or path related to CometBFT's config directory. + // + // NOTE: both tls_cert_file and tls_key_file must be present for CometBFT to create HTTPS server. + // Otherwise, HTTP server is run. + TLSKeyFile string `mapstructure:"tls_key_file"` + + // pprof listen address (https://golang.org/pkg/net/http/pprof) + // FIXME: This should be moved under the instrumentation section + PprofListenAddress string `mapstructure:"pprof_laddr"` +} + +// DefaultRPCConfig returns a default configuration for the RPC server +func DefaultRPCConfig() *RPCConfig { + return &RPCConfig{ + ListenAddress: "tcp://127.0.0.1:26657", + CORSAllowedOrigins: []string{}, + CORSAllowedMethods: []string{http.MethodHead, http.MethodGet, http.MethodPost}, + CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"}, + GRPCListenAddress: "", + GRPCMaxOpenConnections: 900, + + Unsafe: false, + MaxOpenConnections: 900, + + MaxSubscriptionClients: 100, + MaxSubscriptionsPerClient: 5, + SubscriptionBufferSize: defaultSubscriptionBufferSize, + TimeoutBroadcastTxCommit: 10 * time.Second, + WebSocketWriteBufferSize: defaultSubscriptionBufferSize, + + MaxRequestBatchSize: 10, // maximum requests in a JSON-RPC batch request + MaxBodyBytes: int64(1000000), // 1MB + MaxHeaderBytes: 1 << 20, // same as the net/http default + + TLSCertFile: "", + TLSKeyFile: "", + } +} + +// TestRPCConfig returns a configuration for testing the RPC server +func TestRPCConfig() *RPCConfig { + cfg := DefaultRPCConfig() + cfg.ListenAddress = "tcp://127.0.0.1:36657" + cfg.GRPCListenAddress = "tcp://127.0.0.1:36658" + cfg.Unsafe = true + return cfg +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *RPCConfig) ValidateBasic() error { + if cfg.GRPCMaxOpenConnections < 0 { + return errors.New("grpc_max_open_connections can't be negative") + } + if cfg.MaxOpenConnections < 0 { + return errors.New("max_open_connections can't be negative") + } + if cfg.MaxSubscriptionClients < 0 { + return errors.New("max_subscription_clients can't be negative") + } + if cfg.MaxSubscriptionsPerClient < 0 { + return errors.New("max_subscriptions_per_client can't be negative") + } + if cfg.SubscriptionBufferSize < minSubscriptionBufferSize { + return fmt.Errorf( + "experimental_subscription_buffer_size must be >= %d", + minSubscriptionBufferSize, + ) + } + if cfg.WebSocketWriteBufferSize < cfg.SubscriptionBufferSize { + return fmt.Errorf( + "experimental_websocket_write_buffer_size must be >= experimental_subscription_buffer_size (%d)", + cfg.SubscriptionBufferSize, + ) + } + if cfg.TimeoutBroadcastTxCommit < 0 { + return errors.New("timeout_broadcast_tx_commit can't be negative") + } + if cfg.MaxRequestBatchSize < 0 { + return errors.New("max_request_batch_size can't be negative") + } + if cfg.MaxBodyBytes < 0 { + return errors.New("max_body_bytes can't be negative") + } + if cfg.MaxHeaderBytes < 0 { + return errors.New("max_header_bytes can't be negative") + } + return nil +} + +// IsCorsEnabled returns true if cross-origin resource sharing is enabled. +func (cfg *RPCConfig) IsCorsEnabled() bool { + return len(cfg.CORSAllowedOrigins) != 0 +} + +func (cfg *RPCConfig) IsPprofEnabled() bool { + return len(cfg.PprofListenAddress) != 0 +} + +func (cfg RPCConfig) KeyFile() string { + path := cfg.TLSKeyFile + if filepath.IsAbs(path) { + return path + } + return rootify(filepath.Join(DefaultConfigDir, path), cfg.RootDir) +} + +func (cfg RPCConfig) CertFile() string { + path := cfg.TLSCertFile + if filepath.IsAbs(path) { + return path + } + return rootify(filepath.Join(DefaultConfigDir, path), cfg.RootDir) +} + +func (cfg RPCConfig) IsTLSEnabled() bool { + return cfg.TLSCertFile != "" && cfg.TLSKeyFile != "" +} + +//----------------------------------------------------------------------------- +// P2PConfig + +// P2PConfig defines the configuration options for the CometBFT peer-to-peer networking layer +type P2PConfig struct { //nolint: maligned + RootDir string `mapstructure:"home"` + + // Address to listen for incoming connections + ListenAddress string `mapstructure:"laddr"` + + // Address to advertise to peers for them to dial + ExternalAddress string `mapstructure:"external_address"` + + // Comma separated list of seed nodes to connect to + // We only use these if we can’t connect to peers in the addrbook + Seeds string `mapstructure:"seeds"` + + // Comma separated list of nodes to keep persistent connections to + PersistentPeers string `mapstructure:"persistent_peers"` + + // Path to address book + AddrBook string `mapstructure:"addr_book_file"` + + // Set true for strict address routability rules + // Set false for private or local networks + AddrBookStrict bool `mapstructure:"addr_book_strict"` + + // Maximum number of inbound peers + MaxNumInboundPeers int `mapstructure:"max_num_inbound_peers"` + + // Maximum number of outbound peers to connect to, excluding persistent peers + MaxNumOutboundPeers int `mapstructure:"max_num_outbound_peers"` + + // List of node IDs, to which a connection will be (re)established ignoring any existing limits + UnconditionalPeerIDs string `mapstructure:"unconditional_peer_ids"` + + // Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) + PersistentPeersMaxDialPeriod time.Duration `mapstructure:"persistent_peers_max_dial_period"` + + // Time to wait before flushing messages out on the connection + FlushThrottleTimeout time.Duration `mapstructure:"flush_throttle_timeout"` + + // Maximum size of a message packet payload, in bytes + MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"` + + // Rate at which packets can be sent, in bytes/second + SendRate int64 `mapstructure:"send_rate"` + + // Rate at which packets can be received, in bytes/second + RecvRate int64 `mapstructure:"recv_rate"` + + // Set true to enable the peer-exchange reactor + PexReactor bool `mapstructure:"pex"` + + // Seed mode, in which node constantly crawls the network and looks for + // peers. If another node asks it for addresses, it responds and disconnects. + // + // Does not work if the peer-exchange reactor is disabled. + SeedMode bool `mapstructure:"seed_mode"` + + // Comma separated list of peer IDs to keep private (will not be gossiped to + // other peers) + PrivatePeerIDs string `mapstructure:"private_peer_ids"` + + // Toggle to disable guard against peers connecting from the same ip. + AllowDuplicateIP bool `mapstructure:"allow_duplicate_ip"` + + // Peer connection configuration. + HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"` + DialTimeout time.Duration `mapstructure:"dial_timeout"` + + // Testing params. + // Force dial to fail + TestDialFail bool `mapstructure:"test_dial_fail"` + // Fuzz connection + TestFuzz bool `mapstructure:"test_fuzz"` + TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"` +} + +// DefaultP2PConfig returns a default configuration for the peer-to-peer layer +func DefaultP2PConfig() *P2PConfig { + return &P2PConfig{ + ListenAddress: "tcp://0.0.0.0:26656", + ExternalAddress: "", + AddrBook: defaultAddrBookPath, + AddrBookStrict: true, + MaxNumInboundPeers: 40, + MaxNumOutboundPeers: 10, + PersistentPeersMaxDialPeriod: 0 * time.Second, + FlushThrottleTimeout: 100 * time.Millisecond, + MaxPacketMsgPayloadSize: 1024, // 1 kB + SendRate: 5120000, // 5 mB/s + RecvRate: 5120000, // 5 mB/s + PexReactor: true, + SeedMode: false, + AllowDuplicateIP: false, + HandshakeTimeout: 20 * time.Second, + DialTimeout: 3 * time.Second, + TestDialFail: false, + TestFuzz: false, + TestFuzzConfig: DefaultFuzzConnConfig(), + } +} + +// TestP2PConfig returns a configuration for testing the peer-to-peer layer +func TestP2PConfig() *P2PConfig { + cfg := DefaultP2PConfig() + cfg.ListenAddress = "tcp://127.0.0.1:36656" + cfg.FlushThrottleTimeout = 10 * time.Millisecond + cfg.AllowDuplicateIP = true + return cfg +} + +// AddrBookFile returns the full path to the address book +func (cfg *P2PConfig) AddrBookFile() string { + return rootify(cfg.AddrBook, cfg.RootDir) +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *P2PConfig) ValidateBasic() error { + if cfg.MaxNumInboundPeers < 0 { + return errors.New("max_num_inbound_peers can't be negative") + } + if cfg.MaxNumOutboundPeers < 0 { + return errors.New("max_num_outbound_peers can't be negative") + } + if cfg.FlushThrottleTimeout < 0 { + return errors.New("flush_throttle_timeout can't be negative") + } + if cfg.PersistentPeersMaxDialPeriod < 0 { + return errors.New("persistent_peers_max_dial_period can't be negative") + } + if cfg.MaxPacketMsgPayloadSize < 0 { + return errors.New("max_packet_msg_payload_size can't be negative") + } + if cfg.SendRate < 0 { + return errors.New("send_rate can't be negative") + } + if cfg.RecvRate < 0 { + return errors.New("recv_rate can't be negative") + } + return nil +} + +// FuzzConnConfig is a FuzzedConnection configuration. +type FuzzConnConfig struct { + Mode int + MaxDelay time.Duration + ProbDropRW float64 + ProbDropConn float64 + ProbSleep float64 +} + +// DefaultFuzzConnConfig returns the default config. +func DefaultFuzzConnConfig() *FuzzConnConfig { + return &FuzzConnConfig{ + Mode: FuzzModeDrop, + MaxDelay: 3 * time.Second, + ProbDropRW: 0.2, + ProbDropConn: 0.00, + ProbSleep: 0.00, + } +} + +//----------------------------------------------------------------------------- +// MempoolConfig + +// MempoolConfig defines the configuration options for the CometBFT mempool +// +// Note: Until v0.37 there was a `Version` field to select which implementation +// of the mempool to use. Two versions used to exist: the current, default +// implementation (previously called v0), and a prioritized mempool (v1), which +// was removed (see https://github.com/cometbft/cometbft/issues/260). +type MempoolConfig struct { + // The type of mempool for this node to use. + // + // Possible types: + // - "flood" : concurrent linked list mempool with flooding gossip protocol + // (default) + // - "nop" : nop-mempool (short for no operation; the ABCI app is + // responsible for storing, disseminating and proposing txs). + // "create_empty_blocks=false" is not supported. + Type string `mapstructure:"type"` + // RootDir is the root directory for all data. This should be configured via + // the $CMTHOME env variable or --home cmd flag rather than overriding this + // struct field. + RootDir string `mapstructure:"home"` + // Recheck (default: true) defines whether CometBFT should recheck the + // validity for all remaining transaction in the mempool after a block. + // Since a block affects the application state, some transactions in the + // mempool may become invalid. If this does not apply to your application, + // you can disable rechecking. + Recheck bool `mapstructure:"recheck"` + // RecheckTimeout is the time the application has during the rechecking process + // to return CheckTx responses, once all requests have been sent. Responses that + // arrive after the timeout expires are discarded. It only applies to + // non-local ABCI clients and when recheck is enabled. + // + // The ideal value will strongly depend on the application. It could roughly be estimated as the + // average size of the mempool multiplied by the average time it takes the application to validate one + // transaction. We consider that the ABCI application runs in the same location as the CometBFT binary + // so that the recheck duration is not affected by network delays when making requests and receiving responses. + RecheckTimeout time.Duration `mapstructure:"recheck_timeout"` + // Broadcast (default: true) defines whether the mempool should relay + // transactions to other peers. Setting this to false will stop the mempool + // from relaying transactions to other peers until they are included in a + // block. In other words, if Broadcast is disabled, only the peer you send + // the tx to will see it until it is included in a block. + Broadcast bool `mapstructure:"broadcast"` + // WalPath (default: "") configures the location of the Write Ahead Log + // (WAL) for the mempool. The WAL is disabled by default. To enable, set + // WalPath to where you want the WAL to be written (e.g. + // "data/mempool.wal"). + WalPath string `mapstructure:"wal_dir"` + // Maximum number of transactions in the mempool + Size int `mapstructure:"size"` + // Limit the total size of all txs in the mempool. + // This only accounts for raw transactions (e.g. given 1MB transactions and + // max_txs_bytes=5MB, mempool will only accept 5 transactions). + MaxTxsBytes int64 `mapstructure:"max_txs_bytes"` + // Size of the cache (used to filter transactions we saw earlier) in transactions + CacheSize int `mapstructure:"cache_size"` + // Do not remove invalid transactions from the cache (default: false) + // Set to true if it's not possible for any invalid transaction to become + // valid again in the future. + KeepInvalidTxsInCache bool `mapstructure:"keep-invalid-txs-in-cache"` + // Maximum size of a single transaction + // NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. + MaxTxBytes int `mapstructure:"max_tx_bytes"` + // Maximum size of a batch of transactions to send to a peer + // Including space needed by encoding (one varint per transaction). + // XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 + MaxBatchBytes int `mapstructure:"max_batch_bytes"` + // Experimental parameters to limit gossiping txs to up to the specified number of peers. + // We use two independent upper values for persistent and non-persistent peers. + // Unconditional peers are not affected by this feature. + // If we are connected to more than the specified number of persistent peers, only send txs to + // ExperimentalMaxGossipConnectionsToPersistentPeers of them. If one of those + // persistent peers disconnects, activate another persistent peer. + // Similarly for non-persistent peers, with an upper limit of + // ExperimentalMaxGossipConnectionsToNonPersistentPeers. + // If set to 0, the feature is disabled for the corresponding group of peers, that is, the + // number of active connections to that group of peers is not bounded. + // For non-persistent peers, if enabled, a value of 10 is recommended based on experimental + // performance results using the default P2P configuration. + ExperimentalMaxGossipConnectionsToPersistentPeers int `mapstructure:"experimental_max_gossip_connections_to_persistent_peers"` + ExperimentalMaxGossipConnectionsToNonPersistentPeers int `mapstructure:"experimental_max_gossip_connections_to_non_persistent_peers"` +} + +// DefaultMempoolConfig returns a default configuration for the CometBFT mempool +func DefaultMempoolConfig() *MempoolConfig { + return &MempoolConfig{ + Type: MempoolTypeFlood, + Recheck: true, + RecheckTimeout: 1000 * time.Millisecond, + Broadcast: true, + WalPath: "", + // Each signature verification takes .5ms, Size reduced until we implement + // ABCI Recheck + Size: 5000, + MaxTxsBytes: 1024 * 1024 * 1024, // 1GB + CacheSize: 10000, + MaxTxBytes: 1024 * 1024, // 1MB + ExperimentalMaxGossipConnectionsToNonPersistentPeers: 0, + ExperimentalMaxGossipConnectionsToPersistentPeers: 0, + } +} + +// TestMempoolConfig returns a configuration for testing the CometBFT mempool +func TestMempoolConfig() *MempoolConfig { + cfg := DefaultMempoolConfig() + cfg.CacheSize = 1000 + return cfg +} + +// WalDir returns the full path to the mempool's write-ahead log +func (cfg *MempoolConfig) WalDir() string { + return rootify(cfg.WalPath, cfg.RootDir) +} + +// WalEnabled returns true if the WAL is enabled. +func (cfg *MempoolConfig) WalEnabled() bool { + return cfg.WalPath != "" +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *MempoolConfig) ValidateBasic() error { + switch cfg.Type { + case MempoolTypeFlood, MempoolTypeNop: + case "": // allow empty string to be backwards compatible + default: + return fmt.Errorf("unknown mempool type: %q", cfg.Type) + } + if cfg.Size < 0 { + return errors.New("size can't be negative") + } + if cfg.MaxTxsBytes < 0 { + return errors.New("max_txs_bytes can't be negative") + } + if cfg.CacheSize < 0 { + return errors.New("cache_size can't be negative") + } + if cfg.MaxTxBytes < 0 { + return errors.New("max_tx_bytes can't be negative") + } + if cfg.ExperimentalMaxGossipConnectionsToPersistentPeers < 0 { + return errors.New("experimental_max_gossip_connections_to_persistent_peers can't be negative") + } + if cfg.ExperimentalMaxGossipConnectionsToNonPersistentPeers < 0 { + return errors.New("experimental_max_gossip_connections_to_non_persistent_peers can't be negative") + } + return nil +} + +//----------------------------------------------------------------------------- +// StateSyncConfig + +// StateSyncConfig defines the configuration for the CometBFT state sync service +type StateSyncConfig struct { + Enable bool `mapstructure:"enable"` + TempDir string `mapstructure:"temp_dir"` + RPCServers []string `mapstructure:"rpc_servers"` + TrustPeriod time.Duration `mapstructure:"trust_period"` + TrustHeight int64 `mapstructure:"trust_height"` + TrustHash string `mapstructure:"trust_hash"` + DiscoveryTime time.Duration `mapstructure:"discovery_time"` + ChunkRequestTimeout time.Duration `mapstructure:"chunk_request_timeout"` + ChunkFetchers int32 `mapstructure:"chunk_fetchers"` + MaxSnapshotChunks uint32 `mapstructure:"max_snapshot_chunks"` +} + +func (cfg *StateSyncConfig) TrustHashBytes() []byte { + // validated in ValidateBasic, so we can safely panic here + bytes, err := hex.DecodeString(cfg.TrustHash) + if err != nil { + panic(err) + } + return bytes +} + +// DefaultStateSyncConfig returns a default configuration for the state sync service +func DefaultStateSyncConfig() *StateSyncConfig { + return &StateSyncConfig{ + TrustPeriod: 168 * time.Hour, + DiscoveryTime: 15 * time.Second, + ChunkRequestTimeout: 10 * time.Second, + ChunkFetchers: 4, + MaxSnapshotChunks: 100000, + } +} + +// TestStateSyncConfig returns a default configuration for the state sync service +func TestStateSyncConfig() *StateSyncConfig { + return DefaultStateSyncConfig() +} + +// ValidateBasic performs basic validation. +func (cfg *StateSyncConfig) ValidateBasic() error { + if cfg.Enable { + if len(cfg.RPCServers) == 0 { + return errors.New("rpc_servers is required") + } + + if len(cfg.RPCServers) < 2 { + return errors.New("at least two rpc_servers entries is required") + } + + for _, server := range cfg.RPCServers { + if len(server) == 0 { + return errors.New("found empty rpc_servers entry") + } + } + + if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second { + return errors.New("discovery time must be 0s or greater than five seconds") + } + + if cfg.TrustPeriod <= 0 { + return errors.New("trusted_period is required") + } + + if cfg.TrustHeight <= 0 { + return errors.New("trusted_height is required") + } + + if len(cfg.TrustHash) == 0 { + return errors.New("trusted_hash is required") + } + + _, err := hex.DecodeString(cfg.TrustHash) + if err != nil { + return fmt.Errorf("invalid trusted_hash: %w", err) + } + + if cfg.ChunkRequestTimeout < 5*time.Second { + return errors.New("chunk_request_timeout must be at least 5 seconds") + } + + if cfg.ChunkFetchers <= 0 { + return errors.New("chunk_fetchers is required") + } + + if cfg.MaxSnapshotChunks == 0 { + return errors.New("max_snapshot_chunks is required") + } + } + + return nil +} + +//----------------------------------------------------------------------------- +// BlockSyncConfig + +// BlockSyncConfig (formerly known as FastSync) defines the configuration for the CometBFT block sync service +type BlockSyncConfig struct { + Version string `mapstructure:"version"` +} + +// DefaultBlockSyncConfig returns a default configuration for the block sync service +func DefaultBlockSyncConfig() *BlockSyncConfig { + return &BlockSyncConfig{ + Version: "v0", + } +} + +// TestBlockSyncConfig returns a default configuration for the block sync. +func TestBlockSyncConfig() *BlockSyncConfig { + return DefaultBlockSyncConfig() +} + +// ValidateBasic performs basic validation. +func (cfg *BlockSyncConfig) ValidateBasic() error { + switch cfg.Version { + case "v0": + return nil + case "v1", "v2": + return fmt.Errorf("blocksync version %s has been deprecated. Please use v0 instead", cfg.Version) + default: + return fmt.Errorf("unknown blocksync version %s", cfg.Version) + } +} + +//----------------------------------------------------------------------------- +// ConsensusConfig + +// ConsensusConfig defines the configuration for the Tendermint consensus algorithm, adopted by CometBFT, +// including timeouts and details about the WAL and the block structure. +type ConsensusConfig struct { + RootDir string `mapstructure:"home"` + WalPath string `mapstructure:"wal_file"` + walFile string // overrides WalPath if set + + // How long we wait for a proposal block before prevoting nil + TimeoutPropose time.Duration `mapstructure:"timeout_propose"` + // How much timeout_propose increases with each round + TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"` + // How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) + TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"` + // How much the timeout_prevote increases with each round + TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"` + // How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) + TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"` + // How much the timeout_precommit increases with each round + TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"` + // How long we wait after committing a block, before starting on the new + // height (this gives us a chance to receive some more precommits, even + // though we already have +2/3). + // NOTE: when modifying, make sure to update time_iota_ms genesis parameter + TimeoutCommit time.Duration `mapstructure:"timeout_commit"` + + // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) + SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` + + // EmptyBlocks mode and possible interval between empty blocks + CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"` + CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"` + + // Reactor sleep duration parameters + PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"` + PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"` + + DoubleSignCheckHeight int64 `mapstructure:"double_sign_check_height"` +} + +// DefaultConsensusConfig returns a default configuration for the consensus service +func DefaultConsensusConfig() *ConsensusConfig { + return &ConsensusConfig{ + WalPath: filepath.Join(DefaultDataDir, "cs.wal", "wal"), + TimeoutPropose: 3000 * time.Millisecond, + TimeoutProposeDelta: 500 * time.Millisecond, + TimeoutPrevote: 1000 * time.Millisecond, + TimeoutPrevoteDelta: 500 * time.Millisecond, + TimeoutPrecommit: 1000 * time.Millisecond, + TimeoutPrecommitDelta: 500 * time.Millisecond, + TimeoutCommit: 1000 * time.Millisecond, + SkipTimeoutCommit: false, + CreateEmptyBlocks: true, + CreateEmptyBlocksInterval: 0 * time.Second, + PeerGossipSleepDuration: 100 * time.Millisecond, + PeerQueryMaj23SleepDuration: 2000 * time.Millisecond, + DoubleSignCheckHeight: int64(0), + } +} + +// TestConsensusConfig returns a configuration for testing the consensus service +func TestConsensusConfig() *ConsensusConfig { + cfg := DefaultConsensusConfig() + cfg.TimeoutPropose = 40 * time.Millisecond + cfg.TimeoutProposeDelta = 1 * time.Millisecond + cfg.TimeoutPrevote = 10 * time.Millisecond + cfg.TimeoutPrevoteDelta = 1 * time.Millisecond + cfg.TimeoutPrecommit = 10 * time.Millisecond + cfg.TimeoutPrecommitDelta = 1 * time.Millisecond + // NOTE: when modifying, make sure to update time_iota_ms (testGenesisFmt) in toml.go + cfg.TimeoutCommit = 10 * time.Millisecond + cfg.SkipTimeoutCommit = true + cfg.PeerGossipSleepDuration = 5 * time.Millisecond + cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond + cfg.DoubleSignCheckHeight = int64(0) + return cfg +} + +// WaitForTxs returns true if the consensus should wait for transactions before entering the propose step +func (cfg *ConsensusConfig) WaitForTxs() bool { + return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0 +} + +// Propose returns the amount of time to wait for a proposal +func (cfg *ConsensusConfig) Propose(round int32) time.Duration { + return time.Duration( + cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round), + ) * time.Nanosecond +} + +// Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes +func (cfg *ConsensusConfig) Prevote(round int32) time.Duration { + return time.Duration( + cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round), + ) * time.Nanosecond +} + +// Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits +func (cfg *ConsensusConfig) Precommit(round int32) time.Duration { + return time.Duration( + cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round), + ) * time.Nanosecond +} + +// Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits +// for a single block (ie. a commit). +func (cfg *ConsensusConfig) Commit(t time.Time) time.Time { + return t.Add(cfg.TimeoutCommit) +} + +// WalFile returns the full path to the write-ahead log file +func (cfg *ConsensusConfig) WalFile() string { + if cfg.walFile != "" { + return cfg.walFile + } + return rootify(cfg.WalPath, cfg.RootDir) +} + +// SetWalFile sets the path to the write-ahead log file +func (cfg *ConsensusConfig) SetWalFile(walFile string) { + cfg.walFile = walFile +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *ConsensusConfig) ValidateBasic() error { + if cfg.TimeoutPropose < 0 { + return errors.New("timeout_propose can't be negative") + } + if cfg.TimeoutProposeDelta < 0 { + return errors.New("timeout_propose_delta can't be negative") + } + if cfg.TimeoutPrevote < 0 { + return errors.New("timeout_prevote can't be negative") + } + if cfg.TimeoutPrevoteDelta < 0 { + return errors.New("timeout_prevote_delta can't be negative") + } + if cfg.TimeoutPrecommit < 0 { + return errors.New("timeout_precommit can't be negative") + } + if cfg.TimeoutPrecommitDelta < 0 { + return errors.New("timeout_precommit_delta can't be negative") + } + if cfg.TimeoutCommit < 0 { + return errors.New("timeout_commit can't be negative") + } + if cfg.CreateEmptyBlocksInterval < 0 { + return errors.New("create_empty_blocks_interval can't be negative") + } + if cfg.PeerGossipSleepDuration < 0 { + return errors.New("peer_gossip_sleep_duration can't be negative") + } + if cfg.PeerQueryMaj23SleepDuration < 0 { + return errors.New("peer_query_maj23_sleep_duration can't be negative") + } + if cfg.DoubleSignCheckHeight < 0 { + return errors.New("double_sign_check_height can't be negative") + } + return nil +} + +//----------------------------------------------------------------------------- +// StorageConfig + +// StorageConfig allows more fine-grained control over certain storage-related +// behavior. +type StorageConfig struct { + // Set to false to ensure ABCI responses are persisted. ABCI responses are + // required for `/block_results` RPC queries, and to reindex events in the + // command-line tool. + DiscardABCIResponses bool `mapstructure:"discard_abci_responses"` +} + +// DefaultStorageConfig returns the default configuration options relating to +// CometBFT storage optimization. +func DefaultStorageConfig() *StorageConfig { + return &StorageConfig{ + DiscardABCIResponses: false, + } +} + +// TestStorageConfig returns storage configuration that can be used for +// testing. +func TestStorageConfig() *StorageConfig { + return &StorageConfig{ + DiscardABCIResponses: false, + } +} + +// ----------------------------------------------------------------------------- +// TxIndexConfig +// Remember that Event has the following structure: +// type: [ +// +// key: value, +// ... +// +// ] +// +// CompositeKeys are constructed by `type.key` +// TxIndexConfig defines the configuration for the transaction indexer, +// including composite keys to index. +type TxIndexConfig struct { + // What indexer to use for transactions + // + // Options: + // 1) "null" + // 2) "kv" (default) - the simplest possible indexer, + // backed by key-value storage (defaults to levelDB; see DBBackend). + // 3) "psql" - the indexer services backed by PostgreSQL. + Indexer string `mapstructure:"indexer"` + + // The PostgreSQL connection configuration, the connection format: + // postgresql://:@:/? + PsqlConn string `mapstructure:"psql-conn"` +} + +// DefaultTxIndexConfig returns a default configuration for the transaction indexer. +func DefaultTxIndexConfig() *TxIndexConfig { + return &TxIndexConfig{ + Indexer: "kv", + } +} + +// TestTxIndexConfig returns a default configuration for the transaction indexer. +func TestTxIndexConfig() *TxIndexConfig { + return DefaultTxIndexConfig() +} + +//----------------------------------------------------------------------------- +// InstrumentationConfig + +// InstrumentationConfig defines the configuration for metrics reporting. +type InstrumentationConfig struct { + // When true, Prometheus metrics are served under /metrics on + // PrometheusListenAddr. + // Check out the documentation for the list of available metrics. + Prometheus bool `mapstructure:"prometheus"` + + // Address to listen for Prometheus collector(s) connections. + PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"` + + // Maximum number of simultaneous connections. + // If you want to accept a larger number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + MaxOpenConnections int `mapstructure:"max_open_connections"` + + // Instrumentation namespace. + Namespace string `mapstructure:"namespace"` +} + +// DefaultInstrumentationConfig returns a default configuration for metrics +// reporting. +func DefaultInstrumentationConfig() *InstrumentationConfig { + return &InstrumentationConfig{ + Prometheus: false, + PrometheusListenAddr: ":26660", + MaxOpenConnections: 3, + Namespace: "cometbft", + } +} + +// TestInstrumentationConfig returns a default configuration for metrics +// reporting. +func TestInstrumentationConfig() *InstrumentationConfig { + return DefaultInstrumentationConfig() +} + +// ValidateBasic performs basic validation (checking param bounds, etc.) and +// returns an error if any check fails. +func (cfg *InstrumentationConfig) ValidateBasic() error { + if cfg.MaxOpenConnections < 0 { + return errors.New("max_open_connections can't be negative") + } + return nil +} + +func (cfg *InstrumentationConfig) IsPrometheusEnabled() bool { + return cfg.Prometheus && cfg.PrometheusListenAddr != "" +} + +//----------------------------------------------------------------------------- +// Utils + +// helper function to make config creation independent of root dir +func rootify(path, root string) string { + if filepath.IsAbs(path) { + return path + } + return filepath.Join(root, path) +} + +//----------------------------------------------------------------------------- +// Moniker + +var defaultMoniker = getDefaultMoniker() + +// getDefaultMoniker returns a default moniker, which is the host name. If runtime +// fails to get the host name, "anonymous" will be returned. +func getDefaultMoniker() string { + moniker, err := os.Hostname() + if err != nil { + moniker = "anonymous" + } + return moniker +} diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 0000000..87ff71e --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,203 @@ +package config_test + +import ( + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/config" +) + +func TestDefaultConfig(t *testing.T) { + assert := assert.New(t) + + // set up some defaults + cfg := config.DefaultConfig() + assert.NotNil(cfg.P2P) + assert.NotNil(cfg.Mempool) + assert.NotNil(cfg.Consensus) + + // check the root dir stuff... + cfg.SetRoot("/foo") + cfg.Genesis = "bar" + cfg.DBPath = "/opt/data" + cfg.Mempool.WalPath = "wal/mem/" + + assert.Equal("/foo/bar", cfg.GenesisFile()) + assert.Equal("/opt/data", cfg.DBDir()) + assert.Equal("/foo/wal/mem", cfg.Mempool.WalDir()) + +} + +func TestConfigValidateBasic(t *testing.T) { + cfg := config.DefaultConfig() + assert.NoError(t, cfg.ValidateBasic()) + + // tamper with timeout_propose + cfg.Consensus.TimeoutPropose = -10 * time.Second + assert.Error(t, cfg.ValidateBasic()) + cfg.Consensus.TimeoutPropose = 3 * time.Second + + cfg.Consensus.CreateEmptyBlocks = false + cfg.Mempool.Type = config.MempoolTypeNop + assert.Error(t, cfg.ValidateBasic()) +} + +func TestTLSConfiguration(t *testing.T) { + assert := assert.New(t) + cfg := config.DefaultConfig() + cfg.SetRoot("/home/user") + + cfg.RPC.TLSCertFile = "file.crt" + assert.Equal("/home/user/config/file.crt", cfg.RPC.CertFile()) + cfg.RPC.TLSKeyFile = "file.key" + assert.Equal("/home/user/config/file.key", cfg.RPC.KeyFile()) + + cfg.RPC.TLSCertFile = "/abs/path/to/file.crt" + assert.Equal("/abs/path/to/file.crt", cfg.RPC.CertFile()) + cfg.RPC.TLSKeyFile = "/abs/path/to/file.key" + assert.Equal("/abs/path/to/file.key", cfg.RPC.KeyFile()) +} + +func TestBaseConfigValidateBasic(t *testing.T) { + cfg := config.TestBaseConfig() + assert.NoError(t, cfg.ValidateBasic()) + + // tamper with log format + cfg.LogFormat = "invalid" + assert.Error(t, cfg.ValidateBasic()) +} + +func TestRPCConfigValidateBasic(t *testing.T) { + cfg := config.TestRPCConfig() + assert.NoError(t, cfg.ValidateBasic()) + + fieldsToTest := []string{ + "GRPCMaxOpenConnections", + "MaxOpenConnections", + "MaxSubscriptionClients", + "MaxSubscriptionsPerClient", + "TimeoutBroadcastTxCommit", + "MaxBodyBytes", + "MaxHeaderBytes", + "MaxRequestBatchSize", + } + + for _, fieldName := range fieldsToTest { + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(-1) + assert.Error(t, cfg.ValidateBasic()) + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(0) + } +} + +func TestP2PConfigValidateBasic(t *testing.T) { + cfg := config.TestP2PConfig() + assert.NoError(t, cfg.ValidateBasic()) + + fieldsToTest := []string{ + "MaxNumInboundPeers", + "MaxNumOutboundPeers", + "FlushThrottleTimeout", + "MaxPacketMsgPayloadSize", + "SendRate", + "RecvRate", + } + + for _, fieldName := range fieldsToTest { + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(-1) + assert.Error(t, cfg.ValidateBasic()) + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(0) + } +} + +func TestMempoolConfigValidateBasic(t *testing.T) { + cfg := config.TestMempoolConfig() + assert.NoError(t, cfg.ValidateBasic()) + + fieldsToTest := []string{ + "Size", + "MaxTxsBytes", + "CacheSize", + "MaxTxBytes", + } + + for _, fieldName := range fieldsToTest { + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(-1) + assert.Error(t, cfg.ValidateBasic()) + reflect.ValueOf(cfg).Elem().FieldByName(fieldName).SetInt(0) + } + + reflect.ValueOf(cfg).Elem().FieldByName("Type").SetString("invalid") + assert.Error(t, cfg.ValidateBasic()) +} + +func TestStateSyncConfigValidateBasic(t *testing.T) { + cfg := config.TestStateSyncConfig() + require.NoError(t, cfg.ValidateBasic()) +} + +func TestBlockSyncConfigValidateBasic(t *testing.T) { + cfg := config.TestBlockSyncConfig() + assert.NoError(t, cfg.ValidateBasic()) + + // tamper with version + cfg.Version = "v1" + assert.Error(t, cfg.ValidateBasic()) + + cfg.Version = "invalid" + assert.Error(t, cfg.ValidateBasic()) +} + +func TestConsensusConfig_ValidateBasic(t *testing.T) { + //nolint: lll + testcases := map[string]struct { + modify func(*config.ConsensusConfig) + expectErr bool + }{ + "TimeoutPropose": {func(c *config.ConsensusConfig) { c.TimeoutPropose = time.Second }, false}, + "TimeoutPropose negative": {func(c *config.ConsensusConfig) { c.TimeoutPropose = -1 }, true}, + "TimeoutProposeDelta": {func(c *config.ConsensusConfig) { c.TimeoutProposeDelta = time.Second }, false}, + "TimeoutProposeDelta negative": {func(c *config.ConsensusConfig) { c.TimeoutProposeDelta = -1 }, true}, + "TimeoutPrevote": {func(c *config.ConsensusConfig) { c.TimeoutPrevote = time.Second }, false}, + "TimeoutPrevote negative": {func(c *config.ConsensusConfig) { c.TimeoutPrevote = -1 }, true}, + "TimeoutPrevoteDelta": {func(c *config.ConsensusConfig) { c.TimeoutPrevoteDelta = time.Second }, false}, + "TimeoutPrevoteDelta negative": {func(c *config.ConsensusConfig) { c.TimeoutPrevoteDelta = -1 }, true}, + "TimeoutPrecommit": {func(c *config.ConsensusConfig) { c.TimeoutPrecommit = time.Second }, false}, + "TimeoutPrecommit negative": {func(c *config.ConsensusConfig) { c.TimeoutPrecommit = -1 }, true}, + "TimeoutPrecommitDelta": {func(c *config.ConsensusConfig) { c.TimeoutPrecommitDelta = time.Second }, false}, + "TimeoutPrecommitDelta negative": {func(c *config.ConsensusConfig) { c.TimeoutPrecommitDelta = -1 }, true}, + "TimeoutCommit": {func(c *config.ConsensusConfig) { c.TimeoutCommit = time.Second }, false}, + "TimeoutCommit negative": {func(c *config.ConsensusConfig) { c.TimeoutCommit = -1 }, true}, + "PeerGossipSleepDuration": {func(c *config.ConsensusConfig) { c.PeerGossipSleepDuration = time.Second }, false}, + "PeerGossipSleepDuration negative": {func(c *config.ConsensusConfig) { c.PeerGossipSleepDuration = -1 }, true}, + "PeerQueryMaj23SleepDuration": {func(c *config.ConsensusConfig) { c.PeerQueryMaj23SleepDuration = time.Second }, false}, + "PeerQueryMaj23SleepDuration negative": {func(c *config.ConsensusConfig) { c.PeerQueryMaj23SleepDuration = -1 }, true}, + "DoubleSignCheckHeight negative": {func(c *config.ConsensusConfig) { c.DoubleSignCheckHeight = -1 }, true}, + } + for desc, tc := range testcases { + tc := tc // appease linter + t.Run(desc, func(t *testing.T) { + cfg := config.DefaultConsensusConfig() + tc.modify(cfg) + + err := cfg.ValidateBasic() + if tc.expectErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestInstrumentationConfigValidateBasic(t *testing.T) { + cfg := config.TestInstrumentationConfig() + assert.NoError(t, cfg.ValidateBasic()) + + // tamper with maximum open connections + cfg.MaxOpenConnections = -1 + assert.Error(t, cfg.ValidateBasic()) +} diff --git a/config/db.go b/config/db.go new file mode 100644 index 0000000..0e213af --- /dev/null +++ b/config/db.go @@ -0,0 +1,30 @@ +package config + +import ( + "context" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" +) + +// ServiceProvider takes a config and a logger and returns a ready to go Node. +type ServiceProvider func(context.Context, *Config, log.Logger) (service.Service, error) + +// DBContext specifies config information for loading a new DB. +type DBContext struct { + ID string + Config *Config +} + +// DBProvider takes a DBContext and returns an instantiated DB. +type DBProvider func(*DBContext) (dbm.DB, error) + +// DefaultDBProvider returns a database using the DBBackend and DBDir +// specified in the Config. +func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) { + dbType := dbm.BackendType(ctx.Config.DBBackend) + + return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir()) +} diff --git a/config/toml.go b/config/toml.go new file mode 100644 index 0000000..c7edc03 --- /dev/null +++ b/config/toml.go @@ -0,0 +1,570 @@ +package config + +import ( + "bytes" + "path/filepath" + "strings" + "text/template" + + cmtos "github.com/cometbft/cometbft/libs/os" +) + +// DefaultDirPerm is the default permissions used when creating directories. +const DefaultDirPerm = 0700 + +var configTemplate *template.Template + +func init() { + var err error + tmpl := template.New("configFileTemplate").Funcs(template.FuncMap{ + "StringsJoin": strings.Join, + }) + if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { + panic(err) + } +} + +/****** these are for production settings ***********/ + +// EnsureRoot creates the root, config, and data directories if they don't exist, +// and panics if it fails. +func EnsureRoot(rootDir string) { + if err := cmtos.EnsureDir(rootDir, DefaultDirPerm); err != nil { + panic(err.Error()) + } + if err := cmtos.EnsureDir(filepath.Join(rootDir, DefaultConfigDir), DefaultDirPerm); err != nil { + panic(err.Error()) + } + if err := cmtos.EnsureDir(filepath.Join(rootDir, DefaultDataDir), DefaultDirPerm); err != nil { + panic(err.Error()) + } + + configFilePath := filepath.Join(rootDir, defaultConfigFilePath) + + // Write default config file if missing. + if !cmtos.FileExists(configFilePath) { + writeDefaultConfigFile(configFilePath) + } +} + +// XXX: this func should probably be called by cmd/cometbft/commands/init.go +// alongside the writing of the genesis.json and priv_validator.json +func writeDefaultConfigFile(configFilePath string) { + WriteConfigFile(configFilePath, DefaultConfig()) +} + +// WriteConfigFile renders config using the template and writes it to configFilePath. +func WriteConfigFile(configFilePath string, config *Config) { + var buffer bytes.Buffer + + if err := configTemplate.Execute(&buffer, config); err != nil { + panic(err) + } + + cmtos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) +} + +// Note: any changes to the comments/variables/mapstructure +// must be reflected in the appropriate struct in config/config.go +const defaultConfigTemplate = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +# NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or +# relative to the home directory (e.g. "data"). The home directory is +# "$HOME/.cometbft" by default, but could be changed via $CMTHOME env variable +# or --home cmd flag. + +# The version of the CometBFT binary that created or +# last modified the config file. Do not modify this. +version = "{{ .BaseConfig.Version }}" + +####################################################################### +### Main Base Config Options ### +####################################################################### + +# TCP or UNIX socket address of the ABCI application, +# or the name of an ABCI application compiled in with the CometBFT binary +proxy_app = "{{ .BaseConfig.ProxyApp }}" + +# A custom human readable name for this node +moniker = "{{ .BaseConfig.Moniker }}" + +# Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb +# * goleveldb (github.com/syndtr/goleveldb - most popular implementation) +# - pure go +# - stable +# * cleveldb (uses levigo wrapper) +# - fast +# - requires gcc +# - use cleveldb build tag (go build -tags cleveldb) +# * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) +# - EXPERIMENTAL +# - may be faster is some use-cases (random reads - indexer) +# - use boltdb build tag (go build -tags boltdb) +# * rocksdb (uses github.com/tecbot/gorocksdb) +# - EXPERIMENTAL +# - requires gcc +# - use rocksdb build tag (go build -tags rocksdb) +# * badgerdb (uses github.com/dgraph-io/badger) +# - EXPERIMENTAL +# - use badgerdb build tag (go build -tags badgerdb) +db_backend = "{{ .BaseConfig.DBBackend }}" + +# Database directory +db_dir = "{{ js .BaseConfig.DBPath }}" + +# Output level for logging, including package level options +log_level = "{{ .BaseConfig.LogLevel }}" + +# Output format: 'plain' (colored text) or 'json' +log_format = "{{ .BaseConfig.LogFormat }}" + +##### additional base config options ##### + +# Path to the JSON file containing the initial validator set and other meta data +genesis_file = "{{ js .BaseConfig.Genesis }}" + +# Path to the JSON file containing the private key to use as a validator in the consensus protocol +priv_validator_key_file = "{{ js .BaseConfig.PrivValidatorKey }}" + +# Path to the JSON file containing the last sign state of a validator +priv_validator_state_file = "{{ js .BaseConfig.PrivValidatorState }}" + +# TCP or UNIX socket address for CometBFT to listen on for +# connections from an external PrivValidator process +priv_validator_laddr = "{{ .BaseConfig.PrivValidatorListenAddr }}" + +# Path to the JSON file containing the private key to use for node authentication in the p2p protocol +node_key_file = "{{ js .BaseConfig.NodeKey }}" + +# Mechanism to connect to the ABCI application: socket | grpc +abci = "{{ .BaseConfig.ABCI }}" + +# If true, query the ABCI app on connecting to a new peer +# so the app can decide if we should keep the connection or not +filter_peers = {{ .BaseConfig.FilterPeers }} + + +####################################################################### +### Advanced Configuration Options ### +####################################################################### + +####################################################### +### RPC Server Configuration Options ### +####################################################### +[rpc] + +# TCP or UNIX socket address for the RPC server to listen on +laddr = "{{ .RPC.ListenAddress }}" + +# A list of origins a cross-domain request can be executed from +# Default value '[]' disables cors support +# Use '["*"]' to allow any origin +cors_allowed_origins = [{{ range .RPC.CORSAllowedOrigins }}{{ printf "%q, " . }}{{end}}] + +# A list of methods the client is allowed to use with cross-domain requests +cors_allowed_methods = [{{ range .RPC.CORSAllowedMethods }}{{ printf "%q, " . }}{{end}}] + +# A list of non simple headers the client is allowed to use with cross-domain requests +cors_allowed_headers = [{{ range .RPC.CORSAllowedHeaders }}{{ printf "%q, " . }}{{end}}] + +# TCP or UNIX socket address for the gRPC server to listen on +# NOTE: This server only supports /broadcast_tx_commit +grpc_laddr = "{{ .RPC.GRPCListenAddress }}" + +# Maximum number of simultaneous connections. +# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +grpc_max_open_connections = {{ .RPC.GRPCMaxOpenConnections }} + +# Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool +unsafe = {{ .RPC.Unsafe }} + +# Maximum number of simultaneous connections (including WebSocket). +# Does not include gRPC connections. See grpc_max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +max_open_connections = {{ .RPC.MaxOpenConnections }} + +# Maximum number of unique clientIDs that can /subscribe +# If you're using /broadcast_tx_commit, set to the estimated maximum number +# of broadcast_tx_commit calls per block. +max_subscription_clients = {{ .RPC.MaxSubscriptionClients }} + +# Maximum number of unique queries a given client can /subscribe to +# If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to +# the estimated # maximum number of broadcast_tx_commit calls per block. +max_subscriptions_per_client = {{ .RPC.MaxSubscriptionsPerClient }} + +# Experimental parameter to specify the maximum number of events a node will +# buffer, per subscription, before returning an error and closing the +# subscription. Must be set to at least 100, but higher values will accommodate +# higher event throughput rates (and will use more memory). +experimental_subscription_buffer_size = {{ .RPC.SubscriptionBufferSize }} + +# Experimental parameter to specify the maximum number of RPC responses that +# can be buffered per WebSocket client. If clients cannot read from the +# WebSocket endpoint fast enough, they will be disconnected, so increasing this +# parameter may reduce the chances of them being disconnected (but will cause +# the node to use more memory). +# +# Must be at least the same as "experimental_subscription_buffer_size", +# otherwise connections could be dropped unnecessarily. This value should +# ideally be somewhat higher than "experimental_subscription_buffer_size" to +# accommodate non-subscription-related RPC responses. +experimental_websocket_write_buffer_size = {{ .RPC.WebSocketWriteBufferSize }} + +# If a WebSocket client cannot read fast enough, at present we may +# silently drop events instead of generating an error or disconnecting the +# client. +# +# Enabling this experimental parameter will cause the WebSocket connection to +# be closed instead if it cannot read fast enough, allowing for greater +# predictability in subscription behavior. +experimental_close_on_slow_client = {{ .RPC.CloseOnSlowClient }} + +# How long to wait for a tx to be committed during /broadcast_tx_commit. +# WARNING: Using a value larger than 10s will result in increasing the +# global HTTP write timeout, which applies to all connections and endpoints. +# See https://github.com/tendermint/tendermint/issues/3435 +timeout_broadcast_tx_commit = "{{ .RPC.TimeoutBroadcastTxCommit }}" + +# Maximum number of requests that can be sent in a batch +# If the value is set to '0' (zero-value), then no maximum batch size will be +# enforced for a JSON-RPC batch request. +max_request_batch_size = {{ .RPC.MaxRequestBatchSize }} + +# Maximum size of request body, in bytes +max_body_bytes = {{ .RPC.MaxBodyBytes }} + +# Maximum size of request header, in bytes +max_header_bytes = {{ .RPC.MaxHeaderBytes }} + +# The path to a file containing certificate that is used to create the HTTPS server. +# Might be either absolute path or path related to CometBFT's config directory. +# If the certificate is signed by a certificate authority, +# the certFile should be the concatenation of the server's certificate, any intermediates, +# and the CA's certificate. +# NOTE: both tls_cert_file and tls_key_file must be present for CometBFT to create HTTPS server. +# Otherwise, HTTP server is run. +tls_cert_file = "{{ .RPC.TLSCertFile }}" + +# The path to a file containing matching private key that is used to create the HTTPS server. +# Might be either absolute path or path related to CometBFT's config directory. +# NOTE: both tls-cert-file and tls-key-file must be present for CometBFT to create HTTPS server. +# Otherwise, HTTP server is run. +tls_key_file = "{{ .RPC.TLSKeyFile }}" + +# pprof listen address (https://golang.org/pkg/net/http/pprof) +pprof_laddr = "{{ .RPC.PprofListenAddress }}" + +####################################################### +### P2P Configuration Options ### +####################################################### +[p2p] + +# Address to listen for incoming connections +laddr = "{{ .P2P.ListenAddress }}" + +# Address to advertise to peers for them to dial. If empty, will use the same +# port as the laddr, and will introspect on the listener to figure out the +# address. IP and port are required. Example: 159.89.10.97:26656 +external_address = "{{ .P2P.ExternalAddress }}" + +# Comma separated list of seed nodes to connect to +seeds = "{{ .P2P.Seeds }}" + +# Comma separated list of nodes to keep persistent connections to +persistent_peers = "{{ .P2P.PersistentPeers }}" + +# Path to address book +addr_book_file = "{{ js .P2P.AddrBook }}" + +# Set true for strict address routability rules +# Set false for private or local networks +addr_book_strict = {{ .P2P.AddrBookStrict }} + +# Maximum number of inbound peers +max_num_inbound_peers = {{ .P2P.MaxNumInboundPeers }} + +# Maximum number of outbound peers to connect to, excluding persistent peers +max_num_outbound_peers = {{ .P2P.MaxNumOutboundPeers }} + +# List of node IDs, to which a connection will be (re)established ignoring any existing limits +unconditional_peer_ids = "{{ .P2P.UnconditionalPeerIDs }}" + +# Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) +persistent_peers_max_dial_period = "{{ .P2P.PersistentPeersMaxDialPeriod }}" + +# Time to wait before flushing messages out on the connection +flush_throttle_timeout = "{{ .P2P.FlushThrottleTimeout }}" + +# Maximum size of a message packet payload, in bytes +max_packet_msg_payload_size = {{ .P2P.MaxPacketMsgPayloadSize }} + +# Rate at which packets can be sent, in bytes/second +send_rate = {{ .P2P.SendRate }} + +# Rate at which packets can be received, in bytes/second +recv_rate = {{ .P2P.RecvRate }} + +# Set true to enable the peer-exchange reactor +pex = {{ .P2P.PexReactor }} + +# Seed mode, in which node constantly crawls the network and looks for +# peers. If another node asks it for addresses, it responds and disconnects. +# +# Does not work if the peer-exchange reactor is disabled. +seed_mode = {{ .P2P.SeedMode }} + +# Comma separated list of peer IDs to keep private (will not be gossiped to other peers) +private_peer_ids = "{{ .P2P.PrivatePeerIDs }}" + +# Toggle to disable guard against peers connecting from the same ip. +allow_duplicate_ip = {{ .P2P.AllowDuplicateIP }} + +# Peer connection configuration. +handshake_timeout = "{{ .P2P.HandshakeTimeout }}" +dial_timeout = "{{ .P2P.DialTimeout }}" + +####################################################### +### Mempool Configuration Option ### +####################################################### +[mempool] + +# The type of mempool for this node to use. +# +# Possible types: +# - "flood" : concurrent linked list mempool with flooding gossip protocol +# (default) +# - "nop" : nop-mempool (short for no operation; the ABCI app is responsible +# for storing, disseminating and proposing txs). "create_empty_blocks=false" is +# not supported. +type = "flood" + +# Recheck (default: true) defines whether CometBFT should recheck the +# validity for all remaining transaction in the mempool after a block. +# Since a block affects the application state, some transactions in the +# mempool may become invalid. If this does not apply to your application, +# you can disable rechecking. +recheck = {{ .Mempool.Recheck }} + +# recheck_timeout is the time the application has during the rechecking process +# to return CheckTx responses, once all requests have been sent. Responses that +# arrive after the timeout expires are discarded. It only applies to +# non-local ABCI clients and when recheck is enabled. +# +# The ideal value will strongly depend on the application. It could roughly be estimated as the +# average size of the mempool multiplied by the average time it takes the application to validate one +# transaction. We consider that the ABCI application runs in the same location as the CometBFT binary +# so that the recheck duration is not affected by network delays when making requests and receiving responses. +recheck_timeout = "{{ .Mempool.RecheckTimeout }}" + +# Broadcast (default: true) defines whether the mempool should relay +# transactions to other peers. Setting this to false will stop the mempool +# from relaying transactions to other peers until they are included in a +# block. In other words, if Broadcast is disabled, only the peer you send +# the tx to will see it until it is included in a block. +broadcast = {{ .Mempool.Broadcast }} + +# WalPath (default: "") configures the location of the Write Ahead Log +# (WAL) for the mempool. The WAL is disabled by default. To enable, set +# WalPath to where you want the WAL to be written (e.g. +# "data/mempool.wal"). +wal_dir = "{{ js .Mempool.WalPath }}" + +# Maximum number of transactions in the mempool +size = {{ .Mempool.Size }} + +# Limit the total size of all txs in the mempool. +# This only accounts for raw transactions (e.g. given 1MB transactions and +# max_txs_bytes=5MB, mempool will only accept 5 transactions). +max_txs_bytes = {{ .Mempool.MaxTxsBytes }} + +# Size of the cache (used to filter transactions we saw earlier) in transactions +cache_size = {{ .Mempool.CacheSize }} + +# Do not remove invalid transactions from the cache (default: false) +# Set to true if it's not possible for any invalid transaction to become valid +# again in the future. +keep-invalid-txs-in-cache = {{ .Mempool.KeepInvalidTxsInCache }} + +# Maximum size of a single transaction. +# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. +max_tx_bytes = {{ .Mempool.MaxTxBytes }} + +# Maximum size of a batch of transactions to send to a peer +# Including space needed by encoding (one varint per transaction). +# XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 +max_batch_bytes = {{ .Mempool.MaxBatchBytes }} + +# Experimental parameters to limit gossiping txs to up to the specified number of peers. +# We use two independent upper values for persistent and non-persistent peers. +# Unconditional peers are not affected by this feature. +# If we are connected to more than the specified number of persistent peers, only send txs to +# ExperimentalMaxGossipConnectionsToPersistentPeers of them. If one of those +# persistent peers disconnects, activate another persistent peer. +# Similarly for non-persistent peers, with an upper limit of +# ExperimentalMaxGossipConnectionsToNonPersistentPeers. +# If set to 0, the feature is disabled for the corresponding group of peers, that is, the +# number of active connections to that group of peers is not bounded. +# For non-persistent peers, if enabled, a value of 10 is recommended based on experimental +# performance results using the default P2P configuration. +experimental_max_gossip_connections_to_persistent_peers = {{ .Mempool.ExperimentalMaxGossipConnectionsToPersistentPeers }} +experimental_max_gossip_connections_to_non_persistent_peers = {{ .Mempool.ExperimentalMaxGossipConnectionsToNonPersistentPeers }} + +####################################################### +### State Sync Configuration Options ### +####################################################### +[statesync] +# State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine +# snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in +# the network to take and serve state machine snapshots. State sync is not attempted if the node +# has any local state (LastBlockHeight > 0). The node will have a truncated block history, +# starting from the height of the snapshot. +enable = {{ .StateSync.Enable }} + +# RPC servers (comma-separated) for light client verification of the synced state machine and +# retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding +# header hash obtained from a trusted source, and a period during which validators can be trusted. +# +# For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 +# weeks) during which they can be financially punished (slashed) for misbehavior. +rpc_servers = "{{ StringsJoin .StateSync.RPCServers "," }}" +trust_height = {{ .StateSync.TrustHeight }} +trust_hash = "{{ .StateSync.TrustHash }}" +trust_period = "{{ .StateSync.TrustPeriod }}" + +# Time to spend discovering snapshots before initiating a restore. +discovery_time = "{{ .StateSync.DiscoveryTime }}" + +# Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). +# Will create a new, randomly named directory within, and remove it when done. +temp_dir = "{{ .StateSync.TempDir }}" + +# The timeout duration before re-requesting a chunk, possibly from a different +# peer (default: 1 minute). +chunk_request_timeout = "{{ .StateSync.ChunkRequestTimeout }}" + +# The number of concurrent chunk fetchers to run (default: 1). +chunk_fetchers = "{{ .StateSync.ChunkFetchers }}" + +# Maximum number of chunks allowed in a snapshot (default: 100000). +max_snapshot_chunks = {{ .StateSync.MaxSnapshotChunks }} + +####################################################### +### Block Sync Configuration Options ### +####################################################### +[blocksync] + +# Block Sync version to use: +# +# In v0.37, v1 and v2 of the block sync protocols were deprecated. +# Please use v0 instead. +# +# 1) "v0" - the default block sync implementation +version = "{{ .BlockSync.Version }}" + +####################################################### +### Consensus Configuration Options ### +####################################################### +[consensus] + +wal_file = "{{ js .Consensus.WalPath }}" + +# How long we wait for a proposal block before prevoting nil +timeout_propose = "{{ .Consensus.TimeoutPropose }}" +# How much timeout_propose increases with each round +timeout_propose_delta = "{{ .Consensus.TimeoutProposeDelta }}" +# How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) +timeout_prevote = "{{ .Consensus.TimeoutPrevote }}" +# How much the timeout_prevote increases with each round +timeout_prevote_delta = "{{ .Consensus.TimeoutPrevoteDelta }}" +# How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) +timeout_precommit = "{{ .Consensus.TimeoutPrecommit }}" +# How much the timeout_precommit increases with each round +timeout_precommit_delta = "{{ .Consensus.TimeoutPrecommitDelta }}" +# How long we wait after committing a block, before starting on the new +# height (this gives us a chance to receive some more precommits, even +# though we already have +2/3). +timeout_commit = "{{ .Consensus.TimeoutCommit }}" + +# How many blocks to look back to check existence of the node's consensus votes before joining consensus +# When non-zero, the node will panic upon restart +# if the same consensus key was used to sign {double_sign_check_height} last blocks. +# So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. +double_sign_check_height = {{ .Consensus.DoubleSignCheckHeight }} + +# Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) +skip_timeout_commit = {{ .Consensus.SkipTimeoutCommit }} + +# EmptyBlocks mode and possible interval between empty blocks +create_empty_blocks = {{ .Consensus.CreateEmptyBlocks }} +create_empty_blocks_interval = "{{ .Consensus.CreateEmptyBlocksInterval }}" + +# Reactor sleep duration parameters +peer_gossip_sleep_duration = "{{ .Consensus.PeerGossipSleepDuration }}" +peer_query_maj23_sleep_duration = "{{ .Consensus.PeerQueryMaj23SleepDuration }}" + +####################################################### +### Storage Configuration Options ### +####################################################### +[storage] + +# Set to true to discard ABCI responses from the state store, which can save a +# considerable amount of disk space. Set to false to ensure ABCI responses are +# persisted. ABCI responses are required for /block_results RPC queries, and to +# reindex events in the command-line tool. +discard_abci_responses = {{ .Storage.DiscardABCIResponses}} + +####################################################### +### Transaction Indexer Configuration Options ### +####################################################### +[tx_index] + +# What indexer to use for transactions +# +# The application will set which txs to index. In some cases a node operator will be able +# to decide which txs to index based on configuration set in the application. +# +# Options: +# 1) "null" +# 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). +# - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. +# 3) "psql" - the indexer services backed by PostgreSQL. +# When "kv" or "psql" is chosen "tx.height" and "tx.hash" will always be indexed. +indexer = "{{ .TxIndex.Indexer }}" + +# The PostgreSQL connection configuration, the connection format: +# postgresql://:@:/? +psql-conn = "{{ .TxIndex.PsqlConn }}" + +####################################################### +### Instrumentation Configuration Options ### +####################################################### +[instrumentation] + +# When true, Prometheus metrics are served under /metrics on +# PrometheusListenAddr. +# Check out the documentation for the list of available metrics. +prometheus = {{ .Instrumentation.Prometheus }} + +# Address to listen for Prometheus collector(s) connections +prometheus_listen_addr = "{{ .Instrumentation.PrometheusListenAddr }}" + +# Maximum number of simultaneous connections. +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = {{ .Instrumentation.MaxOpenConnections }} + +# Instrumentation namespace +namespace = "{{ .Instrumentation.Namespace }}" +` diff --git a/config/toml_test.go b/config/toml_test.go new file mode 100644 index 0000000..0f1f52f --- /dev/null +++ b/config/toml_test.go @@ -0,0 +1,83 @@ +package config_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/internal/test" +) + +func ensureFiles(t *testing.T, rootDir string, files ...string) { + for _, f := range files { + p := filepath.Join(rootDir, f) + _, err := os.Stat(p) + assert.NoError(t, err, p) + } +} + +func TestEnsureRoot(t *testing.T) { + require := require.New(t) + + // setup temp dir for test + tmpDir, err := os.MkdirTemp("", "config-test") + require.Nil(err) + defer os.RemoveAll(tmpDir) + + // create root dir + config.EnsureRoot(tmpDir) + + // make sure config is set properly + data, err := os.ReadFile(filepath.Join(tmpDir, config.DefaultConfigDir, config.DefaultConfigFileName)) + require.Nil(err) + + assertValidConfig(t, string(data)) + + ensureFiles(t, tmpDir, "data") +} + +func TestEnsureTestRoot(t *testing.T) { + require := require.New(t) + + // create root dir + cfg := test.ResetTestRoot("ensureTestRoot") + defer os.RemoveAll(cfg.RootDir) + rootDir := cfg.RootDir + + // make sure config is set properly + data, err := os.ReadFile(filepath.Join(rootDir, config.DefaultConfigDir, config.DefaultConfigFileName)) + require.Nil(err) + + assertValidConfig(t, string(data)) + + // TODO: make sure the cfg returned and testconfig are the same! + baseConfig := config.DefaultBaseConfig() + ensureFiles(t, rootDir, config.DefaultDataDir, baseConfig.Genesis, baseConfig.PrivValidatorKey, baseConfig.PrivValidatorState) +} + +func assertValidConfig(t *testing.T, configFile string) { + t.Helper() + // list of words we expect in the config + var elems = []string{ + "moniker", + "seeds", + "proxy_app", + "create_empty_blocks", + "peer", + "timeout", + "broadcast", + "send", + "addr", + "wal", + "propose", + "max", + "genesis", + } + for _, e := range elems { + assert.Contains(t, configFile, e) + } +} diff --git a/consensus/README.md b/consensus/README.md new file mode 100644 index 0000000..6ad7a57 --- /dev/null +++ b/consensus/README.md @@ -0,0 +1,3 @@ +# Consensus + +See the [consensus spec](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/consensus) for more information. diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go new file mode 100644 index 0000000..ec6c650 --- /dev/null +++ b/consensus/byzantine_test.go @@ -0,0 +1,680 @@ +package consensus + +import ( + "context" + "fmt" + "os" + "path" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abcicli "github.com/cometbft/cometbft/abci/client" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/proxy" + + "github.com/cometbft/cometbft/p2p" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +//---------------------------------------------- +// byzantine failures + +// Byzantine node sends two different prevotes (nil and blockID) to the same validator +func TestByzantinePrevoteEquivocation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + const nValidators = 4 + const byzantineNode = 0 + const prevoteHeight = int64(2) + testName := "consensus_byzantine_test" + tickerFunc := newMockTickerFunc(true) + appFunc := newKVStore + + genDoc, privVals := randGenesisDoc(nValidators, false, 30, nil) + css := make([]*State, nValidators) + + for i := 0; i < nValidators; i++ { + logger := consensusLogger().With("test", "byzantine", "validator", i) + stateDB := dbm.NewMemDB() // each state needs its own db + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) + defer os.RemoveAll(thisConfig.RootDir) + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal + app := appFunc() + vals := types.TM2PB.ValidatorUpdates(state.Validators) + _, err := app.InitChain(context.Background(), &abci.RequestInitChain{Validators: vals}) + require.NoError(t, err) + + blockDB := dbm.NewMemDB() + blockStore := store.NewBlockStore(blockDB) + + mtx := new(cmtsync.Mutex) + // one for mempool, one for consensus + proxyAppConnCon := proxy.NewAppConnConsensus(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + proxyAppConnMem := proxy.NewAppConnMempool(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + + // Make Mempool + mempool := mempl.NewCListMempool(config.Mempool, + proxyAppConnMem, + state.LastBlockHeight, + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state))) + + if thisConfig.Consensus.WaitForTxs() { + mempool.EnableTxsAvailable() + } + + // Make a full instance of the evidence pool + evidenceDB := dbm.NewMemDB() + evpool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + evpool.SetLogger(logger.With("module", "evidence")) + + // Make State + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore) + cs := NewState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool) + cs.SetLogger(cs.Logger) + // set private validator + pv := privVals[i] + cs.SetPrivValidator(pv) + + eventBus := types.NewEventBus() + eventBus.SetLogger(log.TestingLogger().With("module", "events")) + err = eventBus.Start() + require.NoError(t, err) + cs.SetEventBus(eventBus) + + cs.SetTimeoutTicker(tickerFunc()) + cs.SetLogger(logger) + + css[i] = cs + } + + // initialize the reactors for each of the validators + reactors := make([]*Reactor, nValidators) + blocksSubs := make([]types.Subscription, 0) + eventBuses := make([]*types.EventBus, nValidators) + for i := 0; i < nValidators; i++ { + reactors[i] = NewReactor(css[i], true) // so we dont start the consensus states + reactors[i].SetLogger(css[i].Logger) + + // eventBus is already started with the cs + eventBuses[i] = css[i].eventBus + reactors[i].SetEventBus(eventBuses[i]) + + blocksSub, err := eventBuses[i].Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock, 100) + require.NoError(t, err) + blocksSubs = append(blocksSubs, blocksSub) + + if css[i].state.LastBlockHeight == 0 { // simulate handle initChain in handshake + err = css[i].blockExec.Store().Save(css[i].state) + require.NoError(t, err) + } + } + // make connected switches and start all reactors + p2p.MakeConnectedSwitches(config.P2P, nValidators, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("CONSENSUS", reactors[i]) + s.SetLogger(reactors[i].conS.Logger.With("module", "p2p")) + return s + }, p2p.Connect2Switches) + + // create byzantine validator + bcs := css[byzantineNode] + + // alter prevote so that the byzantine node double votes when height is 2 + bcs.doPrevote = func(height int64, round int32) { + // allow first height to happen normally so that byzantine validator is no longer proposer + if height == prevoteHeight { + bcs.Logger.Info("Sending two votes") + prevote1, err := bcs.signVote(cmtproto.PrevoteType, bcs.ProposalBlock.Hash(), bcs.ProposalBlockParts.Header(), nil) + require.NoError(t, err) + prevote2, err := bcs.signVote(cmtproto.PrevoteType, nil, types.PartSetHeader{}, nil) + require.NoError(t, err) + peerList := reactors[byzantineNode].Switch.Peers().List() + bcs.Logger.Info("Getting peer list", "peers", peerList) + // send two votes to all peers (1st to one half, 2nd to another half) + for i, peer := range peerList { + if i < len(peerList)/2 { + bcs.Logger.Info("Signed and pushed vote", "vote", prevote1, "peer", peer) + peer.Send(p2p.Envelope{ + Message: &cmtcons.Vote{Vote: prevote1.ToProto()}, + ChannelID: VoteChannel, + }) + } else { + bcs.Logger.Info("Signed and pushed vote", "vote", prevote2, "peer", peer) + peer.Send(p2p.Envelope{ + Message: &cmtcons.Vote{Vote: prevote2.ToProto()}, + ChannelID: VoteChannel, + }) + } + } + } else { + bcs.Logger.Info("Behaving normally") + bcs.defaultDoPrevote(height, round) + } + } + + // introducing a lazy proposer means that the time of the block committed is different to the + // timestamp that the other nodes have. This tests to ensure that the evidence that finally gets + // proposed will have a valid timestamp + lazyProposer := css[1] + + lazyProposer.decideProposal = func(height int64, round int32) { + lazyProposer.Logger.Info("Lazy Proposer proposing condensed commit") + if lazyProposer.privValidator == nil { + panic("entered createProposalBlock with privValidator being nil") + } + + var extCommit *types.ExtendedCommit + switch { + case lazyProposer.Height == lazyProposer.state.InitialHeight: + // We're creating a proposal for the first block. + // The commit is empty, but not nil. + extCommit = &types.ExtendedCommit{} + case lazyProposer.LastCommit.HasTwoThirdsMajority(): + // Make the commit from LastCommit + veHeightParam := types.ABCIParams{VoteExtensionsEnableHeight: height} + extCommit = lazyProposer.LastCommit.MakeExtendedCommit(veHeightParam) + default: // This shouldn't happen. + lazyProposer.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block") + return + } + + // omit the last signature in the commit + extCommit.ExtendedSignatures[len(extCommit.ExtendedSignatures)-1] = types.NewExtendedCommitSigAbsent() + + if lazyProposer.privValidatorPubKey == nil { + // If this node is a validator & proposer in the current round, it will + // miss the opportunity to create a block. + lazyProposer.Logger.Error(fmt.Sprintf("enterPropose: %v", errPubKeyIsNotSet)) + return + } + proposerAddr := lazyProposer.privValidatorPubKey.Address() + + block, err := lazyProposer.blockExec.CreateProposalBlock( + ctx, lazyProposer.Height, lazyProposer.state, extCommit, proposerAddr) + require.NoError(t, err) + blockParts, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + + // Flush the WAL. Otherwise, we may not recompute the same proposal to sign, + // and the privValidator will refuse to sign anything. + if err := lazyProposer.wal.FlushAndSync(); err != nil { + lazyProposer.Logger.Error("Error flushing to disk") + } + + // Make proposal + propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()} + proposal := types.NewProposal(height, round, lazyProposer.ValidRound, propBlockID) + p := proposal.ToProto() + if err := lazyProposer.privValidator.SignProposal(lazyProposer.state.ChainID, p); err == nil { + proposal.Signature = p.Signature + + // send proposal and block parts on internal msg queue + lazyProposer.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""}) + for i := 0; i < int(blockParts.Total()); i++ { + part := blockParts.GetPart(i) + lazyProposer.sendInternalMessage(msgInfo{&BlockPartMessage{lazyProposer.Height, lazyProposer.Round, part}, ""}) + } + lazyProposer.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) + lazyProposer.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block)) + } else if !lazyProposer.replayMode { + lazyProposer.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err) + } + } + + // start the consensus reactors + for i := 0; i < nValidators; i++ { + s := reactors[i].conS.GetState() + reactors[i].SwitchToConsensus(s, false) + } + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // Evidence should be submitted and committed at the third height but + // we will check the first six just in case + evidenceFromEachValidator := make([]types.Evidence, nValidators) + + wg := new(sync.WaitGroup) + for i := 0; i < nValidators; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + for msg := range blocksSubs[i].Out() { + block := msg.Data().(types.EventDataNewBlock).Block + if len(block.Evidence.Evidence) != 0 { + evidenceFromEachValidator[i] = block.Evidence.Evidence[0] + return + } + } + }(i) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + pubkey, err := bcs.privValidator.GetPubKey() + require.NoError(t, err) + + select { + case <-done: + for idx, ev := range evidenceFromEachValidator { + if assert.NotNil(t, ev, idx) { + ev, ok := ev.(*types.DuplicateVoteEvidence) + assert.True(t, ok) + assert.Equal(t, pubkey.Address(), ev.VoteA.ValidatorAddress) + assert.Equal(t, prevoteHeight, ev.Height()) + } + } + case <-time.After(20 * time.Second): + t.Fatalf("Timed out waiting for validators to commit evidence") + } +} + +// 4 validators. 1 is byzantine. The other three are partitioned into A (1 val) and B (2 vals). +// byzantine validator sends conflicting proposals into A and B, +// and prevotes/precommits on both of them. +// B sees a commit, A doesn't. +// Heal partition and ensure A sees the commit +func TestByzantineConflictingProposalsWithPartition(t *testing.T) { + N := 4 + logger := consensusLogger().With("test", "byzantine") + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + app := newKVStore + css, cleanup := randConsensusNet(t, N, "consensus_byzantine_test", newMockTickerFunc(false), app) + defer cleanup() + + // give the byzantine validator a normal ticker + ticker := NewTimeoutTicker() + ticker.SetLogger(css[0].Logger) + css[0].SetTimeoutTicker(ticker) + + switches := make([]*p2p.Switch, N) + p2pLogger := logger.With("module", "p2p") + for i := 0; i < N; i++ { + switches[i] = p2p.MakeSwitch( + config.P2P, + i, + func(i int, sw *p2p.Switch) *p2p.Switch { + return sw + }) + switches[i].SetLogger(p2pLogger.With("validator", i)) + } + + blocksSubs := make([]types.Subscription, N) + reactors := make([]p2p.Reactor, N) + for i := 0; i < N; i++ { + + // enable txs so we can create different proposals + assertMempool(css[i].txNotifier).EnableTxsAvailable() + // make first val byzantine + if i == 0 { + // NOTE: Now, test validators are MockPV, which by default doesn't + // do any safety checks. + css[i].privValidator.(types.MockPV).DisableChecks() + j := i + css[i].decideProposal = func(height int64, round int32) { + byzantineDecideProposalFunc(ctx, t, height, round, css[j], switches[j]) + } + // We are setting the prevote function to do nothing because the prevoting + // and precommitting are done alongside the proposal. + css[i].doPrevote = func(height int64, round int32) {} + } + + eventBus := css[i].eventBus + eventBus.SetLogger(logger.With("module", "events", "validator", i)) + + var err error + blocksSubs[i], err = eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock) + require.NoError(t, err) + + conR := NewReactor(css[i], true) // so we don't start the consensus states + conR.SetLogger(logger.With("validator", i)) + conR.SetEventBus(eventBus) + + var conRI p2p.Reactor = conR + + // make first val byzantine + if i == 0 { + conRI = NewByzantineReactor(conR) + } + + reactors[i] = conRI + err = css[i].blockExec.Store().Save(css[i].state) // for save height 1's validators info + require.NoError(t, err) + } + + defer func() { + for _, r := range reactors { + if rr, ok := r.(*ByzantineReactor); ok { + err := rr.reactor.Switch.Stop() + require.NoError(t, err) + } else { + err := r.(*Reactor).Switch.Stop() + require.NoError(t, err) + } + } + }() + + p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { + // ignore new switch s, we already made ours + switches[i].AddReactor("CONSENSUS", reactors[i]) + return switches[i] + }, func(sws []*p2p.Switch, i, j int) { + // the network starts partitioned with globally active adversary + if i != 0 { + return + } + p2p.Connect2Switches(sws, i, j) + }) + + // start the non-byz state machines. + // note these must be started before the byz + for i := 1; i < N; i++ { + cr := reactors[i].(*Reactor) + cr.SwitchToConsensus(cr.conS.GetState(), false) + } + + // start the byzantine state machine + byzR := reactors[0].(*ByzantineReactor) + s := byzR.reactor.conS.GetState() + byzR.reactor.SwitchToConsensus(s, false) + + // byz proposer sends one block to peers[0] + // and the other block to peers[1] and peers[2]. + // note peers and switches order don't match. + peers := switches[0].Peers().List() + + // partition A + ind0 := getSwitchIndex(switches, peers[0]) + + // partition B + ind1 := getSwitchIndex(switches, peers[1]) + ind2 := getSwitchIndex(switches, peers[2]) + p2p.Connect2Switches(switches, ind1, ind2) + + // wait for someone in the big partition (B) to make a block + <-blocksSubs[ind2].Out() + + t.Log("A block has been committed. Healing partition") + p2p.Connect2Switches(switches, ind0, ind1) + p2p.Connect2Switches(switches, ind0, ind2) + + // wait till everyone makes the first new block + // (one of them already has) + wg := new(sync.WaitGroup) + for i := 1; i < N-1; i++ { + wg.Add(1) + go func(j int) { + <-blocksSubs[j].Out() + wg.Done() + }(i) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + tick := time.NewTicker(time.Second * 10) + select { + case <-done: + case <-tick.C: + for i, reactor := range reactors { + t.Logf("Consensus Reactor %v", i) + t.Logf("%v", reactor) + } + t.Fatalf("Timed out waiting for all validators to commit first block") + } +} + +//------------------------------- +// byzantine consensus functions + +func byzantineDecideProposalFunc(ctx context.Context, t *testing.T, height int64, round int32, cs *State, sw *p2p.Switch) { + // byzantine user should create two proposals and try to split the vote. + // Avoid sending on internalMsgQueue and running consensus state. + + // Create a new proposal block from state/txs from the mempool. + block1, err := cs.createProposalBlock(ctx) + require.NoError(t, err) + blockParts1, err := block1.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + polRound, propBlockID := cs.ValidRound, types.BlockID{Hash: block1.Hash(), PartSetHeader: blockParts1.Header()} + proposal1 := types.NewProposal(height, round, polRound, propBlockID) + p1 := proposal1.ToProto() + if err := cs.privValidator.SignProposal(cs.state.ChainID, p1); err != nil { + t.Error(err) + } + + proposal1.Signature = p1.Signature + + // some new transactions come in (this ensures that the proposals are different) + deliverTxsRange(t, cs, 0, 1) + + // Create a new proposal block from state/txs from the mempool. + block2, err := cs.createProposalBlock(ctx) + require.NoError(t, err) + blockParts2, err := block2.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + polRound, propBlockID = cs.ValidRound, types.BlockID{Hash: block2.Hash(), PartSetHeader: blockParts2.Header()} + proposal2 := types.NewProposal(height, round, polRound, propBlockID) + p2 := proposal2.ToProto() + if err := cs.privValidator.SignProposal(cs.state.ChainID, p2); err != nil { + t.Error(err) + } + + proposal2.Signature = p2.Signature + + block1Hash := block1.Hash() + block2Hash := block2.Hash() + + // broadcast conflicting proposals/block parts to peers + peers := sw.Peers().List() + t.Logf("Byzantine: broadcasting conflicting proposals to %d peers", len(peers)) + for i, peer := range peers { + if i < len(peers)/2 { + go sendProposalAndParts(height, round, cs, peer, proposal1, block1Hash, blockParts1) + } else { + go sendProposalAndParts(height, round, cs, peer, proposal2, block2Hash, blockParts2) + } + } +} + +func sendProposalAndParts( + height int64, + round int32, + cs *State, + peer p2p.Peer, + proposal *types.Proposal, + blockHash []byte, + parts *types.PartSet, +) { + // proposal + peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.Proposal{Proposal: *proposal.ToProto()}, + }) + + // parts + for i := 0; i < int(parts.Total()); i++ { + part := parts.GetPart(i) + pp, err := part.ToProto() + if err != nil { + panic(err) // TODO: wbanfield better error handling + } + peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.BlockPart{ + Height: height, // This tells peer that this part applies to us. + Round: round, // This tells peer that this part applies to us. + Part: *pp, + }, + }) + } + + // votes + cs.mtx.Lock() + prevote, _ := cs.signVote(cmtproto.PrevoteType, blockHash, parts.Header(), nil) + precommit, _ := cs.signVote(cmtproto.PrecommitType, blockHash, parts.Header(), nil) + cs.mtx.Unlock() + peer.Send(p2p.Envelope{ + ChannelID: VoteChannel, + Message: &cmtcons.Vote{Vote: prevote.ToProto()}, + }) + peer.Send(p2p.Envelope{ + ChannelID: VoteChannel, + Message: &cmtcons.Vote{Vote: precommit.ToProto()}, + }) +} + +//---------------------------------------- +// byzantine consensus reactor + +type ByzantineReactor struct { + service.Service + reactor *Reactor +} + +func NewByzantineReactor(conR *Reactor) *ByzantineReactor { + return &ByzantineReactor{ + Service: conR, + reactor: conR, + } +} + +func (br *ByzantineReactor) SetSwitch(s *p2p.Switch) { br.reactor.SetSwitch(s) } +func (br *ByzantineReactor) GetChannels() []*p2p.ChannelDescriptor { return br.reactor.GetChannels() } +func (br *ByzantineReactor) AddPeer(peer p2p.Peer) { + if !br.reactor.IsRunning() { + return + } + + // Create peerState for peer + peerState := NewPeerState(peer).SetLogger(br.reactor.Logger) + peer.Set(types.PeerStateKey, peerState) + + // Send our state to peer. + // If we're syncing, broadcast a RoundStepMessage later upon SwitchToConsensus(). + if !br.reactor.waitSync { + br.reactor.sendNewRoundStepMessage(peer) + } +} + +func (br *ByzantineReactor) RemovePeer(peer p2p.Peer, reason interface{}) { + br.reactor.RemovePeer(peer, reason) +} + +func (br *ByzantineReactor) Receive(e p2p.Envelope) { + br.reactor.Receive(e) +} + +func (br *ByzantineReactor) InitPeer(peer p2p.Peer) p2p.Peer { return peer } + +// Large/oversized proposals should be rejected +func TestRejectOversizedProposals(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + n := 2 + css, cleanup := randConsensusNet(t, n, "consensus_reactor_test", newMockTickerFunc(false), newKVStore) + defer cleanup() + + switches := make([]*p2p.Switch, n) + p2pLogger := consensusLogger().With("module", "p2p") + for i := 0; i < n; i++ { + switches[i] = p2p.MakeSwitch( + config.P2P, + i, + func(_ int, sw *p2p.Switch) *p2p.Switch { + return sw + }) + switches[i].SetLogger(p2pLogger.With("validator", i)) + } + + reactors := make([]p2p.Reactor, n) + for i := 0; i < n; i++ { + conR := NewReactor(css[i], false) + defer func() { require.NoError(t, conR.Stop()) }() + + conR.SetLogger(consensusLogger().With("validator", i)) + reactors[i] = conR + } + + p2p.MakeConnectedSwitches(config.P2P, n, func(i int, _ *p2p.Switch) *p2p.Switch { + switches[i].AddReactor("CONSENSUS", reactors[i]) + return switches[i] + }, p2p.Connect2Switches) + + peers := switches[0].Peers().List() + targetPeer := peers[0] + + height := int64(1) + round := int32(0) + cs := css[0] + + block, err := cs.createProposalBlock(ctx) + require.NoError(t, err) + + blockParts, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + + // create oversized proposal + propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()} + propBlockID.PartSetHeader.Total = 4294967295 + + proposal := types.NewProposal(height, round, -1, propBlockID) + p := proposal.ToProto() + if err := cs.privValidator.SignProposal(cs.state.ChainID, p); err != nil { + t.Error(err) + } + proposal.Signature = p.Signature + + success := targetPeer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.Proposal{Proposal: *proposal.ToProto()}, + }) + require.True(t, success) + + select { + case e := <-css[1].peerMsgQueue: + // if we receive a message here, the peer incorrectly accepted the + // oversized proposal + if _, receivedProposal := e.Msg.(*ProposalMessage); receivedProposal { + assert.Fail(t, "peer incorrectly accepted oversized proposal") + return + } + // invalid state, we received some other unexpected message type, fail + // the test + assert.Fail(t, "received unexpected message type on peer msg queue, expected *ProposalMessage") + case <-ctx.Done(): + case <-time.After(500 * time.Millisecond): + // timeout after 500ms if nothing has happened and assume peer rejected + // the proposal + } +} diff --git a/consensus/common_test.go b/consensus/common_test.go new file mode 100644 index 0000000..b5f5051 --- /dev/null +++ b/consensus/common_test.go @@ -0,0 +1,991 @@ +package consensus + +import ( + "bytes" + "context" + "fmt" + "os" + "path" + "path/filepath" + "sort" + "sync" + "testing" + "time" + + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + cfg "github.com/cometbft/cometbft/config" + cstypes "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/internal/test" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtsync "github.com/cometbft/cometbft/libs/sync" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const ( + testSubscriber = "test-client" +) + +// A cleanupFunc cleans up any config / test files created for a particular +// test. +type cleanupFunc func() + +// genesis, chain_id, priv_val +var ( + config *cfg.Config // NOTE: must be reset for each _test.go file + consensusReplayConfig *cfg.Config + ensureTimeout = time.Millisecond * 200 +) + +func ensureDir(dir string, mode os.FileMode) { + if err := cmtos.EnsureDir(dir, mode); err != nil { + panic(err) + } +} + +func ResetConfig(name string) *cfg.Config { + return test.ResetTestRoot(name) +} + +//------------------------------------------------------------------------------- +// validator stub (a kvstore consensus peer we control) + +type validatorStub struct { + Index int32 // Validator index. NOTE: we don't assume validator set changes. + Height int64 + Round int32 + types.PrivValidator + VotingPower int64 + lastVote *types.Vote +} + +var testMinPower int64 = 10 + +func newValidatorStub(privValidator types.PrivValidator, valIndex int32) *validatorStub { + return &validatorStub{ + Index: valIndex, + PrivValidator: privValidator, + VotingPower: testMinPower, + } +} + +func (vs *validatorStub) signVote( + voteType cmtproto.SignedMsgType, + hash []byte, + header types.PartSetHeader, + voteExtension []byte, + extEnabled bool, +) (*types.Vote, error) { + pubKey, err := vs.GetPubKey() + if err != nil { + return nil, fmt.Errorf("can't get pubkey: %w", err) + } + vote := &types.Vote{ + Type: voteType, + Height: vs.Height, + Round: vs.Round, + BlockID: types.BlockID{Hash: hash, PartSetHeader: header}, + Timestamp: cmttime.Now(), + ValidatorAddress: pubKey.Address(), + ValidatorIndex: vs.Index, + Extension: voteExtension, + } + v := vote.ToProto() + if err = vs.SignVote(test.DefaultTestChainID, v); err != nil { + return nil, fmt.Errorf("sign vote failed: %w", err) + } + + // ref: signVote in FilePV, the vote should use the previous vote info when the sign data is the same. + if signDataIsEqual(vs.lastVote, v) { + v.Signature = vs.lastVote.Signature + v.Timestamp = vs.lastVote.Timestamp + v.ExtensionSignature = vs.lastVote.ExtensionSignature + } + + vote.Signature = v.Signature + vote.Timestamp = v.Timestamp + vote.ExtensionSignature = v.ExtensionSignature + + if !extEnabled { + vote.ExtensionSignature = nil + } + + return vote, err +} + +// Sign vote for type/hash/header +func signVote(vs *validatorStub, voteType cmtproto.SignedMsgType, hash []byte, header types.PartSetHeader, extEnabled bool) *types.Vote { + var ext []byte + // Only non-nil precommits are allowed to carry vote extensions. + if extEnabled { + if voteType != cmtproto.PrecommitType { + panic(fmt.Errorf("vote type is not precommit but extensions enabled")) + } + if len(hash) != 0 || !header.IsZero() { + ext = []byte("extension") + } + } + v, err := vs.signVote(voteType, hash, header, ext, extEnabled) + + if err != nil { + panic(fmt.Errorf("failed to sign vote: %v", err)) + } + + vs.lastVote = v + + return v +} + +func signVotes( + voteType cmtproto.SignedMsgType, + hash []byte, + header types.PartSetHeader, + extEnabled bool, + vss ...*validatorStub, +) []*types.Vote { + votes := make([]*types.Vote, len(vss)) + for i, vs := range vss { + votes[i] = signVote(vs, voteType, hash, header, extEnabled) + } + return votes +} + +func incrementHeight(vss ...*validatorStub) { + for _, vs := range vss { + vs.Height++ + } +} + +func incrementRound(vss ...*validatorStub) { + for _, vs := range vss { + vs.Round++ + } +} + +type ValidatorStubsByPower []*validatorStub + +func (vss ValidatorStubsByPower) Len() int { + return len(vss) +} + +func (vss ValidatorStubsByPower) Less(i, j int) bool { + vssi, err := vss[i].GetPubKey() + if err != nil { + panic(err) + } + vssj, err := vss[j].GetPubKey() + if err != nil { + panic(err) + } + + if vss[i].VotingPower == vss[j].VotingPower { + return bytes.Compare(vssi.Address(), vssj.Address()) == -1 + } + return vss[i].VotingPower > vss[j].VotingPower +} + +func (vss ValidatorStubsByPower) Swap(i, j int) { + it := vss[i] + vss[i] = vss[j] + vss[i].Index = int32(i) + vss[j] = it + vss[j].Index = int32(j) +} + +//------------------------------------------------------------------------------- +// Functions for transitioning the consensus state + +func startTestRound(cs *State, height int64, round int32) { + cs.enterNewRound(height, round) + cs.startRoutines(0) +} + +// Create proposal block from cs1 but sign it with vs. +func decideProposal( + ctx context.Context, + t *testing.T, + cs1 *State, + vs *validatorStub, + height int64, + round int32, +) (*types.Proposal, *types.Block) { + cs1.mtx.Lock() + block, err := cs1.createProposalBlock(ctx) + require.NoError(t, err) + blockParts, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + validRound := cs1.ValidRound + chainID := cs1.state.ChainID + cs1.mtx.Unlock() + if block == nil { + panic("Failed to createProposalBlock. Did you forget to add commit for previous block?") + } + + // Make proposal + polRound, propBlockID := validRound, types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()} + proposal := types.NewProposal(height, round, polRound, propBlockID) + p := proposal.ToProto() + if err := vs.SignProposal(chainID, p); err != nil { + panic(err) + } + + proposal.Signature = p.Signature + + return proposal, block +} + +func addVotes(to *State, votes ...*types.Vote) { + for _, vote := range votes { + to.peerMsgQueue <- msgInfo{Msg: &VoteMessage{vote}} + } +} + +func signAddVotes( + to *State, + voteType cmtproto.SignedMsgType, + hash []byte, + header types.PartSetHeader, + extEnabled bool, + vss ...*validatorStub, +) { + votes := signVotes(voteType, hash, header, extEnabled, vss...) + addVotes(to, votes...) +} + +func validatePrevote(t *testing.T, cs *State, round int32, privVal *validatorStub, blockHash []byte) { + prevotes := cs.Votes.Prevotes(round) + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) + address := pubKey.Address() + var vote *types.Vote + if vote = prevotes.GetByAddress(address); vote == nil { + panic("Failed to find prevote from validator") + } + if blockHash == nil { + if vote.BlockID.Hash != nil { + panic(fmt.Sprintf("Expected prevote to be for nil, got %X", vote.BlockID.Hash)) + } + } else { + if !bytes.Equal(vote.BlockID.Hash, blockHash) { + panic(fmt.Sprintf("Expected prevote to be for %X, got %X", blockHash, vote.BlockID.Hash)) + } + } +} + +func validateLastPrecommit(t *testing.T, cs *State, privVal *validatorStub, blockHash []byte) { + votes := cs.LastCommit + pv, err := privVal.GetPubKey() + require.NoError(t, err) + address := pv.Address() + var vote *types.Vote + if vote = votes.GetByAddress(address); vote == nil { + panic("Failed to find precommit from validator") + } + if !bytes.Equal(vote.BlockID.Hash, blockHash) { + panic(fmt.Sprintf("Expected precommit to be for %X, got %X", blockHash, vote.BlockID.Hash)) + } +} + +func validatePrecommit( + t *testing.T, + cs *State, + thisRound, + lockRound int32, + privVal *validatorStub, + votedBlockHash, + lockedBlockHash []byte, +) { + precommits := cs.Votes.Precommits(thisRound) + pv, err := privVal.GetPubKey() + require.NoError(t, err) + address := pv.Address() + var vote *types.Vote + if vote = precommits.GetByAddress(address); vote == nil { + panic("Failed to find precommit from validator") + } + + if votedBlockHash == nil { + if vote.BlockID.Hash != nil { + panic("Expected precommit to be for nil") + } + } else { + if !bytes.Equal(vote.BlockID.Hash, votedBlockHash) { + panic("Expected precommit to be for proposal block") + } + } + + rs := cs.GetRoundState() + if lockedBlockHash == nil { + if rs.LockedRound != lockRound || rs.LockedBlock != nil { + panic(fmt.Sprintf( + "Expected to be locked on nil at round %d. Got locked at round %d with block %v", + lockRound, + rs.LockedRound, + rs.LockedBlock)) + } + } else { + if rs.LockedRound != lockRound || !bytes.Equal(rs.LockedBlock.Hash(), lockedBlockHash) { + panic(fmt.Sprintf( + "Expected block to be locked on round %d, got %d. Got locked block %X, expected %X", + lockRound, + rs.LockedRound, + rs.LockedBlock.Hash(), + lockedBlockHash)) + } + } +} + +func subscribeToVoter(cs *State, addr []byte) <-chan cmtpubsub.Message { + votesSub, err := cs.eventBus.SubscribeUnbuffered(context.Background(), testSubscriber, types.EventQueryVote) + if err != nil { + panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, types.EventQueryVote)) + } + ch := make(chan cmtpubsub.Message) + go func() { + for msg := range votesSub.Out() { + vote := msg.Data().(types.EventDataVote) + // we only fire for our own votes + if bytes.Equal(addr, vote.Vote.ValidatorAddress) { + ch <- msg + } + } + }() + return ch +} + +//------------------------------------------------------------------------------- +// consensus states + +func newState(state sm.State, pv types.PrivValidator, app abci.Application) *State { + config := test.ResetTestRoot("consensus_state_test") + return newStateWithConfig(config, state, pv, app) +} + +func newStateWithConfig( + thisConfig *cfg.Config, + state sm.State, + pv types.PrivValidator, + app abci.Application, +) *State { + blockDB := dbm.NewMemDB() + return newStateWithConfigAndBlockStore(thisConfig, state, pv, app, blockDB) +} + +func newStateWithConfigAndBlockStore( + thisConfig *cfg.Config, + state sm.State, + pv types.PrivValidator, + app abci.Application, + blockDB dbm.DB, +) *State { + // Get BlockStore + blockStore := store.NewBlockStore(blockDB) + + // one for mempool, one for consensus + mtx := new(cmtsync.Mutex) + + proxyAppConnCon := proxy.NewAppConnConsensus(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + proxyAppConnMem := proxy.NewAppConnMempool(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + // Make Mempool + memplMetrics := mempl.NopMetrics() + + // Make Mempool + mempool := mempl.NewCListMempool(config.Mempool, + proxyAppConnMem, + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state))) + + if thisConfig.Consensus.WaitForTxs() { + mempool.EnableTxsAvailable() + } + + evpool := sm.EmptyEvidencePool{} + + // Make State + stateDB := blockDB + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + if err := stateStore.Save(state); err != nil { // for save height 1's validators info + panic(err) + } + + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore) + cs := NewState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool) + cs.SetLogger(log.TestingLogger().With("module", "consensus")) + cs.SetPrivValidator(pv) + + eventBus := types.NewEventBus() + eventBus.SetLogger(log.TestingLogger().With("module", "events")) + err := eventBus.Start() + if err != nil { + panic(err) + } + cs.SetEventBus(eventBus) + return cs +} + +func loadPrivValidator(config *cfg.Config) *privval.FilePV { + privValidatorKeyFile := config.PrivValidatorKeyFile() + ensureDir(filepath.Dir(privValidatorKeyFile), 0o700) + privValidatorStateFile := config.PrivValidatorStateFile() + privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile) + privValidator.Reset() + return privValidator +} + +func randState(nValidators int) (*State, []*validatorStub) { + return randStateWithApp(nValidators, kvstore.NewInMemoryApplication()) +} + +func randStateWithAppWithHeight( + nValidators int, + app abci.Application, + height int64, +) (*State, []*validatorStub) { + c := test.ConsensusParams() + c.ABCI.VoteExtensionsEnableHeight = height + return randStateWithAppImpl(nValidators, app, c) +} +func randStateWithApp(nValidators int, app abci.Application) (*State, []*validatorStub) { + c := test.ConsensusParams() + return randStateWithAppImpl(nValidators, app, c) +} + +func randStateWithAppImpl( + nValidators int, + app abci.Application, + consensusParams *types.ConsensusParams, +) (*State, []*validatorStub) { + // Get State + state, privVals := randGenesisState(nValidators, false, 10, consensusParams) + + vss := make([]*validatorStub, nValidators) + + cs := newState(state, privVals[0], app) + + for i := 0; i < nValidators; i++ { + vss[i] = newValidatorStub(privVals[i], int32(i)) + } + // since cs1 starts at 1 + incrementHeight(vss[1:]...) + + return cs, vss +} + +//------------------------------------------------------------------------------- + +func ensureNoNewEvent(ch <-chan cmtpubsub.Message, timeout time.Duration, + errorMessage string, +) { + select { + case <-time.After(timeout): + break + case <-ch: + panic(errorMessage) + } +} + +func ensureNoNewEventOnChannel(ch <-chan cmtpubsub.Message) { + ensureNoNewEvent( + ch, + ensureTimeout*8/10, // 20% leniency for goroutine scheduling uncertainty + "We should be stuck waiting, not receiving new event on the channel") +} + +func ensureNoNewRoundStep(stepCh <-chan cmtpubsub.Message) { + ensureNoNewEvent( + stepCh, + ensureTimeout, + "We should be stuck waiting, not receiving NewRoundStep event") +} + +func ensureNoNewUnlock(unlockCh <-chan cmtpubsub.Message) { + ensureNoNewEvent( + unlockCh, + ensureTimeout, + "We should be stuck waiting, not receiving Unlock event") +} + +func ensureNoNewTimeout(stepCh <-chan cmtpubsub.Message, timeout int64) { + timeoutDuration := time.Duration(timeout*10) * time.Nanosecond + ensureNoNewEvent( + stepCh, + timeoutDuration, + "We should be stuck waiting, not receiving NewTimeout event") +} + +func ensureNewEvent(ch <-chan cmtpubsub.Message, height int64, round int32, timeout time.Duration, errorMessage string) { + select { + case <-time.After(timeout): + panic(errorMessage) + case msg := <-ch: + roundStateEvent, ok := msg.Data().(types.EventDataRoundState) + if !ok { + panic(fmt.Sprintf("expected a EventDataRoundState, got %T. Wrong subscription channel?", + msg.Data())) + } + if roundStateEvent.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, roundStateEvent.Height)) + } + if roundStateEvent.Round != round { + panic(fmt.Sprintf("expected round %v, got %v", round, roundStateEvent.Round)) + } + // TODO: We could check also for a step at this point! + } +} + +func ensureNewRound(roundCh <-chan cmtpubsub.Message, height int64, round int32) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewRound event") + case msg := <-roundCh: + newRoundEvent, ok := msg.Data().(types.EventDataNewRound) + if !ok { + panic(fmt.Sprintf("expected a EventDataNewRound, got %T. Wrong subscription channel?", + msg.Data())) + } + if newRoundEvent.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, newRoundEvent.Height)) + } + if newRoundEvent.Round != round { + panic(fmt.Sprintf("expected round %v, got %v", round, newRoundEvent.Round)) + } + } +} + +func ensureNewTimeout(timeoutCh <-chan cmtpubsub.Message, height int64, round int32, timeout int64) { + timeoutDuration := time.Duration(timeout*10) * time.Nanosecond + ensureNewEvent(timeoutCh, height, round, timeoutDuration, + "Timeout expired while waiting for NewTimeout event") +} + +func ensureNewProposal(proposalCh <-chan cmtpubsub.Message, height int64, round int32) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewProposal event") + case msg := <-proposalCh: + proposalEvent, ok := msg.Data().(types.EventDataCompleteProposal) + if !ok { + panic(fmt.Sprintf("expected a EventDataCompleteProposal, got %T. Wrong subscription channel?", + msg.Data())) + } + if proposalEvent.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, proposalEvent.Height)) + } + if proposalEvent.Round != round { + panic(fmt.Sprintf("expected round %v, got %v", round, proposalEvent.Round)) + } + } +} + +func ensureNewValidBlock(validBlockCh <-chan cmtpubsub.Message, height int64, round int32) { + ensureNewEvent(validBlockCh, height, round, ensureTimeout, + "Timeout expired while waiting for NewValidBlock event") +} + +func ensureNewBlock(blockCh <-chan cmtpubsub.Message, height int64) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewBlock event") + case msg := <-blockCh: + blockEvent, ok := msg.Data().(types.EventDataNewBlock) + if !ok { + panic(fmt.Sprintf("expected a EventDataNewBlock, got %T. Wrong subscription channel?", + msg.Data())) + } + if blockEvent.Block.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, blockEvent.Block.Height)) + } + } +} + +func ensureNewBlockHeader(blockCh <-chan cmtpubsub.Message, height int64, blockHash cmtbytes.HexBytes) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewBlockHeader event") + case msg := <-blockCh: + blockHeaderEvent, ok := msg.Data().(types.EventDataNewBlockHeader) + if !ok { + panic(fmt.Sprintf("expected a EventDataNewBlockHeader, got %T. Wrong subscription channel?", + msg.Data())) + } + if blockHeaderEvent.Header.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, blockHeaderEvent.Header.Height)) + } + if !bytes.Equal(blockHeaderEvent.Header.Hash(), blockHash) { + panic(fmt.Sprintf("expected header %X, got %X", blockHash, blockHeaderEvent.Header.Hash())) + } + } +} + +func ensureNewUnlock(unlockCh <-chan cmtpubsub.Message, height int64, round int32) { + ensureNewEvent(unlockCh, height, round, ensureTimeout, + "Timeout expired while waiting for NewUnlock event") +} + +func ensureProposal(proposalCh <-chan cmtpubsub.Message, height int64, round int32, propID types.BlockID) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewProposal event") + case msg := <-proposalCh: + proposalEvent, ok := msg.Data().(types.EventDataCompleteProposal) + if !ok { + panic(fmt.Sprintf("expected a EventDataCompleteProposal, got %T. Wrong subscription channel?", + msg.Data())) + } + if proposalEvent.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, proposalEvent.Height)) + } + if proposalEvent.Round != round { + panic(fmt.Sprintf("expected round %v, got %v", round, proposalEvent.Round)) + } + if !proposalEvent.BlockID.Equals(propID) { + panic(fmt.Sprintf("Proposed block does not match expected block (%v != %v)", proposalEvent.BlockID, propID)) + } + } +} + +func ensurePrecommit(voteCh <-chan cmtpubsub.Message, height int64, round int32) { + ensureVote(voteCh, height, round, cmtproto.PrecommitType) +} + +func ensurePrevote(voteCh <-chan cmtpubsub.Message, height int64, round int32) { + ensureVote(voteCh, height, round, cmtproto.PrevoteType) +} + +func ensureVote(voteCh <-chan cmtpubsub.Message, height int64, round int32, + voteType cmtproto.SignedMsgType, +) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for NewVote event") + case msg := <-voteCh: + voteEvent, ok := msg.Data().(types.EventDataVote) + if !ok { + panic(fmt.Sprintf("expected a EventDataVote, got %T. Wrong subscription channel?", + msg.Data())) + } + vote := voteEvent.Vote + if vote.Height != height { + panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height)) + } + if vote.Round != round { + panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round)) + } + if vote.Type != voteType { + panic(fmt.Sprintf("expected type %v, got %v", voteType, vote.Type)) + } + } +} + +func ensurePrevoteMatch(t *testing.T, voteCh <-chan cmtpubsub.Message, height int64, round int32, hash []byte) { + t.Helper() + ensureVoteMatch(t, voteCh, height, round, hash, cmtproto.PrevoteType) +} + +func ensurePrecommitMatch(t *testing.T, voteCh <-chan cmtpubsub.Message, height int64, round int32, hash []byte) { + t.Helper() + ensureVoteMatch(t, voteCh, height, round, hash, cmtproto.PrecommitType) +} + +func ensureVoteMatch(t *testing.T, voteCh <-chan cmtpubsub.Message, height int64, round int32, hash []byte, voteType cmtproto.SignedMsgType) { + t.Helper() + select { + case <-time.After(ensureTimeout): + t.Fatal("Timeout expired while waiting for NewVote event") + case msg := <-voteCh: + voteEvent, ok := msg.Data().(types.EventDataVote) + require.True(t, ok, "expected a EventDataVote, got %T. Wrong subscription channel?", + msg.Data()) + + vote := voteEvent.Vote + assert.Equal(t, height, vote.Height, "expected height %d, but got %d", height, vote.Height) + assert.Equal(t, round, vote.Round, "expected round %d, but got %d", round, vote.Round) + assert.Equal(t, voteType, vote.Type, "expected type %s, but got %s", voteType, vote.Type) + if hash == nil { + require.Nil(t, vote.BlockID.Hash, "Expected prevote to be for nil, got %X", vote.BlockID.Hash) + } else { + require.True(t, bytes.Equal(vote.BlockID.Hash, hash), "Expected prevote to be for %X, got %X", hash, vote.BlockID.Hash) + } + } +} + +func ensurePrecommitTimeout(ch <-chan cmtpubsub.Message) { + select { + case <-time.After(ensureTimeout): + panic("Timeout expired while waiting for the Precommit to Timeout") + case <-ch: + } +} + +func ensureNewEventOnChannel(ch <-chan cmtpubsub.Message) { + select { + case <-time.After(ensureTimeout * 12 / 10): // 20% leniency for goroutine scheduling uncertainty + panic("Timeout expired while waiting for new activity on the channel") + case <-ch: + } +} + +//------------------------------------------------------------------------------- +// consensus nets + +// consensusLogger is a TestingLogger which uses a different +// color for each validator ("validator" key must exist). +func consensusLogger() log.Logger { + return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor { + for i := 0; i < len(keyvals)-1; i += 2 { + if keyvals[i] == "validator" { + return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))} + } + } + return term.FgBgColor{} + }).With("module", "consensus") +} + +func randConsensusNet(t *testing.T, nValidators int, testName string, tickerFunc func() TimeoutTicker, + appFunc func() abci.Application, configOpts ...func(*cfg.Config)) ([]*State, cleanupFunc) { + t.Helper() + genDoc, privVals := randGenesisDoc(nValidators, false, 30, nil) + css := make([]*State, nValidators) + logger := consensusLogger() + configRootDirs := make([]string, 0, nValidators) + for i := 0; i < nValidators; i++ { + stateDB := dbm.NewMemDB() // each state needs its own db + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) + configRootDirs = append(configRootDirs, thisConfig.RootDir) + for _, opt := range configOpts { + opt(thisConfig) + } + ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal + app := appFunc() + vals := types.TM2PB.ValidatorUpdates(state.Validators) + _, err := app.InitChain(context.Background(), &abci.RequestInitChain{Validators: vals}) + require.NoError(t, err) + + css[i] = newStateWithConfigAndBlockStore(thisConfig, state, privVals[i], app, stateDB) + css[i].SetTimeoutTicker(tickerFunc()) + css[i].SetLogger(logger.With("validator", i, "module", "consensus")) + } + return css, func() { + for _, dir := range configRootDirs { + os.RemoveAll(dir) + } + } +} + +// nPeers = nValidators + nNotValidator +func randConsensusNetWithPeers( + t *testing.T, + nValidators, + nPeers int, + testName string, + tickerFunc func() TimeoutTicker, + appFunc func(string) abci.Application, +) ([]*State, *types.GenesisDoc, *cfg.Config, cleanupFunc) { + c := test.ConsensusParams() + genDoc, privVals := randGenesisDoc(nValidators, false, testMinPower, c) + css := make([]*State, nPeers) + logger := consensusLogger() + var peer0Config *cfg.Config + configRootDirs := make([]string, 0, nPeers) + for i := 0; i < nPeers; i++ { + stateDB := dbm.NewMemDB() // each state needs its own db + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + t.Cleanup(func() { _ = stateStore.Close() }) + state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) + configRootDirs = append(configRootDirs, thisConfig.RootDir) + ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal + if i == 0 { + peer0Config = thisConfig + } + var privVal types.PrivValidator + if i < nValidators { + privVal = privVals[i] + } else { + tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") + if err != nil { + panic(err) + } + tempStateFile, err := os.CreateTemp("", "priv_validator_state_") + if err != nil { + panic(err) + } + + privVal = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name()) + } + + app := appFunc(path.Join(config.DBDir(), fmt.Sprintf("%s_%d", testName, i))) + vals := types.TM2PB.ValidatorUpdates(state.Validators) + if _, ok := app.(*kvstore.Application); ok { + // simulate handshake, receive app version. If don't do this, replay test will fail + state.Version.Consensus.App = kvstore.AppVersion + } + _, err := app.InitChain(context.Background(), &abci.RequestInitChain{Validators: vals}) + require.NoError(t, err) + + css[i] = newStateWithConfig(thisConfig, state, privVal, app) + css[i].SetTimeoutTicker(tickerFunc()) + css[i].SetLogger(logger.With("validator", i, "module", "consensus")) + } + return css, genDoc, peer0Config, func() { + for _, dir := range configRootDirs { + os.RemoveAll(dir) + } + } +} + +func getSwitchIndex(switches []*p2p.Switch, peer p2p.Peer) int { + for i, s := range switches { + if peer.NodeInfo().ID() == s.NodeInfo().ID() { + return i + } + } + panic("didnt find peer in switches") +} + +//------------------------------------------------------------------------------- +// genesis + +func randGenesisDoc(numValidators int, + randPower bool, + minPower int64, + consensusParams *types.ConsensusParams, +) (*types.GenesisDoc, []types.PrivValidator) { + validators := make([]types.GenesisValidator, numValidators) + privValidators := make([]types.PrivValidator, numValidators) + for i := 0; i < numValidators; i++ { + val, privVal := types.RandValidator(randPower, minPower) + validators[i] = types.GenesisValidator{ + PubKey: val.PubKey, + Power: val.VotingPower, + } + privValidators[i] = privVal + } + sort.Sort(types.PrivValidatorsByAddress(privValidators)) + + return &types.GenesisDoc{ + GenesisTime: cmttime.Now(), + InitialHeight: 1, + ChainID: test.DefaultTestChainID, + Validators: validators, + ConsensusParams: consensusParams, + }, privValidators +} + +func randGenesisState( + numValidators int, + randPower bool, + minPower int64, + consensusParams *types.ConsensusParams, +) (sm.State, []types.PrivValidator) { + genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower, consensusParams) + s0, _ := sm.MakeGenesisState(genDoc) + return s0, privValidators +} + +//------------------------------------ +// mock ticker + +func newMockTickerFunc(onlyOnce bool) func() TimeoutTicker { + return func() TimeoutTicker { + return &mockTicker{ + c: make(chan timeoutInfo, 10), + onlyOnce: onlyOnce, + } + } +} + +// mock ticker only fires on RoundStepNewHeight +// and only once if onlyOnce=true +type mockTicker struct { + c chan timeoutInfo + + mtx sync.Mutex + onlyOnce bool + fired bool +} + +func (m *mockTicker) Start() error { + return nil +} + +func (m *mockTicker) Stop() error { + return nil +} + +func (m *mockTicker) ScheduleTimeout(ti timeoutInfo) { + m.mtx.Lock() + defer m.mtx.Unlock() + if m.onlyOnce && m.fired { + return + } + if ti.Step == cstypes.RoundStepNewHeight { + m.c <- ti + m.fired = true + } +} + +func (m *mockTicker) Chan() <-chan timeoutInfo { + return m.c +} + +func (*mockTicker) SetLogger(log.Logger) {} + +func newPersistentKVStore() abci.Application { + dir, err := os.MkdirTemp("", "persistent-kvstore") + if err != nil { + panic(err) + } + return kvstore.NewPersistentApplication(dir) +} + +func newKVStore() abci.Application { + return kvstore.NewInMemoryApplication() +} + +func newPersistentKVStoreWithPath(dbDir string) abci.Application { + return kvstore.NewPersistentApplication(dbDir) +} + +func signDataIsEqual(v1 *types.Vote, v2 *cmtproto.Vote) bool { + if v1 == nil || v2 == nil { + return false + } + + return v1.Type == v2.Type && + bytes.Equal(v1.BlockID.Hash, v2.BlockID.GetHash()) && + v1.Height == v2.GetHeight() && + v1.Round == v2.Round && + bytes.Equal(v1.ValidatorAddress.Bytes(), v2.GetValidatorAddress()) && + v1.ValidatorIndex == v2.GetValidatorIndex() && + bytes.Equal(v1.Extension, v2.Extension) +} diff --git a/consensus/errors.go b/consensus/errors.go new file mode 100644 index 0000000..98cbdca --- /dev/null +++ b/consensus/errors.go @@ -0,0 +1,9 @@ +package consensus + +type ErrInvalidVote struct { + Reason string +} + +func (e ErrInvalidVote) Error() string { + return "invalid vote: " + e.Reason +} diff --git a/consensus/invalid_test.go b/consensus/invalid_test.go new file mode 100644 index 0000000..76ab85c --- /dev/null +++ b/consensus/invalid_test.go @@ -0,0 +1,113 @@ +package consensus + +import ( + "testing" + "time" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +//---------------------------------------------- +// byzantine failures + +// one byz val sends a precommit for a random block at each height +// Ensure a testnet makes blocks +func TestReactorInvalidPrecommit(t *testing.T) { + N := 4 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore, + func(c *cfg.Config) { + c.Consensus.TimeoutPropose = 3000 * time.Millisecond + c.Consensus.TimeoutPrevote = 1000 * time.Millisecond + c.Consensus.TimeoutPrecommit = 1000 * time.Millisecond + }) + defer cleanup() + + for i := 0; i < N; i++ { + ticker := NewTimeoutTicker() + ticker.SetLogger(css[i].Logger) + css[i].SetTimeoutTicker(ticker) + + } + + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // this val sends a random precommit at each height + byzValIdx := N - 1 + byzVal := css[byzValIdx] + byzR := reactors[byzValIdx] + + // update the doPrevote function to just send a valid precommit for a random block + // and otherwise disable the priv validator + byzVal.mtx.Lock() + pv := byzVal.privValidator + byzVal.doPrevote = func(int64, int32) { + invalidDoPrevoteFunc(t, byzVal, byzR.Switch, pv) + } + byzVal.mtx.Unlock() + + // wait for a bunch of blocks + // TODO: make this tighter by ensuring the halt happens by block 2 + for i := 0; i < 10; i++ { + timeoutWaitGroup(N, func(j int) { + <-blocksSubs[j].Out() + }) + } +} + +func invalidDoPrevoteFunc(t *testing.T, cs *State, sw *p2p.Switch, pv types.PrivValidator) { + // routine to: + // - precommit for a random block + // - send precommit to all peers + // - disable privValidator (so we don't do normal precommits) + go func() { + cs.mtx.Lock() + defer cs.mtx.Unlock() + cs.privValidator = pv + pubKey, err := cs.privValidator.GetPubKey() + if err != nil { + panic(err) + } + addr := pubKey.Address() + valIndex, _ := cs.Validators.GetByAddress(addr) + + // precommit a random block + blockHash := bytes.HexBytes(cmtrand.Bytes(32)) + precommit := &types.Vote{ + ValidatorAddress: addr, + ValidatorIndex: valIndex, + Height: cs.Height, + Round: cs.Round, + Timestamp: cs.voteTime(), + Type: cmtproto.PrecommitType, + BlockID: types.BlockID{ + Hash: blockHash, + PartSetHeader: types.PartSetHeader{Total: 1, Hash: cmtrand.Bytes(32)}, + }, + } + p := precommit.ToProto() + err = cs.privValidator.SignVote(cs.state.ChainID, p) + if err != nil { + t.Error(err) + } + precommit.Signature = p.Signature + precommit.ExtensionSignature = p.ExtensionSignature + cs.privValidator = nil // disable priv val so we don't do normal votes + + peers := sw.Peers().List() + for _, peer := range peers { + cs.Logger.Info("Sending bad vote", "block", blockHash, "peer", peer) + peer.Send(p2p.Envelope{ + Message: &cmtcons.Vote{Vote: precommit.ToProto()}, + ChannelID: VoteChannel, + }) + } + }() +} diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go new file mode 100644 index 0000000..1bf961d --- /dev/null +++ b/consensus/mempool_test.go @@ -0,0 +1,211 @@ +package consensus + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +// for testing +func assertMempool(txn txNotifier) mempl.Mempool { + return txn.(mempl.Mempool) +} + +func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) { + config := ResetConfig("consensus_mempool_txs_available_test") + defer os.RemoveAll(config.RootDir) + config.Consensus.CreateEmptyBlocks = false + state, privVals := randGenesisState(1, false, 10, nil) + app := kvstore.NewInMemoryApplication() + resp, err := app.Info(context.Background(), proxy.RequestInfo) + require.NoError(t, err) + state.AppHash = resp.LastBlockAppHash + cs := newStateWithConfig(config, state, privVals[0], app) + assertMempool(cs.txNotifier).EnableTxsAvailable() + height, round := cs.Height, cs.Round + newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock) + startTestRound(cs, height, round) + + ensureNewEventOnChannel(newBlockCh) // first block gets committed + ensureNoNewEventOnChannel(newBlockCh) + deliverTxsRange(t, cs, 0, 1) + ensureNewEventOnChannel(newBlockCh) // commit txs + ensureNewEventOnChannel(newBlockCh) // commit updated app hash + ensureNoNewEventOnChannel(newBlockCh) +} + +func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) { + config := ResetConfig("consensus_mempool_txs_available_test") + defer os.RemoveAll(config.RootDir) + + config.Consensus.CreateEmptyBlocksInterval = ensureTimeout + state, privVals := randGenesisState(1, false, 10, nil) + app := kvstore.NewInMemoryApplication() + resp, err := app.Info(context.Background(), proxy.RequestInfo) + require.NoError(t, err) + state.AppHash = resp.LastBlockAppHash + cs := newStateWithConfig(config, state, privVals[0], app) + + assertMempool(cs.txNotifier).EnableTxsAvailable() + + newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock) + startTestRound(cs, cs.Height, cs.Round) + + ensureNewEventOnChannel(newBlockCh) // first block gets committed + ensureNoNewEventOnChannel(newBlockCh) // then we dont make a block ... + ensureNewEventOnChannel(newBlockCh) // until the CreateEmptyBlocksInterval has passed +} + +func TestMempoolProgressInHigherRound(t *testing.T) { + config := ResetConfig("consensus_mempool_txs_available_test") + defer os.RemoveAll(config.RootDir) + config.Consensus.CreateEmptyBlocks = false + state, privVals := randGenesisState(1, false, 10, nil) + cs := newStateWithConfig(config, state, privVals[0], kvstore.NewInMemoryApplication()) + assertMempool(cs.txNotifier).EnableTxsAvailable() + height, round := cs.Height, cs.Round + newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock) + newRoundCh := subscribe(cs.eventBus, types.EventQueryNewRound) + timeoutCh := subscribe(cs.eventBus, types.EventQueryTimeoutPropose) + cs.setProposal = func(proposal *types.Proposal) error { + if cs.Height == 2 && cs.Round == 0 { + // dont set the proposal in round 0 so we timeout and + // go to next round + cs.Logger.Info("Ignoring set proposal at height 2, round 0") + return nil + } + return cs.defaultSetProposal(proposal) + } + startTestRound(cs, height, round) + + ensureNewRound(newRoundCh, height, round) // first round at first height + ensureNewEventOnChannel(newBlockCh) // first block gets committed + + height++ // moving to the next height + round = 0 + + ensureNewRound(newRoundCh, height, round) // first round at next height + deliverTxsRange(t, cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round + ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds()) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) // wait for the next round + ensureNewEventOnChannel(newBlockCh) // now we can commit the block +} + +func deliverTxsRange(t *testing.T, cs *State, start, end int) { + // Deliver some txs. + for i := start; i < end; i++ { + err := assertMempool(cs.txNotifier).CheckTx(kvstore.NewTx(fmt.Sprintf("%d", i), "true"), nil, mempl.TxInfo{}) + require.NoError(t, err) + } +} + +func TestMempoolTxConcurrentWithCommit(t *testing.T) { + state, privVals := randGenesisState(1, false, 10, nil) + blockDB := dbm.NewMemDB() + stateStore := sm.NewStore(blockDB, sm.StoreOptions{DiscardABCIResponses: false}) + cs := newStateWithConfigAndBlockStore(config, state, privVals[0], kvstore.NewInMemoryApplication(), blockDB) + err := stateStore.Save(state) + require.NoError(t, err) + newBlockEventsCh := subscribe(cs.eventBus, types.EventQueryNewBlockEvents) + + const numTxs int64 = 3000 + go deliverTxsRange(t, cs, 0, int(numTxs)) + + startTestRound(cs, cs.Height, cs.Round) + for n := int64(0); n < numTxs; { + select { + case msg := <-newBlockEventsCh: + event := msg.Data().(types.EventDataNewBlockEvents) + n += event.NumTxs + t.Log("new transactions", "nTxs", event.NumTxs, "total", n) + case <-time.After(30 * time.Second): + t.Fatal("Timed out waiting 30s to commit blocks with transactions") + } + } +} + +func TestMempoolRmBadTx(t *testing.T) { + state, privVals := randGenesisState(1, false, 10, nil) + app := kvstore.NewInMemoryApplication() + blockDB := dbm.NewMemDB() + stateStore := sm.NewStore(blockDB, sm.StoreOptions{DiscardABCIResponses: false}) + cs := newStateWithConfigAndBlockStore(config, state, privVals[0], app, blockDB) + err := stateStore.Save(state) + require.NoError(t, err) + + // increment the counter by 1 + txBytes := kvstore.NewTx("key", "value") + res, err := app.FinalizeBlock(context.Background(), &abci.RequestFinalizeBlock{Txs: [][]byte{txBytes}}) + require.NoError(t, err) + assert.False(t, res.TxResults[0].IsErr()) + assert.True(t, len(res.AppHash) > 0) + + _, err = app.Commit(context.Background(), &abci.RequestCommit{}) + require.NoError(t, err) + + emptyMempoolCh := make(chan struct{}) + checkTxRespCh := make(chan struct{}) + go func() { + // Try to send the tx through the mempool. + // CheckTx should not err, but the app should return a bad abci code + // and the tx should get removed from the pool + invalidTx := []byte("invalidTx") + err := assertMempool(cs.txNotifier).CheckTx(invalidTx, func(r *abci.ResponseCheckTx) { + if r.Code != kvstore.CodeTypeInvalidTxFormat { + t.Errorf("expected checktx to return invalid format, got %v", r) + return + } + checkTxRespCh <- struct{}{} + }, mempl.TxInfo{}) + if err != nil { + t.Errorf("error after CheckTx: %v", err) + return + } + + // check for the tx + for { + txs := assertMempool(cs.txNotifier).ReapMaxBytesMaxGas(int64(len(invalidTx)), -1) + if len(txs) == 0 { + emptyMempoolCh <- struct{}{} + return + } + time.Sleep(10 * time.Millisecond) + } + }() + + // Wait until the tx returns + ticker := time.After(time.Second * 5) + select { + case <-checkTxRespCh: + // success + case <-ticker: + t.Errorf("timed out waiting for tx to return") + return + } + + // Wait until the tx is removed + ticker = time.After(time.Second * 5) + select { + case <-emptyMempoolCh: + // success + case <-ticker: + t.Errorf("timed out waiting for tx to be removed") + return + } +} diff --git a/consensus/metrics.gen.go b/consensus/metrics.gen.go new file mode 100644 index 0000000..a8c58e7 --- /dev/null +++ b/consensus/metrics.gen.go @@ -0,0 +1,258 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package consensus + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "height", + Help: "Height of the chain.", + }, labels).With(labelsAndValues...), + ValidatorLastSignedHeight: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validator_last_signed_height", + Help: "Last height signed by this validator if the node is a validator.", + }, append(labels, "validator_address")).With(labelsAndValues...), + Rounds: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "rounds", + Help: "Number of rounds.", + }, labels).With(labelsAndValues...), + RoundDurationSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "round_duration_seconds", + Help: "Histogram of round duration.", + + Buckets: stdprometheus.ExponentialBucketsRange(0.1, 100, 8), + }, labels).With(labelsAndValues...), + Validators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validators", + Help: "Number of validators.", + }, labels).With(labelsAndValues...), + ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validators_power", + Help: "Total power of all validators.", + }, labels).With(labelsAndValues...), + ValidatorPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validator_power", + Help: "Power of a validator.", + }, append(labels, "validator_address")).With(labelsAndValues...), + ValidatorMissedBlocks: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validator_missed_blocks", + Help: "Amount of blocks missed per validator.", + }, append(labels, "validator_address")).With(labelsAndValues...), + MissingValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "missing_validators", + Help: "Number of validators who did not sign.", + }, labels).With(labelsAndValues...), + MissingValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "missing_validators_power", + Help: "Total power of the missing validators.", + }, labels).With(labelsAndValues...), + ByzantineValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "byzantine_validators", + Help: "Number of validators who tried to double sign.", + }, labels).With(labelsAndValues...), + ByzantineValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "byzantine_validators_power", + Help: "Total power of the byzantine validators.", + }, labels).With(labelsAndValues...), + BlockIntervalSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_interval_seconds", + Help: "Time between this and the last block.", + }, labels).With(labelsAndValues...), + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "num_txs", + Help: "Number of transactions.", + }, labels).With(labelsAndValues...), + BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_size_bytes", + Help: "Size of the block.", + }, labels).With(labelsAndValues...), + ChainSizeBytes: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "chain_size_bytes", + Help: "Size of the chain in bytes.", + }, labels).With(labelsAndValues...), + TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "total_txs", + Help: "Total number of transactions.", + }, labels).With(labelsAndValues...), + CommittedHeight: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "latest_block_height", + Help: "The latest block height.", + }, labels).With(labelsAndValues...), + BlockParts: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_parts", + Help: "Number of block parts transmitted by each peer.", + }, append(labels, "peer_id")).With(labelsAndValues...), + DuplicateBlockPart: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "duplicate_block_part", + Help: "Number of times we received a duplicate block part", + }, labels).With(labelsAndValues...), + DuplicateVote: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "duplicate_vote", + Help: "Number of times we received a duplicate vote", + }, labels).With(labelsAndValues...), + StepDurationSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "step_duration_seconds", + Help: "Histogram of durations for each step in the consensus protocol.", + + Buckets: stdprometheus.ExponentialBucketsRange(0.1, 100, 8), + }, append(labels, "step")).With(labelsAndValues...), + BlockGossipPartsReceived: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_gossip_parts_received", + Help: "Number of block parts received by the node, separated by whether the part was relevant to the block the node is trying to gather or not.", + }, append(labels, "matches_current")).With(labelsAndValues...), + QuorumPrevoteDelay: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "quorum_prevote_delay", + Help: "Interval in seconds between the proposal timestamp and the timestamp of the earliest prevote that achieved a quorum.", + }, append(labels, "proposer_address")).With(labelsAndValues...), + QuorumPrecommitDelay: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "quorum_precommit_delay", + Help: "Interval in seconds between the proposal timestamp and the timestamp of the earliest precommit that achieved a quorum.", + }, append(labels, "proposer_address")).With(labelsAndValues...), + FullPrevoteDelay: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "full_prevote_delay", + Help: "Interval in seconds between the proposal timestamp and the timestamp of the latest prevote in a round where all validators voted.", + }, append(labels, "proposer_address")).With(labelsAndValues...), + PrecommitsCounted: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "precommits_counted", + Help: "PrecommitsCounted is the number of precommit votes counted after the timeout commit period has ended.", + }, labels).With(labelsAndValues...), + PrecommitsStakingPercentage: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "precommits_staking_percentage", + Help: "PrecommitsStakingPercentage is the voting power percentage of precommit votes once the timeout commit period has ended.", + }, labels).With(labelsAndValues...), + VoteExtensionReceiveCount: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "vote_extension_receive_count", + Help: "VoteExtensionReceiveCount is the number of vote extensions received by this node. The metric is annotated by the status of the vote extension from the application, either 'accepted' or 'rejected'.", + }, append(labels, "status")).With(labelsAndValues...), + ProposalReceiveCount: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "proposal_receive_count", + Help: "ProposalReceiveCount is the total number of proposals received by this node since process start. The metric is annotated by the status of the proposal from the application, either 'accepted' or 'rejected'.", + }, append(labels, "status")).With(labelsAndValues...), + ProposalCreateCount: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "proposal_create_count", + Help: "ProposalCreationCount is the total number of proposals created by this node since process start. The metric is annotated by the status of the proposal from the application, either 'accepted' or 'rejected'.", + }, labels).With(labelsAndValues...), + RoundVotingPowerPercent: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "round_voting_power_percent", + Help: "RoundVotingPowerPercent is the percentage of the total voting power received with a round. The value begins at 0 for each round and approaches 1.0 as additional voting power is observed. The metric is labeled by vote type.", + }, append(labels, "vote_type")).With(labelsAndValues...), + LateVotes: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "late_votes", + Help: "LateVotes stores the number of votes that were received by this node that correspond to earlier heights and rounds than this node is currently in.", + }, append(labels, "vote_type")).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Height: discard.NewGauge(), + ValidatorLastSignedHeight: discard.NewGauge(), + Rounds: discard.NewGauge(), + RoundDurationSeconds: discard.NewHistogram(), + Validators: discard.NewGauge(), + ValidatorsPower: discard.NewGauge(), + ValidatorPower: discard.NewGauge(), + ValidatorMissedBlocks: discard.NewGauge(), + MissingValidators: discard.NewGauge(), + MissingValidatorsPower: discard.NewGauge(), + ByzantineValidators: discard.NewGauge(), + ByzantineValidatorsPower: discard.NewGauge(), + BlockIntervalSeconds: discard.NewHistogram(), + NumTxs: discard.NewGauge(), + BlockSizeBytes: discard.NewGauge(), + ChainSizeBytes: discard.NewCounter(), + TotalTxs: discard.NewGauge(), + CommittedHeight: discard.NewGauge(), + BlockParts: discard.NewCounter(), + DuplicateBlockPart: discard.NewCounter(), + DuplicateVote: discard.NewCounter(), + StepDurationSeconds: discard.NewHistogram(), + BlockGossipPartsReceived: discard.NewCounter(), + QuorumPrevoteDelay: discard.NewGauge(), + QuorumPrecommitDelay: discard.NewGauge(), + FullPrevoteDelay: discard.NewGauge(), + PrecommitsCounted: discard.NewGauge(), + PrecommitsStakingPercentage: discard.NewGauge(), + VoteExtensionReceiveCount: discard.NewCounter(), + ProposalReceiveCount: discard.NewCounter(), + ProposalCreateCount: discard.NewCounter(), + RoundVotingPowerPercent: discard.NewGauge(), + LateVotes: discard.NewCounter(), + } +} diff --git a/consensus/metrics.go b/consensus/metrics.go new file mode 100644 index 0000000..2cc6d7a --- /dev/null +++ b/consensus/metrics.go @@ -0,0 +1,194 @@ +package consensus + +import ( + "strings" + "time" + + "github.com/go-kit/kit/metrics" + + cstypes "github.com/cometbft/cometbft/consensus/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + types "github.com/cometbft/cometbft/types" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "consensus" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Height of the chain. + Height metrics.Gauge + + // Last height signed by this validator if the node is a validator. + ValidatorLastSignedHeight metrics.Gauge `metrics_labels:"validator_address"` + + // Number of rounds. + Rounds metrics.Gauge + + // Histogram of round duration. + RoundDurationSeconds metrics.Histogram `metrics_buckettype:"exprange" metrics_bucketsizes:"0.1, 100, 8"` + + // Number of validators. + Validators metrics.Gauge + // Total power of all validators. + ValidatorsPower metrics.Gauge + // Power of a validator. + ValidatorPower metrics.Gauge `metrics_labels:"validator_address"` + // Amount of blocks missed per validator. + ValidatorMissedBlocks metrics.Gauge `metrics_labels:"validator_address"` + // Number of validators who did not sign. + MissingValidators metrics.Gauge + // Total power of the missing validators. + MissingValidatorsPower metrics.Gauge + // Number of validators who tried to double sign. + ByzantineValidators metrics.Gauge + // Total power of the byzantine validators. + ByzantineValidatorsPower metrics.Gauge + + // Time between this and the last block. + BlockIntervalSeconds metrics.Histogram + + // Number of transactions. + NumTxs metrics.Gauge + // Size of the block. + BlockSizeBytes metrics.Gauge + // Size of the chain in bytes. + ChainSizeBytes metrics.Counter + // Total number of transactions. + TotalTxs metrics.Gauge + // The latest block height. + CommittedHeight metrics.Gauge `metrics_name:"latest_block_height"` + + // Number of block parts transmitted by each peer. + BlockParts metrics.Counter `metrics_labels:"peer_id"` + + // Number of times we received a duplicate block part + DuplicateBlockPart metrics.Counter + + // Number of times we received a duplicate vote + DuplicateVote metrics.Counter + + // Histogram of durations for each step in the consensus protocol. + StepDurationSeconds metrics.Histogram `metrics_labels:"step" metrics_buckettype:"exprange" metrics_bucketsizes:"0.1, 100, 8"` + stepStart time.Time + + // Number of block parts received by the node, separated by whether the part + // was relevant to the block the node is trying to gather or not. + BlockGossipPartsReceived metrics.Counter `metrics_labels:"matches_current"` + + // QuroumPrevoteMessageDelay is the interval in seconds between the proposal + // timestamp and the timestamp of the earliest prevote that achieved a quorum + // during the prevote step. + // + // To compute it, sum the voting power over each prevote received, in increasing + // order of timestamp. The timestamp of the first prevote to increase the sum to + // be above 2/3 of the total voting power of the network defines the endpoint + // the endpoint of the interval. Subtract the proposal timestamp from this endpoint + // to obtain the quorum delay. + //metrics:Interval in seconds between the proposal timestamp and the timestamp of the earliest prevote that achieved a quorum. + QuorumPrevoteDelay metrics.Gauge `metrics_labels:"proposer_address"` + + // QuorumPrecommitDelay is the interval in seconds between the proposal + // timestamp and the timestamp of the earliest precommit that achieved a quorum + // during the precommit step. + // + // To compute it, sum the voting power over each precommit received, in increasing + // order of timestamp. The timestamp of the first precommit to increase the sum to + // be above 2/3 of the total voting power of the network defines the endpoint + // the endpoint of the interval. Subtract the proposal timestamp from this endpoint + // to obtain the quorum delay. + //metrics:Interval in seconds between the proposal timestamp and the timestamp of the earliest precommit that achieved a quorum. + QuorumPrecommitDelay metrics.Gauge `metrics_labels:"proposer_address"` + + // FullPrevoteDelay is the interval in seconds between the proposal + // timestamp and the timestamp of the latest prevote in a round where 100% + // of the voting power on the network issued prevotes. + //metrics:Interval in seconds between the proposal timestamp and the timestamp of the latest prevote in a round where all validators voted. + FullPrevoteDelay metrics.Gauge `metrics_labels:"proposer_address"` + + // PrecommitsCounted is the number of precommit votes counted after the timeout commit period has ended. + PrecommitsCounted metrics.Gauge + + // PrecommitsStakingPercentage is the voting power percentage of precommit votes once the timeout commit period has ended. + PrecommitsStakingPercentage metrics.Gauge + + // VoteExtensionReceiveCount is the number of vote extensions received by this + // node. The metric is annotated by the status of the vote extension from the + // application, either 'accepted' or 'rejected'. + VoteExtensionReceiveCount metrics.Counter `metrics_labels:"status"` + + // ProposalReceiveCount is the total number of proposals received by this node + // since process start. + // The metric is annotated by the status of the proposal from the application, + // either 'accepted' or 'rejected'. + ProposalReceiveCount metrics.Counter `metrics_labels:"status"` + + // ProposalCreationCount is the total number of proposals created by this node + // since process start. + // The metric is annotated by the status of the proposal from the application, + // either 'accepted' or 'rejected'. + ProposalCreateCount metrics.Counter + + // RoundVotingPowerPercent is the percentage of the total voting power received + // with a round. The value begins at 0 for each round and approaches 1.0 as + // additional voting power is observed. The metric is labeled by vote type. + RoundVotingPowerPercent metrics.Gauge `metrics_labels:"vote_type"` + + // LateVotes stores the number of votes that were received by this node that + // correspond to earlier heights and rounds than this node is currently + // in. + LateVotes metrics.Counter `metrics_labels:"vote_type"` +} + +func (m *Metrics) MarkProposalProcessed(accepted bool) { + status := "accepted" + if !accepted { + status = "rejected" + } + m.ProposalReceiveCount.With("status", status).Add(1) +} + +func (m *Metrics) MarkVoteExtensionReceived(accepted bool) { + status := "accepted" + if !accepted { + status = "rejected" + } + m.VoteExtensionReceiveCount.With("status", status).Add(1) +} + +func (m *Metrics) MarkVoteReceived(vt cmtproto.SignedMsgType, power, totalPower int64) { + p := float64(power) / float64(totalPower) + n := types.SignedMsgTypeToShortString(vt) + m.RoundVotingPowerPercent.With("vote_type", n).Add(p) +} + +func (m *Metrics) MarkRound(r int32, st time.Time) { + m.Rounds.Set(float64(r)) + roundTime := time.Since(st).Seconds() + m.RoundDurationSeconds.Observe(roundTime) + + pvn := types.SignedMsgTypeToShortString(cmtproto.PrevoteType) + m.RoundVotingPowerPercent.With("vote_type", pvn).Set(0) + + pcn := types.SignedMsgTypeToShortString(cmtproto.PrecommitType) + m.RoundVotingPowerPercent.With("vote_type", pcn).Set(0) +} + +func (m *Metrics) MarkLateVote(vt cmtproto.SignedMsgType) { + n := types.SignedMsgTypeToShortString(vt) + m.LateVotes.With("vote_type", n).Add(1) +} + +func (m *Metrics) MarkStep(s cstypes.RoundStepType) { + if !m.stepStart.IsZero() { + stepTime := time.Since(m.stepStart).Seconds() + stepName := strings.TrimPrefix(s.String(), "RoundStep") + m.StepDurationSeconds.With("step", stepName).Observe(stepTime) + } + m.stepStart = time.Now() +} diff --git a/consensus/msgs.go b/consensus/msgs.go new file mode 100644 index 0000000..e1ac026 --- /dev/null +++ b/consensus/msgs.go @@ -0,0 +1,347 @@ +package consensus + +import ( + "errors" + "fmt" + + "github.com/cosmos/gogoproto/proto" + + cstypes "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/libs/bits" + cmtmath "github.com/cometbft/cometbft/libs/math" + "github.com/cometbft/cometbft/p2p" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +// MsgToProto takes a consensus message type and returns the proto defined consensus message. +// +// TODO: This needs to be removed, but WALToProto depends on this. +func MsgToProto(msg Message) (proto.Message, error) { + if msg == nil { + return nil, errors.New("consensus: message is nil") + } + var pb proto.Message + + switch msg := msg.(type) { + case *NewRoundStepMessage: + pb = &cmtcons.NewRoundStep{ + Height: msg.Height, + Round: msg.Round, + Step: uint32(msg.Step), + SecondsSinceStartTime: msg.SecondsSinceStartTime, + LastCommitRound: msg.LastCommitRound, + } + + case *NewValidBlockMessage: + pbPartSetHeader := msg.BlockPartSetHeader.ToProto() + pbBits := msg.BlockParts.ToProto() + pb = &cmtcons.NewValidBlock{ + Height: msg.Height, + Round: msg.Round, + BlockPartSetHeader: pbPartSetHeader, + BlockParts: pbBits, + IsCommit: msg.IsCommit, + } + + case *ProposalMessage: + pbP := msg.Proposal.ToProto() + pb = &cmtcons.Proposal{ + Proposal: *pbP, + } + + case *ProposalPOLMessage: + pbBits := msg.ProposalPOL.ToProto() + pb = &cmtcons.ProposalPOL{ + Height: msg.Height, + ProposalPolRound: msg.ProposalPOLRound, + ProposalPol: *pbBits, + } + + case *BlockPartMessage: + parts, err := msg.Part.ToProto() + if err != nil { + return nil, fmt.Errorf("msg to proto error: %w", err) + } + pb = &cmtcons.BlockPart{ + Height: msg.Height, + Round: msg.Round, + Part: *parts, + } + + case *VoteMessage: + vote := msg.Vote.ToProto() + pb = &cmtcons.Vote{ + Vote: vote, + } + + case *HasVoteMessage: + pb = &cmtcons.HasVote{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + Index: msg.Index, + } + + case *VoteSetMaj23Message: + bi := msg.BlockID.ToProto() + pb = &cmtcons.VoteSetMaj23{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + BlockID: bi, + } + + case *VoteSetBitsMessage: + bi := msg.BlockID.ToProto() + bits := msg.Votes.ToProto() + + vsb := &cmtcons.VoteSetBits{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + BlockID: bi, + } + + if bits != nil { + vsb.Votes = *bits + } + + pb = vsb + + default: + return nil, fmt.Errorf("consensus: message not recognized: %T", msg) + } + + return pb, nil +} + +// MsgFromProto takes a consensus proto message and returns the native go type +func MsgFromProto(p proto.Message) (Message, error) { + if p == nil { + return nil, errors.New("consensus: nil message") + } + var pb Message + + switch msg := p.(type) { + case *cmtcons.NewRoundStep: + rs, err := cmtmath.SafeConvertUint8(int64(msg.Step)) + // deny message based on possible overflow + if err != nil { + return nil, fmt.Errorf("denying message due to possible overflow: %w", err) + } + pb = &NewRoundStepMessage{ + Height: msg.Height, + Round: msg.Round, + Step: cstypes.RoundStepType(rs), + SecondsSinceStartTime: msg.SecondsSinceStartTime, + LastCommitRound: msg.LastCommitRound, + } + case *cmtcons.NewValidBlock: + pbPartSetHeader, err := types.PartSetHeaderFromProto(&msg.BlockPartSetHeader) + if err != nil { + return nil, fmt.Errorf("parts to proto error: %w", err) + } + + pbBits := new(bits.BitArray) + pbBits.FromProto(msg.BlockParts) + + pb = &NewValidBlockMessage{ + Height: msg.Height, + Round: msg.Round, + BlockPartSetHeader: *pbPartSetHeader, + BlockParts: pbBits, + IsCommit: msg.IsCommit, + } + case *cmtcons.Proposal: + pbP, err := types.ProposalFromProto(&msg.Proposal) + if err != nil { + return nil, fmt.Errorf("proposal msg to proto error: %w", err) + } + + pb = &ProposalMessage{ + Proposal: pbP, + } + case *cmtcons.ProposalPOL: + pbBits := new(bits.BitArray) + pbBits.FromProto(&msg.ProposalPol) + pb = &ProposalPOLMessage{ + Height: msg.Height, + ProposalPOLRound: msg.ProposalPolRound, + ProposalPOL: pbBits, + } + case *cmtcons.BlockPart: + parts, err := types.PartFromProto(&msg.Part) + if err != nil { + return nil, fmt.Errorf("blockpart msg to proto error: %w", err) + } + pb = &BlockPartMessage{ + Height: msg.Height, + Round: msg.Round, + Part: parts, + } + case *cmtcons.Vote: + // Vote validation will be handled in the vote message ValidateBasic + // call below. + vote, err := types.VoteFromProto(msg.Vote) + if err != nil { + return nil, fmt.Errorf("vote msg to proto error: %w", err) + } + + pb = &VoteMessage{ + Vote: vote, + } + case *cmtcons.HasVote: + pb = &HasVoteMessage{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + Index: msg.Index, + } + case *cmtcons.VoteSetMaj23: + bi, err := types.BlockIDFromProto(&msg.BlockID) + if err != nil { + return nil, fmt.Errorf("voteSetMaj23 msg to proto error: %w", err) + } + pb = &VoteSetMaj23Message{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + BlockID: *bi, + } + case *cmtcons.VoteSetBits: + bi, err := types.BlockIDFromProto(&msg.BlockID) + if err != nil { + return nil, fmt.Errorf("voteSetBits msg to proto error: %w", err) + } + bits := new(bits.BitArray) + bits.FromProto(&msg.Votes) + + pb = &VoteSetBitsMessage{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + BlockID: *bi, + Votes: bits, + } + default: + return nil, fmt.Errorf("consensus: message not recognized: %T", msg) + } + + if err := pb.ValidateBasic(); err != nil { + return nil, err + } + + return pb, nil +} + +// WALToProto takes a WAL message and return a proto walMessage and error +func WALToProto(msg WALMessage) (*cmtcons.WALMessage, error) { + var pb cmtcons.WALMessage + + switch msg := msg.(type) { + case types.EventDataRoundState: + pb = cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_EventDataRoundState{ + EventDataRoundState: &cmtproto.EventDataRoundState{ + Height: msg.Height, + Round: msg.Round, + Step: msg.Step, + }, + }, + } + case msgInfo: + consMsg, err := MsgToProto(msg.Msg) + if err != nil { + return nil, err + } + if w, ok := consMsg.(p2p.Wrapper); ok { + consMsg = w.Wrap() + } + cm := consMsg.(*cmtcons.Message) + pb = cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_MsgInfo{ + MsgInfo: &cmtcons.MsgInfo{ + Msg: *cm, + PeerID: string(msg.PeerID), + }, + }, + } + case timeoutInfo: + pb = cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_TimeoutInfo{ + TimeoutInfo: &cmtcons.TimeoutInfo{ + Duration: msg.Duration, + Height: msg.Height, + Round: msg.Round, + Step: uint32(msg.Step), + }, + }, + } + case EndHeightMessage: + pb = cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_EndHeight{ + EndHeight: &cmtcons.EndHeight{ + Height: msg.Height, + }, + }, + } + default: + return nil, fmt.Errorf("to proto: wal message not recognized: %T", msg) + } + + return &pb, nil +} + +// WALFromProto takes a proto wal message and return a consensus walMessage and error +func WALFromProto(msg *cmtcons.WALMessage) (WALMessage, error) { + if msg == nil { + return nil, errors.New("nil WAL message") + } + var pb WALMessage + + switch msg := msg.Sum.(type) { + case *cmtcons.WALMessage_EventDataRoundState: + pb = types.EventDataRoundState{ + Height: msg.EventDataRoundState.Height, + Round: msg.EventDataRoundState.Round, + Step: msg.EventDataRoundState.Step, + } + case *cmtcons.WALMessage_MsgInfo: + um, err := msg.MsgInfo.Msg.Unwrap() + if err != nil { + return nil, fmt.Errorf("unwrap message: %w", err) + } + walMsg, err := MsgFromProto(um) + if err != nil { + return nil, fmt.Errorf("msgInfo from proto error: %w", err) + } + pb = msgInfo{ + Msg: walMsg, + PeerID: p2p.ID(msg.MsgInfo.PeerID), + } + + case *cmtcons.WALMessage_TimeoutInfo: + tis, err := cmtmath.SafeConvertUint8(int64(msg.TimeoutInfo.Step)) + // deny message based on possible overflow + if err != nil { + return nil, fmt.Errorf("denying message due to possible overflow: %w", err) + } + pb = timeoutInfo{ + Duration: msg.TimeoutInfo.Duration, + Height: msg.TimeoutInfo.Height, + Round: msg.TimeoutInfo.Round, + Step: cstypes.RoundStepType(tis), + } + return pb, nil + case *cmtcons.WALMessage_EndHeight: + pb := EndHeightMessage{ + Height: msg.EndHeight.Height, + } + return pb, nil + default: + return nil, fmt.Errorf("from proto: wal message not recognized: %T", msg) + } + return pb, nil +} diff --git a/consensus/msgs_test.go b/consensus/msgs_test.go new file mode 100644 index 0000000..67de556 --- /dev/null +++ b/consensus/msgs_test.go @@ -0,0 +1,418 @@ +package consensus + +import ( + "encoding/hex" + "math" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/libs/bits" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +func TestMsgToProto(t *testing.T) { + psh := types.PartSetHeader{ + Total: 1, + Hash: cmtrand.Bytes(32), + } + pbPsh := psh.ToProto() + bi := types.BlockID{ + Hash: cmtrand.Bytes(32), + PartSetHeader: psh, + } + pbBi := bi.ToProto() + bits := bits.NewBitArray(1) + pbBits := bits.ToProto() + + parts := types.Part{ + Index: 1, + Bytes: []byte("test"), + Proof: merkle.Proof{ + Total: 1, + Index: 1, + LeafHash: cmtrand.Bytes(32), + Aunts: [][]byte{}, + }, + } + pbParts, err := parts.ToProto() + require.NoError(t, err) + + proposal := types.Proposal{ + Type: cmtproto.ProposalType, + Height: 1, + Round: 1, + POLRound: 1, + BlockID: bi, + Timestamp: time.Now(), + Signature: cmtrand.Bytes(20), + } + pbProposal := proposal.ToProto() + + vote := types.MakeVoteNoError( + t, + types.NewMockPV(), + "chainID", + 0, + 1, + 0, + cmtproto.PrecommitType, + bi, + time.Now(), + ) + pbVote := vote.ToProto() + + testsCases := []struct { + testName string + msg Message + want proto.Message + wantErr bool + }{ + {"successful NewRoundStepMessage", &NewRoundStepMessage{ + Height: 2, + Round: 1, + Step: 1, + SecondsSinceStartTime: 1, + LastCommitRound: 2, + }, &cmtcons.NewRoundStep{ + Height: 2, + Round: 1, + Step: 1, + SecondsSinceStartTime: 1, + LastCommitRound: 2, + }, + + false}, + + {"successful NewValidBlockMessage", &NewValidBlockMessage{ + Height: 1, + Round: 1, + BlockPartSetHeader: psh, + BlockParts: bits, + IsCommit: false, + }, &cmtcons.NewValidBlock{ + Height: 1, + Round: 1, + BlockPartSetHeader: pbPsh, + BlockParts: pbBits, + IsCommit: false, + }, + + false}, + {"successful BlockPartMessage", &BlockPartMessage{ + Height: 100, + Round: 1, + Part: &parts, + }, &cmtcons.BlockPart{ + Height: 100, + Round: 1, + Part: *pbParts, + }, + + false}, + {"successful ProposalPOLMessage", &ProposalPOLMessage{ + Height: 1, + ProposalPOLRound: 1, + ProposalPOL: bits, + }, &cmtcons.ProposalPOL{ + Height: 1, + ProposalPolRound: 1, + ProposalPol: *pbBits, + }, + false}, + {"successful ProposalMessage", &ProposalMessage{ + Proposal: &proposal, + }, &cmtcons.Proposal{ + Proposal: *pbProposal, + }, + + false}, + {"successful VoteMessage", &VoteMessage{ + Vote: vote, + }, &cmtcons.Vote{ + Vote: pbVote, + }, + + false}, + {"successful VoteSetMaj23", &VoteSetMaj23Message{ + Height: 1, + Round: 1, + Type: 1, + BlockID: bi, + }, &cmtcons.VoteSetMaj23{ + Height: 1, + Round: 1, + Type: 1, + BlockID: pbBi, + }, + + false}, + {"successful VoteSetBits", &VoteSetBitsMessage{ + Height: 1, + Round: 1, + Type: 1, + BlockID: bi, + Votes: bits, + }, &cmtcons.VoteSetBits{ + Height: 1, + Round: 1, + Type: 1, + BlockID: pbBi, + Votes: *pbBits, + }, + + false}, + {"failure", nil, &cmtcons.Message{}, true}, + } + for _, tt := range testsCases { + tt := tt + t.Run(tt.testName, func(t *testing.T) { + pb, err := MsgToProto(tt.msg) + if tt.wantErr == true { + assert.Equal(t, err != nil, tt.wantErr) + return + } + assert.EqualValues(t, tt.want, pb, tt.testName) + + msg, err := MsgFromProto(pb) + + if !tt.wantErr { + require.NoError(t, err) + bcm := assert.Equal(t, tt.msg, msg, tt.testName) + assert.True(t, bcm, tt.testName) + } else { + require.Error(t, err, tt.testName) + } + }) + } +} + +func TestWALMsgProto(t *testing.T) { + + parts := types.Part{ + Index: 1, + Bytes: []byte("test"), + Proof: merkle.Proof{ + Total: 1, + Index: 1, + LeafHash: cmtrand.Bytes(32), + Aunts: [][]byte{}, + }, + } + pbParts, err := parts.ToProto() + require.NoError(t, err) + + testsCases := []struct { + testName string + msg WALMessage + want *cmtcons.WALMessage + wantErr bool + }{ + {"successful EventDataRoundState", types.EventDataRoundState{ + Height: 2, + Round: 1, + Step: "ronies", + }, &cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_EventDataRoundState{ + EventDataRoundState: &cmtproto.EventDataRoundState{ + Height: 2, + Round: 1, + Step: "ronies", + }, + }, + }, false}, + {"successful msgInfo", msgInfo{ + Msg: &BlockPartMessage{ + Height: 100, + Round: 1, + Part: &parts, + }, + PeerID: p2p.ID("string"), + }, &cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_MsgInfo{ + MsgInfo: &cmtcons.MsgInfo{ + Msg: cmtcons.Message{ + Sum: &cmtcons.Message_BlockPart{ + BlockPart: &cmtcons.BlockPart{ + Height: 100, + Round: 1, + Part: *pbParts, + }, + }, + }, + PeerID: "string", + }, + }, + }, false}, + {"successful timeoutInfo", timeoutInfo{ + Duration: time.Duration(100), + Height: 1, + Round: 1, + Step: 1, + }, &cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_TimeoutInfo{ + TimeoutInfo: &cmtcons.TimeoutInfo{ + Duration: time.Duration(100), + Height: 1, + Round: 1, + Step: 1, + }, + }, + }, false}, + {"successful EndHeightMessage", EndHeightMessage{ + Height: 1, + }, &cmtcons.WALMessage{ + Sum: &cmtcons.WALMessage_EndHeight{ + EndHeight: &cmtcons.EndHeight{ + Height: 1, + }, + }, + }, false}, + {"failure", nil, &cmtcons.WALMessage{}, true}, + } + for _, tt := range testsCases { + tt := tt + t.Run(tt.testName, func(t *testing.T) { + pb, err := WALToProto(tt.msg) + if tt.wantErr == true { + assert.Equal(t, err != nil, tt.wantErr) + return + } + assert.EqualValues(t, tt.want, pb, tt.testName) + + msg, err := WALFromProto(pb) + + if !tt.wantErr { + require.NoError(t, err) + assert.Equal(t, tt.msg, msg, tt.testName) // need the concrete type as WAL Message is a empty interface + } else { + require.Error(t, err, tt.testName) + } + }) + } +} + +//nolint:lll //ignore line length for tests +func TestConsMsgsVectors(t *testing.T) { + date := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC) + psh := types.PartSetHeader{ + Total: 1, + Hash: []byte("add_more_exclamation_marks_code-"), + } + pbPsh := psh.ToProto() + + bi := types.BlockID{ + Hash: []byte("add_more_exclamation_marks_code-"), + PartSetHeader: psh, + } + pbBi := bi.ToProto() + bits := bits.NewBitArray(1) + pbBits := bits.ToProto() + + parts := types.Part{ + Index: 1, + Bytes: []byte("test"), + Proof: merkle.Proof{ + Total: 1, + Index: 1, + LeafHash: []byte("add_more_exclamation_marks_code-"), + Aunts: [][]byte{}, + }, + } + pbParts, err := parts.ToProto() + require.NoError(t, err) + + proposal := types.Proposal{ + Type: cmtproto.ProposalType, + Height: 1, + Round: 1, + POLRound: 1, + BlockID: bi, + Timestamp: date, + Signature: []byte("add_more_exclamation"), + } + pbProposal := proposal.ToProto() + + v := &types.Vote{ + ValidatorAddress: []byte("add_more_exclamation"), + ValidatorIndex: 1, + Height: 1, + Round: 0, + Timestamp: date, + Type: cmtproto.PrecommitType, + BlockID: bi, + } + vpb := v.ToProto() + v.Extension = []byte("extension") + vextPb := v.ToProto() + + testCases := []struct { + testName string + cMsg proto.Message + expBytes string + }{ + {"NewRoundStep", &cmtcons.Message{Sum: &cmtcons.Message_NewRoundStep{NewRoundStep: &cmtcons.NewRoundStep{ + Height: 1, + Round: 1, + Step: 1, + SecondsSinceStartTime: 1, + LastCommitRound: 1, + }}}, "0a0a08011001180120012801"}, + {"NewRoundStep Max", &cmtcons.Message{Sum: &cmtcons.Message_NewRoundStep{NewRoundStep: &cmtcons.NewRoundStep{ + Height: math.MaxInt64, + Round: math.MaxInt32, + Step: math.MaxUint32, + SecondsSinceStartTime: math.MaxInt64, + LastCommitRound: math.MaxInt32, + }}}, "0a2608ffffffffffffffff7f10ffffffff0718ffffffff0f20ffffffffffffffff7f28ffffffff07"}, + {"NewValidBlock", &cmtcons.Message{Sum: &cmtcons.Message_NewValidBlock{ + NewValidBlock: &cmtcons.NewValidBlock{ + Height: 1, Round: 1, BlockPartSetHeader: pbPsh, BlockParts: pbBits, IsCommit: false}}}, + "1231080110011a24080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d22050801120100"}, + {"Proposal", &cmtcons.Message{Sum: &cmtcons.Message_Proposal{Proposal: &cmtcons.Proposal{Proposal: *pbProposal}}}, + "1a720a7008201001180120012a480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d320608c0b89fdc053a146164645f6d6f72655f6578636c616d6174696f6e"}, + {"ProposalPol", &cmtcons.Message{Sum: &cmtcons.Message_ProposalPol{ + ProposalPol: &cmtcons.ProposalPOL{Height: 1, ProposalPolRound: 1}}}, + "2206080110011a00"}, + {"BlockPart", &cmtcons.Message{Sum: &cmtcons.Message_BlockPart{ + BlockPart: &cmtcons.BlockPart{Height: 1, Round: 1, Part: *pbParts}}}, + "2a36080110011a3008011204746573741a26080110011a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d"}, + {"Vote_without_ext", &cmtcons.Message{Sum: &cmtcons.Message_Vote{ + Vote: &cmtcons.Vote{Vote: vpb}}}, + "32700a6e0802100122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a0608c0b89fdc0532146164645f6d6f72655f6578636c616d6174696f6e3801"}, + {"Vote_with_ext", &cmtcons.Message{Sum: &cmtcons.Message_Vote{ + Vote: &cmtcons.Vote{Vote: vextPb}}}, + "327b0a790802100122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a0608c0b89fdc0532146164645f6d6f72655f6578636c616d6174696f6e38014a09657874656e73696f6e"}, + {"HasVote", &cmtcons.Message{Sum: &cmtcons.Message_HasVote{ + HasVote: &cmtcons.HasVote{Height: 1, Round: 1, Type: cmtproto.PrevoteType, Index: 1}}}, + "3a080801100118012001"}, + {"HasVote", &cmtcons.Message{Sum: &cmtcons.Message_HasVote{ + HasVote: &cmtcons.HasVote{Height: math.MaxInt64, Round: math.MaxInt32, + Type: cmtproto.PrevoteType, Index: math.MaxInt32}}}, + "3a1808ffffffffffffffff7f10ffffffff07180120ffffffff07"}, + {"VoteSetMaj23", &cmtcons.Message{Sum: &cmtcons.Message_VoteSetMaj23{ + VoteSetMaj23: &cmtcons.VoteSetMaj23{Height: 1, Round: 1, Type: cmtproto.PrevoteType, BlockID: pbBi}}}, + "425008011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d"}, + {"VoteSetBits", &cmtcons.Message{Sum: &cmtcons.Message_VoteSetBits{ + VoteSetBits: &cmtcons.VoteSetBits{Height: 1, Round: 1, Type: cmtproto.PrevoteType, BlockID: pbBi, Votes: *pbBits}}}, + "4a5708011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a050801120100"}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + bz, err := proto.Marshal(tc.cMsg) + require.NoError(t, err) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz)) + }) + } +} diff --git a/consensus/reactor.go b/consensus/reactor.go new file mode 100644 index 0000000..6a2b031 --- /dev/null +++ b/consensus/reactor.go @@ -0,0 +1,1841 @@ +package consensus + +import ( + "errors" + "fmt" + "reflect" + "sync" + "time" + + cstypes "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/libs/bits" + cmtevents "github.com/cometbft/cometbft/libs/events" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const ( + StateChannel = byte(0x20) + DataChannel = byte(0x21) + VoteChannel = byte(0x22) + VoteSetBitsChannel = byte(0x23) + + maxMsgSize = 1048576 // 1MB; NOTE/TODO: keep in sync with types.PartSet sizes. + + blocksToContributeToBecomeGoodPeer = 10000 + votesToContributeToBecomeGoodPeer = 10000 +) + +//----------------------------------------------------------------------------- + +// Reactor defines a reactor for the consensus service. +type Reactor struct { + p2p.BaseReactor // BaseService + p2p.Switch + + conS *State + + mtx cmtsync.RWMutex + waitSync bool + eventBus *types.EventBus + rs *cstypes.RoundState + + Metrics *Metrics +} + +type ReactorOption func(*Reactor) + +// NewReactor returns a new Reactor with the given +// consensusState. +func NewReactor(consensusState *State, waitSync bool, options ...ReactorOption) *Reactor { + conR := &Reactor{ + conS: consensusState, + waitSync: waitSync, + rs: consensusState.GetRoundState(), + Metrics: NopMetrics(), + } + conR.BaseReactor = *p2p.NewBaseReactor("Consensus", conR) + + for _, option := range options { + option(conR) + } + + return conR +} + +// OnStart implements BaseService by subscribing to events, which later will be +// broadcasted to other peers and starting state if we're not in block sync. +func (conR *Reactor) OnStart() error { + conR.Logger.Info("Reactor ", "waitSync", conR.WaitSync()) + + // start routine that computes peer statistics for evaluating peer quality + go conR.peerStatsRoutine() + + conR.subscribeToBroadcastEvents() + go conR.updateRoundStateRoutine() + + if !conR.WaitSync() { + err := conR.conS.Start() + if err != nil { + return err + } + } + + return nil +} + +// OnStop implements BaseService by unsubscribing from events and stopping +// state. +func (conR *Reactor) OnStop() { + conR.unsubscribeFromBroadcastEvents() + if err := conR.conS.Stop(); err != nil { + conR.Logger.Error("Error stopping consensus state", "err", err) + } + if !conR.WaitSync() { + conR.conS.Wait() + } +} + +// SwitchToConsensus switches from block_sync mode to consensus mode. +// It resets the state, turns off block_sync, and starts the consensus state-machine +func (conR *Reactor) SwitchToConsensus(state sm.State, skipWAL bool) { + conR.Logger.Info("SwitchToConsensus") + + func() { + // We need to lock, as we are not entering consensus state from State's `handleMsg` or `handleTimeout` + conR.conS.mtx.Lock() + defer conR.conS.mtx.Unlock() + // We have no votes, so reconstruct LastCommit from SeenCommit + if state.LastBlockHeight > 0 { + conR.conS.reconstructLastCommit(state) + } + + // NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a + // NewRoundStepMessage. + conR.conS.updateToState(state) + }() + + conR.mtx.Lock() + conR.waitSync = false + conR.mtx.Unlock() + + if skipWAL { + conR.conS.doWALCatchup = false + } + err := conR.conS.Start() + if err != nil { + panic(fmt.Sprintf(`Failed to start consensus state: %v + +conS: +%+v + +conR: +%+v`, err, conR.conS, conR)) + } +} + +// GetChannels implements Reactor +func (conR *Reactor) GetChannels() []*p2p.ChannelDescriptor { + // TODO optimize + return []*p2p.ChannelDescriptor{ + { + ID: StateChannel, + Priority: 6, + SendQueueCapacity: 100, + RecvMessageCapacity: maxMsgSize, + MessageType: &cmtcons.Message{}, + }, + { + ID: DataChannel, // maybe split between gossiping current block and catchup stuff + // once we gossip the whole block there's nothing left to send until next height or round + Priority: 10, + SendQueueCapacity: 100, + RecvBufferCapacity: 50 * 4096, + RecvMessageCapacity: maxMsgSize, + MessageType: &cmtcons.Message{}, + }, + { + ID: VoteChannel, + Priority: 7, + SendQueueCapacity: 100, + RecvBufferCapacity: 100 * 100, + RecvMessageCapacity: maxMsgSize, + MessageType: &cmtcons.Message{}, + }, + { + ID: VoteSetBitsChannel, + Priority: 1, + SendQueueCapacity: 2, + RecvBufferCapacity: 1024, + RecvMessageCapacity: maxMsgSize, + MessageType: &cmtcons.Message{}, + }, + } +} + +// InitPeer implements Reactor by creating a state for the peer. +func (conR *Reactor) InitPeer(peer p2p.Peer) p2p.Peer { + peerState := NewPeerState(peer).SetLogger(conR.Logger) + peer.Set(types.PeerStateKey, peerState) + return peer +} + +// AddPeer implements Reactor by spawning multiple gossiping goroutines for the +// peer. +func (conR *Reactor) AddPeer(peer p2p.Peer) { + if !conR.IsRunning() { + return + } + + peerState, ok := peer.Get(types.PeerStateKey).(*PeerState) + if !ok { + panic(fmt.Sprintf("peer %v has no state", peer)) + } + // Begin routines for this peer. + go conR.gossipDataRoutine(peer, peerState) + go conR.gossipVotesRoutine(peer, peerState) + go conR.queryMaj23Routine(peer, peerState) + + // Send our state to peer. + // If we're block_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus(). + if !conR.WaitSync() { + conR.sendNewRoundStepMessage(peer) + } +} + +// RemovePeer is a noop. +func (conR *Reactor) RemovePeer(p2p.Peer, interface{}) { + if !conR.IsRunning() { + return + } + // TODO + // ps, ok := peer.Get(PeerStateKey).(*PeerState) + // if !ok { + // panic(fmt.Sprintf("Peer %v has no state", peer)) + // } + // ps.Disconnect() +} + +// Receive implements Reactor +// NOTE: We process these messages even when we're block_syncing. +// Messages affect either a peer state or the consensus state. +// Peer state updates can happen in parallel, but processing of +// proposals, block parts, and votes are ordered by the receiveRoutine +// NOTE: blocks on consensus state for proposals, block parts, and votes +func (conR *Reactor) Receive(e p2p.Envelope) { + if !conR.IsRunning() { + conR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID) + return + } + msg, err := MsgFromProto(e.Message) + if err != nil { + conR.Logger.Error("Error decoding message", "src", e.Src, "chId", e.ChannelID, "err", err) + conR.Switch.StopPeerForError(e.Src, err) + return + } + + if err = msg.ValidateBasic(); err != nil { + conR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", e.Message, "err", err) + conR.Switch.StopPeerForError(e.Src, err) + return + } + + conR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID, "msg", msg) + + // Get peer states + ps, ok := e.Src.Get(types.PeerStateKey).(*PeerState) + if !ok { + panic(fmt.Sprintf("Peer %v has no state", e.Src)) + } + + switch e.ChannelID { + case StateChannel: + switch msg := msg.(type) { + case *NewRoundStepMessage: + conR.conS.mtx.Lock() + initialHeight := conR.conS.state.InitialHeight + conR.conS.mtx.Unlock() + if err = msg.ValidateHeight(initialHeight); err != nil { + conR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", msg, "err", err) + conR.Switch.StopPeerForError(e.Src, err) + return + } + ps.ApplyNewRoundStepMessage(msg) + case *NewValidBlockMessage: + ps.ApplyNewValidBlockMessage(msg) + case *HasVoteMessage: + ps.ApplyHasVoteMessage(msg) + case *VoteSetMaj23Message: + cs := conR.conS + cs.mtx.Lock() + height, votes := cs.Height, cs.Votes + cs.mtx.Unlock() + if height != msg.Height { + return + } + // Peer claims to have a maj23 for some BlockID at H,R,S, + err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peer.ID(), msg.BlockID) + if err != nil { + conR.Switch.StopPeerForError(e.Src, err) + return + } + // Respond with a VoteSetBitsMessage showing which votes we have. + // (and consequently shows which we don't have) + var ourVotes *bits.BitArray + switch msg.Type { + case cmtproto.PrevoteType: + ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID) + case cmtproto.PrecommitType: + ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID) + default: + panic("Bad VoteSetBitsMessage field Type. Forgot to add a check in ValidateBasic?") + } + eMsg := &cmtcons.VoteSetBits{ + Height: msg.Height, + Round: msg.Round, + Type: msg.Type, + BlockID: msg.BlockID.ToProto(), + } + if votes := ourVotes.ToProto(); votes != nil { + eMsg.Votes = *votes + } + e.Src.TrySend(p2p.Envelope{ + ChannelID: VoteSetBitsChannel, + Message: eMsg, + }) + default: + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } + + case DataChannel: + if conR.WaitSync() { + conR.Logger.Info("Ignoring message received during sync", "msg", msg) + return + } + switch msg := msg.(type) { + case *ProposalMessage: + conR.conS.mtx.RLock() + maxBytes := conR.conS.state.ConsensusParams.Block.MaxBytes + conR.conS.mtx.RUnlock() + if err := msg.Proposal.ValidateBlockSize(maxBytes); err != nil { + conR.Logger.Error("Rejecting oversized proposal", "peer", e.Src, "height", msg.Proposal.Height) + conR.Switch.StopPeerForError(e.Src, ErrProposalTooManyParts) + return + } + + ps.SetHasProposal(msg.Proposal) + conR.conS.peerMsgQueue <- msgInfo{msg, e.Src.ID()} + case *ProposalPOLMessage: + ps.ApplyProposalPOLMessage(msg) + case *BlockPartMessage: + ps.SetHasProposalBlockPart(msg.Height, msg.Round, int(msg.Part.Index)) + conR.Metrics.BlockParts.With("peer_id", string(e.Src.ID())).Add(1) + conR.conS.peerMsgQueue <- msgInfo{msg, e.Src.ID()} + default: + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } + + case VoteChannel: + if conR.WaitSync() { + conR.Logger.Info("Ignoring message received during sync", "msg", msg) + return + } + switch msg := msg.(type) { + case *VoteMessage: + cs := conR.conS + cs.mtx.RLock() + height, valSize, lastCommitSize := cs.Height, cs.Validators.Size(), cs.LastCommit.Size() + cs.mtx.RUnlock() + ps.EnsureVoteBitArrays(height, valSize) + ps.EnsureVoteBitArrays(height-1, lastCommitSize) + ps.SetHasVote(msg.Vote) + + cs.peerMsgQueue <- msgInfo{msg, e.Src.ID()} + + default: + // don't punish (leave room for soft upgrades) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } + + case VoteSetBitsChannel: + if conR.WaitSync() { + conR.Logger.Info("Ignoring message received during sync", "msg", msg) + return + } + switch msg := msg.(type) { + case *VoteSetBitsMessage: + cs := conR.conS + cs.mtx.Lock() + height, votes := cs.Height, cs.Votes + cs.mtx.Unlock() + + if height == msg.Height { + var ourVotes *bits.BitArray + switch msg.Type { + case cmtproto.PrevoteType: + ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID) + case cmtproto.PrecommitType: + ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID) + default: + panic("Bad VoteSetBitsMessage field Type. Forgot to add a check in ValidateBasic?") + } + ps.ApplyVoteSetBitsMessage(msg, ourVotes) + } else { + ps.ApplyVoteSetBitsMessage(msg, nil) + } + default: + // don't punish (leave room for soft upgrades) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + } + + default: + conR.Logger.Error(fmt.Sprintf("Unknown chId %X", e.ChannelID)) + } +} + +// SetEventBus sets event bus. +func (conR *Reactor) SetEventBus(b *types.EventBus) { + conR.eventBus = b + conR.conS.SetEventBus(b) +} + +// WaitSync returns whether the consensus reactor is waiting for state/block sync. +func (conR *Reactor) WaitSync() bool { + conR.mtx.RLock() + defer conR.mtx.RUnlock() + return conR.waitSync +} + +//-------------------------------------- + +// subscribeToBroadcastEvents subscribes for new round steps and votes +// using internal pubsub defined on state to broadcast +// them to peers upon receiving. +func (conR *Reactor) subscribeToBroadcastEvents() { + const subscriber = "consensus-reactor" + if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventNewRoundStep, + func(data cmtevents.EventData) { + conR.broadcastNewRoundStepMessage(data.(*cstypes.RoundState)) + }); err != nil { + conR.Logger.Error("Error adding listener for events", "err", err) + } + + if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventValidBlock, + func(data cmtevents.EventData) { + conR.broadcastNewValidBlockMessage(data.(*cstypes.RoundState)) + }); err != nil { + conR.Logger.Error("Error adding listener for events", "err", err) + } + + if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventVote, + func(data cmtevents.EventData) { + conR.broadcastHasVoteMessage(data.(*types.Vote)) + }); err != nil { + conR.Logger.Error("Error adding listener for events", "err", err) + } +} + +func (conR *Reactor) unsubscribeFromBroadcastEvents() { + const subscriber = "consensus-reactor" + conR.conS.evsw.RemoveListener(subscriber) +} + +func (conR *Reactor) broadcastNewRoundStepMessage(rs *cstypes.RoundState) { + nrsMsg := makeRoundStepMessage(rs) + conR.Switch.Broadcast(p2p.Envelope{ + ChannelID: StateChannel, + Message: nrsMsg, + }) +} + +func (conR *Reactor) broadcastNewValidBlockMessage(rs *cstypes.RoundState) { + psh := rs.ProposalBlockParts.Header() + csMsg := &cmtcons.NewValidBlock{ + Height: rs.Height, + Round: rs.Round, + BlockPartSetHeader: psh.ToProto(), + BlockParts: rs.ProposalBlockParts.BitArray().ToProto(), + IsCommit: rs.Step == cstypes.RoundStepCommit, + } + conR.Switch.Broadcast(p2p.Envelope{ + ChannelID: StateChannel, + Message: csMsg, + }) +} + +// Broadcasts HasVoteMessage to peers that care. +func (conR *Reactor) broadcastHasVoteMessage(vote *types.Vote) { + msg := &cmtcons.HasVote{ + Height: vote.Height, + Round: vote.Round, + Type: vote.Type, + Index: vote.ValidatorIndex, + } + conR.Switch.Broadcast(p2p.Envelope{ + ChannelID: StateChannel, + Message: msg, + }) + /* + // TODO: Make this broadcast more selective. + for _, peer := range conR.Switch.Peers().List() { + ps, ok := peer.Get(PeerStateKey).(*PeerState) + if !ok { + panic(fmt.Sprintf("Peer %v has no state", peer)) + } + prs := ps.GetRoundState() + if prs.Height == vote.Height { + // TODO: Also filter on round? + e := p2p.Envelope{ + ChannelID: StateChannel, struct{ ConsensusMessage }{msg}, + Message: p, + } + peer.TrySend(e) + } else { + // Height doesn't match + // TODO: check a field, maybe CatchupCommitRound? + // TODO: But that requires changing the struct field comment. + } + } + */ +} + +func makeRoundStepMessage(rs *cstypes.RoundState) (nrsMsg *cmtcons.NewRoundStep) { + nrsMsg = &cmtcons.NewRoundStep{ + Height: rs.Height, + Round: rs.Round, + Step: uint32(rs.Step), + SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()), + LastCommitRound: rs.LastCommit.GetRound(), + } + return +} + +func (conR *Reactor) sendNewRoundStepMessage(peer p2p.Peer) { + rs := conR.getRoundState() + nrsMsg := makeRoundStepMessage(rs) + peer.Send(p2p.Envelope{ + ChannelID: StateChannel, + Message: nrsMsg, + }) +} + +func (conR *Reactor) updateRoundStateRoutine() { + t := time.NewTicker(100 * time.Microsecond) + defer t.Stop() + for range t.C { + if !conR.IsRunning() { + return + } + rs := conR.conS.GetRoundState() + conR.mtx.Lock() + conR.rs = rs + conR.mtx.Unlock() + } +} + +func (conR *Reactor) getRoundState() *cstypes.RoundState { + conR.mtx.RLock() + defer conR.mtx.RUnlock() + return conR.rs +} + +func (conR *Reactor) gossipDataRoutine(peer p2p.Peer, ps *PeerState) { + logger := conR.Logger.With("peer", peer) + +OUTER_LOOP: + for { + // Manage disconnects from self or peer. + if !peer.IsRunning() || !conR.IsRunning() { + return + } + rs := conR.getRoundState() + prs := ps.GetRoundState() + + // Send proposal Block parts? + if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) { + if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok { + part := rs.ProposalBlockParts.GetPart(index) + parts, err := part.ToProto() + if err != nil { + panic(err) + } + logger.Debug("Sending block part", "height", prs.Height, "round", prs.Round) + if peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.BlockPart{ + Height: rs.Height, // This tells peer that this part applies to us. + Round: rs.Round, // This tells peer that this part applies to us. + Part: *parts, + }, + }) { + ps.SetHasProposalBlockPart(prs.Height, prs.Round, index) + } + continue OUTER_LOOP + } + } + + // If the peer is on a previous height that we have, help catch up. + blockStoreBase := conR.conS.blockStore.Base() + if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase { + heightLogger := logger.With("height", prs.Height) + + // if we never received the commit message from the peer, the block parts wont be initialized + if prs.ProposalBlockParts == nil { + blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) + if blockMeta == nil { + heightLogger.Error("Failed to load block meta", + "blockstoreBase", blockStoreBase, "blockstoreHeight", conR.conS.blockStore.Height()) + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + } else { + ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader) + } + // continue the loop since prs is a copy and not effected by this initialization + continue OUTER_LOOP + } + conR.gossipDataForCatchup(heightLogger, rs, prs, ps, peer) + continue OUTER_LOOP + } + + // If height and round don't match, sleep. + if (rs.Height != prs.Height) || (rs.Round != prs.Round) { + // logger.Info("Peer Height|Round mismatch, sleeping", + // "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer) + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + continue OUTER_LOOP + } + + // By here, height and round match. + // Proposal block parts were already matched and sent if any were wanted. + // (These can match on hash so the round doesn't matter) + // Now consider sending other things, like the Proposal itself. + + // Send Proposal && ProposalPOL BitArray? + if rs.Proposal != nil && !prs.Proposal { + // Proposal: share the proposal metadata with peer. + { + logger.Debug("Sending proposal", "height", prs.Height, "round", prs.Round) + if peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.Proposal{Proposal: *rs.Proposal.ToProto()}, + }) { + // NOTE[ZM]: A peer might have received different proposal msg so this Proposal msg will be rejected! + ps.SetHasProposal(rs.Proposal) + } + } + // ProposalPOL: lets peer know which POL votes we have so far. + // Peer must receive ProposalMessage first. + // rs.Proposal was validated, so rs.Proposal.POLRound <= rs.Round, + // so we definitely have rs.Votes.Prevotes(rs.Proposal.POLRound). + if 0 <= rs.Proposal.POLRound { + logger.Debug("Sending POL", "height", prs.Height, "round", prs.Round) + peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.ProposalPOL{ + Height: rs.Height, + ProposalPolRound: rs.Proposal.POLRound, + ProposalPol: *rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray().ToProto(), + }, + }) + } + continue OUTER_LOOP + } + + // Nothing to do. Sleep. + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + continue OUTER_LOOP + } +} + +func (conR *Reactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundState, + prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer, +) { + if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok { + // Ensure that the peer's PartSetHeader is correct + blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) + if blockMeta == nil { + logger.Error("Failed to load block meta", "ourHeight", rs.Height, + "blockstoreBase", conR.conS.blockStore.Base(), "blockstoreHeight", conR.conS.blockStore.Height()) + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + return + } else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) { + logger.Info("Peer ProposalBlockPartSetHeader mismatch, sleeping", + "blockPartSetHeader", blockMeta.BlockID.PartSetHeader, "peerBlockPartSetHeader", prs.ProposalBlockPartSetHeader) + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + return + } + // Load the part + part := conR.conS.blockStore.LoadBlockPart(prs.Height, index) + if part == nil { + logger.Error("Could not load part", "index", index, + "blockPartSetHeader", blockMeta.BlockID.PartSetHeader, "peerBlockPartSetHeader", prs.ProposalBlockPartSetHeader) + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + return + } + // Send the part + logger.Debug("Sending block part for catchup", "round", prs.Round, "index", index) + pp, err := part.ToProto() + if err != nil { + logger.Error("Could not convert part to proto", "index", index, "error", err) + return + } + if peer.Send(p2p.Envelope{ + ChannelID: DataChannel, + Message: &cmtcons.BlockPart{ + Height: prs.Height, // Not our height, so it doesn't matter. + Round: prs.Round, // Not our height, so it doesn't matter. + Part: *pp, + }, + }) { + ps.SetHasProposalBlockPart(prs.Height, prs.Round, index) + } else { + logger.Debug("Sending block part for catchup failed") + // sleep to avoid retrying too fast + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + } + return + } + // logger.Info("No parts to send in catch-up, sleeping") + time.Sleep(conR.conS.config.PeerGossipSleepDuration) +} + +func (conR *Reactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) { + logger := conR.Logger.With("peer", peer) + + // Simple hack to throttle logs upon sleep. + sleeping := 0 + +OUTER_LOOP: + for { + // Manage disconnects from self or peer. + if !peer.IsRunning() || !conR.IsRunning() { + return + } + rs := conR.getRoundState() + prs := ps.GetRoundState() + + switch sleeping { + case 1: // First sleep + sleeping = 2 + case 2: // No more sleep + sleeping = 0 + } + + // logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round, + // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step) + + // If height matches, then send LastCommit, Prevotes, Precommits. + if rs.Height == prs.Height { + heightLogger := logger.With("height", prs.Height) + if conR.gossipVotesForHeight(heightLogger, rs, prs, ps) { + continue OUTER_LOOP + } + } + + // Special catchup logic. + // If peer is lagging by height 1, send LastCommit. + if prs.Height != 0 && rs.Height == prs.Height+1 { + if ps.PickSendVote(rs.LastCommit) { + logger.Debug("Picked rs.LastCommit to send", "height", prs.Height) + continue OUTER_LOOP + } + } + + // Catchup logic + // If peer is lagging by more than 1, send Commit. + blockStoreBase := conR.conS.blockStore.Base() + if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase { + // Load the block's extended commit for prs.Height, + // which contains precommit signatures for prs.Height. + var ec *types.ExtendedCommit + var veEnabled bool + func() { + conR.conS.mtx.RLock() + defer conR.conS.mtx.RUnlock() + veEnabled = conR.conS.state.ConsensusParams.ABCI.VoteExtensionsEnabled(prs.Height) + }() + if veEnabled { + ec = conR.conS.blockStore.LoadBlockExtendedCommit(prs.Height) + } else { + c := conR.conS.blockStore.LoadBlockCommit(prs.Height) + if c == nil { + continue + } + ec = c.WrappedExtendedCommit() + } + if ec == nil { + continue + } + if ps.PickSendVote(ec) { + logger.Debug("Picked Catchup commit to send", "height", prs.Height) + continue OUTER_LOOP + } + } + + switch sleeping { + case 0: + // We sent nothing. Sleep... + sleeping = 1 + logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height, + "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes, + "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits) + case 2: + // Continued sleep... + sleeping = 1 + } + + time.Sleep(conR.conS.config.PeerGossipSleepDuration) + continue OUTER_LOOP + } +} + +func (conR *Reactor) gossipVotesForHeight( + logger log.Logger, + rs *cstypes.RoundState, + prs *cstypes.PeerRoundState, + ps *PeerState, +) bool { + // If there are lastCommits to send... + if prs.Step == cstypes.RoundStepNewHeight { + if ps.PickSendVote(rs.LastCommit) { + logger.Debug("Picked rs.LastCommit to send") + return true + } + } + // If there are POL prevotes to send... + if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 { + if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil { + if ps.PickSendVote(polPrevotes) { + logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send", + "round", prs.ProposalPOLRound) + return true + } + } + } + // If there are prevotes to send... + if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round { + if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) { + logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round) + return true + } + } + // If there are precommits to send... + if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round { + if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) { + logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round) + return true + } + } + // If there are prevotes to send...Needed because of validBlock mechanism + if prs.Round != -1 && prs.Round <= rs.Round { + if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) { + logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round) + return true + } + } + // If there are POLPrevotes to send... + if prs.ProposalPOLRound != -1 { + if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil { + if ps.PickSendVote(polPrevotes) { + logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send", + "round", prs.ProposalPOLRound) + return true + } + } + } + + return false +} + +// NOTE: `queryMaj23Routine` has a simple crude design since it only comes +// into play for liveness when there's a signature DDoS attack happening. +func (conR *Reactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) { +OUTER_LOOP: + for { + // Manage disconnects from self or peer. + if !peer.IsRunning() || !conR.IsRunning() { + return + } + + // Maybe send Height/Round/Prevotes + { + rs := conR.getRoundState() + prs := ps.GetRoundState() + if rs.Height == prs.Height { + if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok { + + peer.TrySend(p2p.Envelope{ + ChannelID: StateChannel, + Message: &cmtcons.VoteSetMaj23{ + Height: prs.Height, + Round: prs.Round, + Type: cmtproto.PrevoteType, + BlockID: maj23.ToProto(), + }, + }) + time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration) + } + } + } + + // Maybe send Height/Round/Precommits + { + rs := conR.getRoundState() + prs := ps.GetRoundState() + if rs.Height == prs.Height { + if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok { + peer.TrySend(p2p.Envelope{ + ChannelID: StateChannel, + Message: &cmtcons.VoteSetMaj23{ + Height: prs.Height, + Round: prs.Round, + Type: cmtproto.PrecommitType, + BlockID: maj23.ToProto(), + }, + }) + time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration) + } + } + } + + // Maybe send Height/Round/ProposalPOL + { + rs := conR.getRoundState() + prs := ps.GetRoundState() + if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 { + if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok { + + peer.TrySend(p2p.Envelope{ + ChannelID: StateChannel, + Message: &cmtcons.VoteSetMaj23{ + Height: prs.Height, + Round: prs.ProposalPOLRound, + Type: cmtproto.PrevoteType, + BlockID: maj23.ToProto(), + }, + }) + time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration) + } + } + } + + // Little point sending LastCommitRound/LastCommit, + // These are fleeting and non-blocking. + + // Maybe send Height/CatchupCommitRound/CatchupCommit. + { + prs := ps.GetRoundState() + if prs.CatchupCommitRound != -1 && prs.Height > 0 && prs.Height <= conR.conS.blockStore.Height() && + prs.Height >= conR.conS.blockStore.Base() { + if commit := conR.conS.LoadCommit(prs.Height); commit != nil { + peer.TrySend(p2p.Envelope{ + ChannelID: StateChannel, + Message: &cmtcons.VoteSetMaj23{ + Height: prs.Height, + Round: commit.Round, + Type: cmtproto.PrecommitType, + BlockID: commit.BlockID.ToProto(), + }, + }) + time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration) + } + } + } + + time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration) + + continue OUTER_LOOP + } +} + +func (conR *Reactor) peerStatsRoutine() { + for { + if !conR.IsRunning() { + conR.Logger.Info("Stopping peerStatsRoutine") + return + } + + select { + case msg := <-conR.conS.statsMsgQueue: + // Get peer + peer := conR.Switch.Peers().Get(msg.PeerID) + if peer == nil { + conR.Logger.Debug("Attempt to update stats for non-existent peer", + "peer", msg.PeerID) + continue + } + // Get peer state + ps, ok := peer.Get(types.PeerStateKey).(*PeerState) + if !ok { + panic(fmt.Sprintf("Peer %v has no state", peer)) + } + switch msg.Msg.(type) { + case *VoteMessage: + if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 { + conR.Switch.MarkPeerAsGood(peer) + } + case *BlockPartMessage: + if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 { + conR.Switch.MarkPeerAsGood(peer) + } + } + case <-conR.conS.Quit(): + return + + case <-conR.Quit(): + return + } + } +} + +// String returns a string representation of the Reactor. +// NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables. +// TODO: improve! +func (conR *Reactor) String() string { + // better not to access shared variables + return "ConsensusReactor" // conR.StringIndented("") +} + +// StringIndented returns an indented string representation of the Reactor +func (conR *Reactor) StringIndented(indent string) string { + s := "ConsensusReactor{\n" + s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n" + for _, peer := range conR.Switch.Peers().List() { + ps, ok := peer.Get(types.PeerStateKey).(*PeerState) + if !ok { + panic(fmt.Sprintf("Peer %v has no state", peer)) + } + s += indent + " " + ps.StringIndented(indent+" ") + "\n" + } + s += indent + "}" + return s +} + +// ReactorMetrics sets the metrics +func ReactorMetrics(metrics *Metrics) ReactorOption { + return func(conR *Reactor) { conR.Metrics = metrics } +} + +//----------------------------------------------------------------------------- + +var ( + ErrPeerStateHeightRegression = errors.New("error peer state height regression") + ErrPeerStateInvalidStartTime = errors.New("error peer state invalid startTime") +) + +// PeerState contains the known state of a peer, including its connection and +// threadsafe access to its PeerRoundState. +// NOTE: THIS GETS DUMPED WITH rpc/core/consensus.go. +// Be mindful of what you Expose. +type PeerState struct { + peer p2p.Peer + logger log.Logger + + mtx sync.Mutex // NOTE: Modify below using setters, never directly. + PRS cstypes.PeerRoundState `json:"round_state"` // Exposed. + Stats *peerStateStats `json:"stats"` // Exposed. +} + +// peerStateStats holds internal statistics for a peer. +type peerStateStats struct { + Votes int `json:"votes"` + BlockParts int `json:"block_parts"` +} + +func (pss peerStateStats) String() string { + return fmt.Sprintf("peerStateStats{votes: %d, blockParts: %d}", + pss.Votes, pss.BlockParts) +} + +// NewPeerState returns a new PeerState for the given Peer +func NewPeerState(peer p2p.Peer) *PeerState { + return &PeerState{ + peer: peer, + logger: log.NewNopLogger(), + PRS: cstypes.PeerRoundState{ + Round: -1, + ProposalPOLRound: -1, + LastCommitRound: -1, + CatchupCommitRound: -1, + }, + Stats: &peerStateStats{}, + } +} + +// SetLogger allows to set a logger on the peer state. Returns the peer state +// itself. +func (ps *PeerState) SetLogger(logger log.Logger) *PeerState { + ps.logger = logger + return ps +} + +// GetRoundState returns an shallow copy of the PeerRoundState. +// There's no point in mutating it since it won't change PeerState. +func (ps *PeerState) GetRoundState() *cstypes.PeerRoundState { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + prs := ps.PRS // copy + return &prs +} + +// MarshalJSON implements the json.Marshaler interface. +func (ps *PeerState) MarshalJSON() ([]byte, error) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + type jsonPeerState PeerState + return cmtjson.Marshal((*jsonPeerState)(ps)) +} + +// GetHeight returns an atomic snapshot of the PeerRoundState's height +// used by the mempool to ensure peers are caught up before broadcasting new txs +func (ps *PeerState) GetHeight() int64 { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return ps.PRS.Height +} + +// SetHasProposal sets the given proposal as known for the peer. +func (ps *PeerState) SetHasProposal(proposal *types.Proposal) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.Height != proposal.Height || ps.PRS.Round != proposal.Round { + return + } + + if ps.PRS.Proposal { + return + } + + ps.PRS.Proposal = true + + // ps.PRS.ProposalBlockParts is set due to NewValidBlockMessage + if ps.PRS.ProposalBlockParts != nil { + return + } + + ps.PRS.ProposalBlockPartSetHeader = proposal.BlockID.PartSetHeader + ps.PRS.ProposalBlockParts = bits.NewBitArray(int(proposal.BlockID.PartSetHeader.Total)) + ps.PRS.ProposalPOLRound = proposal.POLRound + ps.PRS.ProposalPOL = nil // Nil until ProposalPOLMessage received. +} + +// InitProposalBlockParts initializes the peer's proposal block parts header and bit array. +func (ps *PeerState) InitProposalBlockParts(partSetHeader types.PartSetHeader) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.ProposalBlockParts != nil { + return + } + + ps.PRS.ProposalBlockPartSetHeader = partSetHeader + ps.PRS.ProposalBlockParts = bits.NewBitArray(int(partSetHeader.Total)) +} + +// SetHasProposalBlockPart sets the given block part index as known for the peer. +func (ps *PeerState) SetHasProposalBlockPart(height int64, round int32, index int) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.Height != height || ps.PRS.Round != round { + return + } + + ps.PRS.ProposalBlockParts.SetIndex(index, true) +} + +// PickSendVote picks a vote and sends it to the peer. +// Returns true if vote was sent. +func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool { + if vote, ok := ps.PickVoteToSend(votes); ok { + ps.logger.Debug("Sending vote message", "ps", ps, "vote", vote) + if ps.peer.Send(p2p.Envelope{ + ChannelID: VoteChannel, + Message: &cmtcons.Vote{ + Vote: vote.ToProto(), + }, + }) { + ps.SetHasVote(vote) + return true + } + return false + } + return false +} + +// PickVoteToSend picks a vote to send to the peer. +// Returns true if a vote was picked. +// NOTE: `votes` must be the correct Size() for the Height(). +func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote, ok bool) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if votes.Size() == 0 { + return nil, false + } + + height, round, votesType, size := votes.GetHeight(), votes.GetRound(), cmtproto.SignedMsgType(votes.Type()), votes.Size() + + // Lazily set data using 'votes'. + if votes.IsCommit() { + ps.ensureCatchupCommitRound(height, round, size) + } + ps.ensureVoteBitArrays(height, size) + + psVotes := ps.getVoteBitArray(height, round, votesType) + if psVotes == nil { + return nil, false // Not something worth sending + } + if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok { + return votes.GetByIndex(int32(index)), true + } + return nil, false +} + +func (ps *PeerState) getVoteBitArray(height int64, round int32, votesType cmtproto.SignedMsgType) *bits.BitArray { + if !types.IsVoteTypeValid(votesType) { + return nil + } + + if ps.PRS.Height == height { + if ps.PRS.Round == round { + switch votesType { + case cmtproto.PrevoteType: + return ps.PRS.Prevotes + case cmtproto.PrecommitType: + return ps.PRS.Precommits + } + } + if ps.PRS.CatchupCommitRound == round { + switch votesType { + case cmtproto.PrevoteType: + return nil + case cmtproto.PrecommitType: + return ps.PRS.CatchupCommit + } + } + if ps.PRS.ProposalPOLRound == round { + switch votesType { + case cmtproto.PrevoteType: + return ps.PRS.ProposalPOL + case cmtproto.PrecommitType: + return nil + } + } + return nil + } + if ps.PRS.Height == height+1 { + if ps.PRS.LastCommitRound == round { + switch votesType { + case cmtproto.PrevoteType: + return nil + case cmtproto.PrecommitType: + return ps.PRS.LastCommit + } + } + return nil + } + return nil +} + +// 'round': A round for which we have a +2/3 commit. +func (ps *PeerState) ensureCatchupCommitRound(height int64, round int32, numValidators int) { + if ps.PRS.Height != height { + return + } + /* + NOTE: This is wrong, 'round' could change. + e.g. if orig round is not the same as block LastCommit round. + if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round { + panic(fmt.Sprintf( + "Conflicting CatchupCommitRound. Height: %v, + Orig: %v, + New: %v", + height, + ps.CatchupCommitRound, + round)) + } + */ + if ps.PRS.CatchupCommitRound == round { + return // Nothing to do! + } + ps.PRS.CatchupCommitRound = round + if round == ps.PRS.Round { + ps.PRS.CatchupCommit = ps.PRS.Precommits + } else { + ps.PRS.CatchupCommit = bits.NewBitArray(numValidators) + } +} + +// EnsureVoteBitArrays ensures the bit-arrays have been allocated for tracking +// what votes this peer has received. +// NOTE: It's important to make sure that numValidators actually matches +// what the node sees as the number of validators for height. +func (ps *PeerState) EnsureVoteBitArrays(height int64, numValidators int) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + ps.ensureVoteBitArrays(height, numValidators) +} + +func (ps *PeerState) ensureVoteBitArrays(height int64, numValidators int) { + switch ps.PRS.Height { + case height: + if ps.PRS.Prevotes == nil { + ps.PRS.Prevotes = bits.NewBitArray(numValidators) + } + if ps.PRS.Precommits == nil { + ps.PRS.Precommits = bits.NewBitArray(numValidators) + } + if ps.PRS.CatchupCommit == nil { + ps.PRS.CatchupCommit = bits.NewBitArray(numValidators) + } + if ps.PRS.ProposalPOL == nil { + ps.PRS.ProposalPOL = bits.NewBitArray(numValidators) + } + case height + 1: + if ps.PRS.LastCommit == nil { + ps.PRS.LastCommit = bits.NewBitArray(numValidators) + } + } +} + +// RecordVote increments internal votes related statistics for this peer. +// It returns the total number of added votes. +func (ps *PeerState) RecordVote() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + ps.Stats.Votes++ + + return ps.Stats.Votes +} + +// VotesSent returns the number of blocks for which peer has been sending us +// votes. +func (ps *PeerState) VotesSent() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + return ps.Stats.Votes +} + +// RecordBlockPart increments internal block part related statistics for this peer. +// It returns the total number of added block parts. +func (ps *PeerState) RecordBlockPart() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + ps.Stats.BlockParts++ + return ps.Stats.BlockParts +} + +// BlockPartsSent returns the number of useful block parts the peer has sent us. +func (ps *PeerState) BlockPartsSent() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + return ps.Stats.BlockParts +} + +// SetHasVote sets the given vote as known by the peer +func (ps *PeerState) SetHasVote(vote *types.Vote) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + ps.setHasVote(vote.Height, vote.Round, vote.Type, vote.ValidatorIndex) +} + +func (ps *PeerState) setHasVote(height int64, round int32, voteType cmtproto.SignedMsgType, index int32) { + ps.logger.Debug("setHasVote", + "peerH/R", + log.NewLazySprintf("%d/%d", ps.PRS.Height, ps.PRS.Round), + "H/R", + log.NewLazySprintf("%d/%d", height, round), + "type", voteType, "index", index) + + // NOTE: some may be nil BitArrays -> no side effects. + psVotes := ps.getVoteBitArray(height, round, voteType) + if psVotes != nil { + psVotes.SetIndex(int(index), true) + } +} + +// ApplyNewRoundStepMessage updates the peer state for the new round. +func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + // Ignore duplicates or decreases + if CompareHRS(msg.Height, msg.Round, msg.Step, ps.PRS.Height, ps.PRS.Round, ps.PRS.Step) <= 0 { + return + } + + // Just remember these values. + psHeight := ps.PRS.Height + psRound := ps.PRS.Round + psCatchupCommitRound := ps.PRS.CatchupCommitRound + psCatchupCommit := ps.PRS.CatchupCommit + lastPrecommits := ps.PRS.Precommits + + startTime := cmttime.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second) + ps.PRS.Height = msg.Height + ps.PRS.Round = msg.Round + ps.PRS.Step = msg.Step + ps.PRS.StartTime = startTime + if psHeight != msg.Height || psRound != msg.Round { + ps.PRS.Proposal = false + ps.PRS.ProposalBlockPartSetHeader = types.PartSetHeader{} + ps.PRS.ProposalBlockParts = nil + ps.PRS.ProposalPOLRound = -1 + ps.PRS.ProposalPOL = nil + // We'll update the BitArray capacity later. + ps.PRS.Prevotes = nil + ps.PRS.Precommits = nil + } + if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound { + // Peer caught up to CatchupCommitRound. + // Preserve psCatchupCommit! + // NOTE: We prefer to use prs.Precommits if + // pr.Round matches pr.CatchupCommitRound. + ps.PRS.Precommits = psCatchupCommit + } + if psHeight != msg.Height { + // Shift Precommits to LastCommit. + if psHeight+1 == msg.Height && psRound == msg.LastCommitRound { + ps.PRS.LastCommitRound = msg.LastCommitRound + ps.PRS.LastCommit = lastPrecommits + } else { + ps.PRS.LastCommitRound = msg.LastCommitRound + ps.PRS.LastCommit = nil + } + // We'll update the BitArray capacity later. + ps.PRS.CatchupCommitRound = -1 + ps.PRS.CatchupCommit = nil + } +} + +// ApplyNewValidBlockMessage updates the peer state for the new valid block. +func (ps *PeerState) ApplyNewValidBlockMessage(msg *NewValidBlockMessage) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.Height != msg.Height { + return + } + + if ps.PRS.Round != msg.Round && !msg.IsCommit { + return + } + + ps.PRS.ProposalBlockPartSetHeader = msg.BlockPartSetHeader + ps.PRS.ProposalBlockParts = msg.BlockParts +} + +// ApplyProposalPOLMessage updates the peer state for the new proposal POL. +func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.Height != msg.Height { + return + } + if ps.PRS.ProposalPOLRound != msg.ProposalPOLRound { + return + } + + // TODO: Merge onto existing ps.PRS.ProposalPOL? + // We might have sent some prevotes in the meantime. + ps.PRS.ProposalPOL = msg.ProposalPOL +} + +// ApplyHasVoteMessage updates the peer state for the new vote. +func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.PRS.Height != msg.Height { + return + } + + ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index) +} + +// ApplyVoteSetBitsMessage updates the peer state for the bit-array of votes +// it claims to have for the corresponding BlockID. +// `ourVotes` is a BitArray of votes we have for msg.BlockID +// NOTE: if ourVotes is nil (e.g. msg.Height < rs.Height), +// we conservatively overwrite ps's votes w/ msg.Votes. +func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes *bits.BitArray) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + votes := ps.getVoteBitArray(msg.Height, msg.Round, msg.Type) + if votes != nil { + if ourVotes == nil { + votes.Update(msg.Votes) + } else { + otherVotes := votes.Sub(ourVotes) + hasVotes := otherVotes.Or(msg.Votes) + votes.Update(hasVotes) + } + } +} + +// String returns a string representation of the PeerState +func (ps *PeerState) String() string { + return ps.StringIndented("") +} + +// StringIndented returns a string representation of the PeerState +func (ps *PeerState) StringIndented(indent string) string { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return fmt.Sprintf(`PeerState{ +%s Key %v +%s RoundState %v +%s Stats %v +%s}`, + indent, ps.peer.ID(), + indent, ps.PRS.StringIndented(indent+" "), + indent, ps.Stats, + indent) +} + +//----------------------------------------------------------------------------- +// Messages + +// Message is a message that can be sent and received on the Reactor +type Message interface { + ValidateBasic() error +} + +func init() { + cmtjson.RegisterType(&NewRoundStepMessage{}, "tendermint/NewRoundStepMessage") + cmtjson.RegisterType(&NewValidBlockMessage{}, "tendermint/NewValidBlockMessage") + cmtjson.RegisterType(&ProposalMessage{}, "tendermint/Proposal") + cmtjson.RegisterType(&ProposalPOLMessage{}, "tendermint/ProposalPOL") + cmtjson.RegisterType(&BlockPartMessage{}, "tendermint/BlockPart") + cmtjson.RegisterType(&VoteMessage{}, "tendermint/Vote") + cmtjson.RegisterType(&HasVoteMessage{}, "tendermint/HasVote") + cmtjson.RegisterType(&VoteSetMaj23Message{}, "tendermint/VoteSetMaj23") + cmtjson.RegisterType(&VoteSetBitsMessage{}, "tendermint/VoteSetBits") +} + +//------------------------------------- + +// NewRoundStepMessage is sent for every step taken in the ConsensusState. +// For every height/round/step transition +type NewRoundStepMessage struct { + Height int64 + Round int32 + Step cstypes.RoundStepType + SecondsSinceStartTime int64 + LastCommitRound int32 +} + +// ValidateBasic performs basic validation. +func (m *NewRoundStepMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.Round < 0 { + return errors.New("negative Round") + } + if !m.Step.IsValid() { + return errors.New("invalid Step") + } + + // NOTE: SecondsSinceStartTime may be negative + + // LastCommitRound will be -1 for the initial height, but we don't know what height this is + // since it can be specified in genesis. The reactor will have to validate this via + // ValidateHeight(). + if m.LastCommitRound < -1 { + return errors.New("invalid LastCommitRound (cannot be < -1)") + } + + return nil +} + +// ValidateHeight validates the height given the chain's initial height. +func (m *NewRoundStepMessage) ValidateHeight(initialHeight int64) error { + if m.Height < initialHeight { + return fmt.Errorf("invalid Height %v (lower than initial height %v)", + m.Height, initialHeight) + } + if m.Height == initialHeight && m.LastCommitRound != -1 { + return fmt.Errorf("invalid LastCommitRound %v (must be -1 for initial height %v)", + m.LastCommitRound, initialHeight) + } + if m.Height > initialHeight && m.LastCommitRound < 0 { + return fmt.Errorf("LastCommitRound can only be negative for initial height %v", + initialHeight) + } + return nil +} + +// String returns a string representation. +func (m *NewRoundStepMessage) String() string { + return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]", + m.Height, m.Round, m.Step, m.LastCommitRound) +} + +//------------------------------------- + +// NewValidBlockMessage is sent when a validator observes a valid block B in some round r, +// i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r. +// In case the block is also committed, then IsCommit flag is set to true. +type NewValidBlockMessage struct { + Height int64 + Round int32 + BlockPartSetHeader types.PartSetHeader + BlockParts *bits.BitArray + IsCommit bool +} + +// ValidateBasic performs basic validation. +func (m *NewValidBlockMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.Round < 0 { + return errors.New("negative Round") + } + if err := m.BlockPartSetHeader.ValidateBasic(); err != nil { + return fmt.Errorf("wrong BlockPartSetHeader: %v", err) + } + if err := m.BlockParts.ValidateBasic(); err != nil { + return fmt.Errorf("validating BlockParts: %w", err) + } + if m.BlockParts.Size() == 0 { + return errors.New("empty blockParts") + } + if m.BlockParts.Size() != int(m.BlockPartSetHeader.Total) { + return fmt.Errorf("blockParts bit array size %d not equal to BlockPartSetHeader.Total %d", + m.BlockParts.Size(), + m.BlockPartSetHeader.Total) + } + if m.BlockParts.Size() > int(types.MaxBlockPartsCount) { + return fmt.Errorf("blockParts bit array is too big: %d, max: %d", m.BlockParts.Size(), types.MaxBlockPartsCount) + } + return nil +} + +// String returns a string representation. +func (m *NewValidBlockMessage) String() string { + return fmt.Sprintf("[ValidBlockMessage H:%v R:%v BP:%v BA:%v IsCommit:%v]", + m.Height, m.Round, m.BlockPartSetHeader, m.BlockParts, m.IsCommit) +} + +//------------------------------------- + +// ProposalMessage is sent when a new block is proposed. +type ProposalMessage struct { + Proposal *types.Proposal +} + +// ValidateBasic performs basic validation. +func (m *ProposalMessage) ValidateBasic() error { + return m.Proposal.ValidateBasic() +} + +// ValidateBlockSize validates the proposals block size against a maximum. If +// -1 is passed, types.MaxBlockSizeBytes will be used as the maximum. +func (m *ProposalMessage) ValidateBlockSize(maxBlockSizeBytes int64) error { + return m.Proposal.ValidateBlockSize(maxBlockSizeBytes) +} + +// String returns a string representation. +func (m *ProposalMessage) String() string { + return fmt.Sprintf("[Proposal %v]", m.Proposal) +} + +//------------------------------------- + +// ProposalPOLMessage is sent when a previous proposal is re-proposed. +type ProposalPOLMessage struct { + Height int64 + ProposalPOLRound int32 + ProposalPOL *bits.BitArray +} + +// ValidateBasic performs basic validation. +func (m *ProposalPOLMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.ProposalPOLRound < 0 { + return errors.New("negative ProposalPOLRound") + } + if err := m.ProposalPOL.ValidateBasic(); err != nil { + return fmt.Errorf("validating ProposalPOL: %w", err) + } + if m.ProposalPOL.Size() == 0 { + return errors.New("empty ProposalPOL bit array") + } + if m.ProposalPOL.Size() > types.MaxVotesCount { + return fmt.Errorf("proposalPOL bit array is too big: %d, max: %d", m.ProposalPOL.Size(), types.MaxVotesCount) + } + return nil +} + +// String returns a string representation. +func (m *ProposalPOLMessage) String() string { + return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL) +} + +//------------------------------------- + +// BlockPartMessage is sent when gossipping a piece of the proposed block. +type BlockPartMessage struct { + Height int64 + Round int32 + Part *types.Part +} + +// ValidateBasic performs basic validation. +func (m *BlockPartMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.Round < 0 { + return errors.New("negative Round") + } + if err := m.Part.ValidateBasic(); err != nil { + return fmt.Errorf("wrong Part: %v", err) + } + return nil +} + +// String returns a string representation. +func (m *BlockPartMessage) String() string { + return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part) +} + +//------------------------------------- + +// VoteMessage is sent when voting for a proposal (or lack thereof). +type VoteMessage struct { + Vote *types.Vote +} + +// ValidateBasic checks whether the vote within the message is well-formed. +func (m *VoteMessage) ValidateBasic() error { + return m.Vote.ValidateBasic() +} + +// String returns a string representation. +func (m *VoteMessage) String() string { + return fmt.Sprintf("[Vote %v]", m.Vote) +} + +//------------------------------------- + +// HasVoteMessage is sent to indicate that a particular vote has been received. +type HasVoteMessage struct { + Height int64 + Round int32 + Type cmtproto.SignedMsgType + Index int32 +} + +// ValidateBasic performs basic validation. +func (m *HasVoteMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.Round < 0 { + return errors.New("negative Round") + } + if !types.IsVoteTypeValid(m.Type) { + return errors.New("invalid Type") + } + if m.Index < 0 { + return errors.New("negative Index") + } + return nil +} + +// String returns a string representation. +func (m *HasVoteMessage) String() string { + return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v}]", m.Index, m.Height, m.Round, m.Type) +} + +//------------------------------------- + +// VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes. +type VoteSetMaj23Message struct { + Height int64 + Round int32 + Type cmtproto.SignedMsgType + BlockID types.BlockID +} + +// ValidateBasic performs basic validation. +func (m *VoteSetMaj23Message) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if m.Round < 0 { + return errors.New("negative Round") + } + if !types.IsVoteTypeValid(m.Type) { + return errors.New("invalid Type") + } + if err := m.BlockID.ValidateBasic(); err != nil { + return fmt.Errorf("wrong BlockID: %v", err) + } + return nil +} + +// String returns a string representation. +func (m *VoteSetMaj23Message) String() string { + return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID) +} + +//------------------------------------- + +// VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID. +type VoteSetBitsMessage struct { + Height int64 + Round int32 + Type cmtproto.SignedMsgType + BlockID types.BlockID + Votes *bits.BitArray +} + +// ValidateBasic performs basic validation. +func (m *VoteSetBitsMessage) ValidateBasic() error { + if m.Height < 0 { + return errors.New("negative Height") + } + if !types.IsVoteTypeValid(m.Type) { + return errors.New("invalid Type") + } + if err := m.BlockID.ValidateBasic(); err != nil { + return fmt.Errorf("wrong BlockID: %v", err) + } + if err := m.Votes.ValidateBasic(); err != nil { + return fmt.Errorf("validating Votes: %w", err) + } + // NOTE: Votes.Size() can be zero if the node does not have any + if m.Votes.Size() > types.MaxVotesCount { + return fmt.Errorf("votes bit array is too big: %d, max: %d", m.Votes.Size(), types.MaxVotesCount) + } + return nil +} + +// String returns a string representation. +func (m *VoteSetBitsMessage) String() string { + return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes) +} + +//------------------------------------- diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go new file mode 100644 index 0000000..771c05f --- /dev/null +++ b/consensus/reactor_test.go @@ -0,0 +1,1189 @@ +package consensus + +import ( + "context" + "fmt" + "os" + "path" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + cfg "github.com/cometbft/cometbft/config" + cstypes "github.com/cometbft/cometbft/consensus/types" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/bits" + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtsync "github.com/cometbft/cometbft/libs/sync" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + p2pmock "github.com/cometbft/cometbft/p2p/mock" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + statemocks "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +//---------------------------------------------- +// in-process testnets + +var defaultTestTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + +func startConsensusNet(t *testing.T, css []*State, n int) ( + []*Reactor, + []types.Subscription, + []*types.EventBus, +) { + reactors := make([]*Reactor, n) + blocksSubs := make([]types.Subscription, 0) + eventBuses := make([]*types.EventBus, n) + for i := 0; i < n; i++ { + /*logger, err := cmtflags.ParseLogLevel("consensus:info,*:error", logger, "info") + if err != nil { t.Fatal(err)}*/ + reactors[i] = NewReactor(css[i], true) // so we dont start the consensus states + reactors[i].SetLogger(css[i].Logger) + + // eventBus is already started with the cs + eventBuses[i] = css[i].eventBus + reactors[i].SetEventBus(eventBuses[i]) + + blocksSub, err := eventBuses[i].Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock) + require.NoError(t, err) + blocksSubs = append(blocksSubs, blocksSub) + + if css[i].state.LastBlockHeight == 0 { // simulate handle initChain in handshake + if err := css[i].blockExec.Store().Save(css[i].state); err != nil { + t.Error(err) + } + } + } + // make connected switches and start all reactors + p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("CONSENSUS", reactors[i]) + s.SetLogger(reactors[i].conS.Logger.With("module", "p2p")) + return s + }, p2p.Connect2Switches) + + // now that everyone is connected, start the state machines + // If we started the state machines before everyone was connected, + // we'd block when the cs fires NewBlockEvent and the peers are trying to start their reactors + // TODO: is this still true with new pubsub? + for i := 0; i < n; i++ { + s := reactors[i].conS.GetState() + reactors[i].SwitchToConsensus(s, false) + } + return reactors, blocksSubs, eventBuses +} + +func stopConsensusNet(logger log.Logger, reactors []*Reactor, eventBuses []*types.EventBus) { + logger.Info("stopConsensusNet", "n", len(reactors)) + for i, r := range reactors { + logger.Info("stopConsensusNet: Stopping Reactor", "i", i) + if err := r.Switch.Stop(); err != nil { + logger.Error("error trying to stop switch", "error", err) + } + } + for i, b := range eventBuses { + logger.Info("stopConsensusNet: Stopping eventBus", "i", i) + if err := b.Stop(); err != nil { + logger.Error("error trying to stop eventbus", "error", err) + } + } + logger.Info("stopConsensusNet: DONE", "n", len(reactors)) +} + +// Ensure a testnet makes blocks +func TestReactorBasic(t *testing.T) { + N := 4 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore) + defer cleanup() + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + // wait till everyone makes the first new block + timeoutWaitGroup(N, func(j int) { + <-blocksSubs[j].Out() + }) +} + +// Ensure we can process blocks with evidence +func TestReactorWithEvidence(t *testing.T) { + nValidators := 4 + testName := "consensus_reactor_test" + tickerFunc := newMockTickerFunc(true) + appFunc := newKVStore + + // heed the advice from https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction + // to unroll unwieldy abstractions. Here we duplicate the code from: + // css := randConsensusNet(N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore) + + genDoc, privVals := randGenesisDoc(nValidators, false, 30, nil) + css := make([]*State, nValidators) + logger := consensusLogger() + for i := 0; i < nValidators; i++ { + stateDB := dbm.NewMemDB() // each state needs its own db + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) + defer os.RemoveAll(thisConfig.RootDir) + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal + app := appFunc() + vals := types.TM2PB.ValidatorUpdates(state.Validators) + _, err := app.InitChain(context.Background(), &abci.RequestInitChain{Validators: vals}) + require.NoError(t, err) + + pv := privVals[i] + // duplicate code from: + // css[i] = newStateWithConfig(thisConfig, state, privVals[i], app) + + blockDB := dbm.NewMemDB() + blockStore := store.NewBlockStore(blockDB) + + mtx := new(cmtsync.Mutex) + memplMetrics := mempl.NopMetrics() + // one for mempool, one for consensus + proxyAppConnCon := proxy.NewAppConnConsensus(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + proxyAppConnMem := proxy.NewAppConnMempool(abcicli.NewLocalClient(mtx, app), proxy.NopMetrics()) + + // Make Mempool + mempool := mempl.NewCListMempool(config.Mempool, + proxyAppConnMem, + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state))) + + if thisConfig.Consensus.WaitForTxs() { + mempool.EnableTxsAvailable() + } + + // mock the evidence pool + // everyone includes evidence of another double signing + vIdx := (i + 1) % nValidators + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultTestTime, privVals[vIdx], genDoc.ChainID) + require.NoError(t, err) + evpool := &statemocks.EvidencePool{} + evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil) + evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{ + ev, + }, int64(len(ev.Bytes()))) + evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return() + + evpool2 := sm.EmptyEvidencePool{} + + // Make State + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore) + cs := NewState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool2) + cs.SetLogger(log.TestingLogger().With("module", "consensus")) + cs.SetPrivValidator(pv) + + eventBus := types.NewEventBus() + eventBus.SetLogger(log.TestingLogger().With("module", "events")) + err = eventBus.Start() + require.NoError(t, err) + cs.SetEventBus(eventBus) + + cs.SetTimeoutTicker(tickerFunc()) + cs.SetLogger(logger.With("validator", i, "module", "consensus")) + + css[i] = cs + } + + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nValidators) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // we expect for each validator that is the proposer to propose one piece of evidence. + for i := 0; i < nValidators; i++ { + timeoutWaitGroup(nValidators, func(j int) { + msg := <-blocksSubs[j].Out() + block := msg.Data().(types.EventDataNewBlock).Block + assert.Len(t, block.Evidence.Evidence, 1) + }) + } +} + +//------------------------------------ + +// Ensure a testnet makes blocks when there are txs +func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) { + N := 4 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore, + func(c *cfg.Config) { + c.Consensus.CreateEmptyBlocks = false + }) + defer cleanup() + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // send a tx + if err := assertMempool(css[3].txNotifier).CheckTx(kvstore.NewTxFromID(1), func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + }, mempl.TxInfo{}); err != nil { + t.Error(err) + } + + // wait till everyone makes the first new block + timeoutWaitGroup(N, func(j int) { + <-blocksSubs[j].Out() + }) +} + +func TestReactorReceiveDoesNotPanicIfAddPeerHasntBeenCalledYet(t *testing.T) { + N := 1 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore) + defer cleanup() + reactors, _, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + var ( + reactor = reactors[0] + peer = p2pmock.NewPeer(nil) + ) + + reactor.InitPeer(peer) + + // simulate switch calling Receive before AddPeer + assert.NotPanics(t, func() { + reactor.Receive(p2p.Envelope{ + ChannelID: StateChannel, + Src: peer, + Message: &cmtcons.HasVote{ + Height: 1, + Round: 1, + Index: 1, + Type: cmtproto.PrevoteType, + }, + }) + reactor.AddPeer(peer) + }) +} + +func TestReactorReceivePanicsIfInitPeerHasntBeenCalledYet(t *testing.T) { + N := 1 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore) + defer cleanup() + reactors, _, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + var ( + reactor = reactors[0] + peer = p2pmock.NewPeer(nil) + ) + + // we should call InitPeer here + + // simulate switch calling Receive before AddPeer + assert.Panics(t, func() { + reactor.Receive(p2p.Envelope{ + ChannelID: StateChannel, + Src: peer, + Message: &cmtcons.HasVote{ + Height: 1, + Round: 1, + Index: 1, + Type: cmtproto.PrevoteType, + }, + }) + }) +} + +// TestSwitchToConsensusVoteExtensions tests that the SwitchToConsensus correctly +// checks for vote extension data when required. +func TestSwitchToConsensusVoteExtensions(t *testing.T) { + for _, testCase := range []struct { + name string + storedHeight int64 + initialRequiredHeight int64 + includeExtensions bool + shouldPanic bool + }{ + { + name: "no vote extensions but not required", + initialRequiredHeight: 0, + storedHeight: 2, + includeExtensions: false, + shouldPanic: false, + }, + { + name: "no vote extensions but required this height", + initialRequiredHeight: 2, + storedHeight: 2, + includeExtensions: false, + shouldPanic: true, + }, + { + name: "no vote extensions and required in future", + initialRequiredHeight: 3, + storedHeight: 2, + includeExtensions: false, + shouldPanic: false, + }, + { + name: "no vote extensions and required previous height", + initialRequiredHeight: 1, + storedHeight: 2, + includeExtensions: false, + shouldPanic: true, + }, + { + name: "vote extensions and required previous height", + initialRequiredHeight: 1, + storedHeight: 2, + includeExtensions: true, + shouldPanic: false, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs, vs := randState(1) + validator := vs[0] + validator.Height = testCase.storedHeight + + cs.state.LastBlockHeight = testCase.storedHeight + cs.state.LastValidators = cs.state.Validators.Copy() + cs.state.ConsensusParams.ABCI.VoteExtensionsEnableHeight = testCase.initialRequiredHeight + + propBlock, err := cs.createProposalBlock(ctx) + require.NoError(t, err) + + // Consensus is preparing to do the next height after the stored height. + cs.Height = testCase.storedHeight + 1 + propBlock.Height = testCase.storedHeight + blockParts, err := propBlock.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + + var voteSet *types.VoteSet + if testCase.includeExtensions { + voteSet = types.NewExtendedVoteSet(cs.state.ChainID, testCase.storedHeight, 0, cmtproto.PrecommitType, cs.state.Validators) + } else { + voteSet = types.NewVoteSet(cs.state.ChainID, testCase.storedHeight, 0, cmtproto.PrecommitType, cs.state.Validators) + } + signedVote := signVote(validator, cmtproto.PrecommitType, propBlock.Hash(), blockParts.Header(), testCase.includeExtensions) + + var veHeight int64 + if testCase.includeExtensions { + require.NotNil(t, signedVote.ExtensionSignature) + veHeight = testCase.storedHeight + } else { + require.Nil(t, signedVote.Extension) + require.Nil(t, signedVote.ExtensionSignature) + } + + added, err := voteSet.AddVote(signedVote) + require.NoError(t, err) + require.True(t, added) + + veHeightParam := types.ABCIParams{VoteExtensionsEnableHeight: veHeight} + if testCase.includeExtensions { + cs.blockStore.SaveBlockWithExtendedCommit(propBlock, blockParts, voteSet.MakeExtendedCommit(veHeightParam)) + } else { + cs.blockStore.SaveBlock(propBlock, blockParts, voteSet.MakeExtendedCommit(veHeightParam).ToCommit()) + } + reactor := NewReactor( + cs, + true, + ) + + if testCase.shouldPanic { + assert.Panics(t, func() { + reactor.SwitchToConsensus(cs.state, false) + }) + } else { + reactor.SwitchToConsensus(cs.state, false) + } + }) + } +} + +// Test we record stats about votes and block parts from other peers. +func TestReactorRecordsVotesAndBlockParts(t *testing.T) { + N := 4 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_test", newMockTickerFunc(true), newKVStore) + defer cleanup() + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // wait till everyone makes the first new block + timeoutWaitGroup(N, func(j int) { + <-blocksSubs[j].Out() + }) + + // Get peer + peer := reactors[1].Switch.Peers().List()[0] + // Get peer state + ps := peer.Get(types.PeerStateKey).(*PeerState) + + assert.Equal(t, true, ps.VotesSent() > 0, "number of votes sent should have increased") + assert.Equal(t, true, ps.BlockPartsSent() > 0, "number of votes sent should have increased") +} + +//------------------------------------------------------------- +// ensure we can make blocks despite cycling a validator set + +func TestReactorVotingPowerChange(t *testing.T) { + nVals := 4 + logger := log.TestingLogger() + css, cleanup := randConsensusNet( + t, + nVals, + "consensus_voting_power_changes_test", + newMockTickerFunc(true), + newPersistentKVStore) + defer cleanup() + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nVals) + defer stopConsensusNet(logger, reactors, eventBuses) + + // map of active validators + activeVals := make(map[string]struct{}) + for i := 0; i < nVals; i++ { + pubKey, err := css[i].privValidator.GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + activeVals[string(addr)] = struct{}{} + } + + // wait till everyone makes block 1 + timeoutWaitGroup(nVals, func(j int) { + <-blocksSubs[j].Out() + }) + + //--------------------------------------------------------------------------- + logger.Debug("---------------------------- Testing changing the voting power of one validator a few times") + + val1PubKey, err := css[0].privValidator.GetPubKey() + require.NoError(t, err) + + val1PubKeyABCI, err := cryptoenc.PubKeyToProto(val1PubKey) + require.NoError(t, err) + updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25) + previousTotalVotingPower := css[0].GetRoundState().LastValidators.TotalVotingPower() + + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + + if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower { + t.Fatalf( + "expected voting power to change (before: %d, after: %d)", + previousTotalVotingPower, + css[0].GetRoundState().LastValidators.TotalVotingPower()) + } + + updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 2) + previousTotalVotingPower = css[0].GetRoundState().LastValidators.TotalVotingPower() + + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + + if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower { + t.Fatalf( + "expected voting power to change (before: %d, after: %d)", + previousTotalVotingPower, + css[0].GetRoundState().LastValidators.TotalVotingPower()) + } + + updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 26) + previousTotalVotingPower = css[0].GetRoundState().LastValidators.TotalVotingPower() + + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css) + + if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower { + t.Fatalf( + "expected voting power to change (before: %d, after: %d)", + previousTotalVotingPower, + css[0].GetRoundState().LastValidators.TotalVotingPower()) + } +} + +func TestReactorValidatorSetChanges(t *testing.T) { + nPeers := 7 + nVals := 4 + css, _, _, cleanup := randConsensusNetWithPeers( + t, + nVals, + nPeers, + "consensus_val_set_changes_test", + newMockTickerFunc(true), + newPersistentKVStoreWithPath) + + defer cleanup() + logger := log.TestingLogger() + + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nPeers) + defer stopConsensusNet(logger, reactors, eventBuses) + + // map of active validators + activeVals := make(map[string]struct{}) + for i := 0; i < nVals; i++ { + pubKey, err := css[i].privValidator.GetPubKey() + require.NoError(t, err) + activeVals[string(pubKey.Address())] = struct{}{} + } + + // wait till everyone makes block 1 + timeoutWaitGroup(nPeers, func(j int) { + <-blocksSubs[j].Out() + }) + + t.Run("Testing adding one validator", func(t *testing.T) { + newValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() + assert.NoError(t, err) + valPubKey1ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey1) + assert.NoError(t, err) + newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) + + // wait till everyone makes block 2 + // ensure the commit includes all validators + // send newValTx to change vals in block 3 + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, newValidatorTx1) + + // wait till everyone makes block 3. + // it includes the commit for block 2, which is by the original validator set + waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, newValidatorTx1) + + // wait till everyone makes block 4. + // it includes the commit for block 3, which is by the original validator set + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css) + + // the commits for block 4 should be with the updated validator set + activeVals[string(newValidatorPubKey1.Address())] = struct{}{} + + // wait till everyone makes block 5 + // it includes the commit for block 4, which should have the updated validator set + waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css) + }) + + t.Run("Testing changing the voting power of one validator", func(t *testing.T) { + updateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() + require.NoError(t, err) + updatePubKey1ABCI, err := cryptoenc.PubKeyToProto(updateValidatorPubKey1) + require.NoError(t, err) + updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) + previousTotalVotingPower := css[nVals].GetRoundState().LastValidators.TotalVotingPower() + + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, updateValidatorTx1) + waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, updateValidatorTx1) + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css) + waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css) + + if css[nVals].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower { + t.Errorf( + "expected voting power to change (before: %d, after: %d)", + previousTotalVotingPower, + css[nVals].GetRoundState().LastValidators.TotalVotingPower()) + } + }) + + newValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey() + require.NoError(t, err) + newVal2ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey2) + require.NoError(t, err) + newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) + + newValidatorPubKey3, err := css[nVals+2].privValidator.GetPubKey() + require.NoError(t, err) + newVal3ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey3) + require.NoError(t, err) + newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) + + t.Run("Testing adding two validators at once", func(t *testing.T) { + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, newValidatorTx2, newValidatorTx3) + waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, newValidatorTx2, newValidatorTx3) + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css) + activeVals[string(newValidatorPubKey2.Address())] = struct{}{} + activeVals[string(newValidatorPubKey3.Address())] = struct{}{} + waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css) + }) + + t.Run("Testing removing two validators at once", func(t *testing.T) { + removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0) + removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0) + + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, removeValidatorTx2, removeValidatorTx3) + waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, removeValidatorTx2, removeValidatorTx3) + waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css) + delete(activeVals, string(newValidatorPubKey2.Address())) + delete(activeVals, string(newValidatorPubKey3.Address())) + waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css) + }) +} + +// Check we can make blocks with skip_timeout_commit=false +func TestReactorWithTimeoutCommit(t *testing.T) { + N := 4 + css, cleanup := randConsensusNet(t, N, "consensus_reactor_with_timeout_commit_test", newMockTickerFunc(false), newKVStore) + defer cleanup() + // override default SkipTimeoutCommit == true for tests + for i := 0; i < N; i++ { + css[i].config.SkipTimeoutCommit = false + } + + reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N-1) + defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses) + + // wait till everyone makes the first new block + timeoutWaitGroup(N-1, func(j int) { + <-blocksSubs[j].Out() + }) +} + +func waitForAndValidateBlock( + t *testing.T, + n int, + activeVals map[string]struct{}, + blocksSubs []types.Subscription, + css []*State, + txs ...[]byte, +) { + timeoutWaitGroup(n, func(j int) { + css[j].Logger.Debug("waitForAndValidateBlock") + msg := <-blocksSubs[j].Out() + newBlock := msg.Data().(types.EventDataNewBlock).Block + css[j].Logger.Debug("waitForAndValidateBlock: Got block", "height", newBlock.Height) + err := validateBlock(newBlock, activeVals) + require.NoError(t, err) + + // optionally add transactions for the next block + for _, tx := range txs { + err := assertMempool(css[j].txNotifier).CheckTx(tx, func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + fmt.Println(resp) + }, mempl.TxInfo{}) + require.NoError(t, err) + } + }) +} + +func waitForAndValidateBlockWithTx( + t *testing.T, + n int, + activeVals map[string]struct{}, + blocksSubs []types.Subscription, + css []*State, + txs ...[]byte, +) { + timeoutWaitGroup(n, func(j int) { + ntxs := 0 + BLOCK_TX_LOOP: + for { + css[j].Logger.Debug("waitForAndValidateBlockWithTx", "ntxs", ntxs) + msg := <-blocksSubs[j].Out() + newBlock := msg.Data().(types.EventDataNewBlock).Block + css[j].Logger.Debug("waitForAndValidateBlockWithTx: Got block", "height", newBlock.Height) + err := validateBlock(newBlock, activeVals) + require.NoError(t, err) + + // check that txs match the txs we're waiting for. + // note they could be spread over multiple blocks, + // but they should be in order. + for _, tx := range newBlock.Txs { + assert.EqualValues(t, txs[ntxs], tx) + ntxs++ + } + + if ntxs == len(txs) { + break BLOCK_TX_LOOP + } + } + }) +} + +func waitForBlockWithUpdatedValsAndValidateIt( + t *testing.T, + n int, + updatedVals map[string]struct{}, + blocksSubs []types.Subscription, + css []*State, +) { + timeoutWaitGroup(n, func(j int) { + var newBlock *types.Block + LOOP: + for { + css[j].Logger.Debug("waitForBlockWithUpdatedValsAndValidateIt") + msg := <-blocksSubs[j].Out() + newBlock = msg.Data().(types.EventDataNewBlock).Block + if newBlock.LastCommit.Size() == len(updatedVals) { + css[j].Logger.Debug("waitForBlockWithUpdatedValsAndValidateIt: Got block", "height", newBlock.Height) + break LOOP + } + css[j].Logger.Debug( + "waitForBlockWithUpdatedValsAndValidateIt: Got block with no new validators. Skipping", + "height", newBlock.Height, "last_commit", newBlock.LastCommit.Size(), "updated_vals", len(updatedVals), + ) + } + + err := validateBlock(newBlock, updatedVals) + assert.Nil(t, err) + }) +} + +// expects high synchrony! +func validateBlock(block *types.Block, activeVals map[string]struct{}) error { + if block.LastCommit.Size() != len(activeVals) { + return fmt.Errorf( + "commit size doesn't match number of active validators. Got %d, expected %d", + block.LastCommit.Size(), + len(activeVals)) + } + + for _, commitSig := range block.LastCommit.Signatures { + if _, ok := activeVals[string(commitSig.ValidatorAddress)]; !ok { + return fmt.Errorf("found vote for inactive validator %X", commitSig.ValidatorAddress) + } + } + return nil +} + +func timeoutWaitGroup(n int, f func(int)) { + wg := new(sync.WaitGroup) + wg.Add(n) + for i := 0; i < n; i++ { + go func(j int) { + f(j) + wg.Done() + }(i) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + // we're running many nodes in-process, possibly in in a virtual machine, + // and spewing debug messages - making a block could take a while, + timeout := time.Second * 20 + + select { + case <-done: + case <-time.After(timeout): + panic("Timed out waiting for all validators to commit a block") + } +} + +//------------------------------------------------------------- +// Ensure basic validation of structs is functioning + +func TestNewRoundStepMessageValidateBasic(t *testing.T) { + testCases := []struct { //nolint: maligned + expectErr bool + messageRound int32 + messageLastCommitRound int32 + messageHeight int64 + testName string + messageStep cstypes.RoundStepType + }{ + {false, 0, 0, 0, "Valid Message", cstypes.RoundStepNewHeight}, + {true, -1, 0, 0, "Negative round", cstypes.RoundStepNewHeight}, + {true, 0, 0, -1, "Negative height", cstypes.RoundStepNewHeight}, + {true, 0, 0, 0, "Invalid Step", cstypes.RoundStepCommit + 1}, + // The following cases will be handled by ValidateHeight + {false, 0, 0, 1, "H == 1 but LCR != -1 ", cstypes.RoundStepNewHeight}, + {false, 0, -1, 2, "H > 1 but LCR < 0", cstypes.RoundStepNewHeight}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + message := NewRoundStepMessage{ + Height: tc.messageHeight, + Round: tc.messageRound, + Step: tc.messageStep, + LastCommitRound: tc.messageLastCommitRound, + } + + err := message.ValidateBasic() + if tc.expectErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestNewRoundStepMessageValidateHeight(t *testing.T) { + initialHeight := int64(10) + testCases := []struct { //nolint: maligned + expectErr bool + messageLastCommitRound int32 + messageHeight int64 + testName string + }{ + {false, 0, 11, "Valid Message"}, + {true, 0, -1, "Negative height"}, + {true, 0, 0, "Zero height"}, + {true, 0, 10, "Initial height but LCR != -1 "}, + {true, -1, 11, "Normal height but LCR < 0"}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + message := NewRoundStepMessage{ + Height: tc.messageHeight, + Round: 0, + Step: cstypes.RoundStepNewHeight, + LastCommitRound: tc.messageLastCommitRound, + } + + err := message.ValidateHeight(initialHeight) + if tc.expectErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestNewValidBlockMessageValidateBasic(t *testing.T) { + testCases := []struct { + malleateFn func(*NewValidBlockMessage) + expErr string + }{ + {func(msg *NewValidBlockMessage) {}, ""}, + {func(msg *NewValidBlockMessage) { msg.Height = -1 }, "negative Height"}, + {func(msg *NewValidBlockMessage) { msg.Round = -1 }, "negative Round"}, + { + func(msg *NewValidBlockMessage) { msg.BlockPartSetHeader.Total = 2 }, + "blockParts bit array size 1 not equal to BlockPartSetHeader.Total 2", + }, + { + func(msg *NewValidBlockMessage) { + msg.BlockPartSetHeader.Total = 0 + msg.BlockParts = bits.NewBitArray(0) + }, + "empty blockParts", + }, + { + func(msg *NewValidBlockMessage) { msg.BlockParts = bits.NewBitArray(int(types.MaxBlockPartsCount) + 1) }, + "blockParts bit array size 1602 not equal to BlockPartSetHeader.Total 1", + }, + { + func(msg *NewValidBlockMessage) { msg.BlockParts.Elems = nil }, + "mismatch between specified number of bits 1, and number of elements 0, expected 1 elements", + }, + { + func(msg *NewValidBlockMessage) { msg.BlockParts.Bits = 500 }, + "mismatch between specified number of bits 500, and number of elements 1, expected 8 elements", + }, + } + + for i, tc := range testCases { + tc := tc + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + msg := &NewValidBlockMessage{ + Height: 1, + Round: 0, + BlockPartSetHeader: types.PartSetHeader{ + Total: 1, + }, + BlockParts: bits.NewBitArray(1), + } + + tc.malleateFn(msg) + err := msg.ValidateBasic() + if tc.expErr != "" && assert.Error(t, err) { + assert.Contains(t, err.Error(), tc.expErr) + } + }) + } +} + +func TestProposalPOLMessageValidateBasic(t *testing.T) { + testCases := []struct { + malleateFn func(*ProposalPOLMessage) + expErr string + }{ + {func(msg *ProposalPOLMessage) {}, ""}, + {func(msg *ProposalPOLMessage) { msg.Height = -1 }, "negative Height"}, + {func(msg *ProposalPOLMessage) { msg.ProposalPOLRound = -1 }, "negative ProposalPOLRound"}, + {func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(0) }, "empty ProposalPOL bit array"}, + { + func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(types.MaxVotesCount + 1) }, + "proposalPOL bit array is too big: 10001, max: 10000", + }, + { + func(msg *ProposalPOLMessage) { msg.ProposalPOL.Elems = nil }, + "mismatch between specified number of bits 1, and number of elements 0, expected 1 elements", + }, + { + func(msg *ProposalPOLMessage) { msg.ProposalPOL.Bits = 500 }, + "mismatch between specified number of bits 500, and number of elements 1, expected 8 elements", + }, + } + + for i, tc := range testCases { + tc := tc + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + msg := &ProposalPOLMessage{ + Height: 1, + ProposalPOLRound: 1, + ProposalPOL: bits.NewBitArray(1), + } + + tc.malleateFn(msg) + err := msg.ValidateBasic() + if tc.expErr != "" && assert.Error(t, err) { + assert.Contains(t, err.Error(), tc.expErr) + } + }) + } +} + +func TestBlockPartMessageValidateBasic(t *testing.T) { + testPart := new(types.Part) + testPart.Proof.LeafHash = tmhash.Sum([]byte("leaf")) + testCases := []struct { + testName string + messageHeight int64 + messageRound int32 + messagePart *types.Part + expectErr bool + }{ + {"Valid Message", 0, 0, testPart, false}, + {"Invalid Message", -1, 0, testPart, true}, + {"Invalid Message", 0, -1, testPart, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + message := BlockPartMessage{ + Height: tc.messageHeight, + Round: tc.messageRound, + Part: tc.messagePart, + } + + assert.Equal(t, tc.expectErr, message.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } + + message := BlockPartMessage{Height: 0, Round: 0, Part: new(types.Part)} + message.Part.Index = 1 + + assert.Equal(t, true, message.ValidateBasic() != nil, "Validate Basic had an unexpected result") +} + +func TestHasVoteMessageValidateBasic(t *testing.T) { + const ( + validSignedMsgType cmtproto.SignedMsgType = 0x01 + invalidSignedMsgType cmtproto.SignedMsgType = 0x03 + ) + + testCases := []struct { //nolint: maligned + expectErr bool + messageRound int32 + messageIndex int32 + messageHeight int64 + testName string + messageType cmtproto.SignedMsgType + }{ + {false, 0, 0, 0, "Valid Message", validSignedMsgType}, + {true, -1, 0, 0, "Invalid Message", validSignedMsgType}, + {true, 0, -1, 0, "Invalid Message", validSignedMsgType}, + {true, 0, 0, 0, "Invalid Message", invalidSignedMsgType}, + {true, 0, 0, -1, "Invalid Message", validSignedMsgType}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + message := HasVoteMessage{ + Height: tc.messageHeight, + Round: tc.messageRound, + Type: tc.messageType, + Index: tc.messageIndex, + } + + assert.Equal(t, tc.expectErr, message.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestVoteSetMaj23MessageValidateBasic(t *testing.T) { + const ( + validSignedMsgType cmtproto.SignedMsgType = 0x01 + invalidSignedMsgType cmtproto.SignedMsgType = 0x03 + ) + + validBlockID := types.BlockID{} + invalidBlockID := types.BlockID{ + Hash: bytes.HexBytes{}, + PartSetHeader: types.PartSetHeader{ + Total: 1, + Hash: []byte{0}, + }, + } + + testCases := []struct { //nolint: maligned + expectErr bool + messageRound int32 + messageHeight int64 + testName string + messageType cmtproto.SignedMsgType + messageBlockID types.BlockID + }{ + {false, 0, 0, "Valid Message", validSignedMsgType, validBlockID}, + {true, -1, 0, "Invalid Message", validSignedMsgType, validBlockID}, + {true, 0, -1, "Invalid Message", validSignedMsgType, validBlockID}, + {true, 0, 0, "Invalid Message", invalidSignedMsgType, validBlockID}, + {true, 0, 0, "Invalid Message", validSignedMsgType, invalidBlockID}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + message := VoteSetMaj23Message{ + Height: tc.messageHeight, + Round: tc.messageRound, + Type: tc.messageType, + BlockID: tc.messageBlockID, + } + + assert.Equal(t, tc.expectErr, message.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestVoteSetBitsMessageValidateBasic(t *testing.T) { + testCases := []struct { + malleateFn func(*VoteSetBitsMessage) + expErr string + }{ + {func(msg *VoteSetBitsMessage) {}, ""}, + {func(msg *VoteSetBitsMessage) { msg.Height = -1 }, "negative Height"}, + {func(msg *VoteSetBitsMessage) { msg.Type = 0x03 }, "invalid Type"}, + {func(msg *VoteSetBitsMessage) { + msg.BlockID = types.BlockID{ + Hash: bytes.HexBytes{}, + PartSetHeader: types.PartSetHeader{ + Total: 1, + Hash: []byte{0}, + }, + } + }, "wrong BlockID: wrong PartSetHeader: wrong Hash:"}, + { + func(msg *VoteSetBitsMessage) { msg.Votes = bits.NewBitArray(types.MaxVotesCount + 1) }, + "votes bit array is too big: 10001, max: 10000", + }, + { + func(msg *VoteSetBitsMessage) { msg.Votes.Elems = nil }, + "mismatch between specified number of bits 1, and number of elements 0, expected 1 elements", + }, + { + func(msg *VoteSetBitsMessage) { msg.Votes.Bits = 500 }, + "mismatch between specified number of bits 500, and number of elements 1, expected 8 elements", + }, + } + + for i, tc := range testCases { + tc := tc + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + msg := &VoteSetBitsMessage{ + Height: 1, + Round: 0, + Type: 0x01, + Votes: bits.NewBitArray(1), + BlockID: types.BlockID{}, + } + + tc.malleateFn(msg) + err := msg.ValidateBasic() + if tc.expErr != "" && assert.Error(t, err) { + assert.Contains(t, err.Error(), tc.expErr) + } + }) + } +} + +func TestMarshalJSONPeerState(t *testing.T) { + ps := NewPeerState(nil) + data, err := json.Marshal(ps) + require.NoError(t, err) + require.JSONEq(t, `{ + "round_state":{ + "height": "0", + "round": -1, + "step": 0, + "start_time": "0001-01-01T00:00:00Z", + "proposal": false, + "proposal_block_part_set_header": + {"total":0, "hash":""}, + "proposal_block_parts": null, + "proposal_pol_round": -1, + "proposal_pol": null, + "prevotes": null, + "precommits": null, + "last_commit_round": -1, + "last_commit": null, + "catchup_commit_round": -1, + "catchup_commit": null + }, + "stats":{ + "votes":"0", + "block_parts":"0"} + }`, string(data)) +} + +func TestVoteMessageValidateBasic(t *testing.T) { + _, vss := randState(2) + + randBytes := cmtrand.Bytes(tmhash.Size) + blockID := types.BlockID{ + Hash: randBytes, + PartSetHeader: types.PartSetHeader{ + Total: 1, + Hash: randBytes, + }, + } + vote := signVote(vss[1], cmtproto.PrecommitType, randBytes, blockID.PartSetHeader, true) + + testCases := []struct { + malleateFn func(*VoteMessage) + expErr string + }{ + {func(_ *VoteMessage) {}, ""}, + {func(msg *VoteMessage) { msg.Vote.ValidatorIndex = -1 }, "negative ValidatorIndex"}, + // INVALID, but passes ValidateBasic, since the method does not know the number of active validators + {func(msg *VoteMessage) { msg.Vote.ValidatorIndex = 1000 }, ""}, + } + + for i, tc := range testCases { + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + msg := &VoteMessage{vote} + + tc.malleateFn(msg) + err := msg.ValidateBasic() + if tc.expErr != "" && assert.Error(t, err) { //nolint:testifylint // require.Error doesn't work with the conditional here + assert.Contains(t, err.Error(), tc.expErr) + } + }) + } +} diff --git a/consensus/replay.go b/consensus/replay.go new file mode 100644 index 0000000..293d5f2 --- /dev/null +++ b/consensus/replay.go @@ -0,0 +1,565 @@ +package consensus + +import ( + "bytes" + "context" + "fmt" + "hash/crc32" + "io" + "reflect" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +var crc32c = crc32.MakeTable(crc32.Castagnoli) + +// Functionality to replay blocks and messages on recovery from a crash. +// There are two general failure scenarios: +// +// 1. failure during consensus +// 2. failure while applying the block +// +// The former is handled by the WAL, the latter by the proxyApp Handshake on +// restart, which ultimately hands off the work to the WAL. + +//----------------------------------------- +// 1. Recover from failure during consensus +// (by replaying messages from the WAL) +//----------------------------------------- + +// Unmarshal and apply a single message to the consensus state as if it were +// received in receiveRoutine. Lines that start with "#" are ignored. +// NOTE: receiveRoutine should not be running. +func (cs *State) readReplayMessage(msg *TimedWALMessage, newStepSub types.Subscription) error { + // Skip meta messages which exist for demarcating boundaries. + if _, ok := msg.Msg.(EndHeightMessage); ok { + return nil + } + + // for logging + switch m := msg.Msg.(type) { + case types.EventDataRoundState: + cs.Logger.Info("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step) + // these are playback checks + ticker := time.After(time.Second * 2) + if newStepSub != nil { + select { + case stepMsg := <-newStepSub.Out(): + m2 := stepMsg.Data().(types.EventDataRoundState) + if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step { + return fmt.Errorf("roundState mismatch. Got %v; Expected %v", m2, m) + } + case <-newStepSub.Canceled(): + return fmt.Errorf("failed to read off newStepSub.Out(). newStepSub was canceled") + case <-ticker: + return fmt.Errorf("failed to read off newStepSub.Out()") + } + } + case msgInfo: + peerID := m.PeerID + if peerID == "" { + peerID = "local" + } + switch msg := m.Msg.(type) { + case *ProposalMessage: + p := msg.Proposal + cs.Logger.Info("Replay: Proposal", "height", p.Height, "round", p.Round, "header", + p.BlockID.PartSetHeader, "pol", p.POLRound, "peer", peerID) + case *BlockPartMessage: + cs.Logger.Info("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerID) + case *VoteMessage: + v := msg.Vote + cs.Logger.Info("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type, + "blockID", v.BlockID, "peer", peerID, "extensionLen", len(v.Extension), "extSigLen", len(v.ExtensionSignature)) + } + + cs.handleMsg(m) + case timeoutInfo: + cs.Logger.Info("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration) + cs.handleTimeout(m, cs.RoundState) + default: + return fmt.Errorf("replay: Unknown TimedWALMessage type: %v", reflect.TypeOf(msg.Msg)) + } + return nil +} + +// Replay only those messages since the last block. `timeoutRoutine` should +// run concurrently to read off tickChan. +func (cs *State) catchupReplay(csHeight int64) error { + + // Set replayMode to true so we don't log signing errors. + cs.replayMode = true + defer func() { cs.replayMode = false }() + + // Ensure that #ENDHEIGHT for this height doesn't exist. + // NOTE: This is just a sanity check. As far as we know things work fine + // without it, and Handshake could reuse State if it weren't for + // this check (since we can crash after writing #ENDHEIGHT). + // + // Ignore data corruption errors since this is a sanity check. + gr, found, err := cs.wal.SearchForEndHeight(csHeight, &WALSearchOptions{IgnoreDataCorruptionErrors: true}) + if err != nil { + return err + } + if gr != nil { + if err := gr.Close(); err != nil { + return err + } + } + if found { + return fmt.Errorf("wal should not contain #ENDHEIGHT %d", csHeight) + } + + // Search for last height marker. + // + // Ignore data corruption errors in previous heights because we only care about last height + if csHeight < cs.state.InitialHeight { + return fmt.Errorf("cannot replay height %v, below initial height %v", csHeight, cs.state.InitialHeight) + } + endHeight := csHeight - 1 + if csHeight == cs.state.InitialHeight { + endHeight = 0 + } + gr, found, err = cs.wal.SearchForEndHeight(endHeight, &WALSearchOptions{IgnoreDataCorruptionErrors: true}) + if err == io.EOF { + cs.Logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", endHeight) + } else if err != nil { + return err + } + if !found { + return fmt.Errorf("cannot replay height %d. WAL does not contain #ENDHEIGHT for %d", csHeight, endHeight) + } + defer gr.Close() + + cs.Logger.Info("Catchup by replaying consensus messages", "height", csHeight) + + var msg *TimedWALMessage + dec := WALDecoder{gr} + +LOOP: + for { + msg, err = dec.Decode() + switch { + case err == io.EOF: + break LOOP + case IsDataCorruptionError(err): + cs.Logger.Error("data has been corrupted in last height of consensus WAL", "err", err, "height", csHeight) + return err + case err != nil: + return err + } + + // NOTE: since the priv key is set when the msgs are received + // it will attempt to eg double sign but we can just ignore it + // since the votes will be replayed and we'll get to the next step + if err := cs.readReplayMessage(msg, nil); err != nil { + return err + } + } + cs.Logger.Info("Replay: Done") + return nil +} + +//-------------------------------------------------------------------------------- + +// Parses marker lines of the form: +// #ENDHEIGHT: 12345 +/* +func makeHeightSearchFunc(height int64) auto.SearchFunc { + return func(line string) (int, error) { + line = strings.TrimRight(line, "\n") + parts := strings.Split(line, " ") + if len(parts) != 2 { + return -1, errors.New("line did not have 2 parts") + } + i, err := strconv.Atoi(parts[1]) + if err != nil { + return -1, errors.New("failed to parse INFO: " + err.Error()) + } + if height < i { + return 1, nil + } else if height == i { + return 0, nil + } else { + return -1, nil + } + } +}*/ + +//--------------------------------------------------- +// 2. Recover from failure while applying the block. +// (by handshaking with the app to figure out where +// we were last, and using the WAL to recover there.) +//--------------------------------------------------- + +type Handshaker struct { + stateStore sm.Store + initialState sm.State + store sm.BlockStore + eventBus types.BlockEventPublisher + genDoc *types.GenesisDoc + logger log.Logger + + nBlocks int // number of blocks applied to the state +} + +func NewHandshaker(stateStore sm.Store, state sm.State, + store sm.BlockStore, genDoc *types.GenesisDoc) *Handshaker { + + return &Handshaker{ + stateStore: stateStore, + initialState: state, + store: store, + eventBus: types.NopEventBus{}, + genDoc: genDoc, + logger: log.NewNopLogger(), + nBlocks: 0, + } +} + +func (h *Handshaker) SetLogger(l log.Logger) { + h.logger = l +} + +// SetEventBus - sets the event bus for publishing block related events. +// If not called, it defaults to types.NopEventBus. +func (h *Handshaker) SetEventBus(eventBus types.BlockEventPublisher) { + h.eventBus = eventBus +} + +// NBlocks returns the number of blocks applied to the state. +func (h *Handshaker) NBlocks() int { + return h.nBlocks +} + +// TODO: retry the handshake/replay if it fails ? +func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { + return h.HandshakeWithContext(context.TODO(), proxyApp) +} + +// HandshakeWithContext is cancellable version of Handshake +func (h *Handshaker) HandshakeWithContext(ctx context.Context, proxyApp proxy.AppConns) error { + + // Handshake is done via ABCI Info on the query conn. + res, err := proxyApp.Query().Info(ctx, proxy.RequestInfo) + if err != nil { + return fmt.Errorf("error calling Info: %v", err) + } + + blockHeight := res.LastBlockHeight + if blockHeight < 0 { + return fmt.Errorf("got a negative last block height (%d) from the app", blockHeight) + } + appHash := res.LastBlockAppHash + + h.logger.Info("ABCI Handshake App Info", + "height", blockHeight, + "hash", log.NewLazySprintf("%X", appHash), + "software-version", res.Version, + "protocol-version", res.AppVersion, + ) + + // Only set the version if there is no existing state. + if h.initialState.LastBlockHeight == 0 { + h.initialState.Version.Consensus.App = res.AppVersion + } + + // Replay blocks up to the latest in the blockstore. + appHash, err = h.ReplayBlocksWithContext(ctx, h.initialState, appHash, blockHeight, proxyApp) + if err != nil { + return fmt.Errorf("error on replay: %v", err) + } + + h.logger.Info("Completed ABCI Handshake - CometBFT and App are synced", + "appHeight", blockHeight, "appHash", log.NewLazySprintf("%X", appHash)) + + // TODO: (on restart) replay mempool + + return nil +} + +// ReplayBlocks replays all blocks since appBlockHeight and ensures the result +// matches the current state. +// Returns the final AppHash or an error. +func (h *Handshaker) ReplayBlocks( + state sm.State, + appHash []byte, + appBlockHeight int64, + proxyApp proxy.AppConns, +) ([]byte, error) { + return h.ReplayBlocksWithContext(context.TODO(), state, appHash, appBlockHeight, proxyApp) +} + +// ReplayBlocksWithContext is cancellable version of ReplayBlocks. +func (h *Handshaker) ReplayBlocksWithContext( + ctx context.Context, + state sm.State, + appHash []byte, + appBlockHeight int64, + proxyApp proxy.AppConns, +) ([]byte, error) { + storeBlockBase := h.store.Base() + storeBlockHeight := h.store.Height() + stateBlockHeight := state.LastBlockHeight + h.logger.Info( + "ABCI Replay Blocks", + "appHeight", + appBlockHeight, + "storeHeight", + storeBlockHeight, + "stateHeight", + stateBlockHeight) + + // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain. + if appBlockHeight == 0 { + validators := make([]*types.Validator, len(h.genDoc.Validators)) + for i, val := range h.genDoc.Validators { + validators[i] = types.NewValidator(val.PubKey, val.Power) + } + validatorSet := types.NewValidatorSet(validators) + nextVals := types.TM2PB.ValidatorUpdates(validatorSet) + pbparams := h.genDoc.ConsensusParams.ToProto() + req := &abci.RequestInitChain{ + Time: h.genDoc.GenesisTime, + ChainId: h.genDoc.ChainID, + InitialHeight: h.genDoc.InitialHeight, + ConsensusParams: &pbparams, + Validators: nextVals, + AppStateBytes: h.genDoc.AppState, + } + res, err := proxyApp.Consensus().InitChain(context.TODO(), req) + if err != nil { + return nil, err + } + + appHash = res.AppHash + + if stateBlockHeight == 0 { // we only update state when we are in initial state + // If the app did not return an app hash, we keep the one set from the genesis doc in + // the state. We don't set appHash since we don't want the genesis doc app hash + // recorded in the genesis block. We should probably just remove GenesisDoc.AppHash. + if len(res.AppHash) > 0 { + state.AppHash = res.AppHash + } + // If the app returned validators or consensus params, update the state. + if len(res.Validators) > 0 { + vals, err := types.PB2TM.ValidatorUpdates(res.Validators) + if err != nil { + return nil, err + } + state.Validators = types.NewValidatorSet(vals) + state.NextValidators = types.NewValidatorSet(vals).CopyIncrementProposerPriority(1) + } else if len(h.genDoc.Validators) == 0 { + // If validator set is not set in genesis and still empty after InitChain, exit. + return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain") + } + + if res.ConsensusParams != nil { + state.ConsensusParams = state.ConsensusParams.Update(res.ConsensusParams) + state.Version.Consensus.App = state.ConsensusParams.Version.App + } + // We update the last results hash with the empty hash, to conform with RFC-6962. + state.LastResultsHash = merkle.HashFromByteSlices(nil) + if err := h.stateStore.Save(state); err != nil { + return nil, err + } + } + } + + // First handle edge cases and constraints on the storeBlockHeight and storeBlockBase. + switch { + case storeBlockHeight == 0: + assertAppHashEqualsOneFromState(appHash, state) + return appHash, nil + + case appBlockHeight == 0 && state.InitialHeight < storeBlockBase: + // the app has no state, and the block store is truncated above the initial height + return appHash, sm.ErrAppBlockHeightTooLow{AppHeight: appBlockHeight, StoreBase: storeBlockBase} + + case appBlockHeight > 0 && appBlockHeight < storeBlockBase-1: + // the app is too far behind truncated store (can be 1 behind since we replay the next) + return appHash, sm.ErrAppBlockHeightTooLow{AppHeight: appBlockHeight, StoreBase: storeBlockBase} + + case storeBlockHeight < appBlockHeight: + // the app should never be ahead of the store (but this is under app's control) + return appHash, sm.ErrAppBlockHeightTooHigh{CoreHeight: storeBlockHeight, AppHeight: appBlockHeight} + + case storeBlockHeight < stateBlockHeight: + // the state should never be ahead of the store (this is under CometBFT's control) + panic(fmt.Sprintf("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) + + case storeBlockHeight > stateBlockHeight+1: + // store should be at most one ahead of the state (this is under CometBFT's control) + panic(fmt.Sprintf("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) + } + + var err error + // Now either store is equal to state, or one ahead. + // For each, consider all cases of where the app could be, given app <= store + switch storeBlockHeight { + case stateBlockHeight: + // CometBFT ran Commit and saved the state. + // Either the app is asking for replay, or we're all synced up. + if appBlockHeight < storeBlockHeight { + // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store) + return h.replayBlocks(ctx, state, proxyApp, appBlockHeight, storeBlockHeight, false) + + } else if appBlockHeight == storeBlockHeight { + // We're good! + assertAppHashEqualsOneFromState(appHash, state) + return appHash, nil + } + + case stateBlockHeight + 1: + // We saved the block in the store but haven't updated the state, + // so we'll need to replay a block using the WAL. + switch { + case appBlockHeight < stateBlockHeight: + // the app is further behind than it should be, so replay blocks + // but leave the last block to go through the WAL + return h.replayBlocks(ctx, state, proxyApp, appBlockHeight, storeBlockHeight, true) + + case appBlockHeight == stateBlockHeight: + // We haven't run Commit (both the state and app are one block behind), + // so replayBlock with the real app. + // NOTE: We could instead use the cs.WAL on cs.Start, + // but we'd have to allow the WAL to replay a block that wrote it's #ENDHEIGHT + h.logger.Info("Replay last block using real app") + state, err = h.replayBlock(state, storeBlockHeight, proxyApp.Consensus()) + return state.AppHash, err + + case appBlockHeight == storeBlockHeight: + // We ran Commit, but didn't save the state, so replayBlock with mock app. + finalizeBlockResponse, err := h.stateStore.LoadLastFinalizeBlockResponse(storeBlockHeight) + if err != nil { + return nil, err + } + // NOTE: There is a rare edge case where a node has upgraded from + // v0.37 with endblock to v0.38 with finalize block and thus + // does not have the app hash saved from the previous height + // here we take the appHash provided from the Info handshake + if len(finalizeBlockResponse.AppHash) == 0 { + finalizeBlockResponse.AppHash = appHash + } + mockApp := newMockProxyApp(finalizeBlockResponse) + h.logger.Info("Replay last block using mock app") + state, err = h.replayBlock(state, storeBlockHeight, mockApp) + return state.AppHash, err + } + + } + + panic(fmt.Sprintf("uncovered case! appHeight: %d, storeHeight: %d, stateHeight: %d", + appBlockHeight, storeBlockHeight, stateBlockHeight)) +} + +func (h *Handshaker) replayBlocks( + ctx context.Context, + state sm.State, + proxyApp proxy.AppConns, + appBlockHeight, + storeBlockHeight int64, + mutateState bool) ([]byte, error) { + // App is further behind than it should be, so we need to replay blocks. + // We replay all blocks from appBlockHeight+1. + // + // Note that we don't have an old version of the state, + // so we by-pass state validation/mutation using sm.ExecCommitBlock. + // This also means we won't be saving validator sets if they change during this period. + // TODO: Load the historical information to fix this and just use state.ApplyBlock + // + // If mutateState == true, the final block is replayed with h.replayBlock() + + var appHash []byte + var err error + finalBlock := storeBlockHeight + if mutateState { + finalBlock-- + } + firstBlock := appBlockHeight + 1 + if firstBlock == 1 { + firstBlock = state.InitialHeight + } + for i := firstBlock; i <= finalBlock; i++ { + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + } + + h.logger.Info("Applying block", "height", i) + block := h.store.LoadBlock(i) + // Extra check to ensure the app was not changed in a way it shouldn't have. + if len(appHash) > 0 { + assertAppHashEqualsOneFromBlock(appHash, block) + } + + appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, h.logger, h.stateStore, h.genDoc.InitialHeight) + if err != nil { + return nil, err + } + + h.nBlocks++ + } + + if mutateState { + // sync the final block + state, err = h.replayBlock(state, storeBlockHeight, proxyApp.Consensus()) + if err != nil { + return nil, err + } + appHash = state.AppHash + } + + assertAppHashEqualsOneFromState(appHash, state) + return appHash, nil +} + +// ApplyBlock on the proxyApp with the last block. +func (h *Handshaker) replayBlock(state sm.State, height int64, proxyApp proxy.AppConnConsensus) (sm.State, error) { + block := h.store.LoadBlock(height) + meta := h.store.LoadBlockMeta(height) + + // Use stubs for both mempool and evidence pool since no transactions nor + // evidence are needed here - block already exists. + blockExec := sm.NewBlockExecutor(h.stateStore, h.logger, proxyApp, emptyMempool{}, sm.EmptyEvidencePool{}, h.store) + blockExec.SetEventBus(h.eventBus) + + var err error + state, err = blockExec.ApplyBlock(state, meta.BlockID, block) + if err != nil { + return sm.State{}, err + } + + h.nBlocks++ + + return state, nil +} + +func assertAppHashEqualsOneFromBlock(appHash []byte, block *types.Block) { + if !bytes.Equal(appHash, block.AppHash) { + panic(fmt.Sprintf(`block.AppHash does not match AppHash after replay. Got %X, expected %X. + +Block: %v +`, + appHash, block.AppHash, block)) + } +} + +func assertAppHashEqualsOneFromState(appHash []byte, state sm.State) { + if !bytes.Equal(appHash, state.AppHash) { + panic(fmt.Sprintf(`state.AppHash does not match AppHash after replay. Got +%X, expected %X. + +State: %v + +Did you reset CometBFT without resetting your application's data?`, + appHash, state.AppHash, state)) + } +} diff --git a/consensus/replay_file.go b/consensus/replay_file.go new file mode 100644 index 0000000..5a4b2ba --- /dev/null +++ b/consensus/replay_file.go @@ -0,0 +1,339 @@ +package consensus + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + + dbm "github.com/cometbft/cometbft-db" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +const ( + // event bus subscriber + subscriber = "replay-file" +) + +//-------------------------------------------------------- +// replay messages interactively or all at once + +// replay the wal file +func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) { + consensusState := newConsensusStateForReplay(config, csConfig) + + if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil { + cmtos.Exit(fmt.Sprintf("Error during consensus replay: %v", err)) + } +} + +// Replay msgs in file or start the console +func (cs *State) ReplayFile(file string, console bool) error { + if cs.IsRunning() { + return errors.New("cs is already running, cannot replay") + } + if cs.wal != nil { + return errors.New("cs wal is open, cannot replay") + } + + cs.startForReplay() + + // ensure all new step events are regenerated as expected + + ctx := context.Background() + newStepSub, err := cs.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep) + if err != nil { + return fmt.Errorf("failed to subscribe %s to %v", subscriber, types.EventQueryNewRoundStep) + } + defer func() { + if err := cs.eventBus.Unsubscribe(ctx, subscriber, types.EventQueryNewRoundStep); err != nil { + cs.Logger.Error("Error unsubscribing to event bus", "err", err) + } + }() + + // just open the file for reading, no need to use wal + fp, err := os.OpenFile(file, os.O_RDONLY, 0o600) + if err != nil { + return err + } + + pb := newPlayback(file, fp, cs, cs.state.Copy()) + defer pb.fp.Close() + + var nextN int // apply N msgs in a row + var msg *TimedWALMessage + for { + if nextN == 0 && console { + nextN = pb.replayConsoleLoop() + } + + msg, err = pb.dec.Decode() + if err == io.EOF { + return nil + } else if err != nil { + return err + } + + if err := pb.cs.readReplayMessage(msg, newStepSub); err != nil { + return err + } + + if nextN > 0 { + nextN-- + } + pb.count++ + } +} + +//------------------------------------------------ +// playback manager + +type playback struct { + cs *State + + fp *os.File + dec *WALDecoder + count int // how many lines/msgs into the file are we + + // replays can be reset to beginning + fileName string // so we can close/reopen the file + genesisState sm.State // so the replay session knows where to restart from +} + +func newPlayback(fileName string, fp *os.File, cs *State, genState sm.State) *playback { + return &playback{ + cs: cs, + fp: fp, + fileName: fileName, + genesisState: genState, + dec: NewWALDecoder(fp), + } +} + +// go back count steps by resetting the state and running (pb.count - count) steps +func (pb *playback) replayReset(count int, newStepSub types.Subscription) error { + if err := pb.cs.Stop(); err != nil { + return err + } + pb.cs.Wait() + + newCS := NewState(pb.cs.config, pb.genesisState.Copy(), pb.cs.blockExec, + pb.cs.blockStore, pb.cs.txNotifier, pb.cs.evpool) + newCS.SetEventBus(pb.cs.eventBus) + newCS.startForReplay() + + if err := pb.fp.Close(); err != nil { + return err + } + fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0o600) + if err != nil { + return err + } + pb.fp = fp + pb.dec = NewWALDecoder(fp) + count = pb.count - count + fmt.Printf("Reseting from %d to %d\n", pb.count, count) + pb.count = 0 + pb.cs = newCS + var msg *TimedWALMessage + for i := 0; i < count; i++ { + msg, err = pb.dec.Decode() + if err == io.EOF { + return nil + } else if err != nil { + return err + } + if err := pb.cs.readReplayMessage(msg, newStepSub); err != nil { + return err + } + pb.count++ + } + return nil +} + +func (cs *State) startForReplay() { + cs.Logger.Error("Replay commands are disabled until someone updates them and writes tests") + /* TODO:! + // since we replay tocks we just ignore ticks + go func() { + for { + select { + case <-cs.tickChan: + case <-cs.Quit: + return + } + } + }()*/ +} + +// console function for parsing input and running commands +func (pb *playback) replayConsoleLoop() int { + for { + fmt.Printf("> ") + bufReader := bufio.NewReader(os.Stdin) + line, more, err := bufReader.ReadLine() + if more { + cmtos.Exit("input is too long") + } else if err != nil { + cmtos.Exit(err.Error()) + } + + tokens := strings.Split(string(line), " ") + if len(tokens) == 0 { + continue + } + + switch tokens[0] { + case "next": + // "next" -> replay next message + // "next N" -> replay next N messages + + if len(tokens) == 1 { + return 0 + } + i, err := strconv.Atoi(tokens[1]) + if err != nil { + fmt.Println("next takes an integer argument") + } else { + return i + } + + case "back": + // "back" -> go back one message + // "back N" -> go back N messages + + // NOTE: "back" is not supported in the state machine design, + // so we restart and replay up to + + ctx := context.Background() + // ensure all new step events are regenerated as expected + + newStepSub, err := pb.cs.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep) + if err != nil { + cmtos.Exit(fmt.Sprintf("failed to subscribe %s to %v", subscriber, types.EventQueryNewRoundStep)) + } + defer func() { + if err := pb.cs.eventBus.Unsubscribe(ctx, subscriber, types.EventQueryNewRoundStep); err != nil { + pb.cs.Logger.Error("Error unsubscribing from eventBus", "err", err) + } + }() + + if len(tokens) == 1 { + if err := pb.replayReset(1, newStepSub); err != nil { + pb.cs.Logger.Error("Replay reset error", "err", err) + } + } else { + i, err := strconv.Atoi(tokens[1]) + if err != nil { + fmt.Println("back takes an integer argument") + } else if i > pb.count { + fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count) + } else if err := pb.replayReset(i, newStepSub); err != nil { + pb.cs.Logger.Error("Replay reset error", "err", err) + } + } + + case "rs": + // "rs" -> print entire round state + // "rs short" -> print height/round/step + // "rs " -> print another field of the round state + + rs := pb.cs.RoundState + if len(tokens) == 1 { + fmt.Println(rs) + } else { + switch tokens[1] { + case "short": + fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step) + case "validators": + fmt.Println(rs.Validators) + case "proposal": + fmt.Println(rs.Proposal) + case "proposal_block": + fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort()) + case "locked_round": + fmt.Println(rs.LockedRound) + case "locked_block": + fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort()) + case "votes": + fmt.Println(rs.Votes.StringIndented(" ")) + + default: + fmt.Println("Unknown option", tokens[1]) + } + } + case "n": + fmt.Println(pb.count) + } + } +} + +//-------------------------------------------------------------------------------- + +// convenience for replay mode +func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *State { + dbType := dbm.BackendType(config.DBBackend) + // Get BlockStore + blockStoreDB, err := dbm.NewDB("blockstore", dbType, config.DBDir()) + if err != nil { + cmtos.Exit(err.Error()) + } + blockStore := store.NewBlockStore(blockStoreDB) + + // Get State + stateDB, err := dbm.NewDB("state", dbType, config.DBDir()) + if err != nil { + cmtos.Exit(err.Error()) + } + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + gdoc, err := sm.MakeGenesisDocFromFile(config.GenesisFile()) + if err != nil { + cmtos.Exit(err.Error()) + } + state, err := sm.MakeGenesisState(gdoc) + if err != nil { + cmtos.Exit(err.Error()) + } + + // Create proxyAppConn connection (consensus, mempool, query) + clientCreator := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()) + proxyApp := proxy.NewAppConns(clientCreator, proxy.NopMetrics()) + err = proxyApp.Start() + if err != nil { + cmtos.Exit(fmt.Sprintf("Error starting proxy app conns: %v", err)) + } + + eventBus := types.NewEventBus() + if err := eventBus.Start(); err != nil { + cmtos.Exit(fmt.Sprintf("Failed to start event bus: %v", err)) + } + + handshaker := NewHandshaker(stateStore, state, blockStore, gdoc) + handshaker.SetEventBus(eventBus) + err = handshaker.Handshake(proxyApp) + if err != nil { + cmtos.Exit(fmt.Sprintf("Error on handshake: %v", err)) + } + + mempool, evpool := emptyMempool{}, sm.EmptyEvidencePool{} + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool, blockStore) + + consensusState := NewState(csConfig, state.Copy(), blockExec, + blockStore, mempool, evpool) + + consensusState.SetEventBus(eventBus) + return consensusState +} diff --git a/consensus/replay_stubs.go b/consensus/replay_stubs.go new file mode 100644 index 0000000..e96866d --- /dev/null +++ b/consensus/replay_stubs.go @@ -0,0 +1,79 @@ +package consensus + +import ( + "context" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/clist" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------------------------------- + +type emptyMempool struct{} + +var _ mempl.Mempool = emptyMempool{} + +func (emptyMempool) Lock() {} +func (emptyMempool) Unlock() {} +func (emptyMempool) Size() int { return 0 } +func (emptyMempool) SizeBytes() int64 { return 0 } +func (emptyMempool) CheckTx(types.Tx, func(*abci.ResponseCheckTx), mempl.TxInfo) error { + return nil +} + +func (txmp emptyMempool) RemoveTxByKey(types.TxKey) error { + return nil +} + +func (emptyMempool) ReapMaxBytesMaxGas(int64, int64) types.Txs { return types.Txs{} } +func (emptyMempool) ReapMaxTxs(int) types.Txs { return types.Txs{} } +func (emptyMempool) Update( + int64, + types.Txs, + []*abci.ExecTxResult, + mempl.PreCheckFunc, + mempl.PostCheckFunc, +) error { + return nil +} +func (emptyMempool) Flush() {} +func (emptyMempool) FlushAppConn() error { return nil } +func (emptyMempool) TxsAvailable() <-chan struct{} { return make(chan struct{}) } +func (emptyMempool) EnableTxsAvailable() {} +func (emptyMempool) TxsBytes() int64 { return 0 } + +func (emptyMempool) TxsFront() *clist.CElement { return nil } +func (emptyMempool) TxsWaitChan() <-chan struct{} { return nil } + +func (emptyMempool) InitWAL() error { return nil } +func (emptyMempool) CloseWAL() {} + +//----------------------------------------------------------------------------- +// mockProxyApp uses ABCIResponses to give the right results. +// +// Useful because we don't want to call Commit() twice for the same block on +// the real app. + +func newMockProxyApp(finalizeBlockResponse *abci.ResponseFinalizeBlock) proxy.AppConnConsensus { + clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{ + finalizeBlockResponse: finalizeBlockResponse, + }) + cli, _ := clientCreator.NewABCIClient() + err := cli.Start() + if err != nil { + panic(err) + } + return proxy.NewAppConnConsensus(cli, proxy.NopMetrics()) +} + +type mockProxyApp struct { + abci.BaseApplication + finalizeBlockResponse *abci.ResponseFinalizeBlock +} + +func (mock *mockProxyApp) FinalizeBlock(context.Context, *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { + return mock.finalizeBlockResponse, nil +} diff --git a/consensus/replay_test.go b/consensus/replay_test.go new file mode 100644 index 0000000..a73b01d --- /dev/null +++ b/consensus/replay_test.go @@ -0,0 +1,1285 @@ +package consensus + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sort" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/abci/types/mocks" + cfg "github.com/cometbft/cometbft/config" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + smmocks "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/types" +) + +func TestMain(m *testing.M) { + config = ResetConfig("consensus_reactor_test") + consensusReplayConfig = ResetConfig("consensus_replay_test") + configStateTest := ResetConfig("consensus_state_test") + configMempoolTest := ResetConfig("consensus_mempool_test") + configByzantineTest := ResetConfig("consensus_byzantine_test") + code := m.Run() + os.RemoveAll(config.RootDir) + os.RemoveAll(consensusReplayConfig.RootDir) + os.RemoveAll(configStateTest.RootDir) + os.RemoveAll(configMempoolTest.RootDir) + os.RemoveAll(configByzantineTest.RootDir) + os.Exit(code) +} + +// These tests ensure we can always recover from failure at any part of the consensus process. +// There are two general failure scenarios: failure during consensus, and failure while applying the block. +// Only the latter interacts with the app and store, +// but the former has to deal with restrictions on re-use of priv_validator keys. +// The `WAL Tests` are for failures during the consensus; +// the `Handshake Tests` are for failures in applying the block. +// With the help of the WAL, we can recover from it all! + +//------------------------------------------------------------------------------------------ +// WAL Tests + +// TODO: It would be better to verify explicitly which states we can recover from without the wal +// and which ones we need the wal for - then we'd also be able to only flush the +// wal writer when we need to, instead of with every message. + +func startNewStateAndWaitForBlock( + t *testing.T, + consensusReplayConfig *cfg.Config, + blockDB dbm.DB, + stateStore sm.Store, +) { + logger := log.TestingLogger() + state, _ := stateStore.LoadFromDBOrGenesisFile(consensusReplayConfig.GenesisFile()) + privValidator := loadPrivValidator(consensusReplayConfig) + cs := newStateWithConfigAndBlockStore( + consensusReplayConfig, + state, + privValidator, + kvstore.NewInMemoryApplication(), + blockDB, + ) + cs.SetLogger(logger) + + bytes, _ := os.ReadFile(cs.config.WalFile()) + t.Logf("====== WAL: \n\r%X\n", bytes) + + err := cs.Start() + require.NoError(t, err) + defer func() { + if err := cs.Stop(); err != nil { + t.Error(err) + } + }() + + // This is just a signal that we haven't halted; its not something contained + // in the WAL itself. Assuming the consensus state is running, replay of any + // WAL, including the empty one, should eventually be followed by a new + // block, or else something is wrong. + newBlockSub, err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock) + require.NoError(t, err) + select { + case <-newBlockSub.Out(): + case <-newBlockSub.Canceled(): + t.Fatal("newBlockSub was canceled") + case <-time.After(120 * time.Second): + t.Fatal("Timed out waiting for new block (see trace above)") + } +} + +func sendTxs(ctx context.Context, cs *State) { + for i := 0; i < 256; i++ { + select { + case <-ctx.Done(): + return + default: + tx := kvstore.NewTxFromID(i) + if err := assertMempool(cs.txNotifier).CheckTx(tx, func(resp *abci.ResponseCheckTx) { + if resp.Code != 0 { + panic(fmt.Sprintf("Unexpected code: %d, log: %s", resp.Code, resp.Log)) + } + }, mempool.TxInfo{}); err != nil { + panic(err) + } + i++ + } + } +} + +// TestWALCrash uses crashing WAL to test we can recover from any WAL failure. +func TestWALCrash(t *testing.T) { + testCases := []struct { + name string + initFn func(dbm.DB, *State, context.Context) + heightToStop int64 + }{ + { + "empty block", + func(stateDB dbm.DB, cs *State, ctx context.Context) {}, + 1, + }, + { + "many non-empty blocks", + func(stateDB dbm.DB, cs *State, ctx context.Context) { + go sendTxs(ctx, cs) + }, + 3, + }, + } + + for i, tc := range testCases { + tc := tc + consensusReplayConfig := ResetConfig(fmt.Sprintf("%s_%d", t.Name(), i)) + t.Run(tc.name, func(t *testing.T) { + crashWALandCheckLiveness(t, consensusReplayConfig, tc.initFn, tc.heightToStop) + }) + } +} + +func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *cfg.Config, + initFn func(dbm.DB, *State, context.Context), heightToStop int64, +) { + walPanicked := make(chan error) + crashingWal := &crashingWAL{panicCh: walPanicked, heightToStop: heightToStop} + + i := 1 +LOOP: + for { + t.Logf("====== LOOP %d\n", i) + + // create consensus state from a clean slate + logger := log.NewNopLogger() + blockDB := dbm.NewMemDB() + stateDB := blockDB + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile()) + require.NoError(t, err) + privValidator := loadPrivValidator(consensusReplayConfig) + cs := newStateWithConfigAndBlockStore( + consensusReplayConfig, + state, + privValidator, + kvstore.NewInMemoryApplication(), + blockDB, + ) + cs.SetLogger(logger) + + // start sending transactions + ctx, cancel := context.WithCancel(context.Background()) + initFn(stateDB, cs, ctx) + + // clean up WAL file from the previous iteration + walFile := cs.config.WalFile() + os.Remove(walFile) + + // set crashing WAL + csWal, err := cs.OpenWAL(walFile) + require.NoError(t, err) + crashingWal.next = csWal + + // reset the message counter + crashingWal.msgIndex = 1 + cs.wal = crashingWal + + // start consensus state + err = cs.Start() + require.NoError(t, err) + + i++ + + select { + case err := <-walPanicked: + t.Logf("WAL panicked: %v", err) + + // make sure we can make blocks after a crash + startNewStateAndWaitForBlock(t, consensusReplayConfig, blockDB, stateStore) + + // stop consensus state and transactions sender (initFn) + cs.Stop() //nolint:errcheck // Logging this error causes failure + cancel() + + // if we reached the required height, exit + if _, ok := err.(ReachedHeightToStopError); ok { + break LOOP + } + case <-time.After(10 * time.Second): + t.Fatal("WAL did not panic for 10 seconds (check the log)") + } + } +} + +// crashingWAL is a WAL which crashes or rather simulates a crash during Save +// (before and after). It remembers a message for which we last panicked +// (lastPanickedForMsgIndex), so we don't panic for it in subsequent iterations. +type crashingWAL struct { + next WAL + panicCh chan error + heightToStop int64 + + msgIndex int // current message index + lastPanickedForMsgIndex int // last message for which we panicked +} + +var _ WAL = &crashingWAL{} + +// WALWriteError indicates a WAL crash. +type WALWriteError struct { + msg string +} + +func (e WALWriteError) Error() string { + return e.msg +} + +// ReachedHeightToStopError indicates we've reached the required consensus +// height and may exit. +type ReachedHeightToStopError struct { + height int64 +} + +func (e ReachedHeightToStopError) Error() string { + return fmt.Sprintf("reached height to stop %d", e.height) +} + +// Write simulate WAL's crashing by sending an error to the panicCh and then +// exiting the cs.receiveRoutine. +func (w *crashingWAL) Write(m WALMessage) error { + if endMsg, ok := m.(EndHeightMessage); ok { + if endMsg.Height == w.heightToStop { + w.panicCh <- ReachedHeightToStopError{endMsg.Height} + runtime.Goexit() + return nil + } + + return w.next.Write(m) + } + + if w.msgIndex > w.lastPanickedForMsgIndex { + w.lastPanickedForMsgIndex = w.msgIndex + _, file, line, _ := runtime.Caller(1) + w.panicCh <- WALWriteError{fmt.Sprintf("failed to write %T to WAL (fileline: %s:%d)", m, file, line)} + runtime.Goexit() + return nil + } + + w.msgIndex++ + return w.next.Write(m) +} + +func (w *crashingWAL) WriteSync(m WALMessage) error { + return w.Write(m) +} + +func (w *crashingWAL) FlushAndSync() error { return w.next.FlushAndSync() } + +func (w *crashingWAL) SearchForEndHeight( + height int64, + options *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { + return w.next.SearchForEndHeight(height, options) +} + +func (w *crashingWAL) Start() error { return w.next.Start() } +func (w *crashingWAL) Stop() error { return w.next.Stop() } +func (w *crashingWAL) Wait() { w.next.Wait() } + +// ------------------------------------------------------------------------------------------ + +const numBlocks = 6 + +//--------------------------------------- +// Test handshake/replay + +// 0 - all synced up +// 1 - saved block but app and state are behind by one height +// 2 - save block and committed (i.e. app got `Commit`) but state is behind +// 3 - same as 2 but with a truncated block store +var modes = []uint{0, 1, 2, 3} + +// This is actually not a test, it's for storing validator change tx data for testHandshakeReplay +func setupChainWithChangingValidators(t *testing.T, name string, nBlocks int) (*cfg.Config, []*types.Block, []*types.ExtendedCommit, sm.State) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + nPeers := 7 + nVals := 4 + css, genDoc, config, cleanup := randConsensusNetWithPeers( + t, + nVals, + nPeers, + name, + newMockTickerFunc(true), + func(_ string) abci.Application { + return newKVStore() + }) + genesisState, err := sm.MakeGenesisState(genDoc) + require.NoError(t, err) + t.Cleanup(cleanup) + + partSize := types.BlockPartSizeBytes + + newRoundCh := subscribe(css[0].eventBus, types.EventQueryNewRound) + proposalCh := subscribe(css[0].eventBus, types.EventQueryCompleteProposal) + + vss := make([]*validatorStub, nPeers) + for i := 0; i < nPeers; i++ { + vss[i] = newValidatorStub(css[i].privValidator, int32(i)) + } + height, round := css[0].Height, css[0].Round + + // start the machine + startTestRound(css[0], height, round) + incrementHeight(vss...) + ensureNewRound(newRoundCh, height, 0) + ensureNewProposal(proposalCh, height, round) + rs := css[0].GetRoundState() + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, vss[1:nVals]...) + ensureNewRound(newRoundCh, height+1, 0) + + // HEIGHT 2 + height++ + incrementHeight(vss...) + newValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() + require.NoError(t, err) + valPubKey1ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey1) + require.NoError(t, err) + newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) + err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil, mempool.TxInfo{}) + assert.NoError(t, err) + propBlock, err := css[0].createProposalBlock(ctx) // changeProposer(t, cs1, vs2) + require.NoError(t, err) + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + + proposal := types.NewProposal(vss[1].Height, round, -1, blockID) + p := proposal.ToProto() + if err := vss[1].SignProposal(test.DefaultTestChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + proposal.Signature = p.Signature + + // set the proposal block + if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height, round) + rs = css[0].GetRoundState() + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, vss[1:nVals]...) + ensureNewRound(newRoundCh, height+1, 0) + + // HEIGHT 3 + height++ + incrementHeight(vss...) + updateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() + require.NoError(t, err) + updatePubKey1ABCI, err := cryptoenc.PubKeyToProto(updateValidatorPubKey1) + require.NoError(t, err) + updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) + err = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil, mempool.TxInfo{}) + assert.NoError(t, err) + propBlock, err = css[0].createProposalBlock(ctx) // changeProposer(t, cs1, vs2) + require.NoError(t, err) + propBlockParts, err = propBlock.MakePartSet(partSize) + require.NoError(t, err) + blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + + proposal = types.NewProposal(vss[2].Height, round, -1, blockID) + p = proposal.ToProto() + if err := vss[2].SignProposal(test.DefaultTestChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + proposal.Signature = p.Signature + + // set the proposal block + if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height, round) + rs = css[0].GetRoundState() + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, vss[1:nVals]...) + ensureNewRound(newRoundCh, height+1, 0) + + // HEIGHT 4 + height++ + incrementHeight(vss...) + newValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey() + require.NoError(t, err) + newVal2ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey2) + require.NoError(t, err) + newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) + err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx2, nil, mempool.TxInfo{}) + require.NoError(t, err) + newValidatorPubKey3, err := css[nVals+2].privValidator.GetPubKey() + require.NoError(t, err) + newVal3ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey3) + require.NoError(t, err) + newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) + err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil, mempool.TxInfo{}) + assert.NoError(t, err) + propBlock, err = css[0].createProposalBlock(ctx) // changeProposer(t, cs1, vs2) + require.NoError(t, err) + propBlockParts, err = propBlock.MakePartSet(partSize) + require.NoError(t, err) + blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + newVss := make([]*validatorStub, nVals+1) + copy(newVss, vss[:nVals+1]) + sort.Sort(ValidatorStubsByPower(newVss)) + + valIndexFn := func(cssIdx int) int { + for i, vs := range newVss { + vsPubKey, err := vs.GetPubKey() + require.NoError(t, err) + + cssPubKey, err := css[cssIdx].privValidator.GetPubKey() + require.NoError(t, err) + + if vsPubKey.Equals(cssPubKey) { + return i + } + } + panic(fmt.Sprintf("validator css[%d] not found in newVss", cssIdx)) + } + + selfIndex := valIndexFn(0) + + proposal = types.NewProposal(vss[3].Height, round, -1, blockID) + p = proposal.ToProto() + if err := vss[3].SignProposal(test.DefaultTestChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + proposal.Signature = p.Signature + + // set the proposal block + if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height, round) + + removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0) + err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx2, nil, mempool.TxInfo{}) + assert.Nil(t, err) + + rs = css[0].GetRoundState() + for i := 0; i < nVals+1; i++ { + if i == selfIndex { + continue + } + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, newVss[i]) + } + + ensureNewRound(newRoundCh, height+1, 0) + + // HEIGHT 5 + height++ + incrementHeight(vss...) + // Reflect the changes to vss[nVals] at height 3 and resort newVss. + newVssIdx := valIndexFn(nVals) + newVss[newVssIdx].VotingPower = 25 + sort.Sort(ValidatorStubsByPower(newVss)) + selfIndex = valIndexFn(0) + ensureNewProposal(proposalCh, height, round) + rs = css[0].GetRoundState() + for i := 0; i < nVals+1; i++ { + if i == selfIndex { + continue + } + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, newVss[i]) + } + ensureNewRound(newRoundCh, height+1, 0) + + // HEIGHT 6 + height++ + incrementHeight(vss...) + removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0) + err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil, mempool.TxInfo{}) + assert.NoError(t, err) + propBlock, err = css[0].createProposalBlock(ctx) // changeProposer(t, cs1, vs2) + require.NoError(t, err) + propBlockParts, err = propBlock.MakePartSet(partSize) + require.NoError(t, err) + blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + newVss = make([]*validatorStub, nVals+3) + copy(newVss, vss[:nVals+3]) + sort.Sort(ValidatorStubsByPower(newVss)) + + selfIndex = valIndexFn(0) + proposal = types.NewProposal(vss[1].Height, round, -1, blockID) + p = proposal.ToProto() + if err := vss[1].SignProposal(test.DefaultTestChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + proposal.Signature = p.Signature + + // set the proposal block + if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height, round) + rs = css[0].GetRoundState() + for i := 0; i < nVals+3; i++ { + if i == selfIndex { + continue + } + signAddVotes(css[0], cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, newVss[i]) + } + ensureNewRound(newRoundCh, height+1, 0) + + chain := []*types.Block{} + extCommits := []*types.ExtendedCommit{} + for i := 1; i <= nBlocks; i++ { + chain = append(chain, css[0].blockStore.LoadBlock(int64(i))) + extCommits = append(extCommits, css[0].blockStore.LoadBlockExtendedCommit(int64(i))) + } + return config, chain, extCommits, genesisState +} + +// Sync from scratch +func TestHandshakeReplayAll(t *testing.T) { + for _, m := range modes { + t.Run(fmt.Sprintf("mode_%d_single", m), func(t *testing.T) { + testHandshakeReplay(t, config, 0, m, false) + }) + t.Run(fmt.Sprintf("mode_%d_multi", m), func(t *testing.T) { + testHandshakeReplay(t, config, 0, m, false) + }) + } +} + +// Sync many, not from scratch +func TestHandshakeReplaySome(t *testing.T) { + for _, m := range modes { + t.Run(fmt.Sprintf("mode_%d_single", m), func(t *testing.T) { + testHandshakeReplay(t, config, 2, m, false) + }) + t.Run(fmt.Sprintf("mode_%d_multi", m), func(t *testing.T) { + testHandshakeReplay(t, config, 2, m, true) + }) + } +} + +// Sync from lagging by one +func TestHandshakeReplayOne(t *testing.T) { + for _, m := range modes { + t.Run(fmt.Sprintf("mode_%d_single", m), func(t *testing.T) { + testHandshakeReplay(t, config, numBlocks-1, m, false) + }) + t.Run(fmt.Sprintf("mode_%d_multi", m), func(t *testing.T) { + testHandshakeReplay(t, config, numBlocks-1, m, true) + }) + } +} + +// Sync from caught up +func TestHandshakeReplayNone(t *testing.T) { + for _, m := range modes { + t.Run(fmt.Sprintf("mode_%d_single", m), func(t *testing.T) { + testHandshakeReplay(t, config, numBlocks, m, false) + }) + t.Run(fmt.Sprintf("mode_%d_multi", m), func(t *testing.T) { + testHandshakeReplay(t, config, numBlocks, m, true) + }) + } +} + +func tempWALWithData(data []byte) string { + walFile, err := os.CreateTemp("", "wal") + if err != nil { + panic(fmt.Sprintf("failed to create temp WAL file: %v", err)) + } + _, err = walFile.Write(data) + if err != nil { + panic(fmt.Sprintf("failed to write to temp WAL file: %v", err)) + } + if err := walFile.Close(); err != nil { + panic(fmt.Sprintf("failed to close temp WAL file: %v", err)) + } + return walFile.Name() +} + +// Make some blocks. Start a fresh app and apply nBlocks blocks. +// Then restart the app and sync it up with the remaining blocks +func testHandshakeReplay(t *testing.T, config *cfg.Config, nBlocks int, mode uint, testValidatorsChange bool) { + var ( + testConfig *cfg.Config + chain []*types.Block + extCommits []*types.ExtendedCommit + store *mockBlockStore + stateDB dbm.DB + genesisState sm.State + mempool = emptyMempool{} + evpool = sm.EmptyEvidencePool{} + ) + + if testValidatorsChange { + testConfig, chain, extCommits, genesisState = setupChainWithChangingValidators(t, fmt.Sprintf("%d_%d_m", nBlocks, mode), numBlocks) + stateDB = dbm.NewMemDB() + store = newMockBlockStore(t, config, genesisState.ConsensusParams) + } else { + testConfig = ResetConfig(fmt.Sprintf("%d_%d_s", nBlocks, mode)) + t.Cleanup(func() { + _ = os.RemoveAll(testConfig.RootDir) + }) + walBody, err := WALWithNBlocks(t, numBlocks, testConfig) + require.NoError(t, err) + walFile := tempWALWithData(walBody) + testConfig.Consensus.SetWalFile(walFile) + + wal, err := NewWAL(walFile) + require.NoError(t, err) + wal.SetLogger(log.TestingLogger()) + err = wal.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := wal.Stop(); err != nil { + t.Error(err) + } + }) + chain, extCommits, err = makeBlockchainFromWAL(wal) + require.NoError(t, err) + stateDB, genesisState, store = stateAndStore(t, testConfig, kvstore.AppVersion) + } + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + t.Cleanup(func() { + _ = stateStore.Close() + }) + store.chain = chain + store.extCommits = extCommits + + state := genesisState.Copy() + // run the chain through state.ApplyBlock to build up the CometBFT state + state, latestAppHash := buildTMStateFromChain(t, testConfig, stateStore, mempool, evpool, state, chain, nBlocks, mode, store) + + // make a new client creator + kvstoreApp := kvstore.NewPersistentApplication( + filepath.Join(testConfig.DBDir(), fmt.Sprintf("replay_test_%d_%d_a", nBlocks, mode))) + t.Cleanup(func() { + _ = kvstoreApp.Close() + }) + + clientCreator2 := proxy.NewLocalClientCreator(kvstoreApp) + if nBlocks > 0 { + // run nBlocks against a new client to build up the app state. + // use a throwaway CometBFT state + proxyApp := proxy.NewAppConns(clientCreator2, proxy.NopMetrics()) + stateDB1 := dbm.NewMemDB() + dummyStateStore := sm.NewStore(stateDB1, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + err := dummyStateStore.Save(genesisState) + require.NoError(t, err) + buildAppStateFromChain(t, proxyApp, dummyStateStore, mempool, evpool, genesisState, chain, nBlocks, mode, store) + } + + // Prune block store if requested + expectError := false + if mode == 3 { + pruned, _, err := store.PruneBlocks(2, state) + require.NoError(t, err) + require.EqualValues(t, 1, pruned) + expectError = int64(nBlocks) < 2 + } + + // now start the app using the handshake - it should sync + genDoc, err := sm.MakeGenesisDocFromFile(testConfig.GenesisFile()) + require.NoError(t, err) + handshaker := NewHandshaker(stateStore, state, store, genDoc) + proxyApp := proxy.NewAppConns(clientCreator2, proxy.NopMetrics()) + if err := proxyApp.Start(); err != nil { + t.Fatalf("Error starting proxy app connections: %v", err) + } + + t.Cleanup(func() { + if err := proxyApp.Stop(); err != nil { + t.Error(err) + } + }) + + // perform the replay protocol to sync Tendermint and the application + err = handshaker.Handshake(proxyApp) + if expectError { + require.Error(t, err) + // finish the test early + return + } + require.NoError(t, err) + + // get the latest app hash from the app + res, err := proxyApp.Query().Info(context.Background(), proxy.RequestInfo) + require.NoError(t, err) + + // block store and app height should be in sync + require.Equal(t, store.Height(), res.LastBlockHeight) + + // tendermint state height and app height should be in sync + state, err = stateStore.Load() + require.NoError(t, err) + require.Equal(t, state.LastBlockHeight, res.LastBlockHeight) + require.Equal(t, int64(numBlocks), res.LastBlockHeight) + + // the app hash should be synced up + if !bytes.Equal(latestAppHash, res.LastBlockAppHash) { + t.Fatalf( + "Expected app hashes to match after handshake/replay. got %X, expected %X", + res.LastBlockAppHash, + latestAppHash) + } + + expectedBlocksToSync := numBlocks - nBlocks + if nBlocks == numBlocks && mode > 0 { + expectedBlocksToSync++ + } else if nBlocks > 0 && mode == 1 { + expectedBlocksToSync++ + } + + if handshaker.NBlocks() != expectedBlocksToSync { + t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks()) + } +} + +func applyBlock(t *testing.T, stateStore sm.Store, mempool mempool.Mempool, evpool sm.EvidencePool, st sm.State, blk *types.Block, proxyApp proxy.AppConns, bs sm.BlockStore) sm.State { + testPartSize := types.BlockPartSizeBytes + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool, bs) + + bps, err := blk.MakePartSet(testPartSize) + require.NoError(t, err) + blkID := types.BlockID{Hash: blk.Hash(), PartSetHeader: bps.Header()} + newState, err := blockExec.ApplyBlock(st, blkID, blk) + require.NoError(t, err) + return newState +} + +func buildAppStateFromChain(t *testing.T, proxyApp proxy.AppConns, stateStore sm.Store, mempool mempool.Mempool, evpool sm.EvidencePool, + state sm.State, chain []*types.Block, nBlocks int, mode uint, bs sm.BlockStore, +) { + // start a new app without handshake, play nBlocks blocks + if err := proxyApp.Start(); err != nil { + panic(err) + } + defer proxyApp.Stop() //nolint:errcheck // ignore + + state.Version.Consensus.App = kvstore.AppVersion // simulate handshake, receive app version + validators := types.TM2PB.ValidatorUpdates(state.Validators) + if _, err := proxyApp.Consensus().InitChain(context.Background(), &abci.RequestInitChain{ + Validators: validators, + }); err != nil { + panic(err) + } + if err := stateStore.Save(state); err != nil { // save height 1's validatorsInfo + panic(err) + } + switch mode { + case 0: + for i := 0; i < nBlocks; i++ { + block := chain[i] + state = applyBlock(t, stateStore, mempool, evpool, state, block, proxyApp, bs) + } + case 1, 2, 3: + for i := 0; i < nBlocks-1; i++ { + block := chain[i] + state = applyBlock(t, stateStore, mempool, evpool, state, block, proxyApp, bs) + } + + // mode 1 only the block at the last height is saved + // mode 2 and 3, the block is saved, commit is called, but the state is not saved + if mode == 2 || mode == 3 { + // update the kvstore height and apphash + // as if we ran commit but not + // here we expect a dummy state store to be used + state = applyBlock(t, stateStore, mempool, evpool, state, chain[nBlocks-1], proxyApp, bs) + } + default: + panic(fmt.Sprintf("unknown mode %v", mode)) + } +} + +func buildTMStateFromChain( + t *testing.T, + config *cfg.Config, + stateStore sm.Store, + mempool mempool.Mempool, + evpool sm.EvidencePool, + state sm.State, + chain []*types.Block, + nBlocks int, + mode uint, + bs sm.BlockStore, +) (sm.State, []byte) { + // run the whole chain against this client to build up the CometBFT state + clientCreator := proxy.NewLocalClientCreator( + kvstore.NewPersistentApplication( + filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_t", nBlocks, mode)))) + proxyApp := proxy.NewAppConns(clientCreator, proxy.NopMetrics()) + if err := proxyApp.Start(); err != nil { + panic(err) + } + defer proxyApp.Stop() //nolint:errcheck + + state.Version.Consensus.App = kvstore.AppVersion // simulate handshake, receive app version + validators := types.TM2PB.ValidatorUpdates(state.Validators) + if _, err := proxyApp.Consensus().InitChain(context.Background(), &abci.RequestInitChain{ + Validators: validators, + }); err != nil { + panic(err) + } + if err := stateStore.Save(state); err != nil { // save height 1's validatorsInfo + panic(err) + } + switch mode { + case 0: + // sync right up + for _, block := range chain { + state = applyBlock(t, stateStore, mempool, evpool, state, block, proxyApp, bs) + } + return state, state.AppHash + + case 1, 2, 3: + // sync up to the penultimate as if we stored the block. + // whether we commit or not depends on the appHash + for _, block := range chain[:len(chain)-1] { + state = applyBlock(t, stateStore, mempool, evpool, state, block, proxyApp, bs) + } + + dummyStateStore := &smmocks.Store{} + lastHeight := int64(len(chain)) + penultimateHeight := int64(len(chain) - 1) + vals, _ := stateStore.LoadValidators(penultimateHeight) + dummyStateStore.On("LoadValidators", penultimateHeight).Return(vals, nil) + dummyStateStore.On("Save", mock.Anything).Return(nil) + dummyStateStore.On("SaveFinalizeBlockResponse", lastHeight, mock.MatchedBy(func(response *abci.ResponseFinalizeBlock) bool { + require.NoError(t, stateStore.SaveFinalizeBlockResponse(lastHeight, response)) + return true + })).Return(nil) + + // apply the final block to a state copy so we can + // get the right next appHash but keep the state back + s := applyBlock(t, dummyStateStore, mempool, evpool, state, chain[len(chain)-1], proxyApp, bs) + return state, s.AppHash + default: + panic(fmt.Sprintf("unknown mode %v", mode)) + } +} + +func makeBlocks(n int, state sm.State, privVals []types.PrivValidator) ([]*types.Block, error) { + blockID := test.MakeBlockID() + blocks := make([]*types.Block, n) + + for i := 0; i < n; i++ { + height := state.LastBlockHeight + 1 + int64(i) + lastCommit, err := test.MakeCommit(blockID, height-1, 0, state.LastValidators, privVals, state.ChainID, state.LastBlockTime) + if err != nil { + return nil, err + } + block, err := state.MakeBlock(height, test.MakeNTxs(height, 10), lastCommit, nil, state.LastValidators.Proposer.Address) + if err != nil { + return nil, err + } + blocks[i] = block + state.LastBlockID = blockID + state.LastBlockHeight = height + state.LastBlockTime = state.LastBlockTime.Add(1 * time.Second) + state.LastValidators = state.Validators.Copy() + state.Validators = state.NextValidators.Copy() + state.NextValidators = state.NextValidators.CopyIncrementProposerPriority(1) + state.AppHash = test.RandomHash() + + blockID = test.MakeBlockIDWithHash(block.Hash()) + } + + return blocks, nil +} + +func TestHandshakePanicsIfAppReturnsWrongAppHash(t *testing.T) { + // 1. Initialize CometBFT and commit 3 blocks with the following app hashes: + // - 0x01 + // - 0x02 + // - 0x03 + config := ResetConfig("handshake_test_") + defer os.RemoveAll(config.RootDir) + privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + const appVersion = 0x0 + stateDB, state, store := stateAndStore(t, config, appVersion) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile()) + state.LastValidators = state.Validators.Copy() + // mode = 0 for committing all the blocks + blocks, err := makeBlocks(3, state, []types.PrivValidator{privVal}) + require.NoError(t, err) + + store.chain = blocks + + // 2. CometBFT must panic if app returns wrong hash for the first block + // - RANDOM HASH + // - 0x02 + // - 0x03 + { + app := &badApp{numBlocks: 3, allHashesAreWrong: true} + clientCreator := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(clientCreator, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := proxyApp.Stop(); err != nil { + t.Error(err) + } + }) + + assert.Panics(t, func() { + h := NewHandshaker(stateStore, state, store, genDoc) + if err = h.Handshake(proxyApp); err != nil { + t.Log(err) + } + }) + } + + // 3. CometBFT must panic if app returns wrong hash for the last block + // - 0x01 + // - 0x02 + // - RANDOM HASH + { + app := &badApp{numBlocks: 3, onlyLastHashIsWrong: true} + clientCreator := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(clientCreator, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := proxyApp.Stop(); err != nil { + t.Error(err) + } + }) + + assert.Panics(t, func() { + h := NewHandshaker(stateStore, state, store, genDoc) + if err = h.Handshake(proxyApp); err != nil { + t.Log(err) + } + }) + } +} + +type badApp struct { + abci.BaseApplication + numBlocks byte + height byte + allHashesAreWrong bool + onlyLastHashIsWrong bool +} + +func (app *badApp) FinalizeBlock(context.Context, *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { + app.height++ + if app.onlyLastHashIsWrong { + if app.height == app.numBlocks { + return &abci.ResponseFinalizeBlock{AppHash: cmtrand.Bytes(8)}, nil + } + return &abci.ResponseFinalizeBlock{AppHash: []byte{app.height}}, nil + } else if app.allHashesAreWrong { + return &abci.ResponseFinalizeBlock{AppHash: cmtrand.Bytes(8)}, nil + } + + panic("either allHashesAreWrong or onlyLastHashIsWrong must be set") +} + +//-------------------------- +// utils for making blocks + +func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.ExtendedCommit, error) { + var height int64 + + // Search for height marker + gr, found, err := wal.SearchForEndHeight(height, &WALSearchOptions{}) + if err != nil { + return nil, nil, err + } + if !found { + return nil, nil, fmt.Errorf("wal does not contain height %d", height) + } + defer gr.Close() + + // log.Notice("Build a blockchain by reading from the WAL") + + var ( + blocks []*types.Block + extCommits []*types.ExtendedCommit + thisBlockParts *types.PartSet + thisBlockExtCommit *types.ExtendedCommit + ) + + dec := NewWALDecoder(gr) + for { + msg, err := dec.Decode() + if err == io.EOF { + break + } else if err != nil { + return nil, nil, err + } + + piece := readPieceFromWAL(msg) + if piece == nil { + continue + } + + switch p := piece.(type) { + case EndHeightMessage: + // if its not the first one, we have a full block + if thisBlockParts != nil { + pbb := new(cmtproto.Block) + bz, err := io.ReadAll(thisBlockParts.GetReader()) + if err != nil { + panic(err) + } + err = proto.Unmarshal(bz, pbb) + if err != nil { + panic(err) + } + block, err := types.BlockFromProto(pbb) + if err != nil { + panic(err) + } + + if block.Height != height+1 { + panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1)) + } + commitHeight := thisBlockExtCommit.Height + if commitHeight != height+1 { + panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) + } + blocks = append(blocks, block) + extCommits = append(extCommits, thisBlockExtCommit) + height++ + } + case *types.PartSetHeader: + thisBlockParts = types.NewPartSetFromHeader(*p) + case *types.Part: + _, err := thisBlockParts.AddPart(p) + if err != nil { + return nil, nil, err + } + case *types.Vote: + if p.Type == cmtproto.PrecommitType { + thisBlockExtCommit = &types.ExtendedCommit{ + Height: p.Height, + Round: p.Round, + BlockID: p.BlockID, + ExtendedSignatures: []types.ExtendedCommitSig{p.ExtendedCommitSig()}, + } + } + } + } + // grab the last block too + bz, err := io.ReadAll(thisBlockParts.GetReader()) + if err != nil { + panic(err) + } + pbb := new(cmtproto.Block) + err = proto.Unmarshal(bz, pbb) + if err != nil { + panic(err) + } + block, err := types.BlockFromProto(pbb) + if err != nil { + panic(err) + } + if block.Height != height+1 { + panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1)) + } + commitHeight := thisBlockExtCommit.Height + if commitHeight != height+1 { + panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) + } + blocks = append(blocks, block) + extCommits = append(extCommits, thisBlockExtCommit) + return blocks, extCommits, nil +} + +func readPieceFromWAL(msg *TimedWALMessage) interface{} { + // for logging + switch m := msg.Msg.(type) { + case msgInfo: + switch msg := m.Msg.(type) { + case *ProposalMessage: + return &msg.Proposal.BlockID.PartSetHeader + case *BlockPartMessage: + return msg.Part + case *VoteMessage: + return msg.Vote + } + case EndHeightMessage: + return m + } + + return nil +} + +// fresh state and mock store +func stateAndStore( + t *testing.T, + config *cfg.Config, + appVersion uint64, +) (dbm.DB, sm.State, *mockBlockStore) { + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := sm.MakeGenesisStateFromFile(config.GenesisFile()) + require.NoError(t, err) + state.Version.Consensus.App = appVersion + store := newMockBlockStore(t, config, state.ConsensusParams) + require.NoError(t, stateStore.Save(state)) + + return stateDB, state, store +} + +//---------------------------------- +// mock block store + +type mockBlockStore struct { + config *cfg.Config + params types.ConsensusParams + chain []*types.Block + extCommits []*types.ExtendedCommit + base int64 + t *testing.T +} + +var _ sm.BlockStore = &mockBlockStore{} + +// TODO: NewBlockStore(db.NewMemDB) ... +func newMockBlockStore(t *testing.T, config *cfg.Config, params types.ConsensusParams) *mockBlockStore { + return &mockBlockStore{ + config: config, + params: params, + t: t, + } +} + +func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) } +func (bs *mockBlockStore) Base() int64 { return bs.base } +func (bs *mockBlockStore) Size() int64 { return bs.Height() - bs.Base() + 1 } +func (bs *mockBlockStore) LoadBaseMeta() *types.BlockMeta { return bs.LoadBlockMeta(bs.base) } +func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] } +func (bs *mockBlockStore) LoadBlockByHash([]byte) *types.Block { + return bs.chain[int64(len(bs.chain))-1] +} +func (bs *mockBlockStore) LoadBlockMetaByHash([]byte) *types.BlockMeta { return nil } +func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta { + block := bs.chain[height-1] + bps, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(bs.t, err) + return &types.BlockMeta{ + BlockID: types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}, + Header: block.Header, + } +} +func (bs *mockBlockStore) LoadBlockPart(int64, int) *types.Part { return nil } +func (bs *mockBlockStore) SaveBlockWithExtendedCommit(*types.Block, *types.PartSet, *types.ExtendedCommit) { +} + +func (bs *mockBlockStore) SaveBlock(*types.Block, *types.PartSet, *types.Commit) { +} + +func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit { + return bs.extCommits[height-1].ToCommit() +} + +func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit { + return bs.extCommits[height-1].ToCommit() +} + +func (bs *mockBlockStore) LoadBlockExtendedCommit(height int64) *types.ExtendedCommit { + return bs.extCommits[height-1] +} + +func (bs *mockBlockStore) PruneBlocks(height int64, _ sm.State) (uint64, int64, error) { + evidencePoint := height + pruned := uint64(0) + for i := int64(0); i < height-1; i++ { + bs.chain[i] = nil + bs.extCommits[i] = nil + pruned++ + } + bs.base = height + return pruned, evidencePoint, nil +} + +func (bs *mockBlockStore) DeleteLatestBlock() error { return nil } +func (bs *mockBlockStore) Close() error { return nil } + +//--------------------------------------- +// Test handshake/init chain + +func TestHandshakeUpdatesValidators(t *testing.T) { + val, _ := types.RandValidator(true, 10) + vals := types.NewValidatorSet([]*types.Validator{val}) + app := &mocks.Application{} + app.On("Info", mock.Anything, mock.Anything).Return(&abci.ResponseInfo{ + LastBlockHeight: 0, + }, nil) + app.On("InitChain", mock.Anything, mock.Anything).Return(&abci.ResponseInitChain{ + Validators: types.TM2PB.ValidatorUpdates(vals), + }, nil) + clientCreator := proxy.NewLocalClientCreator(app) + + config := ResetConfig("handshake_test_") + defer os.RemoveAll(config.RootDir) + stateDB, state, store := stateAndStore(t, config, 0x0) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + oldValAddr := state.Validators.Validators[0].Address + + // now start the app using the handshake - it should sync + genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile()) + handshaker := NewHandshaker(stateStore, state, store, genDoc) + proxyApp := proxy.NewAppConns(clientCreator, proxy.NopMetrics()) + if err := proxyApp.Start(); err != nil { + t.Fatalf("Error starting proxy app connections: %v", err) + } + t.Cleanup(func() { + if err := proxyApp.Stop(); err != nil { + t.Error(err) + } + }) + if err := handshaker.Handshake(proxyApp); err != nil { + t.Fatalf("Error on abci handshake: %v", err) + } + var err error + // reload the state, check the validator set was updated + state, err = stateStore.Load() + require.NoError(t, err) + + newValAddr := state.Validators.Validators[0].Address + expectValAddr := val.Address + assert.NotEqual(t, oldValAddr, newValAddr) + assert.Equal(t, newValAddr, expectValAddr) +} diff --git a/consensus/state.go b/consensus/state.go new file mode 100644 index 0000000..a303a6c --- /dev/null +++ b/consensus/state.go @@ -0,0 +1,2653 @@ +package consensus + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "runtime/debug" + "sort" + "time" + + "github.com/cosmos/gogoproto/proto" + + cfg "github.com/cometbft/cometbft/config" + cstypes "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/crypto" + cmtevents "github.com/cometbft/cometbft/libs/events" + "github.com/cometbft/cometbft/libs/fail" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +// Consensus sentinel errors +var ( + ErrInvalidProposalSignature = errors.New("error invalid proposal signature") + ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round") + ErrAddingVote = errors.New("error adding vote") + ErrSignatureFoundInPastBlocks = errors.New("found signature from the same key") + ErrProposalTooManyParts = errors.New("proposal block has too many parts") + + errPubKeyIsNotSet = errors.New("pubkey is not set. Look for \"Can't get private validator pubkey\" errors") +) + +var msgQueueSize = 1000 + +// msgs from the reactor which may update the state +type msgInfo struct { + Msg Message `json:"msg"` + PeerID p2p.ID `json:"peer_key"` +} + +// internally generated messages which may update the state +type timeoutInfo struct { + Duration time.Duration `json:"duration"` + Height int64 `json:"height"` + Round int32 `json:"round"` + Step cstypes.RoundStepType `json:"step"` +} + +func (ti *timeoutInfo) String() string { + return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step) +} + +// interface to the mempool +type txNotifier interface { + TxsAvailable() <-chan struct{} +} + +// interface to the evidence pool +type evidencePool interface { + // reports conflicting votes to the evidence pool to be processed into evidence + ReportConflictingVotes(voteA, voteB *types.Vote) +} + +// State handles execution of the consensus algorithm. +// It processes votes and proposals, and upon reaching agreement, +// commits blocks to the chain and executes them against the application. +// The internal state machine receives input from peers, the internal validator, and from a timer. +type State struct { + service.BaseService + + // config details + config *cfg.ConsensusConfig + privValidator types.PrivValidator // for signing votes + + // store blocks and commits + blockStore sm.BlockStore + + // create and execute blocks + blockExec *sm.BlockExecutor + + // notify us if txs are available + txNotifier txNotifier + + // add evidence to the pool + // when it's detected + evpool evidencePool + + // internal state + mtx cmtsync.RWMutex + cstypes.RoundState + state sm.State // State until height-1. + // privValidator pubkey, memoized for the duration of one block + // to avoid extra requests to HSM + privValidatorPubKey crypto.PubKey + + // state changes may be triggered by: msgs from peers, + // msgs from ourself, or by timeouts + peerMsgQueue chan msgInfo + internalMsgQueue chan msgInfo + timeoutTicker TimeoutTicker + + // information about about added votes and block parts are written on this channel + // so statistics can be computed by reactor + statsMsgQueue chan msgInfo + + // we use eventBus to trigger msg broadcasts in the reactor, + // and to notify external subscribers, eg. through a websocket + eventBus *types.EventBus + + // a Write-Ahead Log ensures we can recover from any kind of crash + // and helps us avoid signing conflicting votes + wal WAL + replayMode bool // so we don't log signing errors during replay + doWALCatchup bool // determines if we even try to do the catchup + + // for tests where we want to limit the number of transitions the state makes + nSteps int + + // some functions can be overwritten for testing + decideProposal func(height int64, round int32) + doPrevote func(height int64, round int32) + setProposal func(proposal *types.Proposal) error + + // closed when we finish shutting down + done chan struct{} + + // synchronous pubsub between consensus state and reactor. + // state only emits EventNewRoundStep and EventVote + evsw cmtevents.EventSwitch + + // for reporting metrics + metrics *Metrics + + // offline state sync height indicating to which height the node synced offline + offlineStateSyncHeight int64 +} + +// StateOption sets an optional parameter on the State. +type StateOption func(*State) + +// NewState returns a new State. +func NewState( + config *cfg.ConsensusConfig, + state sm.State, + blockExec *sm.BlockExecutor, + blockStore sm.BlockStore, + txNotifier txNotifier, + evpool evidencePool, + options ...StateOption, +) *State { + cs := &State{ + config: config, + blockExec: blockExec, + blockStore: blockStore, + txNotifier: txNotifier, + peerMsgQueue: make(chan msgInfo, msgQueueSize), + internalMsgQueue: make(chan msgInfo, msgQueueSize), + timeoutTicker: NewTimeoutTicker(), + statsMsgQueue: make(chan msgInfo, msgQueueSize), + done: make(chan struct{}), + doWALCatchup: true, + wal: nilWAL{}, + evpool: evpool, + evsw: cmtevents.NewEventSwitch(), + metrics: NopMetrics(), + } + for _, option := range options { + option(cs) + } + // set function defaults (may be overwritten before calling Start) + cs.decideProposal = cs.defaultDecideProposal + cs.doPrevote = cs.defaultDoPrevote + cs.setProposal = cs.defaultSetProposal + + // We have no votes, so reconstruct LastCommit from SeenCommit. + if state.LastBlockHeight > 0 { + // In case of out of band performed statesync, the state store + // will have a state but no extended commit (as no block has been downloaded). + // If the height at which the vote extensions are enabled is lower + // than the height at which we statesync, consensus will panic because + // it will try to reconstruct the extended commit here. + if cs.offlineStateSyncHeight != 0 { + cs.reconstructSeenCommit(state) + } else { + cs.reconstructLastCommit(state) + } + } + + cs.updateToState(state) + + // NOTE: we do not call scheduleRound0 yet, we do that upon Start() + + cs.BaseService = *service.NewBaseService(nil, "State", cs) + + return cs +} + +// SetLogger implements Service. +func (cs *State) SetLogger(l log.Logger) { + cs.Logger = l + cs.timeoutTicker.SetLogger(l) +} + +// SetEventBus sets event bus. +func (cs *State) SetEventBus(b *types.EventBus) { + cs.eventBus = b + cs.blockExec.SetEventBus(b) +} + +// StateMetrics sets the metrics. +func StateMetrics(metrics *Metrics) StateOption { + return func(cs *State) { cs.metrics = metrics } +} + +// OfflineStateSyncHeight indicates the height at which the node +// statesync offline - before booting sets the metrics. +func OfflineStateSyncHeight(height int64) StateOption { + return func(cs *State) { cs.offlineStateSyncHeight = height } +} + +// String returns a string. +func (cs *State) String() string { + // better not to access shared variables + return "ConsensusState" +} + +// GetState returns a copy of the chain state. +func (cs *State) GetState() sm.State { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + return cs.state.Copy() +} + +// GetLastHeight returns the last height committed. +// If there were no blocks, returns 0. +func (cs *State) GetLastHeight() int64 { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + return cs.Height - 1 +} + +// GetRoundState returns a shallow copy of the internal consensus state. +func (cs *State) GetRoundState() *cstypes.RoundState { + cs.mtx.RLock() + rs := cs.RoundState // copy + cs.mtx.RUnlock() + return &rs +} + +// GetRoundStateJSON returns a json of RoundState. +func (cs *State) GetRoundStateJSON() ([]byte, error) { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + return cmtjson.Marshal(cs.RoundState) +} + +// GetRoundStateSimpleJSON returns a json of RoundStateSimple +func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + return cmtjson.Marshal(cs.RoundStateSimple()) +} + +// GetValidators returns a copy of the current validators. +func (cs *State) GetValidators() (int64, []*types.Validator) { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators +} + +// SetPrivValidator sets the private validator account for signing votes. It +// immediately requests pubkey and caches it. +func (cs *State) SetPrivValidator(priv types.PrivValidator) { + cs.mtx.Lock() + defer cs.mtx.Unlock() + + cs.privValidator = priv + + if err := cs.updatePrivValidatorPubKey(); err != nil { + cs.Logger.Error("failed to get private validator pubkey", "err", err) + } +} + +// SetTimeoutTicker sets the local timer. It may be useful to overwrite for +// testing. +func (cs *State) SetTimeoutTicker(timeoutTicker TimeoutTicker) { + cs.mtx.Lock() + cs.timeoutTicker = timeoutTicker + cs.mtx.Unlock() +} + +// LoadCommit loads the commit for a given height. +func (cs *State) LoadCommit(height int64) *types.Commit { + cs.mtx.RLock() + defer cs.mtx.RUnlock() + + if height == cs.blockStore.Height() { + return cs.blockStore.LoadSeenCommit(height) + } + + return cs.blockStore.LoadBlockCommit(height) +} + +// OnStart loads the latest state via the WAL, and starts the timeout and +// receive routines. +func (cs *State) OnStart() error { + // We may set the WAL in testing before calling Start, so only OpenWAL if its + // still the nilWAL. + if _, ok := cs.wal.(nilWAL); ok { + if err := cs.loadWalFile(); err != nil { + return err + } + } + + // we need the timeoutRoutine for replay so + // we don't block on the tick chan. + // NOTE: we will get a build up of garbage go routines + // firing on the tockChan until the receiveRoutine is started + // to deal with them (by that point, at most one will be valid) + if err := cs.timeoutTicker.Start(); err != nil { + return err + } + + // We may have lost some votes if the process crashed reload from consensus + // log to catchup. + if cs.doWALCatchup { + repairAttempted := false + + LOOP: + for { + err := cs.catchupReplay(cs.Height) + switch { + case err == nil: + break LOOP + + case !IsDataCorruptionError(err): + cs.Logger.Error("error on catchup replay; proceeding to start state anyway", "err", err) + break LOOP + + case repairAttempted: + return err + } + + cs.Logger.Error("the WAL file is corrupted; attempting repair", "err", err) + + // 1) prep work + if err := cs.wal.Stop(); err != nil { + return err + } + + repairAttempted = true + + // 2) backup original WAL file + corruptedFile := fmt.Sprintf("%s.CORRUPTED", cs.config.WalFile()) + if err := cmtos.CopyFile(cs.config.WalFile(), corruptedFile); err != nil { + return err + } + + cs.Logger.Debug("backed up WAL file", "src", cs.config.WalFile(), "dst", corruptedFile) + + // 3) try to repair (WAL file will be overwritten!) + if err := repairWalFile(corruptedFile, cs.config.WalFile()); err != nil { + cs.Logger.Error("the WAL repair failed", "err", err) + return err + } + + cs.Logger.Info("successful WAL repair") + + // reload WAL file + if err := cs.loadWalFile(); err != nil { + return err + } + } + } + + if err := cs.evsw.Start(); err != nil { + return err + } + + // Double Signing Risk Reduction + if err := cs.checkDoubleSigningRisk(cs.Height); err != nil { + return err + } + + // now start the receiveRoutine + go cs.receiveRoutine(0) + + // schedule the first round! + // use GetRoundState so we don't race the receiveRoutine for access + cs.scheduleRound0(cs.GetRoundState()) + + return nil +} + +// timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan +// receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions +func (cs *State) startRoutines(maxSteps int) { + err := cs.timeoutTicker.Start() + if err != nil { + cs.Logger.Error("failed to start timeout ticker", "err", err) + return + } + + go cs.receiveRoutine(maxSteps) +} + +// loadWalFile loads WAL data from file. It overwrites cs.wal. +func (cs *State) loadWalFile() error { + wal, err := cs.OpenWAL(cs.config.WalFile()) + if err != nil { + cs.Logger.Error("failed to load state WAL", "err", err) + return err + } + + cs.wal = wal + return nil +} + +// OnStop implements service.Service. +func (cs *State) OnStop() { + if err := cs.evsw.Stop(); err != nil { + cs.Logger.Error("failed trying to stop eventSwitch", "error", err) + } + + if err := cs.timeoutTicker.Stop(); err != nil { + cs.Logger.Error("failed trying to stop timeoutTicket", "error", err) + } + // WAL is stopped in receiveRoutine. +} + +// Wait waits for the the main routine to return. +// NOTE: be sure to Stop() the event switch and drain +// any event channels or this may deadlock +func (cs *State) Wait() { + <-cs.done +} + +// OpenWAL opens a file to log all consensus messages and timeouts for +// deterministic accountability. +func (cs *State) OpenWAL(walFile string) (WAL, error) { + wal, err := NewWAL(walFile) + if err != nil { + cs.Logger.Error("failed to open WAL", "file", walFile, "err", err) + return nil, err + } + + wal.SetLogger(cs.Logger.With("wal", walFile)) + + if err := wal.Start(); err != nil { + cs.Logger.Error("failed to start WAL", "err", err) + return nil, err + } + + return wal, nil +} + +//------------------------------------------------------------ +// Public interface for passing messages into the consensus state, possibly causing a state transition. +// If peerID == "", the msg is considered internal. +// Messages are added to the appropriate queue (peer or internal). +// If the queue is full, the function may block. +// TODO: should these return anything or let callers just use events? + +// AddVote inputs a vote. +func (cs *State) AddVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) { + if peerID == "" { + cs.internalMsgQueue <- msgInfo{&VoteMessage{vote}, ""} + } else { + cs.peerMsgQueue <- msgInfo{&VoteMessage{vote}, peerID} + } + + // TODO: wait for event?! + return false, nil +} + +// SetProposal inputs a proposal. +func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error { + if peerID == "" { + cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""} + } else { + cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerID} + } + + // TODO: wait for event?! + return nil +} + +// AddProposalBlockPart inputs a part of the proposal block. +func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Part, peerID p2p.ID) error { + if peerID == "" { + cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""} + } else { + cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerID} + } + + // TODO: wait for event?! + return nil +} + +// SetProposalAndBlock inputs the proposal and all block parts. +func (cs *State) SetProposalAndBlock( + proposal *types.Proposal, + block *types.Block, //nolint:revive + parts *types.PartSet, + peerID p2p.ID, +) error { + // TODO: Since the block parameter is not used, we should instead expose just a SetProposal method. + if err := cs.SetProposal(proposal, peerID); err != nil { + return err + } + + for i := 0; i < int(parts.Total()); i++ { + part := parts.GetPart(i) + if err := cs.AddProposalBlockPart(proposal.Height, proposal.Round, part, peerID); err != nil { + return err + } + } + + return nil +} + +//------------------------------------------------------------ +// internal functions for managing the state + +func (cs *State) updateHeight(height int64) { + cs.metrics.Height.Set(float64(height)) + cs.Height = height +} + +func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) { + if !cs.replayMode { + if round != cs.Round || round == 0 && step == cstypes.RoundStepNewRound { + cs.metrics.MarkRound(cs.Round, cs.StartTime) + } + if cs.Step != step { + cs.metrics.MarkStep(cs.Step) + } + } + cs.Round = round + cs.Step = step +} + +// enterNewRound(height, 0) at cs.StartTime. +func (cs *State) scheduleRound0(rs *cstypes.RoundState) { + // cs.Logger.Info("scheduleRound0", "now", cmttime.Now(), "startTime", cs.StartTime) + sleepDuration := rs.StartTime.Sub(cmttime.Now()) + cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight) +} + +// Attempt to schedule a timeout (by sending timeoutInfo on the tickChan) +func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) { + cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step}) +} + +// send a msg into the receiveRoutine regarding our own proposal, block part, or vote +func (cs *State) sendInternalMessage(mi msgInfo) { + select { + case cs.internalMsgQueue <- mi: + default: + // NOTE: using the go-routine means our votes can + // be processed out of order. + // TODO: use CList here for strict determinism and + // attempt push to internalMsgQueue in receiveRoutine + cs.Logger.Debug("internal msg queue is full; using a go-routine") + go func() { cs.internalMsgQueue <- mi }() + } +} + +// ReconstructSeenCommit reconstructs the seen commit +// This function is meant to be called after statesync +// that was performed offline as to avoid interfering with vote +// extensions. +func (cs *State) reconstructSeenCommit(state sm.State) { + votes, err := cs.votesFromSeenCommit(state) + if err != nil { + panic(fmt.Sprintf("failed to reconstruct last commit; %s", err)) + } + cs.LastCommit = votes +} + +// Reconstruct the LastCommit from either SeenCommit or the ExtendedCommit. SeenCommit +// and ExtendedCommit are saved along with the block. If VoteExtensions are required +// the method will panic on an absent ExtendedCommit or an ExtendedCommit without +// extension data. +func (cs *State) reconstructLastCommit(state sm.State) { + extensionsEnabled := state.ConsensusParams.ABCI.VoteExtensionsEnabled(state.LastBlockHeight) + if !extensionsEnabled { + cs.reconstructSeenCommit(state) + return + } + votes, err := cs.votesFromExtendedCommit(state) + if err != nil { + panic(fmt.Sprintf("failed to reconstruct last extended commit; %s", err)) + } + cs.LastCommit = votes +} + +func (cs *State) votesFromExtendedCommit(state sm.State) (*types.VoteSet, error) { + ec := cs.blockStore.LoadBlockExtendedCommit(state.LastBlockHeight) + if ec == nil { + return nil, fmt.Errorf("extended commit for height %v not found", state.LastBlockHeight) + } + if ec.Height != state.LastBlockHeight { + return nil, fmt.Errorf("heights don't match in votesFromExtendedCommit %v!=%v", + ec.Height, state.LastBlockHeight) + } + vs := ec.ToExtendedVoteSet(state.ChainID, state.LastValidators) + if !vs.HasTwoThirdsMajority() { + return nil, errors.New("extended commit does not have +2/3 majority") + } + return vs, nil +} + +func (cs *State) votesFromSeenCommit(state sm.State) (*types.VoteSet, error) { + commit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight) + if commit == nil { + commit = cs.blockStore.LoadBlockCommit(state.LastBlockHeight) + } + if commit == nil { + return nil, fmt.Errorf("commit for height %v not found", state.LastBlockHeight) + } + if commit.Height != state.LastBlockHeight { + return nil, fmt.Errorf("heights don't match in votesFromSeenCommit %v!=%v", + commit.Height, state.LastBlockHeight) + } + vs := commit.ToVoteSet(state.ChainID, state.LastValidators) + if !vs.HasTwoThirdsMajority() { + return nil, errors.New("commit does not have +2/3 majority") + } + return vs, nil +} + +// Updates State and increments height to match that of state. +// The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight. +func (cs *State) updateToState(state sm.State) { + if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight { + panic(fmt.Sprintf( + "updateToState() expected state height of %v but found %v", + cs.Height, state.LastBlockHeight, + )) + } + + if !cs.state.IsEmpty() { + if cs.state.LastBlockHeight > 0 && cs.state.LastBlockHeight+1 != cs.Height { + // This might happen when someone else is mutating cs.state. + // Someone forgot to pass in state.Copy() somewhere?! + panic(fmt.Sprintf( + "inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v", + cs.state.LastBlockHeight+1, cs.Height, + )) + } + if cs.state.LastBlockHeight > 0 && cs.Height == cs.state.InitialHeight { + panic(fmt.Sprintf( + "inconsistent cs.state.LastBlockHeight %v, expected 0 for initial height %v", + cs.state.LastBlockHeight, cs.state.InitialHeight, + )) + } + + // If state isn't further out than cs.state, just ignore. + // This happens when SwitchToConsensus() is called in the reactor. + // We don't want to reset e.g. the Votes, but we still want to + // signal the new round step, because other services (eg. txNotifier) + // depend on having an up-to-date peer state! + if state.LastBlockHeight <= cs.state.LastBlockHeight { + cs.Logger.Debug( + "ignoring updateToState()", + "new_height", state.LastBlockHeight+1, + "old_height", cs.state.LastBlockHeight+1, + ) + cs.newStep() + return + } + } + + // Reset fields based on state. + validators := state.Validators + + switch { + case state.LastBlockHeight == 0: // Very first commit should be empty. + cs.LastCommit = (*types.VoteSet)(nil) + case cs.CommitRound > -1 && cs.Votes != nil: // Otherwise, use cs.Votes + if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() { + panic(fmt.Sprintf( + "wanted to form a commit, but precommits (H/R: %d/%d) didn't have 2/3+: %v", + state.LastBlockHeight, cs.CommitRound, cs.Votes.Precommits(cs.CommitRound), + )) + } + + cs.LastCommit = cs.Votes.Precommits(cs.CommitRound) + + case cs.LastCommit == nil: + // NOTE: when consensus starts, it has no votes. reconstructLastCommit + // must be called to reconstruct LastCommit from SeenCommit. + panic(fmt.Sprintf( + "last commit cannot be empty after initial block (H:%d)", + state.LastBlockHeight+1, + )) + } + + // Next desired block height + height := state.LastBlockHeight + 1 + if height == 1 { + height = state.InitialHeight + } + + // RoundState fields + cs.updateHeight(height) + cs.updateRoundStep(0, cstypes.RoundStepNewHeight) + + if cs.CommitTime.IsZero() { + // "Now" makes it easier to sync up dev nodes. + // We add timeoutCommit to allow transactions + // to be gathered for the first block. + // And alternative solution that relies on clocks: + // cs.StartTime = state.LastBlockTime.Add(timeoutCommit) + cs.StartTime = cs.config.Commit(cmttime.Now()) + } else { + cs.StartTime = cs.config.Commit(cs.CommitTime) + } + + cs.Validators = validators + cs.Proposal = nil + cs.ProposalBlock = nil + cs.ProposalBlockParts = nil + cs.LockedRound = -1 + cs.LockedBlock = nil + cs.LockedBlockParts = nil + cs.ValidRound = -1 + cs.ValidBlock = nil + cs.ValidBlockParts = nil + if state.ConsensusParams.ABCI.VoteExtensionsEnabled(height) { + cs.Votes = cstypes.NewExtendedHeightVoteSet(state.ChainID, height, validators) + } else { + cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators) + } + cs.CommitRound = -1 + cs.LastValidators = state.LastValidators + cs.TriggeredTimeoutPrecommit = false + + cs.state = state + + // Finally, broadcast RoundState + cs.newStep() +} + +func (cs *State) newStep() { + rs := cs.RoundStateEvent() + if err := cs.wal.Write(rs); err != nil { + cs.Logger.Error("failed writing to WAL", "err", err) + } + + cs.nSteps++ + + // newStep is called by updateToState in NewState before the eventBus is set! + if cs.eventBus != nil { + if err := cs.eventBus.PublishEventNewRoundStep(rs); err != nil { + cs.Logger.Error("failed publishing new round step", "err", err) + } + + cs.evsw.FireEvent(types.EventNewRoundStep, &cs.RoundState) + } +} + +//----------------------------------------- +// the main go routines + +// receiveRoutine handles messages which may cause state transitions. +// it's argument (n) is the number of messages to process before exiting - use 0 to run forever +// It keeps the RoundState and is the only thing that updates it. +// Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities. +// State must be locked before any internal state is updated. +func (cs *State) receiveRoutine(maxSteps int) { + onExit := func(cs *State) { + // NOTE: the internalMsgQueue may have signed messages from our + // priv_val that haven't hit the WAL, but its ok because + // priv_val tracks LastSig + + // close wal now that we're done writing to it + if err := cs.wal.Stop(); err != nil { + cs.Logger.Error("failed trying to stop WAL", "error", err) + } + + cs.wal.Wait() + close(cs.done) + } + + defer func() { + if r := recover(); r != nil { + cs.Logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack())) + // stop gracefully + // + // NOTE: We most probably shouldn't be running any further when there is + // some unexpected panic. Some unknown error happened, and so we don't + // know if that will result in the validator signing an invalid thing. It + // might be worthwhile to explore a mechanism for manual resuming via + // some console or secure RPC system, but for now, halting the chain upon + // unexpected consensus bugs sounds like the better option. + onExit(cs) + } + }() + + for { + if maxSteps > 0 { + if cs.nSteps >= maxSteps { + cs.Logger.Debug("reached max steps; exiting receive routine") + cs.nSteps = 0 + return + } + } + + rs := cs.RoundState + var mi msgInfo + + select { + case <-cs.txNotifier.TxsAvailable(): + cs.handleTxsAvailable() + + case mi = <-cs.peerMsgQueue: + if err := cs.wal.Write(mi); err != nil { + cs.Logger.Error("failed writing to WAL", "err", err) + } + // handles proposals, block parts, votes + // may generate internal events (votes, complete proposals, 2/3 majorities) + cs.handleMsg(mi) + + case mi = <-cs.internalMsgQueue: + err := cs.wal.WriteSync(mi) // NOTE: fsync + if err != nil { + panic(fmt.Sprintf( + "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node", + mi, err, + )) + } + + if _, ok := mi.Msg.(*VoteMessage); ok { + // we actually want to simulate failing during + // the previous WriteSync, but this isn't easy to do. + // Equivalent would be to fail here and manually remove + // some bytes from the end of the wal. + fail.Fail() // XXX + } + + // handles proposals, block parts, votes + cs.handleMsg(mi) + + case ti := <-cs.timeoutTicker.Chan(): // tockChan: + if err := cs.wal.Write(ti); err != nil { + cs.Logger.Error("failed writing to WAL", "err", err) + } + + // if the timeout is relevant to the rs + // go to the next step + cs.handleTimeout(ti, rs) + + case <-cs.Quit(): + onExit(cs) + return + } + } +} + +// state transitions on complete-proposal, 2/3-any, 2/3-one +func (cs *State) handleMsg(mi msgInfo) { + cs.mtx.Lock() + defer cs.mtx.Unlock() + var ( + added bool + err error + ) + + msg, peerID := mi.Msg, mi.PeerID + + switch msg := msg.(type) { + case *ProposalMessage: + // will not cause transition. + // once proposal is set, we can receive block parts + err = cs.setProposal(msg.Proposal) + + case *BlockPartMessage: + // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit + added, err = cs.addProposalBlockPart(msg, peerID) + + // We unlock here to yield to any routines that need to read the the RoundState. + // Previously, this code held the lock from the point at which the final block + // part was received until the block executed against the application. + // This prevented the reactor from being able to retrieve the most updated + // version of the RoundState. The reactor needs the updated RoundState to + // gossip the now completed block. + // + // This code can be further improved by either always operating on a copy + // of RoundState and only locking when switching out State's copy of + // RoundState with the updated copy or by emitting RoundState events in + // more places for routines depending on it to listen for. + cs.mtx.Unlock() + + cs.mtx.Lock() + if added && cs.ProposalBlockParts.IsComplete() { + cs.handleCompleteProposal(msg.Height) + } + if added { + cs.statsMsgQueue <- mi + } + + if err != nil && msg.Round != cs.Round { + cs.Logger.Debug( + "received block part from wrong round", + "height", cs.Height, + "cs_round", cs.Round, + "block_round", msg.Round, + ) + err = nil + } + + case *VoteMessage: + // attempt to add the vote and dupeout the validator if its a duplicate signature + // if the vote gives us a 2/3-any or 2/3-one, we transition + added, err = cs.tryAddVote(msg.Vote, peerID) + if added { + cs.statsMsgQueue <- mi + } + + // if err == ErrAddingVote { + // TODO: punish peer + // We probably don't want to stop the peer here. The vote does not + // necessarily comes from a malicious peer but can be just broadcasted by + // a typical peer. + // https://github.com/tendermint/tendermint/issues/1281 + // } + + // NOTE: the vote is broadcast to peers by the reactor listening + // for vote events + + // TODO: If rs.Height == vote.Height && rs.Round < vote.Round, + // the peer is sending us CatchupCommit precommits. + // We could make note of this and help filter in broadcastHasVoteMessage(). + + default: + cs.Logger.Error("unknown msg type", "type", fmt.Sprintf("%T", msg)) + return + } + + if err != nil { + cs.Logger.Error( + "failed to process message", + "height", cs.Height, + "round", cs.Round, + "peer", peerID, + "msg_type", fmt.Sprintf("%T", msg), + "err", err, + ) + } +} + +func (cs *State) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) { + cs.Logger.Debug("received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + + // timeouts must be for current height, round, step + if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) { + cs.Logger.Debug("ignoring tock because we are ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step) + return + } + + // the timeout will now cause a state transition + cs.mtx.Lock() + defer cs.mtx.Unlock() + + switch ti.Step { + case cstypes.RoundStepNewHeight: + // NewRound event fired from enterNewRound. + // XXX: should we fire timeout here (for timeout commit)? + cs.enterNewRound(ti.Height, 0) + + case cstypes.RoundStepNewRound: + cs.enterPropose(ti.Height, ti.Round) + + case cstypes.RoundStepPropose: + if err := cs.eventBus.PublishEventTimeoutPropose(cs.RoundStateEvent()); err != nil { + cs.Logger.Error("failed publishing timeout propose", "err", err) + } + + cs.enterPrevote(ti.Height, ti.Round) + + case cstypes.RoundStepPrevoteWait: + if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil { + cs.Logger.Error("failed publishing timeout wait", "err", err) + } + + cs.enterPrecommit(ti.Height, ti.Round) + + case cstypes.RoundStepPrecommitWait: + if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil { + cs.Logger.Error("failed publishing timeout wait", "err", err) + } + + cs.emitPrecommitTimeoutMetrics(ti.Round) + cs.enterPrecommit(ti.Height, ti.Round) + cs.enterNewRound(ti.Height, ti.Round+1) + + default: + panic(fmt.Sprintf("invalid timeout step: %v", ti.Step)) + } +} + +func (cs *State) handleTxsAvailable() { + cs.mtx.Lock() + defer cs.mtx.Unlock() + + // We only need to do this for round 0. + if cs.Round != 0 { + return + } + + switch cs.Step { + case cstypes.RoundStepNewHeight: // timeoutCommit phase + if cs.needProofBlock(cs.Height) { + // enterPropose will be called by enterNewRound + return + } + + // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight + timeoutCommit := cs.StartTime.Sub(cmttime.Now()) + 1*time.Millisecond + cs.scheduleTimeout(timeoutCommit, cs.Height, 0, cstypes.RoundStepNewRound) + + case cstypes.RoundStepNewRound: // after timeoutCommit + cs.enterPropose(cs.Height, 0) + } +} + +//----------------------------------------------------------------------------- +// State functions +// Used internally by handleTimeout and handleMsg to make state transitions + +// Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit), +// +// or, if SkipTimeoutCommit==true, after receiving all precommits from (height,round-1) +// +// Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1) +// Enter: +2/3 precommits for nil at (height,round-1) +// Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round) +// NOTE: cs.StartTime was already set for height. +func (cs *State) enterNewRound(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) { + logger.Debug( + "entering new round with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + if now := cmttime.Now(); cs.StartTime.After(now) { + logger.Debug("need to set a buffer and log message here for sanity", "start_time", cs.StartTime, "now", now) + } + + prevHeight, prevRound, prevStep := cs.Height, cs.Round, cs.Step + + // increment validators if necessary + validators := cs.Validators + if cs.Round < round { + validators = validators.Copy() + validators.IncrementProposerPriority(cmtmath.SafeSubInt32(round, cs.Round)) + } + + // Setup new round + // we don't fire newStep for this step, + // but we fire an event, so update the round step first + cs.updateRoundStep(round, cstypes.RoundStepNewRound) + cs.Validators = validators + // If round == 0, we've already reset these upon new height, and meanwhile + // we might have received a proposal for round 0. + propAddress := validators.GetProposer().PubKey.Address() + if round != 0 { + logger.Info("resetting proposal info", "proposer", propAddress) + cs.Proposal = nil + cs.ProposalBlock = nil + cs.ProposalBlockParts = nil + } + + logger.Debug("entering new round", + "previous", log.NewLazySprintf("%v/%v/%v", prevHeight, prevRound, prevStep), + "proposer", propAddress, + ) + + cs.Votes.SetRound(cmtmath.SafeAddInt32(round, 1)) // also track next round (round+1) to allow round-skipping + cs.TriggeredTimeoutPrecommit = false + + if err := cs.eventBus.PublishEventNewRound(cs.NewRoundEvent()); err != nil { + cs.Logger.Error("failed publishing new round", "err", err) + } + // Wait for txs to be available in the mempool + // before we enterPropose in round 0. If the last block changed the app hash, + // we may need an empty "proof" block, and enterPropose immediately. + waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height) + if waitForTxs { + if cs.config.CreateEmptyBlocksInterval > 0 { + cs.scheduleTimeout(cs.config.CreateEmptyBlocksInterval, height, round, + cstypes.RoundStepNewRound) + } + } else { + cs.enterPropose(height, round) + } +} + +// needProofBlock returns true on the first height (so the genesis app hash is signed right away) +// and where the last block (height-1) caused the app hash to change +func (cs *State) needProofBlock(height int64) bool { + if height == cs.state.InitialHeight { + return true + } + + lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1) + if lastBlockMeta == nil { + // See https://github.com/cometbft/cometbft/issues/370 + cs.Logger.Info("short-circuited needProofBlock", "height", height, "InitialHeight", cs.state.InitialHeight) + return true + } + + return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash) +} + +// Enter (CreateEmptyBlocks): from enterNewRound(height,round) +// Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ): +// +// after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval +// +// Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool +func (cs *State) enterPropose(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) { + logger.Debug( + "entering propose step with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + logger.Debug("entering propose step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + defer func() { + // Done enterPropose: + cs.updateRoundStep(round, cstypes.RoundStepPropose) + cs.newStep() + + // If we have the whole proposal + POL, then goto Prevote now. + // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart), + // or else after timeoutPropose + if cs.isProposalComplete() { + cs.enterPrevote(height, cs.Round) + } + }() + + // If we don't get the proposal and all block parts quick enough, enterPrevote + cs.scheduleTimeout(cs.config.Propose(round), height, round, cstypes.RoundStepPropose) + + // Nothing more to do if we're not a validator + if cs.privValidator == nil { + logger.Debug("node is not a validator") + return + } + + logger.Debug("node is a validator") + + if cs.privValidatorPubKey == nil { + // If this node is a validator & proposer in the current round, it will + // miss the opportunity to create a block. + logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet) + return + } + + address := cs.privValidatorPubKey.Address() + + // if not a validator, we're done + if !cs.Validators.HasAddress(address) { + logger.Debug("node is not a validator", "addr", address, "vals", cs.Validators) + return + } + + if cs.isProposer(address) { + logger.Debug("propose step; our turn to propose", "proposer", address) + cs.decideProposal(height, round) + } else { + logger.Debug("propose step; not our turn to propose", "proposer", cs.Validators.GetProposer().Address) + } +} + +func (cs *State) isProposer(address []byte) bool { + return bytes.Equal(cs.Validators.GetProposer().Address, address) +} + +func (cs *State) defaultDecideProposal(height int64, round int32) { + var block *types.Block + var blockParts *types.PartSet + + // Decide on block + if cs.ValidBlock != nil { + // If there is valid block, choose that. + block, blockParts = cs.ValidBlock, cs.ValidBlockParts + } else { + // Create a new proposal block from state/txs from the mempool. + var err error + block, err = cs.createProposalBlock(context.TODO()) + if err != nil { + cs.Logger.Error("unable to create proposal block", "error", err) + return + } else if block == nil { + panic("Method createProposalBlock should not provide a nil block without errors") + } + cs.metrics.ProposalCreateCount.Add(1) + blockParts, err = block.MakePartSet(types.BlockPartSizeBytes) + if err != nil { + cs.Logger.Error("unable to create proposal block part set", "error", err) + return + } + } + + // Flush the WAL. Otherwise, we may not recompute the same proposal to sign, + // and the privValidator will refuse to sign anything. + if err := cs.wal.FlushAndSync(); err != nil { + cs.Logger.Error("failed flushing WAL to disk") + } + + // Make proposal + propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()} + proposal := types.NewProposal(height, round, cs.ValidRound, propBlockID) + p := proposal.ToProto() + if err := cs.privValidator.SignProposal(cs.state.ChainID, p); err == nil { + proposal.Signature = p.Signature + + // send proposal and block parts on internal msg queue + cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""}) + + for i := 0; i < int(blockParts.Total()); i++ { + part := blockParts.GetPart(i) + cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""}) + } + + cs.Logger.Debug("signed proposal", "height", height, "round", round, "proposal", proposal) + } else if !cs.replayMode { + cs.Logger.Error("propose step; failed signing proposal", "height", height, "round", round, "err", err) + } +} + +// Returns true if the proposal block is complete && +// (if POLRound was proposed, we have +2/3 prevotes from there). +func (cs *State) isProposalComplete() bool { + if cs.Proposal == nil || cs.ProposalBlock == nil { + return false + } + // we have the proposal. if there's a POLRound, + // make sure we have the prevotes from it too + if cs.Proposal.POLRound < 0 { + return true + } + // if this is false the proposer is lying or we haven't received the POL yet + return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority() +} + +// Create the next block to propose and return it. Returns nil block upon error. +// +// We really only need to return the parts, but the block is returned for +// convenience so we can log the proposal block. +// +// NOTE: keep it side-effect free for clarity. +// CONTRACT: cs.privValidator is not nil. +func (cs *State) createProposalBlock(ctx context.Context) (*types.Block, error) { + if cs.privValidator == nil { + return nil, errors.New("entered createProposalBlock with privValidator being nil") + } + + // TODO(sergio): wouldn't it be easier if CreateProposalBlock accepted cs.LastCommit directly? + var lastExtCommit *types.ExtendedCommit + switch { + case cs.Height == cs.state.InitialHeight: + // We're creating a proposal for the first block. + // The commit is empty, but not nil. + lastExtCommit = &types.ExtendedCommit{} + + case cs.LastCommit.HasTwoThirdsMajority(): + // Make the commit from LastCommit + lastExtCommit = cs.LastCommit.MakeExtendedCommit(cs.state.ConsensusParams.ABCI) + + default: // This shouldn't happen. + return nil, errors.New("propose step; cannot propose anything without commit for the previous block") + } + + if cs.privValidatorPubKey == nil { + // If this node is a validator & proposer in the current round, it will + // miss the opportunity to create a block. + return nil, fmt.Errorf("propose step; empty priv validator public key, error: %w", errPubKeyIsNotSet) + } + + proposerAddr := cs.privValidatorPubKey.Address() + + ret, err := cs.blockExec.CreateProposalBlock(ctx, cs.Height, cs.state, lastExtCommit, proposerAddr) + if err != nil { + panic(err) + } + return ret, nil +} + +// Enter: `timeoutPropose` after entering Propose. +// Enter: proposal block and POL is ready. +// Prevote for LockedBlock if we're locked, or ProposalBlock if valid. +// Otherwise vote nil. +func (cs *State) enterPrevote(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) { + logger.Debug( + "entering prevote step with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + defer func() { + // Done enterPrevote: + cs.updateRoundStep(round, cstypes.RoundStepPrevote) + cs.newStep() + }() + + logger.Debug("entering prevote step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + // Sign and broadcast vote as necessary + cs.doPrevote(height, round) + + // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait + // (so we have more time to try and collect +2/3 prevotes for a single block) +} + +func (cs *State) defaultDoPrevote(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + // If a block is locked, prevote that. + if cs.LockedBlock != nil { + logger.Debug("prevote step; already locked on a block; prevoting locked block") + cs.signAddVote(cmtproto.PrevoteType, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header(), nil) + return + } + + // If ProposalBlock is nil, prevote nil. + if cs.ProposalBlock == nil { + logger.Debug("prevote step: ProposalBlock is nil") + cs.signAddVote(cmtproto.PrevoteType, nil, types.PartSetHeader{}, nil) + return + } + + // Validate proposal block, from consensus' perspective + err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock) + if err != nil { + // ProposalBlock is invalid, prevote nil. + logger.Error("prevote step: consensus deems this block invalid; prevoting nil", + "err", err) + cs.signAddVote(cmtproto.PrevoteType, nil, types.PartSetHeader{}, nil) + return + } + + /* + Before prevoting on the block received from the proposer for the current round and height, + we request the Application, via `ProcessProposal` ABCI call, to confirm that the block is + valid. If the Application does not accept the block, consensus prevotes `nil`. + + WARNING: misuse of block rejection by the Application can seriously compromise + the liveness properties of consensus. + Please see `PrepareProosal`-`ProcessProposal` coherence and determinism properties + in the ABCI++ specification. + */ + isAppValid, err := cs.blockExec.ProcessProposal(cs.ProposalBlock, cs.state) + if err != nil { + panic(fmt.Sprintf( + "state machine returned an error (%v) when calling ProcessProposal", err, + )) + } + cs.metrics.MarkProposalProcessed(isAppValid) + + // Vote nil if the Application rejected the block + if !isAppValid { + logger.Error("prevote step: state machine rejected a proposed block; this should not happen:"+ + "the proposer may be misbehaving; prevoting nil", "err", err) + cs.signAddVote(cmtproto.PrevoteType, nil, types.PartSetHeader{}, nil) + return + } + + // Prevote cs.ProposalBlock + // NOTE: the proposal signature is validated when it is received, + // and the proposal block parts are validated as they are received (against the merkle hash in the proposal) + logger.Debug("prevote step: ProposalBlock is valid") + cs.signAddVote(cmtproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header(), nil) +} + +// Enter: any +2/3 prevotes at next round. +func (cs *State) enterPrevoteWait(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) { + logger.Debug( + "entering prevote wait step with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + if !cs.Votes.Prevotes(round).HasTwoThirdsAny() { + panic(fmt.Sprintf( + "entering prevote wait step (%v/%v), but prevotes does not have any +2/3 votes", + height, round, + )) + } + + logger.Debug("entering prevote wait step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + defer func() { + // Done enterPrevoteWait: + cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait) + cs.newStep() + }() + + // Wait for some more prevotes; enterPrecommit + cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait) +} + +// Enter: `timeoutPrevote` after any +2/3 prevotes. +// Enter: `timeoutPrecommit` after any +2/3 precommits. +// Enter: +2/3 precomits for block or nil. +// Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round) +// else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil, +// else, precommit nil otherwise. +func (cs *State) enterPrecommit(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) { + logger.Debug( + "entering precommit step with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + logger.Debug("entering precommit step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + defer func() { + // Done enterPrecommit: + cs.updateRoundStep(round, cstypes.RoundStepPrecommit) + cs.newStep() + }() + + // check for a polka + blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority() + + // If we don't have a polka, we must precommit nil. + if !ok { + if cs.LockedBlock != nil { + logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit while we are locked; precommitting nil") + } else { + logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit; precommitting nil") + } + + cs.signAddVote(cmtproto.PrecommitType, nil, types.PartSetHeader{}, nil) + return + } + + // At this point +2/3 prevoted for a particular block or nil. + if err := cs.eventBus.PublishEventPolka(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing polka", "err", err) + } + + // the latest POLRound should be this round. + polRound, _ := cs.Votes.POLInfo() + if polRound < round { + panic(fmt.Sprintf("this POLRound should be %v but got %v", round, polRound)) + } + + // +2/3 prevoted nil. Unlock and precommit nil. + if len(blockID.Hash) == 0 { + if cs.LockedBlock == nil { + logger.Debug("precommit step; +2/3 prevoted for nil") + } else { + logger.Debug("precommit step; +2/3 prevoted for nil; unlocking") + cs.LockedRound = -1 + cs.LockedBlock = nil + cs.LockedBlockParts = nil + + if err := cs.eventBus.PublishEventUnlock(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing event unlock", "err", err) + } + } + + cs.signAddVote(cmtproto.PrecommitType, nil, types.PartSetHeader{}, nil) + return + } + + // At this point, +2/3 prevoted for a particular block. + + // If we're already locked on that block, precommit it, and update the LockedRound + if cs.LockedBlock.HashesTo(blockID.Hash) { + logger.Debug("precommit step; +2/3 prevoted locked block; relocking") + cs.LockedRound = round + + if err := cs.eventBus.PublishEventRelock(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing event relock", "err", err) + } + + cs.signAddVote(cmtproto.PrecommitType, blockID.Hash, blockID.PartSetHeader, cs.LockedBlock) + return + } + + // If +2/3 prevoted for proposal block, stage and precommit it + if cs.ProposalBlock.HashesTo(blockID.Hash) { + logger.Debug("precommit step; +2/3 prevoted proposal block; locking", "hash", blockID.Hash) + + // Validate the block. + if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil { + panic(fmt.Sprintf("precommit step; +2/3 prevoted for an invalid block: %v", err)) + } + + cs.LockedRound = round + cs.LockedBlock = cs.ProposalBlock + cs.LockedBlockParts = cs.ProposalBlockParts + + if err := cs.eventBus.PublishEventLock(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing event lock", "err", err) + } + + cs.signAddVote(cmtproto.PrecommitType, blockID.Hash, blockID.PartSetHeader, cs.ProposalBlock) + return + } + + // There was a polka in this round for a block we don't have. + // Fetch that block, unlock, and precommit nil. + // The +2/3 prevotes for this round is the POL for our unlock. + logger.Debug("precommit step; +2/3 prevotes for a block we do not have; voting nil", "block_id", blockID) + + cs.LockedRound = -1 + cs.LockedBlock = nil + cs.LockedBlockParts = nil + + if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) { + cs.ProposalBlock = nil + cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader) + } + + if err := cs.eventBus.PublishEventUnlock(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing event unlock", "err", err) + } + + cs.signAddVote(cmtproto.PrecommitType, nil, types.PartSetHeader{}, nil) +} + +// Enter: any +2/3 precommits for next round. +func (cs *State) enterPrecommitWait(height int64, round int32) { + logger := cs.Logger.With("height", height, "round", round) + + if cs.Height != height || round < cs.Round || (cs.Round == round && cs.TriggeredTimeoutPrecommit) { + logger.Debug( + "entering precommit wait step with invalid args", + "triggered_timeout", cs.TriggeredTimeoutPrecommit, + "current", log.NewLazySprintf("%v/%v", cs.Height, cs.Round), + ) + return + } + + if !cs.Votes.Precommits(round).HasTwoThirdsAny() { + panic(fmt.Sprintf( + "entering precommit wait step (%v/%v), but precommits does not have any +2/3 votes", + height, round, + )) + } + + logger.Debug("entering precommit wait step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + defer func() { + // Done enterPrecommitWait: + cs.TriggeredTimeoutPrecommit = true + cs.newStep() + }() + + // wait for some more precommits; enterNewRound + cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait) +} + +// Enter: +2/3 precommits for block +func (cs *State) enterCommit(height int64, commitRound int32) { + logger := cs.Logger.With("height", height, "commit_round", commitRound) + + if cs.Height != height || cstypes.RoundStepCommit <= cs.Step { + logger.Debug( + "entering commit step with invalid args", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + logger.Debug("entering commit step", "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step)) + + defer func() { + // Done enterCommit: + // keep cs.Round the same, commitRound points to the right Precommits set. + cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit) + cs.CommitRound = commitRound + cs.CommitTime = cmttime.Now() + cs.newStep() + + // Maybe finalize immediately. + cs.tryFinalizeCommit(height) + }() + + blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority() + if !ok { + panic("RunActionCommit() expects +2/3 precommits") + } + + // The Locked* fields no longer matter. + // Move them over to ProposalBlock if they match the commit hash, + // otherwise they'll be cleared in updateToState. + if cs.LockedBlock.HashesTo(blockID.Hash) { + logger.Debug("commit is for a locked block; set ProposalBlock=LockedBlock", "block_hash", blockID.Hash) + cs.ProposalBlock = cs.LockedBlock + cs.ProposalBlockParts = cs.LockedBlockParts + } + + // If we don't have the block being committed, set up to get it. + if !cs.ProposalBlock.HashesTo(blockID.Hash) { + if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) { + logger.Info( + "commit is for a block we do not know about; set ProposalBlock=nil", + "proposal", log.NewLazyBlockHash(cs.ProposalBlock), + "commit", blockID.Hash, + ) + + // We're getting the wrong block. + // Set up ProposalBlockParts and keep waiting. + cs.ProposalBlock = nil + cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader) + + if err := cs.eventBus.PublishEventValidBlock(cs.RoundStateEvent()); err != nil { + logger.Error("failed publishing valid block", "err", err) + } + + cs.evsw.FireEvent(types.EventValidBlock, &cs.RoundState) + } + } +} + +// If we have the block AND +2/3 commits for it, finalize. +func (cs *State) tryFinalizeCommit(height int64) { + logger := cs.Logger.With("height", height) + + if cs.Height != height { + panic(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) + } + + blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() + if !ok || len(blockID.Hash) == 0 { + logger.Error("failed attempt to finalize commit; there was no +2/3 majority or +2/3 was for nil") + return + } + + if !cs.ProposalBlock.HashesTo(blockID.Hash) { + // TODO: this happens every time if we're not a validator (ugly logs) + // TODO: ^^ wait, why does it matter that we're a validator? + logger.Debug( + "failed attempt to finalize commit; we do not have the commit block", + "proposal_block", log.NewLazyBlockHash(cs.ProposalBlock), + "commit_block", blockID.Hash, + ) + return + } + + cs.finalizeCommit(height) +} + +// Increment height and goto cstypes.RoundStepNewHeight +func (cs *State) finalizeCommit(height int64) { + logger := cs.Logger.With("height", height) + + if cs.Height != height || cs.Step != cstypes.RoundStepCommit { + logger.Debug( + "entering finalize commit step", + "current", log.NewLazySprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step), + ) + return + } + + cs.calculatePrevoteMessageDelayMetrics() + + blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() + block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts + + if !ok { + panic("cannot finalize commit; commit does not have 2/3 majority") + } + if !blockParts.HasHeader(blockID.PartSetHeader) { + panic("expected ProposalBlockParts header to be commit header") + } + if !block.HashesTo(blockID.Hash) { + panic("cannot finalize commit; proposal block does not hash to commit hash") + } + + if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil { + panic(fmt.Errorf("+2/3 committed an invalid block: %w", err)) + } + + cs.calculatePrecommitMessageDelayMetrics() + + logger.Info( + "finalizing commit of block", + "hash", log.NewLazyBlockHash(block), + "root", block.AppHash, + "num_txs", len(block.Txs), + ) + logger.Debug("committed block", "block", log.NewLazySprintf("%v", block)) + + fail.Fail() // XXX + + // Save to blockStore. + if cs.blockStore.Height() < block.Height { + // NOTE: the seenCommit is local justification to commit this block, + // but may differ from the LastCommit included in the next block + seenExtendedCommit := cs.Votes.Precommits(cs.CommitRound).MakeExtendedCommit(cs.state.ConsensusParams.ABCI) + if cs.state.ConsensusParams.ABCI.VoteExtensionsEnabled(block.Height) { + cs.blockStore.SaveBlockWithExtendedCommit(block, blockParts, seenExtendedCommit) + } else { + cs.blockStore.SaveBlock(block, blockParts, seenExtendedCommit.ToCommit()) + } + } else { + // Happens during replay if we already saved the block but didn't commit + logger.Debug("calling finalizeCommit on already stored block", "height", block.Height) + } + + fail.Fail() // XXX + + // Write EndHeightMessage{} for this height, implying that the blockstore + // has saved the block. + // + // If we crash before writing this EndHeightMessage{}, we will recover by + // running ApplyBlock during the ABCI handshake when we restart. If we + // didn't save the block to the blockstore before writing + // EndHeightMessage{}, we'd have to change WAL replay -- currently it + // complains about replaying for heights where an #ENDHEIGHT entry already + // exists. + // + // Either way, the State should not be resumed until we + // successfully call ApplyBlock (ie. later here, or in Handshake after + // restart). + endMsg := EndHeightMessage{height} + if err := cs.wal.WriteSync(endMsg); err != nil { // NOTE: fsync + panic(fmt.Sprintf( + "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node", + endMsg, err, + )) + } + + fail.Fail() // XXX + + // Create a copy of the state for staging and an event cache for txs. + stateCopy := cs.state.Copy() + + // Execute and commit the block, update and save the state, and update the mempool. + // We use apply verified block here because we have verified the block in this function already. + // NOTE The block.AppHash won't reflect these txs until the next block. + stateCopy, err := cs.blockExec.ApplyVerifiedBlock( + stateCopy, + types.BlockID{ + Hash: block.Hash(), + PartSetHeader: blockParts.Header(), + }, + block, + ) + if err != nil { + panic(fmt.Sprintf("failed to apply block; error %v", err)) + } + + fail.Fail() // XXX + + // must be called before we update state + cs.recordMetrics(height, block) + + // NewHeightStep! + cs.updateToState(stateCopy) + + fail.Fail() // XXX + + // Private validator might have changed it's key pair => refetch pubkey. + if err := cs.updatePrivValidatorPubKey(); err != nil { + logger.Error("failed to get private validator pubkey", "err", err) + } + + // cs.StartTime is already set. + // Schedule Round0 to start soon. + cs.scheduleRound0(&cs.RoundState) + + // By here, + // * cs.Height has been increment to height+1 + // * cs.Step is now cstypes.RoundStepNewHeight + // * cs.StartTime is set to when we will start round0. +} + +func (cs *State) recordMetrics(height int64, block *types.Block) { + cs.metrics.Validators.Set(float64(cs.Validators.Size())) + cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower())) + + var ( + missingValidators int + missingValidatorsPower int64 + ) + // height=0 -> MissingValidators and MissingValidatorsPower are both 0. + // Remember that the first LastCommit is intentionally empty, so it's not + // fair to increment missing validators number. + if height > cs.state.InitialHeight { + // Sanity check that commit size matches validator set size - only applies + // after first block. + var ( + commitSize = block.LastCommit.Size() + valSetLen = len(cs.LastValidators.Validators) + address types.Address + ) + if commitSize != valSetLen { + panic(fmt.Sprintf("commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v", + commitSize, valSetLen, block.Height, block.LastCommit.Signatures, cs.LastValidators.Validators)) + } + + if cs.privValidator != nil { + if cs.privValidatorPubKey == nil { + // Metrics won't be updated, but it's not critical. + cs.Logger.Error(fmt.Sprintf("recordMetrics: %v", errPubKeyIsNotSet)) + } else { + address = cs.privValidatorPubKey.Address() + } + } + + for i, val := range cs.LastValidators.Validators { + commitSig := block.LastCommit.Signatures[i] + if commitSig.BlockIDFlag == types.BlockIDFlagAbsent { + missingValidators++ + missingValidatorsPower += val.VotingPower + } + + if bytes.Equal(val.Address, address) { + label := []string{ + "validator_address", val.Address.String(), + } + cs.metrics.ValidatorPower.With(label...).Set(float64(val.VotingPower)) + if commitSig.BlockIDFlag == types.BlockIDFlagCommit { + cs.metrics.ValidatorLastSignedHeight.With(label...).Set(float64(height)) + } else { + cs.metrics.ValidatorMissedBlocks.With(label...).Add(float64(1)) + } + } + + } + } + cs.metrics.MissingValidators.Set(float64(missingValidators)) + cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower)) + + // NOTE: byzantine validators power and count is only for consensus evidence i.e. duplicate vote + var ( + byzantineValidatorsPower = int64(0) + byzantineValidatorsCount = int64(0) + ) + for _, ev := range block.Evidence.Evidence { + if dve, ok := ev.(*types.DuplicateVoteEvidence); ok { + if _, val := cs.Validators.GetByAddress(dve.VoteA.ValidatorAddress); val != nil { + byzantineValidatorsCount++ + byzantineValidatorsPower += val.VotingPower + } + } + } + cs.metrics.ByzantineValidators.Set(float64(byzantineValidatorsCount)) + cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) + + if height > 1 { + lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1) + if lastBlockMeta != nil { + cs.metrics.BlockIntervalSeconds.Observe( + block.Time.Sub(lastBlockMeta.Header.Time).Seconds(), + ) + } + } + + cs.metrics.NumTxs.Set(float64(len(block.Txs))) + cs.metrics.TotalTxs.Add(float64(len(block.Txs))) + cs.metrics.BlockSizeBytes.Set(float64(block.Size())) + cs.metrics.ChainSizeBytes.Add(float64(block.Size())) + cs.metrics.CommittedHeight.Set(float64(block.Height)) +} + +//----------------------------------------------------------------------------- + +func (cs *State) defaultSetProposal(proposal *types.Proposal) error { + // Already have one + // TODO: possibly catch double proposals + if cs.Proposal != nil { + return nil + } + + // Does not apply + if proposal.Height != cs.Height || proposal.Round != cs.Round { + return nil + } + + // Verify POLRound, which must be -1 or in range [0, proposal.Round). + if proposal.POLRound < -1 || + (proposal.POLRound >= 0 && proposal.POLRound >= proposal.Round) { + return ErrInvalidProposalPOLRound + } + + p := proposal.ToProto() + // Verify signature + pubKey := cs.Validators.GetProposer().PubKey + if !pubKey.VerifySignature( + types.ProposalSignBytes(cs.state.ChainID, p), proposal.Signature, + ) { + return ErrInvalidProposalSignature + } + + // Validate the proposed block size, derived from its PartSetHeader + maxBytes := cs.state.ConsensusParams.Block.MaxBytes + if maxBytes == -1 { + maxBytes = int64(types.MaxBlockSizeBytes) + } + if int64(proposal.BlockID.PartSetHeader.Total) > (maxBytes-1)/int64(types.BlockPartSizeBytes)+1 { + return ErrProposalTooManyParts + } + + proposal.Signature = p.Signature + cs.Proposal = proposal + // We don't update cs.ProposalBlockParts if it is already set. + // This happens if we're already in cstypes.RoundStepCommit or if there is a valid block in the current round. + // TODO: We can check if Proposal is for a different block as this is a sign of misbehavior! + if cs.ProposalBlockParts == nil { + cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockID.PartSetHeader) + } + + cs.Logger.Info("received proposal", "proposal", proposal, "proposer", pubKey.Address()) + return nil +} + +// NOTE: block is not necessarily valid. +// Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit, +// once we have the full block. +func (cs *State) addProposalBlockPart(msg *BlockPartMessage, peerID p2p.ID) (added bool, err error) { + height, round, part := msg.Height, msg.Round, msg.Part + + // Blocks might be reused, so round mismatch is OK + if cs.Height != height { + cs.Logger.Debug("received block part from wrong height", "height", height, "round", round) + cs.metrics.BlockGossipPartsReceived.With("matches_current", "false").Add(1) + return false, nil + } + + // We're not expecting a block part. + if cs.ProposalBlockParts == nil { + cs.metrics.BlockGossipPartsReceived.With("matches_current", "false").Add(1) + // NOTE: this can happen when we've gone to a higher round and + // then receive parts from the previous round - not necessarily a bad peer. + cs.Logger.Debug( + "received a block part when we are not expecting any", + "height", height, + "round", round, + "index", part.Index, + "peer", peerID, + ) + return false, nil + } + + added, err = cs.ProposalBlockParts.AddPart(part) + if err != nil { + if errors.Is(err, types.ErrPartSetInvalidProof) || errors.Is(err, types.ErrPartSetUnexpectedIndex) { + cs.metrics.BlockGossipPartsReceived.With("matches_current", "false").Add(1) + } + return added, err + } + + cs.metrics.BlockGossipPartsReceived.With("matches_current", "true").Add(1) + if !added { + // NOTE: we are disregarding possible duplicates above where heights dont match or we're not expecting block parts yet + // but between the matches_current = true and false, we have all the info. + cs.metrics.DuplicateBlockPart.Add(1) + } + + maxBytes := cs.state.ConsensusParams.Block.MaxBytes + if maxBytes == -1 { + maxBytes = int64(types.MaxBlockSizeBytes) + } + if cs.ProposalBlockParts.ByteSize() > maxBytes { + return added, fmt.Errorf("total size of proposal block parts exceeds maximum block bytes (%d > %d)", + cs.ProposalBlockParts.ByteSize(), maxBytes, + ) + } + if added && cs.ProposalBlockParts.IsComplete() { + bz, err := io.ReadAll(cs.ProposalBlockParts.GetReader()) + if err != nil { + return added, err + } + + pbb := new(cmtproto.Block) + err = proto.Unmarshal(bz, pbb) + if err != nil { + return added, err + } + + block, err := types.BlockFromProto(pbb) + if err != nil { + return added, err + } + + cs.ProposalBlock = block + + // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal + cs.Logger.Info("received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash()) + + if err := cs.eventBus.PublishEventCompleteProposal(cs.CompleteProposalEvent()); err != nil { + cs.Logger.Error("failed publishing event complete proposal", "err", err) + } + } + return added, nil +} + +func (cs *State) handleCompleteProposal(blockHeight int64) { + // Update Valid* if we can. + prevotes := cs.Votes.Prevotes(cs.Round) + blockID, hasTwoThirds := prevotes.TwoThirdsMajority() + if hasTwoThirds && !blockID.IsZero() && (cs.ValidRound < cs.Round) { + if cs.ProposalBlock.HashesTo(blockID.Hash) { + cs.Logger.Debug( + "updating valid block to new proposal block", + "valid_round", cs.Round, + "valid_block_hash", log.NewLazyBlockHash(cs.ProposalBlock), + ) + + cs.ValidRound = cs.Round + cs.ValidBlock = cs.ProposalBlock + cs.ValidBlockParts = cs.ProposalBlockParts + } + // TODO: In case there is +2/3 majority in Prevotes set for some + // block and cs.ProposalBlock contains different block, either + // proposer is faulty or voting power of faulty processes is more + // than 1/3. We should trigger in the future accountability + // procedure at this point. + } + + if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() { + // Move onto the next step + cs.enterPrevote(blockHeight, cs.Round) + if hasTwoThirds { // this is optimisation as this will be triggered when prevote is added + cs.enterPrecommit(blockHeight, cs.Round) + } + } else if cs.Step == cstypes.RoundStepCommit { + // If we're waiting on the proposal block... + cs.tryFinalizeCommit(blockHeight) + } +} + +// Attempt to add the vote. if its a duplicate signature, dupeout the validator +func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) { + added, err := cs.addVote(vote, peerID) + // NOTE: some of these errors are swallowed here + if err != nil { + // If the vote height is off, we'll just ignore it, + // But if it's a conflicting sig, add it to the cs.evpool. + // If it's otherwise invalid, punish peer. + //nolint: gocritic + if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { + if cs.privValidatorPubKey == nil { + return false, errPubKeyIsNotSet + } + + if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) { + cs.Logger.Error( + "found conflicting vote from ourselves; did you unsafe_reset a validator?", + "height", vote.Height, + "round", vote.Round, + "type", vote.Type, + ) + + return added, err + } + + // report conflicting votes to the evidence pool + cs.evpool.ReportConflictingVotes(voteErr.VoteA, voteErr.VoteB) + cs.Logger.Debug( + "found and sent conflicting votes to the evidence pool", + "vote_a", voteErr.VoteA, + "vote_b", voteErr.VoteB, + ) + + return added, err + } else if errors.Is(err, types.ErrVoteNonDeterministicSignature) { + cs.Logger.Debug("vote has non-deterministic signature", "err", err) + } else if errors.Is(err, types.ErrInvalidVoteExtension) { + cs.Logger.Debug("vote has invalid extension") + } else { + // Either + // 1) bad peer OR + // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR + // 3) tmkms use with multiple validators connecting to a single tmkms instance + // (https://github.com/tendermint/tendermint/issues/3839). + cs.Logger.Info("failed attempting to add vote", "err", err) + return added, ErrAddingVote + } + } + + return added, nil +} + +func (cs *State) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) { + cs.Logger.Debug( + "adding vote", + "vote_height", vote.Height, + "vote_type", vote.Type, + "val_index", vote.ValidatorIndex, + "cs_height", cs.Height, + "extLen", len(vote.Extension), + "extSigLen", len(vote.ExtensionSignature), + ) + + if vote.Height < cs.Height || (vote.Height == cs.Height && vote.Round < cs.Round) { + cs.metrics.MarkLateVote(vote.Type) + } + + // A precommit for the previous height? + // These come in while we wait timeoutCommit + if vote.Height+1 == cs.Height && vote.Type == cmtproto.PrecommitType { + if cs.Step != cstypes.RoundStepNewHeight { + // Late precommit at prior height is ignored + cs.Logger.Debug("precommit vote came in after commit timeout and has been ignored", "vote", vote) + return added, err + } + + added, err = cs.LastCommit.AddVote(vote) + if !added { + // If the vote wasnt added but there's no error, its a duplicate vote + if err == nil { + cs.metrics.DuplicateVote.Add(1) + } + return added, err + } + + cs.Logger.Debug("added vote to last precommits", "last_commit", cs.LastCommit.StringShort()) + if err := cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote}); err != nil { + return added, err + } + + cs.evsw.FireEvent(types.EventVote, vote) + + // if we can skip timeoutCommit and have all the votes now, + if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() { + // go straight to new round (skip timeout commit) + // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight) + cs.enterNewRound(cs.Height, 0) + } + + return added, err + } + + // Height mismatch is ignored. + // Not necessarily a bad peer, but not favorable behavior. + if vote.Height != cs.Height { + cs.Logger.Debug("vote ignored and not added", "vote_height", vote.Height, "cs_height", cs.Height, "peer", peerID) + return added, err + } + + // Check to see if the chain is configured to extend votes. + extEnabled := cs.state.ConsensusParams.ABCI.VoteExtensionsEnabled(vote.Height) + if extEnabled { + // The chain is configured to extend votes, check that the vote is + // not for a nil block and verify the extensions signature against the + // corresponding public key. + + var myAddr []byte + if cs.privValidatorPubKey != nil { + myAddr = cs.privValidatorPubKey.Address() + } + // Verify VoteExtension if precommit and not nil + // https://github.com/tendermint/tendermint/issues/8487 + if vote.Type == cmtproto.PrecommitType && !vote.BlockID.IsZero() && + !bytes.Equal(vote.ValidatorAddress, myAddr) { // Skip the VerifyVoteExtension call if the vote was issued by this validator. + + // The core fields of the vote message were already validated in the + // consensus reactor when the vote was received. + // Here, we verify the signature of the vote extension included in the vote + // message. + _, val := cs.state.Validators.GetByIndex(vote.ValidatorIndex) + if val == nil { // TODO: we should disconnect from this malicious peer + valsCount := cs.state.Validators.Size() + cs.Logger.Info("Peer sent us vote with invalid ValidatorIndex", + "peer", peerID, + "validator_index", vote.ValidatorIndex, + "len_validators", valsCount) + return added, ErrInvalidVote{Reason: fmt.Sprintf("ValidatorIndex %d is out of bounds [0, %d)", vote.ValidatorIndex, valsCount)} + } + if err := vote.VerifyExtension(cs.state.ChainID, val.PubKey); err != nil { + return false, err + } + + err := cs.blockExec.VerifyVoteExtension(context.TODO(), vote) + cs.metrics.MarkVoteExtensionReceived(err == nil) + if err != nil { + return false, err + } + } + } else { + // Vote extensions are not enabled on the network. + // Reject the vote, as it is malformed + // + // TODO punish a peer if it sent a vote with an extension when the feature + // is disabled on the network. + // https://github.com/tendermint/tendermint/issues/8565 + if len(vote.Extension) > 0 || len(vote.ExtensionSignature) > 0 { + return false, fmt.Errorf("received vote with vote extension for height %v (extensions disabled) from peer ID %s", vote.Height, peerID) + } + } + + height := cs.Height + added, err = cs.Votes.AddVote(vote, peerID, extEnabled) + if !added { + // Either duplicate, or error upon cs.Votes.AddByIndex() + + // If the vote wasnt added but there's no error, its a duplicate vote + if err == nil { + cs.metrics.DuplicateVote.Add(1) + } + return added, err + } + if vote.Round == cs.Round { + vals := cs.state.Validators + _, val := vals.GetByIndex(vote.ValidatorIndex) + cs.metrics.MarkVoteReceived(vote.Type, val.VotingPower, vals.TotalVotingPower()) + } + + if err := cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote}); err != nil { + return added, err + } + cs.evsw.FireEvent(types.EventVote, vote) + + switch vote.Type { + case cmtproto.PrevoteType: + prevotes := cs.Votes.Prevotes(vote.Round) + cs.Logger.Debug("added vote to prevote", "vote", vote, "prevotes", prevotes.StringShort()) + + // If +2/3 prevotes for a block or nil for *any* round: + if blockID, ok := prevotes.TwoThirdsMajority(); ok { + // There was a polka! + // If we're locked but this is a recent polka, unlock. + // If it matches our ProposalBlock, update the ValidBlock + + // Unlock if `cs.LockedRound < vote.Round <= cs.Round` + // NOTE: If vote.Round > cs.Round, we'll deal with it when we get to vote.Round + if (cs.LockedBlock != nil) && + (cs.LockedRound < vote.Round) && + (vote.Round <= cs.Round) && + !cs.LockedBlock.HashesTo(blockID.Hash) { + + cs.Logger.Debug("unlocking because of POL", "locked_round", cs.LockedRound, "pol_round", vote.Round) + + cs.LockedRound = -1 + cs.LockedBlock = nil + cs.LockedBlockParts = nil + + if err := cs.eventBus.PublishEventUnlock(cs.RoundStateEvent()); err != nil { + return added, err + } + } + + // Update Valid* if we can. + // NOTE: our proposal block may be nil or not what received a polka.. + if len(blockID.Hash) != 0 && (cs.ValidRound < vote.Round) && (vote.Round == cs.Round) { + if cs.ProposalBlock.HashesTo(blockID.Hash) { + cs.Logger.Debug("updating valid block because of POL", "valid_round", cs.ValidRound, "pol_round", vote.Round) + cs.ValidRound = vote.Round + cs.ValidBlock = cs.ProposalBlock + cs.ValidBlockParts = cs.ProposalBlockParts + } else { + cs.Logger.Debug( + "valid block we do not know about; set ProposalBlock=nil", + "proposal", log.NewLazyBlockHash(cs.ProposalBlock), + "block_id", blockID.Hash, + ) + + // we're getting the wrong block + cs.ProposalBlock = nil + } + + if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) { + cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader) + } + + cs.evsw.FireEvent(types.EventValidBlock, &cs.RoundState) + if err := cs.eventBus.PublishEventValidBlock(cs.RoundStateEvent()); err != nil { + return added, err + } + } + } + + // If +2/3 prevotes for *anything* for future round: + switch { + case cs.Round < vote.Round && prevotes.HasTwoThirdsAny(): + // Round-skip if there is any 2/3+ of votes ahead of us + cs.enterNewRound(height, vote.Round) + + case cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step: // current round + blockID, ok := prevotes.TwoThirdsMajority() + if ok && (cs.isProposalComplete() || len(blockID.Hash) == 0) { + cs.enterPrecommit(height, vote.Round) + } else if prevotes.HasTwoThirdsAny() { + cs.enterPrevoteWait(height, vote.Round) + } + + case cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round: + // If the proposal is now complete, enter prevote of cs.Round. + if cs.isProposalComplete() { + cs.enterPrevote(height, cs.Round) + } + } + + case cmtproto.PrecommitType: + precommits := cs.Votes.Precommits(vote.Round) + cs.Logger.Debug("added vote to precommit", + "height", vote.Height, + "round", vote.Round, + "validator", vote.ValidatorAddress.String(), + "vote_timestamp", vote.Timestamp, + "data", precommits.LogString()) + + blockID, ok := precommits.TwoThirdsMajority() + if ok { + // Executed as TwoThirdsMajority could be from a higher round + cs.enterNewRound(height, vote.Round) + cs.enterPrecommit(height, vote.Round) + + if len(blockID.Hash) != 0 { + cs.enterCommit(height, vote.Round) + if cs.config.SkipTimeoutCommit && precommits.HasAll() { + cs.enterNewRound(cs.Height, 0) + } + } else { + cs.enterPrecommitWait(height, vote.Round) + } + } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() { + cs.enterNewRound(height, vote.Round) + cs.enterPrecommitWait(height, vote.Round) + } + + default: + panic(fmt.Sprintf("unexpected vote type %v", vote.Type)) + } + + return added, err +} + +// CONTRACT: cs.privValidator is not nil. +func (cs *State) signVote( + msgType cmtproto.SignedMsgType, + hash []byte, + header types.PartSetHeader, + block *types.Block, +) (*types.Vote, error) { + // Flush the WAL. Otherwise, we may not recompute the same vote to sign, + // and the privValidator will refuse to sign anything. + if err := cs.wal.FlushAndSync(); err != nil { + return nil, err + } + + if cs.privValidatorPubKey == nil { + return nil, errPubKeyIsNotSet + } + + addr := cs.privValidatorPubKey.Address() + valIdx, _ := cs.Validators.GetByAddress(addr) + + vote := &types.Vote{ + ValidatorAddress: addr, + ValidatorIndex: valIdx, + Height: cs.Height, + Round: cs.Round, + Timestamp: cs.voteTime(), + Type: msgType, + BlockID: types.BlockID{Hash: hash, PartSetHeader: header}, + } + + extEnabled := cs.state.ConsensusParams.ABCI.VoteExtensionsEnabled(vote.Height) + if msgType == cmtproto.PrecommitType && !vote.BlockID.IsZero() { + // if the signedMessage type is for a non-nil precommit, add + // VoteExtension + if extEnabled { + ext, err := cs.blockExec.ExtendVote(context.TODO(), vote, block, cs.state) + if err != nil { + return nil, err + } + vote.Extension = ext + } + } + + recoverable, err := types.SignAndCheckVote(vote, cs.privValidator, cs.state.ChainID, extEnabled && (msgType == cmtproto.PrecommitType)) + if err != nil && !recoverable { + panic(fmt.Sprintf("non-recoverable error when signing vote %v: %v", vote, err)) + } + + return vote, err +} + +func (cs *State) voteTime() time.Time { + now := cmttime.Now() + minVoteTime := now + // Minimum time increment between blocks + const timeIota = time.Millisecond + // TODO: We should remove next line in case we don't vote for v in case cs.ProposalBlock == nil, + // even if cs.LockedBlock != nil. See https://github.com/cometbft/cometbft/tree/v0.38.x/spec/. + if cs.LockedBlock != nil { + // See the BFT time spec + // https://github.com/cometbft/cometbft/blob/v0.38.x/spec/consensus/bft-time.md + minVoteTime = cs.LockedBlock.Time.Add(timeIota) + } else if cs.ProposalBlock != nil { + minVoteTime = cs.ProposalBlock.Time.Add(timeIota) + } + + if now.After(minVoteTime) { + return now + } + return minVoteTime +} + +// sign the vote and publish on internalMsgQueue +// block information is only used to extend votes (precommit only); should be nil in all other cases +func (cs *State) signAddVote( + msgType cmtproto.SignedMsgType, + hash []byte, + header types.PartSetHeader, + block *types.Block, +) { + if cs.privValidator == nil { // the node does not have a key + return + } + + if cs.privValidatorPubKey == nil { + // Vote won't be signed, but it's not critical. + cs.Logger.Error(fmt.Sprintf("signAddVote: %v", errPubKeyIsNotSet)) + return + } + + // If the node not in the validator set, do nothing. + if !cs.Validators.HasAddress(cs.privValidatorPubKey.Address()) { + return + } + + // TODO: pass pubKey to signVote + vote, err := cs.signVote(msgType, hash, header, block) + if err != nil { + cs.Logger.Error("failed signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err) + return + } + hasExt := len(vote.ExtensionSignature) > 0 + extEnabled := cs.state.ConsensusParams.ABCI.VoteExtensionsEnabled(vote.Height) + if vote.Type == cmtproto.PrecommitType && !vote.BlockID.IsZero() && hasExt != extEnabled { + panic(fmt.Errorf("vote extension absence/presence does not match extensions enabled %t!=%t, height %d, type %v", + hasExt, extEnabled, vote.Height, vote.Type)) + } + cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""}) + cs.Logger.Debug("signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote) +} + +// updatePrivValidatorPubKey get's the private validator public key and +// memoizes it. This func returns an error if the private validator is not +// responding or responds with an error. +func (cs *State) updatePrivValidatorPubKey() error { + if cs.privValidator == nil { + return nil + } + + pubKey, err := cs.privValidator.GetPubKey() + if err != nil { + return err + } + cs.privValidatorPubKey = pubKey + return nil +} + +// look back to check existence of the node's consensus votes before joining consensus +func (cs *State) checkDoubleSigningRisk(height int64) error { + if cs.privValidator != nil && cs.privValidatorPubKey != nil && cs.config.DoubleSignCheckHeight > 0 && height > 0 { + valAddr := cs.privValidatorPubKey.Address() + doubleSignCheckHeight := cs.config.DoubleSignCheckHeight + if doubleSignCheckHeight > height { + doubleSignCheckHeight = height + } + + for i := int64(1); i < doubleSignCheckHeight; i++ { + lastCommit := cs.blockStore.LoadSeenCommit(height - i) + if lastCommit != nil { + for sigIdx, s := range lastCommit.Signatures { + if s.BlockIDFlag == types.BlockIDFlagCommit && bytes.Equal(s.ValidatorAddress, valAddr) { + cs.Logger.Info("found signature from the same key", "sig", s, "idx", sigIdx, "height", height-i) + return ErrSignatureFoundInPastBlocks + } + } + } + } + } + + return nil +} + +// emitPrecommitTimeoutMetrics calculates and emits metrics for votes collected +// during the TimeoutCommit period. +func (cs *State) emitPrecommitTimeoutMetrics(round int32) { + // Count votes and accumulate voting power from LastCommit + // (these are the votes collected during TimeoutCommit for the previous height) + totalVotesCollected := 0 + totalVotingPowerCollected := int64(0) + + for _, vote := range cs.Votes.Precommits(round).List() { + totalVotesCollected++ + _, val := cs.Validators.GetByAddress(vote.ValidatorAddress) + if val != nil { + totalVotingPowerCollected += val.VotingPower + } + } + + // Calculate stake percentage of votes collected during TimeoutCommit + totalPossibleVotingPower := cs.Validators.TotalVotingPower() + var stakePercentage float64 + if totalPossibleVotingPower > 0 { + stakePercentage = float64(totalVotingPowerCollected) / float64(totalPossibleVotingPower) + } + + // Emit metrics showing what was collected during TimeoutCommit + cs.metrics.PrecommitsCounted.Set(float64(totalVotesCollected)) + cs.metrics.PrecommitsStakingPercentage.Set(stakePercentage) + + cs.Logger.Debug("emitted post-quorum precommit metrics", + "votes_collected", totalVotesCollected, + "stake_percentage", stakePercentage) +} + +func (cs *State) calculatePrecommitMessageDelayMetrics() { + if cs.Proposal == nil { + return + } + + ps := cs.Votes.Precommits(cs.Round) + pl := ps.List() + + sort.Slice(pl, func(i, j int) bool { + return pl[i].Timestamp.Before(pl[j].Timestamp) + }) + + var votingPowerSeen int64 + for _, v := range pl { + _, val := cs.Validators.GetByAddress(v.ValidatorAddress) + votingPowerSeen += val.VotingPower + if votingPowerSeen >= cs.Validators.TotalVotingPower()*2/3+1 { + cs.metrics.QuorumPrecommitDelay.With("proposer_address", cs.Validators.GetProposer().Address.String()).Set(v.Timestamp.Sub(cs.Proposal.Timestamp).Seconds()) + break + } + } +} + +func (cs *State) calculatePrevoteMessageDelayMetrics() { + if cs.Proposal == nil { + return + } + + ps := cs.Votes.Prevotes(cs.Round) + pl := ps.List() + + sort.Slice(pl, func(i, j int) bool { + return pl[i].Timestamp.Before(pl[j].Timestamp) + }) + + var votingPowerSeen int64 + for _, v := range pl { + _, val := cs.Validators.GetByAddress(v.ValidatorAddress) + votingPowerSeen += val.VotingPower + if votingPowerSeen >= cs.Validators.TotalVotingPower()*2/3+1 { + cs.metrics.QuorumPrevoteDelay.With("proposer_address", cs.Validators.GetProposer().Address.String()).Set(v.Timestamp.Sub(cs.Proposal.Timestamp).Seconds()) + break + } + } + if ps.HasAll() { + cs.metrics.FullPrevoteDelay.With("proposer_address", cs.Validators.GetProposer().Address.String()).Set(pl[len(pl)-1].Timestamp.Sub(cs.Proposal.Timestamp).Seconds()) + } +} + +//--------------------------------------------------------- + +func CompareHRS(h1 int64, r1 int32, s1 cstypes.RoundStepType, h2 int64, r2 int32, s2 cstypes.RoundStepType) int { + if h1 < h2 { + return -1 + } else if h1 > h2 { + return 1 + } + if r1 < r2 { + return -1 + } else if r1 > r2 { + return 1 + } + if s1 < s2 { + return -1 + } else if s1 > s2 { + return 1 + } + return 0 +} + +// repairWalFile decodes messages from src (until the decoder errors) and +// writes them to dst. +func repairWalFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + var ( + dec = NewWALDecoder(in) + enc = NewWALEncoder(out) + ) + + // best-case repair (until first error is encountered) + for { + msg, err := dec.Decode() + if err != nil { + break + } + + err = enc.Encode(msg) + if err != nil { + return fmt.Errorf("failed to encode msg: %w", err) + } + } + + return nil +} diff --git a/consensus/state_test.go b/consensus/state_test.go new file mode 100644 index 0000000..d196a9f --- /dev/null +++ b/consensus/state_test.go @@ -0,0 +1,2621 @@ +package consensus + +import ( + "bytes" + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + abcimocks "github.com/cometbft/cometbft/abci/types/mocks" + cstypes "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/protoio" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtrand "github.com/cometbft/cometbft/libs/rand" + p2pmock "github.com/cometbft/cometbft/p2p/mock" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +/* + +ProposeSuite +x * TestProposerSelection0 - round robin ordering, round 0 +x * TestProposerSelection2 - round robin ordering, round 2++ +x * TestEnterProposeNoValidator - timeout into prevote round +x * TestEnterPropose - finish propose without timing out (we have the proposal) +x * TestBadProposal - 2 vals, bad proposal (bad block state hash), should prevote and precommit nil +x * TestOversizedBlock - block with too many txs should be rejected +FullRoundSuite +x * TestFullRound1 - 1 val, full successful round +x * TestFullRoundNil - 1 val, full round of nil +x * TestFullRound2 - 2 vals, both required for full round +LockSuite +x * TestLockNoPOL - 2 vals, 4 rounds. one val locked, precommits nil every round except first. +x * TestLockPOLRelock - 4 vals, one precommits, other 3 polka at next round, so we unlock and precomit the polka +x * TestLockPOLUnlock - 4 vals, one precommits, other 3 polka nil at next round, so we unlock and precomit nil +x * TestLockPOLSafety1 - 4 vals. We shouldn't change lock based on polka at earlier round +x * TestLockPOLSafety2 - 4 vals. After unlocking, we shouldn't relock based on polka at earlier round + * TestNetworkLock - once +1/3 precommits, network should be locked + * TestNetworkLockPOL - once +1/3 precommits, the block with more recent polka is committed +SlashingSuite +x * TestSlashingPrevotes - a validator prevoting twice in a round gets slashed +x * TestSlashingPrecommits - a validator precomitting twice in a round gets slashed +CatchupSuite + * TestCatchup - if we might be behind and we've seen any 2/3 prevotes, round skip to new round, precommit, or prevote +HaltSuite +x * TestHalt1 - if we see +2/3 precommits after timing out into new round, we should still commit + +*/ + +//---------------------------------------------------------------------------------------------------- +// ProposeSuite + +func TestStateProposerSelection0(t *testing.T) { + cs1, vss := randState(4) + height, round := cs1.Height, cs1.Round + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + + startTestRound(cs1, height, round) + + // Wait for new round so proposer is set. + ensureNewRound(newRoundCh, height, round) + + // Commit a block and ensure proposer for the next height is correct. + prop := cs1.GetRoundState().Validators.GetProposer() + pv, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + address := pv.Address() + if !bytes.Equal(prop.Address, address) { + t.Fatalf("expected proposer to be validator %d. Got %X", 0, prop.Address) + } + + // Wait for complete proposal. + ensureNewProposal(proposalCh, height, round) + + rs := cs1.GetRoundState() + signAddVotes(cs1, cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), true, vss[1:]...) + + // Wait for new round so next validator is set. + ensureNewRound(newRoundCh, height+1, 0) + + prop = cs1.GetRoundState().Validators.GetProposer() + pv1, err := vss[1].GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + if !bytes.Equal(prop.Address, addr) { + panic(fmt.Sprintf("expected proposer to be validator %d. Got %X", 1, prop.Address)) + } +} + +// Now let's do it all again, but starting from round 2 instead of 0 +func TestStateProposerSelection2(t *testing.T) { + cs1, vss := randState(4) // test needs more work for more than 3 validators + height := cs1.Height + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + + // this time we jump in at round 2 + incrementRound(vss[1:]...) + incrementRound(vss[1:]...) + + var round int32 = 2 + startTestRound(cs1, height, round) + + ensureNewRound(newRoundCh, height, round) // wait for the new round + + // everyone just votes nil. we get a new proposer each round + for i := int32(0); int(i) < len(vss); i++ { + prop := cs1.GetRoundState().Validators.GetProposer() + pvk, err := vss[int(i+round)%len(vss)].GetPubKey() + require.NoError(t, err) + addr := pvk.Address() + correctProposer := addr + if !bytes.Equal(prop.Address, correctProposer) { + panic(fmt.Sprintf( + "expected RoundState.Validators.GetProposer() to be validator %d. Got %X", + int(i+2)%len(vss), + prop.Address)) + } + + rs := cs1.GetRoundState() + signAddVotes(cs1, cmtproto.PrecommitType, nil, rs.ProposalBlockParts.Header(), true, vss[1:]...) + ensureNewRound(newRoundCh, height, i+round+1) // wait for the new round event each round + incrementRound(vss[1:]...) + } +} + +// a non-validator should timeout into the prevote round +func TestStateEnterProposeNoPrivValidator(t *testing.T) { + cs, _ := randState(1) + cs.SetPrivValidator(nil) + height, round := cs.Height, cs.Round + + // Listen for propose timeout event + timeoutCh := subscribe(cs.eventBus, types.EventQueryTimeoutPropose) + + startTestRound(cs, height, round) + + // if we're not a validator, EnterPropose should timeout + ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds()) + + if cs.GetRoundState().Proposal != nil { + t.Error("Expected to make no proposal, since no privValidator") + } +} + +// a validator should not timeout of the prevote round (TODO: unless the block is really big!) +func TestStateEnterProposeYesPrivValidator(t *testing.T) { + cs, _ := randState(1) + height, round := cs.Height, cs.Round + + // Listen for propose timeout event + + timeoutCh := subscribe(cs.eventBus, types.EventQueryTimeoutPropose) + proposalCh := subscribe(cs.eventBus, types.EventQueryCompleteProposal) + + cs.enterNewRound(height, round) + cs.startRoutines(3) + + ensureNewProposal(proposalCh, height, round) + + // Check that Proposal, ProposalBlock, ProposalBlockParts are set. + rs := cs.GetRoundState() + if rs.Proposal == nil { + t.Error("rs.Proposal should be set") + } + if rs.ProposalBlock == nil { + t.Error("rs.ProposalBlock should be set") + } + if rs.ProposalBlockParts.Total() == 0 { + t.Error("rs.ProposalBlockParts should be set") + } + + // if we're a validator, enterPropose should not timeout + ensureNoNewTimeout(timeoutCh, cs.config.TimeoutPropose.Nanoseconds()) +} + +func TestStateBadProposal(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(2) + height, round := cs1.Height, cs1.Round + vs2 := vss[1] + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + voteCh := subscribe(cs1.eventBus, types.EventQueryVote) + + propBlock, err := cs1.createProposalBlock(ctx) // changeProposer(t, cs1, vs2) + require.NoError(t, err) + + // make the second validator the proposer by incrementing round + round++ + incrementRound(vss[1:]...) + + // make the block bad by tampering with statehash + stateHash := propBlock.AppHash + if len(stateHash) == 0 { + stateHash = make([]byte, 32) + } + stateHash[0] = (stateHash[0] + 1) % 255 + propBlock.AppHash = stateHash + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + proposal := types.NewProposal(vs2.Height, round, -1, blockID) + p := proposal.ToProto() + if err := vs2.SignProposal(cs1.state.ChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + + proposal.Signature = p.Signature + + // set the proposal block + if err := cs1.SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + // start the machine + startTestRound(cs1, height, round) + + // wait for proposal + ensureProposal(proposalCh, height, round, blockID) + + // wait for prevote + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], nil) + + // add bad prevote from vs2 and wait for it + bps, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + signAddVotes(cs1, cmtproto.PrevoteType, propBlock.Hash(), bps.Header(), false, vs2) + ensurePrevote(voteCh, height, round) + + // wait for precommit + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + bps2, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes(cs1, cmtproto.PrecommitType, propBlock.Hash(), bps2.Header(), true, vs2) +} + +func TestStateOversizedBlock(t *testing.T) { + const maxBytes = int64(types.BlockPartSizeBytes) + + for _, testCase := range []struct { + name string + oversized bool + }{ + { + name: "max size, correct block", + oversized: false, + }, + { + name: "off-by-1 max size, incorrect block", + oversized: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + cs1, vss := randState(2) + cs1.state.ConsensusParams.Block.MaxBytes = maxBytes + height, round := cs1.Height, cs1.Round + vs2 := vss[1] + + partSize := types.BlockPartSizeBytes + + propBlock, propBlockParts := findBlockSizeLimit(t, height, maxBytes, cs1, partSize, testCase.oversized) + + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + voteCh := subscribe(cs1.eventBus, types.EventQueryVote) + + // make the second validator the proposer by incrementing round + round++ + incrementRound(vss[1:]...) + + blockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} + proposal := types.NewProposal(height, round, -1, blockID) + p := proposal.ToProto() + if err := vs2.SignProposal(cs1.state.ChainID, p); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + proposal.Signature = p.Signature + + totalBytes := 0 + for i := 0; i < int(propBlockParts.Total()); i++ { + part := propBlockParts.GetPart(i) + totalBytes += len(part.Bytes) + } + + maxBlockParts := maxBytes / int64(types.BlockPartSizeBytes) + if maxBytes > maxBlockParts*int64(types.BlockPartSizeBytes) { + maxBlockParts++ + } + numBlockParts := int64(propBlockParts.Total()) + + if err := cs1.SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + // start the machine + startTestRound(cs1, height, round) + + t.Log("Block Sizes;", "Limit", maxBytes, "Current", totalBytes) + t.Log("Proposal Parts;", "Maximum", maxBlockParts, "Current", numBlockParts) + + validateHash := propBlock.Hash() + lockedRound := int32(1) + if testCase.oversized { + validateHash = nil + lockedRound = -1 + // if the block is oversized cs1 should log an error with the block part message as it exceeds + // the consensus params. The block is not added to cs.ProposalBlock so the node timeouts. + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + // and then should send nil prevote and precommit regardless of whether other validators prevote and + // precommit on it + } + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], validateHash) + + // Should not accept a Proposal with too many block parts + if numBlockParts > maxBlockParts { + require.Nil(t, cs1.Proposal) + } + + bps, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + signAddVotes(cs1, cmtproto.PrevoteType, propBlock.Hash(), bps.Header(), false, vs2) + ensurePrevote(voteCh, height, round) + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, lockedRound, vss[0], validateHash, validateHash) + + bps2, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes(cs1, cmtproto.PrecommitType, propBlock.Hash(), bps2.Header(), true, vs2) + }) + } +} + +//---------------------------------------------------------------------------------------------------- +// FullRoundSuite + +// propose, prevote, and precommit a block +func TestStateFullRound1(t *testing.T) { + cs, vss := randState(1) + height, round := cs.Height, cs.Round + + // NOTE: buffer capacity of 0 ensures we can validate prevote and last commit + // before consensus can move to the next height (and cause a race condition) + if err := cs.eventBus.Stop(); err != nil { + t.Error(err) + } + eventBus := types.NewEventBusWithBufferCapacity(0) + eventBus.SetLogger(log.TestingLogger().With("module", "events")) + cs.SetEventBus(eventBus) + if err := eventBus.Start(); err != nil { + t.Error(err) + } + + voteCh := subscribeUnBuffered(cs.eventBus, types.EventQueryVote) + propCh := subscribe(cs.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs.eventBus, types.EventQueryNewRound) + + // Maybe it would be better to call explicitly startRoutines(4) + startTestRound(cs, height, round) + + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(propCh, height, round) + propBlockHash := cs.GetRoundState().ProposalBlock.Hash() + + ensurePrevote(voteCh, height, round) // wait for prevote + validatePrevote(t, cs, round, vss[0], propBlockHash) + + ensurePrecommit(voteCh, height, round) // wait for precommit + + // we're going to roll right into new height + ensureNewRound(newRoundCh, height+1, 0) + + validateLastPrecommit(t, cs, vss[0], propBlockHash) +} + +// nil is proposed, so prevote and precommit nil +func TestStateFullRoundNil(t *testing.T) { + cs, _ := randState(1) + height, round := cs.Height, cs.Round + + voteCh := subscribeUnBuffered(cs.eventBus, types.EventQueryVote) + + cs.enterPrevote(height, round) + cs.startRoutines(4) + + ensurePrevoteMatch(t, voteCh, height, round, nil) // prevote + ensurePrecommitMatch(t, voteCh, height, round, nil) // precommit +} + +// run through propose, prevote, precommit commit with two validators +// where the first validator has to wait for votes from the second +func TestStateFullRound2(t *testing.T) { + cs1, vss := randState(2) + vs2 := vss[1] + height, round := cs1.Height, cs1.Round + + voteCh := subscribeUnBuffered(cs1.eventBus, types.EventQueryVote) + newBlockCh := subscribe(cs1.eventBus, types.EventQueryNewBlock) + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + + ensurePrevote(voteCh, height, round) // prevote + + // we should be stuck in limbo waiting for more prevotes + rs := cs1.GetRoundState() + propBlockHash, propPartSetHeader := rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header() + + // prevote arrives from vs2: + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propPartSetHeader, false, vs2) + ensurePrevote(voteCh, height, round) // prevote + + ensurePrecommit(voteCh, height, round) // precommit + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, vss[0], propBlockHash, propBlockHash) + + // we should be stuck in limbo waiting for more precommits + + // precommit arrives from vs2: + signAddVotes(cs1, cmtproto.PrecommitType, propBlockHash, propPartSetHeader, true, vs2) + ensurePrecommit(voteCh, height, round) + + // wait to finish commit, propose in next height + ensureNewBlock(newBlockCh, height) +} + +//------------------------------------------------------------------------------------------ +// LockSuite + +// two validators, 4 rounds. +// two vals take turns proposing. val1 locks on first one, precommits nil on everything else +func TestStateLockNoPOL(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(2) + vs2 := vss[1] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + voteCh := subscribeUnBuffered(cs1.eventBus, types.EventQueryVote) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + + /* + Round1 (cs1, B) // B B // B B2 + */ + + // start round and wait for prevote + cs1.enterNewRound(height, round) + cs1.startRoutines(0) + + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + roundState := cs1.GetRoundState() + theBlockHash := roundState.ProposalBlock.Hash() + thePartSetHeader := roundState.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) // prevote + + // we should now be stuck in limbo forever, waiting for more prevotes + // prevote arrives from vs2: + signAddVotes(cs1, cmtproto.PrevoteType, theBlockHash, thePartSetHeader, false, vs2) + ensurePrevote(voteCh, height, round) // prevote + + ensurePrecommit(voteCh, height, round) // precommit + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], theBlockHash, theBlockHash) + + // we should now be stuck in limbo forever, waiting for more precommits + // lets add one for a different block + hash := make([]byte, len(theBlockHash)) + copy(hash, theBlockHash) + hash[0] = (hash[0] + 1) % 255 + signAddVotes(cs1, cmtproto.PrecommitType, hash, thePartSetHeader, true, vs2) + ensurePrecommit(voteCh, height, round) // precommit + + // (note we're entering precommit for a second time this round) + // but with invalid args. then we enterPrecommitWait, and the timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + /// + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) + t.Log("#### ONTO ROUND 1") + /* + Round2 (cs1, B) // B B2 + */ + + incrementRound(vs2) + + // now we're on a new round and not the proposer, so wait for timeout + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + rs := cs1.GetRoundState() + + require.Nil(t, rs.ProposalBlock, "Expected proposal block to be nil") + + // wait to finish prevote + ensurePrevote(voteCh, height, round) + // we should have prevoted our locked block + validatePrevote(t, cs1, round, vss[0], rs.LockedBlock.Hash()) + + // add a conflicting prevote from the other validator + bps, err := rs.LockedBlock.MakePartSet(partSize) + require.NoError(t, err) + + signAddVotes(cs1, cmtproto.PrevoteType, hash, bps.Header(), false, vs2) + ensurePrevote(voteCh, height, round) + + // now we're going to enter prevote again, but with invalid args + // and then prevote wait, which should timeout. then wait for precommit + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds()) + + ensurePrecommit(voteCh, height, round) // precommit + // the proposed block should still be locked and our precommit added + // we should precommit nil and be locked on the proposal + validatePrecommit(t, cs1, round, 0, vss[0], nil, theBlockHash) + + // add conflicting precommit from vs2 + bps2, err := rs.LockedBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes(cs1, cmtproto.PrecommitType, hash, bps2.Header(), true, vs2) + ensurePrecommit(voteCh, height, round) + + // (note we're entering precommit for a second time this round, but with invalid args + // then we enterPrecommitWait and timeout into NewRound + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // entering new round + ensureNewRound(newRoundCh, height, round) + t.Log("#### ONTO ROUND 2") + /* + Round3 (vs2, _) // B, B2 + */ + + incrementRound(vs2) + + ensureNewProposal(proposalCh, height, round) + rs = cs1.GetRoundState() + + // now we're on a new round and are the proposer + if !bytes.Equal(rs.ProposalBlock.Hash(), rs.LockedBlock.Hash()) { + panic(fmt.Sprintf( + "Expected proposal block to be locked block. Got %v, Expected %v", + rs.ProposalBlock, + rs.LockedBlock)) + } + + ensurePrevote(voteCh, height, round) // prevote + validatePrevote(t, cs1, round, vss[0], rs.LockedBlock.Hash()) + + bps0, err := rs.ProposalBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes(cs1, cmtproto.PrevoteType, hash, bps0.Header(), false, vs2) + ensurePrevote(voteCh, height, round) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds()) + ensurePrecommit(voteCh, height, round) // precommit + + validatePrecommit(t, cs1, round, 0, vss[0], nil, theBlockHash) // precommit nil but be locked on proposal + + bps1, err := rs.ProposalBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes( + cs1, + cmtproto.PrecommitType, + hash, + bps1.Header(), + true, + vs2) // NOTE: conflicting precommits at same height + ensurePrecommit(voteCh, height, round) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + cs2, _ := randState(2) // needed so generated block is different than locked block + // before we time out into new round, set next proposal block + prop, propBlock := decideProposal(ctx, t, cs2, vs2, vs2.Height, vs2.Round+1) + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with vs2") + } + + incrementRound(vs2) + + round++ // entering new round + ensureNewRound(newRoundCh, height, round) + t.Log("#### ONTO ROUND 3") + /* + Round4 (vs2, C) // B C // B C + */ + + // now we're on a new round and not the proposer + // so set the proposal block + bps3, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + if err := cs1.SetProposalAndBlock(prop, propBlock, bps3, ""); err != nil { + t.Fatal(err) + } + + ensureNewProposal(proposalCh, height, round) + ensurePrevote(voteCh, height, round) // prevote + // prevote for locked block (not proposal) + validatePrevote(t, cs1, 3, vss[0], cs1.LockedBlock.Hash()) + + // prevote for proposed block + bps4, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + signAddVotes(cs1, cmtproto.PrevoteType, propBlock.Hash(), bps4.Header(), false, vs2) + ensurePrevote(voteCh, height, round) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds()) + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, 0, vss[0], nil, theBlockHash) // precommit nil but locked on proposal + + bps5, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes( + cs1, + cmtproto.PrecommitType, + propBlock.Hash(), + bps5.Header(), + true, + vs2) // NOTE: conflicting precommits at same height + ensurePrecommit(voteCh, height, round) +} + +// 4 vals in two rounds, +// in round one: v1 precommits, other 3 only prevote so the block isn't committed +// in round two: v1 prevotes the same block that the node is locked on +// the others prevote a new block hence v1 changes lock and precommits the new block with the others +func TestStateLockPOLRelock(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + newBlockCh := subscribe(cs1.eventBus, types.EventQueryNewBlockHeader) + + // everything done from perspective of cs1 + + /* + Round1 (cs1, B) // B B B B// B nil B nil + + eg. vs2 and vs4 didn't see the 2/3 prevotes + */ + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + theBlockHash := rs.ProposalBlock.Hash() + theBlockParts := rs.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) // prevote + + signAddVotes(cs1, cmtproto.PrevoteType, theBlockHash, theBlockParts, false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) // our precommit + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], theBlockHash, theBlockHash) + + // add precommits from the rest + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + // before we timeout to the new round set the new proposal + cs2 := newState(cs1.state, vs2, kvstore.NewInMemoryApplication()) + prop, propBlock := decideProposal(ctx, t, cs2, vs2, vs2.Height, vs2.Round+1) + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with vs2") + } + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + propBlockHash := propBlock.Hash() + require.NotEqual(t, propBlockHash, theBlockHash) + + incrementRound(vs2, vs3, vs4) + + // timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + // XXX: this isnt guaranteed to get there before the timeoutPropose ... + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + ensureNewRound(newRoundCh, height, round) + t.Log("### ONTO ROUND 1") + + /* + Round2 (vs2, C) // B C C C // C C C _) + + cs1 changes lock! + */ + + // now we're on a new round and not the proposer + // but we should receive the proposal + ensureNewProposal(proposalCh, height, round) + + // go to prevote, node should prevote for locked block (not the new proposal) - this is relocking + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], theBlockHash) + + // now lets add prevotes from everyone else for the new block + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propBlockParts.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // we should have unlocked and locked on the new block, sending a precommit for this new block + validatePrecommit(t, cs1, round, round, vss[0], propBlockHash, propBlockHash) + + // more prevote creating a majority on the new block and this is then committed + signAddVotes(cs1, cmtproto.PrecommitType, propBlockHash, propBlockParts.Header(), true, vs2, vs3) + ensureNewBlockHeader(newBlockCh, height, propBlockHash) + + ensureNewRound(newRoundCh, height+1, 0) +} + +// 4 vals, one precommits, other 3 polka at next round, so we unlock and precomit the polka +func TestStateLockPOLUnlock(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // everything done from perspective of cs1 + + /* + Round1 (cs1, B) // B B B B // B nil B nil + eg. didn't see the 2/3 prevotes + */ + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + theBlockHash := rs.ProposalBlock.Hash() + theBlockParts := rs.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], theBlockHash) + + signAddVotes(cs1, cmtproto.PrevoteType, theBlockHash, theBlockParts, false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], theBlockHash, theBlockHash) + + // add precommits from the rest + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs4) + signAddVotes(cs1, cmtproto.PrecommitType, theBlockHash, theBlockParts, true, vs3) + + // before we time out into new round, set next proposal block + prop, propBlock := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round+1) + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + // timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + rs = cs1.GetRoundState() + lockedBlockHash := rs.LockedBlock.Hash() + + incrementRound(vs2, vs3, vs4) + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + t.Log("#### ONTO ROUND 1") + /* + Round2 (vs2, C) // B nil nil nil // nil nil nil _ + cs1 unlocks! + */ + //XXX: this isnt guaranteed to get there before the timeoutPropose ... + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + ensureNewProposal(proposalCh, height, round) + + // go to prevote, prevote for locked block (not proposal) + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], lockedBlockHash) + // now lets add prevotes from everyone else for nil (a polka!) + signAddVotes(cs1, cmtproto.PrevoteType, nil, types.PartSetHeader{}, false, vs2, vs3, vs4) + + // the polka makes us unlock and precommit nil + ensureNewUnlock(unlockCh, height, round) + ensurePrecommit(voteCh, height, round) + + // we should have unlocked and committed nil + // NOTE: since we don't relock on nil, the lock round is -1 + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3) + ensureNewRound(newRoundCh, height, round+1) +} + +// 4 vals, v1 locks on proposed block in the first round but the other validators only prevote +// In the second round, v1 misses the proposal but sees a majority prevote an unknown block so +// v1 should unlock and precommit nil. In the third round another block is proposed, all vals +// prevote and now v1 can lock onto the third block and precommit that +func TestStateLockPOLUnlockOnUnknownBlock(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + // everything done from perspective of cs1 + + /* + Round0 (cs1, A) // A A A A// A nil nil nil + */ + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + firstBlockHash := rs.ProposalBlock.Hash() + firstBlockParts := rs.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) // prevote + + signAddVotes(cs1, cmtproto.PrevoteType, firstBlockHash, firstBlockParts, false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) // our precommit + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], firstBlockHash, firstBlockHash) + + // add precommits from the rest + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + // before we timeout to the new round set the new proposal + cs2 := newState(cs1.state, vs2, kvstore.NewInMemoryApplication()) + prop, propBlock := decideProposal(ctx, t, cs2, vs2, vs2.Height, vs2.Round+1) + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with vs2") + } + secondBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + secondBlockHash := propBlock.Hash() + require.NotEqual(t, secondBlockHash, firstBlockHash) + + incrementRound(vs2, vs3, vs4) + + // timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + t.Log("### ONTO ROUND 1") + + /* + Round1 (vs2, B) // A B B B // nil nil nil nil) + */ + + // now we're on a new round but v1 misses the proposal + + // go to prevote, node should prevote for locked block (not the new proposal) - this is relocking + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], firstBlockHash) + + // now lets add prevotes from everyone else for the new block + signAddVotes(cs1, cmtproto.PrevoteType, secondBlockHash, secondBlockParts.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // we should have unlocked and locked on the new block, sending a precommit for this new block + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + if err := cs1.SetProposalAndBlock(prop, propBlock, secondBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + // more prevote creating a majority on the new block and this is then committed + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + // before we timeout to the new round set the new proposal + cs3 := newState(cs1.state, vs3, kvstore.NewInMemoryApplication()) + prop, propBlock = decideProposal(ctx, t, cs3, vs3, vs3.Height, vs3.Round+1) + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with vs2") + } + thirdPropBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + thirdPropBlockHash := propBlock.Hash() + require.NotEqual(t, secondBlockHash, thirdPropBlockHash) + + incrementRound(vs2, vs3, vs4) + + // timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) + t.Log("### ONTO ROUND 2") + + /* + Round2 (vs3, C) // C C C C // C nil nil nil) + */ + + if err := cs1.SetProposalAndBlock(prop, propBlock, thirdPropBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + ensurePrevote(voteCh, height, round) + // we are no longer locked to the first block so we should be able to prevote + validatePrevote(t, cs1, round, vss[0], thirdPropBlockHash) + + signAddVotes(cs1, cmtproto.PrevoteType, thirdPropBlockHash, thirdPropBlockParts.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // we have a majority, now vs1 can change lock to the third block + validatePrecommit(t, cs1, round, round, vss[0], thirdPropBlockHash, thirdPropBlockHash) +} + +// 4 vals +// a polka at round 1 but we miss it +// then a polka at round 2 that we lock on +// then we see the polka from round 1 but shouldn't unlock +func TestStateLockPOLSafety1(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + propBlock := rs.ProposalBlock + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlock.Hash()) + + // the others sign a polka but we don't see it + bps, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + prevotes := signVotes(cmtproto.PrevoteType, propBlock.Hash(), bps.Header(), false, vs2, vs3, vs4) + + t.Logf("old prop hash %v", fmt.Sprintf("%X", propBlock.Hash())) + + // we do see them precommit nil + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + // cs1 precommit nil + ensurePrecommit(voteCh, height, round) + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + t.Log("### ONTO ROUND 1") + + prop, propBlock := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round+1) + propBlockHash := propBlock.Hash() + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + incrementRound(vs2, vs3, vs4) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) + + // XXX: this isnt guaranteed to get there before the timeoutPropose ... + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + /*Round2 + // we timeout and prevote our lock + // a polka happened but we didn't see it! + */ + + ensureNewProposal(proposalCh, height, round) + + rs = cs1.GetRoundState() + + if rs.LockedBlock != nil { + panic("we should not be locked!") + } + t.Logf("new prop hash %v", fmt.Sprintf("%X", propBlockHash)) + + // go to prevote, prevote for proposal block + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash) + + // now we see the others prevote for it, so we should lock on it + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propBlockParts.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // we should have precommitted + validatePrecommit(t, cs1, round, round, vss[0], propBlockHash, propBlockHash) + + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + incrementRound(vs2, vs3, vs4) + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + + t.Log("### ONTO ROUND 2") + /*Round3 + we see the polka from round 1 but we shouldn't unlock! + */ + + // timeout of propose + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + // finish prevote + ensurePrevote(voteCh, height, round) + // we should prevote what we're locked on + validatePrevote(t, cs1, round, vss[0], propBlockHash) + + newStepCh := subscribe(cs1.eventBus, types.EventQueryNewRoundStep) + + // before prevotes from the previous round are added + // add prevotes from the earlier round + addVotes(cs1, prevotes...) + + t.Log("Done adding prevotes!") + + ensureNoNewRoundStep(newStepCh) +} + +// 4 vals. +// polka P0 at R0, P1 at R1, and P2 at R2, +// we lock on P0 at R0, don't see P1, and unlock using P2 at R2 +// then we should make sure we don't lock using P1 + +// What we want: +// dont see P0, lock on P1 at R1, dont unlock using P0 at R2 +func TestStateLockPOLSafety2(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // the block for R0: gets polkad but we miss it + // (even though we signed it, shhh) + _, propBlock0 := decideProposal(ctx, t, cs1, vss[0], height, round) + propBlockHash0 := propBlock0.Hash() + propBlockParts0, err := propBlock0.MakePartSet(partSize) + require.NoError(t, err) + propBlockID0 := types.BlockID{Hash: propBlockHash0, PartSetHeader: propBlockParts0.Header()} + + // the others sign a polka but we don't see it + prevotes := signVotes(cmtproto.PrevoteType, propBlockHash0, propBlockParts0.Header(), false, vs2, vs3, vs4) + + // the block for round 1 + prop1, propBlock1 := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round+1) + propBlockHash1 := propBlock1.Hash() + propBlockParts1, err := propBlock1.MakePartSet(partSize) + require.NoError(t, err) + + incrementRound(vs2, vs3, vs4) + + round++ // moving to the next round + t.Log("### ONTO Round 1") + // jump in at round 1 + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + if err := cs1.SetProposalAndBlock(prop1, propBlock1, propBlockParts1, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height, round) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash1) + + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash1, propBlockParts1.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], propBlockHash1, propBlockHash1) + + // add precommits from the rest + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs4) + signAddVotes(cs1, cmtproto.PrecommitType, propBlockHash1, propBlockParts1.Header(), true, vs3) + + incrementRound(vs2, vs3, vs4) + + // timeout of precommit wait to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + // in round 2 we see the polkad block from round 0 + newProp := types.NewProposal(height, round, 0, propBlockID0) + p := newProp.ToProto() + if err := vs3.SignProposal(cs1.state.ChainID, p); err != nil { + t.Fatal(err) + } + + newProp.Signature = p.Signature + + if err := cs1.SetProposalAndBlock(newProp, propBlock0, propBlockParts0, "some peer"); err != nil { + t.Fatal(err) + } + + // Add the pol votes + addVotes(cs1, prevotes...) + + ensureNewRound(newRoundCh, height, round) + t.Log("### ONTO Round 2") + /*Round2 + // now we see the polka from round 1, but we shouldnt unlock + */ + ensureNewProposal(proposalCh, height, round) + + ensureNoNewUnlock(unlockCh) + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash1) +} + +// 4 vals. +// polka P0 at R0 for B0. We lock B0 on P0 at R0. P0 unlocks value at R1. + +// What we want: +// P0 proposes B0 at R3. +func TestProposeValidBlock(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + propBlock := rs.ProposalBlock + propBlockHash := propBlock.Hash() + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash) + + // the others sign a polka + bps, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, bps.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // we should have precommitted + validatePrecommit(t, cs1, round, round, vss[0], propBlockHash, propBlockHash) + + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + incrementRound(vs2, vs3, vs4) + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + + t.Log("### ONTO ROUND 2") + + // timeout of propose + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash) + + signAddVotes(cs1, cmtproto.PrevoteType, nil, types.PartSetHeader{}, false, vs2, vs3, vs4) + + ensureNewUnlock(unlockCh, height, round) + + ensurePrecommit(voteCh, height, round) + // we should have precommitted + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + incrementRound(vs2, vs3, vs4) + incrementRound(vs2, vs3, vs4) + + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + round += 2 // moving to the next round + + ensureNewRound(newRoundCh, height, round) + t.Log("### ONTO ROUND 3") + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + + t.Log("### ONTO ROUND 4") + + ensureNewProposal(proposalCh, height, round) + + rs = cs1.GetRoundState() + assert.True(t, bytes.Equal(rs.ProposalBlock.Hash(), propBlockHash)) + assert.True(t, bytes.Equal(rs.ProposalBlock.Hash(), rs.ValidBlock.Hash())) + assert.True(t, rs.Proposal.POLRound == rs.ValidRound) + assert.True(t, bytes.Equal(rs.Proposal.BlockID.Hash, rs.ValidBlock.Hash())) +} + +// What we want: +// P0 miss to lock B but set valid block to B after receiving delayed prevote. +func TestSetValidBlockOnDelayedPrevote(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + validBlockCh := subscribe(cs1.eventBus, types.EventQueryValidBlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + propBlock := rs.ProposalBlock + propBlockHash := propBlock.Hash() + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], propBlockHash) + + // vs2 send prevote for propBlock + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propBlockParts.Header(), false, vs2) + + // vs3 send prevote nil + signAddVotes(cs1, cmtproto.PrevoteType, nil, types.PartSetHeader{}, false, vs3) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds()) + + ensurePrecommit(voteCh, height, round) + // we should have precommitted + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + rs = cs1.GetRoundState() + + assert.True(t, rs.ValidBlock == nil) + assert.True(t, rs.ValidBlockParts == nil) + assert.True(t, rs.ValidRound == -1) + + // vs2 send (delayed) prevote for propBlock + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propBlockParts.Header(), false, vs4) + + ensureNewValidBlock(validBlockCh, height, round) + + rs = cs1.GetRoundState() + + assert.True(t, bytes.Equal(rs.ValidBlock.Hash(), propBlockHash)) + assert.True(t, rs.ValidBlockParts.Header().Equals(propBlockParts.Header())) + assert.True(t, rs.ValidRound == round) +} + +// What we want: +// P0 miss to lock B as Proposal Block is missing, but set valid block to B after +// receiving delayed Block Proposal. +func TestSetValidBlockOnDelayedProposal(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + validBlockCh := subscribe(cs1.eventBus, types.EventQueryValidBlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + + round++ // move to round in which P0 is not proposer + incrementRound(vs2, vs3, vs4) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], nil) + + prop, propBlock := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round+1) + propBlockHash := propBlock.Hash() + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + // vs2, vs3 and vs4 send prevote for propBlock + signAddVotes(cs1, cmtproto.PrevoteType, propBlockHash, propBlockParts.Header(), false, vs2, vs3, vs4) + ensureNewValidBlock(validBlockCh, height, round) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds()) + + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + + assert.True(t, bytes.Equal(rs.ValidBlock.Hash(), propBlockHash)) + assert.True(t, rs.ValidBlockParts.Header().Equals(propBlockParts.Header())) + assert.True(t, rs.ValidRound == round) +} + +func TestProcessProposalAccept(t *testing.T) { + for _, testCase := range []struct { + name string + accept bool + expectedNilPrevote bool + }{ + { + name: "accepted block is prevoted", + accept: true, + expectedNilPrevote: false, + }, + { + name: "rejected block is not prevoted", + accept: false, + expectedNilPrevote: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + m := abcimocks.NewApplication(t) + status := abci.ResponseProcessProposal_REJECT + if testCase.accept { + status = abci.ResponseProcessProposal_ACCEPT + } + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{Status: status}, nil) + m.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil).Maybe() + cs1, _ := randStateWithApp(4, m) + height, round := cs1.Height, cs1.Round + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + var prevoteHash cmtbytes.HexBytes + if !testCase.expectedNilPrevote { + prevoteHash = rs.ProposalBlock.Hash() + } + ensurePrevoteMatch(t, voteCh, height, round, prevoteHash) + }) + } +} + +// TestExtendVoteCalledWhenEnabled tests that the vote extension methods are called at the +// correct point in the consensus algorithm when vote extensions are enabled. +func TestExtendVoteCalledWhenEnabled(t *testing.T) { + for _, testCase := range []struct { + name string + enabled bool + }{ + { + name: "enabled", + enabled: true, + }, + { + name: "disabled", + enabled: false, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + m := abcimocks.NewApplication(t) + m.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil) + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil) + if testCase.enabled { + m.On("ExtendVote", mock.Anything, mock.Anything).Return(&abci.ResponseExtendVote{ + VoteExtension: []byte("extension"), + }, nil) + m.On("VerifyVoteExtension", mock.Anything, mock.Anything).Return(&abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT, + }, nil) + } + m.On("Commit", mock.Anything, mock.Anything).Return(&abci.ResponseCommit{}, nil).Maybe() + m.On("FinalizeBlock", mock.Anything, mock.Anything).Return(&abci.ResponseFinalizeBlock{}, nil).Maybe() + height := int64(1) + if !testCase.enabled { + height = 0 + } + cs1, vss := randStateWithAppWithHeight(4, m, height) + + height, round := cs1.Height, cs1.Round + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + + m.AssertNotCalled(t, "ExtendVote", mock.Anything, mock.Anything) + + rs := cs1.GetRoundState() + + blockID := types.BlockID{ + Hash: rs.ProposalBlock.Hash(), + PartSetHeader: rs.ProposalBlockParts.Header(), + } + signAddVotes(cs1, cmtproto.PrevoteType, blockID.Hash, blockID.PartSetHeader, false, vss[1:]...) + ensurePrevoteMatch(t, voteCh, height, round, blockID.Hash) + + ensurePrecommit(voteCh, height, round) + + if testCase.enabled { + m.AssertCalled(t, "ExtendVote", context.TODO(), &abci.RequestExtendVote{ + Height: height, + Hash: blockID.Hash, + Time: rs.ProposalBlock.Time, + Txs: rs.ProposalBlock.Txs.ToSliceOfBytes(), + ProposedLastCommit: abci.CommitInfo{}, + Misbehavior: rs.ProposalBlock.Evidence.Evidence.ToABCI(), + NextValidatorsHash: rs.ProposalBlock.NextValidatorsHash, + ProposerAddress: rs.ProposalBlock.ProposerAddress, + }) + } else { + m.AssertNotCalled(t, "ExtendVote", mock.Anything, mock.Anything) + } + + signAddVotes(cs1, cmtproto.PrecommitType, blockID.Hash, blockID.PartSetHeader, testCase.enabled, vss[1:]...) + ensureNewRound(newRoundCh, height+1, 0) + m.AssertExpectations(t) + + // Only 3 of the vote extensions are seen, as consensus proceeds as soon as the +2/3 threshold + // is observed by the consensus engine. + for _, pv := range vss[1:3] { + pv, err := pv.GetPubKey() + require.NoError(t, err) + addr := pv.Address() + if testCase.enabled { + m.AssertCalled(t, "VerifyVoteExtension", context.TODO(), &abci.RequestVerifyVoteExtension{ + Hash: blockID.Hash, + ValidatorAddress: addr, + Height: height, + VoteExtension: []byte("extension"), + }) + } else { + m.AssertNotCalled(t, "VerifyVoteExtension", mock.Anything, mock.Anything) + } + } + }) + } +} + +// TestVerifyVoteExtensionNotCalledOnAbsentPrecommit tests that the VerifyVoteExtension +// method is not called for a validator's vote that is never delivered. +func TestVerifyVoteExtensionNotCalledOnAbsentPrecommit(t *testing.T) { + m := abcimocks.NewApplication(t) + m.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil) + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil) + m.On("ExtendVote", mock.Anything, mock.Anything).Return(&abci.ResponseExtendVote{ + VoteExtension: []byte("extension"), + }, nil) + m.On("VerifyVoteExtension", mock.Anything, mock.Anything).Return(&abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT, + }, nil) + m.On("FinalizeBlock", mock.Anything, mock.Anything).Return(&abci.ResponseFinalizeBlock{}, nil).Maybe() + m.On("Commit", mock.Anything, mock.Anything).Return(&abci.ResponseCommit{}, nil).Maybe() + cs1, vss := randStateWithApp(4, m) + height, round := cs1.Height, cs1.Round + cs1.state.ConsensusParams.ABCI.VoteExtensionsEnableHeight = cs1.Height + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + + blockID := types.BlockID{ + Hash: rs.ProposalBlock.Hash(), + PartSetHeader: rs.ProposalBlockParts.Header(), + } + signAddVotes(cs1, cmtproto.PrevoteType, blockID.Hash, blockID.PartSetHeader, false, vss...) + ensurePrevoteMatch(t, voteCh, height, round, blockID.Hash) + + ensurePrecommit(voteCh, height, round) + + m.AssertCalled(t, "ExtendVote", context.TODO(), &abci.RequestExtendVote{ + Height: height, + Hash: blockID.Hash, + Time: rs.ProposalBlock.Time, + Txs: rs.ProposalBlock.Txs.ToSliceOfBytes(), + ProposedLastCommit: abci.CommitInfo{}, + Misbehavior: rs.ProposalBlock.Evidence.Evidence.ToABCI(), + NextValidatorsHash: rs.ProposalBlock.NextValidatorsHash, + ProposerAddress: rs.ProposalBlock.ProposerAddress, + }) + + signAddVotes(cs1, cmtproto.PrecommitType, blockID.Hash, blockID.PartSetHeader, true, vss[2:]...) + ensureNewRound(newRoundCh, height+1, 0) + m.AssertExpectations(t) + + // vss[1] did not issue a precommit for the block, ensure that a vote extension + // for its address was not sent to the application. + pv, err := vss[1].GetPubKey() + require.NoError(t, err) + addr = pv.Address() + + m.AssertNotCalled(t, "VerifyVoteExtension", context.TODO(), &abci.RequestVerifyVoteExtension{ + Hash: blockID.Hash, + ValidatorAddress: addr, + Height: height, + VoteExtension: []byte("extension"), + }) +} + +// TestPrepareProposalReceivesVoteExtensions tests that the PrepareProposal method +// is called with the vote extensions from the previous height. The test functions +// by completing a consensus height with a mock application as the proposer. The +// test then proceeds to fail several rounds of consensus until the mock application +// is the proposer again and ensures that the mock application receives the set of +// vote extensions from the previous consensus instance. +func TestPrepareProposalReceivesVoteExtensions(t *testing.T) { + // create a list of vote extensions, one for each validator. + voteExtensions := [][]byte{ + []byte("extension 0"), + []byte("extension 1"), + []byte("extension 2"), + []byte("extension 3"), + } + + m := abcimocks.NewApplication(t) + m.On("ExtendVote", mock.Anything, mock.Anything).Return(&abci.ResponseExtendVote{ + VoteExtension: voteExtensions[0], + }, nil) + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil) + + // capture the prepare proposal request. + rpp := &abci.RequestPrepareProposal{} + m.On("PrepareProposal", mock.Anything, mock.MatchedBy(func(r *abci.RequestPrepareProposal) bool { + rpp = r + return true + })).Return(&abci.ResponsePrepareProposal{}, nil) + + m.On("VerifyVoteExtension", mock.Anything, mock.Anything).Return(&abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil) + m.On("Commit", mock.Anything, mock.Anything).Return(&abci.ResponseCommit{}, nil).Maybe() + m.On("FinalizeBlock", mock.Anything, mock.Anything).Return(&abci.ResponseFinalizeBlock{}, nil) + + cs1, vss := randStateWithApp(4, m) + height, round := cs1.Height, cs1.Round + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + + rs := cs1.GetRoundState() + blockID := types.BlockID{ + Hash: rs.ProposalBlock.Hash(), + PartSetHeader: rs.ProposalBlockParts.Header(), + } + signAddVotes(cs1, cmtproto.PrevoteType, blockID.Hash, blockID.PartSetHeader, false, vss[1:]...) + + // create a precommit for each validator with the associated vote extension. + for i, vs := range vss[1:] { + signAddPrecommitWithExtension(t, cs1, blockID.Hash, blockID.PartSetHeader, voteExtensions[i+1], vs) + } + + ensurePrevote(voteCh, height, round) + + // ensure that the height is committed. + ensurePrecommitMatch(t, voteCh, height, round, blockID.Hash) + incrementHeight(vss[1:]...) + + height++ + round = 0 + ensureNewRound(newRoundCh, height, round) + incrementRound(vss[1:]...) + incrementRound(vss[1:]...) + incrementRound(vss[1:]...) + round = 3 + + blockID2 := types.BlockID{} + signAddVotes(cs1, cmtproto.PrecommitType, blockID2.Hash, blockID2.PartSetHeader, true, vss[1:]...) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + + // ensure that the proposer received the list of vote extensions from the + // previous height. + require.Len(t, rpp.LocalLastCommit.Votes, len(vss)) + for i := range vss { + vote := &rpp.LocalLastCommit.Votes[i] + require.Equal(t, vote.VoteExtension, voteExtensions[i]) + + require.NotZero(t, len(vote.ExtensionSignature)) + cve := cmtproto.CanonicalVoteExtension{ + Extension: vote.VoteExtension, + Height: height - 1, // the vote extension was signed in the previous height + Round: int64(rpp.LocalLastCommit.Round), + ChainId: test.DefaultTestChainID, + } + extSignBytes, err := protoio.MarshalDelimited(&cve) + require.NoError(t, err) + pubKey, err := vss[i].GetPubKey() + require.NoError(t, err) + require.True(t, pubKey.VerifySignature(extSignBytes, vote.ExtensionSignature)) + } +} + +func TestFinalizeBlockCalled(t *testing.T) { + for _, testCase := range []struct { + name string + voteNil bool + expectCalled bool + }{ + { + name: "finalize block called when block committed", + voteNil: false, + expectCalled: true, + }, + { + name: "not called when block not committed", + voteNil: true, + expectCalled: false, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + m := abcimocks.NewApplication(t) + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_ACCEPT, + }, nil) + m.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil) + // We only expect VerifyVoteExtension to be called on non-nil precommits. + // https://github.com/tendermint/tendermint/issues/8487 + if !testCase.voteNil { + m.On("ExtendVote", mock.Anything, mock.Anything).Return(&abci.ResponseExtendVote{}, nil) + m.On("VerifyVoteExtension", mock.Anything, mock.Anything).Return(&abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT, + }, nil) + } + r := &abci.ResponseFinalizeBlock{AppHash: []byte("the_hash")} + m.On("FinalizeBlock", mock.Anything, mock.Anything).Return(r, nil).Maybe() + m.On("Commit", mock.Anything, mock.Anything).Return(&abci.ResponseCommit{}, nil).Maybe() + + cs1, vss := randStateWithApp(4, m) + height, round := cs1.Height, cs1.Round + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + + blockID := types.BlockID{} + nextRound := round + 1 + nextHeight := height + if !testCase.voteNil { + nextRound = 0 + nextHeight = height + 1 + blockID = types.BlockID{ + Hash: rs.ProposalBlock.Hash(), + PartSetHeader: rs.ProposalBlockParts.Header(), + } + } + + signAddVotes(cs1, cmtproto.PrevoteType, blockID.Hash, blockID.PartSetHeader, false, vss[1:]...) + ensurePrevoteMatch(t, voteCh, height, round, rs.ProposalBlock.Hash()) + + signAddVotes(cs1, cmtproto.PrecommitType, blockID.Hash, blockID.PartSetHeader, true, vss[1:]...) + ensurePrecommit(voteCh, height, round) + + ensureNewRound(newRoundCh, nextHeight, nextRound) + m.AssertExpectations(t) + + if !testCase.expectCalled { + m.AssertNotCalled(t, "FinalizeBlock", context.TODO(), mock.Anything) + } else { + m.AssertCalled(t, "FinalizeBlock", context.TODO(), mock.Anything) + } + }) + } +} + +// TestVoteExtensionEnableHeight tests that 'ExtensionRequireHeight' correctly +// enforces that vote extensions be present in consensus for heights greater than +// or equal to the configured value. +func TestVoteExtensionEnableHeight(t *testing.T) { + for _, testCase := range []struct { + name string + enableHeight int64 + hasExtension bool + expectExtendCalled bool + expectVerifyCalled bool + expectSuccessfulRound bool + }{ + { + name: "extension present but not enabled", + hasExtension: true, + enableHeight: 0, + expectExtendCalled: false, + expectVerifyCalled: false, + expectSuccessfulRound: false, + }, + { + name: "extension absent but not required", + hasExtension: false, + enableHeight: 0, + expectExtendCalled: false, + expectVerifyCalled: false, + expectSuccessfulRound: true, + }, + { + name: "extension present and required", + hasExtension: true, + enableHeight: 1, + expectExtendCalled: true, + expectVerifyCalled: true, + expectSuccessfulRound: true, + }, + { + name: "extension absent but required", + hasExtension: false, + enableHeight: 1, + expectExtendCalled: true, + expectVerifyCalled: false, + expectSuccessfulRound: false, + }, + { + name: "extension absent but required in future height", + hasExtension: false, + enableHeight: 2, + expectExtendCalled: false, + expectVerifyCalled: false, + expectSuccessfulRound: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + numValidators := 3 + m := abcimocks.NewApplication(t) + m.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_ACCEPT, + }, nil) + m.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil) + if testCase.expectExtendCalled { + m.On("ExtendVote", mock.Anything, mock.Anything).Return(&abci.ResponseExtendVote{}, nil) + } + if testCase.expectVerifyCalled { + m.On("VerifyVoteExtension", mock.Anything, mock.Anything).Return(&abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT, + }, nil).Times(numValidators - 1) + } + m.On("FinalizeBlock", mock.Anything, mock.Anything).Return(&abci.ResponseFinalizeBlock{}, nil).Maybe() + m.On("Commit", mock.Anything, mock.Anything).Return(&abci.ResponseCommit{}, nil).Maybe() + cs1, vss := randStateWithAppWithHeight(numValidators, m, testCase.enableHeight) + cs1.state.ConsensusParams.ABCI.VoteExtensionsEnableHeight = testCase.enableHeight + height, round := cs1.Height, cs1.Round + + timeoutCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + startTestRound(cs1, cs1.Height, round) + ensureNewRound(newRoundCh, height, round) + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + + // sign all of the votes + signAddVotes(cs1, cmtproto.PrevoteType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), false, vss[1:]...) + ensurePrevoteMatch(t, voteCh, height, round, rs.ProposalBlock.Hash()) + + var ext []byte + if testCase.hasExtension { + ext = []byte("extension") + } + + for _, vs := range vss[1:] { + vote, err := vs.signVote(cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), ext, testCase.hasExtension) + require.NoError(t, err) + addVotes(cs1, vote) + } + if testCase.expectSuccessfulRound { + ensurePrecommit(voteCh, height, round) + height++ + ensureNewRound(newRoundCh, height, round) + } else { + ensureNoNewTimeout(timeoutCh, cs1.config.Precommit(round).Nanoseconds()) + } + + m.AssertExpectations(t) + }) + } +} + +// TestStateDoesntCrashOnInvalidVote tests that the state does not crash when +// receiving an invalid vote. In particular, one with the incorrect +// ValidatorIndex. +func TestStateDoesntCrashOnInvalidVote(t *testing.T) { + cs, vss := randState(2) + height, round := cs.Height, cs.Round + // create dummy peer + peer := p2pmock.NewPeer(nil) + + startTestRound(cs, height, round) + + _, propBlock := decideProposal(context.Background(), t, cs, vss[0], height, round) + propBlockParts, err := propBlock.MakePartSet(types.BlockPartSizeBytes) + assert.NoError(t, err) + + vote := signVote(vss[1], cmtproto.PrecommitType, propBlock.Hash(), propBlockParts.Header(), true) + + // Non-existent validator index + vote.ValidatorIndex = int32(len(vss)) + + voteMessage := &VoteMessage{vote} + assert.NotPanics(t, func() { + cs.handleMsg(msgInfo{voteMessage, peer.ID()}) + }) + + added, err := cs.AddVote(vote, peer.ID()) + assert.False(t, added) + assert.NoError(t, err) + // TODO: uncomment once we punish peer and return an error + // assert.Equal(t, ErrInvalidVote{Reason: "ValidatorIndex 2 is out of bounds [0, 2)"}, err) +} + +// 4 vals, 3 Nil Precommits at P0 +// What we want: +// P0 waits for timeoutPrecommit before starting next round +func TestWaitingTimeoutOnNilPolka(*testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + + // start round + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + ensureNewRound(newRoundCh, height, round+1) +} + +// 4 vals, 3 Prevotes for nil from the higher round. +// What we want: +// P0 waits for timeoutPropose in the next round before entering prevote +func TestWaitingTimeoutProposeOnNewRound(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensurePrevote(voteCh, height, round) + + incrementRound(vss[1:]...) + signAddVotes(cs1, cmtproto.PrevoteType, nil, types.PartSetHeader{}, false, vs2, vs3, vs4) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) + + rs := cs1.GetRoundState() + assert.True(t, rs.Step == cstypes.RoundStepPropose) // P0 does not prevote before timeoutPropose expires + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], nil) +} + +// 4 vals, 3 Precommits for nil from the higher round. +// What we want: +// P0 jump to higher round, precommit and start precommit wait +func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensurePrevote(voteCh, height, round) + + incrementRound(vss[1:]...) + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2, vs3, vs4) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) + + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, -1, vss[0], nil, nil) + + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + ensureNewRound(newRoundCh, height, round) +} + +// 4 vals, 3 Prevotes for nil in the current round. +// What we want: +// P0 wait for timeoutPropose to expire before sending prevote. +func TestWaitTimeoutProposeOnNilPolkaForTheCurrentRound(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, int32(1) + + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round in which PO is not proposer + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + incrementRound(vss[1:]...) + signAddVotes(cs1, cmtproto.PrevoteType, nil, types.PartSetHeader{}, false, vs2, vs3, vs4) + + ensureNewTimeout(timeoutProposeCh, height, round, cs1.config.Propose(round).Nanoseconds()) + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], nil) +} + +// What we want: +// P0 emit NewValidBlock event upon receiving 2/3+ Precommit for B but hasn't received block B yet +func TestEmitNewValidBlockEventOnCommitWithoutBlock(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, int32(1) + + incrementRound(vs2, vs3, vs4) + + partSize := types.BlockPartSizeBytes + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + validBlockCh := subscribe(cs1.eventBus, types.EventQueryValidBlock) + + _, propBlock := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round) + propBlockHash := propBlock.Hash() + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + // start round in which PO is not proposer + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + // vs2, vs3 and vs4 send precommit for propBlock + signAddVotes(cs1, cmtproto.PrecommitType, propBlockHash, propBlockParts.Header(), true, vs2, vs3, vs4) + ensureNewValidBlock(validBlockCh, height, round) + + rs := cs1.GetRoundState() + assert.True(t, rs.Step == cstypes.RoundStepCommit) + assert.True(t, rs.ProposalBlock == nil) + assert.True(t, rs.ProposalBlockParts.Header().Equals(propBlockParts.Header())) +} + +// What we want: +// P0 receives 2/3+ Precommit for B for round 0, while being in round 1. It emits NewValidBlock event. +// After receiving block, it executes block and moves to the next height. +func TestCommitFromPreviousRound(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, int32(1) + + partSize := types.BlockPartSizeBytes + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + validBlockCh := subscribe(cs1.eventBus, types.EventQueryValidBlock) + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + + prop, propBlock := decideProposal(ctx, t, cs1, vs2, vs2.Height, vs2.Round) + propBlockHash := propBlock.Hash() + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + // start round in which PO is not proposer + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + // vs2, vs3 and vs4 send precommit for propBlock for the previous round + signAddVotes(cs1, cmtproto.PrecommitType, propBlockHash, propBlockParts.Header(), true, vs2, vs3, vs4) + + ensureNewValidBlock(validBlockCh, height, round) + + rs := cs1.GetRoundState() + assert.True(t, rs.Step == cstypes.RoundStepCommit) + assert.True(t, rs.CommitRound == vs2.Round) + assert.True(t, rs.ProposalBlock == nil) + assert.True(t, rs.ProposalBlockParts.Header().Equals(propBlockParts.Header())) + + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + + ensureNewProposal(proposalCh, height, round) + ensureNewRound(newRoundCh, height+1, 0) +} + +type fakeTxNotifier struct { + ch chan struct{} +} + +func (n *fakeTxNotifier) TxsAvailable() <-chan struct{} { + return n.ch +} + +func (n *fakeTxNotifier) Notify() { + n.ch <- struct{}{} +} + +// 2 vals precommit votes for a block but node times out waiting for the third. Move to next round +// and third precommit arrives which leads to the commit of that header and the correct +// start of the next round +func TestStartNextHeightCorrectlyAfterTimeout(t *testing.T) { + config.Consensus.SkipTimeoutCommit = false + cs1, vss := randState(4) + cs1.txNotifier = &fakeTxNotifier{ch: make(chan struct{})} + + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) + precommitTimeoutCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + newBlockHeader := subscribe(cs1.eventBus, types.EventQueryNewBlockHeader) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + theBlockHash := rs.ProposalBlock.Hash() + theBlockParts := rs.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], theBlockHash) + + signAddVotes(cs1, cmtproto.PrevoteType, theBlockHash, theBlockParts, false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], theBlockHash, theBlockHash) + + // add precommits + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2) + signAddVotes(cs1, cmtproto.PrecommitType, theBlockHash, theBlockParts, true, vs3) + + // wait till timeout occurs + ensurePrecommitTimeout(precommitTimeoutCh) + + ensureNewRound(newRoundCh, height, round+1) + + // majority is now reached + signAddVotes(cs1, cmtproto.PrecommitType, theBlockHash, theBlockParts, true, vs4) + + ensureNewBlockHeader(newBlockHeader, height, theBlockHash) + + cs1.txNotifier.(*fakeTxNotifier).Notify() + + ensureNewTimeout(timeoutProposeCh, height+1, round, cs1.config.Propose(round).Nanoseconds()) + rs = cs1.GetRoundState() + assert.False( + t, + rs.TriggeredTimeoutPrecommit, + "triggeredTimeoutPrecommit should be false at the beginning of each round") +} + +func TestResetTimeoutPrecommitUponNewHeight(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + config.Consensus.SkipTimeoutCommit = false + cs1, vss := randState(4) + + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + newBlockHeader := subscribe(cs1.eventBus, types.EventQueryNewBlockHeader) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + theBlockHash := rs.ProposalBlock.Hash() + theBlockParts := rs.ProposalBlockParts.Header() + + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], theBlockHash) + + signAddVotes(cs1, cmtproto.PrevoteType, theBlockHash, theBlockParts, false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + validatePrecommit(t, cs1, round, round, vss[0], theBlockHash, theBlockHash) + + // add precommits + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2) + signAddVotes(cs1, cmtproto.PrecommitType, theBlockHash, theBlockParts, true, vs3) + signAddVotes(cs1, cmtproto.PrecommitType, theBlockHash, theBlockParts, true, vs4) + + ensureNewBlockHeader(newBlockHeader, height, theBlockHash) + + prop, propBlock := decideProposal(ctx, t, cs1, vs2, height+1, 0) + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { + t.Fatal(err) + } + ensureNewProposal(proposalCh, height+1, 0) + + rs = cs1.GetRoundState() + assert.False( + t, + rs.TriggeredTimeoutPrecommit, + "triggeredTimeoutPrecommit should be false at the beginning of each height") +} + +//------------------------------------------------------------------------------------------ +// SlashingSuite +// TODO: Slashing + +/* +func TestStateSlashingPrevotes(t *testing.T) { + cs1, vss := randState(2) + vs2 := vss[1] + + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + + // start round and wait for propose and prevote + startTestRound(cs1, cs1.Height, 0) + <-newRoundCh + re := <-proposalCh + <-voteCh // prevote + + rs := re.(types.EventDataRoundState).RoundState.(*cstypes.RoundState) + + // we should now be stuck in limbo forever, waiting for more prevotes + // add one for a different block should cause us to go into prevote wait + hash := rs.ProposalBlock.Hash() + hash[0] = byte(hash[0]+1) % 255 + signAddVotes(cs1, cmtproto.PrevoteType, hash, rs.ProposalBlockParts.Header(), vs2) + + <-timeoutWaitCh + + // NOTE: we have to send the vote for different block first so we don't just go into precommit round right + // away and ignore more prevotes (and thus fail to slash!) + + // add the conflicting vote + signAddVotes(cs1, cmtproto.PrevoteType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vs2) + + // XXX: Check for existence of Dupeout info +} + +func TestStateSlashingPrecommits(t *testing.T) { + cs1, vss := randState(2) + vs2 := vss[1] + + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + + // start round and wait for propose and prevote + startTestRound(cs1, cs1.Height, 0) + <-newRoundCh + re := <-proposalCh + <-voteCh // prevote + + // add prevote from vs2 + signAddVotes(cs1, cmtproto.PrevoteType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vs2) + + <-voteCh // precommit + + // we should now be stuck in limbo forever, waiting for more prevotes + // add one for a different block should cause us to go into prevote wait + hash := rs.ProposalBlock.Hash() + hash[0] = byte(hash[0]+1) % 255 + signAddVotes(cs1, cmtproto.PrecommitType, hash, rs.ProposalBlockParts.Header(), vs2) + + // NOTE: we have to send the vote for different block first so we don't just go into precommit round right + // away and ignore more prevotes (and thus fail to slash!) + + // add precommit from vs2 + signAddVotes(cs1, cmtproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vs2) + + // XXX: Check for existence of Dupeout info +} +*/ + +//------------------------------------------------------------------------------------------ +// CatchupSuite + +//------------------------------------------------------------------------------------------ +// HaltSuite + +// 4 vals. +// we receive a final precommit after going into next round, but others might have gone to commit already! +func TestStateHalt1(t *testing.T) { + cs1, vss := randState(4) + vs2, vs3, vs4 := vss[1], vss[2], vss[3] + height, round := cs1.Height, cs1.Round + partSize := types.BlockPartSizeBytes + + proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) + timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) + newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) + newBlockCh := subscribe(cs1.eventBus, types.EventQueryNewBlock) + pv1, err := cs1.privValidator.GetPubKey() + require.NoError(t, err) + addr := pv1.Address() + voteCh := subscribeToVoter(cs1, addr) + + // start round and wait for propose and prevote + startTestRound(cs1, height, round) + ensureNewRound(newRoundCh, height, round) + + ensureNewProposal(proposalCh, height, round) + rs := cs1.GetRoundState() + propBlock := rs.ProposalBlock + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + + ensurePrevote(voteCh, height, round) + + signAddVotes(cs1, cmtproto.PrevoteType, propBlock.Hash(), propBlockParts.Header(), false, vs2, vs3, vs4) + + ensurePrecommit(voteCh, height, round) + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, round, round, vss[0], propBlock.Hash(), propBlock.Hash()) + + // add precommits from the rest + signAddVotes(cs1, cmtproto.PrecommitType, nil, types.PartSetHeader{}, true, vs2) // didnt receive proposal + signAddVotes(cs1, cmtproto.PrecommitType, propBlock.Hash(), propBlockParts.Header(), true, vs3) + // we receive this later, but vs3 might receive it earlier and with ours will go to commit! + precommit4 := signVote(vs4, cmtproto.PrecommitType, propBlock.Hash(), propBlockParts.Header(), true) + + incrementRound(vs2, vs3, vs4) + + // timeout to new round + ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) + + round++ // moving to the next round + + ensureNewRound(newRoundCh, height, round) + rs = cs1.GetRoundState() + + t.Log("### ONTO ROUND 1") + /*Round2 + // we timeout and prevote our lock + // a polka happened but we didn't see it! + */ + + // go to prevote, prevote for locked block + ensurePrevote(voteCh, height, round) + validatePrevote(t, cs1, round, vss[0], rs.LockedBlock.Hash()) + + // now we receive the precommit from the previous round + addVotes(cs1, precommit4) + + // receiving that precommit should take us straight to commit + ensureNewBlock(newBlockCh, height) + + ensureNewRound(newRoundCh, height+1, 0) +} + +func TestStateOutputsBlockPartsStats(t *testing.T) { + // create dummy peer + cs, _ := randState(1) + peer := p2pmock.NewPeer(nil) + + // 1) new block part + parts := types.NewPartSetFromData(cmtrand.Bytes(100), 10) + msg := &BlockPartMessage{ + Height: 1, + Round: 0, + Part: parts.GetPart(0), + } + + cs.ProposalBlockParts = types.NewPartSetFromHeader(parts.Header()) + cs.handleMsg(msgInfo{msg, peer.ID()}) + + statsMessage := <-cs.statsMsgQueue + require.Equal(t, msg, statsMessage.Msg, "") + require.Equal(t, peer.ID(), statsMessage.PeerID, "") + + // sending the same part from different peer + cs.handleMsg(msgInfo{msg, "peer2"}) + + // sending the part with the same height, but different round + msg.Round = 1 + cs.handleMsg(msgInfo{msg, peer.ID()}) + + // sending the part from the smaller height + msg.Height = 0 + cs.handleMsg(msgInfo{msg, peer.ID()}) + + // sending the part from the bigger height + msg.Height = 3 + cs.handleMsg(msgInfo{msg, peer.ID()}) + + select { + case <-cs.statsMsgQueue: + t.Errorf("should not output stats message after receiving the known block part!") + case <-time.After(50 * time.Millisecond): + } +} + +func TestStateOutputVoteStats(t *testing.T) { + cs, vss := randState(2) + // create dummy peer + peer := p2pmock.NewPeer(nil) + + randBytes := cmtrand.Bytes(tmhash.Size) + + vote := signVote(vss[1], cmtproto.PrecommitType, randBytes, types.PartSetHeader{}, true) + + voteMessage := &VoteMessage{vote} + cs.handleMsg(msgInfo{voteMessage, peer.ID()}) + + statsMessage := <-cs.statsMsgQueue + require.Equal(t, voteMessage, statsMessage.Msg, "") + require.Equal(t, peer.ID(), statsMessage.PeerID, "") + + // sending the same part from different peer + cs.handleMsg(msgInfo{&VoteMessage{vote}, "peer2"}) + + // sending the vote for the bigger height + incrementHeight(vss[1]) + vote = signVote(vss[1], cmtproto.PrecommitType, randBytes, types.PartSetHeader{}, true) + + cs.handleMsg(msgInfo{&VoteMessage{vote}, peer.ID()}) + + select { + case <-cs.statsMsgQueue: + t.Errorf("should not output stats message after receiving the known vote or vote from bigger height") + case <-time.After(50 * time.Millisecond): + } +} + +func TestSignSameVoteTwice(t *testing.T) { + _, vss := randState(2) + + randBytes := cmtrand.Bytes(tmhash.Size) + + vote := signVote(vss[1], + cmtproto.PrecommitType, + randBytes, + types.PartSetHeader{Total: 10, Hash: randBytes}, + true, + ) + + vote2 := signVote(vss[1], + cmtproto.PrecommitType, + randBytes, + types.PartSetHeader{Total: 10, Hash: randBytes}, + true, + ) + + require.Equal(t, vote, vote2) +} + +// subscribe subscribes test client to the given query and returns a channel with cap = 1. +func subscribe(eventBus *types.EventBus, q cmtpubsub.Query) <-chan cmtpubsub.Message { + sub, err := eventBus.Subscribe(context.Background(), testSubscriber, q) + if err != nil { + panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, q)) + } + return sub.Out() +} + +// subscribe subscribes test client to the given query and returns a channel with cap = 0. +func subscribeUnBuffered(eventBus *types.EventBus, q cmtpubsub.Query) <-chan cmtpubsub.Message { + sub, err := eventBus.SubscribeUnbuffered(context.Background(), testSubscriber, q) + if err != nil { + panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, q)) + } + return sub.Out() +} + +func signAddPrecommitWithExtension( + t *testing.T, + cs *State, + hash []byte, + header types.PartSetHeader, + extension []byte, + stub *validatorStub, +) { + v, err := stub.signVote(cmtproto.PrecommitType, hash, header, extension, true) + require.NoError(t, err, "failed to sign vote") + addVotes(cs, v) +} + +func findBlockSizeLimit(t *testing.T, height, maxBytes int64, cs *State, partSize uint32, oversized bool) (*types.Block, *types.PartSet) { + var offset int64 + if !oversized { + offset = -2 + } + softMaxDataBytes := int(types.MaxDataBytes(maxBytes, 0, 0)) + for i := softMaxDataBytes; i < softMaxDataBytes*2; i++ { + propBlock, err := cs.state.MakeBlock( + height, + []types.Tx{[]byte("a=" + strings.Repeat("o", i-2))}, + &types.Commit{}, + nil, + cs.privValidatorPubKey.Address(), + ) + require.NoError(t, err) + + propBlockParts, err := propBlock.MakePartSet(partSize) + require.NoError(t, err) + if propBlockParts.ByteSize() > maxBytes+offset { + s := "real max" + if oversized { + s = "off-by-1" + } + t.Log("Detected "+s+" data size for block;", "size", i, "softMaxDataBytes", softMaxDataBytes) + return propBlock, propBlockParts + } + } + require.Fail(t, "We shouldn't hit the end of the loop") + return nil, nil +} diff --git a/consensus/ticker.go b/consensus/ticker.go new file mode 100644 index 0000000..37d7b10 --- /dev/null +++ b/consensus/ticker.go @@ -0,0 +1,143 @@ +package consensus + +import ( + "time" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" +) + +var ( + tickTockBufferSize = 10 +) + +// TimeoutTicker is a timer that schedules timeouts +// conditional on the height/round/step in the timeoutInfo. +// The timeoutInfo.Duration may be non-positive. +type TimeoutTicker interface { + Start() error + Stop() error + Chan() <-chan timeoutInfo // on which to receive a timeout + ScheduleTimeout(ti timeoutInfo) // reset the timer + + SetLogger(log.Logger) +} + +// timeoutTicker wraps time.Timer, +// scheduling timeouts only for greater height/round/step +// than what it's already seen. +// Timeouts are scheduled along the tickChan, +// and fired on the tockChan. +type timeoutTicker struct { + service.BaseService + + timerActive bool + timer *time.Timer + tickChan chan timeoutInfo // for scheduling timeouts + tockChan chan timeoutInfo // for notifying about them +} + +// NewTimeoutTicker returns a new TimeoutTicker. +func NewTimeoutTicker() TimeoutTicker { + tt := &timeoutTicker{ + timer: time.NewTimer(0), + // An indicator variable to check if the timer is active or not. + // Concurrency safe because the timer is only accessed by a single goroutine. + timerActive: true, + tickChan: make(chan timeoutInfo, tickTockBufferSize), + tockChan: make(chan timeoutInfo, tickTockBufferSize), + } + tt.BaseService = *service.NewBaseService(nil, "TimeoutTicker", tt) + tt.stopTimer() // don't want to fire until the first scheduled timeout + return tt +} + +// OnStart implements service.Service. It starts the timeout routine. +func (t *timeoutTicker) OnStart() error { + + go t.timeoutRoutine() + + return nil +} + +// OnStop implements service.Service. It stops the timeout routine. +func (t *timeoutTicker) OnStop() { + t.BaseService.OnStop() +} + +// Chan returns a channel on which timeouts are sent. +func (t *timeoutTicker) Chan() <-chan timeoutInfo { + return t.tockChan +} + +// ScheduleTimeout schedules a new timeout by sending on the internal tickChan. +// The timeoutRoutine is always available to read from tickChan, so this won't block. +// The scheduling may fail if the timeoutRoutine has already scheduled a timeout for a later height/round/step. +func (t *timeoutTicker) ScheduleTimeout(ti timeoutInfo) { + t.tickChan <- ti +} + +//------------------------------------------------------------- + +// if the timer is active, stop it and drain the channel. +func (t *timeoutTicker) stopTimer() { + if !t.timerActive { + return + } + // Stop() returns false if it was already fired or was stopped + if !t.timer.Stop() { + <-t.timer.C + } + t.timerActive = false +} + +// send on tickChan to start a new timer. +// timers are interrupted and replaced by new ticks from later steps +// timeouts of 0 on the tickChan will be immediately relayed to the tockChan. +// NOTE: timerActive is not concurrency safe, but it's only accessed in NewTimer and timeoutRoutine, +// making it single-threaded access. +func (t *timeoutTicker) timeoutRoutine() { + t.Logger.Debug("Starting timeout routine") + var ti timeoutInfo + for { + select { + case newti := <-t.tickChan: + t.Logger.Debug("Received tick", "old_ti", ti, "new_ti", newti) + + // ignore tickers for old height/round/step + if newti.Height < ti.Height { + continue + } else if newti.Height == ti.Height { + if newti.Round < ti.Round { + continue + } else if newti.Round == ti.Round { + if ti.Step > 0 && newti.Step <= ti.Step { + continue + } + } + } + + // stop the last timer if it exists + t.stopTimer() + + // update timeoutInfo, reset timer, and mark timer as active + // NOTE time.Timer allows duration to be non-positive + ti = newti + t.timer.Reset(ti.Duration) + t.timerActive = true + + t.Logger.Debug("Scheduled timeout", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + case <-t.timer.C: + t.timerActive = false + t.Logger.Info("Timed out", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + // go routine here guarantees timeoutRoutine doesn't block. + // Determinism comes from playback in the receiveRoutine. + // We can eliminate it by merging the timeoutRoutine into receiveRoutine + // and managing the timeouts ourselves with a millisecond ticker + go func(toi timeoutInfo) { t.tockChan <- toi }(ti) + case <-t.Quit(): + t.stopTimer() + return + } + } +} diff --git a/consensus/ticker_test.go b/consensus/ticker_test.go new file mode 100644 index 0000000..e603425 --- /dev/null +++ b/consensus/ticker_test.go @@ -0,0 +1,40 @@ +package consensus + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/consensus/types" +) + +func TestTimeoutTicker(t *testing.T) { + ticker := NewTimeoutTicker() + err := ticker.Start() + require.NoError(t, err) + defer func() { + err := ticker.Stop() + require.NoError(t, err) + }() + + c := ticker.Chan() + for i := 1; i <= 10; i++ { + height := int64(i) + + startTime := time.Now() + // Schedule a timeout for 5ms from now + negTimeout := timeoutInfo{Duration: -1 * time.Millisecond, Height: height, Round: 0, Step: types.RoundStepNewHeight} + timeout := timeoutInfo{Duration: 5 * time.Millisecond, Height: height, Round: 0, Step: types.RoundStepNewRound} + ticker.ScheduleTimeout(negTimeout) + ticker.ScheduleTimeout(timeout) + + // Wait for the timeout to be received + to := <-c + endTime := time.Now() + elapsedTime := endTime.Sub(startTime) + if timeout == to { + require.True(t, elapsedTime >= timeout.Duration, "We got the 5ms timeout. However the timeout happened too quickly. Should be >= 5ms. Got %dms (start time %d end time %d)", elapsedTime.Milliseconds(), startTime.UnixMilli(), endTime.UnixMilli()) + } + } +} diff --git a/consensus/types/height_vote_set.go b/consensus/types/height_vote_set.go new file mode 100644 index 0000000..5fb3d8e --- /dev/null +++ b/consensus/types/height_vote_set.go @@ -0,0 +1,286 @@ +package types + +import ( + "errors" + "fmt" + "strings" + "sync" + + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtmath "github.com/cometbft/cometbft/libs/math" + "github.com/cometbft/cometbft/p2p" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +type RoundVoteSet struct { + Prevotes *types.VoteSet + Precommits *types.VoteSet +} + +var ( + ErrGotVoteFromUnwantedRound = errors.New( + "peer has sent a vote that does not match our round for more than one round", + ) +) + +/* +Keeps track of all VoteSets from round 0 to round 'round'. + +Also keeps track of up to one RoundVoteSet greater than +'round' from each peer, to facilitate catchup syncing of commits. + +A commit is +2/3 precommits for a block at a round, +but which round is not known in advance, so when a peer +provides a precommit for a round greater than mtx.round, +we create a new entry in roundVoteSets but also remember the +peer to prevent abuse. +We let each peer provide us with up to 2 unexpected "catchup" rounds. +One for their LastCommit round, and another for the official commit round. +*/ +type HeightVoteSet struct { + chainID string + height int64 + valSet *types.ValidatorSet + extensionsEnabled bool + + mtx sync.Mutex + round int32 // max tracked round + roundVoteSets map[int32]RoundVoteSet // keys: [0...round] + peerCatchupRounds map[p2p.ID][]int32 // keys: peer.ID; values: at most 2 rounds +} + +func NewHeightVoteSet(chainID string, height int64, valSet *types.ValidatorSet) *HeightVoteSet { + hvs := &HeightVoteSet{ + chainID: chainID, + extensionsEnabled: false, + } + hvs.Reset(height, valSet) + return hvs +} + +func NewExtendedHeightVoteSet(chainID string, height int64, valSet *types.ValidatorSet) *HeightVoteSet { + hvs := &HeightVoteSet{ + chainID: chainID, + extensionsEnabled: true, + } + hvs.Reset(height, valSet) + return hvs +} + +func (hvs *HeightVoteSet) Reset(height int64, valSet *types.ValidatorSet) { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + + hvs.height = height + hvs.valSet = valSet + hvs.roundVoteSets = make(map[int32]RoundVoteSet) + hvs.peerCatchupRounds = make(map[p2p.ID][]int32) + + hvs.addRound(0) + hvs.round = 0 +} + +func (hvs *HeightVoteSet) Height() int64 { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + return hvs.height +} + +func (hvs *HeightVoteSet) Round() int32 { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + return hvs.round +} + +// Create more RoundVoteSets up to round. +func (hvs *HeightVoteSet) SetRound(round int32) { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + newRound := cmtmath.SafeSubInt32(hvs.round, 1) + if hvs.round != 0 && (round < newRound) { + panic("SetRound() must increment hvs.round") + } + for r := newRound; r <= round; r++ { + if _, ok := hvs.roundVoteSets[r]; ok { + continue // Already exists because peerCatchupRounds. + } + hvs.addRound(r) + } + hvs.round = round +} + +func (hvs *HeightVoteSet) addRound(round int32) { + if _, ok := hvs.roundVoteSets[round]; ok { + panic("addRound() for an existing round") + } + // log.Debug("addRound(round)", "round", round) + prevotes := types.NewVoteSet(hvs.chainID, hvs.height, round, cmtproto.PrevoteType, hvs.valSet) + var precommits *types.VoteSet + if hvs.extensionsEnabled { + precommits = types.NewExtendedVoteSet(hvs.chainID, hvs.height, round, cmtproto.PrecommitType, hvs.valSet) + } else { + precommits = types.NewVoteSet(hvs.chainID, hvs.height, round, cmtproto.PrecommitType, hvs.valSet) + } + hvs.roundVoteSets[round] = RoundVoteSet{ + Prevotes: prevotes, + Precommits: precommits, + } +} + +// Duplicate votes return added=false, err=nil. +// By convention, peerID is "" if origin is self. +func (hvs *HeightVoteSet) AddVote(vote *types.Vote, peerID p2p.ID, extEnabled bool) (added bool, err error) { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + if hvs.extensionsEnabled != extEnabled { + panic(fmt.Errorf("extensions enabled general param does not match the one in HeightVoteSet %t!=%t", hvs.extensionsEnabled, extEnabled)) + } + if !types.IsVoteTypeValid(vote.Type) { + return + } + voteSet := hvs.getVoteSet(vote.Round, vote.Type) + if voteSet == nil { + if rndz := hvs.peerCatchupRounds[peerID]; len(rndz) < 2 { + hvs.addRound(vote.Round) + voteSet = hvs.getVoteSet(vote.Round, vote.Type) + hvs.peerCatchupRounds[peerID] = append(rndz, vote.Round) + } else { + // punish peer + err = ErrGotVoteFromUnwantedRound + return + } + } + added, err = voteSet.AddVote(vote) + return +} + +func (hvs *HeightVoteSet) Prevotes(round int32) *types.VoteSet { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + return hvs.getVoteSet(round, cmtproto.PrevoteType) +} + +func (hvs *HeightVoteSet) Precommits(round int32) *types.VoteSet { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + return hvs.getVoteSet(round, cmtproto.PrecommitType) +} + +// Last round and blockID that has +2/3 prevotes for a particular block or nil. +// Returns -1 if no such round exists. +func (hvs *HeightVoteSet) POLInfo() (polRound int32, polBlockID types.BlockID) { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + for r := hvs.round; r >= 0; r-- { + rvs := hvs.getVoteSet(r, cmtproto.PrevoteType) + polBlockID, ok := rvs.TwoThirdsMajority() + if ok { + return r, polBlockID + } + } + return -1, types.BlockID{} +} + +func (hvs *HeightVoteSet) getVoteSet(round int32, voteType cmtproto.SignedMsgType) *types.VoteSet { + rvs, ok := hvs.roundVoteSets[round] + if !ok { + return nil + } + switch voteType { + case cmtproto.PrevoteType: + return rvs.Prevotes + case cmtproto.PrecommitType: + return rvs.Precommits + default: + panic(fmt.Sprintf("Unexpected vote type %X", voteType)) + } +} + +// If a peer claims that it has 2/3 majority for given blockKey, call this. +// NOTE: if there are too many peers, or too much peer churn, +// this can cause memory issues. +// TODO: implement ability to remove peers too +func (hvs *HeightVoteSet) SetPeerMaj23( + round int32, + voteType cmtproto.SignedMsgType, + peerID p2p.ID, + blockID types.BlockID) error { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + if !types.IsVoteTypeValid(voteType) { + return fmt.Errorf("setPeerMaj23: Invalid vote type %X", voteType) + } + voteSet := hvs.getVoteSet(round, voteType) + if voteSet == nil { + return nil // something we don't know about yet + } + return voteSet.SetPeerMaj23(types.P2PID(peerID), blockID) +} + +//--------------------------------------------------------- +// string and json + +func (hvs *HeightVoteSet) String() string { + return hvs.StringIndented("") +} + +func (hvs *HeightVoteSet) StringIndented(indent string) string { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + vsStrings := make([]string, 0, (len(hvs.roundVoteSets)+1)*2) + // rounds 0 ~ hvs.round inclusive + for round := int32(0); round <= hvs.round; round++ { + voteSetString := hvs.roundVoteSets[round].Prevotes.StringShort() + vsStrings = append(vsStrings, voteSetString) + voteSetString = hvs.roundVoteSets[round].Precommits.StringShort() + vsStrings = append(vsStrings, voteSetString) + } + // all other peer catchup rounds + for round, roundVoteSet := range hvs.roundVoteSets { + if round <= hvs.round { + continue + } + voteSetString := roundVoteSet.Prevotes.StringShort() + vsStrings = append(vsStrings, voteSetString) + voteSetString = roundVoteSet.Precommits.StringShort() + vsStrings = append(vsStrings, voteSetString) + } + return fmt.Sprintf(`HeightVoteSet{H:%v R:0~%v +%s %v +%s}`, + hvs.height, hvs.round, + indent, strings.Join(vsStrings, "\n"+indent+" "), + indent) +} + +func (hvs *HeightVoteSet) MarshalJSON() ([]byte, error) { + hvs.mtx.Lock() + defer hvs.mtx.Unlock() + return cmtjson.Marshal(hvs.toAllRoundVotes()) +} + +func (hvs *HeightVoteSet) toAllRoundVotes() []roundVotes { + totalRounds := hvs.round + 1 + allVotes := make([]roundVotes, totalRounds) + // rounds 0 ~ hvs.round inclusive + for round := int32(0); round < totalRounds; round++ { + allVotes[round] = roundVotes{ + Round: round, + Prevotes: hvs.roundVoteSets[round].Prevotes.VoteStrings(), + PrevotesBitArray: hvs.roundVoteSets[round].Prevotes.BitArrayString(), + Precommits: hvs.roundVoteSets[round].Precommits.VoteStrings(), + PrecommitsBitArray: hvs.roundVoteSets[round].Precommits.BitArrayString(), + } + } + // TODO: all other peer catchup rounds + return allVotes +} + +type roundVotes struct { + Round int32 `json:"round"` + Prevotes []string `json:"prevotes"` + PrevotesBitArray string `json:"prevotes_bit_array"` + Precommits []string `json:"precommits"` + PrecommitsBitArray string `json:"precommits_bit_array"` +} diff --git a/consensus/types/height_vote_set_test.go b/consensus/types/height_vote_set_test.go new file mode 100644 index 0000000..9ec504f --- /dev/null +++ b/consensus/types/height_vote_set_test.go @@ -0,0 +1,99 @@ +package types + +import ( + "os" + "testing" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/stretchr/testify/require" +) + +var config *cfg.Config // NOTE: must be reset for each _test.go file + +func TestMain(m *testing.M) { + config = test.ResetTestRoot("consensus_height_vote_set_test") + code := m.Run() + os.RemoveAll(config.RootDir) + os.Exit(code) +} + +func TestPeerCatchupRounds(t *testing.T) { + valSet, privVals := types.RandValidatorSet(10, 1) + + hvs := NewExtendedHeightVoteSet(test.DefaultTestChainID, 1, valSet) + + vote999_0 := makeVoteHR(1, 0, 999, privVals) + added, err := hvs.AddVote(vote999_0, "peer1", true) + if !added || err != nil { + t.Error("Expected to successfully add vote from peer", added, err) + } + + vote1000_0 := makeVoteHR(1, 0, 1000, privVals) + added, err = hvs.AddVote(vote1000_0, "peer1", true) + if !added || err != nil { + t.Error("Expected to successfully add vote from peer", added, err) + } + + vote1001_0 := makeVoteHR(1, 0, 1001, privVals) + added, err = hvs.AddVote(vote1001_0, "peer1", true) + if err != ErrGotVoteFromUnwantedRound { + t.Errorf("expected GotVoteFromUnwantedRoundError, but got %v", err) + } + if added { + t.Error("Expected to *not* add vote from peer, too many catchup rounds.") + } + + added, err = hvs.AddVote(vote1001_0, "peer2", true) + if !added || err != nil { + t.Error("Expected to successfully add vote from another peer") + } +} + +func TestInconsistentExtensionData(t *testing.T) { + valSet, privVals := types.RandValidatorSet(10, 1) + + hvsE := NewExtendedHeightVoteSet(test.DefaultTestChainID, 1, valSet) + voteNoExt := makeVoteHR(1, 0, 20, privVals) + voteNoExt.Extension, voteNoExt.ExtensionSignature = nil, nil + require.Panics(t, func() { + _, _ = hvsE.AddVote(voteNoExt, "peer1", false) + }) + + hvsNoE := NewHeightVoteSet(test.DefaultTestChainID, 1, valSet) + voteExt := makeVoteHR(1, 0, 20, privVals) + require.Panics(t, func() { + _, _ = hvsNoE.AddVote(voteExt, "peer1", true) + }) +} + +func makeVoteHR( + height int64, + valIndex, + round int32, + privVals []types.PrivValidator, +) *types.Vote { + privVal := privVals[valIndex] + randBytes := cmtrand.Bytes(tmhash.Size) + + vote, err := types.MakeVote( + privVal, + test.DefaultTestChainID, + valIndex, + height, + round, + cmtproto.PrecommitType, + types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}}, + cmttime.Now(), + ) + if err != nil { + panic(err) + } + + return vote +} diff --git a/consensus/types/peer_round_state.go b/consensus/types/peer_round_state.go new file mode 100644 index 0000000..729d274 --- /dev/null +++ b/consensus/types/peer_round_state.go @@ -0,0 +1,68 @@ +package types + +import ( + "fmt" + "time" + + "github.com/cometbft/cometbft/libs/bits" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------------------------------- + +// PeerRoundState contains the known state of a peer. +// NOTE: Read-only when returned by PeerState.GetRoundState(). +type PeerRoundState struct { + Height int64 `json:"height"` // Height peer is at + Round int32 `json:"round"` // Round peer is at, -1 if unknown. + Step RoundStepType `json:"step"` // Step peer is at + + // Estimated start of round 0 at this height + StartTime time.Time `json:"start_time"` + + // True if peer has proposal for this round + Proposal bool `json:"proposal"` + ProposalBlockPartSetHeader types.PartSetHeader `json:"proposal_block_part_set_header"` + ProposalBlockParts *bits.BitArray `json:"proposal_block_parts"` + // Proposal's POL round. -1 if none. + ProposalPOLRound int32 `json:"proposal_pol_round"` + + // nil until ProposalPOLMessage received. + ProposalPOL *bits.BitArray `json:"proposal_pol"` + Prevotes *bits.BitArray `json:"prevotes"` // All votes peer has for this round + Precommits *bits.BitArray `json:"precommits"` // All precommits peer has for this round + LastCommitRound int32 `json:"last_commit_round"` // Round of commit for last height. -1 if none. + LastCommit *bits.BitArray `json:"last_commit"` // All commit precommits of commit for last height. + + // Round that we have commit for. Not necessarily unique. -1 if none. + CatchupCommitRound int32 `json:"catchup_commit_round"` + + // All commit precommits peer has for this height & CatchupCommitRound + CatchupCommit *bits.BitArray `json:"catchup_commit"` +} + +// String returns a string representation of the PeerRoundState +func (prs PeerRoundState) String() string { + return prs.StringIndented("") +} + +// StringIndented returns a string representation of the PeerRoundState +func (prs PeerRoundState) StringIndented(indent string) string { + return fmt.Sprintf(`PeerRoundState{ +%s %v/%v/%v @%v +%s Proposal %v -> %v +%s POL %v (round %v) +%s Prevotes %v +%s Precommits %v +%s LastCommit %v (round %v) +%s Catchup %v (round %v) +%s}`, + indent, prs.Height, prs.Round, prs.Step, prs.StartTime, + indent, prs.ProposalBlockPartSetHeader, prs.ProposalBlockParts, + indent, prs.ProposalPOL, prs.ProposalPOLRound, + indent, prs.Prevotes, + indent, prs.Precommits, + indent, prs.LastCommit, prs.LastCommitRound, + indent, prs.CatchupCommit, prs.CatchupCommitRound, + indent) +} diff --git a/consensus/types/round_state.go b/consensus/types/round_state.go new file mode 100644 index 0000000..69ff6e5 --- /dev/null +++ b/consensus/types/round_state.go @@ -0,0 +1,224 @@ +package types + +import ( + "encoding/json" + "fmt" + "time" + + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------------------------------- +// RoundStepType enum type + +// RoundStepType enumerates the state of the consensus state machine +type RoundStepType uint8 // These must be numeric, ordered. + +// RoundStepType +const ( + RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit + RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose + RoundStepPropose = RoundStepType(0x03) // Did propose, gossip proposal + RoundStepPrevote = RoundStepType(0x04) // Did prevote, gossip prevotes + RoundStepPrevoteWait = RoundStepType(0x05) // Did receive any +2/3 prevotes, start timeout + RoundStepPrecommit = RoundStepType(0x06) // Did precommit, gossip precommits + RoundStepPrecommitWait = RoundStepType(0x07) // Did receive any +2/3 precommits, start timeout + RoundStepCommit = RoundStepType(0x08) // Entered commit state machine + // NOTE: RoundStepNewHeight acts as RoundStepCommitWait. + + // NOTE: Update IsValid method if you change this! +) + +// IsValid returns true if the step is valid, false if unknown/undefined. +func (rs RoundStepType) IsValid() bool { + return uint8(rs) >= 0x01 && uint8(rs) <= 0x08 +} + +// String returns a string +func (rs RoundStepType) String() string { + switch rs { + case RoundStepNewHeight: + return "RoundStepNewHeight" + case RoundStepNewRound: + return "RoundStepNewRound" + case RoundStepPropose: + return "RoundStepPropose" + case RoundStepPrevote: + return "RoundStepPrevote" + case RoundStepPrevoteWait: + return "RoundStepPrevoteWait" + case RoundStepPrecommit: + return "RoundStepPrecommit" + case RoundStepPrecommitWait: + return "RoundStepPrecommitWait" + case RoundStepCommit: + return "RoundStepCommit" + default: + return "RoundStepUnknown" // Cannot panic. + } +} + +//----------------------------------------------------------------------------- + +// RoundState defines the internal consensus state. +// NOTE: Not thread safe. Should only be manipulated by functions downstream +// of the cs.receiveRoutine +type RoundState struct { + Height int64 `json:"height"` // Height we are working on + Round int32 `json:"round"` + Step RoundStepType `json:"step"` + StartTime time.Time `json:"start_time"` + + // Subjective time when +2/3 precommits for Block at Round were found + CommitTime time.Time `json:"commit_time"` + Validators *types.ValidatorSet `json:"validators"` + Proposal *types.Proposal `json:"proposal"` + ProposalBlock *types.Block `json:"proposal_block"` + ProposalBlockParts *types.PartSet `json:"proposal_block_parts"` + LockedRound int32 `json:"locked_round"` + LockedBlock *types.Block `json:"locked_block"` + LockedBlockParts *types.PartSet `json:"locked_block_parts"` + + // The variables below starting with "Valid..." derive their name from + // the algorithm presented in this paper: + // [The latest gossip on BFT consensus](https://arxiv.org/abs/1807.04938). + // Therefore, "Valid...": + // * means that the block or round that the variable refers to has + // received 2/3+ non-`nil` prevotes (a.k.a. a *polka*) + // * has nothing to do with whether the Application returned "Accept" in its + // response to `ProcessProposal`, or "Reject" + + // Last known round with POL for non-nil valid block. + ValidRound int32 `json:"valid_round"` + ValidBlock *types.Block `json:"valid_block"` // Last known block of POL mentioned above. + + // Last known block parts of POL mentioned above. + ValidBlockParts *types.PartSet `json:"valid_block_parts"` + Votes *HeightVoteSet `json:"votes"` + CommitRound int32 `json:"commit_round"` // + LastCommit *types.VoteSet `json:"last_commit"` // Last precommits at Height-1 + LastValidators *types.ValidatorSet `json:"last_validators"` + TriggeredTimeoutPrecommit bool `json:"triggered_timeout_precommit"` +} + +// Compressed version of the RoundState for use in RPC +type RoundStateSimple struct { + HeightRoundStep string `json:"height/round/step"` + StartTime time.Time `json:"start_time"` + ProposalBlockHash bytes.HexBytes `json:"proposal_block_hash"` + LockedBlockHash bytes.HexBytes `json:"locked_block_hash"` + ValidBlockHash bytes.HexBytes `json:"valid_block_hash"` + Votes json.RawMessage `json:"height_vote_set"` + Proposer types.ValidatorInfo `json:"proposer"` +} + +// Compress the RoundState to RoundStateSimple +func (rs *RoundState) RoundStateSimple() RoundStateSimple { + votesJSON, err := rs.Votes.MarshalJSON() + if err != nil { + panic(err) + } + + addr := rs.Validators.GetProposer().Address + idx, _ := rs.Validators.GetByAddress(addr) + + return RoundStateSimple{ + HeightRoundStep: fmt.Sprintf("%d/%d/%d", rs.Height, rs.Round, rs.Step), + StartTime: rs.StartTime, + ProposalBlockHash: rs.ProposalBlock.Hash(), + LockedBlockHash: rs.LockedBlock.Hash(), + ValidBlockHash: rs.ValidBlock.Hash(), + Votes: votesJSON, + Proposer: types.ValidatorInfo{ + Address: addr, + Index: idx, + }, + } +} + +// NewRoundEvent returns the RoundState with proposer information as an event. +func (rs *RoundState) NewRoundEvent() types.EventDataNewRound { + addr := rs.Validators.GetProposer().Address + idx, _ := rs.Validators.GetByAddress(addr) + + return types.EventDataNewRound{ + Height: rs.Height, + Round: rs.Round, + Step: rs.Step.String(), + Proposer: types.ValidatorInfo{ + Address: addr, + Index: idx, + }, + } +} + +// CompleteProposalEvent returns information about a proposed block as an event. +func (rs *RoundState) CompleteProposalEvent() types.EventDataCompleteProposal { + // We must construct BlockID from ProposalBlock and ProposalBlockParts + // cs.Proposal is not guaranteed to be set when this function is called + blockID := types.BlockID{ + Hash: rs.ProposalBlock.Hash(), + PartSetHeader: rs.ProposalBlockParts.Header(), + } + + return types.EventDataCompleteProposal{ + Height: rs.Height, + Round: rs.Round, + Step: rs.Step.String(), + BlockID: blockID, + } +} + +// RoundStateEvent returns the H/R/S of the RoundState as an event. +func (rs *RoundState) RoundStateEvent() types.EventDataRoundState { + return types.EventDataRoundState{ + Height: rs.Height, + Round: rs.Round, + Step: rs.Step.String(), + } +} + +// String returns a string +func (rs *RoundState) String() string { + return rs.StringIndented("") +} + +// StringIndented returns a string +func (rs *RoundState) StringIndented(indent string) string { + return fmt.Sprintf(`RoundState{ +%s H:%v R:%v S:%v +%s StartTime: %v +%s CommitTime: %v +%s Validators: %v +%s Proposal: %v +%s ProposalBlock: %v %v +%s LockedRound: %v +%s LockedBlock: %v %v +%s ValidRound: %v +%s ValidBlock: %v %v +%s Votes: %v +%s LastCommit: %v +%s LastValidators:%v +%s}`, + indent, rs.Height, rs.Round, rs.Step, + indent, rs.StartTime, + indent, rs.CommitTime, + indent, rs.Validators.StringIndented(indent+" "), + indent, rs.Proposal, + indent, rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort(), + indent, rs.LockedRound, + indent, rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort(), + indent, rs.ValidRound, + indent, rs.ValidBlockParts.StringShort(), rs.ValidBlock.StringShort(), + indent, rs.Votes.StringIndented(indent+" "), + indent, rs.LastCommit.StringShort(), + indent, rs.LastValidators.StringIndented(indent+" "), + indent) +} + +// StringShort returns a string +func (rs *RoundState) StringShort() string { + return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`, + rs.Height, rs.Round, rs.Step, rs.StartTime) +} diff --git a/consensus/wal.go b/consensus/wal.go new file mode 100644 index 0000000..204590e --- /dev/null +++ b/consensus/wal.go @@ -0,0 +1,434 @@ +package consensus + +import ( + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "io" + "path/filepath" + "time" + + "github.com/cosmos/gogoproto/proto" + + auto "github.com/cometbft/cometbft/libs/autofile" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/libs/service" + cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const ( + // time.Time + max consensus msg size + maxMsgSizeBytes = maxMsgSize + 24 + + // how often the WAL should be sync'd during period sync'ing + walDefaultFlushInterval = 2 * time.Second +) + +//-------------------------------------------------------- +// types and functions for savings consensus messages + +// TimedWALMessage wraps WALMessage and adds Time for debugging purposes. +type TimedWALMessage struct { + Time time.Time `json:"time"` + Msg WALMessage `json:"msg"` +} + +// EndHeightMessage marks the end of the given height inside WAL. +// @internal used by scripts/wal2json util. +type EndHeightMessage struct { + Height int64 `json:"height"` +} + +type WALMessage interface{} + +func init() { + cmtjson.RegisterType(msgInfo{}, "tendermint/wal/MsgInfo") + cmtjson.RegisterType(timeoutInfo{}, "tendermint/wal/TimeoutInfo") + cmtjson.RegisterType(EndHeightMessage{}, "tendermint/wal/EndHeightMessage") +} + +//-------------------------------------------------------- +// Simple write-ahead logger + +// WAL is an interface for any write-ahead logger. +type WAL interface { + Write(WALMessage) error + WriteSync(WALMessage) error + FlushAndSync() error + + SearchForEndHeight(height int64, options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) + + // service methods + Start() error + Stop() error + Wait() +} + +// Write ahead logger writes msgs to disk before they are processed. +// Can be used for crash-recovery and deterministic replay. +// TODO: currently the wal is overwritten during replay catchup, give it a mode +// so it's either reading or appending - must read to end to start appending +// again. +type BaseWAL struct { + service.BaseService + + group *auto.Group + + enc *WALEncoder + + flushTicker *time.Ticker + flushInterval time.Duration +} + +var _ WAL = &BaseWAL{} + +// NewWAL returns a new write-ahead logger based on `baseWAL`, which implements +// WAL. It's flushed and synced to disk every 2s and once when stopped. +func NewWAL(walFile string, groupOptions ...func(*auto.Group)) (*BaseWAL, error) { + err := cmtos.EnsureDir(filepath.Dir(walFile), 0o700) + if err != nil { + return nil, fmt.Errorf("failed to ensure WAL directory is in place: %w", err) + } + + group, err := auto.OpenGroup(walFile, groupOptions...) + if err != nil { + return nil, err + } + wal := &BaseWAL{ + group: group, + enc: NewWALEncoder(group), + flushInterval: walDefaultFlushInterval, + } + wal.BaseService = *service.NewBaseService(nil, "baseWAL", wal) + return wal, nil +} + +// SetFlushInterval allows us to override the periodic flush interval for the WAL. +func (wal *BaseWAL) SetFlushInterval(i time.Duration) { + wal.flushInterval = i +} + +func (wal *BaseWAL) Group() *auto.Group { + return wal.group +} + +func (wal *BaseWAL) SetLogger(l log.Logger) { + wal.Logger = l + wal.group.SetLogger(l) +} + +func (wal *BaseWAL) OnStart() error { + size, err := wal.group.Head.Size() + if err != nil { + return err + } else if size == 0 { + if err := wal.WriteSync(EndHeightMessage{0}); err != nil { + return err + } + } + err = wal.group.Start() + if err != nil { + return err + } + wal.flushTicker = time.NewTicker(wal.flushInterval) + go wal.processFlushTicks() + return nil +} + +func (wal *BaseWAL) processFlushTicks() { + for { + select { + case <-wal.flushTicker.C: + if err := wal.FlushAndSync(); err != nil { + wal.Logger.Error("Periodic WAL flush failed", "err", err) + } + case <-wal.Quit(): + return + } + } +} + +// FlushAndSync flushes and fsync's the underlying group's data to disk. +// See auto#FlushAndSync +func (wal *BaseWAL) FlushAndSync() error { + return wal.group.FlushAndSync() +} + +// Stop the underlying autofile group. +// Use Wait() to ensure it's finished shutting down +// before cleaning up files. +func (wal *BaseWAL) OnStop() { + wal.flushTicker.Stop() + if err := wal.FlushAndSync(); err != nil { + wal.Logger.Error("error on flush data to disk", "error", err) + } + if err := wal.group.Stop(); err != nil { + wal.Logger.Error("error trying to stop wal", "error", err) + } + wal.group.Close() +} + +// Wait for the underlying autofile group to finish shutting down +// so it's safe to cleanup files. +func (wal *BaseWAL) Wait() { + wal.group.Wait() +} + +// Write is called in newStep and for each receive on the +// peerMsgQueue and the timeoutTicker. +// NOTE: does not call fsync() +func (wal *BaseWAL) Write(msg WALMessage) error { + if wal == nil { + return nil + } + + if err := wal.enc.Encode(&TimedWALMessage{cmttime.Now(), msg}); err != nil { + wal.Logger.Error("Error writing msg to consensus wal. WARNING: recover may not be possible for the current height", + "err", err, "msg", msg) + return err + } + + return nil +} + +// WriteSync is called when we receive a msg from ourselves +// so that we write to disk before sending signed messages. +// NOTE: calls fsync() +func (wal *BaseWAL) WriteSync(msg WALMessage) error { + if wal == nil { + return nil + } + + if err := wal.Write(msg); err != nil { + return err + } + + if err := wal.FlushAndSync(); err != nil { + wal.Logger.Error(`WriteSync failed to flush consensus wal. + WARNING: may result in creating alternative proposals / votes for the current height iff the node restarted`, + "err", err) + return err + } + + return nil +} + +// WALSearchOptions are optional arguments to SearchForEndHeight. +type WALSearchOptions struct { + // IgnoreDataCorruptionErrors set to true will result in skipping data corruption errors. + IgnoreDataCorruptionErrors bool +} + +// SearchForEndHeight searches for the EndHeightMessage with the given height +// and returns an auto.GroupReader, whenever it was found or not and an error. +// Group reader will be nil if found equals false. +// +// CONTRACT: caller must close group reader. +func (wal *BaseWAL) SearchForEndHeight( + height int64, + options *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { + var ( + msg *TimedWALMessage + gr *auto.GroupReader + ) + lastHeightFound := int64(-1) + + // NOTE: starting from the last file in the group because we're usually + // searching for the last height. See replay.go + min, max := wal.group.MinIndex(), wal.group.MaxIndex() + wal.Logger.Info("Searching for height", "height", height, "min", min, "max", max) + for index := max; index >= min; index-- { + gr, err = wal.group.NewReader(index) + if err != nil { + return nil, false, err + } + + dec := NewWALDecoder(gr) + for { + msg, err = dec.Decode() + if err == io.EOF { + // OPTIMISATION: no need to look for height in older files if we've seen h < height + if lastHeightFound > 0 && lastHeightFound < height { + gr.Close() + return nil, false, nil + } + // check next file + break + } + if options.IgnoreDataCorruptionErrors && IsDataCorruptionError(err) { + wal.Logger.Error("Corrupted entry. Skipping...", "err", err) + // do nothing + continue + } else if err != nil { + gr.Close() + return nil, false, err + } + + if m, ok := msg.Msg.(EndHeightMessage); ok { + lastHeightFound = m.Height + if m.Height == height { // found + wal.Logger.Info("Found", "height", height, "index", index) + return gr, true, nil + } + } + } + gr.Close() + } + + return nil, false, nil +} + +// A WALEncoder writes custom-encoded WAL messages to an output stream. +// +// Format: 4 bytes CRC sum + 4 bytes length + arbitrary-length value +type WALEncoder struct { + wr io.Writer +} + +// NewWALEncoder returns a new encoder that writes to wr. +func NewWALEncoder(wr io.Writer) *WALEncoder { + return &WALEncoder{wr} +} + +// Encode writes the custom encoding of v to the stream. It returns an error if +// the encoded size of v is greater than 1MB. Any error encountered +// during the write is also returned. +func (enc *WALEncoder) Encode(v *TimedWALMessage) error { + pbMsg, err := WALToProto(v.Msg) + if err != nil { + return err + } + pv := cmtcons.TimedWALMessage{ + Time: v.Time, + Msg: pbMsg, + } + + data, err := proto.Marshal(&pv) + if err != nil { + panic(fmt.Errorf("encode timed wall message failure: %w", err)) + } + + crc := crc32.Checksum(data, crc32c) + length := uint32(len(data)) + if length > maxMsgSizeBytes { + return fmt.Errorf("msg is too big: %d bytes, max: %d bytes", length, maxMsgSizeBytes) + } + totalLength := 8 + int(length) + + msg := make([]byte, totalLength) + binary.BigEndian.PutUint32(msg[0:4], crc) + binary.BigEndian.PutUint32(msg[4:8], length) + copy(msg[8:], data) + + _, err = enc.wr.Write(msg) + return err +} + +// IsDataCorruptionError returns true if data has been corrupted inside WAL. +func IsDataCorruptionError(err error) bool { + _, ok := err.(DataCorruptionError) + return ok +} + +// DataCorruptionError is an error that occures if data on disk was corrupted. +type DataCorruptionError struct { + cause error +} + +func (e DataCorruptionError) Error() string { + return fmt.Sprintf("DataCorruptionError[%v]", e.cause) +} + +func (e DataCorruptionError) Cause() error { + return e.cause +} + +// A WALDecoder reads and decodes custom-encoded WAL messages from an input +// stream. See WALEncoder for the format used. +// +// It will also compare the checksums and make sure data size is equal to the +// length from the header. If that is not the case, error will be returned. +type WALDecoder struct { + rd io.Reader +} + +// NewWALDecoder returns a new decoder that reads from rd. +func NewWALDecoder(rd io.Reader) *WALDecoder { + return &WALDecoder{rd} +} + +// Decode reads the next custom-encoded value from its reader and returns it. +func (dec *WALDecoder) Decode() (*TimedWALMessage, error) { + b := make([]byte, 4) + + _, err := dec.rd.Read(b) + if errors.Is(err, io.EOF) { + return nil, err + } + if err != nil { + return nil, DataCorruptionError{fmt.Errorf("failed to read checksum: %v", err)} + } + crc := binary.BigEndian.Uint32(b) + + b = make([]byte, 4) + _, err = dec.rd.Read(b) + if err != nil { + return nil, DataCorruptionError{fmt.Errorf("failed to read length: %v", err)} + } + length := binary.BigEndian.Uint32(b) + + if length > maxMsgSizeBytes { + return nil, DataCorruptionError{fmt.Errorf( + "length %d exceeded maximum possible value of %d bytes", + length, + maxMsgSizeBytes)} + } + + data := make([]byte, length) + n, err := dec.rd.Read(data) + if err != nil { + return nil, DataCorruptionError{fmt.Errorf("failed to read data: %v (read: %d, wanted: %d)", err, n, length)} + } + + // check checksum before decoding data + actualCRC := crc32.Checksum(data, crc32c) + if actualCRC != crc { + return nil, DataCorruptionError{fmt.Errorf("checksums do not match: read: %v, actual: %v", crc, actualCRC)} + } + + res := new(cmtcons.TimedWALMessage) + err = proto.Unmarshal(data, res) + if err != nil { + return nil, DataCorruptionError{fmt.Errorf("failed to decode data: %v", err)} + } + + walMsg, err := WALFromProto(res.Msg) + if err != nil { + return nil, DataCorruptionError{fmt.Errorf("failed to convert from proto: %w", err)} + } + tMsgWal := &TimedWALMessage{ + Time: res.Time, + Msg: walMsg, + } + + return tMsgWal, err +} + +type nilWAL struct{} + +var _ WAL = nilWAL{} + +func (nilWAL) Write(WALMessage) error { return nil } +func (nilWAL) WriteSync(WALMessage) error { return nil } +func (nilWAL) FlushAndSync() error { return nil } +func (nilWAL) SearchForEndHeight(int64, *WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + return nil, false, nil +} +func (nilWAL) Start() error { return nil } +func (nilWAL) Stop() error { return nil } +func (nilWAL) Wait() {} diff --git a/consensus/wal_fuzz.go b/consensus/wal_fuzz.go new file mode 100644 index 0000000..73eec7d --- /dev/null +++ b/consensus/wal_fuzz.go @@ -0,0 +1,32 @@ +//go:build gofuzz +// +build gofuzz + +package consensus + +import ( + "bytes" + "io" +) + +func Fuzz(data []byte) int { + dec := NewWALDecoder(bytes.NewReader(data)) + for { + msg, err := dec.Decode() + if err == io.EOF { + break + } + if err != nil { + if msg != nil { + panic("msg != nil on error") + } + return 0 + } + var w bytes.Buffer + enc := NewWALEncoder(&w) + err = enc.Encode(msg) + if err != nil { + panic(err) + } + } + return 1 +} diff --git a/consensus/wal_generator.go b/consensus/wal_generator.go new file mode 100644 index 0000000..8543b57 --- /dev/null +++ b/consensus/wal_generator.go @@ -0,0 +1,228 @@ +package consensus + +import ( + "bufio" + "bytes" + "fmt" + "io" + "path/filepath" + "testing" + "time" + + db "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/example/kvstore" + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" +) + +// WALGenerateNBlocks generates a consensus WAL. It does this by spinning up a +// stripped down version of node (proxy app, event bus, consensus state) with a +// persistent kvstore application and special consensus wal instance +// (byteBufferWAL) and waits until numBlocks are created. +// If the node fails to produce given numBlocks, it returns an error. +func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int, config *cfg.Config) (err error) { + app := kvstore.NewPersistentApplication(filepath.Join(config.DBDir(), "wal_generator")) + + logger := log.TestingLogger().With("wal_generator", "wal_generator") + logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks) + + // COPY PASTE FROM node.go WITH A FEW MODIFICATIONS + // NOTE: we can't import node package because of circular dependency. + // NOTE: we don't do handshake so need to set state.Version.Consensus.App directly. + privValidatorKeyFile := config.PrivValidatorKeyFile() + privValidatorStateFile := config.PrivValidatorStateFile() + privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile) + genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) + if err != nil { + return fmt.Errorf("failed to read genesis file: %w", err) + } + blockStoreDB := db.NewMemDB() + stateDB := blockStoreDB + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := sm.MakeGenesisState(genDoc) + if err != nil { + return fmt.Errorf("failed to make genesis state: %w", err) + } + state.Version.Consensus.App = kvstore.AppVersion + if err = stateStore.Save(state); err != nil { + t.Error(err) + } + + blockStore := store.NewBlockStore(blockStoreDB) + + proxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app), proxy.NopMetrics()) + proxyApp.SetLogger(logger.With("module", "proxy")) + if err := proxyApp.Start(); err != nil { + return fmt.Errorf("failed to start proxy app connections: %w", err) + } + t.Cleanup(func() { + if err := proxyApp.Stop(); err != nil { + t.Error(err) + } + }) + + eventBus := types.NewEventBus() + eventBus.SetLogger(logger.With("module", "events")) + if err := eventBus.Start(); err != nil { + return fmt.Errorf("failed to start event bus: %w", err) + } + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + mempool := emptyMempool{} + evpool := sm.EmptyEvidencePool{} + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool, blockStore) + consensusState := NewState(config.Consensus, state.Copy(), blockExec, blockStore, mempool, evpool) + consensusState.SetLogger(logger) + consensusState.SetEventBus(eventBus) + if privValidator != nil { + consensusState.SetPrivValidator(privValidator) + } + // END OF COPY PASTE + + // set consensus wal to buffered WAL, which will write all incoming msgs to buffer + numBlocksWritten := make(chan struct{}) + wal := newByteBufferWAL(logger, NewWALEncoder(wr), int64(numBlocks), numBlocksWritten) + // see wal.go#103 + if err := wal.Write(EndHeightMessage{0}); err != nil { + t.Error(err) + } + + consensusState.wal = wal + + if err := consensusState.Start(); err != nil { + return fmt.Errorf("failed to start consensus state: %w", err) + } + + select { + case <-numBlocksWritten: + if err := consensusState.Stop(); err != nil { + t.Error(err) + } + return nil + case <-time.After(1 * time.Minute): + if err := consensusState.Stop(); err != nil { + t.Error(err) + } + return fmt.Errorf("waited too long for CometBFT to produce %d blocks (grep logs for `wal_generator`)", numBlocks) + } +} + +// WALWithNBlocks returns a WAL content with numBlocks. +func WALWithNBlocks(t *testing.T, numBlocks int, config *cfg.Config) (data []byte, err error) { + var b bytes.Buffer + wr := bufio.NewWriter(&b) + + if err := WALGenerateNBlocks(t, wr, numBlocks, config); err != nil { + return []byte{}, err + } + + wr.Flush() + return b.Bytes(), nil +} + +func randPort() int { + // returns between base and base + spread + base, spread := 20000, 20000 + return base + cmtrand.Intn(spread) +} + +func makeAddrs() (string, string, string) { + start := randPort() + return fmt.Sprintf("tcp://127.0.0.1:%d", start), + fmt.Sprintf("tcp://127.0.0.1:%d", start+1), + fmt.Sprintf("tcp://127.0.0.1:%d", start+2) +} + +// getConfig returns a config for test cases +func getConfig(t *testing.T) *cfg.Config { + c := test.ResetTestRoot(t.Name()) + + // and we use random ports to run in parallel + cmt, rpc, grpc := makeAddrs() + c.P2P.ListenAddress = cmt + c.RPC.ListenAddress = rpc + c.RPC.GRPCListenAddress = grpc + return c +} + +// byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops +// when the heightToStop is reached. Client will be notified via +// signalWhenStopsTo channel. +type byteBufferWAL struct { + enc *WALEncoder + stopped bool + heightToStop int64 + signalWhenStopsTo chan<- struct{} + + logger log.Logger +} + +// needed for determinism +var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z") + +func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL { + return &byteBufferWAL{ + enc: enc, + heightToStop: nBlocks, + signalWhenStopsTo: signalStop, + logger: logger, + } +} + +// Save writes message to the internal buffer except when heightToStop is +// reached, in which case it will signal the caller via signalWhenStopsTo and +// skip writing. +func (w *byteBufferWAL) Write(m WALMessage) error { + if w.stopped { + w.logger.Debug("WAL already stopped. Not writing message", "msg", m) + return nil + } + + if endMsg, ok := m.(EndHeightMessage); ok { + w.logger.Debug("WAL write end height message", "height", endMsg.Height, "stopHeight", w.heightToStop) + if endMsg.Height == w.heightToStop { + w.logger.Debug("Stopping WAL at height", "height", endMsg.Height) + w.signalWhenStopsTo <- struct{}{} + w.stopped = true + return nil + } + } + + w.logger.Debug("WAL Write Message", "msg", m) + err := w.enc.Encode(&TimedWALMessage{fixedTime, m}) + if err != nil { + panic(fmt.Sprintf("failed to encode the msg %v", m)) + } + + return nil +} + +func (w *byteBufferWAL) WriteSync(m WALMessage) error { + return w.Write(m) +} + +func (w *byteBufferWAL) FlushAndSync() error { return nil } + +func (w *byteBufferWAL) SearchForEndHeight( + int64, + *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { + return nil, false, nil +} + +func (w *byteBufferWAL) Start() error { return nil } +func (w *byteBufferWAL) Stop() error { return nil } +func (w *byteBufferWAL) Wait() {} diff --git a/consensus/wal_test.go b/consensus/wal_test.go new file mode 100644 index 0000000..24aee47 --- /dev/null +++ b/consensus/wal_test.go @@ -0,0 +1,285 @@ +package consensus + +import ( + "bytes" + "crypto/rand" + "os" + "path/filepath" + + // "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/consensus/types" + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/libs/autofile" + "github.com/cometbft/cometbft/libs/log" + cmttypes "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const ( + walTestFlushInterval = time.Duration(100) * time.Millisecond +) + +func TestWALTruncate(t *testing.T) { + walDir, err := os.MkdirTemp("", "wal") + require.NoError(t, err) + defer os.RemoveAll(walDir) + + walFile := filepath.Join(walDir, "wal") + + // this magic number 4K can truncate the content when RotateFile. + // defaultHeadSizeLimit(10M) is hard to simulate. + // this magic number 1 * time.Millisecond make RotateFile check frequently. + // defaultGroupCheckDuration(5s) is hard to simulate. + wal, err := NewWAL(walFile, + autofile.GroupHeadSizeLimit(4096), + autofile.GroupCheckDuration(1*time.Millisecond), + ) + require.NoError(t, err) + wal.SetLogger(log.TestingLogger()) + err = wal.Start() + require.NoError(t, err) + defer func() { + if err := wal.Stop(); err != nil { + t.Error(err) + } + // wait for the wal to finish shutting down so we + // can safely remove the directory + wal.Wait() + }() + + // 60 block's size nearly 70K, greater than group's headBuf size(4096 * 10), + // when headBuf is full, truncate content will Flush to the file. at this + // time, RotateFile is called, truncate content exist in each file. + err = WALGenerateNBlocks(t, wal.Group(), 60, getConfig(t)) + require.NoError(t, err) + + time.Sleep(1 * time.Millisecond) // wait groupCheckDuration, make sure RotateFile run + + if err := wal.FlushAndSync(); err != nil { + t.Error(err) + } + + h := int64(50) + gr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{}) + assert.NoError(t, err, "expected not to err on height %d", h) + assert.True(t, found, "expected to find end height for %d", h) + assert.NotNil(t, gr) + defer gr.Close() + + dec := NewWALDecoder(gr) + msg, err := dec.Decode() + assert.NoError(t, err, "expected to decode a message") + rs, ok := msg.Msg.(cmttypes.EventDataRoundState) + assert.True(t, ok, "expected message of type EventDataRoundState") + assert.Equal(t, rs.Height, h+1, "wrong height") +} + +func TestWALEncoderDecoder(t *testing.T) { + now := cmttime.Now() + msgs := []TimedWALMessage{ + {Time: now, Msg: EndHeightMessage{0}}, + {Time: now, Msg: timeoutInfo{Duration: time.Second, Height: 1, Round: 1, Step: types.RoundStepPropose}}, + {Time: now, Msg: cmttypes.EventDataRoundState{Height: 1, Round: 1, Step: ""}}, + } + + b := new(bytes.Buffer) + + for _, msg := range msgs { + msg := msg + + b.Reset() + + enc := NewWALEncoder(b) + err := enc.Encode(&msg) + require.NoError(t, err) + + dec := NewWALDecoder(b) + decoded, err := dec.Decode() + require.NoError(t, err) + assert.Equal(t, msg.Time.UTC(), decoded.Time) + assert.Equal(t, msg.Msg, decoded.Msg) + } +} + +func TestWALWrite(t *testing.T) { + walDir, err := os.MkdirTemp("", "wal") + require.NoError(t, err) + defer os.RemoveAll(walDir) + walFile := filepath.Join(walDir, "wal") + + wal, err := NewWAL(walFile) + require.NoError(t, err) + err = wal.Start() + require.NoError(t, err) + defer func() { + if err := wal.Stop(); err != nil { + t.Error(err) + } + // wait for the wal to finish shutting down so we + // can safely remove the directory + wal.Wait() + }() + + // 1) Write returns an error if msg is too big + msg := &BlockPartMessage{ + Height: 1, + Round: 1, + Part: &cmttypes.Part{ + Index: 1, + Bytes: make([]byte, 1), + Proof: merkle.Proof{ + Total: 1, + Index: 1, + LeafHash: make([]byte, maxMsgSizeBytes-30), + }, + }, + } + + err = wal.Write(msgInfo{ + Msg: msg, + }) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), "msg is too big") + } +} + +func TestWALSearchForEndHeight(t *testing.T) { + walBody, err := WALWithNBlocks(t, 6, getConfig(t)) + if err != nil { + t.Fatal(err) + } + walFile := tempWALWithData(walBody) + + wal, err := NewWAL(walFile) + require.NoError(t, err) + wal.SetLogger(log.TestingLogger()) + + h := int64(3) + gr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{}) + assert.NoError(t, err, "expected not to err on height %d", h) + assert.True(t, found, "expected to find end height for %d", h) + assert.NotNil(t, gr) + defer gr.Close() + + dec := NewWALDecoder(gr) + msg, err := dec.Decode() + assert.NoError(t, err, "expected to decode a message") + rs, ok := msg.Msg.(cmttypes.EventDataRoundState) + assert.True(t, ok, "expected message of type EventDataRoundState") + assert.Equal(t, rs.Height, h+1, "wrong height") +} + +func TestWALPeriodicSync(t *testing.T) { + walDir, err := os.MkdirTemp("", "wal") + require.NoError(t, err) + defer os.RemoveAll(walDir) + + walFile := filepath.Join(walDir, "wal") + wal, err := NewWAL(walFile, autofile.GroupCheckDuration(1*time.Millisecond)) + require.NoError(t, err) + + wal.SetFlushInterval(walTestFlushInterval) + wal.SetLogger(log.TestingLogger()) + + // Generate some data + err = WALGenerateNBlocks(t, wal.Group(), 5, getConfig(t)) + require.NoError(t, err) + + // We should have data in the buffer now + assert.NotZero(t, wal.Group().Buffered()) + + require.NoError(t, wal.Start()) + defer func() { + if err := wal.Stop(); err != nil { + t.Error(err) + } + wal.Wait() + }() + + time.Sleep(walTestFlushInterval + (10 * time.Millisecond)) + + // The data should have been flushed by the periodic sync + assert.Zero(t, wal.Group().Buffered()) + + h := int64(4) + gr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{}) + assert.NoError(t, err, "expected not to err on height %d", h) + assert.True(t, found, "expected to find end height for %d", h) + assert.NotNil(t, gr) + if gr != nil { + gr.Close() + } +} + +/* +var initOnce sync.Once + +func registerInterfacesOnce() { + initOnce.Do(func() { + var _ = wire.RegisterInterface( + struct{ WALMessage }{}, + wire.ConcreteType{[]byte{}, 0x10}, + ) + }) +} +*/ + +func nBytes(n int) []byte { + buf := make([]byte, n) + n, _ = rand.Read(buf) + return buf[:n] +} + +func benchmarkWalDecode(b *testing.B, n int) { + // registerInterfacesOnce() + + buf := new(bytes.Buffer) + enc := NewWALEncoder(buf) + + data := nBytes(n) + if err := enc.Encode(&TimedWALMessage{Msg: data, Time: time.Now().Round(time.Second).UTC()}); err != nil { + b.Error(err) + } + + encoded := buf.Bytes() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + buf.Reset() + buf.Write(encoded) + dec := NewWALDecoder(buf) + if _, err := dec.Decode(); err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() +} + +func BenchmarkWalDecode512B(b *testing.B) { + benchmarkWalDecode(b, 512) +} + +func BenchmarkWalDecode10KB(b *testing.B) { + benchmarkWalDecode(b, 10*1024) +} +func BenchmarkWalDecode100KB(b *testing.B) { + benchmarkWalDecode(b, 100*1024) +} +func BenchmarkWalDecode1MB(b *testing.B) { + benchmarkWalDecode(b, 1024*1024) +} +func BenchmarkWalDecode10MB(b *testing.B) { + benchmarkWalDecode(b, 10*1024*1024) +} +func BenchmarkWalDecode100MB(b *testing.B) { + benchmarkWalDecode(b, 100*1024*1024) +} +func BenchmarkWalDecode1GB(b *testing.B) { + benchmarkWalDecode(b, 1024*1024*1024) +} diff --git a/crypto/README.md b/crypto/README.md new file mode 100644 index 0000000..5e783ca --- /dev/null +++ b/crypto/README.md @@ -0,0 +1,30 @@ +# crypto + +crypto is the cryptographic package adapted for CometBFT's uses + +## Importing it + +To get the interfaces, +`import "github.com/cometbft/cometbft/crypto"` + +For any specific algorithm, use its specific module e.g. +`import "github.com/cometbft/cometbft/crypto/ed25519"` + +## Binary encoding + +For Binary encoding, please refer to the [CometBFT encoding specification](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/encoding.md). + +## JSON Encoding + +JSON encoding is done using CometBFT's internal json encoder. For more information on JSON encoding, please refer to [CometBFT JSON encoding](https://github.com/cometbft/cometbft/blob/v0.38.x/libs/json/doc.go) + +```go +Example JSON encodings: + +ed25519.PrivKey - {"type":"tendermint/PrivKeyEd25519","value":"EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ=="} +ed25519.PubKey - {"type":"tendermint/PubKeyEd25519","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="} +sr25519.PrivKeySr25519 - {"type":"tendermint/PrivKeySr25519","value":"xtYVH8UCIqfrY8FIFc0QEpAEBShSG4NT0zlEOVSZ2w4="} +sr25519.PubKeySr25519 - {"type":"tendermint/PubKeySr25519","value":"8sKBLKQ/OoXMcAJVxBqz1U7TyxRFQ5cmliuHy4MrF0s="} +crypto.PrivKeySecp256k1 - {"type":"tendermint/PrivKeySecp256k1","value":"zx4Pnh67N+g2V+5vZbQzEyRerX9c4ccNZOVzM9RvJ0Y="} +crypto.PubKeySecp256k1 - {"type":"tendermint/PubKeySecp256k1","value":"A8lPKJXcNl5VHt1FK8a244K9EJuS4WX1hFBnwisi0IJx"} +``` diff --git a/crypto/armor/armor.go b/crypto/armor/armor.go new file mode 100644 index 0000000..a978fa7 --- /dev/null +++ b/crypto/armor/armor.go @@ -0,0 +1,39 @@ +package armor + +import ( + "bytes" + "fmt" + "io" + + "golang.org/x/crypto/openpgp/armor" //nolint: staticcheck +) + +func EncodeArmor(blockType string, headers map[string]string, data []byte) string { + buf := new(bytes.Buffer) + w, err := armor.Encode(buf, blockType, headers) + if err != nil { + panic(fmt.Errorf("could not encode ascii armor: %s", err)) + } + _, err = w.Write(data) + if err != nil { + panic(fmt.Errorf("could not encode ascii armor: %s", err)) + } + err = w.Close() + if err != nil { + panic(fmt.Errorf("could not encode ascii armor: %s", err)) + } + return buf.String() +} + +func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) { + buf := bytes.NewBufferString(armorStr) + block, err := armor.Decode(buf) + if err != nil { + return "", nil, nil, err + } + data, err = io.ReadAll(block.Body) + if err != nil { + return "", nil, nil, err + } + return block.Type, block.Header, data, nil +} diff --git a/crypto/armor/armor_test.go b/crypto/armor/armor_test.go new file mode 100644 index 0000000..2849cb6 --- /dev/null +++ b/crypto/armor/armor_test.go @@ -0,0 +1,20 @@ +package armor + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestArmor(t *testing.T) { + blockType := "MINT TEST" + data := []byte("somedata") + armorStr := EncodeArmor(blockType, nil, data) + + // Decode armorStr and test for equivalence. + blockType2, _, data2, err := DecodeArmor(armorStr) + require.Nil(t, err, "%+v", err) + assert.Equal(t, blockType, blockType2) + assert.Equal(t, data, data2) +} diff --git a/crypto/batch/batch.go b/crypto/batch/batch.go new file mode 100644 index 0000000..557b1ee --- /dev/null +++ b/crypto/batch/batch.go @@ -0,0 +1,35 @@ +package batch + +import ( + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/sr25519" +) + +// CreateBatchVerifier checks if a key type implements the batch verifier interface. +// Currently only ed25519 & sr25519 supports batch verification. +func CreateBatchVerifier(pk crypto.PubKey) (crypto.BatchVerifier, bool) { + switch pk.Type() { + case ed25519.KeyType: + return ed25519.NewBatchVerifier(), true + case sr25519.KeyType: + return sr25519.NewBatchVerifier(), true + } + + // case where the key does not support batch verification + return nil, false +} + +// SupportsBatchVerifier checks if a key type implements the batch verifier +// interface. +func SupportsBatchVerifier(pk crypto.PubKey) bool { + if pk == nil { + return false + } + switch pk.Type() { + case ed25519.KeyType, sr25519.KeyType: + return true + } + + return false +} diff --git a/crypto/crypto.go b/crypto/crypto.go new file mode 100644 index 0000000..f725f9c --- /dev/null +++ b/crypto/crypto.go @@ -0,0 +1,54 @@ +package crypto + +import ( + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/bytes" +) + +const ( + // AddressSize is the size of a pubkey address. + AddressSize = tmhash.TruncatedSize +) + +// An address is a []byte, but hex-encoded even in JSON. +// []byte leaves us the option to change the address length. +// Use an alias so Unmarshal methods (with ptr receivers) are available too. +type Address = bytes.HexBytes + +func AddressHash(bz []byte) Address { + return Address(tmhash.SumTruncated(bz)) +} + +type PubKey interface { + Address() Address + Bytes() []byte + VerifySignature(msg []byte, sig []byte) bool + Equals(PubKey) bool + Type() string +} + +type PrivKey interface { + Bytes() []byte + Sign(msg []byte) ([]byte, error) + PubKey() PubKey + Equals(PrivKey) bool + Type() string +} + +type Symmetric interface { + Keygen() []byte + Encrypt(plaintext []byte, secret []byte) (ciphertext []byte) + Decrypt(ciphertext []byte, secret []byte) (plaintext []byte, err error) +} + +// If a new key type implements batch verification, +// the key type must be registered in github.com/cometbft/cometbft/crypto/batch +type BatchVerifier interface { + // Add appends an entry into the BatchVerifier. + Add(key PubKey, message, signature []byte) error + // Verify verifies all the entries in the BatchVerifier, and returns + // if every signature in the batch is valid, and a vector of bools + // indicating the verification status of each signature (in the order + // that signatures were added to the batch). + Verify() (bool, []bool) +} diff --git a/crypto/doc.go b/crypto/doc.go new file mode 100644 index 0000000..12a94b0 --- /dev/null +++ b/crypto/doc.go @@ -0,0 +1,42 @@ +// crypto is a customized/convenience cryptography package for supporting +// CometBFT. + +// It wraps select functionality of equivalent functions in the +// Go standard library, for easy usage with our libraries. + +// Keys: + +// All key generation functions return an instance of the PrivKey interface +// which implements methods + +// AssertIsPrivKeyInner() +// Bytes() []byte +// Sign(msg []byte) Signature +// PubKey() PubKey +// Equals(PrivKey) bool +// Wrap() PrivKey + +// From the above method we can: +// a) Retrieve the public key if needed + +// pubKey := key.PubKey() + +// For example: +// privKey, err := ed25519.GenPrivKey() +// if err != nil { +// ... +// } +// pubKey := privKey.PubKey() +// ... +// // And then you can use the private and public key +// doSomething(privKey, pubKey) + +// We also provide hashing wrappers around algorithms: + +// Sha256 +// sum := crypto.Sha256([]byte("This is CometBFT")) +// fmt.Printf("%x\n", sum) + +package crypto + +// TODO: Add more docs in here diff --git a/crypto/ed25519/bench_test.go b/crypto/ed25519/bench_test.go new file mode 100644 index 0000000..25d97aa --- /dev/null +++ b/crypto/ed25519/bench_test.go @@ -0,0 +1,68 @@ +package ed25519 + +import ( + "fmt" + "io" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/internal/benchmarking" +) + +func BenchmarkKeyGeneration(b *testing.B) { + benchmarkKeygenWrapper := func(reader io.Reader) crypto.PrivKey { + return genPrivKey(reader) + } + benchmarking.BenchmarkKeyGeneration(b, benchmarkKeygenWrapper) +} + +func BenchmarkSigning(b *testing.B) { + priv := GenPrivKey() + benchmarking.BenchmarkSigning(b, priv) +} + +func BenchmarkVerification(b *testing.B) { + priv := GenPrivKey() + benchmarking.BenchmarkVerification(b, priv) +} + +func BenchmarkVerifyBatch(b *testing.B) { + msg := []byte("BatchVerifyTest") + + for _, sigsCount := range []int{1, 8, 64, 1024} { + sigsCount := sigsCount + b.Run(fmt.Sprintf("sig-count-%d", sigsCount), func(b *testing.B) { + // Pre-generate all of the keys, and signatures, but do not + // benchmark key-generation and signing. + pubs := make([]crypto.PubKey, 0, sigsCount) + sigs := make([][]byte, 0, sigsCount) + for i := 0; i < sigsCount; i++ { + priv := GenPrivKey() + sig, _ := priv.Sign(msg) + pubs = append(pubs, priv.PubKey().(PubKey)) + sigs = append(sigs, sig) + } + b.ResetTimer() + + b.ReportAllocs() + // NOTE: dividing by n so that metrics are per-signature + for i := 0; i < b.N/sigsCount; i++ { + // The benchmark could just benchmark the Verify() + // routine, but there is non-trivial overhead associated + // with BatchVerifier.Add(), which should be included + // in the benchmark. + v := NewBatchVerifier() + for i := 0; i < sigsCount; i++ { + err := v.Add(pubs[i], msg, sigs[i]) + require.NoError(b, err) + } + + if ok, _ := v.Verify(); !ok { + b.Fatal("signature set failed batch verification") + } + } + }) + } +} diff --git a/crypto/ed25519/ed25519.go b/crypto/ed25519/ed25519.go new file mode 100644 index 0000000..3a8e131 --- /dev/null +++ b/crypto/ed25519/ed25519.go @@ -0,0 +1,228 @@ +package ed25519 + +import ( + "bytes" + "crypto/subtle" + "errors" + "fmt" + "io" + + "github.com/oasisprotocol/curve25519-voi/primitives/ed25519" + "github.com/oasisprotocol/curve25519-voi/primitives/ed25519/extra/cache" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtjson "github.com/cometbft/cometbft/libs/json" +) + +//------------------------------------- + +var ( + _ crypto.PrivKey = PrivKey{} + _ crypto.BatchVerifier = &BatchVerifier{} + + // curve25519-voi's Ed25519 implementation supports configurable + // verification behavior, and CometBFT uses the ZIP-215 verification + // semantics. + verifyOptions = &ed25519.Options{ + Verify: ed25519.VerifyOptionsZIP_215, + } + + cachingVerifier = cache.NewVerifier(cache.NewLRUCache(cacheSize)) +) + +const ( + PrivKeyName = "tendermint/PrivKeyEd25519" + PubKeyName = "tendermint/PubKeyEd25519" + // PubKeySize is is the size, in bytes, of public keys as used in this package. + PubKeySize = 32 + // PrivateKeySize is the size, in bytes, of private keys as used in this package. + PrivateKeySize = 64 + // Size of an Edwards25519 signature. Namely the size of a compressed + // Edwards25519 point, and a field element. Both of which are 32 bytes. + SignatureSize = 64 + // SeedSize is the size, in bytes, of private key seeds. These are the + // private key representations used by RFC 8032. + SeedSize = 32 + + KeyType = "ed25519" + + // cacheSize is the number of public keys that will be cached in + // an expanded format for repeated signature verification. + // + // TODO/perf: Either this should exclude single verification, or be + // tuned to `> validatorSize + maxTxnsPerBlock` to avoid cache + // thrashing. + cacheSize = 4096 +) + +func init() { + cmtjson.RegisterType(PubKey{}, PubKeyName) + cmtjson.RegisterType(PrivKey{}, PrivKeyName) +} + +// PrivKey implements crypto.PrivKey. +type PrivKey []byte + +// Bytes returns the privkey byte format. +func (privKey PrivKey) Bytes() []byte { + return []byte(privKey) +} + +// Sign produces a signature on the provided message. +// This assumes the privkey is wellformed in the golang format. +// The first 32 bytes should be random, +// corresponding to the normal ed25519 private key. +// The latter 32 bytes should be the compressed public key. +// If these conditions aren't met, Sign will panic or produce an +// incorrect signature. +func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { + signatureBytes := ed25519.Sign(ed25519.PrivateKey(privKey), msg) + return signatureBytes, nil +} + +// PubKey gets the corresponding public key from the private key. +// +// Panics if the private key is not initialized. +func (privKey PrivKey) PubKey() crypto.PubKey { + // If the latter 32 bytes of the privkey are all zero, privkey is not + // initialized. + initialized := false + for _, v := range privKey[32:] { + if v != 0 { + initialized = true + break + } + } + + if !initialized { + panic("Expected ed25519 PrivKey to include concatenated pubkey bytes") + } + + pubkeyBytes := make([]byte, PubKeySize) + copy(pubkeyBytes, privKey[32:]) + return PubKey(pubkeyBytes) +} + +// Equals - you probably don't need to use this. +// Runs in constant time based on length of the keys. +func (privKey PrivKey) Equals(other crypto.PrivKey) bool { + if otherEd, ok := other.(PrivKey); ok { + return subtle.ConstantTimeCompare(privKey[:], otherEd[:]) == 1 + } + + return false +} + +func (privKey PrivKey) Type() string { + return KeyType +} + +// GenPrivKey generates a new ed25519 private key. +// It uses OS randomness in conjunction with the current global random seed +// in cometbft/libs/rand to generate the private key. +func GenPrivKey() PrivKey { + return genPrivKey(crypto.CReader()) +} + +// genPrivKey generates a new ed25519 private key using the provided reader. +func genPrivKey(rand io.Reader) PrivKey { + _, priv, err := ed25519.GenerateKey(rand) + if err != nil { + panic(err) + } + + return PrivKey(priv) +} + +// GenPrivKeyFromSecret hashes the secret with SHA2, and uses +// that 32 byte output to create the private key. +// NOTE: secret should be the output of a KDF like bcrypt, +// if it's derived from user input. +func GenPrivKeyFromSecret(secret []byte) PrivKey { + seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes. + + return PrivKey(ed25519.NewKeyFromSeed(seed)) +} + +//------------------------------------- + +var _ crypto.PubKey = PubKey{} + +// PubKey implements crypto.PubKey for the Ed25519 signature scheme. +type PubKey []byte + +// Address is the SHA256-20 of the raw pubkey bytes. +func (pubKey PubKey) Address() crypto.Address { + if len(pubKey) != PubKeySize { + panic("pubkey is incorrect size") + } + return crypto.Address(tmhash.SumTruncated(pubKey)) +} + +// Bytes returns the PubKey byte format. +func (pubKey PubKey) Bytes() []byte { + return []byte(pubKey) +} + +func (pubKey PubKey) VerifySignature(msg []byte, sig []byte) bool { + // make sure we use the same algorithm to sign + if len(sig) != SignatureSize { + return false + } + + return cachingVerifier.VerifyWithOptions(ed25519.PublicKey(pubKey), msg, sig, verifyOptions) +} + +func (pubKey PubKey) String() string { + return fmt.Sprintf("PubKeyEd25519{%X}", []byte(pubKey)) +} + +func (pubKey PubKey) Type() string { + return KeyType +} + +func (pubKey PubKey) Equals(other crypto.PubKey) bool { + if otherEd, ok := other.(PubKey); ok { + return bytes.Equal(pubKey[:], otherEd[:]) + } + + return false +} + +//------------------------------------- + +// BatchVerifier implements batch verification for ed25519. +type BatchVerifier struct { + *ed25519.BatchVerifier +} + +func NewBatchVerifier() crypto.BatchVerifier { + return &BatchVerifier{ed25519.NewBatchVerifier()} +} + +func (b *BatchVerifier) Add(key crypto.PubKey, msg, signature []byte) error { + pkEd, ok := key.(PubKey) + if !ok { + return fmt.Errorf("pubkey is not Ed25519") + } + + pkBytes := pkEd.Bytes() + + if l := len(pkBytes); l != PubKeySize { + return fmt.Errorf("pubkey size is incorrect; expected: %d, got %d", PubKeySize, l) + } + + // check that the signature is the correct length + if len(signature) != SignatureSize { + return errors.New("invalid signature") + } + + cachingVerifier.AddWithOptions(b.BatchVerifier, ed25519.PublicKey(pkBytes), msg, signature, verifyOptions) + + return nil +} + +func (b *BatchVerifier) Verify() (bool, []bool) { + return b.BatchVerifier.Verify(crypto.CReader()) +} diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go new file mode 100644 index 0000000..606dac7 --- /dev/null +++ b/crypto/ed25519/ed25519_test.go @@ -0,0 +1,54 @@ +package ed25519_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" +) + +func TestSignAndValidateEd25519(t *testing.T) { + privKey := ed25519.GenPrivKey() + pubKey := privKey.PubKey() + + msg := crypto.CRandBytes(128) + sig, err := privKey.Sign(msg) + require.Nil(t, err) + + // Test the signature + assert.True(t, pubKey.VerifySignature(msg, sig)) + + // Mutate the signature, just one bit. + // TODO: Replace this with a much better fuzzer, tendermint/ed25519/issues/10 + sig[7] ^= byte(0x01) + + assert.False(t, pubKey.VerifySignature(msg, sig)) +} + +func TestBatchSafe(t *testing.T) { + v := ed25519.NewBatchVerifier() + + for i := 0; i <= 38; i++ { + priv := ed25519.GenPrivKey() + pub := priv.PubKey() + + var msg []byte + if i%2 == 0 { + msg = []byte("easter") + } else { + msg = []byte("egg") + } + + sig, err := priv.Sign(msg) + require.NoError(t, err) + + err = v.Add(pub, msg, sig) + require.NoError(t, err) + } + + ok, _ := v.Verify() + require.True(t, ok) +} diff --git a/crypto/encoding/codec.go b/crypto/encoding/codec.go new file mode 100644 index 0000000..c3343db --- /dev/null +++ b/crypto/encoding/codec.go @@ -0,0 +1,63 @@ +package encoding + +import ( + "fmt" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/secp256k1" + "github.com/cometbft/cometbft/libs/json" + pc "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +func init() { + json.RegisterType((*pc.PublicKey)(nil), "tendermint.crypto.PublicKey") + json.RegisterType((*pc.PublicKey_Ed25519)(nil), "tendermint.crypto.PublicKey_Ed25519") + json.RegisterType((*pc.PublicKey_Secp256K1)(nil), "tendermint.crypto.PublicKey_Secp256K1") +} + +// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey +func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) { + var kp pc.PublicKey + switch k := k.(type) { + case ed25519.PubKey: + kp = pc.PublicKey{ + Sum: &pc.PublicKey_Ed25519{ + Ed25519: k, + }, + } + case secp256k1.PubKey: + kp = pc.PublicKey{ + Sum: &pc.PublicKey_Secp256K1{ + Secp256K1: k, + }, + } + default: + return kp, fmt.Errorf("toproto: key type %v is not supported", k) + } + return kp, nil +} + +// PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey +func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) { + switch k := k.Sum.(type) { + case *pc.PublicKey_Ed25519: + if len(k.Ed25519) != ed25519.PubKeySize { + return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d", + len(k.Ed25519), ed25519.PubKeySize) + } + pk := make(ed25519.PubKey, ed25519.PubKeySize) + copy(pk, k.Ed25519) + return pk, nil + case *pc.PublicKey_Secp256K1: + if len(k.Secp256K1) != secp256k1.PubKeySize { + return nil, fmt.Errorf("invalid size for PubKeySecp256k1. Got %d, expected %d", + len(k.Secp256K1), secp256k1.PubKeySize) + } + pk := make(secp256k1.PubKey, secp256k1.PubKeySize) + copy(pk, k.Secp256K1) + return pk, nil + default: + return nil, fmt.Errorf("fromproto: key type %v is not supported", k) + } +} diff --git a/crypto/example_test.go b/crypto/example_test.go new file mode 100644 index 0000000..ca488b7 --- /dev/null +++ b/crypto/example_test.go @@ -0,0 +1,14 @@ +package crypto_test + +import ( + "fmt" + + "github.com/cometbft/cometbft/crypto" +) + +func ExampleSha256() { + sum := crypto.Sha256([]byte("This is CometBFT")) + fmt.Printf("%x\n", sum) + // Output: + // ea186526b041852d923b02c91aa04b00c0df258b3d69cb688eaba577f5562758 +} diff --git a/crypto/hash.go b/crypto/hash.go new file mode 100644 index 0000000..705f6ad --- /dev/null +++ b/crypto/hash.go @@ -0,0 +1,11 @@ +package crypto + +import ( + "crypto/sha256" +) + +func Sha256(bytes []byte) []byte { + hasher := sha256.New() + hasher.Write(bytes) + return hasher.Sum(nil) +} diff --git a/crypto/internal/benchmarking/bench.go b/crypto/internal/benchmarking/bench.go new file mode 100644 index 0000000..804df50 --- /dev/null +++ b/crypto/internal/benchmarking/bench.go @@ -0,0 +1,92 @@ +package benchmarking + +import ( + "io" + "testing" + + "github.com/cometbft/cometbft/crypto" +) + +// The code in this file is adapted from agl/ed25519. +// As such it is under the following license. +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found at the bottom of this file. + +type zeroReader struct{} + +func (zeroReader) Read(buf []byte) (int, error) { + for i := range buf { + buf[i] = 0 + } + return len(buf), nil +} + +// BenchmarkKeyGeneration benchmarks the given key generation algorithm using +// a dummy reader. +func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) crypto.PrivKey) { + var zero zeroReader + for i := 0; i < b.N; i++ { + generateKey(zero) + } +} + +// BenchmarkSigning benchmarks the given signing algorithm using +// the provided privkey. +func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) { + message := []byte("Hello, world!") + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, err := priv.Sign(message) + + if err != nil { + b.FailNow() + } + } +} + +// BenchmarkVerification benchmarks the given verification algorithm using +// the provided privkey on a constant message. +func BenchmarkVerification(b *testing.B, priv crypto.PrivKey) { + pub := priv.PubKey() + // use a short message, so this time doesn't get dominated by hashing. + message := []byte("Hello, world!") + signature, err := priv.Sign(message) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + pub.VerifySignature(message, signature) + } +} + +// Below is the aforementioned license. + +// Copyright (c) 2012 The Go Authors. All rights reserved. + +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: + +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/crypto/merkle/README.md b/crypto/merkle/README.md new file mode 100644 index 0000000..6bf21c0 --- /dev/null +++ b/crypto/merkle/README.md @@ -0,0 +1,4 @@ +# Merkle Tree + +For smaller static data structures that don't require immutable snapshots or mutability; +for instance the transactions and validation signatures of a block can be hashed using this simple merkle tree logic. diff --git a/crypto/merkle/bench_test.go b/crypto/merkle/bench_test.go new file mode 100644 index 0000000..63a2cfd --- /dev/null +++ b/crypto/merkle/bench_test.go @@ -0,0 +1,42 @@ +package merkle + +import ( + "crypto/sha256" + "strings" + "testing" +) + +var sink any + +type innerHashTest struct { + left, right string +} + +var innerHashTests = []*innerHashTest{ + {"aaaaaaaaaaaaaaa", " "}, + {"", ""}, + {" ", "a ff b f1 a"}, + {"ffff122fff", "ffff122fff"}, + {"😎💡✅alalalalalalalalalallalallaallalaallalalalalalalalaallalalalalalala", "😎💡✅alalalalalalalalalallalallaallalaallalalalalalalalaallalalalalalalaffff122fff"}, + {strings.Repeat("ff", 1<<10), strings.Repeat("00af", 4<<10)}, + {strings.Repeat("f", sha256.Size), strings.Repeat("00af", 10<<10)}, + {"aaaaaaaaaaaaaaaaaaaaaaaaaaaffff122fffaaaaaaaaa", "aaaaaaaaaffff1aaaaaaaaaaaaaaaaaa22fffaaaaaaaaa"}, +} + +func BenchmarkInnerHash(b *testing.B) { + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + for _, tt := range innerHashTests { + got := innerHash([]byte(tt.left), []byte(tt.right)) + if g, w := len(got), sha256.Size; g != w { + b.Fatalf("size discrepancy: got %d, want %d", g, w) + } + sink = got + } + } + + if sink == nil { + b.Fatal("Benchmark did not run!") + } +} diff --git a/crypto/merkle/doc.go b/crypto/merkle/doc.go new file mode 100644 index 0000000..e36380f --- /dev/null +++ b/crypto/merkle/doc.go @@ -0,0 +1,30 @@ +/* +Package merkle computes a deterministic minimal height Merkle tree hash. +If the number of items is not a power of two, some leaves +will be at different levels. Tries to keep both sides of +the tree the same size, but the left may be one greater. + +Use this for short deterministic trees, such as the validator list. +For larger datasets, use IAVLTree. + +Be aware that the current implementation by itself does not prevent +second pre-image attacks. Hence, use this library with caution. +Otherwise you might run into similar issues as, e.g., in early Bitcoin: +https://bitcointalk.org/?topic=102395 + + * + / \ + / \ + / \ + / \ + * * + / \ / \ + / \ / \ + / \ / \ + * * * h6 + / \ / \ / \ + h0 h1 h2 h3 h4 h5 + +TODO(ismail): add 2nd pre-image protection or clarify further on how we use this and why this secure. +*/ +package merkle diff --git a/crypto/merkle/hash.go b/crypto/merkle/hash.go new file mode 100644 index 0000000..21e2f7a --- /dev/null +++ b/crypto/merkle/hash.go @@ -0,0 +1,44 @@ +package merkle + +import ( + "hash" + + "github.com/cometbft/cometbft/crypto/tmhash" +) + +// TODO: make these have a large predefined capacity +var ( + leafPrefix = []byte{0} + innerPrefix = []byte{1} +) + +// returns tmhash() +func emptyHash() []byte { + return tmhash.Sum([]byte{}) +} + +// returns tmhash(0x00 || leaf) +func leafHash(leaf []byte) []byte { + return tmhash.Sum(append(leafPrefix, leaf...)) +} + +// returns tmhash(0x00 || leaf) +func leafHashOpt(s hash.Hash, leaf []byte) []byte { + s.Reset() + s.Write(leafPrefix) + s.Write(leaf) + return s.Sum(nil) +} + +// returns tmhash(0x01 || left || right) +func innerHash(left []byte, right []byte) []byte { + return tmhash.SumMany(innerPrefix, left, right) +} + +func innerHashOpt(s hash.Hash, left []byte, right []byte) []byte { + s.Reset() + s.Write(innerPrefix) + s.Write(left) + s.Write(right) + return s.Sum(nil) +} diff --git a/crypto/merkle/proof.go b/crypto/merkle/proof.go new file mode 100644 index 0000000..2804d0f --- /dev/null +++ b/crypto/merkle/proof.go @@ -0,0 +1,252 @@ +package merkle + +import ( + "bytes" + "errors" + "fmt" + + "github.com/cometbft/cometbft/crypto/tmhash" + cmtcrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +const ( + // MaxAunts is the maximum number of aunts that can be included in a Proof. + // This corresponds to a tree of size 2^100, which should be sufficient for all conceivable purposes. + // This maximum helps prevent Denial-of-Service attacks by limitting the size of the proofs. + MaxAunts = 100 +) + +// Proof represents a Merkle proof. +// NOTE: The convention for proofs is to include leaf hashes but to +// exclude the root hash. +// This convention is implemented across IAVL range proofs as well. +// Keep this consistent unless there's a very good reason to change +// everything. This also affects the generalized proof system as +// well. +type Proof struct { + Total int64 `json:"total"` // Total number of items. + Index int64 `json:"index"` // Index of item to prove. + LeafHash []byte `json:"leaf_hash"` // Hash of item value. + Aunts [][]byte `json:"aunts,omitempty"` // Hashes from leaf's sibling to a root's child. +} + +// ProofsFromByteSlices computes inclusion proof for given items. +// proofs[0] is the proof for items[0]. +func ProofsFromByteSlices(items [][]byte) (rootHash []byte, proofs []*Proof) { + trails, rootSPN := trailsFromByteSlices(items) + rootHash = rootSPN.Hash + proofs = make([]*Proof, len(items)) + for i, trail := range trails { + proofs[i] = &Proof{ + Total: int64(len(items)), + Index: int64(i), + LeafHash: trail.Hash, + Aunts: trail.FlattenAunts(), + } + } + return +} + +// Verify that the Proof proves the root hash. +// Check sp.Index/sp.Total manually if needed +func (sp *Proof) Verify(rootHash []byte, leaf []byte) error { + if rootHash == nil { + return fmt.Errorf("invalid root hash: cannot be nil") + } + if sp.Total < 0 { + return errors.New("proof total must be positive") + } + if sp.Index < 0 { + return errors.New("proof index cannot be negative") + } + leafHash := leafHash(leaf) + if !bytes.Equal(sp.LeafHash, leafHash) { + return fmt.Errorf("invalid leaf hash: wanted %X got %X", leafHash, sp.LeafHash) + } + computedHash, err := sp.computeRootHash() + if err != nil { + return fmt.Errorf("compute root hash: %w", err) + } + if !bytes.Equal(computedHash, rootHash) { + return fmt.Errorf("invalid root hash: wanted %X got %X", rootHash, computedHash) + } + return nil +} + +// Compute the root hash given a leaf hash. Panics in case of errors. +func (sp *Proof) ComputeRootHash() []byte { + computedHash, err := sp.computeRootHash() + if err != nil { + panic(fmt.Errorf("ComputeRootHash errored %w", err)) + } + return computedHash +} + +// Compute the root hash given a leaf hash. +func (sp *Proof) computeRootHash() ([]byte, error) { + return computeHashFromAunts( + sp.Index, + sp.Total, + sp.LeafHash, + sp.Aunts, + ) +} + +// String implements the stringer interface for Proof. +// It is a wrapper around StringIndented. +func (sp *Proof) String() string { + return sp.StringIndented("") +} + +// StringIndented generates a canonical string representation of a Proof. +func (sp *Proof) StringIndented(indent string) string { + return fmt.Sprintf(`Proof{ +%s Aunts: %X +%s}`, + indent, sp.Aunts, + indent) +} + +// ValidateBasic performs basic validation. +// NOTE: it expects the LeafHash and the elements of Aunts to be of size tmhash.Size, +// and it expects at most MaxAunts elements in Aunts. +func (sp *Proof) ValidateBasic() error { + if sp.Total < 0 { + return errors.New("negative Total") + } + if sp.Index < 0 { + return errors.New("negative Index") + } + if len(sp.LeafHash) != tmhash.Size { + return fmt.Errorf("expected LeafHash size to be %d, got %d", tmhash.Size, len(sp.LeafHash)) + } + if len(sp.Aunts) > MaxAunts { + return fmt.Errorf("expected no more than %d aunts, got %d", MaxAunts, len(sp.Aunts)) + } + for i, auntHash := range sp.Aunts { + if len(auntHash) != tmhash.Size { + return fmt.Errorf("expected Aunts#%d size to be %d, got %d", i, tmhash.Size, len(auntHash)) + } + } + return nil +} + +func (sp *Proof) ToProto() *cmtcrypto.Proof { + if sp == nil { + return nil + } + pb := new(cmtcrypto.Proof) + + pb.Total = sp.Total + pb.Index = sp.Index + pb.LeafHash = sp.LeafHash + pb.Aunts = sp.Aunts + + return pb +} + +func ProofFromProto(pb *cmtcrypto.Proof) (*Proof, error) { + if pb == nil { + return nil, errors.New("nil proof") + } + + sp := new(Proof) + + sp.Total = pb.Total + sp.Index = pb.Index + sp.LeafHash = pb.LeafHash + sp.Aunts = pb.Aunts + + return sp, sp.ValidateBasic() +} + +// Use the leafHash and innerHashes to get the root merkle hash. +// If the length of the innerHashes slice isn't exactly correct, the result is nil. +// Recursive impl. +func computeHashFromAunts(index, total int64, leafHash []byte, innerHashes [][]byte) ([]byte, error) { + if index >= total || index < 0 || total <= 0 { + return nil, fmt.Errorf("invalid index %d and/or total %d", index, total) + } + switch total { + case 0: + panic("Cannot call computeHashFromAunts() with 0 total") + case 1: + if len(innerHashes) != 0 { + return nil, fmt.Errorf("unexpected inner hashes") + } + return leafHash, nil + default: + if len(innerHashes) == 0 { + return nil, fmt.Errorf("expected at least one inner hash") + } + numLeft := getSplitPoint(total) + if index < numLeft { + leftHash, err := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1]) + if err != nil { + return nil, err + } + + return innerHash(leftHash, innerHashes[len(innerHashes)-1]), nil + } + rightHash, err := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1]) + if err != nil { + return nil, err + } + return innerHash(innerHashes[len(innerHashes)-1], rightHash), nil + } +} + +// ProofNode is a helper structure to construct merkle proof. +// The node and the tree is thrown away afterwards. +// Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil. +// node.Parent.Hash = hash(node.Hash, node.Right.Hash) or +// hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child. +type ProofNode struct { + Hash []byte + Parent *ProofNode + Left *ProofNode // Left sibling (only one of Left,Right is set) + Right *ProofNode // Right sibling (only one of Left,Right is set) +} + +// FlattenAunts will return the inner hashes for the item corresponding to the leaf, +// starting from a leaf ProofNode. +func (spn *ProofNode) FlattenAunts() [][]byte { + // Nonrecursive impl. + innerHashes := [][]byte{} + for spn != nil { + switch { + case spn.Left != nil: + innerHashes = append(innerHashes, spn.Left.Hash) + case spn.Right != nil: + innerHashes = append(innerHashes, spn.Right.Hash) + default: + break + } + spn = spn.Parent + } + return innerHashes +} + +// trails[0].Hash is the leaf hash for items[0]. +// trails[i].Parent.Parent....Parent == root for all i. +func trailsFromByteSlices(items [][]byte) (trails []*ProofNode, root *ProofNode) { + // Recursive impl. + switch len(items) { + case 0: + return []*ProofNode{}, &ProofNode{emptyHash(), nil, nil, nil} + case 1: + trail := &ProofNode{leafHash(items[0]), nil, nil, nil} + return []*ProofNode{trail}, trail + default: + k := getSplitPoint(int64(len(items))) + lefts, leftRoot := trailsFromByteSlices(items[:k]) + rights, rightRoot := trailsFromByteSlices(items[k:]) + rootHash := innerHash(leftRoot.Hash, rightRoot.Hash) + root := &ProofNode{rootHash, nil, nil, nil} + leftRoot.Parent = root + leftRoot.Right = rightRoot + rightRoot.Parent = root + rightRoot.Left = leftRoot + return append(lefts, rights...), root + } +} diff --git a/crypto/merkle/proof_key_path.go b/crypto/merkle/proof_key_path.go new file mode 100644 index 0000000..9b7c851 --- /dev/null +++ b/crypto/merkle/proof_key_path.go @@ -0,0 +1,110 @@ +package merkle + +import ( + "encoding/hex" + "errors" + "fmt" + "net/url" + "strings" +) + +/* + + For generalized Merkle proofs, each layer of the proof may require an + optional key. The key may be encoded either by URL-encoding or + (upper-case) hex-encoding. + TODO: In the future, more encodings may be supported, like base32 (e.g. + /32:) + + For example, for a Cosmos-SDK application where the first two proof layers + are ValueOps, and the third proof layer is an IAVLValueOp, the keys + might look like: + + 0: []byte("App") + 1: []byte("IBC") + 2: []byte{0x01, 0x02, 0x03} + + Assuming that we know that the first two layers are always ASCII texts, we + probably want to use URLEncoding for those, whereas the third layer will + require HEX encoding for efficient representation. + + kp := new(KeyPath) + kp.AppendKey([]byte("App"), KeyEncodingURL) + kp.AppendKey([]byte("IBC"), KeyEncodingURL) + kp.AppendKey([]byte{0x01, 0x02, 0x03}, KeyEncodingURL) + kp.String() // Should return "/App/IBC/x:010203" + + NOTE: Key paths must begin with a `/`. + + NOTE: All encodings *MUST* work compatibly, such that you can choose to use + whatever encoding, and the decoded keys will always be the same. In other + words, it's just as good to encode all three keys using URL encoding or HEX + encoding... it just wouldn't be optimal in terms of readability or space + efficiency. + + NOTE: Punycode will never be supported here, because not all values can be + decoded. For example, no string decodes to the string "xn--blah" in + Punycode. + +*/ + +type keyEncoding int + +const ( + KeyEncodingURL keyEncoding = iota + KeyEncodingHex + KeyEncodingMax // Number of known encodings. Used for testing +) + +type Key struct { + name []byte + enc keyEncoding +} + +type KeyPath []Key + +func (pth KeyPath) AppendKey(key []byte, enc keyEncoding) KeyPath { + return append(pth, Key{key, enc}) +} + +func (pth KeyPath) String() string { + res := "" + for _, key := range pth { + switch key.enc { + case KeyEncodingURL: + res += "/" + url.PathEscape(string(key.name)) + case KeyEncodingHex: + res += "/x:" + fmt.Sprintf("%X", key.name) + default: + panic("unexpected key encoding type") + } + } + return res +} + +// Decode a path to a list of keys. Path must begin with `/`. +// Each key must use a known encoding. +func KeyPathToKeys(path string) (keys [][]byte, err error) { + if path == "" || path[0] != '/' { + return nil, errors.New("key path string must start with a forward slash '/'") + } + parts := strings.Split(path[1:], "/") + keys = make([][]byte, len(parts)) + for i, part := range parts { + if strings.HasPrefix(part, "x:") { + hexPart := part[2:] + key, err := hex.DecodeString(hexPart) + if err != nil { + return nil, fmt.Errorf("decoding hex-encoded part #%d: /%s: %w", i, part, err) + } + keys[i] = key + } else { + key, err := url.PathUnescape(part) + if err != nil { + return nil, fmt.Errorf("decoding url-encoded part #%d: /%s: %w", i, part, err) + } + keys[i] = []byte(key) // TODO Test this with random bytes, I'm not sure that it works for arbitrary bytes... + } + } + return keys, nil +} diff --git a/crypto/merkle/proof_key_path_test.go b/crypto/merkle/proof_key_path_test.go new file mode 100644 index 0000000..6151871 --- /dev/null +++ b/crypto/merkle/proof_key_path_test.go @@ -0,0 +1,45 @@ +package merkle + +import ( + // it is ok to use math/rand here: we do not need a cryptographically secure random + // number generator here and we can run the tests a bit faster + crand "crypto/rand" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestKeyPath(t *testing.T) { + var path KeyPath + keys := make([][]byte, 10) + alphanum := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + + for d := 0; d < 1e4; d++ { + path = nil + + for i := range keys { + enc := keyEncoding(rand.Intn(int(KeyEncodingMax))) + keys[i] = make([]byte, rand.Uint32()%20) + switch enc { + case KeyEncodingURL: + for j := range keys[i] { + keys[i][j] = alphanum[rand.Intn(len(alphanum))] + } + case KeyEncodingHex: + _, _ = crand.Read(keys[i]) + default: + panic("Unexpected encoding") + } + path = path.AppendKey(keys[i], enc) + } + + res, err := KeyPathToKeys(path.String()) + require.Nil(t, err) + require.Equal(t, len(keys), len(res)) + + for i, key := range keys { + require.Equal(t, key, res[i]) + } + } +} diff --git a/crypto/merkle/proof_op.go b/crypto/merkle/proof_op.go new file mode 100644 index 0000000..a83638c --- /dev/null +++ b/crypto/merkle/proof_op.go @@ -0,0 +1,139 @@ +package merkle + +import ( + "bytes" + "errors" + "fmt" + + cmtcrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +//---------------------------------------- +// ProofOp gets converted to an instance of ProofOperator: + +// ProofOperator is a layer for calculating intermediate Merkle roots +// when a series of Merkle trees are chained together. +// Run() takes leaf values from a tree and returns the Merkle +// root for the corresponding tree. It takes and returns a list of bytes +// to allow multiple leaves to be part of a single proof, for instance in a range proof. +// ProofOp() encodes the ProofOperator in a generic way so it can later be +// decoded with OpDecoder. +type ProofOperator interface { + Run([][]byte) ([][]byte, error) + GetKey() []byte + ProofOp() cmtcrypto.ProofOp +} + +//---------------------------------------- +// Operations on a list of ProofOperators + +// ProofOperators is a slice of ProofOperator(s). +// Each operator will be applied to the input value sequentially +// and the last Merkle root will be verified with already known data +type ProofOperators []ProofOperator + +func (poz ProofOperators) VerifyValue(root []byte, keypath string, value []byte) (err error) { + return poz.Verify(root, keypath, [][]byte{value}) +} + +func (poz ProofOperators) Verify(root []byte, keypath string, args [][]byte) (err error) { + keys, err := KeyPathToKeys(keypath) + if err != nil { + return + } + + for i, op := range poz { + key := op.GetKey() + if len(key) != 0 { + if len(keys) == 0 { + return fmt.Errorf("key path has insufficient # of parts: expected no more keys but got %+v", string(key)) + } + lastKey := keys[len(keys)-1] + if !bytes.Equal(lastKey, key) { + return fmt.Errorf("key mismatch on operation #%d: expected %+v but got %+v", i, string(lastKey), string(key)) + } + keys = keys[:len(keys)-1] + } + args, err = op.Run(args) + if err != nil { + return + } + } + if !bytes.Equal(root, args[0]) { + return fmt.Errorf("calculated root hash is invalid: expected %X but got %X", root, args[0]) + } + if len(keys) != 0 { + return errors.New("keypath not consumed all") + } + return nil +} + +//---------------------------------------- +// ProofRuntime - main entrypoint + +type OpDecoder func(cmtcrypto.ProofOp) (ProofOperator, error) + +type ProofRuntime struct { + decoders map[string]OpDecoder +} + +func NewProofRuntime() *ProofRuntime { + return &ProofRuntime{ + decoders: make(map[string]OpDecoder), + } +} + +func (prt *ProofRuntime) RegisterOpDecoder(typ string, dec OpDecoder) { + _, ok := prt.decoders[typ] + if ok { + panic("already registered for type " + typ) + } + prt.decoders[typ] = dec +} + +func (prt *ProofRuntime) Decode(pop cmtcrypto.ProofOp) (ProofOperator, error) { + decoder := prt.decoders[pop.Type] + if decoder == nil { + return nil, fmt.Errorf("unrecognized proof type %v", pop.Type) + } + return decoder(pop) +} + +func (prt *ProofRuntime) DecodeProof(proof *cmtcrypto.ProofOps) (ProofOperators, error) { + poz := make(ProofOperators, 0, len(proof.Ops)) + for _, pop := range proof.Ops { + operator, err := prt.Decode(pop) + if err != nil { + return nil, fmt.Errorf("decoding a proof operator: %w", err) + } + poz = append(poz, operator) + } + return poz, nil +} + +func (prt *ProofRuntime) VerifyValue(proof *cmtcrypto.ProofOps, root []byte, keypath string, value []byte) (err error) { + return prt.Verify(proof, root, keypath, [][]byte{value}) +} + +// TODO In the long run we'll need a method of classifcation of ops, +// whether existence or absence or perhaps a third? +func (prt *ProofRuntime) VerifyAbsence(proof *cmtcrypto.ProofOps, root []byte, keypath string) (err error) { + return prt.Verify(proof, root, keypath, nil) +} + +func (prt *ProofRuntime) Verify(proof *cmtcrypto.ProofOps, root []byte, keypath string, args [][]byte) (err error) { + poz, err := prt.DecodeProof(proof) + if err != nil { + return fmt.Errorf("decoding proof: %w", err) + } + return poz.Verify(root, keypath, args) +} + +// DefaultProofRuntime only knows about value proofs. +// To use e.g. IAVL proofs, register op-decoders as +// defined in the IAVL package. +func DefaultProofRuntime() (prt *ProofRuntime) { + prt = NewProofRuntime() + prt.RegisterOpDecoder(ProofOpValue, ValueOpDecoder) + return +} diff --git a/crypto/merkle/proof_test.go b/crypto/merkle/proof_test.go new file mode 100644 index 0000000..50cbf21 --- /dev/null +++ b/crypto/merkle/proof_test.go @@ -0,0 +1,225 @@ +package merkle + +import ( + "bytes" + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/tmhash" + cmtcrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +const ProofOpDomino = "test:domino" + +// Expects given input, produces given output. +// Like the game dominos. +type DominoOp struct { + key string // unexported, may be empty + Input string + Output string +} + +func NewDominoOp(key, input, output string) DominoOp { + return DominoOp{ + key: key, + Input: input, + Output: output, + } +} + +func (dop DominoOp) ProofOp() cmtcrypto.ProofOp { + dopb := cmtcrypto.DominoOp{ + Key: dop.key, + Input: dop.Input, + Output: dop.Output, + } + bz, err := dopb.Marshal() + if err != nil { + panic(err) + } + + return cmtcrypto.ProofOp{ + Type: ProofOpDomino, + Key: []byte(dop.key), + Data: bz, + } +} + +func (dop DominoOp) Run(input [][]byte) (output [][]byte, err error) { + if len(input) != 1 { + return nil, errors.New("expected input of length 1") + } + if string(input[0]) != dop.Input { + return nil, fmt.Errorf("expected input %v, got %v", + dop.Input, string(input[0])) + } + return [][]byte{[]byte(dop.Output)}, nil +} + +func (dop DominoOp) GetKey() []byte { + return []byte(dop.key) +} + +//---------------------------------------- + +func TestProofOperators(t *testing.T) { + var err error + + // ProofRuntime setup + // TODO test this somehow. + + // ProofOperators setup + op1 := NewDominoOp("KEY1", "INPUT1", "INPUT2") + op2 := NewDominoOp("KEY2", "INPUT2", "INPUT3") + op3 := NewDominoOp("", "INPUT3", "INPUT4") + op4 := NewDominoOp("KEY4", "INPUT4", "OUTPUT4") + + // Good + popz := ProofOperators([]ProofOperator{op1, op2, op3, op4}) + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.Nil(t, err) + err = popz.VerifyValue(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", bz("INPUT1")) + assert.Nil(t, err) + + // BAD INPUT + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1_WRONG")}) + assert.NotNil(t, err) + err = popz.VerifyValue(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", bz("INPUT1_WRONG")) + assert.NotNil(t, err) + + // BAD KEY 1 + err = popz.Verify(bz("OUTPUT4"), "/KEY3/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD KEY 2 + err = popz.Verify(bz("OUTPUT4"), "KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD KEY 3 + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1/", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD KEY 4 + err = popz.Verify(bz("OUTPUT4"), "//KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD KEY 5 + err = popz.Verify(bz("OUTPUT4"), "/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD OUTPUT 1 + err = popz.Verify(bz("OUTPUT4_WRONG"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD OUTPUT 2 + err = popz.Verify(bz(""), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD POPZ 1 + popz = []ProofOperator{op1, op2, op4} + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD POPZ 2 + popz = []ProofOperator{op4, op3, op2, op1} + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) + + // BAD POPZ 3 + popz = []ProofOperator{} + err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) + assert.NotNil(t, err) +} + +func bz(s string) []byte { + return []byte(s) +} + +func TestProofValidateBasic(t *testing.T) { + testCases := []struct { + testName string + malleateProof func(*Proof) + errStr string + }{ + {"Good", func(sp *Proof) {}, ""}, + {"Negative Total", func(sp *Proof) { sp.Total = -1 }, "negative Total"}, + {"Negative Index", func(sp *Proof) { sp.Index = -1 }, "negative Index"}, + {"Invalid LeafHash", func(sp *Proof) { sp.LeafHash = make([]byte, 10) }, + "expected LeafHash size to be 32, got 10"}, + {"Too many Aunts", func(sp *Proof) { sp.Aunts = make([][]byte, MaxAunts+1) }, + "expected no more than 100 aunts, got 101"}, + {"Invalid Aunt", func(sp *Proof) { sp.Aunts[0] = make([]byte, 10) }, + "expected Aunts#0 size to be 32, got 10"}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + _, proofs := ProofsFromByteSlices([][]byte{ + []byte("apple"), + []byte("watermelon"), + []byte("kiwi"), + }) + tc.malleateProof(proofs[0]) + err := proofs[0].ValidateBasic() + if tc.errStr != "" { + assert.Contains(t, err.Error(), tc.errStr) + } + }) + } +} +func TestVoteProtobuf(t *testing.T) { + _, proofs := ProofsFromByteSlices([][]byte{ + []byte("apple"), + []byte("watermelon"), + []byte("kiwi"), + }) + + testCases := []struct { + testName string + v1 *Proof + expPass bool + }{ + {"empty proof", &Proof{}, false}, + {"failure nil", nil, false}, + {"success", proofs[0], true}, + } + for _, tc := range testCases { + pb := tc.v1.ToProto() + + v, err := ProofFromProto(pb) + if tc.expPass { + require.NoError(t, err) + require.Equal(t, tc.v1, v, tc.testName) + } else { + require.Error(t, err) + } + } +} + +// TestVsa2022_100 verifies https://blog.verichains.io/p/vsa-2022-100-tendermint-forging-membership-proof +func TestVsa2022_100(t *testing.T) { + // a fake key-value pair and its hash + key := []byte{0x13} + value := []byte{0x37} + vhash := tmhash.Sum(value) + bz := new(bytes.Buffer) + _ = encodeByteSlice(bz, key) + _ = encodeByteSlice(bz, vhash) + kvhash := tmhash.Sum(append([]byte{0}, bz.Bytes()...)) + + // the malicious `op` + op := NewValueOp( + key, + &Proof{LeafHash: kvhash}, + ) + + // the nil root + var root []byte + + assert.NotNil(t, ProofOperators{op}.Verify(root, "/"+string(key), [][]byte{value})) +} diff --git a/crypto/merkle/proof_value.go b/crypto/merkle/proof_value.go new file mode 100644 index 0000000..f55854f --- /dev/null +++ b/crypto/merkle/proof_value.go @@ -0,0 +1,107 @@ +package merkle + +import ( + "bytes" + "fmt" + + "github.com/cometbft/cometbft/crypto/tmhash" + cmtcrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +const ProofOpValue = "simple:v" + +// ValueOp takes a key and a single value as argument and +// produces the root hash. The corresponding tree structure is +// the SimpleMap tree. SimpleMap takes a Hasher, and currently +// CometBFT uses tmhash. SimpleValueOp should support +// the hash function as used in tmhash. TODO support +// additional hash functions here as options/args to this +// operator. +// +// If the produced root hash matches the expected hash, the +// proof is good. +type ValueOp struct { + // Encoded in ProofOp.Key. + key []byte + + // To encode in ProofOp.Data + Proof *Proof `json:"proof"` +} + +var _ ProofOperator = ValueOp{} + +func NewValueOp(key []byte, proof *Proof) ValueOp { + return ValueOp{ + key: key, + Proof: proof, + } +} + +func ValueOpDecoder(pop cmtcrypto.ProofOp) (ProofOperator, error) { + if pop.Type != ProofOpValue { + return nil, fmt.Errorf("unexpected ProofOp.Type; got %v, want %v", pop.Type, ProofOpValue) + } + var pbop cmtcrypto.ValueOp // a bit strange as we'll discard this, but it works. + err := pbop.Unmarshal(pop.Data) + if err != nil { + return nil, fmt.Errorf("decoding ProofOp.Data into ValueOp: %w", err) + } + + sp, err := ProofFromProto(pbop.Proof) + if err != nil { + return nil, err + } + return NewValueOp(pop.Key, sp), nil +} + +func (op ValueOp) ProofOp() cmtcrypto.ProofOp { + pbval := cmtcrypto.ValueOp{ + Key: op.key, + Proof: op.Proof.ToProto(), + } + bz, err := pbval.Marshal() + if err != nil { + panic(err) + } + return cmtcrypto.ProofOp{ + Type: ProofOpValue, + Key: op.key, + Data: bz, + } +} + +func (op ValueOp) String() string { + return fmt.Sprintf("ValueOp{%v}", op.GetKey()) +} + +func (op ValueOp) Run(args [][]byte) ([][]byte, error) { + if len(args) != 1 { + return nil, fmt.Errorf("expected 1 arg, got %v", len(args)) + } + value := args[0] + hasher := tmhash.New() + hasher.Write(value) + vhash := hasher.Sum(nil) + + bz := new(bytes.Buffer) + // Wrap to hash the KVPair. + encodeByteSlice(bz, op.key) //nolint: errcheck // does not error + encodeByteSlice(bz, vhash) //nolint: errcheck // does not error + kvhash := leafHash(bz.Bytes()) + + if !bytes.Equal(kvhash, op.Proof.LeafHash) { + return nil, fmt.Errorf("leaf hash mismatch: want %X got %X", op.Proof.LeafHash, kvhash) + } + + rootHash, err := op.Proof.computeRootHash() + if err != nil { + return nil, err + } + return [][]byte{ + rootHash, + }, nil +} + +func (op ValueOp) GetKey() []byte { + return op.key +} diff --git a/crypto/merkle/rfc6962_test.go b/crypto/merkle/rfc6962_test.go new file mode 100644 index 0000000..5f383c7 --- /dev/null +++ b/crypto/merkle/rfc6962_test.go @@ -0,0 +1,105 @@ +package merkle + +// Copyright 2016 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// These tests were taken from https://github.com/google/trillian/blob/master/merkle/rfc6962/rfc6962_test.go, +// and consequently fall under the above license. +import ( + "bytes" + "encoding/hex" + "testing" + + "github.com/cometbft/cometbft/crypto/tmhash" +) + +func TestRFC6962Hasher(t *testing.T) { + _, leafHashTrail := trailsFromByteSlices([][]byte{[]byte("L123456")}) + leafHash := leafHashTrail.Hash + _, leafHashTrail = trailsFromByteSlices([][]byte{{}}) + emptyLeafHash := leafHashTrail.Hash + _, emptyHashTrail := trailsFromByteSlices([][]byte{}) + emptyTreeHash := emptyHashTrail.Hash + for _, tc := range []struct { + desc string + got []byte + want string + }{ + // Check that empty trees return the hash of an empty string. + // echo -n '' | sha256sum + { + desc: "RFC6962 Empty Tree", + want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"[:tmhash.Size*2], + got: emptyTreeHash, + }, + + // Check that the empty hash is not the same as the hash of an empty leaf. + // echo -n 00 | xxd -r -p | sha256sum + { + desc: "RFC6962 Empty Leaf", + want: "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"[:tmhash.Size*2], + got: emptyLeafHash, + }, + // echo -n 004C313233343536 | xxd -r -p | sha256sum + { + desc: "RFC6962 Leaf", + want: "395aa064aa4c29f7010acfe3f25db9485bbd4b91897b6ad7ad547639252b4d56"[:tmhash.Size*2], + got: leafHash, + }, + // echo -n 014E3132334E343536 | xxd -r -p | sha256sum + { + desc: "RFC6962 Node", + want: "aa217fe888e47007fa15edab33c2b492a722cb106c64667fc2b044444de66bbb"[:tmhash.Size*2], + got: innerHash([]byte("N123"), []byte("N456")), + }, + } { + tc := tc + t.Run(tc.desc, func(t *testing.T) { + wantBytes, err := hex.DecodeString(tc.want) + if err != nil { + t.Fatalf("hex.DecodeString(%x): %v", tc.want, err) + } + if got, want := tc.got, wantBytes; !bytes.Equal(got, want) { + t.Errorf("got %x, want %x", got, want) + } + }) + } +} + +func TestRFC6962HasherCollisions(t *testing.T) { + // Check that different leaves have different hashes. + leaf1, leaf2 := []byte("Hello"), []byte("World") + _, leafHashTrail := trailsFromByteSlices([][]byte{leaf1}) + hash1 := leafHashTrail.Hash + _, leafHashTrail = trailsFromByteSlices([][]byte{leaf2}) + hash2 := leafHashTrail.Hash + if bytes.Equal(hash1, hash2) { + t.Errorf("leaf hashes should differ, but both are %x", hash1) + } + // Compute an intermediate subtree hash. + _, subHash1Trail := trailsFromByteSlices([][]byte{hash1, hash2}) + subHash1 := subHash1Trail.Hash + // Check that this is not the same as a leaf hash of their concatenation. + preimage := append(hash1, hash2...) + _, forgedHashTrail := trailsFromByteSlices([][]byte{preimage}) + forgedHash := forgedHashTrail.Hash + if bytes.Equal(subHash1, forgedHash) { + t.Errorf("hasher is not second-preimage resistant") + } + // Swap the order of nodes and check that the hash is different. + _, subHash2Trail := trailsFromByteSlices([][]byte{hash2, hash1}) + subHash2 := subHash2Trail.Hash + if bytes.Equal(subHash1, subHash2) { + t.Errorf("subtree hash does not depend on the order of leaves") + } +} diff --git a/crypto/merkle/tree.go b/crypto/merkle/tree.go new file mode 100644 index 0000000..199b863 --- /dev/null +++ b/crypto/merkle/tree.go @@ -0,0 +1,112 @@ +package merkle + +import ( + "crypto/sha256" + "hash" + "math/bits" +) + +// HashFromByteSlices computes a Merkle tree where the leaves are the byte slice, +// in the provided order. It follows RFC-6962. +func HashFromByteSlices(items [][]byte) []byte { + return hashFromByteSlices(sha256.New(), items) +} + +func hashFromByteSlices(sha hash.Hash, items [][]byte) []byte { + switch len(items) { + case 0: + return emptyHash() + case 1: + return leafHashOpt(sha, items[0]) + default: + k := getSplitPoint(int64(len(items))) + left := hashFromByteSlices(sha, items[:k]) + right := hashFromByteSlices(sha, items[k:]) + return innerHashOpt(sha, left, right) + } +} + +// HashFromByteSliceIterative is an iterative alternative to +// HashFromByteSlice motivated by potential performance improvements. +// (#2611) had suggested that an iterative version of +// HashFromByteSlice would be faster, presumably because +// we can envision some overhead accumulating from stack +// frames and function calls. Additionally, a recursive algorithm risks +// hitting the stack limit and causing a stack overflow should the tree +// be too large. +// +// Provided here is an iterative alternative, a test to assert +// correctness and a benchmark. On the performance side, there appears to +// be no overall difference: +// +// BenchmarkHashAlternatives/recursive-4 20000 77677 ns/op +// BenchmarkHashAlternatives/iterative-4 20000 76802 ns/op +// +// On the surface it might seem that the additional overhead is due to +// the different allocation patterns of the implementations. The recursive +// version uses a single [][]byte slices which it then re-slices at each level of the tree. +// The iterative version reproduces [][]byte once within the function and +// then rewrites sub-slices of that array at each level of the tree. +// +// Experimenting by modifying the code to simply calculate the +// hash and not store the result show little to no difference in performance. +// +// These preliminary results suggest: +// +// 1. The performance of the HashFromByteSlice is pretty good +// 2. Go has low overhead for recursive functions +// 3. The performance of the HashFromByteSlice routine is dominated +// by the actual hashing of data +// +// Although this work is in no way exhaustive, point #3 suggests that +// optimization of this routine would need to take an alternative +// approach to make significant improvements on the current performance. +// +// Finally, considering that the recursive implementation is easier to +// read, it might not be worthwhile to switch to a less intuitive +// implementation for so little benefit. +func HashFromByteSlicesIterative(input [][]byte) []byte { + items := make([][]byte, len(input)) + sha := sha256.New() + for i, leaf := range input { + items[i] = leafHash(leaf) + } + + size := len(items) + for { + switch size { + case 0: + return emptyHash() + case 1: + return items[0] + default: + rp := 0 // read position + wp := 0 // write position + for rp < size { + if rp+1 < size { + items[wp] = innerHashOpt(sha, items[rp], items[rp+1]) + rp += 2 + } else { + items[wp] = items[rp] + rp++ + } + wp++ + } + size = wp + } + } +} + +// getSplitPoint returns the largest power of 2 less than length +func getSplitPoint(length int64) int64 { + if length < 1 { + panic("Trying to split a tree with size < 1") + } + uLength := uint(length) + bitlen := bits.Len(uLength) + k := int64(1 << uint(bitlen-1)) + if k == length { + k >>= 1 + } + return k +} diff --git a/crypto/merkle/tree_test.go b/crypto/merkle/tree_test.go new file mode 100644 index 0000000..da4bb6f --- /dev/null +++ b/crypto/merkle/tree_test.go @@ -0,0 +1,161 @@ +package merkle + +import ( + "encoding/hex" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/test" + + "github.com/cometbft/cometbft/crypto/tmhash" +) + +type testItem []byte + +func (tI testItem) Hash() []byte { + return []byte(tI) +} + +func TestHashFromByteSlices(t *testing.T) { + testcases := map[string]struct { + slices [][]byte + expectHash string // in hex format + }{ + "nil": {nil, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + "empty": {[][]byte{}, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + "single": {[][]byte{{1, 2, 3}}, "054edec1d0211f624fed0cbca9d4f9400b0e491c43742af2c5b0abebf0c990d8"}, + "single blank": {[][]byte{{}}, "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"}, + "two": {[][]byte{{1, 2, 3}, {4, 5, 6}}, "82e6cfce00453804379b53962939eaa7906b39904be0813fcadd31b100773c4b"}, + "many": { + [][]byte{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}}, + "f326493eceab4f2d9ffbc78c59432a0a005d6ea98392045c74df5d14a113be18", + }, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + hash := HashFromByteSlices(tc.slices) + assert.Equal(t, tc.expectHash, hex.EncodeToString(hash)) + }) + } +} + +func TestProof(t *testing.T) { + + // Try an empty proof first + rootHash, proofs := ProofsFromByteSlices([][]byte{}) + require.Equal(t, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hex.EncodeToString(rootHash)) + require.Empty(t, proofs) + + total := 100 + + items := make([][]byte, total) + for i := 0; i < total; i++ { + items[i] = testItem(cmtrand.Bytes(tmhash.Size)) + } + + rootHash = HashFromByteSlices(items) + + rootHash2, proofs := ProofsFromByteSlices(items) + + require.Equal(t, rootHash, rootHash2, "Unmatched root hashes: %X vs %X", rootHash, rootHash2) + + // For each item, check the trail. + for i, item := range items { + proof := proofs[i] + + // Check total/index + require.EqualValues(t, proof.Index, i, "Unmatched indicies: %d vs %d", proof.Index, i) + + require.EqualValues(t, proof.Total, total, "Unmatched totals: %d vs %d", proof.Total, total) + + // Verify success + err := proof.Verify(rootHash, item) + require.NoError(t, err, "Verification failed: %v.", err) + + // Trail too long should make it fail + origAunts := proof.Aunts + proof.Aunts = append(proof.Aunts, cmtrand.Bytes(32)) + err = proof.Verify(rootHash, item) + require.Error(t, err, "Expected verification to fail for wrong trail length") + + proof.Aunts = origAunts + + // Trail too short should make it fail + proof.Aunts = proof.Aunts[0 : len(proof.Aunts)-1] + err = proof.Verify(rootHash, item) + require.Error(t, err, "Expected verification to fail for wrong trail length") + + proof.Aunts = origAunts + + // Mutating the itemHash should make it fail. + err = proof.Verify(rootHash, test.MutateByteSlice(item)) + require.Error(t, err, "Expected verification to fail for mutated leaf hash") + + // Mutating the rootHash should make it fail. + err = proof.Verify(test.MutateByteSlice(rootHash), item) + require.Error(t, err, "Expected verification to fail for mutated root hash") + } +} + +func TestHashAlternatives(t *testing.T) { + + total := 100 + + items := make([][]byte, total) + for i := 0; i < total; i++ { + items[i] = testItem(cmtrand.Bytes(tmhash.Size)) + } + + rootHash1 := HashFromByteSlicesIterative(items) + rootHash2 := HashFromByteSlices(items) + require.Equal(t, rootHash1, rootHash2, "Unmatched root hashes: %X vs %X", rootHash1, rootHash2) +} + +func BenchmarkHashAlternatives(b *testing.B) { + total := 100 + + items := make([][]byte, total) + for i := 0; i < total; i++ { + items[i] = testItem(cmtrand.Bytes(tmhash.Size)) + } + + b.ResetTimer() + b.Run("recursive", func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = HashFromByteSlices(items) + } + }) + + b.Run("iterative", func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = HashFromByteSlicesIterative(items) + } + }) +} + +func Test_getSplitPoint(t *testing.T) { + tests := []struct { + length int64 + want int64 + }{ + {1, 0}, + {2, 1}, + {3, 2}, + {4, 2}, + {5, 4}, + {10, 8}, + {20, 16}, + {100, 64}, + {255, 128}, + {256, 128}, + {257, 256}, + } + for _, tt := range tests { + got := getSplitPoint(tt.length) + require.EqualValues(t, tt.want, got, "getSplitPoint(%d) = %v, want %v", tt.length, got, tt.want) + } +} diff --git a/crypto/merkle/types.go b/crypto/merkle/types.go new file mode 100644 index 0000000..4d63d84 --- /dev/null +++ b/crypto/merkle/types.go @@ -0,0 +1,39 @@ +package merkle + +import ( + "encoding/binary" + "io" +) + +// Tree is a Merkle tree interface. +type Tree interface { + Size() (size int) + Height() (height int8) + Has(key []byte) (has bool) + Proof(key []byte) (value []byte, proof []byte, exists bool) // TODO make it return an index + Get(key []byte) (index int, value []byte, exists bool) + GetByIndex(index int) (key []byte, value []byte) + Set(key []byte, value []byte) (updated bool) + Remove(key []byte) (value []byte, removed bool) + HashWithCount() (hash []byte, count int) + Hash() (hash []byte) + Save() (hash []byte) + Load(hash []byte) + Copy() Tree + Iterate(func(key []byte, value []byte) (stop bool)) (stopped bool) + IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool) +} + +//----------------------------------------------------------------------- + +// Uvarint length prefixed byteslice +func encodeByteSlice(w io.Writer, bz []byte) (err error) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutUvarint(buf[:], uint64(len(bz))) + _, err = w.Write(buf[0:n]) + if err != nil { + return + } + _, err = w.Write(bz) + return +} diff --git a/crypto/random.go b/crypto/random.go new file mode 100644 index 0000000..8167623 --- /dev/null +++ b/crypto/random.go @@ -0,0 +1,35 @@ +package crypto + +import ( + crand "crypto/rand" + "encoding/hex" + "io" +) + +// This only uses the OS's randomness +func randBytes(numBytes int) []byte { + b := make([]byte, numBytes) + _, err := crand.Read(b) + if err != nil { + panic(err) + } + return b +} + +// This only uses the OS's randomness +func CRandBytes(numBytes int) []byte { + return randBytes(numBytes) +} + +// CRandHex returns a hex encoded string that's floor(numDigits/2) * 2 long. +// +// Note: CRandHex(24) gives 96 bits of randomness that +// are usually strong enough for most purposes. +func CRandHex(numDigits int) string { + return hex.EncodeToString(CRandBytes(numDigits / 2)) +} + +// Returns a crand.Reader. +func CReader() io.Reader { + return crand.Reader +} diff --git a/crypto/random_test.go b/crypto/random_test.go new file mode 100644 index 0000000..d456601 --- /dev/null +++ b/crypto/random_test.go @@ -0,0 +1,23 @@ +package crypto_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" +) + +// the purpose of this test is primarily to ensure that the randomness +// generation won't error. +func TestRandomConsistency(t *testing.T) { + x1 := crypto.CRandBytes(256) + x2 := crypto.CRandBytes(256) + x3 := crypto.CRandBytes(256) + x4 := crypto.CRandBytes(256) + x5 := crypto.CRandBytes(256) + require.NotEqual(t, x1, x2) + require.NotEqual(t, x3, x4) + require.NotEqual(t, x4, x5) + require.NotEqual(t, x1, x5) +} diff --git a/crypto/secp256k1/secp256k1.go b/crypto/secp256k1/secp256k1.go new file mode 100644 index 0000000..d2b04e5 --- /dev/null +++ b/crypto/secp256k1/secp256k1.go @@ -0,0 +1,225 @@ +package secp256k1 + +import ( + "bytes" + "crypto/sha256" + "crypto/subtle" + "fmt" + "io" + "math/big" + + "github.com/decred/dcrd/dcrec/secp256k1/v4" + "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa" + "golang.org/x/crypto/ripemd160" //nolint: gosec,staticcheck // necessary for Bitcoin address format + + "github.com/cometbft/cometbft/crypto" + cmtjson "github.com/cometbft/cometbft/libs/json" +) + +// ------------------------------------- +const ( + PrivKeyName = "tendermint/PrivKeySecp256k1" + PubKeyName = "tendermint/PubKeySecp256k1" + + KeyType = "secp256k1" + PrivKeySize = 32 +) + +func init() { + cmtjson.RegisterType(PubKey{}, PubKeyName) + cmtjson.RegisterType(PrivKey{}, PrivKeyName) +} + +var _ crypto.PrivKey = PrivKey{} + +// PrivKey implements PrivKey. +type PrivKey []byte + +// Bytes marshalls the private key using amino encoding. +func (privKey PrivKey) Bytes() []byte { + return []byte(privKey) +} + +// PubKey performs the point-scalar multiplication from the privKey on the +// generator point to get the pubkey. +func (privKey PrivKey) PubKey() crypto.PubKey { + secpPrivKey := secp256k1.PrivKeyFromBytes(privKey) + + pk := secpPrivKey.PubKey().SerializeCompressed() + + return PubKey(pk) +} + +// Equals - you probably don't need to use this. +// Runs in constant time based on length of the keys. +func (privKey PrivKey) Equals(other crypto.PrivKey) bool { + if otherSecp, ok := other.(PrivKey); ok { + return subtle.ConstantTimeCompare(privKey[:], otherSecp[:]) == 1 + } + return false +} + +func (privKey PrivKey) Type() string { + return KeyType +} + +// GenPrivKey generates a new ECDSA private key on curve secp256k1 private key. +// It uses OS randomness to generate the private key. +func GenPrivKey() PrivKey { + return genPrivKey(crypto.CReader()) +} + +// genPrivKey generates a new secp256k1 private key using the provided reader. +func genPrivKey(rand io.Reader) PrivKey { + var privKeyBytes [PrivKeySize]byte + d := new(big.Int) + + for { + privKeyBytes = [PrivKeySize]byte{} + _, err := io.ReadFull(rand, privKeyBytes[:]) + if err != nil { + panic(err) + } + + d.SetBytes(privKeyBytes[:]) + // break if we found a valid point (i.e. > 0 and < N == curverOrder) + isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0 + if isValidFieldElement { + break + } + } + + return PrivKey(privKeyBytes[:]) +} + +var one = new(big.Int).SetInt64(1) + +// GenPrivKeySecp256k1 hashes the secret with SHA2, and uses +// that 32 byte output to create the private key. +// +// It makes sure the private key is a valid field element by setting: +// +// c = sha256(secret) +// k = (c mod (n − 1)) + 1, where n = curve order. +// +// NOTE: secret should be the output of a KDF like bcrypt, +// if it's derived from user input. +func GenPrivKeySecp256k1(secret []byte) PrivKey { + secHash := sha256.Sum256(secret) + // to guarantee that we have a valid field element, we use the approach of: + // "Suite B Implementer’s Guide to FIPS 186-3", A.2.1 + // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm + // see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101 + fe := new(big.Int).SetBytes(secHash[:]) + n := new(big.Int).Sub(secp256k1.S256().N, one) + fe.Mod(fe, n) + fe.Add(fe, one) + + feB := fe.Bytes() + privKey32 := make([]byte, PrivKeySize) + // copy feB over to fixed 32 byte privKey32 and pad (if necessary) + copy(privKey32[32-len(feB):32], feB) + + return PrivKey(privKey32) +} + +// Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg. +// The returned signature will be of the form R || S (in lower-S form). +func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { + priv := secp256k1.PrivKeyFromBytes(privKey) + + sum := sha256.Sum256(msg) + sig := ecdsa.SignCompact(priv, sum[:], false) + + // remove the first byte which is compactSigRecoveryCode + return sig[1:], nil +} + +//------------------------------------- + +var _ crypto.PubKey = PubKey{} + +// PubKeySize is comprised of 32 bytes for one field element +// (the x-coordinate), plus one byte for the parity of the y-coordinate. +const PubKeySize = 33 + +// PubKey implements crypto.PubKey. +// It is the compressed form of the pubkey. The first byte depends is a 0x02 byte +// if the y-coordinate is the lexicographically largest of the two associated with +// the x-coordinate. Otherwise the first byte is a 0x03. +// This prefix is followed with the x-coordinate. +type PubKey []byte + +// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey)) +func (pubKey PubKey) Address() crypto.Address { + if len(pubKey) != PubKeySize { + panic("length of pubkey is incorrect") + } + hasherSHA256 := sha256.New() + _, _ = hasherSHA256.Write(pubKey) // does not error + sha := hasherSHA256.Sum(nil) + + hasherRIPEMD160 := ripemd160.New() + _, _ = hasherRIPEMD160.Write(sha) // does not error + + return crypto.Address(hasherRIPEMD160.Sum(nil)) +} + +// Bytes returns the pubkey marshaled with amino encoding. +func (pubKey PubKey) Bytes() []byte { + return []byte(pubKey) +} + +func (pubKey PubKey) String() string { + return fmt.Sprintf("PubKeySecp256k1{%X}", []byte(pubKey)) +} + +func (pubKey PubKey) Equals(other crypto.PubKey) bool { + if otherSecp, ok := other.(PubKey); ok { + return bytes.Equal(pubKey[:], otherSecp[:]) + } + return false +} + +func (pubKey PubKey) Type() string { + return KeyType +} + +// VerifySignature verifies a signature of the form R || S. +// It rejects signatures which are not in lower-S form. +func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool { + if len(sigStr) != 64 { + return false + } + + pub, err := secp256k1.ParsePubKey(pubKey) + if err != nil { + return false + } + + // parse the signature: + signature := signatureFromBytes(sigStr) + // Reject malleable signatures. libsecp256k1 does this check but decred doesn't. + // see: https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 + // Serialize() would negate S value if it is over half order. + // Hence, if the signature is different after Serialize() if should be rejected. + var modifiedSignature, parseErr = ecdsa.ParseDERSignature(signature.Serialize()) + if parseErr != nil { + return false + } + if !signature.IsEqual(modifiedSignature) { + return false + } + + return signature.Verify(crypto.Sha256(msg), pub) +} + +// Read Signature struct from R || S. Caller needs to ensure +// that len(sigStr) == 64. +func signatureFromBytes(sigStr []byte) *ecdsa.Signature { + var r secp256k1.ModNScalar + r.SetByteSlice(sigStr[:32]) + var s secp256k1.ModNScalar + s.SetByteSlice(sigStr[32:64]) + return ecdsa.NewSignature(&r, &s) +} diff --git a/crypto/secp256k1/secp256k1_internal_test.go b/crypto/secp256k1/secp256k1_internal_test.go new file mode 100644 index 0000000..8407979 --- /dev/null +++ b/crypto/secp256k1/secp256k1_internal_test.go @@ -0,0 +1,84 @@ +package secp256k1 + +import ( + "bytes" + "math/big" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/decred/dcrd/dcrec/secp256k1/v4" +) + +func Test_genPrivKey(t *testing.T) { + + empty := make([]byte, 32) + oneB := big.NewInt(1).Bytes() + onePadded := make([]byte, 32) + copy(onePadded[32-len(oneB):32], oneB) + t.Logf("one padded: %v, len=%v", onePadded, len(onePadded)) + + validOne := append(empty, onePadded...) + tests := []struct { + name string + notSoRand []byte + shouldPanic bool + }{ + {"empty bytes (panics because 1st 32 bytes are zero and 0 is not a valid field element)", empty, true}, + {"curve order: N", secp256k1.S256().N.Bytes(), true}, + {"valid because 0 < 1 < N", validOne, false}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + if tt.shouldPanic { + require.Panics(t, func() { + genPrivKey(bytes.NewReader(tt.notSoRand)) + }) + return + } + got := genPrivKey(bytes.NewReader(tt.notSoRand)) + fe := new(big.Int).SetBytes(got[:]) + require.True(t, fe.Cmp(secp256k1.S256().N) < 0) + require.True(t, fe.Sign() > 0) + }) + } +} + +// Ensure that signature verification works, and that +// non-canonical signatures fail. +// Note: run with CGO_ENABLED=0 or go test -tags !cgo. +func TestSignatureVerificationAndRejectUpperS(t *testing.T) { + msg := []byte("We have lingered long enough on the shores of the cosmic ocean.") + for i := 0; i < 500; i++ { + priv := GenPrivKey() + sigStr, err := priv.Sign(msg) + require.NoError(t, err) + var r secp256k1.ModNScalar + r.SetByteSlice(sigStr[:32]) + var s secp256k1.ModNScalar + s.SetByteSlice(sigStr[32:64]) + require.False(t, s.IsOverHalfOrder()) + + pub := priv.PubKey() + require.True(t, pub.VerifySignature(msg, sigStr)) + + // malleate: + var S256 secp256k1.ModNScalar + S256.SetByteSlice(secp256k1.S256().N.Bytes()) + s.Negate().Add(&S256) + require.True(t, s.IsOverHalfOrder()) + + rBytes := r.Bytes() + sBytes := s.Bytes() + malSigStr := make([]byte, 64) + copy(malSigStr[32-len(rBytes):32], rBytes[:]) + copy(malSigStr[64-len(sBytes):64], sBytes[:]) + + require.False(t, pub.VerifySignature(msg, malSigStr), + "VerifyBytes incorrect with malleated & invalid S. sig=%v, key=%v", + malSigStr, + priv, + ) + } +} diff --git a/crypto/secp256k1/secp256k1_test.go b/crypto/secp256k1/secp256k1_test.go new file mode 100644 index 0000000..46e10f3 --- /dev/null +++ b/crypto/secp256k1/secp256k1_test.go @@ -0,0 +1,115 @@ +package secp256k1_test + +import ( + "encoding/hex" + "math/big" + "testing" + + "github.com/btcsuite/btcd/btcutil/base58" + underlyingsecp256k1 "github.com/decred/dcrd/dcrec/secp256k1/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/secp256k1" +) + +type keyData struct { + priv string + pub string + addr string +} + +var secpDataTable = []keyData{ + { + priv: "a96e62ed3955e65be32703f12d87b6b5cf26039ecfa948dc5107a495418e5330", + pub: "02950e1cdfcb133d6024109fd489f734eeb4502418e538c28481f22bce276f248c", + addr: "1CKZ9Nx4zgds8tU7nJHotKSDr4a9bYJCa3", + }, +} + +func TestPubKeySecp256k1Address(t *testing.T) { + for _, d := range secpDataTable { + privB, _ := hex.DecodeString(d.priv) + pubB, _ := hex.DecodeString(d.pub) + addrBbz, _, _ := base58.CheckDecode(d.addr) + addrB := crypto.Address(addrBbz) + + priv := secp256k1.PrivKey(privB) + + pubKey := priv.PubKey() + pubT, _ := pubKey.(secp256k1.PubKey) + pub := pubT + addr := pubKey.Address() + + assert.Equal(t, pub, secp256k1.PubKey(pubB), "Expected pub keys to match") + assert.Equal(t, addr, addrB, "Expected addresses to match") + } +} + +func TestSignAndValidateSecp256k1(t *testing.T) { + privKey := secp256k1.GenPrivKey() + pubKey := privKey.PubKey() + + msg := crypto.CRandBytes(128) + sig, err := privKey.Sign(msg) + require.Nil(t, err) + + assert.True(t, pubKey.VerifySignature(msg, sig)) + + // Mutate the signature, just one bit. + sig[3] ^= byte(0x01) + + assert.False(t, pubKey.VerifySignature(msg, sig)) +} + +// This test is intended to justify the removal of calls to the underlying library +// in creating the privkey. +func TestSecp256k1LoadPrivkeyAndSerializeIsIdentity(t *testing.T) { + numberOfTests := 256 + for i := 0; i < numberOfTests; i++ { + // Seed the test case with some random bytes + privKeyBytes := [32]byte{} + copy(privKeyBytes[:], crypto.CRandBytes(32)) + + // This function creates a private and public key in the underlying libraries format. + // The private key is basically calling new(big.Int).SetBytes(pk), which removes leading zero bytes + priv := underlyingsecp256k1.PrivKeyFromBytes(privKeyBytes[:]) + // this takes the bytes returned by `(big int).Bytes()`, and if the length is less than 32 bytes, + // pads the bytes from the left with zero bytes. Therefore these two functions composed + // result in the identity function on privKeyBytes, hence the following equality check + // always returning true. + serializedBytes := priv.Serialize() + require.Equal(t, privKeyBytes[:], serializedBytes) + } +} + +func TestGenPrivKeySecp256k1(t *testing.T) { + // curve oder N + N := underlyingsecp256k1.S256().N + tests := []struct { + name string + secret []byte + }{ + {"empty secret", []byte{}}, + { + "some long secret", + []byte("We live in a society exquisitely dependent on science and technology, " + + "in which hardly anyone knows anything about science and technology."), + }, + {"another seed used in cosmos tests #1", []byte{0}}, + {"another seed used in cosmos tests #2", []byte("mySecret")}, + {"another seed used in cosmos tests #3", []byte("")}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + gotPrivKey := secp256k1.GenPrivKeySecp256k1(tt.secret) + require.NotNil(t, gotPrivKey) + // interpret as a big.Int and make sure it is a valid field element: + fe := new(big.Int).SetBytes(gotPrivKey[:]) + require.True(t, fe.Cmp(N) < 0) + require.True(t, fe.Sign() > 0) + }) + } +} diff --git a/crypto/sr25519/batch.go b/crypto/sr25519/batch.go new file mode 100644 index 0000000..c5dbaec --- /dev/null +++ b/crypto/sr25519/batch.go @@ -0,0 +1,46 @@ +package sr25519 + +import ( + "fmt" + + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" + + "github.com/cometbft/cometbft/crypto" +) + +var _ crypto.BatchVerifier = &BatchVerifier{} + +// BatchVerifier implements batch verification for sr25519. +type BatchVerifier struct { + *sr25519.BatchVerifier +} + +func NewBatchVerifier() crypto.BatchVerifier { + return &BatchVerifier{sr25519.NewBatchVerifier()} +} + +func (b *BatchVerifier) Add(key crypto.PubKey, msg, signature []byte) error { + pk, ok := key.(PubKey) + if !ok { + return fmt.Errorf("sr25519: pubkey is not sr25519") + } + + var srpk sr25519.PublicKey + if err := srpk.UnmarshalBinary(pk); err != nil { + return fmt.Errorf("sr25519: invalid public key: %w", err) + } + + var sig sr25519.Signature + if err := sig.UnmarshalBinary(signature); err != nil { + return fmt.Errorf("sr25519: unable to decode signature: %w", err) + } + + st := signingCtx.NewTranscriptBytes(msg) + b.BatchVerifier.Add(&srpk, st, &sig) + + return nil +} + +func (b *BatchVerifier) Verify() (bool, []bool) { + return b.BatchVerifier.Verify(crypto.CReader()) +} diff --git a/crypto/sr25519/bench_test.go b/crypto/sr25519/bench_test.go new file mode 100644 index 0000000..bdb53da --- /dev/null +++ b/crypto/sr25519/bench_test.go @@ -0,0 +1,68 @@ +package sr25519 + +import ( + "fmt" + "io" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/internal/benchmarking" +) + +func BenchmarkKeyGeneration(b *testing.B) { + benchmarkKeygenWrapper := func(reader io.Reader) crypto.PrivKey { + return genPrivKey(reader) + } + benchmarking.BenchmarkKeyGeneration(b, benchmarkKeygenWrapper) +} + +func BenchmarkSigning(b *testing.B) { + priv := GenPrivKey() + benchmarking.BenchmarkSigning(b, priv) +} + +func BenchmarkVerification(b *testing.B) { + priv := GenPrivKey() + benchmarking.BenchmarkVerification(b, priv) +} + +func BenchmarkVerifyBatch(b *testing.B) { + msg := []byte("BatchVerifyTest") + + for _, sigsCount := range []int{1, 8, 64, 1024} { + sigsCount := sigsCount + b.Run(fmt.Sprintf("sig-count-%d", sigsCount), func(b *testing.B) { + // Pre-generate all of the keys, and signatures, but do not + // benchmark key-generation and signing. + pubs := make([]crypto.PubKey, 0, sigsCount) + sigs := make([][]byte, 0, sigsCount) + for i := 0; i < sigsCount; i++ { + priv := GenPrivKey() + sig, _ := priv.Sign(msg) + pubs = append(pubs, priv.PubKey().(PubKey)) + sigs = append(sigs, sig) + } + b.ResetTimer() + + b.ReportAllocs() + // NOTE: dividing by n so that metrics are per-signature + for i := 0; i < b.N/sigsCount; i++ { + // The benchmark could just benchmark the Verify() + // routine, but there is non-trivial overhead associated + // with BatchVerifier.Add(), which should be included + // in the benchmark. + v := NewBatchVerifier() + for i := 0; i < sigsCount; i++ { + err := v.Add(pubs[i], msg, sigs[i]) + require.NoError(b, err) + } + + if ok, _ := v.Verify(); !ok { + b.Fatal("signature set failed batch verification") + } + } + }) + } +} diff --git a/crypto/sr25519/encoding.go b/crypto/sr25519/encoding.go new file mode 100644 index 0000000..69131bf --- /dev/null +++ b/crypto/sr25519/encoding.go @@ -0,0 +1,13 @@ +package sr25519 + +import cmtjson "github.com/cometbft/cometbft/libs/json" + +const ( + PrivKeyName = "tendermint/PrivKeySr25519" + PubKeyName = "tendermint/PubKeySr25519" +) + +func init() { + cmtjson.RegisterType(PubKey{}, PubKeyName) + cmtjson.RegisterType(PrivKey{}, PrivKeyName) +} diff --git a/crypto/sr25519/privkey.go b/crypto/sr25519/privkey.go new file mode 100644 index 0000000..1bc029d --- /dev/null +++ b/crypto/sr25519/privkey.go @@ -0,0 +1,164 @@ +package sr25519 + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" + + "github.com/cometbft/cometbft/crypto" +) + +var ( + _ crypto.PrivKey = PrivKey{} + + signingCtx = sr25519.NewSigningContext([]byte{}) +) + +const ( + // PrivKeySize is the number of bytes in an Sr25519 private key. + PrivKeySize = 32 + + KeyType = "sr25519" +) + +// PrivKey implements crypto.PrivKey. +type PrivKey struct { + msk sr25519.MiniSecretKey + kp *sr25519.KeyPair +} + +// Bytes returns the byte representation of the PrivKey. +func (privKey PrivKey) Bytes() []byte { + if privKey.kp == nil { + return nil + } + return privKey.msk[:] +} + +// Sign produces a signature on the provided message. +func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { + if privKey.kp == nil { + return nil, fmt.Errorf("sr25519: uninitialized private key") + } + + st := signingCtx.NewTranscriptBytes(msg) + + sig, err := privKey.kp.Sign(crypto.CReader(), st) + if err != nil { + return nil, fmt.Errorf("sr25519: failed to sign message: %w", err) + } + + sigBytes, err := sig.MarshalBinary() + if err != nil { + return nil, fmt.Errorf("sr25519: failed to serialize signature: %w", err) + } + + return sigBytes, nil +} + +// PubKey gets the corresponding public key from the private key. +func (privKey PrivKey) PubKey() crypto.PubKey { + if privKey.kp == nil { + panic("sr25519: uninitialized private key") + } + + b, err := privKey.kp.PublicKey().MarshalBinary() + if err != nil { + panic("sr25519: failed to serialize public key: " + err.Error()) + } + + return PubKey(b) +} + +// Equals - you probably don't need to use this. +// Runs in constant time based on length of the keys. +func (privKey PrivKey) Equals(other crypto.PrivKey) bool { + if otherSr, ok := other.(PrivKey); ok { + return privKey.msk.Equal(&otherSr.msk) + } + return false +} + +func (privKey PrivKey) Type() string { + return KeyType +} + +func (privKey PrivKey) MarshalJSON() ([]byte, error) { + var b []byte + + // Handle uninitialized private keys gracefully. + if privKey.kp != nil { + b = privKey.Bytes() + } + + return json.Marshal(b) +} + +func (privKey *PrivKey) UnmarshalJSON(data []byte) error { + for i := range privKey.msk { + privKey.msk[i] = 0 + } + privKey.kp = nil + + var b []byte + if err := json.Unmarshal(data, &b); err != nil { + return fmt.Errorf("sr25519: failed to deserialize JSON: %w", err) + } + if len(b) == 0 { + return nil + } + + msk, err := sr25519.NewMiniSecretKeyFromBytes(b) + if err != nil { + return err + } + + sk := msk.ExpandEd25519() + + privKey.msk = *msk + privKey.kp = sk.KeyPair() + + return nil +} + +// GenPrivKey generates a new sr25519 private key. +// It uses OS randomness in conjunction with the current global random seed +// in cometbft/libs/rand to generate the private key. +func GenPrivKey() PrivKey { + return genPrivKey(crypto.CReader()) +} + +// genPrivKey generates a new sr25519 private key using the provided reader. +func genPrivKey(rng io.Reader) PrivKey { + msk, err := sr25519.GenerateMiniSecretKey(rng) + if err != nil { + panic("sr25519: failed to generate MiniSecretKey: " + err.Error()) + } + + sk := msk.ExpandEd25519() + + return PrivKey{ + msk: *msk, + kp: sk.KeyPair(), + } +} + +// GenPrivKeyFromSecret hashes the secret with SHA2, and uses +// that 32 byte output to create the private key. +// NOTE: secret should be the output of a KDF like bcrypt, +// if it's derived from user input. +func GenPrivKeyFromSecret(secret []byte) PrivKey { + seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes. + + var privKey PrivKey + if err := privKey.msk.UnmarshalBinary(seed); err != nil { + panic("sr25519: failed to deserialize MiniSecretKey: " + err.Error()) + } + + sk := privKey.msk.ExpandEd25519() + privKey.kp = sk.KeyPair() + + return privKey +} diff --git a/crypto/sr25519/pubkey.go b/crypto/sr25519/pubkey.go new file mode 100644 index 0000000..0f4930c --- /dev/null +++ b/crypto/sr25519/pubkey.go @@ -0,0 +1,70 @@ +package sr25519 + +import ( + "bytes" + "fmt" + + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" +) + +var _ crypto.PubKey = PubKey{} + +const ( + // PubKeySize is the number of bytes in an Sr25519 public key. + PubKeySize = 32 + + // SignatureSize is the size of a Sr25519 signature in bytes. + SignatureSize = 64 +) + +// PubKey implements crypto.PubKey for the Sr25519 signature scheme. +type PubKey []byte + +// Address is the SHA256-20 of the raw pubkey bytes. +func (pubKey PubKey) Address() crypto.Address { + if len(pubKey) != PubKeySize { + panic("pubkey is incorrect size") + } + return crypto.Address(tmhash.SumTruncated(pubKey[:])) +} + +// Bytes returns the byte representation of the PubKey. +func (pubKey PubKey) Bytes() []byte { + return []byte(pubKey) +} + +// Equals - checks that two public keys are the same time +// Runs in constant time based on length of the keys. +func (pubKey PubKey) Equals(other crypto.PubKey) bool { + if otherSr, ok := other.(PubKey); ok { + return bytes.Equal(pubKey[:], otherSr[:]) + } + + return false +} + +func (pubKey PubKey) VerifySignature(msg []byte, sigBytes []byte) bool { + var srpk sr25519.PublicKey + if err := srpk.UnmarshalBinary(pubKey); err != nil { + return false + } + + var sig sr25519.Signature + if err := sig.UnmarshalBinary(sigBytes); err != nil { + return false + } + + st := signingCtx.NewTranscriptBytes(msg) + return srpk.Verify(st, &sig) +} + +func (pubKey PubKey) String() string { + return fmt.Sprintf("PubKeySr25519{%X}", []byte(pubKey)) +} + +func (pubKey PubKey) Type() string { + return KeyType +} diff --git a/crypto/sr25519/sr25519_test.go b/crypto/sr25519/sr25519_test.go new file mode 100644 index 0000000..4f8d15b --- /dev/null +++ b/crypto/sr25519/sr25519_test.go @@ -0,0 +1,98 @@ +package sr25519_test + +import ( + "encoding/base64" + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/sr25519" +) + +func TestSignAndValidateSr25519(t *testing.T) { + privKey := sr25519.GenPrivKey() + pubKey := privKey.PubKey() + + msg := crypto.CRandBytes(128) + sig, err := privKey.Sign(msg) + require.Nil(t, err) + + // Test the signature + assert.True(t, pubKey.VerifySignature(msg, sig)) + assert.True(t, pubKey.VerifySignature(msg, sig)) + + // Mutate the signature, just one bit. + // TODO: Replace this with a much better fuzzer, tendermint/ed25519/issues/10 + sig[7] ^= byte(0x01) + + assert.False(t, pubKey.VerifySignature(msg, sig)) +} + +func TestBatchSafe(t *testing.T) { + v := sr25519.NewBatchVerifier() + vFail := sr25519.NewBatchVerifier() + for i := 0; i <= 38; i++ { + priv := sr25519.GenPrivKey() + pub := priv.PubKey() + + var msg []byte + if i%2 == 0 { + msg = []byte("easter") + } else { + msg = []byte("egg") + } + + sig, err := priv.Sign(msg) + require.NoError(t, err) + + err = v.Add(pub, msg, sig) + require.NoError(t, err) + + switch i % 2 { + case 0: + err = vFail.Add(pub, msg, sig) + case 1: + msg[2] ^= byte(0x01) + err = vFail.Add(pub, msg, sig) + } + require.NoError(t, err) + } + + ok, valid := v.Verify() + require.True(t, ok, "failed batch verification") + for i, ok := range valid { + require.Truef(t, ok, "sig[%d] should be marked valid", i) + } + + ok, valid = vFail.Verify() + require.False(t, ok, "succeeded batch verification (invalid batch)") + for i, ok := range valid { + expected := (i % 2) == 0 + require.Equalf(t, expected, ok, "sig[%d] should be %v", i, expected) + } +} + +func TestJSON(t *testing.T) { + privKey := sr25519.GenPrivKey() + + t.Run("PrivKey", func(t *testing.T) { + b, err := json.Marshal(privKey) + require.NoError(t, err) + + // b should be the base64 encoded MiniSecretKey, enclosed by doublequotes. + b64 := base64.StdEncoding.EncodeToString(privKey.Bytes()) + b64 = "\"" + b64 + "\"" + require.Equal(t, []byte(b64), b) + + var privKey2 sr25519.PrivKey + err = json.Unmarshal(b, &privKey2) + require.NoError(t, err) + require.Len(t, privKey2.Bytes(), sr25519.PrivKeySize) + require.EqualValues(t, privKey.Bytes(), privKey2.Bytes()) + }) + + // PubKeys are just []byte, so there is no special handling. +} diff --git a/crypto/tmhash/bench_test.go b/crypto/tmhash/bench_test.go new file mode 100644 index 0000000..590581b --- /dev/null +++ b/crypto/tmhash/bench_test.go @@ -0,0 +1,52 @@ +package tmhash + +import ( + "bytes" + "crypto/sha256" + "strings" + "testing" +) + +var sink any + +var manySlices = []struct { + name string + in [][]byte + want [32]byte +}{ + { + name: "all empty", + in: [][]byte{[]byte(""), []byte("")}, + want: sha256.Sum256(nil), + }, + { + name: "ax6", + in: [][]byte{[]byte("aaaa"), []byte("😎"), []byte("aaaa")}, + want: sha256.Sum256([]byte("aaaa😎aaaa")), + }, + { + name: "composite joined", + in: [][]byte{bytes.Repeat([]byte("a"), 1<<10), []byte("AA"), bytes.Repeat([]byte("z"), 100)}, + want: sha256.Sum256([]byte(strings.Repeat("a", 1<<10) + "AA" + strings.Repeat("z", 100))), + }, +} + +func BenchmarkSHA256Many(b *testing.B) { + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + for _, tt := range manySlices { + got := SumMany(tt.in[0], tt.in[1:]...) + if !bytes.Equal(got, tt.want[:]) { + b.Fatalf("Outward checksum mismatch for %q\n\tGot: %x\n\tWant: %x", tt.name, got, tt.want) + } + sink = got + } + } + + if sink == nil { + b.Fatal("Benchmark did not run!") + } + + sink = nil +} diff --git a/crypto/tmhash/hash.go b/crypto/tmhash/hash.go new file mode 100644 index 0000000..9891f04 --- /dev/null +++ b/crypto/tmhash/hash.go @@ -0,0 +1,77 @@ +package tmhash + +import ( + "crypto/sha256" + "hash" +) + +const ( + Size = sha256.Size + BlockSize = sha256.BlockSize +) + +// New returns a new hash.Hash. +func New() hash.Hash { + return sha256.New() +} + +// Sum returns the SHA256 of the bz. +func Sum(bz []byte) []byte { + h := sha256.Sum256(bz) + return h[:] +} + +// SumMany takes at least 1 byteslice along with a variadic +// number of other byteslices and produces the SHA256 sum from +// hashing them as if they were 1 joined slice. +func SumMany(data []byte, rest ...[]byte) []byte { + h := sha256.New() + h.Write(data) + for _, data := range rest { + h.Write(data) + } + return h.Sum(nil) +} + +//------------------------------------------------------------- + +const ( + TruncatedSize = 20 +) + +type sha256trunc struct { + sha256 hash.Hash +} + +func (h sha256trunc) Write(p []byte) (n int, err error) { + return h.sha256.Write(p) +} +func (h sha256trunc) Sum(b []byte) []byte { + shasum := h.sha256.Sum(b) + return shasum[:TruncatedSize] +} + +func (h sha256trunc) Reset() { + h.sha256.Reset() +} + +func (h sha256trunc) Size() int { + return TruncatedSize +} + +func (h sha256trunc) BlockSize() int { + return h.sha256.BlockSize() +} + +// NewTruncated returns a new hash.Hash. +func NewTruncated() hash.Hash { + return sha256trunc{ + sha256: sha256.New(), + } +} + +// SumTruncated returns the first 20 bytes of SHA256 of the bz. +func SumTruncated(bz []byte) []byte { + hash := sha256.Sum256(bz) + return hash[:TruncatedSize] +} diff --git a/crypto/tmhash/hash_test.go b/crypto/tmhash/hash_test.go new file mode 100644 index 0000000..a43cce3 --- /dev/null +++ b/crypto/tmhash/hash_test.go @@ -0,0 +1,48 @@ +package tmhash_test + +import ( + "crypto/sha256" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/tmhash" +) + +func TestHash(t *testing.T) { + testVector := []byte("abc") + hasher := tmhash.New() + _, err := hasher.Write(testVector) + require.NoError(t, err) + bz := hasher.Sum(nil) + + bz2 := tmhash.Sum(testVector) + + hasher = sha256.New() + _, err = hasher.Write(testVector) + require.NoError(t, err) + bz3 := hasher.Sum(nil) + + assert.Equal(t, bz, bz2) + assert.Equal(t, bz, bz3) +} + +func TestHashTruncated(t *testing.T) { + testVector := []byte("abc") + hasher := tmhash.NewTruncated() + _, err := hasher.Write(testVector) + require.NoError(t, err) + bz := hasher.Sum(nil) + + bz2 := tmhash.SumTruncated(testVector) + + hasher = sha256.New() + _, err = hasher.Write(testVector) + require.NoError(t, err) + bz3 := hasher.Sum(nil) + bz3 = bz3[:tmhash.TruncatedSize] + + assert.Equal(t, bz, bz2) + assert.Equal(t, bz, bz3) +} diff --git a/crypto/version.go b/crypto/version.go new file mode 100644 index 0000000..b754776 --- /dev/null +++ b/crypto/version.go @@ -0,0 +1,3 @@ +package crypto + +const Version = "0.9.0-dev" diff --git a/crypto/xchacha20poly1305/vector_test.go b/crypto/xchacha20poly1305/vector_test.go new file mode 100644 index 0000000..a4e36fc --- /dev/null +++ b/crypto/xchacha20poly1305/vector_test.go @@ -0,0 +1,122 @@ +package xchacha20poly1305 + +import ( + "bytes" + "encoding/hex" + "testing" +) + +func toHex(bits []byte) string { + return hex.EncodeToString(bits) +} + +func fromHex(bits string) []byte { + b, err := hex.DecodeString(bits) + if err != nil { + panic(err) + } + return b +} + +func TestHChaCha20(t *testing.T) { + for i, v := range hChaCha20Vectors { + var key [32]byte + var nonce [16]byte + copy(key[:], v.key) + copy(nonce[:], v.nonce) + + HChaCha20(&key, &nonce, &key) + if !bytes.Equal(key[:], v.keystream) { + t.Errorf("test %d: keystream mismatch:\n \t got: %s\n \t want: %s", i, toHex(key[:]), toHex(v.keystream)) + } + } +} + +var hChaCha20Vectors = []struct { + key, nonce, keystream []byte +}{ + { + fromHex("0000000000000000000000000000000000000000000000000000000000000000"), + fromHex("000000000000000000000000000000000000000000000000"), + fromHex("1140704c328d1d5d0e30086cdf209dbd6a43b8f41518a11cc387b669b2ee6586"), + }, + { + fromHex("8000000000000000000000000000000000000000000000000000000000000000"), + fromHex("000000000000000000000000000000000000000000000000"), + fromHex("7d266a7fd808cae4c02a0a70dcbfbcc250dae65ce3eae7fc210f54cc8f77df86"), + }, + { + fromHex("0000000000000000000000000000000000000000000000000000000000000001"), + fromHex("000000000000000000000000000000000000000000000002"), + fromHex("e0c77ff931bb9163a5460c02ac281c2b53d792b1c43fea817e9ad275ae546963"), + }, + { + fromHex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"), + fromHex("000102030405060708090a0b0c0d0e0f1011121314151617"), + fromHex("51e3ff45a895675c4b33b46c64f4a9ace110d34df6a2ceab486372bacbd3eff6"), + }, + { + fromHex("24f11cce8a1b3d61e441561a696c1c1b7e173d084fd4812425435a8896a013dc"), + fromHex("d9660c5900ae19ddad28d6e06e45fe5e"), + fromHex("5966b3eec3bff1189f831f06afe4d4e3be97fa9235ec8c20d08acfbbb4e851e3"), + }, +} + +func TestVectors(t *testing.T) { + for i, v := range vectors { + if len(v.plaintext) == 0 { + v.plaintext = make([]byte, len(v.ciphertext)) + } + + var nonce [24]byte + copy(nonce[:], v.nonce) + + aead, err := New(v.key) + if err != nil { + t.Error(err) + } + + dst := aead.Seal(nil, nonce[:], v.plaintext, v.ad) + if !bytes.Equal(dst, v.ciphertext) { + t.Errorf("test %d: ciphertext mismatch:\n \t got: %s\n \t want: %s", i, toHex(dst), toHex(v.ciphertext)) + } + open, err := aead.Open(nil, nonce[:], dst, v.ad) + if err != nil { + t.Error(err) + } + if !bytes.Equal(open, v.plaintext) { + t.Errorf("test %d: plaintext mismatch:\n \t got: %s\n \t want: %s", i, string(open), string(v.plaintext)) + } + } +} + +var vectors = []struct { + key, nonce, ad, plaintext, ciphertext []byte +}{ + { + []byte{ + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, + 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + }, + []byte{0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b}, + []byte{0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7}, + []byte( + "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.", + ), + []byte{ + 0x45, 0x3c, 0x06, 0x93, 0xa7, 0x40, 0x7f, 0x04, 0xff, 0x4c, 0x56, + 0xae, 0xdb, 0x17, 0xa3, 0xc0, 0xa1, 0xaf, 0xff, 0x01, 0x17, 0x49, + 0x30, 0xfc, 0x22, 0x28, 0x7c, 0x33, 0xdb, 0xcf, 0x0a, 0xc8, 0xb8, + 0x9a, 0xd9, 0x29, 0x53, 0x0a, 0x1b, 0xb3, 0xab, 0x5e, 0x69, 0xf2, + 0x4c, 0x7f, 0x60, 0x70, 0xc8, 0xf8, 0x40, 0xc9, 0xab, 0xb4, 0xf6, + 0x9f, 0xbf, 0xc8, 0xa7, 0xff, 0x51, 0x26, 0xfa, 0xee, 0xbb, 0xb5, + 0x58, 0x05, 0xee, 0x9c, 0x1c, 0xf2, 0xce, 0x5a, 0x57, 0x26, 0x32, + 0x87, 0xae, 0xc5, 0x78, 0x0f, 0x04, 0xec, 0x32, 0x4c, 0x35, 0x14, + 0x12, 0x2c, 0xfc, 0x32, 0x31, 0xfc, 0x1a, 0x8b, 0x71, 0x8a, 0x62, + 0x86, 0x37, 0x30, 0xa2, 0x70, 0x2b, 0xb7, 0x63, 0x66, 0x11, 0x6b, + 0xed, 0x09, 0xe0, 0xfd, 0x5c, 0x6d, 0x84, 0xb6, 0xb0, 0xc1, 0xab, + 0xaf, 0x24, 0x9d, 0x5d, 0xd0, 0xf7, 0xf5, 0xa7, 0xea, + }, + }, +} diff --git a/crypto/xchacha20poly1305/xchachapoly.go b/crypto/xchacha20poly1305/xchachapoly.go new file mode 100644 index 0000000..c80c497 --- /dev/null +++ b/crypto/xchacha20poly1305/xchachapoly.go @@ -0,0 +1,259 @@ +// Package xchacha20poly1305 creates an AEAD using hchacha, chacha, and poly1305 +// This allows for randomized nonces to be used in conjunction with chacha. +package xchacha20poly1305 + +import ( + "crypto/cipher" + "encoding/binary" + "errors" + "fmt" + + "golang.org/x/crypto/chacha20poly1305" +) + +// Implements crypto.AEAD +type xchacha20poly1305 struct { + key [KeySize]byte +} + +const ( + // KeySize is the size of the key used by this AEAD, in bytes. + KeySize = 32 + // NonceSize is the size of the nonce used with this AEAD, in bytes. + NonceSize = 24 + // TagSize is the size added from poly1305 + TagSize = 16 + // MaxPlaintextSize is the max size that can be passed into a single call of Seal + MaxPlaintextSize = (1 << 38) - 64 + // MaxCiphertextSize is the max size that can be passed into a single call of Open, + // this differs from plaintext size due to the tag + MaxCiphertextSize = (1 << 38) - 48 + + // sigma are constants used in xchacha. + // Unrolled from a slice so that they can be inlined, as slices can't be constants. + sigma0 = uint32(0x61707865) + sigma1 = uint32(0x3320646e) + sigma2 = uint32(0x79622d32) + sigma3 = uint32(0x6b206574) +) + +// New returns a new xchachapoly1305 AEAD +func New(key []byte) (cipher.AEAD, error) { + if len(key) != KeySize { + return nil, errors.New("xchacha20poly1305: bad key length") + } + ret := new(xchacha20poly1305) + copy(ret.key[:], key) + return ret, nil +} + +func (c *xchacha20poly1305) NonceSize() int { + return NonceSize +} + +func (c *xchacha20poly1305) Overhead() int { + return TagSize +} + +func (c *xchacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte { + if len(nonce) != NonceSize { + panic("xchacha20poly1305: bad nonce length passed to Seal") + } + + if uint64(len(plaintext)) > MaxPlaintextSize { + panic("xchacha20poly1305: plaintext too large") + } + + var subKey [KeySize]byte + var hNonce [16]byte + var subNonce [chacha20poly1305.NonceSize]byte + copy(hNonce[:], nonce[:16]) + + HChaCha20(&subKey, &hNonce, &c.key) + + // This can't error because we always provide a correctly sized key + chacha20poly1305, _ := chacha20poly1305.New(subKey[:]) + + copy(subNonce[4:], nonce[16:]) + + return chacha20poly1305.Seal(dst, subNonce[:], plaintext, additionalData) +} + +func (c *xchacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { + if len(nonce) != NonceSize { + return nil, fmt.Errorf("xchacha20poly1305: bad nonce length passed to Open") + } + if uint64(len(ciphertext)) > MaxCiphertextSize { + return nil, fmt.Errorf("xchacha20poly1305: ciphertext too large") + } + var subKey [KeySize]byte + var hNonce [16]byte + var subNonce [chacha20poly1305.NonceSize]byte + copy(hNonce[:], nonce[:16]) + + HChaCha20(&subKey, &hNonce, &c.key) + + // This can't error because we always provide a correctly sized key + chacha20poly1305, _ := chacha20poly1305.New(subKey[:]) + + copy(subNonce[4:], nonce[16:]) + + return chacha20poly1305.Open(dst, subNonce[:], ciphertext, additionalData) +} + +// HChaCha exported from +// https://github.com/aead/chacha20/blob/8b13a72661dae6e9e5dea04f344f0dc95ea29547/chacha/chacha_generic.go#L194 +// TODO: Add support for the different assembly instructions used there. + +// The MIT License (MIT) + +// Copyright (c) 2016 Andreas Auernhammer + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +// HChaCha20 generates 32 pseudo-random bytes from a 128 bit nonce and a 256 bit secret key. +// It can be used as a key-derivation-function (KDF). +func HChaCha20(out *[32]byte, nonce *[16]byte, key *[32]byte) { hChaCha20Generic(out, nonce, key) } + +func hChaCha20Generic(out *[32]byte, nonce *[16]byte, key *[32]byte) { + v00 := sigma0 + v01 := sigma1 + v02 := sigma2 + v03 := sigma3 + v04 := binary.LittleEndian.Uint32(key[0:]) + v05 := binary.LittleEndian.Uint32(key[4:]) + v06 := binary.LittleEndian.Uint32(key[8:]) + v07 := binary.LittleEndian.Uint32(key[12:]) + v08 := binary.LittleEndian.Uint32(key[16:]) + v09 := binary.LittleEndian.Uint32(key[20:]) + v10 := binary.LittleEndian.Uint32(key[24:]) + v11 := binary.LittleEndian.Uint32(key[28:]) + v12 := binary.LittleEndian.Uint32(nonce[0:]) + v13 := binary.LittleEndian.Uint32(nonce[4:]) + v14 := binary.LittleEndian.Uint32(nonce[8:]) + v15 := binary.LittleEndian.Uint32(nonce[12:]) + + for i := 0; i < 20; i += 2 { + v00 += v04 + v12 ^= v00 + v12 = (v12 << 16) | (v12 >> 16) + v08 += v12 + v04 ^= v08 + v04 = (v04 << 12) | (v04 >> 20) + v00 += v04 + v12 ^= v00 + v12 = (v12 << 8) | (v12 >> 24) + v08 += v12 + v04 ^= v08 + v04 = (v04 << 7) | (v04 >> 25) + v01 += v05 + v13 ^= v01 + v13 = (v13 << 16) | (v13 >> 16) + v09 += v13 + v05 ^= v09 + v05 = (v05 << 12) | (v05 >> 20) + v01 += v05 + v13 ^= v01 + v13 = (v13 << 8) | (v13 >> 24) + v09 += v13 + v05 ^= v09 + v05 = (v05 << 7) | (v05 >> 25) + v02 += v06 + v14 ^= v02 + v14 = (v14 << 16) | (v14 >> 16) + v10 += v14 + v06 ^= v10 + v06 = (v06 << 12) | (v06 >> 20) + v02 += v06 + v14 ^= v02 + v14 = (v14 << 8) | (v14 >> 24) + v10 += v14 + v06 ^= v10 + v06 = (v06 << 7) | (v06 >> 25) + v03 += v07 + v15 ^= v03 + v15 = (v15 << 16) | (v15 >> 16) + v11 += v15 + v07 ^= v11 + v07 = (v07 << 12) | (v07 >> 20) + v03 += v07 + v15 ^= v03 + v15 = (v15 << 8) | (v15 >> 24) + v11 += v15 + v07 ^= v11 + v07 = (v07 << 7) | (v07 >> 25) + v00 += v05 + v15 ^= v00 + v15 = (v15 << 16) | (v15 >> 16) + v10 += v15 + v05 ^= v10 + v05 = (v05 << 12) | (v05 >> 20) + v00 += v05 + v15 ^= v00 + v15 = (v15 << 8) | (v15 >> 24) + v10 += v15 + v05 ^= v10 + v05 = (v05 << 7) | (v05 >> 25) + v01 += v06 + v12 ^= v01 + v12 = (v12 << 16) | (v12 >> 16) + v11 += v12 + v06 ^= v11 + v06 = (v06 << 12) | (v06 >> 20) + v01 += v06 + v12 ^= v01 + v12 = (v12 << 8) | (v12 >> 24) + v11 += v12 + v06 ^= v11 + v06 = (v06 << 7) | (v06 >> 25) + v02 += v07 + v13 ^= v02 + v13 = (v13 << 16) | (v13 >> 16) + v08 += v13 + v07 ^= v08 + v07 = (v07 << 12) | (v07 >> 20) + v02 += v07 + v13 ^= v02 + v13 = (v13 << 8) | (v13 >> 24) + v08 += v13 + v07 ^= v08 + v07 = (v07 << 7) | (v07 >> 25) + v03 += v04 + v14 ^= v03 + v14 = (v14 << 16) | (v14 >> 16) + v09 += v14 + v04 ^= v09 + v04 = (v04 << 12) | (v04 >> 20) + v03 += v04 + v14 ^= v03 + v14 = (v14 << 8) | (v14 >> 24) + v09 += v14 + v04 ^= v09 + v04 = (v04 << 7) | (v04 >> 25) + } + + binary.LittleEndian.PutUint32(out[0:], v00) + binary.LittleEndian.PutUint32(out[4:], v01) + binary.LittleEndian.PutUint32(out[8:], v02) + binary.LittleEndian.PutUint32(out[12:], v03) + binary.LittleEndian.PutUint32(out[16:], v12) + binary.LittleEndian.PutUint32(out[20:], v13) + binary.LittleEndian.PutUint32(out[24:], v14) + binary.LittleEndian.PutUint32(out[28:], v15) +} diff --git a/crypto/xchacha20poly1305/xchachapoly_test.go b/crypto/xchacha20poly1305/xchachapoly_test.go new file mode 100644 index 0000000..24d00f6 --- /dev/null +++ b/crypto/xchacha20poly1305/xchachapoly_test.go @@ -0,0 +1,113 @@ +package xchacha20poly1305 + +import ( + "bytes" + cr "crypto/rand" + mr "math/rand" + "testing" +) + +// The following test is taken from +// https://github.com/golang/crypto/blob/master/chacha20poly1305/chacha20poly1305_test.go#L69 +// It requires the below copyright notice, where "this source code" refers to the following function. +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found at the bottom of this file. +func TestRandom(t *testing.T) { + // Some random tests to verify Open(Seal) == Plaintext + for i := 0; i < 256; i++ { + var nonce [24]byte + var key [32]byte + + al := mr.Intn(128) + pl := mr.Intn(16384) + ad := make([]byte, al) + plaintext := make([]byte, pl) + _, err := cr.Read(key[:]) + if err != nil { + t.Errorf("error on read: %v", err) + } + _, err = cr.Read(nonce[:]) + if err != nil { + t.Errorf("error on read: %v", err) + } + _, err = cr.Read(ad) + if err != nil { + t.Errorf("error on read: %v", err) + } + _, err = cr.Read(plaintext) + if err != nil { + t.Errorf("error on read: %v", err) + } + + aead, err := New(key[:]) + if err != nil { + t.Fatal(err) + } + + ct := aead.Seal(nil, nonce[:], plaintext, ad) + + plaintext2, err := aead.Open(nil, nonce[:], ct, ad) + if err != nil { + t.Errorf("random #%d: Open failed", i) + continue + } + + if !bytes.Equal(plaintext, plaintext2) { + t.Errorf("random #%d: plaintext's don't match: got %x vs %x", i, plaintext2, plaintext) + continue + } + + if len(ad) > 0 { + alterAdIdx := mr.Intn(len(ad)) + ad[alterAdIdx] ^= 0x80 + if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { + t.Errorf("random #%d: Open was successful after altering additional data", i) + } + ad[alterAdIdx] ^= 0x80 + } + + alterNonceIdx := mr.Intn(aead.NonceSize()) + nonce[alterNonceIdx] ^= 0x80 + if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { + t.Errorf("random #%d: Open was successful after altering nonce", i) + } + nonce[alterNonceIdx] ^= 0x80 + + alterCtIdx := mr.Intn(len(ct)) + ct[alterCtIdx] ^= 0x80 + if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { + t.Errorf("random #%d: Open was successful after altering ciphertext", i) + } + ct[alterCtIdx] ^= 0x80 + } +} + +// AFOREMENTIONED LICENSE +// Copyright (c) 2009 The Go Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go new file mode 100644 index 0000000..5afa6e6 --- /dev/null +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -0,0 +1,54 @@ +package xsalsa20symmetric + +import ( + "errors" + "fmt" + + "golang.org/x/crypto/nacl/secretbox" + + "github.com/cometbft/cometbft/crypto" +) + +// TODO, make this into a struct that implements crypto.Symmetric. + +const nonceLen = 24 +const secretLen = 32 + +// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) +// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. +func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { + if len(secret) != secretLen { + panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) + } + nonce := crypto.CRandBytes(nonceLen) + nonceArr := [nonceLen]byte{} + copy(nonceArr[:], nonce) + secretArr := [secretLen]byte{} + copy(secretArr[:], secret) + ciphertext = make([]byte, nonceLen+secretbox.Overhead+len(plaintext)) + copy(ciphertext, nonce) + secretbox.Seal(ciphertext[nonceLen:nonceLen], plaintext, &nonceArr, &secretArr) + return ciphertext +} + +// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) +// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. +func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) { + if len(secret) != secretLen { + panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) + } + if len(ciphertext) <= secretbox.Overhead+nonceLen { + return nil, errors.New("ciphertext is too short") + } + nonce := ciphertext[:nonceLen] + nonceArr := [nonceLen]byte{} + copy(nonceArr[:], nonce) + secretArr := [secretLen]byte{} + copy(secretArr[:], secret) + plaintext = make([]byte, len(ciphertext)-nonceLen-secretbox.Overhead) + _, ok := secretbox.Open(plaintext[:0], ciphertext[nonceLen:], &nonceArr, &secretArr) + if !ok { + return nil, errors.New("ciphertext decryption failed") + } + return plaintext, nil +} diff --git a/crypto/xsalsa20symmetric/symmetric_test.go b/crypto/xsalsa20symmetric/symmetric_test.go new file mode 100644 index 0000000..6643177 --- /dev/null +++ b/crypto/xsalsa20symmetric/symmetric_test.go @@ -0,0 +1,40 @@ +package xsalsa20symmetric + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "golang.org/x/crypto/bcrypt" + + "github.com/cometbft/cometbft/crypto" +) + +func TestSimple(t *testing.T) { + + plaintext := []byte("sometext") + secret := []byte("somesecretoflengththirtytwo===32") + ciphertext := EncryptSymmetric(plaintext, secret) + plaintext2, err := DecryptSymmetric(ciphertext, secret) + + require.Nil(t, err, "%+v", err) + assert.Equal(t, plaintext, plaintext2) +} + +func TestSimpleWithKDF(t *testing.T) { + + plaintext := []byte("sometext") + secretPass := []byte("somesecret") + secret, err := bcrypt.GenerateFromPassword(secretPass, 12) + if err != nil { + t.Error(err) + } + secret = crypto.Sha256(secret) + + ciphertext := EncryptSymmetric(plaintext, secret) + plaintext2, err := DecryptSymmetric(ciphertext, secret) + + require.Nil(t, err, "%+v", err) + assert.Equal(t, plaintext, plaintext2) +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f41bab2 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,66 @@ +version: '3' + +services: + node0: + container_name: node0 + image: "cometbft/localnode" + ports: + - "26656-26657:26656-26657" + environment: + - ID=0 + - LOG=${LOG:-cometbft.log} + volumes: + - ./build:/cometbft:Z + networks: + localnet: + ipv4_address: 192.167.10.2 + + node1: + container_name: node1 + image: "cometbft/localnode" + ports: + - "26659-26660:26656-26657" + environment: + - ID=1 + - LOG=${LOG:-cometbft.log} + volumes: + - ./build:/cometbft:Z + networks: + localnet: + ipv4_address: 192.167.10.3 + + node2: + container_name: node2 + image: "cometbft/localnode" + environment: + - ID=2 + - LOG=${LOG:-cometbft.log} + ports: + - "26661-26662:26656-26657" + volumes: + - ./build:/cometbft:Z + networks: + localnet: + ipv4_address: 192.167.10.4 + + node3: + container_name: node3 + image: "cometbft/localnode" + environment: + - ID=3 + - LOG=${LOG:-cometbft.log} + ports: + - "26663-26664:26656-26657" + volumes: + - ./build:/cometbft:Z + networks: + localnet: + ipv4_address: 192.167.10.5 + +networks: + localnet: + driver: bridge + ipam: + driver: default + config: + - subnet: 192.167.0.0/16 diff --git a/docs/DOCS_README.md b/docs/DOCS_README.md new file mode 100644 index 0000000..15250fc --- /dev/null +++ b/docs/DOCS_README.md @@ -0,0 +1,13 @@ +# Docs Build Workflow + +The documentation for CometBFT is hosted at: + +- + +built from the files in these (`/docs` and `/spec`) directories. + +Content modified and merged to these folders will be deployed to the `https://docs.cometbft.com` website using workflow logic from the [cometbft-docs](https://github.com/cometbft/cometbft-docs) repository + +### Building locally + +For information on how to build the documentation and view it locally, please visit the [cometbft-docs](https://github.com/cometbft/cometbft-docs) Github repository. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..c003506 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,43 @@ +--- +title: CometBFT Documentation +description: CometBFT is a blockchain application platform. +footer: + newsletter: false +--- + +# CometBFT + +Welcome to the CometBFT documentation! + +CometBFT is a blockchain application platform; it provides the equivalent +of a web-server, database, and supporting libraries for blockchain applications +written in any programming language. Like a web-server serving web applications, +CometBFT serves blockchain applications. + +More formally, CometBFT performs Byzantine Fault Tolerant (BFT) +State Machine Replication (SMR) for arbitrary deterministic, finite state machines. +For more background, see [What is CometBFT?](./introduction/README.md#what-is-cometbft). + +To get started quickly with an example application, see the [quick start guide](guides/quick-start.md). + +To learn about application development on CometBFT, see the [Application Blockchain Interface](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/abci). + +For more details on using CometBFT, see the respective documentation for +[CometBFT internals](core/), [benchmarking and monitoring](tools/), and [network deployments](networks/). + +## Contribute + +To recommend a change to the documentation, please submit a PR. Each major +release's documentation is housed on the corresponding release branch, e.g. for +the v0.34 release series, the documentation is housed on the `v0.34.x` branch. + +When submitting changes that affect all releases, please start by submitting a +PR to the docs on `main` - this will be backported to the relevant release +branches. If a change is exclusively relevant to a specific release, please +target that release branch with your PR. + +Changes to the documentation will be reviewed by the team and, if accepted and +merged, published to for the respective version(s). + +The build process for the documentation is housed in the [CometBFT documentation +repository](https://github.com/cometbft/cometbft-docs). diff --git a/docs/app-dev/README.md b/docs/app-dev/README.md new file mode 100644 index 0000000..40c756b --- /dev/null +++ b/docs/app-dev/README.md @@ -0,0 +1,12 @@ +--- +order: false +parent: + order: 3 +--- + +# Apps + +- [Using ABCI-CLI](./abci-cli.md) +- [Getting Started](./getting-started.md) +- [Indexing transactions](./indexing-transactions.md) +- [Application Architecture Guide](./app-architecture.md) diff --git a/docs/app-dev/abci-cli.md b/docs/app-dev/abci-cli.md new file mode 100644 index 0000000..68e9784 --- /dev/null +++ b/docs/app-dev/abci-cli.md @@ -0,0 +1,213 @@ +--- +order: 3 +--- + +# Using ABCI-CLI + +To facilitate testing and debugging of ABCI servers and simple apps, we +built a CLI, the `abci-cli`, for sending ABCI messages from the command +line. + +## Install + +Make sure you [have Go installed](https://golang.org/doc/install). + +Next, install the `abci-cli` tool and example applications: + +```sh +git clone https://github.com/cometbft/cometbft.git +cd cometbft +make install_abci +``` + +Now run `abci-cli` to see the list of commands: + +```sh +Usage: + abci-cli [command] + +Available Commands: + batch run a batch of abci commands against an application + check_tx validate a transaction + commit commit the application state and return the Merkle root hash + completion Generate the autocompletion script for the specified shell + console start an interactive ABCI console for multiple commands + echo have the application echo a message + finalize_block deliver a block of transactions to the application + help Help about any command + info get some info about the application + kvstore ABCI demo example + prepare_proposal prepare proposal + process_proposal process proposal + query query the application state + test run integration tests + version print ABCI console version + +Flags: + --abci string either socket or grpc (default "socket") + --address string address of application socket (default "tcp://0.0.0.0:26658") + -h, --help help for abci-cli + --log_level string set the logger level (default "debug") + -v, --verbose print the command and results as if it were a console session + +Use "abci-cli [command] --help" for more information about a command. +``` + +## KVStore - First Example + +The `abci-cli` tool lets us send ABCI messages to our application, to +help build and debug them. + +The most important messages are `deliver_tx`, `check_tx`, and `commit`, +but there are others for convenience, configuration, and information +purposes. + +We'll start a kvstore application, which was installed at the same time as +`abci-cli` above. The kvstore just stores transactions in a Merkle tree. Its +code can be found +[here](https://github.com/cometbft/cometbft/blob/v0.38.x/abci/example/kvstore/kvstore.go). + +Start the application by running: + +```sh +abci-cli kvstore +``` + +And in another terminal, run + +```sh +abci-cli echo hello +abci-cli info +``` + +You'll see something like: + +```sh +-> data: hello +-> data.hex: 68656C6C6F +``` + +and: + +```sh +-> data: {"size":0} +-> data.hex: 7B2273697A65223A307D +``` + +An ABCI application must provide two things: + +- a socket server +- a handler for ABCI messages + +When we run the `abci-cli` tool we open a new connection to the +application's socket server, send the given ABCI message, and wait for a +response. + +The server may be generic for a particular language, and we provide a +[reference implementation in +Golang](https://github.com/cometbft/cometbft/tree/v0.38.x/abci/server). See the +[list of other ABCI implementations](https://github.com/tendermint/awesome#ecosystem) for servers in +other languages. + +The handler is specific to the application, and may be arbitrary, so +long as it is deterministic and conforms to the ABCI interface +specification. + +So when we run `abci-cli info`, we open a new connection to the ABCI +server, which calls the `Info()` method on the application, which tells +us the number of transactions in our Merkle tree. + +Now, since every command opens a new connection, we provide the +`abci-cli console` and `abci-cli batch` commands, to allow multiple ABCI +messages to be sent over a single connection. + +Running `abci-cli console` should drop you in an interactive console for +speaking ABCI messages to your application. + +Try running these commands: + +```sh +> echo hello +-> code: OK +-> data: hello +-> data.hex: 0x68656C6C6F + +> info +-> code: OK +-> data: {"size":0} +-> data.hex: 0x7B2273697A65223A307D + +> prepare_proposal "abc=123" +-> code: OK +-> log: Succeeded. Tx: abc=123 + +> process_proposal "abc==456" +-> code: OK +-> status: REJECT + +> process_proposal "abc=123" +-> code: OK +-> status: ACCEPT + +> finalize_block "abc=123" +-> code: OK +-> code: OK +-> data.hex: 0x0200000000000000 + +> commit +-> code: OK + +> info +-> code: OK +-> data: {"size":1} +-> data.hex: 0x7B2273697A65223A317D + +> query "abc" +-> code: OK +-> log: exists +-> height: 0 +-> key: abc +-> key.hex: 616263 +-> value: 123 +-> value.hex: 313233 + +> finalize_block "def=xyz" "ghi=123" +-> code: OK +-> code: OK +-> code: OK +-> data.hex: 0x0600000000000000 + +> commit +-> code: OK + +> query "def" +-> code: OK +-> log: exists +-> height: 0 +-> key: def +-> key.hex: 646566 +-> value: xyz +-> value.hex: 78797A +``` + +Note that if we do `finalize_block "abc" ...` it will store `(abc, abc)`, but if +we do `finalize_block "abc=efg" ...` it will store `(abc, efg)`. + +You could put the commands in a file and run +`abci-cli --verbose batch < myfile`. + + +Note that the `abci-cli` is designed strictly for testing and debugging. In a real +deployment, the role of sending messages is taken by CometBFT, which +connects to the app using four separate connections, each with its own +pattern of messages. + +For examples of running an ABCI app with CometBFT, see the +[getting started guide](./getting-started.md). + +## Bounties + +Want to write an app in your favorite language?! We'd be happy +to add you to our [ecosystem](https://github.com/tendermint/awesome#ecosystem)! +See [funding](https://github.com/interchainio/funding) opportunities from the +[Interchain Foundation](https://interchain.io) for implementations in new languages and more. diff --git a/docs/app-dev/app-architecture.md b/docs/app-dev/app-architecture.md new file mode 100644 index 0000000..41ab222 --- /dev/null +++ b/docs/app-dev/app-architecture.md @@ -0,0 +1,55 @@ +--- +order: 4 +--- + +# Application Architecture Guide + +Here we provide a brief guide on the recommended architecture of a +CometBFT blockchain application. + +We distinguish here between two forms of "application". The first is the +end-user application, like a desktop-based wallet app that a user downloads, +which is where the user actually interacts with the system. The other is the +ABCI application, which is the logic that actually runs on the blockchain. +Transactions sent by an end-user application are ultimately processed by the ABCI +application after being committed by CometBFT. + +The end-user application communicates with a REST API exposed by the application. +The application runs CometBFT nodes and verifies CometBFT light-client proofs +through the CometBFT RPC. The CometBFT process communicates with +a local ABCI application, where the user query or transaction is actually +processed. + +The ABCI application must be a deterministic result of the CometBFT +consensus - any external influence on the application state that didn't +come through CometBFT could cause a consensus failure. Thus _nothing_ +should communicate with the ABCI application except CometBFT via ABCI. + +If the ABCI application is written in Go, it can be compiled into the +CometBFT binary. Otherwise, it should use a unix socket to communicate +with CometBFT. If it's necessary to use TCP, extra care must be taken +to encrypt and authenticate the connection. + +All reads from the ABCI application happen through the CometBFT `/abci_query` +endpoint. All writes to the ABCI application happen through the CometBFT +`/broadcast_tx_*` endpoints. + +The Light-Client Daemon is what provides light clients (end users) with +nearly all the security of a full node. It formats and broadcasts +transactions, and verifies proofs of queries and transaction results. +Note that it need not be a daemon - the Light-Client logic could instead +be implemented in the same process as the end-user application. + +Note for those ABCI applications with weaker security requirements, the +functionality of the Light-Client Daemon can be moved into the ABCI +application process itself. That said, exposing the ABCI application process +to anything besides CometBFT over ABCI requires extreme caution, as +all transactions, and possibly all queries, should still pass through +CometBFT. + +See the following for more extensive documentation: + +- [Interchain Standard for the Light-Client REST API](https://github.com/cosmos/cosmos-sdk/pull/1617) (legacy/deprecated) +- [CometBFT RPC Docs](../rpc) +- [CometBFT in Production](../core/running-in-production.md) +- [ABCI spec](../spec/abci) diff --git a/docs/app-dev/getting-started.md b/docs/app-dev/getting-started.md new file mode 100644 index 0000000..c3e2eaa --- /dev/null +++ b/docs/app-dev/getting-started.md @@ -0,0 +1,199 @@ +--- +order: 2 +--- + +# Getting Started + +## First CometBFT App + +As a general purpose blockchain engine, CometBFT is agnostic to the +application you want to run. So, to run a complete blockchain that does +something useful, you must start two programs: one is CometBFT, +the other is your application, which can be written in any programming +language. + +CometBFT handles all the p2p and consensus logic, and just forwards transactions to the +application when they need to be validated, or when they're ready to be +executed and committed. + +In this guide, we show you some examples of how to run an application +using CometBFT. + +### Install + +The first apps we will work with are written in Go. To install them, you +need to [install Go](https://golang.org/doc/install), put +`$GOPATH/bin` in your `$PATH` and enable go modules. If you use `bash`, +follow these instructions: + +```bash +echo export GOPATH=\"\$HOME/go\" >> ~/.bash_profile +echo export PATH=\"\$PATH:\$GOPATH/bin\" >> ~/.bash_profile +``` + +Then run + +```bash +go get github.com/cometbft/cometbft +cd $GOPATH/src/github.com/cometbft/cometbft +make install_abci +``` + +Now you should have the `abci-cli` installed; run `abci-cli` to see the list of commands: + +``` +Usage: + abci-cli [command] + +Available Commands: + batch run a batch of abci commands against an application + check_tx validate a transaction + commit commit the application state and return the Merkle root hash + completion Generate the autocompletion script for the specified shell + console start an interactive ABCI console for multiple commands + echo have the application echo a message + finalize_block deliver a block of transactions to the application + help Help about any command + info get some info about the application + kvstore ABCI demo example + prepare_proposal prepare proposal + process_proposal process proposal + query query the application state + test run integration tests + version print ABCI console version + +Flags: + --abci string either socket or grpc (default "socket") + --address string address of application socket (default "tcp://0.0.0.0:26658") + -h, --help help for abci-cli + --log_level string set the logger level (default "debug") + -v, --verbose print the command and results as if it were a console session + +Use "abci-cli [command] --help" for more information about a command. +``` + +You'll notice the `kvstore` command, an example application written in Go. + +Now, let's run an app! + +## KVStore - A First Example + +The kvstore app is a [Merkle +tree](https://en.wikipedia.org/wiki/Merkle_tree) that just stores all +transactions. If the transaction contains an `=`, e.g. `key=value`, then +the `value` is stored under the `key` in the Merkle tree. Otherwise, the +full transaction bytes are stored as the key and the value. + +Let's start a kvstore application. + +```sh +abci-cli kvstore +``` + +In another terminal, we can start CometBFT. You should already have the +CometBFT binary installed. If not, follow the steps from +[here](../guides/install.md). If you have never run CometBFT +before, use: + +```sh +cometbft init +cometbft node +``` + +If you have used CometBFT, you may want to reset the data for a new +blockchain by running `cometbft unsafe-reset-all`. Then you can run +`cometbft node` to start CometBFT, and connect to the app. For more +details, see [the guide on using CometBFT](../core/using-cometbft.md). + +You should see CometBFT making blocks! We can get the status of our +CometBFT node as follows: + +```sh +curl -s localhost:26657/status +``` + +The `-s` just silences `curl`. For nicer output, pipe the result into a +tool like [jq](https://stedolan.github.io/jq/) or `json_pp`. + +Now let's send some transactions to the kvstore. + +```sh +curl -s 'localhost:26657/broadcast_tx_commit?tx="abcd"' +``` + +Note the single quote (`'`) around the url, which ensures that the +double quotes (`"`) are not escaped by bash. This command sent a +transaction with bytes `abcd`, so `abcd` will be stored as both the key +and the value in the Merkle tree. The response should look something +like: + +```json +{ + "jsonrpc": "2.0", + "id": "", + "result": { + "check_tx": {}, + "deliver_tx": { + "tags": [ + { + "key": "YXBwLmNyZWF0b3I=", + "value": "amFl" + }, + { + "key": "YXBwLmtleQ==", + "value": "YWJjZA==" + } + ] + }, + "hash": "9DF66553F98DE3C26E3C3317A3E4CED54F714E39", + "height": 14 + } +} +``` + +We can confirm that our transaction worked and the value got stored by +querying the app: + +```sh +curl -s 'localhost:26657/abci_query?data="abcd"' +``` + +The result should look like: + +```json +{ + "jsonrpc": "2.0", + "id": "", + "result": { + "response": { + "log": "exists", + "index": "-1", + "key": "YWJjZA==", + "value": "YWJjZA==" + } + } +} +``` + +Note the `value` in the result (`YWJjZA==`); this is the base64-encoding +of the ASCII of `abcd`. You can verify this in a python 2 shell by +running `"YWJjZA==".decode('base64')` or in python 3 shell by running +`import codecs; codecs.decode(b"YWJjZA==", 'base64').decode('ascii')`. +Stay tuned for a future release that [makes this output more +human-readable](https://github.com/tendermint/tendermint/issues/1794). + +Now let's try setting a different key and value: + +```sh +curl -s 'localhost:26657/broadcast_tx_commit?tx="name=satoshi"' +``` + +Now if we query for `name`, we should get `satoshi`, or `c2F0b3NoaQ==` +in base64: + +```sh +curl -s 'localhost:26657/abci_query?data="name"' +``` + +Try some other transactions and queries to make sure everything is +working! diff --git a/docs/app-dev/indexing-transactions.md b/docs/app-dev/indexing-transactions.md new file mode 100644 index 0000000..29f8c54 --- /dev/null +++ b/docs/app-dev/indexing-transactions.md @@ -0,0 +1,305 @@ +--- +order: 5 +--- + +# Indexing Transactions + +CometBFT allows you to index transactions and blocks and later query or +subscribe to their results. Transactions are indexed by `ResponseFinalizeBlock.tx_results.events` and +blocks are indexed by `ResponseFinalizeBlock.events`. However, transactions +are also indexed by a primary key which includes the transaction hash and maps +to and stores the corresponding transaction results. Blocks are indexed by a primary key +which includes the block height and maps to and stores the block height, i.e. +the block itself is never stored. + +Each event contains a type and a list of attributes, which are key-value pairs +denoting something about what happened during the method's execution. For more +details on `Events`, see the [ABCI][abci-events] documentation. + +An `Event` has a composite key associated with it. A `compositeKey` is +constructed by its type and key separated by a dot. + +For example: + +```json +"jack": [ + "account.number": 100 +] +``` + +would be equal to the composite key of `jack.account.number`. + +By default, CometBFT will index all transactions by their respective hashes +and height and blocks by their height. + +CometBFT allows for different events within the same height to have +equal attributes. + +## Configuration + +Operators can configure indexing via the `[tx_index]` section. The `indexer` +field takes a series of supported indexers. If `null` is included, indexing will +be turned off regardless of other values provided. + +```toml +[tx-index] + +# The backend database to back the indexer. +# If indexer is "null", no indexer service will be used. +# +# The application will set which txs to index. In some cases a node operator will be able +# to decide which txs to index based on configuration set in the application. +# +# Options: +# 1) "null" +# 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). +# - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. +# 3) "psql" - the indexer services backed by PostgreSQL. +# indexer = "kv" +``` + +### Supported Indexers + +#### KV + +The `kv` indexer type is an embedded key-value store supported by the main +underlying CometBFT database. Using the `kv` indexer type allows you to query +for block and transaction events directly against CometBFT's RPC. However, the +query syntax is limited and so this indexer type might be deprecated or removed +entirely in the future. + +**Implementation and data layout** + +The kv indexer stores each attribute of an event individually, by creating a composite key +with + +- event type, +- attribute key, +- attribute value, +- event generator (e.g. `FinalizeBlock`) +- the height, and +- event counter. + For example the following events: + +``` +Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: "sender", Value: "Bob", Index: true}, + {Key: "recipient", Value: "Alice", Index: true}, + {Key: "balance", Value: "100", Index: true}, + {Key: "note", Value: "nothing", Index: true}, + }, + +``` + +``` +Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: "sender", Value: "Tom", Index: true}, + {Key: "recipient", Value: "Alice", Index: true}, + {Key: "balance", Value: "200", Index: true}, + {Key: "note", Value: "nothing", Index: true}, + }, +``` + +will be represented as follows in the store, assuming these events result from the `FinalizeBlock` call for height 1: + +``` +Key value +---- event1 ------ +transferSenderBobFinalizeBlock11 1 +transferRecipientAliceFinalizeBlock11 1 +transferBalance100FinalizeBlock11 1 +transferNodeNothingFinalizeBlock11 1 +---- event2 ------ +transferSenderTomFinalizeBlock12 1 +transferRecepientAliceFinalizeBlock12 1 +transferBalance200FinalizeBlock12 1 +transferNodeNothingFinalizeBlock12 1 + +``` + +The event number is a local variable kept by the indexer and incremented when a new event is processed. +It is an `int64` variable and has no other semantics besides being used to associate attributes belonging to the same events within a height. +This variable is not atomically incremented as event indexing is deterministic. **Should this ever change**, the event id generation +will be broken. + +#### PostgreSQL + +The `psql` indexer type allows an operator to enable block and transaction event +indexing by proxying it to an external PostgreSQL instance allowing for the events +to be stored in relational models. Since the events are stored in a RDBMS, operators +can leverage SQL to perform a series of rich and complex queries that are not +supported by the `kv` indexer type. Since operators can leverage SQL directly, +searching is not enabled for the `psql` indexer type via CometBFT's RPC -- any +such query will fail. + +Note, the SQL schema is stored in `state/indexer/sink/psql/schema.sql` and operators +must explicitly create the relations prior to starting CometBFT and enabling +the `psql` indexer type. + +Example: + +```shell +psql ... -f state/indexer/sink/psql/schema.sql +``` + +## Default Indexes + +The CometBFT tx and block event indexer indexes a few select reserved events +by default. + +### Transactions + +The following indexes are indexed by default: + +- `tx.height` +- `tx.hash` + +### Blocks + +The following indexes are indexed by default: + +- `block.height` + +## Adding Events + +Applications are free to define which events to index. CometBFT does not +expose functionality to define which events to index and which to ignore. In +your application's `FinalizeBlock` method, add the `Events` field with pairs of +UTF-8 encoded strings (e.g. "transfer.sender": "Bob", "transfer.recipient": +"Alice", "transfer.balance": "100"). + +Example: + +```go +func (app *Application) FinalizeBlock(_ context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + + //... + tx_results[0] := &types.ExecTxResult{ + Code: CodeTypeOK, + // With every transaction we can emit a series of events. To make it simple, we just emit the same events. + Events: []types.Event{ + { + Type: "app", + Attributes: []types.EventAttribute{ + {Key: "creator", Value: "Cosmoshi Netowoko", Index: true}, + {Key: "key", Value: key, Index: true}, + {Key: "index_key", Value: "index is working", Index: true}, + {Key: "noindex_key", Value: "index is working", Index: false}, + }, + }, + { + Type: "app", + Attributes: []types.EventAttribute{ + {Key: "creator", Value: "Cosmoshi", Index: true}, + {Key: "key", Value: value, Index: true}, + {Key: "index_key", Value: "index is working", Index: true}, + {Key: "noindex_key", Value: "index is working", Index: false}, + }, + }, + }, + } + + block_events = []types.Event{ + { + Type: "loan", + Attributes: []types.EventAttribute{ + { Key: "account_no", Value: "1", Index: true}, + { Key: "amount", Value: "200", Index: true }, + }, + }, + { + Type: "loan", + Attributes: []types.EventAttribute{ + { Key: "account_no", Value: "2", Index: true }, + { Key: "amount", Value: "300", Index: true}, + }, + }, + } + return &types.ResponseFinalizeBlock{TxResults: tx_results, Events: block_events} +} +``` + +If the indexer is not `null`, the transaction will be indexed. Each event is +indexed using a composite key in the form of `{eventType}.{eventAttribute}={eventValue}`, +e.g. `transfer.sender=bob`. + +## Querying Transactions Events + +You can query for a paginated set of transaction by their events by calling the +`/tx_search` RPC endpoint: + +```bash +curl "localhost:26657/tx_search?query=\"message.sender='cosmos1...'\"&prove=true" +``` + +Check out [API docs](https://docs.cometbft.com/v0.38/rpc/#/Info/tx_search) +for more information on query syntax and other options. + +## Subscribing to Transactions + +Clients can subscribe to transactions with the given tags via WebSocket by providing +a query to `/subscribe` RPC endpoint. + +```json +{ + "jsonrpc": "2.0", + "method": "subscribe", + "id": "0", + "params": { + "query": "message.sender='cosmos1...'" + } +} +``` + +Check out [API docs](https://docs.cometbft.com/v0.38/rpc/#subscribe) for more information +on query syntax and other options. + +## Querying Block Events + +You can query for a paginated set of blocks by their events by calling the +`/block_search` RPC endpoint: + +```bash +curl "localhost:26657/block_search?query=\"block.height > 10\"" +``` + + +Storing the event sequence was introduced in CometBFT 0.34.26. Before that, up +until Tendermint Core 0.34.26, the event sequence was not stored in the kvstore +and events were stored only by height. That means that queries returned blocks +and transactions whose event attributes match within the height but can match +across different events on that height. + +This behavior was fixed with CometBFT 0.34.26+. However, if the data was +indexed with earlier versions of Tendermint Core and not re-indexed, that data +will be queried as if all the attributes within a height occurred within the +same event. + +## Event attribute value types + +Users can use anything as an event value. However, if the event attribute value +is a number, the following needs to be taken into account: + +- Negative numbers will not be properly retrieved when querying the indexer. +- Event values are converted to big floats (from the `big/math` package). The + precision of the floating point number is set to the bit length of the + integer it is supposed to represent, so that there is no loss of information + due to insufficient precision. This was not present before CometBFT v0.38.x + and all float values were ignored. +- As of CometBFT v0.38.x, queries can contain floating point numbers as well. +- Note that comparing to floats can be imprecise with a high number of decimals. + +## Event type and attribute key format + +An event type/attribute key is a string that can contain any Unicode letter or +digit, as well as the following characters: `.` (dot), `-` (dash), `_` +(underscore). The event type/attribute key must not start with `-` (dash) or +`.` (dot). + +``` +^[\w]+[\.-\w]?$ +``` + +[abci-events]: ../spec/abci/abci++_basic_concepts.md#events diff --git a/docs/architecture/README.md b/docs/architecture/README.md new file mode 100644 index 0000000..37446d5 --- /dev/null +++ b/docs/architecture/README.md @@ -0,0 +1,54 @@ +--- +order: 1 +parent: + order: false +--- + +# Architecture Decision Records (ADR) + +This is a location to record all high-level architecture decisions in the +CometBFT project. + +You can read more about the ADR concept in this +[blog post](https://product.reverb.com/documenting-architecture-decisions-the-reverb-way-a3563bb24bd0#.78xhdix6t). + +An ADR should, with a strong focus on the impact on _users_ of the system, +provide: + +- Context on the relevant goals and the current state +- Proposed changes to achieve the goals +- Summary of pros and cons +- References +- Changelog + +To create a new ADR, please use the [ADR template](./adr-template.md). + +Note the distinction between an ADR and a spec. An ADR provides the context, +intuition, reasoning, and justification for a change in architecture, or for the +architecture of something new. A spec is more compressed and streamlined +summary of everything as it stands today. + +If recorded decisions turned out to be lacking, convene a discussion, record the +new decisions here, and then modify the code to match. + +Note the context/background should be written in the present tense. + +## Table of Contents + +The following ADRs are exclusively relevant to CometBFT. For historical ADRs +relevant to Tendermint Core as well, please see [this list](./tendermint-core/). +To distinguish CometBFT ADRs from historical ones from Tendermint Core, we start +numbering our ADRs from 100 onwards. + +### Proposed + +### Accepted + +- [ADR-111: `nop` Mempool](./adr-111-nop-mempool.md) + +### Implemented + +### Deprecated + +### Rejected + diff --git a/docs/architecture/adr-111-nop-mempool.md b/docs/architecture/adr-111-nop-mempool.md new file mode 100644 index 0000000..2063981 --- /dev/null +++ b/docs/architecture/adr-111-nop-mempool.md @@ -0,0 +1,324 @@ +# ADR 111: `nop` Mempool + +## Changelog + +- 2023-11-07: First version (@sergio-mena) +- 2023-11-15: Addressed PR comments (@sergio-mena) +- 2023-11-17: Renamed `nil` to `nop` (@melekes) +- 2023-11-20: Mentioned that the app could reuse p2p network in the future (@melekes) +- 2023-11-22: Adapt ADR to implementation (@melekes) + +## Status + +Accepted + +[Tracking issue](https://github.com/cometbft/cometbft/issues/1666) + +## Context + +### Summary + +The current mempool built into CometBFT implements a robust yet somewhat inefficient transaction gossip mechanism. +While the CometBFT team is currently working on more efficient general-purpose transaction gossiping mechanisms, +some users have expressed their desire to manage both the mempool and the transaction dissemination mechanism +outside CometBFT (typically at the application level). + +This ADR proposes a fairly simple way for CometBFT to fulfill this use case without moving away from our current architecture. + +### In the Beginning... + +It is well understood that a dissemination mechanism +(sometimes using _Reliable Broadcast_ [\[HT94\]][HT94] but not necessarily), +is needed in a distributed system implementing State-Machine Replication (SMR). +This is also the case in blockchains. +Early designs such as Bitcoin or Ethereum include an _internal_ component, +responsible for dissemination, called mempool. +Tendermint Core chose to follow the same design given the success +of those early blockchains and, since inception, Tendermint Core and later CometBFT have featured a mempool as an internal piece of its architecture. + + +However, the design of ABCI clearly dividing the application logic (i.e., the appchain) +and the consensus logic that provides SMR semantics to the app is a unique innovation in Cosmos +that sets it apart from Bitcoin, Ethereum, and many others. +This clear separation of concerns entailed many consequences, mostly positive: +it allows CometBFT to be used underneath (currently) tens of different appchains in production +in the Cosmos ecosystem and elsewhere. +But there are other implications for having an internal mempool +in CometBFT: the interaction between the mempool, the application, and the network +becomes more indirect, and thus more complex and hard to understand and operate. + +### ABCI++ Improvements and Remaining Shortcomings + +Before the release of ABCI++, `CheckTx` was the main mechanism the app had at its disposal to influence +what transactions made it to the mempool, and very indirectly what transactions got ultimately proposed in a block. +Since ABCI 1.0 (the first part of ABCI++, shipped in `v0.37.x`), the application has +a more direct say in what is proposed through `PrepareProposal` and `ProcessProposal`. + +This has greatly improved the ability for appchains to influence the contents of the proposed block. +Further, ABCI++ has enabled many new use cases for appchains. However some issues remain with +the current model: + +* We are using the same P2P network for disseminating transactions and consensus-related messages. +* Many mempool parameters are configured on a per-node basis by node operators, + allowing the possibility of inconsistent mempool configuration across the network + with potentially serious scalability effects + (even causing unacceptable performance degradation in some extreme cases). +* The current mempool implementation uses a basic (robust but sub-optimal) flood algorithm + * the CometBFT team is working on improving it as one of our current priorities, + but any improvement we come up with must address the needs of a vast spectrum of applications, + as well as be heavily scaled-tested in various scenarios + (in an attempt to cover the applications' wide spectrum) + * a mempool designed specifically for one particular application + would reduce the search space as its designers can devise it with just their application's + needs in mind. +* The interaction with the application is still somewhat convoluted: + * the application has to decide what logic to implement in `CheckTx`, + what to do with the transaction list coming in `RequestPrepareProposal`, + whether it wants to maintain an app-side mempool (more on this below), and whether or not + to combine the transactions in the app-side mempool with those coming in `RequestPrepareProposal` + * all those combinations are hard to fully understand, as the semantics and guarantees are + often not clear + * when using exclusively an app-mempool (the approach taken in the Cosmos SDK `v0.47.x`) + for populating proposed blocks, with the aim of simplifying the app developers' life, + we still have a suboptimal model where we need to continue using CometBFT's mempool + in order to disseminate the transactions. So, we end up using twice as much memory, + as in-transit transactions need to be kept in both mempools. + +The approach presented in this ADR builds on the app-mempool design released in `v0.47.x` +of the Cosmos SDK, +and briefly discussed in the last bullet point above (see [SDK app-mempool][sdk-app-mempool] for further details of this model). + +In the app-mempool design in Cosmos SDK `v0.47.x` +an unconfirmed transaction must be both in CometBFT's mempool for dissemination and +in the app's mempool so the application can decide how to manage the mempool. +There is no doubt that this approach has numerous advantages. However, it also has some implications that need to be considered: + +* Having every transaction both in CometBFT and in the application is suboptimal in terms of memory. + Additionally, the app developer has to be careful + that the contents of both mempools do not diverge over time + (hence the crucial role `re-CheckTx` plays post-ABCI++). +* The main reason for a transaction needing to be in CometBFT's mempool is + because the design in Cosmos SDK `v0.47.x` does not consider an application + that has its own means of disseminating transactions. + It reuses the peer to peer network underneath CometBFT reactors. +* There is no point in having transactions in CometBFT's mempool if an application implements an ad-hoc design for disseminating transactions. + +This proposal targets this kind of applications: +those that have an ad-hoc mechanism for transaction dissemination that better meets the application requirements. + +The ABCI application could reuse the P2P network once this is exposed via ABCI. +But this will take some time as it needs to be implemented, and has a dependency +on bi-directional ABCI, which is also quite substantial. See +[1](https://github.com/cometbft/cometbft/discussions/1112) and +[2](https://github.com/cometbft/cometbft/discussions/494) discussions. + +We propose to introduce a `nop` (short for no operation) mempool which will effectively act as a stubbed object +internally: + +* it will reject any transaction being locally submitted or gossipped by a peer +* when a _reap_ (as it is currently called) is executed in the mempool, an empty answer will always be returned +* the application running on the proposer validator will add transactions it received + using the appchains's own mechanism via `PrepareProposal`. + +## Alternative Approaches + +These are the alternatives known to date: + +1. Keep the current model. Useful for basic apps, but clearly suboptimal for applications + with their own mechanism to disseminate transactions and particular performance requirements. +2. Provide more efficient general-purpose mempool implementations. + This is an ongoing effort (e.g., [CAT mempool][cat-mempool]), but will take some time, and R&D effort, to come up with + advanced mechanisms -- likely highly configurable and thus complex -- which then will have to be thoroughly tested. +3. A similar approach to this one ([ADR110][adr-110]) whereby the application-specific + mechanism directly interacts with CometBFT via a newly defined gRPC interface. +4. Partially adopting this ADR. There are several possibilities: + * Use the current mempool, disable transaction broadcast in `config.toml`, and accept transactions from users via `BroadcastTX*` RPC methods. + Positive: avoids transaction gossiping; app can reuse the mempool existing in ComeBFT. + Negative: requires clients to know the validators' RPC endpoints (potential security issues). + * Transaction broadcast is disabled in `config.toml`, and have the application always reject transactions in `CheckTx`. + Positive: effectively disables the mempool; does not require modifications to Comet (may be used in `v0.37.x` and `v0.38.x`). + Negative: requires apps to disseminate txs themselves; the setup for this is less straightforward than this ADR's proposal. + +## Decision + +TBD + +## Detailed Design + +What this ADR proposes can already be achieved with an unmodified CometBFT since +`v0.37.x`, albeit with a complex, poor UX (see the last alternative in section +[Alternative Approaches](#alternative-approaches)). The core of this proposal +is to make some internal changes so it is clear an simple for app developers, +thus improving the UX. + +#### `nop` Mempool + +We propose a new mempool implementation, called `nop` Mempool, that effectively disables all mempool functionality +within CometBFT. +The `nop` Mempool implements the `Mempool` interface in a very simple manner: + +* `CheckTx(tx types.Tx) (*abcicli.ReqRes, error)`: returns `nil, ErrNotAllowed` +* `RemoveTxByKey(txKey types.TxKey) error`: returns `ErrNotAllowed` +* `ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs`: returns `nil` +* `ReapMaxTxs(max int) types.Txs`: returns `nil` +* `Lock()`: does nothing +* `Unlock()`: does nothing +* `Update(...) error`: returns `nil` +* `FlushAppConn() error`: returns `nil` +* `Flush()`: does nothing +* `TxsAvailable() <-chan struct{}`: returns `nil` +* `EnableTxsAvailable()`: does nothing +* `SetTxRemovedCallback(cb func(types.TxKey))`: does nothing +* `Size() int` returns 0 +* `SizeBytes() int64` returns 0 + +Upon startup, the `nop` mempool reactor will advertise no channels to the peer-to-peer layer. + +### Configuration + +We propose the following changes to the `config.toml` file: + +```toml +[mempool] +# The type of mempool for this CometBFT node to use. +# +# Valid types of mempools supported by CometBFT: +# - "flood" : clist mempool with flooding gossip protocol (default) +# - "nop" : nop-mempool (app has implemented an alternative tx dissemination mechanism) +type = "nop" +``` + +The config validation logic will be modified to add a new rule that rejects a configuration file +if all of these conditions are met: + +* the mempool is set to `nop` +* `create_empty_blocks`, in `consensus` section, is set to `false`. + +The reason for this extra validity rule is that the `nop`-mempool, as proposed here, +does not support the "do not create empty blocks" functionality. +Here are some considerations on this: + +* The "do not create empty blocks" functionality + * entangles the consensus and mempool reactors + * is hardly used in production by real appchains (to the best of CometBFT team's knowledge) + * its current implementation for the built-in mempool has undesired side-effects + * app hashes currently refer to the previous block, + * and thus it interferes with query provability. +* If needed in the future, this can be supported by extending ABCI, + but we will first need to see a real need for this before committing to changing ABCI + (which has other, higher-impact changes waiting to be prioritized). + +### RPC Calls + +There are no changes needed in the code dealing with RPC. Those RPC paths that call methods of the `Mempool` interface, +will simply be calling the new implementation. + +### Impacted Workflows + +* *Submitting a transaction*. Users are not to submit transactions via CometBFT's RPC. + `BroadcastTx*` RPC methods will fail with a reasonable error and the 501 status code. + The application running on a full node must offer an interface for users to submit new transactions. + It could also be a distinct node (or set of nodes) in the network. + These considerations are exclusively the application's concern in this approach. +* *Time to propose a block*. The consensus reactor will call `ReapMaxBytesMaxGas` which will return a `nil` slice. + `RequestPrepareProposal` will thus contain no transactions. +* *Consensus waiting for transactions to become available*. `TxsAvailable()` returns `nil`. + `cs.handleTxsAvailable()` won't ever be executed. + At any rate, a configuration with the `nop` mempool and `create_empty_blocks` set to `false` + will be rejected in the first place. +* *A new block is decided*. + * When `Update` is called, nothing is done (no decided transaction is removed). + * Locking and unlocking the mempool has no effect. +* *ABCI mempool's connection* + CometBFT will still open a "mempool" connection, even though it won't be used. + This is to avoid doing lots of breaking changes. + +### Impact on Current Release Plans + +The changes needed for this approach, are fairly simple, and the logic is clear. +This might allow us to even deliver it as part of CometBFT `v1` (our next release) +even without a noticeable impact on `v1`'s delivery schedule. + +The CometBFT team (learning from past dramatic events) usually takes a conservative approach +for backporting changes to release branches that have already undergone a full QA cycle +(and thus are in code-freeze mode). +For this reason, although the limited impact of these changes would limit the risks +of backporting to `v0.38.x` and `v0.37.x`, a careful risk/benefit evaluation will +have to be carried out. + +Backporting to `v0.34.x` does not make sense as this version predates the release of `ABCI 1.0`, +so using the `nop` mempool renders CometBFT's operation useless. + +### Config parameter _vs._ application-enforced parameter + +In the current proposal, the parameter selecting the mempool is in `config.toml`. +However, it is not a clear-cut decision. These are the alternatives we see: + +* *Mempool selected in `config.toml` (our current design)*. + This is the way the mempool has always been selected in Tendermint Core and CometBFT, + in those versions where there were more than one mempool to choose from. + As the configuration is in `config.toml`, it is up to the node operators to configure their + nodes consistently, via social consensus. However this cannot be guaranteed. + A network with an inconsistent choice of mempool at different nodes might + result in undesirable side effects, such as peers disconnecting from nodes + that sent them messages via the mempool channel. +* *Mempool selected as a network-wide parameter*. + A way to prevent any inconsistency when selecting the mempool is to move the configuration out of `config.toml` + and have it as a network-wide application-enforced parameter, implemented in the same way as Consensus Params. + The Cosmos community may not be ready for such a rigid, radical change, + even if it eliminates the risk of operators shooting themselves in the foot. + Hence we went currently favor the previous alternative. +* *Mempool selected as a network-wide parameter, but allowing override*. + A third option, half way between the previous two, is to have the mempool selection + as a network-wide parameter, but with a special value called _local-config_ that still + allows an appchain to decide to leave it up to operators to configure it in `config.toml`. + +Ultimately, the "config parameter _vs._ application-enforced parameter" discussion +is a more general one that is applicable to other parameters not related to mempool selection. +In that sense, it is out of the scope of this ADR. + +## Consequences + +### Positive + +- Applications can now find mempool mechanisms that fit better their particular needs: + - Ad-hoc ways to add, remove, merge, reorder, modify, prioritize transactions according + to application needs. + - A way to disseminate transactions (gossip-based or other) to get the submitted transactions + to proposers. The application developers can devise simpler, efficient mechanisms tailored + to their application. + - Back-pressure mechanisms to prevent malicious users from abusing the transaction + dissemination mechanism. +- In this approach, CometBFT's peer-to-peer layer is relieved from managing transaction gossip, freeing up its resources for other reactors such as consensus, evidence, block-sync, or state-sync. +- There is no risk for the operators of a network to provide inconsistent configurations + for some mempool-related parameters. Some of those misconfigurations are known to have caused + serious performance issues in CometBFT's peer to peer network. + Unless, of course, the application-defined transaction dissemination mechanism ends up + allowing similar configuration inconsistencies. +- The interaction between the application and CometBFT at `PrepareProposal` time + is simplified. No transactions are ever provided by CometBFT, + and no transactions can ever be left in the mempool when CometBFT calls `PrepareProposal`: + the application trivially has all the information. +- UX is improved compared to how this can be done prior to this ADR. + +### Negative + +- With the `nop` mempool, it is up to the application to provide users with a way + to submit transactions and deliver those transactions to validators. + This is a considerable endeavor, and more basic appchains may consider it is not worth the hassle. +- There is a risk of wasting resources by those nodes that have a misconfigured + mempool (bandwidth, CPU, memory, etc). If there are TXs submitted (incorrectly) + via CometBFT's RPC, but those TXs are never submitted (correctly via an + app-specific interface) to the App. As those TXs risk being there until the node + is stopped. Moreover, those TXs will be replied & proposed every single block. + App developers will need to keep this in mind and panic on `CheckTx` or + `PrepareProposal` with non-empty list of transactions. +- Optimizing block proposals by only including transaction IDs (e.g. TX hashes) is more difficult. + The ABCI app could do it by submitting TX hashes (rather than TXs themselves) + in `PrepareProposal`, and then having a mechanism for pulling TXs from the + network upon `FinalizeBlock`. + +[sdk-app-mempool]: https://docs.cosmos.network/v0.47/build/building-apps/app-mempool +[adr-110]: https://github.com/cometbft/cometbft/pull/1565 +[HT94]: https://dl.acm.org/doi/book/10.5555/866693 +[cat-mempool]: https://github.com/cometbft/cometbft/pull/1472 \ No newline at end of file diff --git a/docs/architecture/adr-template.md b/docs/architecture/adr-template.md new file mode 100644 index 0000000..469b9d5 --- /dev/null +++ b/docs/architecture/adr-template.md @@ -0,0 +1,101 @@ +# ADR {ADR-NUMBER}: {TITLE} + +## Changelog + +- {date}: {changelog} + +## Status + +> An architecture decision is considered "proposed" when a PR containing the ADR +> is submitted. When merged, an ADR must have a status associated with it, which +> must be one of: "Accepted", "Rejected", "Deprecated" or "Superseded". +> +> An accepted ADR's implementation status must be tracked via a tracking issue, +> milestone or project board (only one of these is necessary). For example: +> +> Accepted +> +> [Tracking issue](https://github.com/cometbft/cometbft/issues/123) +> [Milestone](https://github.com/cometbft/cometbft/milestones/123) +> [Project board](https://github.com/orgs/cometbft/projects/123) +> +> Rejected ADRs are captured as a record of recommendations that we specifically +> do not (and possibly never) want to implement. The ADR itself must, for +> posterity, include reasoning as to why it was rejected. +> +> If an ADR is deprecated, simply write "Deprecated" in this section. If an ADR +> is superseded by one or more other ADRs, provide local a reference to those +> ADRs, e.g.: +> +> Superseded by [ADR 123](./adr-123.md) + +Accepted | Rejected | Deprecated | Superseded by + +## Context + +> This section contains all the context one needs to understand the current state, +> and why there is a problem. It should be as succinct as possible and introduce +> the high level idea behind the solution. + +## Alternative Approaches + +> This section contains information around alternative options that are considered +> before making a decision. It should contain a explanation on why the alternative +> approach(es) were not chosen. + +## Decision + +> This section records the decision that was made. +> It is best to record as much info as possible from the discussion that happened. +> This aids in not having to go back to the Pull Request to get the needed information. + +## Detailed Design + +> This section does not need to be filled in at the start of the ADR, but must +> be completed prior to the merging of the implementation. +> +> Here are some common questions that get answered as part of the detailed design: +> +> - What are the user requirements? +> +> - What systems will be affected? +> +> - What new data structures are needed, what data structures will be changed? +> +> - What new APIs will be needed, what APIs will be changed? +> +> - What are the efficiency considerations (time/space)? +> +> - What are the expected access patterns (load/throughput)? +> +> - Are there any logging, monitoring or observability needs? +> +> - Are there any security considerations? +> +> - Are there any privacy considerations? +> +> - How will the changes be tested? +> +> - If the change is large, how will the changes be broken up for ease of review? +> +> - Will these changes require a breaking (major) release? +> +> - Does this change require coordination with the SDK or other? + +## Consequences + +> This section describes the consequences, after applying the decision. All +> consequences should be summarized here, not just the "positive" ones. + +### Positive + +### Negative + +### Neutral + +## References + +> Are there any relevant PR comments, issues that led up to this, or articles +> referenced for why we made the given design choice? If so link them here! + +- {reference link} diff --git a/docs/architecture/tendermint-core/README.md b/docs/architecture/tendermint-core/README.md new file mode 100644 index 0000000..6168b04 --- /dev/null +++ b/docs/architecture/tendermint-core/README.md @@ -0,0 +1,105 @@ +--- +order: 1 +parent: + order: false +--- + +# Tendermint Core Architecture Decision Records (ADR) + +Here we record all high-level architecture decisions in the Tendermint Core +project. All implemented ADRs in this list naturally affect CometBFT, since +CometBFT is a fork of Tendermint Core as of December 2022. + +This list is currently frozen and kept for reference purposes. To add new ADRs, +please do so for CometBFT [here](../). + +## Table of Contents + +### Implemented + +- [ADR-001: Logging](./adr-001-logging.md) +- [ADR-002: Event-Subscription](./adr-002-event-subscription.md) +- [ADR-003: ABCI-APP-RPC](./adr-003-abci-app-rpc.md) +- [ADR-004: Historical-Validators](./adr-004-historical-validators.md) +- [ADR-005: Consensus-Params](./adr-005-consensus-params.md) +- [ADR-008: Priv-Validator](./adr-008-priv-validator.md) +- [ADR-009: ABCI-Design](./adr-009-ABCI-design.md) +- [ADR-010: Crypto-Changes](./adr-010-crypto-changes.md) +- [ADR-011: Monitoring](./adr-011-monitoring.md) +- [ADR-014: Secp-Malleability](./adr-014-secp-malleability.md) +- [ADR-015: Crypto-Encoding](./adr-015-crypto-encoding.md) +- [ADR-016: Protocol-Versions](./adr-016-protocol-versions.md) +- [ADR-017: Chain-Versions](./adr-017-chain-versions.md) +- [ADR-018: ABCI-Validators](./adr-018-ABCI-Validators.md) +- [ADR-019: Multisigs](./adr-019-multisigs.md) +- [ADR-020: Block-Size](./adr-020-block-size.md) +- [ADR-021: ABCI-Events](./adr-021-abci-events.md) +- [ADR-025: Commit](./adr-025-commit.md) +- [ADR-026: General-Merkle-Proof](./adr-026-general-merkle-proof.md) +- [ADR-033: Pubsub](./adr-033-pubsub.md) +- [ADR-034: Priv-Validator-File-Structure](./adr-034-priv-validator-file-structure.md) +- [ADR-043: Blockchain-RiRi-Org](./adr-043-blockchain-riri-org.md) +- [ADR-044: Lite-Client-With-Weak-Subjectivity](./adr-044-lite-client-with-weak-subjectivity.md) +- [ADR-046: Light-Client-Implementation](./adr-046-light-client-implementation.md) +- [ADR-047: Handling-Evidence-From-Light-Client](./adr-047-handling-evidence-from-light-client.md) +- [ADR-051: Double-Signing-Risk-Reduction](./adr-051-double-signing-risk-reduction.md) +- [ADR-052: Tendermint-Mode](./adr-052-tendermint-mode.md) +- [ADR-053: State-Sync-Prototype](./adr-053-state-sync-prototype.md) +- [ADR-054: Crypto-Encoding-2](./adr-054-crypto-encoding-2.md) +- [ADR-055: Protobuf-Design](./adr-055-protobuf-design.md) +- [ADR-056: Light-Client-Amnesia-Attacks](./adr-056-light-client-amnesia-attacks.md) +- [ADR-059: Evidence-Composition-and-Lifecycle](./adr-059-evidence-composition-and-lifecycle.md) +- [ADR-065: Custom Event Indexing](./adr-065-custom-event-indexing.md) +- [ADR-066: E2E-Testing](./adr-066-e2e-testing.md) +- [ADR-072: Restore Requests for Comments](./adr-072-request-for-comments.md) +- [ADR-076: Combine Spec and Tendermint Repositories](./adr-076-combine-spec-repo.md) +- [ADR-077: Configurable Block Retention](./adr-077-block-retention.md) +- [ADR-078: Non-zero Genesis](./adr-078-nonzero-genesis.md) + +### Accepted + +- [ADR-006: Trust-Metric](./adr-006-trust-metric.md) +- [ADR-024: Sign-Bytes](./adr-024-sign-bytes.md) +- [ADR-039: Peer-Behaviour](./adr-039-peer-behaviour.md) +- [ADR-063: Privval-gRPC](./adr-063-privval-grpc.md) +- [ADR-067: Mempool Refactor](./adr-067-mempool-refactor.md) +- [ADR-071: Proposer-Based Timestamps](./adr-071-proposer-based-timestamps.md) +- [ADR-075: RPC Event Subscription Interface](./adr-075-rpc-subscription.md) +- [ADR-079: Ed25519 Verification](./adr-079-ed25519-verification.md) +- [ADR-081: Protocol Buffers Management](./adr-081-protobuf-mgmt.md) + +### Deprecated + +- [ADR-035: Documentation](./adr-035-documentation.md) + +### Rejected + +- [ADR-023: ABCI-Propose-tx](./adr-023-ABCI-propose-tx.md) +- [ADR-029: Check-Tx-Consensus](./adr-029-check-tx-consensus.md) +- [ADR-058: Event-Hashing](./adr-058-event-hashing.md) + +### Proposed + +- [ADR-007: Trust-Metric-Usage](./adr-007-trust-metric-usage.md) +- [ADR-012: Peer-Transport](./adr-012-peer-transport.md) +- [ADR-013: Symmetric-Crypto](./adr-013-symmetric-crypto.md) +- [ADR-022: ABCI-Errors](./adr-022-abci-errors.md) +- [ADR-030: Consensus-Refactor](./adr-030-consensus-refactor.md) +- [ADR-036: Empty Blocks via ABCI](./adr-036-empty-blocks-abci.md) +- [ADR-037: Deliver-Block](./adr-037-deliver-block.md) +- [ADR-038: Non-Zero-Start-Height](./adr-038-non-zero-start-height.md) +- [ADR-040: Blockchain Reactor Refactor](./adr-040-blockchain-reactor-refactor.md) +- [ADR-041: Proposer-Selection-via-ABCI](./adr-041-proposer-selection-via-abci.md) +- [ADR-042: State Sync Design](./adr-042-state-sync.md) +- [ADR-045: ABCI-Evidence](./adr-045-abci-evidence.md) +- [ADR-050: Improved Trusted Peering](./adr-050-improved-trusted-peering.md) +- [ADR-057: RPC](./adr-057-RPC.md) +- [ADR-060: Go-API-Stability](./adr-060-go-api-stability.md) +- [ADR-061: P2P-Refactor-Scope](./adr-061-p2p-refactor-scope.md) +- [ADR-062: P2P-Architecture](./adr-062-p2p-architecture.md) +- [ADR-064: Batch Verification](./adr-064-batch-verification.md) +- [ADR-068: Reverse-Sync](./adr-068-reverse-sync.md) +- [ADR-069: Node Initialization](./adr-069-flexible-node-initialization.md) +- [ADR-073: Adopt LibP2P](./adr-073-libp2p.md) +- [ADR-074: Migrate Timeout Parameters to Consensus Parameters](./adr-074-timeout-params.md) +- [ADR-080: Reverse Sync](./adr-080-reverse-sync.md) diff --git a/docs/architecture/tendermint-core/adr-001-logging.md b/docs/architecture/tendermint-core/adr-001-logging.md new file mode 100644 index 0000000..71b142e --- /dev/null +++ b/docs/architecture/tendermint-core/adr-001-logging.md @@ -0,0 +1,216 @@ +# ADR 1: Logging + +## Context + +Current logging system in Tendermint is very static and not flexible enough. + +Issues: [358](https://github.com/tendermint/tendermint/issues/358), [375](https://github.com/tendermint/tendermint/issues/375). + +What we want from the new system: + +- per package dynamic log levels +- dynamic logger setting (logger tied to the processing struct) +- conventions +- be more visually appealing + +"dynamic" here means the ability to set smth in runtime. + +## Decision + +### 1) An interface + +First, we will need an interface for all of our libraries (`tmlibs`, Tendermint, etc.). My personal preference is go-kit `Logger` interface (see Appendix A.), but that is too much a bigger change. Plus we will still need levels. + +```go +# log.go +type Logger interface { + Debug(msg string, keyvals ...interface{}) error + Info(msg string, keyvals ...interface{}) error + Error(msg string, keyvals ...interface{}) error + + With(keyvals ...interface{}) Logger +} +``` + +On a side note: difference between `Info` and `Notice` is subtle. We probably +could do without `Notice`. Don't think we need `Panic` or `Fatal` as a part of +the interface. These funcs could be implemented as helpers. In fact, we already +have some in `tmlibs/common`. + +- `Debug` - extended output for devs +- `Info` - all that is useful for a user +- `Error` - errors + +`Notice` should become `Info`, `Warn` either `Error` or `Debug` depending on the message, `Crit` -> `Error`. + +This interface should go into `tmlibs/log`. All libraries which are part of the core (tendermint/tendermint) should obey it. + +### 2) Logger with our current formatting + +On top of this interface, we will need to implement a stdout logger, which will be used when Tendermint is configured to output logs to STDOUT. + +Many people say that they like the current output, so let's stick with it. + +``` +NOTE[2017-04-25|14:45:08] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 +``` + +Couple of minor changes: + +``` +I[2017-04-25|14:45:08.322] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 +``` + +Notice the level is encoded using only one char plus milliseconds. + +Note: there are many other formats out there like [logfmt](https://brandur.org/logfmt). + +This logger could be implemented using any logger - [logrus](https://github.com/sirupsen/logrus), [go-kit/log](https://github.com/go-kit/kit/tree/master/log), [zap](https://github.com/uber-go/zap), log15 so far as it + +a) supports coloring output
+b) is moderately fast (buffering)
+c) conforms to the new interface or adapter could be written for it
+d) is somewhat configurable
+ +go-kit is my favorite so far. Check out how easy it is to color errors in red https://github.com/go-kit/kit/blob/master/log/term/example_test.go#L12. Although, coloring could only be applied to the whole string :( + +``` +go-kit +: flexible, modular +go-kit “-”: logfmt format https://brandur.org/logfmt + +logrus +: popular, feature rich (hooks), API and output is more like what we want +logrus -: not so flexible +``` + +```go +# tm_logger.go +// NewTmLogger returns a logger that encodes keyvals to the Writer in +// tm format. +func NewTmLogger(w io.Writer) Logger { + return &tmLogger{kitlog.NewLogfmtLogger(w)} +} + +func (l tmLogger) SetLevel(level string() { + switch (level) { + case "debug": + l.sourceLogger = level.NewFilter(l.sourceLogger, level.AllowDebug()) + } +} + +func (l tmLogger) Info(msg string, keyvals ...interface{}) error { + l.sourceLogger.Log("msg", msg, keyvals...) +} + +# log.go +func With(logger Logger, keyvals ...interface{}) Logger { + kitlog.With(logger.sourceLogger, keyvals...) +} +``` + +Usage: + +```go +logger := log.NewTmLogger(os.Stdout) +logger.SetLevel(config.GetString("log_level")) +node.SetLogger(log.With(logger, "node", Name)) +``` + +**Other log formatters** + +In the future, we may want other formatters like JSONFormatter. + +``` +{ "level": "notice", "time": "2017-04-25 14:45:08.562471297 -0400 EDT", "module": "consensus", "msg": "ABCI Replay Blocks", "appHeight": 0, "storeHeight": 0, "stateHeight": 0 } +``` + +### 3) Dynamic logger setting + +https://dave.cheney.net/2017/01/23/the-package-level-logger-anti-pattern + +This is the hardest part and where the most work will be done. logger should be tied to the processing struct, or the context if it adds some fields to the logger. + +```go +type BaseService struct { + log log15.Logger + name string + started uint32 // atomic + stopped uint32 // atomic +... +} +``` + +BaseService already contains `log` field, so most of the structs embedding it should be fine. We should rename it to `logger`. + +The only thing missing is the ability to set logger: + +``` +func (bs *BaseService) SetLogger(l log.Logger) { + bs.logger = l +} +``` + +### 4) Conventions + +Important keyvals should go first. Example: + +``` +correct +I[2017-04-25|14:45:08.322] ABCI Replay Blocks module=consensus instance=1 appHeight=0 storeHeight=0 stateHeight=0 +``` + +not + +``` +wrong +I[2017-04-25|14:45:08.322] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 instance=1 +``` + +for that in most cases you'll need to add `instance` field to a logger upon creating, not when u log a particular message: + +```go +colorFn := func(keyvals ...interface{}) term.FgBgColor { + for i := 1; i < len(keyvals); i += 2 { + if keyvals[i] == "instance" && keyvals[i+1] == "1" { + return term.FgBgColor{Fg: term.Blue} + } else if keyvals[i] == "instance" && keyvals[i+1] == "1" { + return term.FgBgColor{Fg: term.Red} + } + } + return term.FgBgColor{} + } +logger := term.NewLogger(os.Stdout, log.NewTmLogger, colorFn) + +c1 := NewConsensusReactor(...) +c1.SetLogger(log.With(logger, "instance", 1)) + +c2 := NewConsensusReactor(...) +c2.SetLogger(log.With(logger, "instance", 2)) +``` + +## Status + +Implemented + +## Consequences + +### Positive + +Dynamic logger, which could be turned off for some modules at runtime. Public interface for other projects using Tendermint libraries. + +### Negative + +We may loose the ability to color keys in keyvalue pairs. go-kit allow you to easily change foreground / background colors of the whole string, but not its parts. + +### Neutral + +## Appendix A. + +I really like a minimalistic approach go-kit took with his logger https://github.com/go-kit/kit/tree/master/log: + +``` +type Logger interface { + Log(keyvals ...interface{}) error +} +``` + +See [The Hunt for a Logger Interface](https://web.archive.org/web/20210902161539/https://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide#1). The advantage is greater composability (check out how go-kit defines colored logging or log-leveled logging on top of this interface https://github.com/go-kit/kit/tree/master/log). diff --git a/docs/architecture/tendermint-core/adr-002-event-subscription.md b/docs/architecture/tendermint-core/adr-002-event-subscription.md new file mode 100644 index 0000000..ba46a5b --- /dev/null +++ b/docs/architecture/tendermint-core/adr-002-event-subscription.md @@ -0,0 +1,88 @@ +# ADR 2: Event Subscription + +## Context + +In the light client (or any other client), the user may want to **subscribe to +a subset of transactions** (rather than all of them) using `/subscribe?event=X`. For +example, I want to subscribe for all transactions associated with a particular +account. Same for fetching. The user may want to **fetch transactions based on +some filter** (rather than fetching all the blocks). For example, I want to get +all transactions for a particular account in the last two weeks (`tx's block time >= '2017-06-05'`). + +Now you can't even subscribe to "all txs" in Tendermint. + +The goal is a simple and easy to use API for doing that. + +![Tx Send Flow Diagram](img/tags1.png) + +## Decision + +ABCI app return tags with a `DeliverTx` response inside the `data` field (_for +now, later we may create a separate field_). Tags is a list of key-value pairs, +protobuf encoded. + +Example data: + +```json +{ + "abci.account.name": "Igor", + "abci.account.address": "0xdeadbeef", + "tx.gas": 7 +} +``` + +### Subscribing for transactions events + +If the user wants to receive only a subset of transactions, ABCI-app must +return a list of tags with a `DeliverTx` response. These tags will be parsed and +matched with the current queries (subscribers). If the query matches the tags, +subscriber will get the transaction event. + +``` +/subscribe?query="tm.event = Tx AND tx.hash = AB0023433CF0334223212243BDD AND abci.account.invoice.number = 22" +``` + +A new package must be developed to replace the current `events` package. It +will allow clients to subscribe to a different types of events in the future: + +``` +/subscribe?query="abci.account.invoice.number = 22" +/subscribe?query="abci.account.invoice.owner CONTAINS Igor" +``` + +### Fetching transactions + +This is a bit tricky because a) we want to support a number of indexers, all of +which have a different API b) we don't know whenever tags will be sufficient +for the most apps (I guess we'll see). + +``` +/txs/search?query="tx.hash = AB0023433CF0334223212243BDD AND abci.account.owner CONTAINS Igor" +/txs/search?query="abci.account.owner = Igor" +``` + +For historic queries we will need a indexing storage (Postgres, SQLite, ...). + +### Issues + +- https://github.com/tendermint/tendermint/issues/376 +- https://github.com/tendermint/tendermint/issues/287 +- https://github.com/tendermint/tendermint/issues/525 (related) + +## Status + +Implemented + +## Consequences + +### Positive + +- same format for event notifications and search APIs +- powerful enough query + +### Negative + +- performance of the `match` function (where we have too many queries / subscribers) +- there is an issue where there are too many txs in the DB + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-003-abci-app-rpc.md b/docs/architecture/tendermint-core/adr-003-abci-app-rpc.md new file mode 100644 index 0000000..d8ff337 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-003-abci-app-rpc.md @@ -0,0 +1,34 @@ +# ADR 3: Must an ABCI-app have an RPC server? + +## Context + +ABCI-server could expose its own RPC-server and act as a proxy to Tendermint. + +The idea was for the Tendermint RPC to just be a transparent proxy to the app. +Clients need to talk to Tendermint for proofs, unless we burden all app devs +with exposing Tendermint proof stuff. Also seems less complex to lock down one +server than two, but granted it makes querying a bit more kludgy since it needs +to be passed as a `Query`. Also, **having a very standard rpc interface means +the light-client can work with all apps and handle proofs**. The only +app-specific logic is decoding the binary data to a more readable form (eg. +json). This is a huge advantage for code-reuse and standardization. + +## Decision + +We dont expose an RPC server on any of our ABCI-apps. + +## Status + +Implemented + +## Consequences + +### Positive + +- Unified interface for all apps + +### Negative + +- `Query` interface + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-004-historical-validators.md b/docs/architecture/tendermint-core/adr-004-historical-validators.md new file mode 100644 index 0000000..97b61b4 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-004-historical-validators.md @@ -0,0 +1,38 @@ +# ADR 004: Historical Validators + +## Context + +Right now, we can query the present validator set, but there is no history. +If you were offline for a long time, there is no way to reconstruct past validators. This is needed for the light client and we agreed needs enhancement of the API. + +## Decision + +For every block, store a new structure that contains either the latest validator set, +or the height of the last block for which the validator set changed. Note this is not +the height of the block which returned the validator set change itself, but the next block, +ie. the first block it comes into effect for. + +Storing the validators will be handled by the `state` package. + +At some point in the future, we may consider more efficient storage in the case where the validators +are updated frequently - for instance by only saving the diffs, rather than the whole set. + +An alternative approach suggested keeping the validator set, or diffs of it, in a merkle IAVL tree. +While it might afford cheaper proofs that a validator set has not changed, it would be more complex, +and likely less efficient. + +## Status + +Implemented + +## Consequences + +### Positive + +- Can query old validator sets, with proof. + +### Negative + +- Writes an extra structure to disk with every block. + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-005-consensus-params.md b/docs/architecture/tendermint-core/adr-005-consensus-params.md new file mode 100644 index 0000000..108a9e4 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-005-consensus-params.md @@ -0,0 +1,85 @@ +# ADR 005: Consensus Params + +## Context + +Consensus critical parameters controlling blockchain capacity have until now been hard coded, loaded from a local config, or neglected. +Since they may be need to be different in different networks, and potentially to evolve over time within +networks, we seek to initialize them in a genesis file, and expose them through the ABCI. + +While we have some specific parameters now, like maximum block and transaction size, we expect to have more in the future, +such as a period over which evidence is valid, or the frequency of checkpoints. + +## Decision + +### ConsensusParams + +No consensus critical parameters should ever be found in the `config.toml`. + +A new `ConsensusParams` is optionally included in the `genesis.json` file, +and loaded into the `State`. Any items not included are set to their default value. +A value of 0 is undefined (see ABCI, below). A value of -1 is used to indicate the parameter does not apply. +The parameters are used to determine the validity of a block (and tx) via the union of all relevant parameters. + +``` +type ConsensusParams struct { + BlockSize + TxSize + BlockGossip +} + +type BlockSize struct { + MaxBytes int + MaxTxs int + MaxGas int +} + +type TxSize struct { + MaxBytes int + MaxGas int +} + +type BlockGossip struct { + BlockPartSizeBytes int +} +``` + +The `ConsensusParams` can evolve over time by adding new structs that cover different aspects of the consensus rules. + +The `BlockPartSizeBytes` and the `BlockSize.MaxBytes` are enforced to be greater than 0. +The former because we need a part size, the latter so that we always have at least some sanity check over the size of blocks. + +### ABCI + +#### InitChain + +InitChain currently takes the initial validator set. It should be extended to also take parts of the ConsensusParams. +There is some case to be made for it to take the entire Genesis, except there may be things in the genesis, +like the BlockPartSize, that the app shouldn't really know about. + +#### EndBlock + +The EndBlock response includes a `ConsensusParams`, which includes BlockSize and TxSize, but not BlockGossip. +Other param struct can be added to `ConsensusParams` in the future. +The `0` value is used to denote no change. +Any other value will update that parameter in the `State.ConsensusParams`, to be applied for the next block. +Tendermint should have hard-coded upper limits as sanity checks. + +## Status + +Implemented + +## Consequences + +### Positive + +- Alternative capacity limits and consensus parameters can be specified without re-compiling the software. +- They can also change over time under the control of the application + +### Negative + +- More exposed parameters is more complexity +- Different rules at different heights in the blockchain complicates fast sync + +### Neutral + +- The TxSize, which checks validity, may be in conflict with the config's `max_block_size_tx`, which determines proposal sizes diff --git a/docs/architecture/tendermint-core/adr-006-trust-metric.md b/docs/architecture/tendermint-core/adr-006-trust-metric.md new file mode 100644 index 0000000..d49d566 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-006-trust-metric.md @@ -0,0 +1,229 @@ +# ADR 006: Trust Metric Design + +## Context + +The proposed trust metric will allow Tendermint to maintain local trust rankings for peers it has directly interacted with, which can then be used to implement soft security controls. The calculations were obtained from the [TrustGuard](https://dl.acm.org/citation.cfm?id=1060808) project. + +### Background + +The Tendermint Core project developers would like to improve Tendermint security and reliability by keeping track of the level of trustworthiness peers have demonstrated within the peer-to-peer network. This way, undesirable outcomes from peers will not immediately result in them being dropped from the network (potentially causing drastic changes to take place). Instead, peers behavior can be monitored with appropriate metrics and be removed from the network once Tendermint Core is certain the peer is a threat. For example, when the PEXReactor makes a request for peers network addresses from a already known peer, and the returned network addresses are unreachable, this untrustworthy behavior should be tracked. Returning a few bad network addresses probably shouldn’t cause a peer to be dropped, while excessive amounts of this behavior does qualify the peer being dropped. + +Trust metrics can be circumvented by malicious nodes through the use of strategic oscillation techniques, which adapts the malicious node’s behavior pattern in order to maximize its goals. For instance, if the malicious node learns that the time interval of the Tendermint trust metric is _X_ hours, then it could wait _X_ hours in-between malicious activities. We could try to combat this issue by increasing the interval length, yet this will make the system less adaptive to recent events. + +Instead, having shorter intervals, but keeping a history of interval values, will give our metric the flexibility needed in order to keep the network stable, while also making it resilient against a strategic malicious node in the Tendermint peer-to-peer network. Also, the metric can access trust data over a rather long period of time while not greatly increasing its history size by aggregating older history values over a larger number of intervals, and at the same time, maintain great precision for the recent intervals. This approach is referred to as fading memories, and closely resembles the way human beings remember their experiences. The trade-off to using history data is that the interval values should be preserved in-between executions of the node. + +### References + +S. Mudhakar, L. Xiong, and L. Liu, “TrustGuard: Countering Vulnerabilities in Reputation Management for Decentralized Overlay Networks,” in _Proceedings of the 14th international conference on World Wide Web, pp. 422-431_, May 2005. + +## Decision + +The proposed trust metric will allow a developer to inform the trust metric store of all good and bad events relevant to a peer's behavior, and at any time, the metric can be queried for a peer's current trust ranking. + +The three subsections below will cover the process being considered for calculating the trust ranking, the concept of the trust metric store, and the interface for the trust metric. + +### Proposed Process + +The proposed trust metric will count good and bad events relevant to the object, and calculate the percent of counters that are good over an interval with a predefined duration. This is the procedure that will continue for the life of the trust metric. When the trust metric is queried for the current **trust value**, a resilient equation will be utilized to perform the calculation. + +The equation being proposed resembles a Proportional-Integral-Derivative (PID) controller used in control systems. The proportional component allows us to be sensitive to the value of the most recent interval, while the integral component allows us to incorporate trust values stored in the history data, and the derivative component allows us to give weight to sudden changes in the behavior of a peer. We compute the trust value of a peer in interval i based on its current trust ranking, its trust rating history prior to interval _i_ (over the past _maxH_ number of intervals) and its trust ranking fluctuation. We will break up the equation into the three components. + +```math +(1) Proportional Value = a * R[i] +``` + +where _R_[*i*] denotes the raw trust value at time interval _i_ (where _i_ == 0 being current time) and _a_ is the weight applied to the contribution of the current reports. The next component of our equation uses a weighted sum over the last _maxH_ intervals to calculate the history value for time _i_: + +`H[i] =` ![formula1](img/formula1.png "Weighted Sum Formula") + +The weights can be chosen either optimistically or pessimistically. An optimistic weight creates larger weights for newer history data values, while the the pessimistic weight creates larger weights for time intervals with lower scores. The default weights used during the calculation of the history value are optimistic and calculated as _Wk_ = 0.8^_k_, for time interval _k_. With the history value available, we can now finish calculating the integral value: + +```math +(2) Integral Value = b * H[i] +``` + +Where _H_[*i*] denotes the history value at time interval _i_ and _b_ is the weight applied to the contribution of past performance for the object being measured. The derivative component will be calculated as follows: + +```math +D[i] = R[i] – H[i] + +(3) Derivative Value = c(D[i]) * D[i] +``` + +Where the value of _c_ is selected based on the _D_[*i*] value relative to zero. The default selection process makes _c_ equal to 0 unless _D_[*i*] is a negative value, in which case c is equal to 1. The result is that the maximum penalty is applied when current behavior is lower than previously experienced behavior. If the current behavior is better than the previously experienced behavior, then the Derivative Value has no impact on the trust value. With the three components brought together, our trust value equation is calculated as follows: + +```math +TrustValue[i] = a * R[i] + b * H[i] + c(D[i]) * D[i] +``` + +As a performance optimization that will keep the amount of raw interval data being saved to a reasonable size of _m_, while allowing us to represent 2^_m_ - 1 history intervals, we can employ the fading memories technique that will trade space and time complexity for the precision of the history data values by summarizing larger quantities of less recent values. While our equation above attempts to access up to _maxH_ (which can be 2^_m_ - 1), we will map those requests down to _m_ values using equation 4 below: + +```math +(4) j = index, where index > 0 +``` + +Where _j_ is one of _(0, 1, 2, … , m – 1)_ indices used to access history interval data. Now we can access the raw intervals using the following calculations: + +```math +R[0] = raw data for current time interval +``` + +`R[j] =` ![formula2](img/formula2.png "Fading Memories Formula") + +### Trust Metric Store + +Similar to the P2P subsystem AddrBook, the trust metric store will maintain information relevant to Tendermint peers. Additionally, the trust metric store will ensure that trust metrics will only be active for peers that a node is currently and directly engaged with. + +Reactors will provide a peer key to the trust metric store in order to retrieve the associated trust metric. The trust metric can then record new positive and negative events experienced by the reactor, as well as provided the current trust score calculated by the metric. + +When the node is shutting down, the trust metric store will save history data for trust metrics associated with all known peers. This saved information allows experiences with a peer to be preserved across node executions, which can span a tracking windows of days or weeks. The trust history data is loaded automatically during OnStart. + +### Interface Detailed Design + +Each trust metric allows for the recording of positive/negative events, querying the current trust value/score, and the stopping/pausing of tracking over time intervals. This can be seen below: + +```go +// TrustMetric - keeps track of peer reliability +type TrustMetric struct { + // Private elements. +} + +// Pause tells the metric to pause recording data over time intervals. +// All method calls that indicate events will unpause the metric +func (tm *TrustMetric) Pause() {} + +// Stop tells the metric to stop recording data over time intervals +func (tm *TrustMetric) Stop() {} + +// BadEvents indicates that an undesirable event(s) took place +func (tm *TrustMetric) BadEvents(num int) {} + +// GoodEvents indicates that a desirable event(s) took place +func (tm *TrustMetric) GoodEvents(num int) {} + +// TrustValue gets the dependable trust value; always between 0 and 1 +func (tm *TrustMetric) TrustValue() float64 {} + +// TrustScore gets a score based on the trust value always between 0 and 100 +func (tm *TrustMetric) TrustScore() int {} + +// NewMetric returns a trust metric with the default configuration +func NewMetric() *TrustMetric {} + +//------------------------------------------------------------------------------------------------ +// For example + +tm := NewMetric() + +tm.BadEvents(1) +score := tm.TrustScore() + +tm.Stop() +``` + +Some of the trust metric parameters can be configured. The weight values should probably be left alone in more cases, yet the time durations for the tracking window and individual time interval should be considered. + +```go +// TrustMetricConfig - Configures the weight functions and time intervals for the metric +type TrustMetricConfig struct { + // Determines the percentage given to current behavior + ProportionalWeight float64 + + // Determines the percentage given to prior behavior + IntegralWeight float64 + + // The window of time that the trust metric will track events across. + // This can be set to cover many days without issue + TrackingWindow time.Duration + + // Each interval should be short for adapability. + // Less than 30 seconds is too sensitive, + // and greater than 5 minutes will make the metric numb + IntervalLength time.Duration +} + +// DefaultConfig returns a config with values that have been tested and produce desirable results +func DefaultConfig() TrustMetricConfig {} + +// NewMetricWithConfig returns a trust metric with a custom configuration +func NewMetricWithConfig(tmc TrustMetricConfig) *TrustMetric {} + +//------------------------------------------------------------------------------------------------ +// For example + +config := TrustMetricConfig{ + TrackingWindow: time.Minute * 60 * 24, // one day + IntervalLength: time.Minute * 2, +} + +tm := NewMetricWithConfig(config) + +tm.BadEvents(10) +tm.Pause() +tm.GoodEvents(1) // becomes active again +``` + +A trust metric store should be created with a DB that has persistent storage so it can save history data across node executions. All trust metrics instantiated by the store will be created with the provided TrustMetricConfig configuration. + +When you attempt to fetch the trust metric for a peer, and an entry does not exist in the trust metric store, a new metric is automatically created and the entry made within the store. + +In additional to the fetching method, GetPeerTrustMetric, the trust metric store provides a method to call when a peer has disconnected from the node. This is so the metric can be paused (history data will not be saved) for periods of time when the node is not having direct experiences with the peer. + +```go +// TrustMetricStore - Manages all trust metrics for peers +type TrustMetricStore struct { + cmn.BaseService + + // Private elements +} + +// OnStart implements Service +func (tms *TrustMetricStore) OnStart(context.Context) error { return nil } + +// OnStop implements Service +func (tms *TrustMetricStore) OnStop() {} + +// NewTrustMetricStore returns a store that saves data to the DB +// and uses the config when creating new trust metrics +func NewTrustMetricStore(db dbm.DB, tmc TrustMetricConfig) *TrustMetricStore {} + +// Size returns the number of entries in the trust metric store +func (tms *TrustMetricStore) Size() int {} + +// GetPeerTrustMetric returns a trust metric by peer key +func (tms *TrustMetricStore) GetPeerTrustMetric(key string) *TrustMetric {} + +// PeerDisconnected pauses the trust metric associated with the peer identified by the key +func (tms *TrustMetricStore) PeerDisconnected(key string) {} + +//------------------------------------------------------------------------------------------------ +// For example + +db := dbm.NewDB("trusthistory", "goleveldb", dirPathStr) +tms := NewTrustMetricStore(db, DefaultConfig()) + +tm := tms.GetPeerTrustMetric(key) +tm.BadEvents(1) + +tms.PeerDisconnected(key) +``` + +## Status + +Approved. + +## Consequences + +### Positive + +- The trust metric will allow Tendermint to make non-binary security and reliability decisions +- Will help Tendermint implement deterrents that provide soft security controls, yet avoids disruption on the network +- Will provide useful profiling information when analyzing performance over time related to peer interaction + +### Negative + +- Requires saving the trust metric history data across node executions + +### Neutral + +- Keep in mind that, good events need to be recorded just as bad events do using this implementation diff --git a/docs/architecture/tendermint-core/adr-007-trust-metric-usage.md b/docs/architecture/tendermint-core/adr-007-trust-metric-usage.md new file mode 100644 index 0000000..7ebc9cf --- /dev/null +++ b/docs/architecture/tendermint-core/adr-007-trust-metric-usage.md @@ -0,0 +1,106 @@ +# ADR 007: Trust Metric Usage Guide + +## Context + +Tendermint is required to monitor peer quality in order to inform its peer dialing and peer exchange strategies. + +When a node first connects to the network, it is important that it can quickly find good peers. +Thus, while a node has fewer connections, it should prioritize connecting to higher quality peers. +As the node becomes well connected to the rest of the network, it can dial lesser known or lesser +quality peers and help assess their quality. Similarly, when queried for peers, a node should make +sure they dont return low quality peers. + +Peer quality can be tracked using a trust metric that flags certain behaviors as good or bad. When enough +bad behavior accumulates, we can mark the peer as bad and disconnect. +For example, when the PEXReactor makes a request for peers network addresses from an already known peer, and the returned network addresses are unreachable, this undesirable behavior should be tracked. Returning a few bad network addresses probably shouldn’t cause a peer to be dropped, while excessive amounts of this behavior does qualify the peer for removal. The originally proposed approach and design document for the trust metric can be found in the [ADR 006](adr-006-trust-metric.md) document. + +The trust metric implementation allows a developer to obtain a peer's trust metric from a trust metric store, and track good and bad events relevant to a peer's behavior, and at any time, the peer's metric can be queried for a current trust value. The current trust value is calculated with a formula that utilizes current behavior, previous behavior, and change between the two. Current behavior is calculated as the percentage of good behavior within a time interval. The time interval is short; probably set between 30 seconds and 5 minutes. On the other hand, the historic data can estimate a peer's behavior over days worth of tracking. At the end of a time interval, the current behavior becomes part of the historic data, and a new time interval begins with the good and bad counters reset to zero. + +These are some important things to keep in mind regarding how the trust metrics handle time intervals and scoring: + +- Each new time interval begins with a perfect score +- Bad events quickly bring the score down and good events cause the score to slowly rise +- When the time interval is over, the percentage of good events becomes historic data. + +Some useful information about the inner workings of the trust metric: + +- When a trust metric is first instantiated, a timer (ticker) periodically fires in order to handle transitions between trust metric time intervals +- If a peer is disconnected from a node, the timer should be paused, since the node is no longer connected to that peer +- The ability to pause the metric is supported with the store **PeerDisconnected** method and the metric **Pause** method +- After a pause, if a good or bad event method is called on a metric, it automatically becomes unpaused and begins a new time interval. + +## Decision + +The trust metric capability is now available, yet, it still leaves the question of how should it be applied throughout Tendermint in order to properly track the quality of peers? + +### Proposed Process + +Peers are managed using an address book and a trust metric: + +- The address book keeps a record of peers and provides selection methods +- The trust metric tracks the quality of the peers + +#### Presence in Address Book + +Outbound peers are added to the address book before they are dialed, +and inbound peers are added once the peer connection is set up. +Peers are also added to the address book when they are received in response to +a pexRequestMessage. + +While a node has less than `needAddressThreshold`, it will periodically request more, +via pexRequestMessage, from randomly selected peers and from newly dialed outbound peers. + +When a new address is added to an address book that has more than `0.5*needAddressThreshold` addresses, +then with some low probability, a randomly chosen low quality peer is removed. + +#### Outbound Peers + +Peers attempt to maintain a minimum number of outbound connections by +repeatedly querying the address book for peers to connect to. +While a node has few to no outbound connections, the address book is biased to return +higher quality peers. As the node increases the number of outbound connections, +the address book is biased to return less-vetted or lower-quality peers. + +#### Inbound Peers + +Peers also maintain a maximum number of total connections, MaxNumPeers. +If a peer has MaxNumPeers, new incoming connections will be accepted with low probability. +When such a new connection is accepted, the peer disconnects from a probabilistically chosen low ranking peer +so it does not exceed MaxNumPeers. + +#### Peer Exchange + +When a peer receives a pexRequestMessage, it returns a random sample of high quality peers from the address book. Peers with no score or low score should not be inclided in a response to pexRequestMessage. + +#### Peer Quality + +Peer quality is tracked in the connection and across the reactors by storing the TrustMetric in the peer's +thread safe Data store. + +Peer behavior is then defined as one of the following: + +- Fatal - something outright malicious that causes us to disconnect the peer and ban it from the address book for some amount of time +- Bad - Any kind of timeout, messages that don't unmarshal, fail other validity checks, or messages we didn't ask for or aren't expecting (usually worth one bad event) +- Neutral - Unknown channels/message types/version upgrades (no good or bad events recorded) +- Correct - Normal correct behavior (worth one good event) +- Good - some random majority of peers per reactor sending us useful messages (worth more than one good event). + +Note that Fatal behavior causes us to remove the peer, and neutral behavior does not affect the score. + +## Status + +Proposed. + +## Consequences + +### Positive + +- Bringing the address book and trust metric store together will cause the network to be built in a way that encourages greater security and reliability. + +### Negative + +- TBD + +### Neutral + +- Keep in mind that, good events need to be recorded just as bad events do using this implementation. diff --git a/docs/architecture/tendermint-core/adr-008-priv-validator.md b/docs/architecture/tendermint-core/adr-008-priv-validator.md new file mode 100644 index 0000000..dbedc9a --- /dev/null +++ b/docs/architecture/tendermint-core/adr-008-priv-validator.md @@ -0,0 +1,35 @@ +# ADR 008: SocketPV + +Tendermint node's should support only two in-process PrivValidator +implementations: + +- FilePV uses an unencrypted private key in a "priv_validator.json" file - no + configuration required (just `tendermint init validator`). +- TCPVal and IPCVal use TCP and Unix sockets respectively to send signing requests + to another process - the user is responsible for starting that process themselves. + +Both TCPVal and IPCVal addresses can be provided via flags at the command line +or in the configuration file; TCPVal addresses must be of the form +`tcp://:` and IPCVal addresses `unix:///path/to/file.sock` - +doing so will cause Tendermint to ignore any private validator files. + +TCPVal will listen on the given address for incoming connections from an external +private validator process. It will halt any operation until at least one external +process successfully connected. + +The external priv_validator process will dial the address to connect to +Tendermint, and then Tendermint will send requests on the ensuing connection to +sign votes and proposals. Thus the external process initiates the connection, +but the Tendermint process makes all requests. In a later stage we're going to +support multiple validators for fault tolerance. To prevent double signing they +need to be synced, which is deferred to an external solution (see #1185). + +Conversely, IPCVal will make an outbound connection to an existing socket opened +by the external validator process. + +In addition, Tendermint will provide implementations that can be run in that +external process. These include: + +- FilePV will encrypt the private key, and the user must enter password to + decrypt key when process is started. +- LedgerPV uses a Ledger Nano S to handle all signing. diff --git a/docs/architecture/tendermint-core/adr-009-ABCI-design.md b/docs/architecture/tendermint-core/adr-009-ABCI-design.md new file mode 100644 index 0000000..39ea150 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-009-ABCI-design.md @@ -0,0 +1,271 @@ +# ADR 009: ABCI UX Improvements + +## Changelog + +23-06-2018: Some minor fixes from review +07-06-2018: Some updates based on discussion with Jae +07-06-2018: Initial draft to match what was released in ABCI v0.11 + +## Context + +The ABCI was first introduced in late 2015. It's purpose is to be: + +- a generic interface between state machines and their replication engines +- agnostic to the language the state machine is written in +- agnostic to the replication engine that drives it + +This means ABCI should provide an interface for both pluggable applications and +pluggable consensus engines. + +To achieve this, it uses Protocol Buffers (proto3) for message types. The dominant +implementation is in Go. + +After some recent discussions with the community on github, the following were +identified as pain points: + +- Amino encoded types +- Managing validator sets +- Imports in the protobuf file + +See the [references](#references) for more. + +### Imports + +The native proto library in Go generates inflexible and verbose code. +Many in the Go community have adopted a fork called +[gogoproto](https://github.com/cosmos/gogoproto) that provides a +variety of features aimed to improve the developer experience. +While `gogoproto` is nice, it creates an additional dependency, and compiling +the protobuf types for other languages has been reported to fail when `gogoproto` is used. + +### Amino + +Amino is an encoding protocol designed to improve over insufficiencies of protobuf. +It's goal is to be proto4. + +Many people are frustrated by incompatibility with protobuf, +and with the requirement for Amino to be used at all within ABCI. + +We intend to make Amino successful enough that we can eventually use it for ABCI +message types directly. By then it should be called proto4. In the meantime, +we want it to be easy to use. + +### PubKey + +PubKeys are encoded using Amino (and before that, go-wire). +Ideally, PubKeys are an interface type where we don't know all the +implementation types, so its unfitting to use `oneof` or `enum`. + +### Addresses + +The address for ED25519 pubkey is the RIPEMD160 of the Amino +encoded pubkey. This introduces an Amino dependency in the address generation, +a functionality that is widely required and should be easy to compute as +possible. + +### Validators + +To change the validator set, applications can return a list of validator updates +with ResponseEndBlock. In these updates, the public key _must_ be included, +because Tendermint requires the public key to verify validator signatures. This +means ABCI developers have to work with PubKeys. That said, it would also be +convenient to work with address information, and for it to be simple to do so. + +### AbsentValidators + +Tendermint also provides a list of validators in BeginBlock who did not sign the +last block. This allows applications to reflect availability behavior in the +application, for instance by punishing validators for not having votes included +in commits. + +### InitChain + +Tendermint passes in a list of validators here, and nothing else. It would +benefit the application to be able to control the initial validator set. For +instance the genesis file could include application-based information about the +initial validator set that the application could process to determine the +initial validator set. Additionally, InitChain would benefit from getting all +the genesis information. + +### Header + +ABCI provides the Header in RequestBeginBlock so the application can have +important information about the latest state of the blockchain. + +## Decision + +### Imports + +Move away from gogoproto. In the short term, we will just maintain a second +protobuf file without the gogoproto annotations. In the medium term, we will +make copies of all the structs in Golang and shuttle back and forth. In the long +term, we will use Amino. + +### Amino + +To simplify ABCI application development in the short term, +Amino will be completely removed from the ABCI: + +- It will not be required for PubKey encoding +- It will not be required for computing PubKey addresses + +That said, we are working to make Amino a huge success, and to become proto4. +To facilitate adoption and cross-language compatibility in the near-term, Amino +v1 will: + +- be fully compatible with the subset of proto3 that excludes `oneof` +- use the Amino prefix system to provide interface types, as opposed to `oneof` + style union types. + +That said, an Amino v2 will be worked on to improve the performance of the +format and its useability in cryptographic applications. + +### PubKey + +Encoding schemes infect software. As a generic middleware, ABCI aims to have +some cross scheme compatibility. For this it has no choice but to include opaque +bytes from time to time. While we will not enforce Amino encoding for these +bytes yet, we need to provide a type system. The simplest way to do this is to +use a type string. + +PubKey will now look like: + +``` +message PubKey { + string type + bytes data +} +``` + +where `type` can be: + +- "ed225519", with `data = ` +- "secp256k1", with `data = <33-byte OpenSSL compressed pubkey>` + +As we want to retain flexibility here, and since ideally, PubKey would be an +interface type, we do not use `enum` or `oneof`. + +### Addresses + +To simplify and improve computing addresses, we change it to the first 20-bytes of the SHA256 +of the raw 32-byte public key. + +We continue to use the Bitcoin address scheme for secp256k1 keys. + +### Validators + +Add a `bytes address` field: + +``` +message Validator { + bytes address + PubKey pub_key + int64 power +} +``` + +### RequestBeginBlock and AbsentValidators + +To simplify this, RequestBeginBlock will include the complete validator set, +including the address, and voting power of each validator, along +with a boolean for whether or not they voted: + +``` +message RequestBeginBlock { + bytes hash + Header header + LastCommitInfo last_commit_info + repeated Evidence byzantine_validators +} + +message LastCommitInfo { + int32 CommitRound + repeated SigningValidator validators +} + +message SigningValidator { + Validator validator + bool signed_last_block +} +``` + +Note that in Validators in RequestBeginBlock, we DO NOT include public keys. Public keys are +larger than addresses and in the future, with quantum computers, will be much +larger. The overhead of passing them, especially during fast-sync, is +significant. + +Additional, addresses are changing to be simpler to compute, further removing +the need to include pubkeys here. + +In short, ABCI developers must be aware of both addresses and public keys. + +### ResponseEndBlock + +Since ResponseEndBlock includes Validator, it must now include their address. + +### InitChain + +Change RequestInitChain to give the app all the information from the genesis file: + +``` +message RequestInitChain { + int64 time + string chain_id + ConsensusParams consensus_params + repeated Validator validators + bytes app_state_bytes +} +``` + +Change ResponseInitChain to allow the app to specify the initial validator set +and consensus parameters. + +``` +message ResponseInitChain { + ConsensusParams consensus_params + repeated Validator validators +} +``` + +### Header + +Now that Tendermint Amino will be compatible with proto3, the Header in ABCI +should exactly match the Tendermint header - they will then be encoded +identically in ABCI and in Tendermint Core. + +## Status + +Implemented + +## Consequences + +### Positive + +- Easier for developers to build on the ABCI +- ABCI and Tendermint headers are identically serialized + +### Negative + +- Maintenance overhead of alternative type encoding scheme +- Performance overhead of passing all validator info every block (at least its + only addresses, and not also pubkeys) +- Maintenance overhead of duplicate types + +### Neutral + +- ABCI developers must know about validator addresses + +## References + +- [ABCI v0.10.3 Specification (before this + proposal)](https://github.com/tendermint/abci/blob/v0.10.3/specification.rst) +- [ABCI v0.11.0 Specification (implementing first draft of this + proposal)](https://github.com/tendermint/abci/blob/v0.11.0/specification.md) +- [Ed25519 addresses](https://github.com/tendermint/go-crypto/issues/103) +- [InitChain contains the + Genesis](https://github.com/tendermint/abci/issues/216) +- [PubKeys](https://github.com/tendermint/tendermint/issues/1524) +- [Notes on + Header](https://github.com/tendermint/tendermint/issues/1605) +- [Gogoproto issues](https://github.com/tendermint/abci/issues/256) +- [Absent Validators](https://github.com/tendermint/abci/issues/231) diff --git a/docs/architecture/tendermint-core/adr-010-crypto-changes.md b/docs/architecture/tendermint-core/adr-010-crypto-changes.md new file mode 100644 index 0000000..3386e85 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-010-crypto-changes.md @@ -0,0 +1,77 @@ +# ADR 010: Crypto Changes + +## Context + +Tendermint is a cryptographic protocol that uses and composes a variety of cryptographic primitives. + +After nearly 4 years of development, Tendermint has recently undergone multiple security reviews to search for vulnerabilities and to assess the the use and composition of cryptographic primitives. + +### Hash Functions + +Tendermint uses RIPEMD160 universally as a hash function, most notably in its Merkle tree implementation. + +RIPEMD160 was chosen because it provides the shortest fingerprint that is long enough to be considered secure (ie. birthday bound of 80-bits). +It was also developed in the open academic community, unlike NSA-designed algorithms like SHA256. + +That said, the cryptographic community appears to unanimously agree on the security of SHA256. It has become a universal standard, especially now that SHA1 is broken, being required in TLS connections and having optimized support in hardware. + +### Merkle Trees + +Tendermint uses a simple Merkle tree to compute digests of large structures like transaction batches +and even blockchain headers. The Merkle tree length prefixes byte arrays before concatenating and hashing them. +It uses RIPEMD160. + +### Addresses + +ED25519 addresses are computed using the RIPEMD160 of the Amino encoding of the public key. +RIPEMD160 is generally considered an outdated hash function, and is much slower +than more modern functions like SHA256 or Blake2. + +### Authenticated Encryption + +Tendermint P2P connections use authenticated encryption to provide privacy and authentication in the communications. +This is done using the simple Station-to-Station protocol with the NaCL Ed25519 library. + +While there have been no vulnerabilities found in the implementation, there are some concerns: + +- NaCL uses Salsa20, a not-widely used and relatively out-dated stream cipher that has been obsoleted by ChaCha20 +- Connections use RIPEMD160 to compute a value that is used for the encryption nonce with subtle requirements on how it's used + +## Decision + +### Hash Functions + +Use the first 20-bytes of the SHA256 hash instead of RIPEMD160 for everything + +### Merkle Trees + +TODO + +### Addresses + +Compute ED25519 addresses as the first 20-bytes of the SHA256 of the raw 32-byte public key + +### Authenticated Encryption + +Make the following changes: + +- Use xChaCha20 instead of xSalsa20 - https://github.com/tendermint/tendermint/issues/1124 +- Use an HKDF instead of RIPEMD160 to compute nonces - https://github.com/tendermint/tendermint/issues/1165 + +## Status + +Implemented + +## Consequences + +### Positive + +- More modern and standard cryptographic functions with wider adoption and hardware acceleration + +### Negative + +- Exact authenticated encryption construction isn't already provided in a well-used library + +### Neutral + +## References diff --git a/docs/architecture/tendermint-core/adr-011-monitoring.md b/docs/architecture/tendermint-core/adr-011-monitoring.md new file mode 100644 index 0000000..f73b4fc --- /dev/null +++ b/docs/architecture/tendermint-core/adr-011-monitoring.md @@ -0,0 +1,116 @@ +# ADR 011: Monitoring + +## Changelog + +08-06-2018: Initial draft +11-06-2018: Reorg after @xla comments +13-06-2018: Clarification about usage of labels + +## Context + +In order to bring more visibility into Tendermint, we would like it to report +metrics and, maybe later, traces of transactions and RPC queries. See +https://github.com/tendermint/tendermint/issues/986. + +A few solutions were considered: + +1. [Prometheus](https://prometheus.io) + a) Prometheus API + b) [go-kit metrics package](https://github.com/go-kit/kit/tree/master/metrics) as an interface plus Prometheus + c) [telegraf](https://github.com/influxdata/telegraf) + d) new service, which will listen to events emitted by pubsub and report metrics +2. [OpenCensus](https://opencensus.io/introduction/) + +### 1. Prometheus + +Prometheus seems to be the most popular product out there for monitoring. It has +a Go client library, powerful queries, alerts. + +**a) Prometheus API** + +We can commit to using Prometheus in Tendermint, but I think Tendermint users +should be free to choose whatever monitoring tool they feel will better suit +their needs (if they don't have existing one already). So we should try to +abstract interface enough so people can switch between Prometheus and other +similar tools. + +**b) go-kit metrics package as an interface** + +metrics package provides a set of uniform interfaces for service +instrumentation and offers adapters to popular metrics packages: + +https://godoc.org/github.com/go-kit/kit/metrics#pkg-subdirectories + +Comparing to Prometheus API, we're losing customisability and control, but gaining +freedom in choosing any instrument from the above list given we will extract +metrics creation into a separate function (see "providers" in node/node.go). + +**c) telegraf** + +Unlike already discussed options, telegraf does not require modifying Tendermint +source code. You create something called an input plugin, which polls +Tendermint RPC every second and calculates the metrics itself. + +While it may sound good, but some metrics we want to report are not exposed via +RPC or pubsub, therefore can't be accessed externally. + +**d) service, listening to pubsub** + +Same issue as the above. + +### 2. opencensus + +opencensus provides both metrics and tracing, which may be important in the +future. It's API looks different from go-kit and Prometheus, but looks like it +covers everything we need. + +Unfortunately, OpenCensus go client does not define any +interfaces, so if we want to abstract away metrics we +will need to write interfaces ourselves. + +### List of metrics + +| | Name | Type | Description | +| --- | ------------------------------------ | ------ | ----------------------------------------------------------------------------- | +| A | consensus_height | Gauge | | +| A | consensus_validators | Gauge | Number of validators who signed | +| A | consensus_validators_power | Gauge | Total voting power of all validators | +| A | consensus_missing_validators | Gauge | Number of validators who did not sign | +| A | consensus_missing_validators_power | Gauge | Total voting power of the missing validators | +| A | consensus_byzantine_validators | Gauge | Number of validators who tried to double sign | +| A | consensus_byzantine_validators_power | Gauge | Total voting power of the byzantine validators | +| A | consensus_block_interval | Timing | Time between this and last block (Block.Header.Time) | +| | consensus_block_time | Timing | Time to create a block (from creating a proposal to commit) | +| | consensus_time_between_blocks | Timing | Time between committing last block and (receiving proposal creating proposal) | +| A | consensus_rounds | Gauge | Number of rounds | +| | consensus_prevotes | Gauge | | +| | consensus_precommits | Gauge | | +| | consensus_prevotes_total_power | Gauge | | +| | consensus_precommits_total_power | Gauge | | +| A | consensus_num_txs | Gauge | | +| A | mempool_size | Gauge | | +| A | consensus_total_txs | Gauge | | +| A | consensus_block_size | Gauge | In bytes | +| A | p2p_peers | Gauge | Number of peers node's connected to | + +`A` - will be implemented in the fist place. + +**Proposed solution** + +## Status + +Implemented + +## Consequences + +### Positive + +Better visibility, support of variety of monitoring backends + +### Negative + +One more library to audit, messing metrics reporting code with business domain. + +### Neutral + +- diff --git a/docs/architecture/tendermint-core/adr-012-peer-transport.md b/docs/architecture/tendermint-core/adr-012-peer-transport.md new file mode 100644 index 0000000..f334180 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-012-peer-transport.md @@ -0,0 +1,113 @@ +# ADR 012: PeerTransport + +## Context + +One of the more apparent problems with the current architecture in the p2p +package is that there is no clear separation of concerns between different +components. Most notably the `Switch` is currently doing physical connection +handling. An artifact is the dependency of the Switch on +`[config.P2PConfig`](https://github.com/tendermint/tendermint/blob/05a76fb517f50da27b4bfcdc7b4cf185fc61eff6/config/config.go#L272-L339). + +Addresses: + +- [#2046](https://github.com/tendermint/tendermint/issues/2046) +- [#2047](https://github.com/tendermint/tendermint/issues/2047) + +First iteraton in [#2067](https://github.com/tendermint/tendermint/issues/2067) + +## Decision + +Transport concerns will be handled by a new component (`PeerTransport`) which +will provide Peers at its boundary to the caller. In turn `Switch` will use +this new component accept new `Peer`s and dial them based on `NetAddress`. + +### PeerTransport + +Responsible for emitting and connecting to Peers. The implementation of `Peer` +is left to the transport, which implies that the chosen transport dictates the +characteristics of the implementation handed back to the `Switch`. Each +transport implementation is responsible to filter establishing peers specific +to its domain, for the default multiplexed implementation the following will +apply: + +- connections from our own node +- handshake fails +- upgrade to secret connection fails +- prevent duplicate ip +- prevent duplicate id +- nodeinfo incompatibility + +```go +// PeerTransport proxies incoming and outgoing peer connections. +type PeerTransport interface { + // Accept returns a newly connected Peer. + Accept() (Peer, error) + + // Dial connects to a Peer. + Dial(NetAddress) (Peer, error) +} + +// EXAMPLE OF DEFAULT IMPLEMENTATION + +// multiplexTransport accepts tcp connections and upgrades to multiplexted +// peers. +type multiplexTransport struct { + listener net.Listener + + acceptc chan accept + closec <-chan struct{} + listenc <-chan struct{} + + dialTimeout time.Duration + handshakeTimeout time.Duration + nodeAddr NetAddress + nodeInfo NodeInfo + nodeKey NodeKey + + // TODO(xla): Remove when MConnection is refactored into mPeer. + mConfig conn.MConnConfig +} + +var _ PeerTransport = (*multiplexTransport)(nil) + +// NewMTransport returns network connected multiplexed peers. +func NewMTransport( + nodeAddr NetAddress, + nodeInfo NodeInfo, + nodeKey NodeKey, +) *multiplexTransport +``` + +### Switch + +From now the Switch will depend on a fully setup `PeerTransport` to +retrieve/reach out to its peers. As the more low-level concerns are pushed to +the transport, we can omit passing the `config.P2PConfig` to the Switch. + +```go +func NewSwitch(transport PeerTransport, opts ...SwitchOption) *Switch +``` + +## Status + +In Review. + +## Consequences + +### Positive + +- free Switch from transport concerns - simpler implementation +- pluggable transport implementation - simpler test setup +- remove Switch dependency on P2PConfig - easier to test + +### Negative + +- more setup for tests which depend on Switches + +### Neutral + +- multiplexed will be the default implementation + +[0] These guards could be potentially extended to be pluggable much like +middlewares to express different concerns required by differentally configured +environments. diff --git a/docs/architecture/tendermint-core/adr-013-symmetric-crypto.md b/docs/architecture/tendermint-core/adr-013-symmetric-crypto.md new file mode 100644 index 0000000..0c8dd8b --- /dev/null +++ b/docs/architecture/tendermint-core/adr-013-symmetric-crypto.md @@ -0,0 +1,99 @@ +# ADR 013: Need for symmetric cryptography + +## Context + +We require symmetric ciphers to handle how we encrypt keys in the sdk, +and to potentially encrypt `priv_validator.json` in tendermint. + +Currently we use AEAD's to support symmetric encryption, +which is great since we want data integrity in addition to privacy and authenticity. +We don't currently have a scenario where we want to encrypt without data integrity, +so it is fine to optimize our code to just use AEAD's. +Currently there is not a way to switch out AEAD's easily, this ADR outlines a way +to easily swap these out. + +### How do we encrypt with AEAD's + +AEAD's typically require a nonce in addition to the key. +For the purposes we require symmetric cryptography for, +we need encryption to be stateless. +Because of this we use random nonces. +(Thus the AEAD must support random nonces) + +We currently construct a random nonce, and encrypt the data with it. +The returned value is `nonce || encrypted data`. +The limitation of this is that does not provide a way to identify +which algorithm was used in encryption. +Consequently decryption with multiple algoritms is sub-optimal. +(You have to try them all) + +## Decision + +We should create the following two methods in a new `crypto/encoding/symmetric` package: + +```golang +func Encrypt(aead cipher.AEAD, plaintext []byte) (ciphertext []byte, err error) +func Decrypt(key []byte, ciphertext []byte) (plaintext []byte, err error) +func Register(aead cipher.AEAD, algo_name string, NewAead func(key []byte) (cipher.Aead, error)) error +``` + +This allows you to specify the algorithm in encryption, but not have to specify +it in decryption. +This is intended for ease of use in downstream applications, in addition to people +looking at the file directly. +One downside is that for the encrypt function you must have already initialized an AEAD, +but I don't really see this as an issue. + +If there is no error in encryption, Encrypt will return `algo_name || nonce || aead_ciphertext`. +`algo_name` should be length prefixed, using standard varuint encoding. +This will be binary data, but thats not a problem considering the nonce and ciphertext are also binary. + +This solution requires a mapping from aead type to name. +We can achieve this via reflection. + +```golang +func getType(myvar interface{}) string { + if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr { + return "*" + t.Elem().Name() + } else { + return t.Name() + } +} +``` + +Then we maintain a map from the name returned from `getType(aead)` to `algo_name`. + +In decryption, we read the `algo_name`, and then instantiate a new AEAD with the key. +Then we call the AEAD's decrypt method on the provided nonce/ciphertext. + +`Register` allows a downstream user to add their own desired AEAD to the symmetric package. +It will error if the AEAD name is already registered. +This prevents a malicious import from modifying / nullifying an AEAD at runtime. + +## Implementation strategy + +The golang implementation of what is proposed is rather straight forward. +The concern is that we will break existing private keys if we just switch to this. +If this is concerning, we can make a simple script which doesn't require decoding privkeys, +for converting from the old format to the new one. + +## Status + +Proposed. + +## Consequences + +### Positive + +- Allows us to support new AEAD's, in a way that makes decryption easier +- Allows downstream users to add their own AEAD + +### Negative + +- We will have to break all private keys stored on disk. + They can be recovered using seed words, and upgrade scripts are simple. + +### Neutral + +- Caller has to instantiate the AEAD with the private key. + However it forces them to be aware of what signing algorithm they are using, which is a positive. diff --git a/docs/architecture/tendermint-core/adr-014-secp-malleability.md b/docs/architecture/tendermint-core/adr-014-secp-malleability.md new file mode 100644 index 0000000..17ee0bc --- /dev/null +++ b/docs/architecture/tendermint-core/adr-014-secp-malleability.md @@ -0,0 +1,63 @@ +# ADR 014: Secp256k1 Signature Malleability + +## Context + +Secp256k1 has two layers of malleability. +The signer has a random nonce, and thus can produce many different valid signatures. +This ADR is not concerned with that. +The second layer of malleability basically allows one who is given a signature +to produce exactly one more valid signature for the same message from the same public key. +(They don't even have to know the message!) +The math behind this will be explained in the subsequent section. + +Note that in many downstream applications, signatures will appear in a transaction, and therefore in the tx hash. +This means that if someone broadcasts a transaction with secp256k1 signature, the signature can be altered into the other form by anyone in the p2p network. +Thus the tx hash will change, and this altered tx hash may be committed instead. +This breaks the assumption that you can broadcast a valid transaction and just wait for its hash to be included on chain. +One example is if you are broadcasting a tx in cosmos, +and you wait for it to appear on chain before incrementing your sequence number. +You may never increment your sequence number if a different tx hash got committed. +Removing this second layer of signature malleability concerns could ease downstream development. + +### ECDSA context + +Secp256k1 is ECDSA over a particular curve. +The signature is of the form `(r, s)`, where `s` is a field element. +(The particular field is the `Z_n`, where the elliptic curve has order `n`) +However `(r, -s)` is also another valid solution. +Note that anyone can negate a group element, and therefore can get this second signature. + +## Decision + +We can just distinguish a canonical form for the ECDSA signatures. +Then we require that all ECDSA signatures be in the form which we defined as canonical. +We reject signatures in non-canonical form. + +A canonical form is rather easy to define and check. +It would just be the smaller of the two values for `s`, defined lexicographically. +This is a simple check, instead of checking if `s < n`, instead check `s <= (n - 1)/2`. +An example of another cryptosystem using this +is the parity definition here https://github.com/zkcrypto/pairing/pull/30#issuecomment-372910663. + +This is the same solution Ethereum has chosen for solving secp malleability. + +## Proposed Implementation + +Fork https://github.com/btcsuite/btcd, and just update the [parse sig method](https://github.com/btcsuite/btcd/blob/11fcd83963ab0ecd1b84b429b1efc1d2cdc6d5c5/btcec/signature.go#L195) and serialize functions to enforce our canonical form. + +## Status + +Implemented + +## Consequences + +### Positive + +- Lets us maintain the ability to expect a tx hash to appear in the blockchain. + +### Negative + +- More work in all future implementations (Though this is a very simple check) +- Requires us to maintain another fork + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-015-crypto-encoding.md b/docs/architecture/tendermint-core/adr-015-crypto-encoding.md new file mode 100644 index 0000000..8dcd8d6 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-015-crypto-encoding.md @@ -0,0 +1,84 @@ +# ADR 015: Crypto encoding + +## Context + +We must standardize our method for encoding public keys and signatures on chain. +Currently we amino encode the public keys and signatures. +The reason we are using amino here is primarily due to ease of support in +parsing for other languages. +We don't need its upgradability properties in cryptosystems, as a change in +the crypto that requires adapting the encoding, likely warrants being deemed +a new cryptosystem. +(I.e. using new public parameters) + +## Decision + +### Public keys + +For public keys, we will continue to use amino encoding on the canonical +representation of the pubkey. +(Canonical as defined by the cryptosystem itself) +This has two significant drawbacks. +Amino encoding is less space-efficient, due to requiring support for upgradability. +Amino encoding support requires forking protobuf and adding this new interface support +option in the language of choice. + +The reason for continuing to use amino however is that people can create code +more easily in languages that already have an up to date amino library. +It is possible that this will change in the future, if it is deemed that +requiring amino for interacting with Tendermint cryptography is unnecessary. + +The arguments for space efficiency here are refuted on the basis that there are +far more egregious wastages of space in the SDK. +The space requirement of the public keys doesn't cause many problems beyond +increasing the space attached to each validator / account. + +The alternative to using amino here would be for us to create an enum type. +Switching to just an enum type is worthy of investigation post-launch. +For reference, part of amino encoding interfaces is basically a 4 byte enum +type definition. +Enum types would just change that 4 bytes to be a variant, and it would remove +the protobuf overhead, but it would be hard to integrate into the existing API. + +### Signatures + +Signatures should be switched to be `[]byte`. +Spatial efficiency in the signatures is quite important, +as it directly affects the gas cost of every transaction, +and the throughput of the chain. +Signatures don't need to encode what type they are for (unlike public keys) +since public keys must already be known. +Therefore we can validate the signature without needing to encode its type. + +When placed in state, signatures will still be amino encoded, but it will be the +primitive type `[]byte` getting encoded. + +#### Ed25519 + +Use the canonical representation for signatures. + +#### Secp256k1 + +There isn't a clear canonical representation here. +Signatures have two elements `r,s`. +These bytes are encoded as `r || s`, where `r` and `s` are both exactly +32 bytes long, encoded big-endian. +This is basically Ethereum's encoding, but without the leading recovery bit. + +## Status + +Implemented + +## Consequences + +### Positive + +- More space efficient signatures + +### Negative + +- We have an amino dependency for cryptography. + +### Neutral + +- No change to public keys diff --git a/docs/architecture/tendermint-core/adr-016-protocol-versions.md b/docs/architecture/tendermint-core/adr-016-protocol-versions.md new file mode 100644 index 0000000..bc3ee59 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-016-protocol-versions.md @@ -0,0 +1,308 @@ +# ADR 016: Protocol Versions + +## TODO + +- How to / should we version the authenticated encryption handshake itself (ie. + upfront protocol negotiation for the P2PVersion) +- How to / should we version ABCI itself? Should it just be absorbed by the + BlockVersion? + +## Changelog + +- 18-09-2018: Updates after working a bit on implementation + - ABCI Handshake needs to happen independently of starting the app + conns so we can see the result + - Add question about ABCI protocol version +- 16-08-2018: Updates after discussion with SDK team + - Remove signalling for next version from Header/ABCI +- 03-08-2018: Updates from discussion with Jae: + - ProtocolVersion contains Block/AppVersion, not Current/Next + - signal upgrades to Tendermint using EndBlock fields + - dont restrict peer compatibilty by version to simplify syncing old nodes +- 28-07-2018: Updates from review + - split into two ADRs - one for protocol, one for chains + - include signalling for upgrades in header +- 16-07-2018: Initial draft - was originally joint ADR for protocol and chain + versions + +## Context + +Here we focus on software-agnostic protocol versions. + +The Software Version is covered by SemVer and described elsewhere. +It is not relevant to the protocol description, suffice to say that if any protocol version +changes, the software version changes, but not necessarily vice versa. + +Software version should be included in NodeInfo for convenience/diagnostics. + +We are also interested in versioning across different blockchains in a +meaningful way, for instance to differentiate branches of a contentious +hard-fork. We leave that for a later ADR. + +## Requirements + +We need to version components of the blockchain that may be independently upgraded. +We need to do it in a way that is scalable and maintainable - we can't just litter +the code with conditionals. + +We can consider the complete version of the protocol to contain the following sub-versions: +BlockVersion, P2PVersion, AppVersion. These versions reflect the major sub-components +of the software that are likely to evolve together, at different rates, and in different ways, +as described below. + +The BlockVersion defines the core of the blockchain data structures and +should change infrequently. + +The P2PVersion defines how peers connect and communicate with eachother - it's +not part of the blockchain data structures, but defines the protocols used to build the +blockchain. It may change gradually. + +The AppVersion determines how we compute app specific information, like the +AppHash and the Results. + +All of these versions may change over the life of a blockchain, and we need to +be able to help new nodes sync up across version changes. This means we must be willing +to connect to peers with older version. + +### BlockVersion + +- All tendermint hashed data-structures (headers, votes, txs, responses, etc.). + - Note the semantic meaning of a transaction may change according to the AppVersion, but the way txs are merklized into the header is part of the BlockVersion +- It should be the least frequent/likely to change. + - Tendermint should be stabilizing - it's just Atomic Broadcast. + - We can start considering for Tendermint v2.0 in a year +- It's easy to determine the version of a block from its serialized form + +### P2PVersion + +- All p2p and reactor messaging (messages, detectable behavior) +- Will change gradually as reactors evolve to improve performance and support new features - eg proposed new message types BatchTx in the mempool and HasBlockPart in the consensus +- It's easy to determine the version of a peer from its first serialized message/s +- New versions must be compatible with at least one old version to allow gradual upgrades + +### AppVersion + +- The ABCI state machine (txs, begin/endblock behavior, commit hashing) +- Behaviour and message types will change abruptly in the course of the life of a chain +- Need to minimize complexity of the code for supporting different AppVersions at different heights +- Ideally, each version of the software supports only a _single_ AppVersion at one time + - this means we checkout different versions of the software at different heights instead of littering the code + with conditionals + - minimize the number of data migrations required across AppVersion (ie. most AppVersion should be able to read the same state from disk as previous AppVersion). + +## Ideal + +Each component of the software is independently versioned in a modular way and its easy to mix and match and upgrade. + +## Proposal + +Each of BlockVersion, AppVersion, P2PVersion, is a monotonically increasing uint64. + +To use these versions, we need to update the block Header, the p2p NodeInfo, and the ABCI. + +### Header + +Block Header should include a `Version` struct as its first field like: + +``` +type Version struct { + Block uint64 + App uint64 +} +``` + +Here, `Version.Block` defines the rules for the current block, while +`Version.App` defines the app version that processed the last block and computed +the `AppHash` in the current block. Together they provide a complete description +of the consensus-critical protocol. + +Since we have settled on a proto3 header, the ability to read the BlockVersion out of the serialized header is unanimous. + +Using a Version struct gives us more flexibility to add fields without breaking +the header. + +The ProtocolVersion struct includes both the Block and App versions - it should +serve as a complete description of the consensus-critical protocol. + +### NodeInfo + +NodeInfo should include a Version struct as its first field like: + +``` +type Version struct { + P2P uint64 + Block uint64 + App uint64 + + Other []string +} +``` + +Note this effectively makes `Version.P2P` the first field in the NodeInfo, so it +should be easy to read this out of the serialized header if need be to facilitate an upgrade. + +The `Version.Other` here should include additional information like the name of the software client and +it's SemVer version - this is for convenience only. Eg. +`tendermint-core/v0.22.8`. It's a `[]string` so it can include information about +the version of Tendermint, of the app, of Tendermint libraries, etc. + +### ABCI + +Since the ABCI is responsible for keeping Tendermint and the App in sync, we +need to communicate version information through it. + +On startup, we use Info to perform a basic handshake. It should include all the +version information. + +We also need to be able to update versions in the life of a blockchain. The +natural place to do this is EndBlock. + +Note that currently the result of the Handshake isn't exposed anywhere, as the +handshaking happens inside the `proxy.AppConns` abstraction. We will need to +remove the handshaking from the `proxy` package so we can call it independently +and get the result, which should contain the application version. + +#### Info + +RequestInfo should add support for protocol versions like: + +``` +message RequestInfo { + string version + uint64 block_version + uint64 p2p_version +} +``` + +Similarly, ResponseInfo should return the versions: + +``` +message ResponseInfo { + string data + + string version + uint64 app_version + + int64 last_block_height + bytes last_block_app_hash +} +``` + +The existing `version` fields should be called `software_version` but we leave +them for now to reduce the number of breaking changes. + +#### EndBlock + +Updating the version could be done either with new fields or by using the +existing `tags`. Since we're trying to communicate information that will be +included in Tendermint block Headers, it should be native to the ABCI, and not +something embedded through some scheme in the tags. Thus, version updates should +be communicated through EndBlock. + +EndBlock already contains `ConsensusParams`. We can add version information to +the ConsensusParams as well: + +``` +message ConsensusParams { + + BlockSize block_size + EvidenceParams evidence_params + VersionParams version +} + +message VersionParams { + uint64 block_version + uint64 app_version +} +``` + +For now, the `block_version` will be ignored, as we do not allow block version +to be updated live. If the `app_version` is set, it signals that the app's +protocol version has changed, and the new `app_version` will be included in the +`Block.Header.Version.App` for the next block. + +### BlockVersion + +BlockVersion is included in both the Header and the NodeInfo. + +Changing BlockVersion should happen quite infrequently and ideally only for +critical upgrades. For now, it is not encoded in ABCI, though it's always +possible to use tags to signal an external process to co-ordinate an upgrade. + +Note Ethereum has not had to make an upgrade like this (everything has been at state machine level, AFAIK). + +### P2PVersion + +P2PVersion is not included in the block Header, just the NodeInfo. + +P2PVersion is the first field in the NodeInfo. NodeInfo is also proto3 so this is easy to read out. + +Note we need the peer/reactor protocols to take the versions of peers into account when sending messages: + +- don't send messages they don't understand +- don't send messages they don't expect + +Doing this will be specific to the upgrades being made. + +Note we also include the list of reactor channels in the NodeInfo and already don't send messages for channels the peer doesn't understand. +If upgrades always use new channels, this simplifies the development cost of backwards compatibility. + +Note NodeInfo is only exchanged after the authenticated encryption handshake to ensure that it's private. +Doing any version exchange before encrypting could be considered information leakage, though I'm not sure +how much that matters compared to being able to upgrade the protocol. + +XXX: if needed, can we change the meaning of the first byte of the first message to encode a handshake version? +this is the first byte of a 32-byte ed25519 pubkey. + +### AppVersion + +AppVersion is also included in the block Header and the NodeInfo. + +AppVersion essentially defines how the AppHash and LastResults are computed. + +### Peer Compatibility + +Restricting peer compatibility based on version is complicated by the need to +help old peers, possibly on older versions, sync the blockchain. + +We might be tempted to say that we only connect to peers with the same +AppVersion and BlockVersion (since these define the consensus critical +computations), and a select list of P2PVersions (ie. those compatible with +ours), but then we'd need to make accomodations for connecting to peers with the +right Block/AppVersion for the height they're on. + +For now, we will connect to peers with any version and restrict compatibility +solely based on the ChainID. We leave more restrictive rules on peer +compatibiltiy to a future proposal. + +### Future Changes + +It may be valuable to support an `/unsafe_stop?height=_` endpoint to tell Tendermint to shutdown at a given height. +This could be use by an external manager process that oversees upgrades by +checking out and installing new software versions and restarting the process. It +would subscribe to the relevant upgrade event (needs to be implemented) and call `/unsafe_stop` at +the correct height (of course only after getting approval from its user!) + +## Consequences + +### Positive + +- Make tendermint and application versions native to the ABCI to more clearly + communicate about them +- Distinguish clearly between protocol versions and software version to + facilitate implementations in other languages +- Versions included in key data structures in easy to discern way +- Allows proposers to signal for upgrades and apps to decide when to actually change the + version (and start signalling for a new version) + +### Neutral + +- Unclear how to version the initial P2P handshake itself +- Versions aren't being used (yet) to restrict peer compatibility +- Signalling for a new version happens through the proposer and must be + tallied/tracked in the app. + +### Negative + +- Adds more fields to the ABCI +- Implies that a single codebase must be able to handle multiple versions diff --git a/docs/architecture/tendermint-core/adr-017-chain-versions.md b/docs/architecture/tendermint-core/adr-017-chain-versions.md new file mode 100644 index 0000000..026df7c --- /dev/null +++ b/docs/architecture/tendermint-core/adr-017-chain-versions.md @@ -0,0 +1,99 @@ +# ADR 017: Chain Versions + +## TODO + +- clarify how to handle slashing when ChainID changes + +## Changelog + +- 28-07-2018: Updates from review + - split into two ADRs - one for protocol, one for chains +- 16-07-2018: Initial draft - was originally joint ADR for protocol and chain + versions + +## Context + +Software and Protocol versions are covered in a separate ADR. + +Here we focus on chain versions. + +## Requirements + +We need to version blockchains across protocols, networks, forks, etc. +We need chain identifiers and descriptions so we can talk about a multitude of chains, +and especially the differences between them, in a meaningful way. + +### Networks + +We need to support many independent networks running the same version of the software, +even possibly starting from the same initial state. +They must have distinct identifiers so that peers know which one they are joining and so +validators and users can prevent replay attacks. + +Call this the `NetworkName` (note we currently call this `ChainID` in the software. In this +ADR, ChainID has a different meaning). +It represents both the application being run and the community or intention +of running it. + +Peers only connect to other peers with the same NetworkName. + +### Forks + +We need to support existing networks upgrading and forking, wherein they may do any of: + + - revert back to some height, continue with the same versions but new blocks + - arbitrarily mutate state at some height, continue with the same versions (eg. Dao Fork) + - change the AppVersion at some height + +Note because of Tendermint's voting power threshold rules, a chain can only be extended under the "original" rules and under the new rules +if 1/3 or more is double signing, which is expressly prohibited, and is supposed to result in their punishment on both chains. Since they can censor +the punishment, the chain is expected to be hardforked to remove the validators. Thus, if both branches are to continue after a fork, +they will each require a new identifier, and the old chain identifier will be retired (ie. only useful for syncing history, not for new blocks).. + +TODO: explain how to handle slashing when chain id changed! + +We need a consistent way to describe forks. + +## Proposal + +### ChainDescription + +ChainDescription is a complete immutable description of a blockchain. It takes the following form: + +``` +ChainDescription = ///// +``` + +Here, StateHash is the merkle root of the initial state, ValHash is the merkle root of the initial Tendermint validator set, +and ConsensusParamsHash is the merkle root of the initial Tendermint consensus parameters. + +The `genesis.json` file must contain enough information to compute this value. It need not contain the StateHash or ValHash itself, +but contain the state from which they can be computed with the given protocol versions. + +NOTE: consider splitting NetworkName into NetworkName and AppName - this allows +folks to independently use the same application for different networks (ie we +could imagine multiple communities of validators wanting to put up a Hub using +the same app but having a distinct network name. Arguably not needed if +differences will come via different initial state / validators). + +#### ChainID + +Define `ChainID = TMHASH(ChainDescriptor)`. It's the unique ID of a blockchain. + +It should be Bech32 encoded when handled by users, eg. with `cosmoschain` prefix. + +#### Forks and Uprades + +When a chain forks or upgrades but continues the same history, it takes a new ChainDescription as follows: + +``` +ChainDescription = /x// +``` + +Where + +- ChainID is the ChainID from the previous ChainDescription (ie. its hash) +- `x` denotes that a change occured +- `Height` is the height the change occured +- ForkDescription has the same form as ChainDescription but for the fork +- this allows forks to specify new versions for tendermint or the app, as well as arbitrary changes to the state or validator set diff --git a/docs/architecture/tendermint-core/adr-018-ABCI-Validators.md b/docs/architecture/tendermint-core/adr-018-ABCI-Validators.md new file mode 100644 index 0000000..e85247b --- /dev/null +++ b/docs/architecture/tendermint-core/adr-018-ABCI-Validators.md @@ -0,0 +1,100 @@ +# ADR 018: ABCI Validator Improvements + +## Changelog + +016-08-2018: Follow up from review: - Revert changes to commit round - Remind about justification for removing pubkey - Update pros/cons +05-08-2018: Initial draft + +## Context + +ADR 009 introduced major improvements to the ABCI around validators and the use +of Amino. Here we follow up with some additional changes to improve the naming +and expected use of Validator messages. + +## Decision + +### Validator + +Currently a Validator contains `address` and `pub_key`, and one or the other is +optional/not-sent depending on the use case. Instead, we should have a +`Validator` (with just the address, used for RequestBeginBlock) +and a `ValidatorUpdate` (with the pubkey, used for ResponseEndBlock): + +``` +message Validator { + bytes address + int64 power +} + +message ValidatorUpdate { + PubKey pub_key + int64 power +} +``` + +As noted in [ADR-009](adr-009-ABCI-design.md), +the `Validator` does not contain a pubkey because quantum public keys are +quite large and it would be wasteful to send them all over ABCI with every block. +Thus, applications that want to take advantage of the information in BeginBlock +are _required_ to store pubkeys in state (or use much less efficient lazy means +of verifying BeginBlock data). + +### RequestBeginBlock + +LastCommitInfo currently has an array of `SigningValidator` that contains +information for each validator in the entire validator set. +Instead, this should be called `VoteInfo`, since it is information about the +validator votes. + +Note that all votes in a commit must be from the same round. + +``` +message LastCommitInfo { + int64 round + repeated VoteInfo commit_votes +} + +message VoteInfo { + Validator validator + bool signed_last_block +} +``` + +### ResponseEndBlock + +Use ValidatorUpdates instead of Validators. Then it's clear we don't need an +address, and we do need a pubkey. + +We could require the address here as well as a sanity check, but it doesn't seem +necessary. + +### InitChain + +Use ValidatorUpdates for both Request and Response. InitChain +is about setting/updating the initial validator set, unlike BeginBlock +which is just informational. + +## Status + +Implemented + +## Consequences + +### Positive + +- Clarifies the distinction between the different uses of validator information + +### Negative + +- Apps must still store the public keys in state to utilize the RequestBeginBlock info + +### Neutral + +- ResponseEndBlock does not require an address + +## References + +- [Latest ABCI Spec](https://github.com/tendermint/tendermint/blob/v0.22.8/docs/app-dev/abci-spec.md) +- [ADR-009](https://github.com/tendermint/tendermint/blob/v0.22.8/docs/architecture/adr-009-ABCI-design.md) +- [Issue #1712 - Don't send PubKey in + RequestBeginBlock](https://github.com/tendermint/tendermint/issues/1712) diff --git a/docs/architecture/tendermint-core/adr-019-multisigs.md b/docs/architecture/tendermint-core/adr-019-multisigs.md new file mode 100644 index 0000000..ccac1b0 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-019-multisigs.md @@ -0,0 +1,162 @@ +# ADR 019: Encoding standard for Multisignatures + +## Changelog + +06-08-2018: Minor updates + +27-07-2018: Update draft to use amino encoding + +11-07-2018: Initial Draft + +5-26-2021: Multisigs were moved into the Cosmos-sdk + +## Context + +Multisignatures, or technically _Accountable Subgroup Multisignatures_ (ASM), +are signature schemes which enable any subgroup of a set of signers to sign any message, +and reveal to the verifier exactly who the signers were. +This allows for complex conditionals of when to validate a signature. + +Suppose the set of signers is of size _n_. +If we validate a signature if any subgroup of size _k_ signs a message, +this becomes what is commonly reffered to as a _k of n multisig_ in Bitcoin. + +This ADR specifies the encoding standard for general accountable subgroup multisignatures, +k of n accountable subgroup multisignatures, and its weighted variant. + +In the future, we can also allow for more complex conditionals on the accountable subgroup. + +## Proposed Solution + +### New structs + +Every ASM will then have its own struct, implementing the crypto.Pubkey interface. + +This ADR assumes that [replacing crypto.Signature with []bytes](https://github.com/tendermint/tendermint/issues/1957) has been accepted. + +#### K of N threshold signature + +The pubkey is the following struct: + +```golang +type ThresholdMultiSignaturePubKey struct { // K of N threshold multisig + K uint `json:"threshold"` + Pubkeys []crypto.Pubkey `json:"pubkeys"` +} +``` + +We will derive N from the length of pubkeys. (For spatial efficiency in encoding) + +`Verify` will expect an `[]byte` encoded version of the Multisignature. +(Multisignature is described in the next section) +The multisignature will be rejected if the bitmap has less than k indices, +or if any signature at any of the k indices is not a valid signature from +the kth public key on the message. +(If more than k signatures are included, all must be valid) + +`Bytes` will be the amino encoded version of the pubkey. + +Address will be `Hash(amino_encoded_pubkey)` + +The reason this doesn't use `log_8(n)` bytes per signer is because that heavily optimizes for the case where a very small number of signers are required. +e.g. for `n` of size `24`, that would only be more space efficient for `k < 3`. +This seems less likely, and that it should not be the case optimized for. + +#### Weighted threshold signature + +The pubkey is the following struct: + +```golang +type WeightedThresholdMultiSignaturePubKey struct { + Weights []uint `json:"weights"` + Threshold uint `json:"threshold"` + Pubkeys []crypto.Pubkey `json:"pubkeys"` +} +``` + +Weights and Pubkeys must be of the same length. +Everything else proceeds identically to the K of N multisig, +except the multisig fails if the sum of the weights is less than the threshold. + +#### Multisignature + +The inter-mediate phase of the signatures (as it accrues more signatures) will be the following struct: + +```golang +type Multisignature struct { + BitArray CryptoBitArray // Documented later + Sigs [][]byte +``` + +It is important to recall that each private key will output a signature on the provided message itself. +So no signing algorithm ever outputs the multisignature. +The UI will take a signature, cast into a multisignature, and then keep adding +new signatures into it, and when done marshal into `[]byte`. +This will require the following helper methods: + +```golang +func SigToMultisig(sig []byte, n int) +func GetIndex(pk crypto.Pubkey, []crypto.Pubkey) +func AddSignature(sig Signature, index int, multiSig *Multisignature) +``` + +The multisignature will be converted to an `[]byte` using amino.MarshalBinaryBare. \* + +#### Bit Array + +We would be using a new implementation of a bitarray. The struct it would be encoded/decoded from is + +```golang +type CryptoBitArray struct { + ExtraBitsStored byte `json:"extra_bits"` // The number of extra bits in elems. + Elems []byte `json:"elems"` +} +``` + +The reason for not using the BitArray currently implemented in `libs/common/bit_array.go` +is that it is less space efficient, due to a space / time trade-off. +Evidence for this is outlined in [this issue](https://github.com/tendermint/tendermint/issues/2077). + +In the multisig, we will not be performing arithmetic operations, +so there is no performance increase with the current implementation, +and just loss of spatial efficiency. +Implementing this new bit array with `[]byte` _should_ be simple, as no +arithmetic operations between bit arrays are required, and save a couple of bytes. +(Explained in that same issue) + +When this bit array encoded, the number of elements is encoded due to amino. +However we may be encoding a full byte for what we actually only need 1-7 bits for. +We store that difference in ExtraBitsStored. +This allows for us to have an unbounded number of signers, and is more space efficient than what is currently used in `libs/common`. +Again the implementation of this space saving feature is straight forward. + +### Encoding the structs + +We will use straight forward amino encoding. This is chosen for ease of compatibility in other languages. + +### Future points of discussion + +If desired, we can use ed25519 batch verification for all ed25519 keys. +This is a future point of discussion, but would be backwards compatible as this information won't need to be marshalled. +(There may even be cofactor concerns without ristretto) +Aggregation of pubkeys / sigs in Schnorr sigs / BLS sigs is not backwards compatible, and would need to be a new ASM type. + +## Status + +Implemented (moved to cosmos-sdk) + +## Consequences + +### Positive + +- Supports multisignatures, in a way that won't require any special cases in our downstream verification code. +- Easy to serialize / deserialize +- Unbounded number of signers + +### Negative + +- Larger codebase, however this should reside in a subfolder of tendermint/crypto, as it provides no new interfaces. (Ref #https://github.com/tendermint/go-crypto/issues/136) +- Space inefficient due to utilization of amino encoding +- Suggested implementation requires a new struct for every ASM. + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-020-block-size.md b/docs/architecture/tendermint-core/adr-020-block-size.md new file mode 100644 index 0000000..54ca9fc --- /dev/null +++ b/docs/architecture/tendermint-core/adr-020-block-size.md @@ -0,0 +1,104 @@ +# ADR 020: Limiting txs size inside a block + +## Changelog + +13-08-2018: Initial Draft +15-08-2018: Second version after Dev's comments +28-08-2018: Third version after Ethan's comments +30-08-2018: AminoOverheadForBlock => MaxAminoOverheadForBlock +31-08-2018: Bounding evidence and chain ID +13-01-2019: Add section on MaxBytes vs MaxDataBytes + +## Context + +We currently use MaxTxs to reap txs from the mempool when proposing a block, +but enforce MaxBytes when unmarshaling a block, so we could easily propose a +block thats too large to be valid. + +We should just remove MaxTxs all together and stick with MaxBytes, and have a +`mempool.ReapMaxBytes`. + +But we can't just reap BlockSize.MaxBytes, since MaxBytes is for the entire block, +not for the txs inside the block. There's extra amino overhead + the actual +headers on top of the actual transactions + evidence + last commit. +We could also consider using a MaxDataBytes instead of or in addition to MaxBytes. + +## MaxBytes vs MaxDataBytes + +The [PR #3045](https://github.com/tendermint/tendermint/pull/3045) suggested +additional clarity/justification was necessary here, wither respect to the use +of MaxDataBytes in addition to, or instead of, MaxBytes. + +MaxBytes provides a clear limit on the total size of a block that requires no +additional calculation if you want to use it to bound resource usage, and there +has been considerable discussions about optimizing tendermint around 1MB blocks. +Regardless, we need some maximum on the size of a block so we can avoid +unmarshaling blocks that are too big during the consensus, and it seems more +straightforward to provide a single fixed number for this rather than a +computation of "MaxDataBytes + everything else you need to make room for +(signatures, evidence, header)". MaxBytes provides a simple bound so we can +always say "blocks are less than X MB". + +Having both MaxBytes and MaxDataBytes feels like unnecessary complexity. It's +not particularly surprising for MaxBytes to imply the maximum size of the +entire block (not just txs), one just has to know that a block includes header, +txs, evidence, votes. For more fine grained control over the txs included in the +block, there is the MaxGas. In practice, the MaxGas may be expected to do most of +the tx throttling, and the MaxBytes to just serve as an upper bound on the total +size. Applications can use MaxGas as a MaxDataBytes by just taking the gas for +every tx to be its size in bytes. + +## Proposed solution + +Therefore, we should + +1) Get rid of MaxTxs. +2) Rename MaxTxsBytes to MaxBytes. + +When we need to ReapMaxBytes from the mempool, we calculate the upper bound as follows: + +``` +ExactLastCommitBytes = {number of validators currently enabled} * {MaxVoteBytes} +MaxEvidenceBytesPerBlock = MaxBytes / 10 +ExactEvidenceBytes = cs.evpool.PendingEvidence(MaxEvidenceBytesPerBlock) * MaxEvidenceBytes + +mempool.ReapMaxBytes(MaxBytes - MaxAminoOverheadForBlock - ExactLastCommitBytes - ExactEvidenceBytes - MaxHeaderBytes) +``` + +where MaxVoteBytes, MaxEvidenceBytes, MaxHeaderBytes and MaxAminoOverheadForBlock +are constants defined inside the `types` package: + +- MaxVoteBytes - 170 bytes +- MaxEvidenceBytes - 364 bytes +- MaxHeaderBytes - 476 bytes (~276 bytes hashes + 200 bytes - 50 UTF-8 encoded + symbols of chain ID 4 bytes each in the worst case + amino overhead) +- MaxAminoOverheadForBlock - 8 bytes (assuming MaxHeaderBytes includes amino + overhead for encoding header, MaxVoteBytes - for encoding vote, etc.) + +ChainID needs to bound to 50 symbols max. + +When reaping evidence, we use MaxBytes to calculate the upper bound (e.g. 1/10) +to save some space for transactions. + +NOTE while reaping the `max int` bytes in mempool, we should account that every +transaction will take `len(tx)+aminoOverhead`, where aminoOverhead=1-4 bytes. + +We should write a test that fails if the underlying structs got changed, but +MaxXXX stayed the same. + +## Status + +Implemented + +## Consequences + +### Positive + +* one way to limit the size of a block +* less variables to configure + +### Negative + +* constants that need to be adjusted if the underlying structs got changed + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-021-abci-events.md b/docs/architecture/tendermint-core/adr-021-abci-events.md new file mode 100644 index 0000000..0f8aca8 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-021-abci-events.md @@ -0,0 +1,52 @@ +# ADR 012: ABCI Events + +## Changelog + +- *2018-09-02* Remove ABCI errors component. Update description for events +- *2018-07-12* Initial version + +## Context + +ABCI tags were first described in [ADR 002](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-002-event-subscription.md). +They are key-value pairs that can be used to index transactions. + +Currently, ABCI messages return a list of tags to describe an +"event" that took place during the Check/DeliverTx/Begin/EndBlock, +where each tag refers to a different property of the event, like the sending and receiving account addresses. + +Since there is only one list of tags, recording data for multiple such events in +a single Check/DeliverTx/Begin/EndBlock must be done using prefixes in the key +space. + +Alternatively, groups of tags that constitute an event can be separated by a +special tag that denotes a break between the events. This would allow +straightforward encoding of multiple events into a single list of tags without +prefixing, at the cost of these "special" tags to separate the different events. + +TODO: brief description of how the indexing works + +## Decision + +Instead of returning a list of tags, return a list of events, where +each event is a list of tags. This way we naturally capture the concept of +multiple events happening during a single ABCI message. + +TODO: describe impact on indexing and querying + +## Status + +Implemented + +## Consequences + +### Positive + +- Ability to track distinct events separate from ABCI calls (DeliverTx/BeginBlock/EndBlock) +- More powerful query abilities + +### Negative + +- More complex query syntax +- More complex search implementation + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-022-abci-errors.md b/docs/architecture/tendermint-core/adr-022-abci-errors.md new file mode 100644 index 0000000..25af4d8 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-022-abci-errors.md @@ -0,0 +1,63 @@ +# ADR 022: ABCI Errors + +## Changelog + +- *2018-09-01* Initial version + +## Context + +ABCI errors should provide an abstraction between application details +and the client interface responsible for formatting & displaying errors to the user. + +Currently, this abstraction consists of a single integer (the `code`), where any +`code > 0` is considered an error (ie. invalid transaction) and all type +information about the error is contained in the code. This integer is +expected to be decoded by the client into a known error string, where any +more specific data is contained in the `data`. + +In a [previous conversation](https://github.com/tendermint/abci/issues/165#issuecomment-353704015), +it was suggested that not all non-zero codes need to be errors, hence why it's called `code` and not `error code`. +It is unclear exactly how the semantics of the `code` field will evolve, though +better lite-client proofs (like discussed for tags +[here](https://github.com/tendermint/tendermint/issues/1007#issuecomment-413917763)) +may play a role. + +Note that having all type information in a single integer +precludes an easy coordination method between "module implementers" and "client +implementers", especially for apps with many "modules". With an unbounded error domain (such as a string), module +implementers can pick a globally unique prefix & error code set, so client +implementers could easily implement support for "module A" regardless of which +particular blockchain network it was running in and which other modules were running with it. With +only error codes, globally unique codes are difficult/impossible, as the space +is finite and collisions are likely without an easy way to coordinate. + +For instance, while trying to build an ecosystem of modules that can be composed into a single +ABCI application, the Cosmos-SDK had to hack a higher level "codespace" into the +single integer so that each module could have its own space to express its +errors. + +## Decision + +Include a `string code_space` in all ABCI messages that have a `code`. +This allows applications to namespace the codes so they can experiment with +their own code schemes. + +It is the responsibility of applications to limit the size of the `code_space` +string. + +How the codespace is hashed into block headers (ie. so it can be queried +efficiently by lite clients) is left for a separate ADR. + +## Consequences + +## Positive + +- No need for complex codespacing on a single integer +- More expressive type system for errors + +## Negative + +- Another field in the response needs to be accounted for +- Some redundancy with `code` field +- May encourage more error/code type info to move to the `codespace` string, which + could impact lite clients. diff --git a/docs/architecture/tendermint-core/adr-023-ABCI-propose-tx.md b/docs/architecture/tendermint-core/adr-023-ABCI-propose-tx.md new file mode 100644 index 0000000..d43f690 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-023-ABCI-propose-tx.md @@ -0,0 +1,183 @@ +# ADR 023: ABCI `ProposeTx` Method + +## Changelog + +25-06-2018: Initial draft based on [#1776](https://github.com/tendermint/tendermint/issues/1776) + +## Context + +[#1776](https://github.com/tendermint/tendermint/issues/1776) was +opened in relation to implementation of a Plasma child chain using Tendermint +Core as consensus/replication engine. + +Due to the requirements of [Minimal Viable Plasma (MVP)](https://ethresear.ch/t/minimal-viable-plasma/426) and [Plasma Cash](https://ethresear.ch/t/plasma-cash-plasma-with-much-less-per-user-data-checking/1298), it is necessary for ABCI apps to have a mechanism to handle the following cases (more may emerge in the near future): + +1. `deposit` transactions on the Root Chain, which must consist of a block + with a single transaction, where there are no inputs and only one output + made in favour of the depositor. In this case, a `block` consists of + a transaction with the following shape: + + ``` + [0, 0, 0, 0, #input1 - zeroed out + 0, 0, 0, 0, #input2 - zeroed out + , , #output1 - in favour of depositor + 0, 0, #output2 - zeroed out + , + ] + ``` + + `exit` transactions may also be treated in a similar manner, wherein the + input is the UTXO being exited on the Root Chain, and the output belongs to + a reserved "burn" address, e.g., `0x0`. In such cases, it is favorable for + the containing block to only hold a single transaction that may receive + special treatment. + +2. Other "internal" transactions on the child chain, which may be initiated + unilaterally. The most basic example of is a coinbase transaction + implementing validator node incentives, but may also be app-specific. In + these cases, it may be favorable for such transactions to + be ordered in a specific manner, e.g., coinbase transactions will always be + at index 0. In general, such strategies increase the determinism and + predictability of blockchain applications. + +While it is possible to deal with the cases enumerated above using the +existing ABCI, currently available result in suboptimal workarounds. Two are +explained in greater detail below. + +### Solution 1: App state-based Plasma chain + +In this work around, the app maintains a `PlasmaStore` with a corresponding +`Keeper`. The PlasmaStore is responsible for maintaing a second, separate +blockchain that complies with the MVP specification, including `deposit` +blocks and other "internal" transactions. These "virtual" blocks are then broadcasted +to the Root Chain. + +This naive approach is, however, fundamentally flawed, as it by definition +diverges from the canonical chain maintained by Tendermint. This is further +exacerbated if the business logic for generating such transactions is +potentially non-deterministic, as this should not even be done in +`Begin/EndBlock`, which may, as a result, break consensus guarantees. + +Additinoally, this has serious implications for "watchers" - independent third parties, +or even an auxilliary blockchain, responsible for ensuring that blocks recorded +on the Root Chain are consistent with the Plasma chain's. Since, in this case, +the Plasma chain is inconsistent with the canonical one maintained by Tendermint +Core, it seems that there exists no compact means of verifying the legitimacy of +the Plasma chain without replaying every state transition from genesis (!). + +### Solution 2: Broadcast to Tendermint Core from ABCI app + +This approach is inspired by `tendermint`, in which Ethereum transactions are +relayed to Tendermint Core. It requires the app to maintain a client connection +to the consensus engine. + +Whenever an "internal" transaction needs to be created, the proposer of the +current block broadcasts the transaction or transactions to Tendermint as +needed in order to ensure that the Tendermint chain and Plasma chain are +completely consistent. + +This allows "internal" transactions to pass through the full consensus +process, and can be validated in methods like `CheckTx`, i.e., signed by the +proposer, is the semantically correct, etc. Note that this involves informing +the ABCI app of the block proposer, which was temporarily hacked in as a means +of conducting this experiment, although this should not be necessary when the +current proposer is passed to `BeginBlock`. + +It is much easier to relay these transactions directly to the Root +Chain smart contract and/or maintain a "compressed" auxiliary chain comprised +of Plasma-friendly blocks that 100% reflect the canonical (Tendermint) +blockchain. Unfortunately, this approach not idiomatic (i.e., utilises the +Tendermint consensus engine in unintended ways). Additionally, it does not +allow the application developer to: + +- Control the _ordering_ of transactions in the proposed block (e.g., index 0, + or 0 to `n` for coinbase transactions) +- Control the _number_ of transactions in the block (e.g., when a `deposit` + block is required) + +Since determinism is of utmost importance in blockchain engineering, this approach, +while more viable, should also not be considered as fit for production. + +## Decision + +### `ProposeTx` + +In order to address the difficulties described above, the ABCI interface must +expose an additional method, tentatively named `ProposeTx`. + +It should have the following signature: + +``` +ProposeTx(RequestProposeTx) ResponseProposeTx +``` + +Where `RequestProposeTx` and `ResponseProposeTx` are `message`s with the +following shapes: + +``` +message RequestProposeTx { + int64 next_block_height = 1; // height of the block the proposed tx would be part of + Validator proposer = 2; // the proposer details +} + +message ResponseProposeTx { + int64 num_tx = 1; // the number of tx to include in proposed block + repeated bytes txs = 2; // ordered transaction data to include in block + bool exclusive = 3; // whether the block should include other transactions (from `mempool`) +} +``` + +`ProposeTx` would be called by before `mempool.Reap` at this +[line](https://github.com/tendermint/tendermint/blob/9cd9f3338bc80a12590631632c23c8dbe3ff5c34/consensus/state.go#L935). +Depending on whether `exclusive` is `true` or `false`, the proposed +transactions are then pushed on top of the transactions received from +`mempool.Reap`. + +### `DeliverTx` + +Since the list of `tx` received from `ProposeTx` are _not_ passed through `CheckTx`, +it is probably a good idea to provide a means of differentiatiating "internal" transactions +from user-generated ones, in case the app developer needs/wants to take extra measures to +ensure validity of the proposed transactions. + +Therefore, the `RequestDeliverTx` message should be changed to provide an additional flag, like so: + +``` +message RequestDeliverTx { + bytes tx = 1; + bool internal = 2; +} +``` + +Alternatively, an additional method `DeliverProposeTx` may be added as an accompanient to +`ProposeTx`. However, it is not clear at this stage if this additional overhead is necessary +to preserve consensus guarantees given that a simple flag may suffice for now. + +## Status + +Pending + +## Consequences + +### Positive + +- Tendermint ABCI apps will be able to function as minimally viable Plasma chains. +- It will thereby become possible to add an extension to `cosmos-sdk` to enable + ABCI apps to support both IBC and Plasma, maximising interop. +- ABCI apps will have great control and flexibility in managing blockchain state, + without having to resort to non-deterministic hacks and/or unsafe workarounds + +### Negative + +- Maintenance overhead of exposing additional ABCI method +- Potential security issues that may have been overlooked and must now be tested extensively + +### Neutral + +- ABCI developers must deal with increased (albeit nominal) API surface area. + +## References + +- [#1776 Plasma and "Internal" Transactions in ABCI Apps](https://github.com/tendermint/tendermint/issues/1776) +- [Minimal Viable Plasma](https://ethresear.ch/t/minimal-viable-plasma/426) +- [Plasma Cash: Plasma with much less per-user data checking](https://ethresear.ch/t/plasma-cash-plasma-with-much-less-per-user-data-checking/1298) diff --git a/docs/architecture/tendermint-core/adr-024-sign-bytes.md b/docs/architecture/tendermint-core/adr-024-sign-bytes.md new file mode 100644 index 0000000..a55e326 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-024-sign-bytes.md @@ -0,0 +1,234 @@ +# ADR 024: SignBytes and validator types in privval + +## Context + +Currently, the messages exchanged between tendermint and a (potentially remote) signer/validator, +namely votes, proposals, and heartbeats, are encoded as a JSON string +(e.g., via `Vote.SignBytes(...)`) and then +signed . JSON encoding is sub-optimal for both, hardware wallets +and for usage in ethereum smart contracts. Both is laid down in detail in [issue#1622]. + +Also, there are currently no differences between sign-request and -replies. Also, there is no possibility +for a remote signer to include an error code or message in case something went wrong. +The messages exchanged between tendermint and a remote signer currently live in +[privval/socket.go] and encapsulate the corresponding types in [types]. + + +[privval/socket.go]: https://github.com/tendermint/tendermint/blob/d419fffe18531317c28c29a292ad7d253f6cafdf/privval/socket.go#L496-L502 +[issue#1622]: https://github.com/tendermint/tendermint/issues/1622 +[types]: https://github.com/tendermint/tendermint/tree/main/types + + +## Decision + +- restructure vote, proposal, and heartbeat such that their encoding is easily parseable by +hardware devices and smart contracts using a binary encoding format ([amino] in this case) +- split up the messages exchanged between tendermint and remote signers into requests and +responses (see details below) +- include an error type in responses + +### Overview +``` ++--------------+ +----------------+ +| | SignXRequest | | +|Remote signer |<---------------------+ tendermint | +| (e.g. KMS) | | | +| +--------------------->| | ++--------------+ SignedXReply +----------------+ + + +SignXRequest { + x: X +} + +SignedXReply { + x: X + sig: Signature // []byte + err: Error{ + code: int + desc: string + } +} +``` + +TODO: Alternatively, the type `X` might directly include the signature. A lot of places expect a vote with a +signature and do not necessarily deal with "Replies". +Still exploring what would work best here. +This would look like (exemplified using X = Vote): +``` +Vote { + // all fields besides signature +} + +SignedVote { + Vote Vote + Signature []byte +} + +SignVoteRequest { + Vote Vote +} + +SignedVoteReply { + Vote SignedVote + Err Error +} +``` + +**Note:** There was a related discussion around including a fingerprint of, or, the whole public-key +into each sign-request to tell the signer which corresponding private-key to +use to sign the message. This is particularly relevant in the context of the KMS +but is currently not considered in this ADR. + + +[amino]: https://github.com/tendermint/go-amino/ + +### Vote + +As explained in [issue#1622] `Vote` will be changed to contain the following fields +(notation in protobuf-like syntax for easy readability): + +```proto +// vanilla protobuf / amino encoded +message Vote { + Version fixed32 + Height sfixed64 + Round sfixed32 + VoteType fixed32 + Timestamp Timestamp // << using protobuf definition + BlockID BlockID // << as already defined + ChainID string // at the end because length could vary a lot +} + +// this is an amino registered type; like currently privval.SignVoteMsg: +// registered with "tendermint/socketpv/SignVoteRequest" +message SignVoteRequest { + Vote vote +} + +// amino registered type +// registered with "tendermint/socketpv/SignedVoteReply" +message SignedVoteReply { + Vote Vote + Signature Signature + Err Error +} + +// we will use this type everywhere below +message Error { + Type uint // error code + Description string // optional description +} + +``` + +The `ChainID` gets moved into the vote message directly. Previously, it was injected +using the [Signable] interface method `SignBytes(chainID string) []byte`. Also, the +signature won't be included directly, only in the corresponding `SignedVoteReply` message. + +[Signable]: https://github.com/tendermint/tendermint/blob/d419fffe18531317c28c29a292ad7d253f6cafdf/types/signable.go#L9-L11 + +### Proposal + +```proto +// vanilla protobuf / amino encoded +message Proposal { + Height sfixed64 + Round sfixed32 + Timestamp Timestamp // << using protobuf definition + BlockPartsHeader PartSetHeader // as already defined + POLRound sfixed32 + POLBlockID BlockID // << as already defined +} + +// amino registered with "tendermint/socketpv/SignProposalRequest" +message SignProposalRequest { + Proposal proposal +} + +// amino registered with "tendermint/socketpv/SignProposalReply" +message SignProposalReply { + Prop Proposal + Sig Signature + Err Error // as defined above +} +``` + +### Heartbeat + +**TODO**: clarify if heartbeat also needs a fixed offset and update the fields accordingly: + +```proto +message Heartbeat { + ValidatorAddress Address + ValidatorIndex int + Height int64 + Round int + Sequence int +} +// amino registered with "tendermint/socketpv/SignHeartbeatRequest" +message SignHeartbeatRequest { + Hb Heartbeat +} + +// amino registered with "tendermint/socketpv/SignHeartbeatReply" +message SignHeartbeatReply { + Hb Heartbeat + Sig Signature + Err Error // as defined above +} + +``` + +## PubKey + +TBA - this needs further thoughts: e.g. what todo like in the case of the KMS which holds +several keys? How does it know with which key to reply? + +## SignBytes +`SignBytes` will not require a `ChainID` parameter: + +```golang +type Signable interface { + SignBytes() []byte +} + +``` +And the implementation for vote, heartbeat, proposal will look like: +```golang +// type T is one of vote, sign, proposal +func (tp *T) SignBytes() []byte { + bz, err := cdc.MarshalBinary(tp) + if err != nil { + panic(err) + } + return bz +} +``` + +## Status + +Partially Accepted + +## Consequences + + + +### Positive + +The most relevant positive effect is that the signing bytes can easily be parsed by a +hardware module and a smart contract. Besides that: + +- clearer separation between requests and responses +- added error messages enable better error handling + + +### Negative + +- relatively huge change / refactoring touching quite some code +- lot's of places assume a `Vote` with a signature included -> they will need to +- need to modify some interfaces + +### Neutral + +not even the swiss are neutral diff --git a/docs/architecture/tendermint-core/adr-025-commit.md b/docs/architecture/tendermint-core/adr-025-commit.md new file mode 100644 index 0000000..e6efc21 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-025-commit.md @@ -0,0 +1,150 @@ +# ADR 025 Commit + +## Context + +Currently the `Commit` structure contains a lot of potentially redundant or unnecessary data. +It contains a list of precommits from every validator, where the precommit +includes the whole `Vote` structure. Thus each of the commit height, round, +type, and blockID are repeated for every validator, and could be deduplicated, +leading to very significant savings in block size. + +``` +type Commit struct { + BlockID BlockID `json:"block_id"` + Precommits []*Vote `json:"precommits"` +} + +type Vote struct { + ValidatorAddress Address `json:"validator_address"` + ValidatorIndex int `json:"validator_index"` + Height int64 `json:"height"` + Round int `json:"round"` + Timestamp time.Time `json:"timestamp"` + Type byte `json:"type"` + BlockID BlockID `json:"block_id"` + Signature []byte `json:"signature"` +} +``` + +The original tracking issue for this is [#1648](https://github.com/tendermint/tendermint/issues/1648). +We have discussed replacing the `Vote` type in `Commit` with a new `CommitSig` +type, which includes at minimum the vote signature. The `Vote` type will +continue to be used in the consensus reactor and elsewhere. + +A primary question is what should be included in the `CommitSig` beyond the +signature. One current constraint is that we must include a timestamp, since +this is how we calculuate BFT time, though we may be able to change this [in the +future](https://github.com/tendermint/tendermint/issues/2840). + +Other concerns here include: + +- Validator Address [#3596](https://github.com/tendermint/tendermint/issues/3596) - + Should the CommitSig include the validator address? It is very convenient to + do so, but likely not necessary. This was also discussed in [#2226](https://github.com/tendermint/tendermint/issues/2226). +- Absent Votes [#3591](https://github.com/tendermint/tendermint/issues/3591) - + How to represent absent votes? Currently they are just present as `nil` in the + Precommits list, which is actually problematic for serialization +- Other BlockIDs [#3485](https://github.com/tendermint/tendermint/issues/3485) - + How to represent votes for nil and for other block IDs? We currently allow + votes for nil and votes for alternative block ids, but just ignore them + + +## Decision + +Deduplicate the fields and introduce `CommitSig`: + +``` +type Commit struct { + Height int64 + Round int + BlockID BlockID `json:"block_id"` + Precommits []CommitSig `json:"precommits"` +} + +type CommitSig struct { + BlockID BlockIDFlag + ValidatorAddress Address + Timestamp time.Time + Signature []byte +} + + +// indicate which BlockID the signature is for +type BlockIDFlag int + +const ( + BlockIDFlagAbsent BlockIDFlag = iota // vote is not included in the Commit.Precommits + BlockIDFlagCommit // voted for the Commit.BlockID + BlockIDFlagNil // voted for nil +) + +``` + +Re the concerns outlined in the context: + +**Timestamp**: Leave the timestamp for now. Removing it and switching to +proposer based time will take more analysis and work, and will be left for a +future breaking change. In the meantime, the concerns with the current approach to +BFT time [can be +mitigated](https://github.com/tendermint/tendermint/issues/2840#issuecomment-529122431). + +**ValidatorAddress**: we include it in the `CommitSig` for now. While this +does increase the block size unecessarily (20-bytes per validator), it has some ergonomic and debugging advantages: + +- `Commit` contains everything necessary to reconstruct `[]Vote`, and doesn't depend on additional access to a `ValidatorSet` +- Lite clients can check if they know the validators in a commit without + re-downloading the validator set +- Easy to see directly in a commit which validators signed what without having + to fetch the validator set + +If and when we change the `CommitSig` again, for instance to remove the timestamp, +we can reconsider whether the ValidatorAddress should be removed. + +**Absent Votes**: we include absent votes explicitly with no Signature or +Timestamp but with the ValidatorAddress. This should resolve the serialization +issues and make it easy to see which validator's votes failed to be included. + +**Other BlockIDs**: We use a single byte to indicate which blockID a `CommitSig` +is for. The only options are: + - `Absent` - no vote received from the this validator, so no signature + - `Nil` - validator voted Nil - meaning they did not see a polka in time + - `Commit` - validator voted for this block + +Note this means we don't allow votes for any other blockIDs. If a signature is +included in a commit, it is either for nil or the correct blockID. According to +the Tendermint protocol and assumptions, there is no way for a correct validator to +precommit for a conflicting blockID in the same round an actual commit was +created. This was the consensus from +[#3485](https://github.com/tendermint/tendermint/issues/3485) + +We may want to consider supporting other blockIDs later, as a way to capture +evidence that might be helpful. We should clarify if/when/how doing so would +actually help first. To implement it, we could change the `Commit.BlockID` +field to a slice, where the first entry is the correct block ID and the other +entries are other BlockIDs that validators precommited before. The BlockIDFlag +enum can be extended to represent these additional block IDs on a per block +basis. + +## Status + +Implemented + +## Consequences + +### Positive + +Removing the Type/Height/Round/Index and the BlockID saves roughly 80 bytes per precommit. +It varies because some integers are varint. The BlockID contains two 32-byte hashes an integer, +and the Height is 8-bytes. + +For a chain with 100 validators, that's up to 8kB in savings per block! + + +### Negative + +- Large breaking change to the block and commit structure +- Requires differentiating in code between the Vote and CommitSig objects, which may add some complexity (votes need to be reconstructed to be verified and gossiped) + +### Neutral + +- Commit.Precommits no longer contains nil values diff --git a/docs/architecture/tendermint-core/adr-026-general-merkle-proof.md b/docs/architecture/tendermint-core/adr-026-general-merkle-proof.md new file mode 100644 index 0000000..e70d825 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-026-general-merkle-proof.md @@ -0,0 +1,49 @@ +# ADR 026: General Merkle Proof + +## Context + +We are using raw `[]byte` for merkle proofs in `abci.ResponseQuery`. It makes hard to handle multilayer merkle proofs and general cases. Here, new interface `ProofOperator` is defined. The users can defines their own Merkle proof format and layer them easily. + +Goals: +- Layer Merkle proofs without decoding/reencoding +- Provide general way to chain proofs +- Make the proof format extensible, allowing thirdparty proof types + +## Decision + +### ProofOperator + +`type ProofOperator` is an interface for Merkle proofs. The definition is: + +```go +type ProofOperator interface { + Run([][]byte) ([][]byte, error) + GetKey() []byte + ProofOp() ProofOp +} +``` + +Since a proof can treat various data type, `Run()` takes `[][]byte` as the argument, not `[]byte`. For example, a range proof's `Run()` can take multiple key-values as its argument. It will then return the root of the tree for the further process, calculated with the input value. + +`ProofOperator` does not have to be a Merkle proof - it can be a function that transforms the argument for intermediate process e.g. prepending the length to the `[]byte`. + +### ProofOp + +`type ProofOp` is a protobuf message which is a triple of `Type string`, `Key []byte`, and `Data []byte`. `ProofOperator` and `ProofOp`are interconvertible, using `ProofOperator.ProofOp()` and `OpDecoder()`, where `OpDecoder` is a function that each proof type can register for their own encoding scheme. For example, we can add an byte for encoding scheme before the serialized proof, supporting JSON decoding. + +## Status + +Implemented + +## Consequences + +### Positive + +- Layering becomes easier (no encoding/decoding at each step) +- Thirdparty proof format is available + +### Negative + +- Larger size for abci.ResponseQuery +- Unintuitive proof chaining(it is not clear what `Run()` is doing) +- Additional codes for registering `OpDecoder`s diff --git a/docs/architecture/tendermint-core/adr-029-check-tx-consensus.md b/docs/architecture/tendermint-core/adr-029-check-tx-consensus.md new file mode 100644 index 0000000..2c56325 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-029-check-tx-consensus.md @@ -0,0 +1,127 @@ +# ADR 029: Check block txs before prevote + +## Changelog + +04-10-2018: Update with link to issue +[#2384](https://github.com/tendermint/tendermint/issues/2384) and reason for rejection +19-09-2018: Initial Draft + +## Context + +We currently check a tx's validity through 2 ways. + +1. Through checkTx in mempool connection. +2. Through deliverTx in consensus connection. + +The 1st is called when external tx comes in, so the node should be a proposer this time. The 2nd is called when external block comes in and reach the commit phase, the node doesn't need to be the proposer of the block, however it should check the txs in that block. + +In the 2nd situation, if there are many invalid txs in the block, it would be too late for all nodes to discover that most txs in the block are invalid, and we'd better not record invalid txs in the blockchain too. + +## Proposed solution + +Therefore, we should find a way to check the txs' validity before send out a prevote. Currently we have cs.isProposalComplete() to judge whether a block is complete. We can have + +``` +func (blockExec *BlockExecutor) CheckBlock(block *types.Block) error { + // check txs of block. + for _, tx := range block.Txs { + reqRes := blockExec.proxyApp.CheckTxAsync(tx) + reqRes.Wait() + if reqRes.Response == nil || reqRes.Response.GetCheckTx() == nil || reqRes.Response.GetCheckTx().Code != abci.CodeTypeOK { + return errors.Errorf("tx %v check failed. response: %v", tx, reqRes.Response) + } + } + return nil +} +``` + +such a method in BlockExecutor to check all txs' validity in that block. + +However, this method should not be implemented like that, because checkTx will share the same state used in mempool in the app. So we should define a new interface method checkBlock in Application to indicate it to use the same state as deliverTx. + +``` +type Application interface { + // Info/Query Connection + Info(RequestInfo) ResponseInfo // Return application info + Query(RequestQuery) ResponseQuery // Query for state + + // Mempool Connection + CheckTx(tx []byte) ResponseCheckTx // Validate a tx for the mempool + + // Consensus Connection + InitChain(RequestInitChain) ResponseInitChain // Initialize blockchain with validators and other info from TendermintCore + CheckBlock(RequestCheckBlock) ResponseCheckBlock + BeginBlock(RequestBeginBlock) ResponseBeginBlock // Signals the beginning of a block + DeliverTx(tx []byte) ResponseDeliverTx // Deliver a tx for full processing + EndBlock(RequestEndBlock) ResponseEndBlock // Signals the end of a block, returns changes to the validator set + Commit() ResponseCommit // Commit the state and return the application Merkle root hash +} +``` + +All app should implement that method. For example, counter: + +``` +func (app *CounterApplication) CheckBlock(block types.Request_CheckBlock) types.ResponseCheckBlock { + if app.serial { + app.originalTxCount = app.txCount //backup the txCount state + for _, tx := range block.CheckBlock.Block.Txs { + if len(tx) > 8 { + return types.ResponseCheckBlock{ + Code: code.CodeTypeEncodingError, + Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(tx))} + } + tx8 := make([]byte, 8) + copy(tx8[len(tx8)-len(tx):], tx) + txValue := binary.BigEndian.Uint64(tx8) + if txValue < uint64(app.txCount) { + return types.ResponseCheckBlock{ + Code: code.CodeTypeBadNonce, + Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)} + } + app.txCount++ + } + } + return types.ResponseCheckBlock{Code: code.CodeTypeOK} +} +``` + +In BeginBlock, the app should restore the state to the orignal state before checking the block: + +``` +func (app *CounterApplication) DeliverTx(tx []byte) types.ResponseDeliverTx { + if app.serial { + app.txCount = app.originalTxCount //restore the txCount state + } + app.txCount++ + return types.ResponseDeliverTx{Code: code.CodeTypeOK} +} +``` + +The txCount is like the nonce in ethermint, it should be restored when entering the deliverTx phase. While some operation like checking the tx signature needs not to be done again. So the deliverTx can focus on how a tx can be applied, ignoring the checking of the tx, because all the checking has already been done in the checkBlock phase before. + +An optional optimization is alter the deliverTx to deliverBlock. For the block has already been checked by checkBlock, so all the txs in it are valid. So the app can cache the block, and in the deliverBlock phase, it just needs to apply the block in the cache. This optimization can save network current in deliverTx. + + + +## Status + +Rejected + +## Decision + +Performance impact is considered too great. See [#2384](https://github.com/tendermint/tendermint/issues/2384) + +## Consequences + +### Positive + +- more robust to defend the adversary to propose a block full of invalid txs. + +### Negative + +- add a new interface method. app logic needs to adjust to appeal to it. +- sending all the tx data over the ABCI twice +- potentially redundant validations (eg. signature checks in both CheckBlock and + DeliverTx) + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-030-consensus-refactor.md b/docs/architecture/tendermint-core/adr-030-consensus-refactor.md new file mode 100644 index 0000000..0ee910c --- /dev/null +++ b/docs/architecture/tendermint-core/adr-030-consensus-refactor.md @@ -0,0 +1,458 @@ +# ADR 030: Consensus Refactor + +## Context + +One of the biggest challenges this project faces is to proof that the +implementations of the specifications are correct, much like we strive to +formaly verify our alogrithms and protocols we should work towards high +confidence about the correctness of our program code. One of those is the core +of Tendermint - Consensus - which currently resides in the `consensus` package. +Over time there has been high friction making changes to the package due to the +algorithm being scattered in a side-effectful container (the current +`ConsensusState`). In order to test the algorithm a large object-graph needs to +be set up and even than the non-deterministic parts of the container makes will +prevent high certainty. Where ideally we have a 1-to-1 representation of the +[spec](https://github.com/tendermint/spec), ready and easy to test for domain +experts. + +Addresses: + +- [#1495](https://github.com/tendermint/tendermint/issues/1495) +- [#1692](https://github.com/tendermint/tendermint/issues/1692) + +## Decision + +To remedy these issues we plan a gradual, non-invasive refactoring of the +`consensus` package. Starting of by isolating the consensus alogrithm into +a pure function and a finite state machine to address the most pressuring issue +of lack of confidence. Doing so while leaving the rest of the package in tact +and have follow-up optional changes to improve the sepration of concerns. + +### Implementation changes + +The core of Consensus can be modelled as a function with clear defined inputs: + +* `State` - data container for current round, height, etc. +* `Event`- significant events in the network + +producing clear outputs; + +* `State` - updated input +* `Message` - signal what actions to perform + +```go +type Event int + +const ( + EventUnknown Event = iota + EventProposal + Majority23PrevotesBlock + Majority23PrecommitBlock + Majority23PrevotesAny + Majority23PrecommitAny + TimeoutNewRound + TimeoutPropose + TimeoutPrevotes + TimeoutPrecommit +) + +type Message int + +const ( + MeesageUnknown Message = iota + MessageProposal + MessageVotes + MessageDecision +) + +type State struct { + height uint64 + round uint64 + step uint64 + lockedValue interface{} // TODO: Define proper type. + lockedRound interface{} // TODO: Define proper type. + validValue interface{} // TODO: Define proper type. + validRound interface{} // TODO: Define proper type. + // From the original notes: valid(v) + valid interface{} // TODO: Define proper type. + // From the original notes: proposer(h, r) + proposer interface{} // TODO: Define proper type. +} + +func Consensus(Event, State) (State, Message) { + // Consolidate implementation. +} +``` + +Tracking of relevant information to feed `Event` into the function and act on +the output is left to the `ConsensusExecutor` (formerly `ConsensusState`). + +Benefits for testing surfacing nicely as testing for a sequence of events +against algorithm could be as simple as the following example: + +``` go +func TestConsensusXXX(t *testing.T) { + type expected struct { + message Message + state State + } + + // Setup order of events, initial state and expectation. + var ( + events = []struct { + event Event + want expected + }{ + // ... + } + state = State{ + // ... + } + ) + + for _, e := range events { + sate, msg = Consensus(e.event, state) + + // Test message expectation. + if msg != e.want.message { + t.Fatalf("have %v, want %v", msg, e.want.message) + } + + // Test state expectation. + if !reflect.DeepEqual(state, e.want.state) { + t.Fatalf("have %v, want %v", state, e.want.state) + } + } +} +``` + + +## Consensus Executor + +## Consensus Core + +```go +type Event interface{} + +type EventNewHeight struct { + Height int64 + ValidatorId int +} + +type EventNewRound HeightAndRound + +type EventProposal struct { + Height int64 + Round int + Timestamp Time + BlockID BlockID + POLRound int + Sender int +} + +type Majority23PrevotesBlock struct { + Height int64 + Round int + BlockID BlockID +} + +type Majority23PrecommitBlock struct { + Height int64 + Round int + BlockID BlockID +} + +type HeightAndRound struct { + Height int64 + Round int +} + +type Majority23PrevotesAny HeightAndRound +type Majority23PrecommitAny HeightAndRound +type TimeoutPropose HeightAndRound +type TimeoutPrevotes HeightAndRound +type TimeoutPrecommit HeightAndRound + + +type Message interface{} + +type MessageProposal struct { + Height int64 + Round int + BlockID BlockID + POLRound int +} + +type VoteType int + +const ( + VoteTypeUnknown VoteType = iota + Prevote + Precommit +) + + +type MessageVote struct { + Height int64 + Round int + BlockID BlockID + Type VoteType +} + + +type MessageDecision struct { + Height int64 + Round int + BlockID BlockID +} + +type TriggerTimeout struct { + Height int64 + Round int + Duration Duration +} + + +type RoundStep int + +const ( + RoundStepUnknown RoundStep = iota + RoundStepPropose + RoundStepPrevote + RoundStepPrecommit + RoundStepCommit +) + +type State struct { + Height int64 + Round int + Step RoundStep + LockedValue BlockID + LockedRound int + ValidValue BlockID + ValidRound int + ValidatorId int + ValidatorSetSize int +} + +func proposer(height int64, round int) int {} +func getValue() BlockID {} + +func Consensus(event Event, state State) (State, Message, TriggerTimeout) { + msg = nil + timeout = nil + switch event := event.(type) { + case EventNewHeight: + if event.Height > state.Height { + state.Height = event.Height + state.Round = -1 + state.Step = RoundStepPropose + state.LockedValue = nil + state.LockedRound = -1 + state.ValidValue = nil + state.ValidRound = -1 + state.ValidatorId = event.ValidatorId + } + return state, msg, timeout + + case EventNewRound: + if event.Height == state.Height and event.Round > state.Round { + state.Round = eventRound + state.Step = RoundStepPropose + if proposer(state.Height, state.Round) == state.ValidatorId { + proposal = state.ValidValue + if proposal == nil { + proposal = getValue() + } + msg = MessageProposal { state.Height, state.Round, proposal, state.ValidRound } + } + timeout = TriggerTimeout { state.Height, state.Round, timeoutPropose(state.Round) } + } + return state, msg, timeout + + case EventProposal: + if event.Height == state.Height and event.Round == state.Round and + event.Sender == proposal(state.Height, state.Round) and state.Step == RoundStepPropose { + if event.POLRound >= state.LockedRound or event.BlockID == state.BlockID or state.LockedRound == -1 { + msg = MessageVote { state.Height, state.Round, event.BlockID, Prevote } + } + state.Step = RoundStepPrevote + } + return state, msg, timeout + + case TimeoutPropose: + if event.Height == state.Height and event.Round == state.Round and state.Step == RoundStepPropose { + msg = MessageVote { state.Height, state.Round, nil, Prevote } + state.Step = RoundStepPrevote + } + return state, msg, timeout + + case Majority23PrevotesBlock: + if event.Height == state.Height and event.Round == state.Round and state.Step >= RoundStepPrevote and event.Round > state.ValidRound { + state.ValidRound = event.Round + state.ValidValue = event.BlockID + if state.Step == RoundStepPrevote { + state.LockedRound = event.Round + state.LockedValue = event.BlockID + msg = MessageVote { state.Height, state.Round, event.BlockID, Precommit } + state.Step = RoundStepPrecommit + } + } + return state, msg, timeout + + case Majority23PrevotesAny: + if event.Height == state.Height and event.Round == state.Round and state.Step == RoundStepPrevote { + timeout = TriggerTimeout { state.Height, state.Round, timeoutPrevote(state.Round) } + } + return state, msg, timeout + + case TimeoutPrevote: + if event.Height == state.Height and event.Round == state.Round and state.Step == RoundStepPrevote { + msg = MessageVote { state.Height, state.Round, nil, Precommit } + state.Step = RoundStepPrecommit + } + return state, msg, timeout + + case Majority23PrecommitBlock: + if event.Height == state.Height { + state.Step = RoundStepCommit + state.LockedValue = event.BlockID + } + return state, msg, timeout + + case Majority23PrecommitAny: + if event.Height == state.Height and event.Round == state.Round { + timeout = TriggerTimeout { state.Height, state.Round, timeoutPrecommit(state.Round) } + } + return state, msg, timeout + + case TimeoutPrecommit: + if event.Height == state.Height and event.Round == state.Round { + state.Round = state.Round + 1 + } + return state, msg, timeout + } +} + +func ConsensusExecutor() { + proposal = nil + votes = HeightVoteSet { Height: 1 } + state = State { + Height: 1 + Round: 0 + Step: RoundStepPropose + LockedValue: nil + LockedRound: -1 + ValidValue: nil + ValidRound: -1 + } + + event = EventNewHeight {1, id} + state, msg, timeout = Consensus(event, state) + + event = EventNewRound {state.Height, 0} + state, msg, timeout = Consensus(event, state) + + if msg != nil { + send msg + } + + if timeout != nil { + trigger timeout + } + + for { + select { + case message := <- msgCh: + switch msg := message.(type) { + case MessageProposal: + + case MessageVote: + if msg.Height == state.Height { + newVote = votes.AddVote(msg) + if newVote { + switch msg.Type { + case Prevote: + prevotes = votes.Prevotes(msg.Round) + if prevotes.WeakCertificate() and msg.Round > state.Round { + event = EventNewRound { msg.Height, msg.Round } + state, msg, timeout = Consensus(event, state) + state = handleStateChange(state, msg, timeout) + } + + if blockID, ok = prevotes.TwoThirdsMajority(); ok and blockID != nil { + if msg.Round == state.Round and hasBlock(blockID) { + event = Majority23PrevotesBlock { msg.Height, msg.Round, blockID } + state, msg, timeout = Consensus(event, state) + state = handleStateChange(state, msg, timeout) + } + if proposal != nil and proposal.POLRound == msg.Round and hasBlock(blockID) { + event = EventProposal { + Height: state.Height + Round: state.Round + BlockID: blockID + POLRound: proposal.POLRound + Sender: message.Sender + } + state, msg, timeout = Consensus(event, state) + state = handleStateChange(state, msg, timeout) + } + } + + if prevotes.HasTwoThirdsAny() and msg.Round == state.Round { + event = Majority23PrevotesAny { msg.Height, msg.Round, blockID } + state, msg, timeout = Consensus(event, state) + state = handleStateChange(state, msg, timeout) + } + + case Precommit: + + } + } + } + case timeout := <- timeoutCh: + + case block := <- blockCh: + + } + } +} + +func handleStateChange(state, msg, timeout) State { + if state.Step == Commit { + state = ExecuteBlock(state.LockedValue) + } + if msg != nil { + send msg + } + if timeout != nil { + trigger timeout + } +} + +``` + +### Implementation roadmap + +* implement proposed implementation +* replace currently scattered calls in `ConsensusState` with calls to the new + `Consensus` function +* rename `ConsensusState` to `ConsensusExecutor` to avoid confusion +* propose design for improved separation and clear information flow between + `ConsensusExecutor` and `ConsensusReactor` + +## Status + +Draft. + +## Consequences + +### Positive + +- isolated implementation of the algorithm +- improved testability - simpler to proof correctness +- clearer separation of concerns - easier to reason + +### Negative + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-033-pubsub.md b/docs/architecture/tendermint-core/adr-033-pubsub.md new file mode 100644 index 0000000..f456649 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-033-pubsub.md @@ -0,0 +1,247 @@ +# ADR 033: pubsub 2.0 + +Author: Anton Kaliaev (@melekes) + +## Changelog + +02-10-2018: Initial draft + +16-01-2019: Second version based on our conversation with Jae + +17-01-2019: Third version explaining how new design solves current issues + +25-01-2019: Fourth version to treat buffered and unbuffered channels differently + +## Context + +Since the initial version of the pubsub, there's been a number of issues +raised: [#951], [#1879], [#1880]. Some of them are high-level issues questioning the +core design choices made. Others are minor and mostly about the interface of +`Subscribe()` / `Publish()` functions. + +### Sync vs Async + +Now, when publishing a message to subscribers, we can do it in a goroutine: + +_using channels for data transmission_ +```go +for each subscriber { + out := subscriber.outc + go func() { + out <- msg + } +} +``` + +_by invoking callback functions_ +```go +for each subscriber { + go subscriber.callbackFn() +} +``` + +This gives us greater performance and allows us to avoid "slow client problem" +(when other subscribers have to wait for a slow subscriber). A pool of +goroutines can be used to avoid uncontrolled memory growth. + +In certain cases, this is what you want. But in our case, because we need +strict ordering of events (if event A was published before B, the guaranteed +delivery order will be A -> B), we can't publish msg in a new goroutine every time. + +We can also have a goroutine per subscriber, although we'd need to be careful +with the number of subscribers. It's more difficult to implement as well + +unclear if we'll benefit from it (cause we'd be forced to create N additional +channels to distribute msg to these goroutines). + +### Non-blocking send + +There is also a question whenever we should have a non-blocking send. +Currently, sends are blocking, so publishing to one client can block on +publishing to another. This means a slow or unresponsive client can halt the +system. Instead, we can use a non-blocking send: + +```go +for each subscriber { + out := subscriber.outc + select { + case out <- msg: + default: + log("subscriber %v buffer is full, skipping...") + } +} +``` + +This fixes the "slow client problem", but there is no way for a slow client to +know if it had missed a message. We could return a second channel and close it +to indicate subscription termination. On the other hand, if we're going to +stick with blocking send, **devs must always ensure subscriber's handling code +does not block**, which is a hard task to put on their shoulders. + +The interim option is to run goroutines pool for a single message, wait for all +goroutines to finish. This will solve "slow client problem", but we'd still +have to wait `max(goroutine_X_time)` before we can publish the next message. + +### Channels vs Callbacks + +Yet another question is whether we should use channels for message transmission or +call subscriber-defined callback functions. Callback functions give subscribers +more flexibility - you can use mutexes in there, channels, spawn goroutines, +anything you really want. But they also carry local scope, which can result in +memory leaks and/or memory usage increase. + +Go channels are de-facto standard for carrying data between goroutines. + +### Why `Subscribe()` accepts an `out` channel? + +Because in our tests, we create buffered channels (cap: 1). Alternatively, we +can make capacity an argument and return a channel. + +## Decision + +### MsgAndTags + +Use a `MsgAndTags` struct on the subscription channel to indicate what tags the +msg matched. + +```go +type MsgAndTags struct { + Msg interface{} + Tags TagMap +} +``` + +### Subscription Struct + + +Change `Subscribe()` function to return a `Subscription` struct: + +```go +type Subscription struct { + // private fields +} + +func (s *Subscription) Out() <-chan MsgAndTags +func (s *Subscription) Canceled() <-chan struct{} +func (s *Subscription) Err() error +``` + +`Out()` returns a channel onto which messages and tags are published. +`Unsubscribe`/`UnsubscribeAll` does not close the channel to avoid clients from +receiving a nil message. + +`Canceled()` returns a channel that's closed when the subscription is terminated +and supposed to be used in a select statement. + +If the channel returned by `Canceled()` is not closed yet, `Err()` returns nil. +If the channel is closed, `Err()` returns a non-nil error explaining why: +`ErrUnsubscribed` if the subscriber choose to unsubscribe, +`ErrOutOfCapacity` if the subscriber is not pulling messages fast enough and the channel returned by `Out()` became full. +After `Err()` returns a non-nil error, successive calls to `Err() return the same error. + +```go +subscription, err := pubsub.Subscribe(...) +if err != nil { + // ... +} +for { +select { + case msgAndTags <- subscription.Out(): + // ... + case <-subscription.Canceled(): + return subscription.Err() +} +``` + +### Capacity and Subscriptions + +Make the `Out()` channel buffered (with capacity 1) by default. In most cases, we want to +terminate the slow subscriber. Only in rare cases, we want to block the pubsub +(e.g. when debugging consensus). This should lower the chances of the pubsub +being frozen. + +```go +// outCap can be used to set capacity of Out channel +// (1 by default, must be greater than 0). +Subscribe(ctx context.Context, clientID string, query Query, outCap... int) (Subscription, error) { +``` + +Use a different function for an unbuffered channel: + +```go +// Subscription uses an unbuffered channel. Publishing will block. +SubscribeUnbuffered(ctx context.Context, clientID string, query Query) (Subscription, error) { +``` + +SubscribeUnbuffered should not be exposed to users. + +### Blocking/Nonblocking + +The publisher should treat these kinds of channels separately. +It should block on unbuffered channels (for use with internal consensus events +in the consensus tests) and not block on the buffered ones. If a client is too +slow to keep up with it's messages, it's subscription is terminated: + +for each subscription { + out := subscription.outChan + if cap(out) == 0 { + // block on unbuffered channel + out <- msg + } else { + // don't block on buffered channels + select { + case out <- msg: + default: + // set the error, notify on the cancel chan + subscription.err = fmt.Errorf("client is too slow for msg) + close(subscription.cancelChan) + + // ... unsubscribe and close out + } + } +} + +### How this new design solves the current issues? + +[#951] ([#1880]): + +Because of non-blocking send, situation where we'll deadlock is not possible +anymore. If the client stops reading messages, it will be removed. + +[#1879]: + +MsgAndTags is used now instead of a plain message. + +### Future problems and their possible solutions + +[#2826] + +One question I am still pondering about: how to prevent pubsub from slowing +down consensus. We can increase the pubsub queue size (which is 0 now). Also, +it's probably a good idea to limit the total number of subscribers. + +This can be made automatically. Say we set queue size to 1000 and, when it's >= +80% full, refuse new subscriptions. + +## Status + +Implemented + +## Consequences + +### Positive + +- more idiomatic interface +- subscribers know what tags msg was published with +- subscribers aware of the reason their subscription was canceled + +### Negative + +- (since v1) no concurrency when it comes to publishing messages + +### Neutral + + +[#951]: https://github.com/tendermint/tendermint/issues/951 +[#1879]: https://github.com/tendermint/tendermint/issues/1879 +[#1880]: https://github.com/tendermint/tendermint/issues/1880 +[#2826]: https://github.com/tendermint/tendermint/issues/2826 diff --git a/docs/architecture/tendermint-core/adr-034-priv-validator-file-structure.md b/docs/architecture/tendermint-core/adr-034-priv-validator-file-structure.md new file mode 100644 index 0000000..83bee68 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-034-priv-validator-file-structure.md @@ -0,0 +1,72 @@ +# ADR 034: PrivValidator file structure + +## Changelog + +03-11-2018: Initial Draft + +## Context + +For now, the PrivValidator file `priv_validator.json` contains mutable and immutable parts. +Even in an insecure mode which does not encrypt private key on disk, it is reasonable to separate +the mutable part and immutable part. + +References: +[#1181](https://github.com/tendermint/tendermint/issues/1181) +[#2657](https://github.com/tendermint/tendermint/issues/2657) +[#2313](https://github.com/tendermint/tendermint/issues/2313) + +## Proposed Solution + +We can split mutable and immutable parts with two structs: +```go +// FilePVKey stores the immutable part of PrivValidator +type FilePVKey struct { + Address types.Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` + PrivKey crypto.PrivKey `json:"priv_key"` + + filePath string +} + +// FilePVState stores the mutable part of PrivValidator +type FilePVLastSignState struct { + Height int64 `json:"height"` + Round int `json:"round"` + Step int8 `json:"step"` + Signature []byte `json:"signature,omitempty"` + SignBytes cmn.HexBytes `json:"signbytes,omitempty"` + + filePath string + mtx sync.Mutex +} +``` + +Then we can combine `FilePVKey` with `FilePVLastSignState` and will get the original `FilePV`. + +```go +type FilePV struct { + Key FilePVKey + LastSignState FilePVLastSignState +} +``` + +As discussed, `FilePV` should be located in `config`, and `FilePVLastSignState` should be stored in `data`. The +store path of each file should be specified in `config.yml`. + +What we need to do next is changing the methods of `FilePV`. + +## Status + +Implemented + +## Consequences + +### Positive + +- separate the mutable and immutable of PrivValidator + +### Negative + +- need to add more config for file path + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-035-documentation.md b/docs/architecture/tendermint-core/adr-035-documentation.md new file mode 100644 index 0000000..8691b04 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-035-documentation.md @@ -0,0 +1,40 @@ +# ADR 035: Documentation + +Author: @zramsay (Zach Ramsay) + +## Changelog + +### November 2nd 2018 + +- initial write-up + +## Context + +The Tendermint documentation has undergone several changes until settling on the current model. Originally, the documentation was hosted on the website and had to be updated asynchronously from the code. Along with the other repositories requiring documentation, the whole stack moved to using Read The Docs to automatically generate, publish, and host the documentation. This, however, was insufficient; the RTD site had advertisement, it wasn't easily accessible to devs, didn't collect metrics, was another set of external links, etc. + +## Decision + +For two reasons, the decision was made to use VuePress: + +1) ability to get metrics (implemented on both Tendermint and SDK) +2) host the documentation on the website as a `/docs` endpoint. + +This is done while maintaining synchrony between the docs and code, i.e., the website is built whenever the docs are updated. + +## Status + +The two points above have been implemented; the `config.js` has a Google Analytics identifier and the documentation workflow has been up and running largely without problems for several months. Details about the documentation build & workflow can be found [here](../DOCS_README.md) + +## Consequences + +Because of the organizational seperation between Tendermint & Cosmos, there is a challenge of "what goes where" for certain aspects of documentation. + +### Positive + +This architecture is largely positive relative to prior docs arrangements. + +### Negative + +A significant portion of the docs automation / build process is in private repos with limited access/visibility to devs. However, these tasks are handled by the SRE team. + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-036-empty-blocks-abci.md b/docs/architecture/tendermint-core/adr-036-empty-blocks-abci.md new file mode 100644 index 0000000..7a851e2 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-036-empty-blocks-abci.md @@ -0,0 +1,38 @@ +# ADR 036: Empty Blocks via ABCI + +## Changelog + +- {date}: {changelog} + +## Context + +> This section contains all the context one needs to understand the current state, and why there is a problem. It should be as succinct as possible and introduce the high level idea behind the solution. + +## Decision + +> This section explains all of the details of the proposed solution, including implementation details. +> It should also describe affects / corollary items that may need to be changed as a part of this. +> If the proposed change will be large, please also indicate a way to do the change to maximize ease of review. +> (e.g. the optimal split of things to do between separate PR's) + +## Status + +> A decision may be "proposed" if it hasn't been agreed upon yet, or "accepted" once it is agreed upon. If a later ADR changes or reverses a decision, it may be marked as "deprecated" or "superseded" with a reference to its replacement. + +{Deprecated|Proposed|Accepted|Declined} + +## Consequences + +> This section describes the consequences, after applying the decision. All consequences should be summarized here, not just the "positive" ones. + +### Positive + +### Negative + +### Neutral + +## References + +> Are there any relevant PR comments, issues that led up to this, or articles referenced for why we made the given design choice? If so link them here! + +- {reference link} diff --git a/docs/architecture/tendermint-core/adr-037-deliver-block.md b/docs/architecture/tendermint-core/adr-037-deliver-block.md new file mode 100644 index 0000000..c5a225f --- /dev/null +++ b/docs/architecture/tendermint-core/adr-037-deliver-block.md @@ -0,0 +1,100 @@ +# ADR 037: Deliver Block + +Author: Daniil Lashin (@danil-lashin) + +## Changelog + +13-03-2019: Initial draft + +## Context + +Initial conversation: https://github.com/tendermint/tendermint/issues/2901 + +Some applications can handle transactions in parallel, or at least some +part of tx processing can be parallelized. Now it is not possible for developer +to execute txs in parallel because Tendermint delivers them consequentially. + +## Decision + +Now Tendermint have `BeginBlock`, `EndBlock`, `Commit`, `DeliverTx` steps +while executing block. This doc proposes merging this steps into one `DeliverBlock` +step. It will allow developers of applications to decide how they want to +execute transactions (in parallel or consequentially). Also it will simplify and +speed up communications between application and Tendermint. + +As @jaekwon [mentioned](https://github.com/tendermint/tendermint/issues/2901#issuecomment-477746128) +in discussion not all application will benefit from this solution. In some cases, +when application handles transaction consequentially, it way slow down the blockchain, +because it need to wait until full block is transmitted to application to start +processing it. Also, in the case of complete change of ABCI, we need to force all the apps +to change their implementation completely. That's why I propose to introduce one more ABCI +type. + +# Implementation Changes + +In addition to default application interface which now have this structure + +```go +type Application interface { + // Info and Mempool methods... + + // Consensus Connection + InitChain(RequestInitChain) ResponseInitChain // Initialize blockchain with validators and other info from TendermintCore + BeginBlock(RequestBeginBlock) ResponseBeginBlock // Signals the beginning of a block + DeliverTx(tx []byte) ResponseDeliverTx // Deliver a tx for full processing + EndBlock(RequestEndBlock) ResponseEndBlock // Signals the end of a block, returns changes to the validator set + Commit() ResponseCommit // Commit the state and return the application Merkle root hash +} +``` + +this doc proposes to add one more: + +```go +type Application interface { + // Info and Mempool methods... + + // Consensus Connection + InitChain(RequestInitChain) ResponseInitChain // Initialize blockchain with validators and other info from TendermintCore + DeliverBlock(RequestDeliverBlock) ResponseDeliverBlock // Deliver full block + Commit() ResponseCommit // Commit the state and return the application Merkle root hash +} + +type RequestDeliverBlock struct { + Hash []byte + Header Header + Txs Txs + LastCommitInfo LastCommitInfo + ByzantineValidators []Evidence +} + +type ResponseDeliverBlock struct { + ValidatorUpdates []ValidatorUpdate + ConsensusParamUpdates *ConsensusParams + Tags []kv.Pair + TxResults []ResponseDeliverTx +} + +``` + +Also, we will need to add new config param, which will specify what kind of ABCI application uses. +For example, it can be `abci_type`. Then we will have 2 types: +- `advanced` - current ABCI +- `simple` - proposed implementation + +## Status + +In review + +## Consequences + +### Positive + +- much simpler introduction and tutorials for new developers (instead of implementing 5 methods whey +will need to implement only 3) +- txs can be handled in parallel +- simpler interface +- faster communications between Tendermint and application + +### Negative + +- Tendermint should now support 2 kinds of ABCI diff --git a/docs/architecture/tendermint-core/adr-038-non-zero-start-height.md b/docs/architecture/tendermint-core/adr-038-non-zero-start-height.md new file mode 100644 index 0000000..871cd40 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-038-non-zero-start-height.md @@ -0,0 +1,38 @@ +# ADR 038: Non-zero start height + +## Changelog + +- {date}: {changelog} + +## Context + +> This section contains all the context one needs to understand the current state, and why there is a problem. It should be as succinct as possible and introduce the high level idea behind the solution. + +## Decision + +> This section explains all of the details of the proposed solution, including implementation details. +> It should also describe affects / corollary items that may need to be changed as a part of this. +> If the proposed change will be large, please also indicate a way to do the change to maximize ease of review. +> (e.g. the optimal split of things to do between separate PR's) + +## Status + +> A decision may be "proposed" if it hasn't been agreed upon yet, or "accepted" once it is agreed upon. If a later ADR changes or reverses a decision, it may be marked as "deprecated" or "superseded" with a reference to its replacement. + +{Deprecated|Proposed|Accepted|Declined} + +## Consequences + +> This section describes the consequences, after applying the decision. All consequences should be summarized here, not just the "positive" ones. + +### Positive + +### Negative + +### Neutral + +## References + +> Are there any relevant PR comments, issues that led up to this, or articles referenced for why we made the given design choice? If so link them here! + +- {reference link} diff --git a/docs/architecture/tendermint-core/adr-039-peer-behaviour.md b/docs/architecture/tendermint-core/adr-039-peer-behaviour.md new file mode 100644 index 0000000..919713c --- /dev/null +++ b/docs/architecture/tendermint-core/adr-039-peer-behaviour.md @@ -0,0 +1,159 @@ +# ADR 039: Peer Behaviour Interface + +## Changelog +* 07-03-2019: Initial draft +* 14-03-2019: Updates from feedback + +## Context + +The responsibility for signaling and acting upon peer behavior lacks a single +owning component and is heavily coupled with the network stack[1](#references). Reactors +maintain a reference to the `p2p.Switch` which they use to call +`switch.StopPeerForError(...)` when a peer misbehaves and +`switch.MarkAsGood(...)` when a peer contributes in some meaningful way. +While the switch handles `StopPeerForError` internally, the `MarkAsGood` +method delegates to another component, `p2p.AddrBook`. This scheme of delegation +across Switch obscures the responsibility for handling peer behavior +and ties up the reactors in a larger dependency graph when testing. + +## Decision + +Introduce a `PeerBehaviour` interface and concrete implementations which +provide methods for reactors to signal peer behavior without direct +coupling `p2p.Switch`. Introduce a ErrorBehaviourPeer to provide +concrete reasons for stopping peers. Introduce GoodBehaviourPeer to provide +concrete ways in which a peer contributes. + +### Implementation Changes + +PeerBehaviour then becomes an interface for signaling peer errors as well +as for marking peers as `good`. + +```go +type PeerBehaviour interface { + Behaved(peer Peer, reason GoodBehaviourPeer) + Errored(peer Peer, reason ErrorBehaviourPeer) +} +``` + +Instead of signaling peers to stop with arbitrary reasons: +`reason interface{}` + +We introduce a concrete error type ErrorBehaviourPeer: +```go +type ErrorBehaviourPeer int + +const ( + ErrorBehaviourUnknown = iota + ErrorBehaviourBadMessage + ErrorBehaviourMessageOutofOrder + ... +) +``` + +To provide additional information on the ways a peer contributed, we introduce +the GoodBehaviourPeer type. + +```go +type GoodBehaviourPeer int + +const ( + GoodBehaviourVote = iota + GoodBehaviourBlockPart + ... +) +``` + +As a first iteration we provide a concrete implementation which wraps +the switch: +```go +type SwitchedPeerBehaviour struct { + sw *Switch +} + +func (spb *SwitchedPeerBehaviour) Errored(peer Peer, reason ErrorBehaviourPeer) { + spb.sw.StopPeerForError(peer, reason) +} + +func (spb *SwitchedPeerBehaviour) Behaved(peer Peer, reason GoodBehaviourPeer) { + spb.sw.MarkPeerAsGood(peer) +} + +func NewSwitchedPeerBehaviour(sw *Switch) *SwitchedPeerBehaviour { + return &SwitchedPeerBehaviour{ + sw: sw, + } +} +``` + +Reactors, which are often difficult to unit test[2](#references) could use an implementation which exposes the signals produced by the reactor in +manufactured scenarios: + +```go +type ErrorBehaviours map[Peer][]ErrorBehaviourPeer +type GoodBehaviours map[Peer][]GoodBehaviourPeer + +type StorePeerBehaviour struct { + eb ErrorBehaviours + gb GoodBehaviours +} + +func NewStorePeerBehaviour() *StorePeerBehaviour{ + return &StorePeerBehaviour{ + eb: make(ErrorBehaviours), + gb: make(GoodBehaviours), + } +} + +func (spb StorePeerBehaviour) Errored(peer Peer, reason ErrorBehaviourPeer) { + if _, ok := spb.eb[peer]; !ok { + spb.eb[peer] = []ErrorBehaviours{reason} + } else { + spb.eb[peer] = append(spb.eb[peer], reason) + } +} + +func (mpb *StorePeerBehaviour) GetErrored() ErrorBehaviours { + return mpb.eb +} + + +func (spb StorePeerBehaviour) Behaved(peer Peer, reason GoodBehaviourPeer) { + if _, ok := spb.gb[peer]; !ok { + spb.gb[peer] = []GoodBehaviourPeer{reason} + } else { + spb.gb[peer] = append(spb.gb[peer], reason) + } +} + +func (spb *StorePeerBehaviour) GetBehaved() GoodBehaviours { + return spb.gb +} +``` + +## Status + +Accepted + +## Consequences + +### Positive + + * De-couple signaling from acting upon peer behavior. + * Reduce the coupling of reactors and the Switch and the network + stack + * The responsibility of managing peer behavior can be migrated to + a single component instead of split between the switch and the + address book. + +### Negative + + * The first iteration will simply wrap the Switch and introduce a + level of indirection. + +### Neutral + +## References + +1. Issue [#2067](https://github.com/tendermint/tendermint/issues/2067): P2P Refactor +2. PR: [#3506](https://github.com/tendermint/tendermint/pull/3506): ADR 036: Blockchain Reactor Refactor diff --git a/docs/architecture/tendermint-core/adr-040-blockchain-reactor-refactor.md b/docs/architecture/tendermint-core/adr-040-blockchain-reactor-refactor.md new file mode 100644 index 0000000..ca8df5c --- /dev/null +++ b/docs/architecture/tendermint-core/adr-040-blockchain-reactor-refactor.md @@ -0,0 +1,534 @@ +# ADR 040: Blockchain Reactor Refactor + +## Changelog + +19-03-2019: Initial draft + +## Context + +The Blockchain Reactor's high level responsibility is to enable peers who are far behind the current state of the +blockchain to quickly catch up by downloading many blocks in parallel from its peers, verifying block correctness, and +executing them against the ABCI application. We call the protocol executed by the Blockchain Reactor `fast-sync`. +The current architecture diagram of the blockchain reactor can be found here: + +![Blockchain Reactor Architecture Diagram](img/bc-reactor.png) + +The current architecture consists of dozens of routines and it is tightly depending on the `Switch`, making writing +unit tests almost impossible. Current tests require setting up complex dependency graphs and dealing with concurrency. +Note that having dozens of routines is in this case overkill as most of the time routines sits idle waiting for +something to happen (message to arrive or timeout to expire). Due to dependency on the `Switch`, testing relatively +complex network scenarios and failures (for example adding and removing peers) is very complex tasks and frequently lead +to complex tests with not deterministic behavior ([#3400]). Impossibility to write proper tests makes confidence in +the code low and this resulted in several issues (some are fixed in the meantime and some are still open): +[#3400], [#2897], [#2896], [#2699], [#2888], [#2457], [#2622], [#2026]. + +## Decision + +To remedy these issues we plan a major refactor of the blockchain reactor. The proposed architecture is largely inspired +by ADR-30 and is presented on the following diagram: +![Blockchain Reactor Refactor Diagram](img/bc-reactor-refactor.png) + +We suggest a concurrency architecture where the core algorithm (we call it `Controller`) is extracted into a finite +state machine. The active routine of the reactor is called `Executor` and is responsible for receiving and sending +messages from/to peers and triggering timeouts. What messages should be sent and timeouts triggered is determined mostly +by the `Controller`. The exception is `Peer Heartbeat` mechanism which is `Executor` responsibility. The heartbeat +mechanism is used to remove slow and unresponsive peers from the peer list. Writing of unit tests is simpler with +this architecture as most of the critical logic is part of the `Controller` function. We expect that simpler concurrency +architecture will not have significant negative effect on the performance of this reactor (to be confirmed by +experimental evaluation). + + +### Implementation changes + +We assume the following system model for "fast sync" protocol: + +* a node is connected to a random subset of all nodes that represents its peer set. Some nodes are correct and some + might be faulty. We don't make assumptions about ratio of faulty nodes, i.e., it is possible that all nodes in some + peer set are faulty. +* we assume that communication between correct nodes is synchronous, i.e., if a correct node `p` sends a message `m` to + a correct node `q` at time `t`, then `q` will receive message the latest at time `t+Delta` where `Delta` is a system + parameter that is known by network participants. `Delta` is normally chosen to be an order of magnitude higher than + the real communication delay (maximum) between correct nodes. Therefore if a correct node `p` sends a request message + to a correct node `q` at time `t` and there is no the corresponding reply at time `t + 2*Delta`, then `p` can assume + that `q` is faulty. Note that the network assumptions for the consensus reactor are different (we assume partially + synchronous model there). + +The requirements for the "fast sync" protocol are formally specified as follows: + +- `Correctness`: If a correct node `p` is connected to a correct node `q` for a long enough period of time, then `p` +- will eventually download all requested blocks from `q`. +- `Termination`: If a set of peers of a correct node `p` is stable (no new nodes are added to the peer set of `p`) for +- a long enough period of time, then protocol eventually terminates. +- `Fairness`: A correct node `p` sends requests for blocks to all peers from its peer set. + +As explained above, the `Executor` is responsible for sending and receiving messages that are part of the `fast-sync` +protocol. The following messages are exchanged as part of `fast-sync` protocol: + +``` go +type Message int +const ( + MessageUnknown Message = iota + MessageStatusRequest + MessageStatusResponse + MessageBlockRequest + MessageBlockResponse +) +``` +`MessageStatusRequest` is sent periodically to all peers as a request for a peer to provide its current height. It is +part of the `Peer Heartbeat` mechanism and a failure to respond timely to this message results in a peer being removed +from the peer set. Note that the `Peer Heartbeat` mechanism is used only while a peer is in `fast-sync` mode. We assume +here existence of a mechanism that gives node a possibility to inform its peers that it is in the `fast-sync` mode. + +``` go +type MessageStatusRequest struct { + SeqNum int64 // sequence number of the request +} +``` +`MessageStatusResponse` is sent as a response to `MessageStatusRequest` to inform requester about the peer current +height. + +``` go +type MessageStatusResponse struct { + SeqNum int64 // sequence number of the corresponding request + Height int64 // current peer height +} +``` + +`MessageBlockRequest` is used to make a request for a block and the corresponding commit certificate at a given height. + +``` go +type MessageBlockRequest struct { + Height int64 +} +``` + +`MessageBlockResponse` is a response for the corresponding block request. In addition to providing the block and the +corresponding commit certificate, it contains also a current peer height. + +``` go +type MessageBlockResponse struct { + Height int64 + Block Block + Commit Commit + PeerHeight int64 +} +``` + +In addition to sending and receiving messages, and `HeartBeat` mechanism, controller is also managing timeouts +that are triggered upon `Controller` request. `Controller` is then informed once a timeout expires. + +``` go +type TimeoutTrigger int +const ( + TimeoutUnknown TimeoutTrigger = iota + TimeoutResponseTrigger + TimeoutTerminationTrigger +) +``` + +The `Controller` can be modelled as a function with clearly defined inputs: + +* `State` - current state of the node. Contains data about connected peers and its behavior, pending requests, +* received blocks, etc. +* `Event` - significant events in the network. + +producing clear outputs: + +* `State` - updated state of the node, +* `MessageToSend` - signal what message to send and to which peer +* `TimeoutTrigger` - signal that timeout should be triggered. + + +We consider the following `Event` types: + +``` go +type Event int +const ( + EventUnknown Event = iota + EventStatusReport + EventBlockRequest + EventBlockResponse + EventRemovePeer + EventTimeoutResponse + EventTimeoutTermination +) +``` + +`EventStatusResponse` event is generated once `MessageStatusResponse` is received by the `Executor`. + +``` go +type EventStatusReport struct { + PeerID ID + Height int64 +} +``` + +`EventBlockRequest` event is generated once `MessageBlockRequest` is received by the `Executor`. + +``` go +type EventBlockRequest struct { + Height int64 + PeerID p2p.ID +} +``` +`EventBlockResponse` event is generated upon reception of `MessageBlockResponse` message by the `Executor`. + +``` go +type EventBlockResponse struct { + Height int64 + Block Block + Commit Commit + PeerID ID + PeerHeight int64 +} +``` +`EventRemovePeer` is generated by `Executor` to signal that the connection to a peer is closed due to peer misbehavior. + +``` go +type EventRemovePeer struct { + PeerID ID +} +``` +`EventTimeoutResponse` is generated by `Executor` to signal that a timeout triggered by `TimeoutResponseTrigger` has +expired. + +``` go +type EventTimeoutResponse struct { + PeerID ID + Height int64 +} +``` +`EventTimeoutTermination` is generated by `Executor` to signal that a timeout triggered by `TimeoutTerminationTrigger` +has expired. + +``` go +type EventTimeoutTermination struct { + Height int64 +} +``` + +`MessageToSend` is just a wrapper around `Message` type that contains id of the peer to which message should be sent. + +``` go +type MessageToSend struct { + PeerID ID + Message Message +} +``` + +The Controller state machine can be in two modes: `ModeFastSync` when +a node is trying to catch up with the network by downloading committed blocks, +and `ModeConsensus` in which it executes Tendermint consensus protocol. We +consider that `fast sync` mode terminates once the Controller switch to +`ModeConsensus`. + +``` go +type Mode int +const ( + ModeUnknown Mode = iota + ModeFastSync + ModeConsensus +) +``` +`Controller` is managing the following state: + +``` go +type ControllerState struct { + Height int64 // the first block that is not committed + Mode Mode // mode of operation + PeerMap map[ID]PeerStats // map of peer IDs to peer statistics + MaxRequestPending int64 // maximum height of the pending requests + FailedRequests []int64 // list of failed block requests + PendingRequestsNum int // total number of pending requests + Store []BlockInfo // contains list of downloaded blocks + Executor BlockExecutor // store, verify and executes blocks +} +``` + +`PeerStats` data structure keeps for every peer its current height and a list of pending requests for blocks. + +``` go +type PeerStats struct { + Height int64 + PendingRequest int64 // a request sent to this peer +} +``` + +`BlockInfo` data structure is used to store information (as part of block store) about downloaded blocks: from what peer + a block and the corresponding commit certificate are received. +``` go +type BlockInfo struct { + Block Block + Commit Commit + PeerID ID // a peer from which we received the corresponding Block and Commit +} +``` + +The `Controller` is initialized by providing an initial height (`startHeight`) from which it will start downloading +blocks from peers and the current state of the `BlockExecutor`. + +``` go +func NewControllerState(startHeight int64, executor BlockExecutor) ControllerState { + state = ControllerState {} + state.Height = startHeight + state.Mode = ModeFastSync + state.MaxRequestPending = startHeight - 1 + state.PendingRequestsNum = 0 + state.Executor = executor + initialize state.PeerMap, state.FailedRequests and state.Store to empty data structures + return state +} +``` + +The core protocol logic is given with the following function: + +``` go +func handleEvent(state ControllerState, event Event) (ControllerState, Message, TimeoutTrigger, Error) { + msg = nil + timeout = nil + error = nil + + switch state.Mode { + case ModeConsensus: + switch event := event.(type) { + case EventBlockRequest: + msg = createBlockResponseMessage(state, event) + return state, msg, timeout, error + default: + error = "Only respond to BlockRequests while in ModeConsensus!" + return state, msg, timeout, error + } + + case ModeFastSync: + switch event := event.(type) { + case EventBlockRequest: + msg = createBlockResponseMessage(state, event) + return state, msg, timeout, error + + case EventStatusResponse: + return handleEventStatusResponse(event, state) + + case EventRemovePeer: + return handleEventRemovePeer(event, state) + + case EventBlockResponse: + return handleEventBlockResponse(event, state) + + case EventResponseTimeout: + return handleEventResponseTimeout(event, state) + + case EventTerminationTimeout: + // Termination timeout is triggered in case of empty peer set and in case there are no pending requests. + // If this timeout expires and in the meantime no new peers are added or new pending requests are made + // then `fast-sync` mode terminates by switching to `ModeConsensus`. + // Note that termination timeout should be higher than the response timeout. + if state.Height == event.Height && state.PendingRequestsNum == 0 { state.State = ConsensusMode } + return state, msg, timeout, error + + default: + error = "Received unknown event type!" + return state, msg, timeout, error + } + } +} +``` + +``` go +func createBlockResponseMessage(state ControllerState, event BlockRequest) MessageToSend { + msgToSend = nil + if _, ok := state.PeerMap[event.PeerID]; !ok { peerStats = PeerStats{-1, -1} } + if state.Executor.ContainsBlockWithHeight(event.Height) && event.Height > peerStats.Height { + peerStats = event.Height + msg = BlockResponseMessage{ + Height: event.Height, + Block: state.Executor.getBlock(eventHeight), + Commit: state.Executor.getCommit(eventHeight), + PeerID: event.PeerID, + CurrentHeight: state.Height - 1, + } + msgToSend = MessageToSend { event.PeerID, msg } + } + state.PeerMap[event.PeerID] = peerStats + return msgToSend +} +``` + +``` go +func handleEventStatusResponse(event EventStatusResponse, state ControllerState) (ControllerState, MessageToSend, TimeoutTrigger, Error) { + if _, ok := state.PeerMap[event.PeerID]; !ok { + peerStats = PeerStats{ -1, -1 } + } else { + peerStats = state.PeerMap[event.PeerID] + } + + if event.Height > peerStats.Height { peerStats.Height = event.Height } + // if there are no pending requests for this peer, try to send him a request for block + if peerStats.PendingRequest == -1 { + msg = createBlockRequestMessages(state, event.PeerID, peerStats.Height) + // msg is nil if no request for block can be made to a peer at this point in time + if msg != nil { + peerStats.PendingRequests = msg.Height + state.PendingRequestsNum++ + // when a request for a block is sent to a peer, a response timeout is triggered. If no corresponding block is sent by the peer + // during response timeout period, then the peer is considered faulty and is removed from the peer set. + timeout = ResponseTimeoutTrigger{ msg.PeerID, msg.Height, PeerTimeout } + } else if state.PendingRequestsNum == 0 { + // if there are no pending requests and no new request can be placed to the peer, termination timeout is triggered. + // If termination timeout expires and we are still at the same height and there are no pending requests, the "fast-sync" + // mode is finished and we switch to `ModeConsensus`. + timeout = TerminationTimeoutTrigger{ state.Height, TerminationTimeout } + } + } + state.PeerMap[event.PeerID] = peerStats + return state, msg, timeout, error +} +``` + +``` go +func handleEventRemovePeer(event EventRemovePeer, state ControllerState) (ControllerState, MessageToSend, TimeoutTrigger, Error) { + if _, ok := state.PeerMap[event.PeerID]; ok { + pendingRequest = state.PeerMap[event.PeerID].PendingRequest + // if a peer is removed from the peer set, its pending request is declared failed and added to the `FailedRequests` list + // so it can be retried. + if pendingRequest != -1 { + add(state.FailedRequests, pendingRequest) + } + state.PendingRequestsNum-- + delete(state.PeerMap, event.PeerID) + // if the peer set is empty after removal of this peer then termination timeout is triggered. + if state.PeerMap.isEmpty() { + timeout = TerminationTimeoutTrigger{ state.Height, TerminationTimeout } + } + } else { error = "Removing unknown peer!" } + return state, msg, timeout, error +``` + +``` go +func handleEventBlockResponse(event EventBlockResponse, state ControllerState) (ControllerState, MessageToSend, TimeoutTrigger, Error) + if state.PeerMap[event.PeerID] { + peerStats = state.PeerMap[event.PeerID] + // when expected block arrives from a peer, it is added to the store so it can be verified and if correct executed after. + if peerStats.PendingRequest == event.Height { + peerStats.PendingRequest = -1 + state.PendingRequestsNum-- + if event.PeerHeight > peerStats.Height { peerStats.Height = event.PeerHeight } + state.Store[event.Height] = BlockInfo{ event.Block, event.Commit, event.PeerID } + // blocks are verified sequentially so adding a block to the store does not mean that it will be immediately verified + // as some of the previous blocks might be missing. + state = verifyBlocks(state) // it can lead to event.PeerID being removed from peer list + if _, ok := state.PeerMap[event.PeerID]; ok { + // we try to identify new request for a block that can be asked to the peer + msg = createBlockRequestMessage(state, event.PeerID, peerStats.Height) + if msg != nil { + peerStats.PendingRequests = msg.Height + state.PendingRequestsNum++ + // if request for block is made, response timeout is triggered + timeout = ResponseTimeoutTrigger{ msg.PeerID, msg.Height, PeerTimeout } + } else if state.PeerMap.isEmpty() || state.PendingRequestsNum == 0 { + // if the peer map is empty (the peer can be removed as block verification failed) or there are no pending requests + // termination timeout is triggered. + timeout = TerminationTimeoutTrigger{ state.Height, TerminationTimeout } + } + } + } else { error = "Received Block from wrong peer!" } + } else { error = "Received Block from unknown peer!" } + + state.PeerMap[event.PeerID] = peerStats + return state, msg, timeout, error +} +``` + +``` go +func handleEventResponseTimeout(event, state) { + if _, ok := state.PeerMap[event.PeerID]; ok { + peerStats = state.PeerMap[event.PeerID] + // if a response timeout expires and the peer hasn't delivered the block, the peer is removed from the peer list and + // the request is added to the `FailedRequests` so the block can be downloaded from other peer + if peerStats.PendingRequest == event.Height { + add(state.FailedRequests, pendingRequest) + delete(state.PeerMap, event.PeerID) + state.PendingRequestsNum-- + // if peer set is empty, then termination timeout is triggered + if state.PeerMap.isEmpty() { + timeout = TimeoutTrigger{ state.Height, TerminationTimeout } + } + } + } + return state, msg, timeout, error +} +``` + +``` go +func createBlockRequestMessage(state ControllerState, peerID ID, peerHeight int64) MessageToSend { + msg = nil + blockHeight = -1 + r = find request in state.FailedRequests such that r <= peerHeight // returns `nil` if there are no such request + // if there is a height in failed requests that can be downloaded from the peer send request to it + if r != nil { + blockNumber = r + delete(state.FailedRequests, r) + } else if state.MaxRequestPending < peerHeight { + // if height of the maximum pending request is smaller than peer height, then ask peer for next block + state.MaxRequestPending++ + blockHeight = state.MaxRequestPending // increment state.MaxRequestPending and then return the new value + } + + if blockHeight > -1 { msg = MessageToSend { peerID, MessageBlockRequest { blockHeight } } + return msg +} +``` + +``` go +func verifyBlocks(state State) State { + done = false + for !done { + block = state.Store[height] + if block != nil { + verified = verify block.Block using block.Commit // return `true` is verification succeed, 'false` otherwise + + if verified { + block.Execute() // executing block is costly operation so it might make sense executing asynchronously + state.Height++ + } else { + // if block verification failed, then it is added to `FailedRequests` and the peer is removed from the peer set + add(state.FailedRequests, height) + state.Store[height] = nil + if _, ok := state.PeerMap[block.PeerID]; ok { + pendingRequest = state.PeerMap[block.PeerID].PendingRequest + // if there is a pending request sent to the peer that is just to be removed from the peer set, add it to `FailedRequests` + if pendingRequest != -1 { + add(state.FailedRequests, pendingRequest) + state.PendingRequestsNum-- + } + delete(state.PeerMap, event.PeerID) + } + done = true + } + } else { done = true } + } + return state +} +``` + +In the proposed architecture `Controller` is not active task, i.e., it is being called by the `Executor`. Depending on +the return values returned by `Controller`,`Executor` will send a message to some peer (`msg` != nil), trigger a +timeout (`timeout` != nil) or deal with errors (`error` != nil). +In case a timeout is triggered, it will provide as an input to `Controller` the corresponding timeout event once +timeout expires. + + +## Status + +Draft. + +## Consequences + +### Positive + +- isolated implementation of the algorithm +- improved testability - simpler to prove correctness +- clearer separation of concerns - easier to reason + +### Negative + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-041-proposer-selection-via-abci.md b/docs/architecture/tendermint-core/adr-041-proposer-selection-via-abci.md new file mode 100644 index 0000000..0e4a942 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-041-proposer-selection-via-abci.md @@ -0,0 +1,29 @@ +# ADR 041: Application should be in charge of validator set + +## Changelog + + +## Context + +Currently Tendermint is in charge of validator set and proposer selection. Application can only update the validator set changes at EndBlock time. +To support Light Client, application should make sure at least 2/3 of validator are same at each round. + +Application should have full control on validator set changes and proposer selection. In each round Application can provide the list of validators for next rounds in order with their power. The proposer is the first in the list, in case the proposer is offline, the next one can propose the proposal and so on. + +## Decision + +## Status + +## Consequences + +Tendermint is no more in charge of validator set and its changes. The Application should provide the correct information. +However Tendermint can provide psedo-randomness algorithm to help application for selecting proposer in each round. + +### Positive + +### Negative + +### Neutral + +## References + diff --git a/docs/architecture/tendermint-core/adr-042-state-sync.md b/docs/architecture/tendermint-core/adr-042-state-sync.md new file mode 100644 index 0000000..365738c --- /dev/null +++ b/docs/architecture/tendermint-core/adr-042-state-sync.md @@ -0,0 +1,235 @@ +# ADR 042: State Sync Design + +## Changelog + +2019-06-27: Init by EB +2019-07-04: Follow up by brapse + +## Context +StateSync is a feature which would allow a new node to receive a +snapshot of the application state without downloading blocks or going +through consensus. Once downloaded, the node could switch to FastSync +and eventually participate in consensus. The goal of StateSync is to +facilitate setting up a new node as quickly as possible. + +## Considerations +Because Tendermint doesn't know anything about the application state, +StateSync will broker messages between nodes and through +the ABCI to an opaque applicaton. The implementation will have multiple +touch points on both the tendermint code base and ABCI application. + +* A StateSync reactor to facilitate peer communication - Tendermint +* A Set of ABCI messages to transmit application state to the reactor - Tendermint +* A Set of MultiStore APIs for exposing snapshot data to the ABCI - ABCI application +* A Storage format with validation and performance considerations - ABCI application + +### Implementation Properties +Beyond the approach, any implementation of StateSync can be evaluated +across different criteria: + +* Speed: Expected throughput of producing and consuming snapshots +* Safety: Cost of pushing invalid snapshots to a node +* Liveness: Cost of preventing a node from receiving/constructing a snapshot +* Effort: How much effort does an implementation require + +### Implementation Question +* What is the format of a snapshot + * Complete snapshot + * Ordered IAVL key ranges + * Compressed individually chunks which can be validated +* How is data validated + * Trust a peer with it's data blindly + * Trust a majority of peers + * Use light client validation to validate each chunk against consensus + produced merkle tree root +* What are the performance characteristics + * Random vs sequential reads + * How parallelizeable is the scheduling algorithm + +### Proposals +Broadly speaking there are two approaches to this problem which have had +varying degrees of discussion and progress. These approach can be +summarized as: + +**Lazy:** Where snapshots are produced dynamically at request time. This +solution would use the existing data structure. +**Eager:** Where snapshots are produced periodically and served from disk at +request time. This solution would create an auxiliary data structure +optimized for batch read/writes. + +Additionally the propsosals tend to vary on how they provide safety +properties. + +**LightClient** Where a client can aquire the merkle root from the block +headers synchronized from a trusted validator set. Subsets of the application state, +called chunks can therefore be validated on receipt to ensure each chunk +is part of the merkle root. + +**Majority of Peers** Where manifests of chunks along with checksums are +downloaded and compared against versions provided by a majority of +peers. + +#### Lazy StateSync +An initial specification was published by Alexis Sellier. +In this design, the state has a given `size` of primitive elements (like +keys or nodes), each element is assigned a number from 0 to `size-1`, +and chunks consists of a range of such elements. Ackratos raised +[some concerns](https://docs.google.com/document/d/1npGTAa1qxe8EQZ1wG0a0Sip9t5oX2vYZNUDwr_LVRR4/edit) +about this design, somewhat specific to the IAVL tree, and mainly concerning +performance of random reads and of iterating through the tree to determine element numbers +(ie. elements aren't indexed by the element number). + +An alternative design was suggested by Jae Kwon in +[#3639](https://github.com/tendermint/tendermint/issues/3639) where chunking +happens lazily and in a dynamic way: nodes request key ranges from their peers, +and peers respond with some subset of the +requested range and with notes on how to request the rest in parallel from other +peers. Unlike chunk numbers, keys can be verified directly. And if some keys in the +range are ommitted, proofs for the range will fail to verify. +This way a node can start by requesting the entire tree from one peer, +and that peer can respond with say the first few keys, and the ranges to request +from other peers. + +Additionally, per chunk validation tends to come more naturally to the +Lazy approach since it tends to use the existing structure of the tree +(ie. keys or nodes) rather than state-sync specific chunks. Such a +design for tendermint was originally tracked in +[#828](https://github.com/tendermint/tendermint/issues/828). + +#### Eager StateSync +Warp Sync as implemented in OpenEthereum to rapidly +download both blocks and state snapshots from peers. Data is carved into ~4MB +chunks and snappy compressed. Hashes of snappy compressed chunks are stored in a +manifest file which co-ordinates the state-sync. Obtaining a correct manifest +file seems to require an honest majority of peers. This means you may not find +out the state is incorrect until you download the whole thing and compare it +with a verified block header. + +A similar solution was implemented by Binance in +[#3594](https://github.com/tendermint/tendermint/pull/3594) +based on their initial implementation in +[PR #3243](https://github.com/tendermint/tendermint/pull/3243) +and [some learnings](https://docs.google.com/document/d/1npGTAa1qxe8EQZ1wG0a0Sip9t5oX2vYZNUDwr_LVRR4/edit). +Note this still requires the honest majority peer assumption. + +As an eager protocol, warp-sync can efficiently compress larger, more +predicatable chunks once per snapshot and service many new peers. By +comparison lazy chunkers would have to compress each chunk at request +time. + +### Analysis of Lazy vs Eager +Lazy vs Eager have more in common than they differ. They all require +reactors on the tendermint side, a set of ABCI messages and a method for +serializing/deserializing snapshots facilitated by a SnapshotFormat. + +The biggest difference between Lazy and Eager proposals is in the +read/write patterns necessitated by serving a snapshot chunk. +Specifically, Lazy State Sync performs random reads to the underlying data +structure while Eager can optimize for sequential reads. + +This distinctin between approaches was demonstrated by Binance's +[ackratos](https://github.com/ackratos) in their implementation of [Lazy +State sync](https://github.com/tendermint/tendermint/pull/3243), The +[analysis](https://docs.google.com/document/d/1npGTAa1qxe8EQZ1wG0a0Sip9t5oX2vYZNUDwr_LVRR4/) +of the performance, and follow up implementation of [Warp +Sync](http://github.com/tendermint/tendermint/pull/3594). + +#### Compairing Security Models +There are several different security models which have been +discussed/proposed in the past but generally fall into two categories. + +Light client validation: In which the node receiving data is expected to +first perform a light client sync and have all the nessesary block +headers. Within the trusted block header (trusted in terms of from a +validator set subject to [weak +subjectivity](https://github.com/tendermint/tendermint/pull/3795)) and +can compare any subset of keys called a chunk against the merkle root. +The advantage of light client validation is that the block headers are +signed by validators which have something to lose for malicious +behavior. If a validator were to provide an invalid proof, they can be +slashed. + +Majority of peer validation: A manifest file containing a list of chunks +along with checksums of each chunk is downloaded from a +trusted source. That source can be a community resource similar to +[sum.golang.org](https://sum.golang.org) or downloaded from the majority +of peers. One disadantage of the majority of peer security model is the +vuliberability to eclipse attacks in which a malicious users looks to +saturate a target node's peer list and produce a manufactured picture of +majority. + +A third option would be to include snapshot related data in the +block header. This could include the manifest with related checksums and be +secured through consensus. One challenge of this approach is to +ensure that creating snapshots does not put undo burden on block +propsers by synchronizing snapshot creation and block creation. One +approach to minimizing the burden is for snapshots for height +`H` to be included in block `H+n` where `n` is some `n` block away, +giving the block propser enough time to complete the snapshot +asynchronousy. + +## Proposal: Eager StateSync With Per Chunk Light Client Validation +The conclusion after some concideration of the advantages/disadvances of +eager/lazy and different security models is to produce a state sync +which eagerly produces snapshots and uses light client validation. This +approach has the performance advantages of pre-computing efficient +snapshots which can streamed to new nodes on demand using sequential IO. +Secondly, by using light client validation we cna validate each chunk on +receipt and avoid the potential eclipse attack of majority of peer based +security. + +### Implementation +Tendermint is responsible for downloading and verifying chunks of +AppState from peers. ABCI Application is responsible for taking +AppStateChunk objects from TM and constructing a valid state tree whose +root corresponds with the AppHash of syncing block. In particular we +will need implement: + +* Build new StateSync reactor brokers message transmission between the peers + and the ABCI application +* A set of ABCI Messages +* Design SnapshotFormat as an interface which can: + * validate chunks + * read/write chunks from file + * read/write chunks to/from application state store + * convert manifests into chunkRequest ABCI messages +* Implement SnapshotFormat for cosmos-hub with concrete implementation for: + * read/write chunks in a way which can be: + * parallelized across peers + * validated on receipt + * read/write to/from IAVL+ tree + +![StateSync Architecture Diagram](img/state-sync.png) + +## Implementation Path +* Create StateSync reactor based on [#3753](https://github.com/tendermint/tendermint/pull/3753) +* Design SnapshotFormat with an eye towards cosmos-hub implementation +* ABCI message to send/receive SnapshotFormat +* IAVL+ changes to support SnapshotFormat +* Deliver Warp sync (no chunk validation) +* light client implementation for weak subjectivity +* Deliver StateSync with chunk validation + +## Status + +Proposed + +## Concequences + +### Neutral + +### Positive +* Safe & performant state sync design substantiated with real world implementation experience +* General interfaces allowing application specific innovation +* Parallizable implementation trajectory with reasonable engineering effort + +### Negative +* Static Scheduling lacks opportunity for real time chunk availability optimizations + +## References +[sync: Sync current state without full replay for Applications](https://github.com/tendermint/tendermint/issues/828) - original issue +[tendermint state sync proposal 2](https://docs.google.com/document/d/1npGTAa1qxe8EQZ1wG0a0Sip9t5oX2vYZNUDwr_LVRR4/edit) - ackratos proposal +[proposal 2 implementation](https://github.com/tendermint/tendermint/pull/3243) - ackratos implementation +[WIP General/Lazy State-Sync pseudo-spec](https://github.com/tendermint/tendermint/issues/3639) - Jae Proposal +[Warp Sync Implementation](https://github.com/tendermint/tendermint/pull/3594) - ackratos +[Chunk Proposal](https://github.com/tendermint/tendermint/pull/3799) - Bucky proposed diff --git a/docs/architecture/tendermint-core/adr-043-blockchain-riri-org.md b/docs/architecture/tendermint-core/adr-043-blockchain-riri-org.md new file mode 100644 index 0000000..7348812 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-043-blockchain-riri-org.md @@ -0,0 +1,404 @@ +# ADR 043: Blockhchain Reactor Riri-Org + +## Changelog + +- 18-06-2019: Initial draft +- 08-07-2019: Reviewed +- 29-11-2019: Implemented +- 14-02-2020: Updated with the implementation details + +## Context + +The blockchain reactor is responsible for two high level processes:sending/receiving blocks from peers and FastSync-ing blocks to catch upnode who is far behind. The goal of [ADR-40](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-040-blockchain-reactor-refactor.md) was to refactor these two processes by separating business logic currently wrapped up in go-channels into pure `handle*` functions. While the ADR specified what the final form of the reactor might look like it lacked guidance on intermediary steps to get there. +The following diagram illustrates the state of the [blockchain-reorg](https://github.com/tendermint/tendermint/pull/3561) reactor which will be referred to as `v1`. + +![v1 Blockchain Reactor Architecture +Diagram](https://github.com/tendermint/tendermint/blob/f9e556481654a24aeb689bdadaf5eab3ccd66829/docs/architecture/img/blockchain-reactor-v1.png) + +While `v1` of the blockchain reactor has shown significant improvements in terms of simplifying the concurrency model, the current PR has run into few roadblocks. + +- The current PR large and difficult to review. +- Block gossiping and fast sync processes are highly coupled to the shared `Pool` data structure. +- Peer communication is spread over multiple components creating complex dependency graph which must be mocked out during testing. +- Timeouts modeled as stateful tickers introduce non-determinism in tests + +This ADR is meant to specify the missing components and control necessary to achieve [ADR-40](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-040-blockchain-reactor-refactor.md). + +## Decision + +Partition the responsibilities of the blockchain reactor into a set of components which communicate exclusively with events. Events will contain timestamps allowing each component to track time as internal state. The internal state will be mutated by a set of `handle*` which will produce event(s). The integration between components will happen in the reactor and reactor tests will then become integration tests between components. This design will be known as `v2`. + +![v2 Blockchain Reactor Architecture +Diagram](https://github.com/tendermint/tendermint/blob/584e67ac3fac220c5c3e0652e3582eca8231e814/docs/architecture/img/blockchain-reactor-v2.png) + +### Fast Sync Related Communication Channels + +The diagram below shows the fast sync routines and the types of channels and queues used to communicate with each other. +In addition the per reactor channels used by the sendRoutine to send messages over the Peer MConnection are shown. + +![v2 Blockchain Channels and Queues +Diagram](https://github.com/tendermint/tendermint/blob/5cf570690f989646fb3b615b734da503f038891f/docs/architecture/img/blockchain-v2-channels.png) + +### Reactor changes in detail + +The reactor will include a demultiplexing routine which will send each message to each sub routine for independent processing. Each sub routine will then select the messages it's interested in and call the handle specific function specified in [ADR-40](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-040-blockchain-reactor-refactor.md). The demuxRoutine acts as "pacemaker" setting the time in which events are expected to be handled. + +```go +func demuxRoutine(msgs, scheduleMsgs, processorMsgs, ioMsgs) { + timer := time.NewTicker(interval) + for { + select { + case <-timer.C: + now := evTimeCheck{time.Now()} + schedulerMsgs <- now + processorMsgs <- now + ioMsgs <- now + case msg:= <- msgs: + msg.time = time.Now() + // These channels should produce backpressure before + // being full to avoid starving each other + schedulerMsgs <- msg + processorMsgs <- msg + ioMesgs <- msg + if msg == stop { + break; + } + } + } +} + +func processRoutine(input chan Message, output chan Message) { + processor := NewProcessor(..) + for { + msg := <- input + switch msg := msg.(type) { + case bcBlockRequestMessage: + output <- processor.handleBlockRequest(msg)) + ... + case stop: + processor.stop() + break; + } +} + +func scheduleRoutine(input chan Message, output chan Message) { + schelduer = NewScheduler(...) + for { + msg := <-msgs + switch msg := input.(type) { + case bcBlockResponseMessage: + output <- scheduler.handleBlockResponse(msg) + ... + case stop: + schedule.stop() + break; + } + } +} +``` + +## Lifecycle management + +A set of routines for individual processes allow processes to run in parallel with clear lifecycle management. `Start`, `Stop`, and `AddPeer` hooks currently present in the reactor will delegate to the sub-routines allowing them to manage internal state independent without further coupling to the reactor. + +```go +func (r *BlockChainReactor) Start() { + r.msgs := make(chan Message, maxInFlight) + schedulerMsgs := make(chan Message) + processorMsgs := make(chan Message) + ioMsgs := make(chan Message) + + go processorRoutine(processorMsgs, r.msgs) + go scheduleRoutine(schedulerMsgs, r.msgs) + go ioRoutine(ioMsgs, r.msgs) + ... +} + +func (bcR *BlockchainReactor) Receive(...) { + ... + r.msgs <- msg + ... +} + +func (r *BlockchainReactor) Stop() { + ... + r.msgs <- stop + ... +} + +... +func (r *BlockchainReactor) Stop() { + ... + r.msgs <- stop + ... +} +... + +func (r *BlockchainReactor) AddPeer(peer p2p.Peer) { + ... + r.msgs <- bcAddPeerEv{peer.ID} + ... +} + +``` + +## IO handling + +An io handling routine within the reactor will isolate peer communication. Message going through the ioRoutine will usually be one way, using `p2p` APIs. In the case in which the `p2p` API such as `trySend` return errors, the ioRoutine can funnel those message back to the demuxRoutine for distribution to the other routines. For instance errors from the ioRoutine can be consumed by the scheduler to inform better peer selection implementations. + +```go +func (r *BlockchainReacor) ioRoutine(ioMesgs chan Message, outMsgs chan Message) { + ... + for { + msg := <-ioMsgs + switch msg := msg.(type) { + case scBlockRequestMessage: + queued := r.sendBlockRequestToPeer(...) + if queued { + outMsgs <- ioSendQueued{...} + } + case scStatusRequestMessage + r.sendStatusRequestToPeer(...) + case bcPeerError + r.Swtich.StopPeerForError(msg.src) + ... + ... + case bcFinished + break; + } + } +} + +``` + +### Processor Internals + +The processor is responsible for ordering, verifying and executing blocks. The Processor will maintain an internal cursor `height` refering to the last processed block. As a set of blocks arrive unordered, the Processor will check if it has `height+1` necessary to process the next block. The processor also maintains the map `blockPeers` of peers to height, to keep track of which peer provided the block at `height`. `blockPeers` can be used in`handleRemovePeer(...)` to reschedule all unprocessed blocks provided by a peer who has errored. + +```go +type Processor struct { + height int64 // the height cursor + state ... + blocks [height]*Block // keep a set of blocks in memory until they are processed + blockPeers [height]PeerID // keep track of which heights came from which peerID + lastTouch timestamp +} + +func (proc *Processor) handleBlockResponse(peerID, block) { + if block.height <= height || block[block.height] { + } else if blocks[block.height] { + return errDuplicateBlock{} + } else { + blocks[block.height] = block + } + + if blocks[height] && blocks[height+1] { + ... = state.Validators.VerifyCommit(...) + ... = store.SaveBlock(...) + state, err = blockExec.ApplyBlock(...) + ... + if err == nil { + delete blocks[height] + height++ + lastTouch = msg.time + return pcBlockProcessed{height-1} + } else { + ... // Delete all unprocessed block from the peer + return pcBlockProcessError{peerID, height} + } + } +} + +func (proc *Processor) handleRemovePeer(peerID) { + events = [] + // Delete all unprocessed blocks from peerID + for i = height; i < len(blocks); i++ { + if blockPeers[i] == peerID { + events = append(events, pcBlockReschedule{height}) + + delete block[height] + } + } + return events +} + +func handleTimeCheckEv(time) { + if time - lastTouch > timeout { + // Timeout the processor + ... + } +} +``` + +## Schedule + +The Schedule maintains the internal state used for scheduling blockRequestMessages based on some scheduling algorithm. The schedule needs to maintain state on: + +- The state `blockState` of every block seem up to height of maxHeight +- The set of peers and their peer state `peerState` +- which peers have which blocks +- which blocks have been requested from which peers + +```go +type blockState int + +const ( + blockStateNew = iota + blockStatePending, + blockStateReceived, + blockStateProcessed +) + +type schedule { + // a list of blocks in which blockState + blockStates map[height]blockState + + // a map of which blocks are available from which peers + blockPeers map[height]map[p2p.ID]scPeer + + // a map of peerID to schedule specific peer struct `scPeer` + peers map[p2p.ID]scPeer + + // a map of heights to the peer we are waiting for a response from + pending map[height]scPeer + + targetPending int // the number of blocks we want in blockStatePending + targetReceived int // the number of blocks we want in blockStateReceived + + peerTimeout int + peerMinSpeed int +} + +func (sc *schedule) numBlockInState(state blockState) uint32 { + num := 0 + for i := sc.minHeight(); i <= sc.maxHeight(); i++ { + if sc.blockState[i] == state { + num++ + } + } + return num +} + + +func (sc *schedule) popSchedule(maxRequest int) []scBlockRequestMessage { + // We only want to schedule requests such that we have less than sc.targetPending and sc.targetReceived + // This ensures we don't saturate the network or flood the processor with unprocessed blocks + todo := min(sc.targetPending - sc.numBlockInState(blockStatePending), sc.numBlockInState(blockStateReceived)) + events := []scBlockRequestMessage{} + for i := sc.minHeight(); i < sc.maxMaxHeight(); i++ { + if todo == 0 { + break + } + if blockStates[i] == blockStateNew { + peer = sc.selectPeer(blockPeers[i]) + sc.blockStates[i] = blockStatePending + sc.pending[i] = peer + events = append(events, scBlockRequestMessage{peerID: peer.peerID, height: i}) + todo-- + } + } + return events +} +... + +type scPeer struct { + peerID p2p.ID + numOustandingRequest int + lastTouched time.Time + monitor flow.Monitor +} + +``` + +# Scheduler + +The scheduler is configured to maintain a target `n` of in flight +messages and will use feedback from `_blockResponseMessage`, +`_statusResponseMessage` and `_peerError` produce an optimal assignment +of scBlockRequestMessage at each `timeCheckEv`. + +``` + +func handleStatusResponse(peerID, height, time) { + schedule.touchPeer(peerID, time) + schedule.setPeerHeight(peerID, height) +} + +func handleBlockResponseMessage(peerID, height, block, time) { + schedule.touchPeer(peerID, time) + schedule.markReceived(peerID, height, size(block)) +} + +func handleNoBlockResponseMessage(peerID, height, time) { + schedule.touchPeer(peerID, time) + // reschedule that block, punish peer... + ... +} + +func handlePeerError(peerID) { + // Remove the peer, reschedule the requests + ... +} + +func handleTimeCheckEv(time) { + // clean peer list + + events = [] + for peerID := range schedule.peersNotTouchedSince(time) { + pending = schedule.pendingFrom(peerID) + schedule.setPeerState(peerID, timedout) + schedule.resetBlocks(pending) + events = append(events, peerTimeout{peerID}) + } + + events = append(events, schedule.popSchedule()) + + return events +} +``` + +## Peer + +The Peer Stores per peer state based on messages received by the scheduler. + +```go +type Peer struct { + lastTouched timestamp + lastDownloaded timestamp + pending map[height]struct{} + height height // max height for the peer + state { + pending, // we know the peer but not the height + active, // we know the height + timeout // the peer has timed out + } +} +``` + +## Status + +Implemented + +## Consequences + +### Positive + +- Test become deterministic +- Simulation becomes a-termporal: no need wait for a wall-time timeout +- Peer Selection can be independently tested/simulated +- Develop a general approach to refactoring reactors + +### Negative + +### Neutral + +### Implementation Path + +- Implement the scheduler, test the scheduler, review the rescheduler +- Implement the processor, test the processor, review the processor +- Implement the demuxer, write integration test, review integration tests + +## References + +- [ADR-40](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-040-blockchain-reactor-refactor.md): The original blockchain reactor re-org proposal +- [Blockchain re-org](https://github.com/tendermint/tendermint/pull/3561): The current blockchain reactor re-org implementation (v1) diff --git a/docs/architecture/tendermint-core/adr-044-lite-client-with-weak-subjectivity.md b/docs/architecture/tendermint-core/adr-044-lite-client-with-weak-subjectivity.md new file mode 100644 index 0000000..579cc63 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-044-lite-client-with-weak-subjectivity.md @@ -0,0 +1,141 @@ +# ADR 044: Lite Client with Weak Subjectivity + +## Changelog +* 13-07-2019: Initial draft +* 14-08-2019: Address cwgoes comments + +## Context + +The concept of light clients was introduced in the Bitcoin white paper. It +describes a watcher of distributed consensus process that only validates the +consensus algorithm and not the state machine transactions within. + +Tendermint light clients allow bandwidth & compute-constrained devices, such as smartphones, low-power embedded chips, or other blockchains to +efficiently verify the consensus of a Tendermint blockchain. This forms the +basis of safe and efficient state synchronization for new network nodes and +inter-blockchain communication (where a light client of one Tendermint instance +runs in another chain's state machine). + +In a network that is expected to reliably punish validators for misbehavior +by slashing bonded stake and where the validator set changes +infrequently, clients can take advantage of this assumption to safely +synchronize a lite client without downloading the intervening headers. + +Light clients (and full nodes) operating in the Proof Of Stake context need a +trusted block height from a trusted source that is no older than 1 unbonding +window plus a configurable evidence submission synchrony bound. This is called “weak subjectivity”. + +Weak subjectivity is required in Proof of Stake blockchains because it is +costless for an attacker to buy up voting keys that are no longer bonded and +fork the network at some point in its prior history. See Vitalik’s post at +[Proof of Stake: How I Learned to Love Weak +Subjectivity](https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity/). + +Currently, Tendermint provides a lite client implementation in the +[light](https://github.com/tendermint/tendermint/tree/main/light) package. This +lite client implements a bisection algorithm that tries to use a binary search +to find the minimum number of block headers where the validator set voting +power changes are less than < 1/3rd. This interface does not support weak +subjectivity at this time. The Cosmos SDK also does not support counterfactual +slashing, nor does the lite client have any capacity to report evidence making +these systems *theoretically unsafe*. + +NOTE: Tendermint provides a somewhat different (stronger) light client model +than Bitcoin under eclipse, since the eclipsing node(s) can only fool the light +client if they have two-thirds of the private keys from the last root-of-trust. + +## Decision + +### The Weak Subjectivity Interface + +Add the weak subjectivity interface for when a new light client connects to the +network or when a light client that has been offline for longer than the +unbonding period connects to the network. Specifically, the node needs to +initialize the following structure before syncing from user input: + +``` +type TrustOptions struct { + // Required: only trust commits up to this old. + // Should be equal to the unbonding period minus some delta for evidence reporting. + TrustPeriod time.Duration `json:"trust-period"` + + // Option 1: TrustHeight and TrustHash can both be provided + // to force the trusting of a particular height and hash. + // If the latest trusted height/hash is more recent, then this option is + // ignored. + TrustHeight int64 `json:"trust-height"` + TrustHash []byte `json:"trust-hash"` + + // Option 2: Callback can be set to implement a confirmation + // step if the trust store is uninitialized, or expired. + Callback func(height int64, hash []byte) error +} +``` + +The expectation is the user will get this information from a trusted source +like a validator, a friend, or a secure website. A more user friendly +solution with trust tradeoffs is that we establish an https based protocol with +a default end point that populates this information. Also an on-chain registry +of roots-of-trust (e.g. on the Cosmos Hub) seems likely in the future. + +### Linear Verification + +The linear verification algorithm requires downloading all headers +between the `TrustHeight` and the `LatestHeight`. The lite client downloads the +full header for the provided `TrustHeight` and then proceeds to download `N+1` +headers and applies the [Tendermint validation +rules](https://github.com/tendermint/tendermint/tree/main/spec/light-client/verification/README.md) +to each block. + +### Bisecting Verification + +Bisecting Verification is a more bandwidth and compute intensive mechanism that +in the most optimistic case requires a light client to only download two block +headers to come into synchronization. + +The bisection algorithm proceeds in the following fashion. The client downloads +and verifies the full block header for `TrustHeight` and then fetches +`LatestHeight` blocker header. The client then verifies the `LatestHeight` +header. Finally the client attempts to verify the `LatestHeight` header with +voting powers taken from `NextValidatorSet` in the `TrustHeight` header. This +verification will succeed if the validators from `TrustHeight` still have > 2/3 ++1 of voting power in the `LatestHeight`. If this succeeds, the client is fully +synchronized. If this fails, then following Bisection Algorithm should be +executed. + +The Client tries to download the block at the mid-point block between +`LatestHeight` and `TrustHeight` and attempts that same algorithm as above +using `MidPointHeight` instead of `LatestHeight` and a different threshold - +1/3 +1 of voting power for *non-adjacent headers*. In the case the of failure, +recursively perform the `MidPoint` verification until success then start over +with an updated `NextValidatorSet` and `TrustHeight`. + +If the client encounters a forged header, it should submit the header along +with some other intermediate headers as the evidence of misbehavior to other +full nodes. After that, it can retry the bisection using another full node. An +optimal client will cache trusted headers from the previous run to minimize +network usage. + +--- + +Check out the formal specification +[here](https://github.com/tendermint/tendermint/tree/main/spec/light-client). + +## Status + +Implemented + +## Consequences + +### Positive + +* light client which is safe to use (it can go offline, but not for too long) + +### Negative + +* complexity of bisection + +### Neutral + +* social consensus can be prone to errors (for cases where a new light client + joins a network or it has been offline for too long) diff --git a/docs/architecture/tendermint-core/adr-045-abci-evidence.md b/docs/architecture/tendermint-core/adr-045-abci-evidence.md new file mode 100644 index 0000000..cbceb88 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-045-abci-evidence.md @@ -0,0 +1,140 @@ +# ADR 45 - ABCI Evidence Handling + +## Changelog +* 21-09-2019: Initial draft + +## Context + +Evidence is a distinct component in a Tendermint block and has it's own reactor +for high priority gossipping. Currently, Tendermint supports only a single form of evidence, an explicit +equivocation, where a validator signs conflicting blocks at the same +height/round. It is detected in real-time in the consensus reactor, and gossiped +through the evidence reactor. Evidence can also be submitted through the RPC. + +Currently, Tendermint does not gracefully handle a fork on the main chain. +If a fork is detected, the node panics. At this point manual intervention and +social consensus are required to reconfigure. We'd like to do something more +graceful here, but that's for another day. + +It's possible to fool lite clients without there being a fork on the +main chain - so called Fork-Lite. See the +[fork accountability](https://github.com/tendermint/tendermint/blob/main/spec/light-client/accountability/README.md) +document for more details. For a sequential lite client, this can happen via +equivocation or amnesia attacks. For a skipping lite client this can also happen +via lunatic validator attacks. There must be some way for applications to punish +all forms of misbehavior. + +The essential question is whether Tendermint should manage the evidence +verification, or whether it should treat evidence more like a transaction (ie. +arbitrary bytes) and let the application handle it (including all the signature +checking). + +Currently, evidence verification is handled by Tendermint. Once committed, +[evidence is passed over +ABCI](https://github.com/tendermint/tendermint/blob/main/proto/tendermint/abci/types.proto#L354) +in BeginBlock in a reduced form that includes only +the type of evidence, its height and timestamp, the validator it's from, and the +total voting power of the validator set at the height. The app trusts Tendermint +to perform the evidence verification, as the ABCI evidence does not contain the +signatures and additional data for the app to verify itself. + +Arguments in favor of leaving evidence handling in Tendermint: + +1) Attacks on full nodes must be detectable by full nodes in real time, ie. within the consensus reactor. + So at the very least, any evidence involved in something that could fool a full + node must be handled natively by Tendermint as there would otherwise be no way + for the ABCI app to detect it (ie. we don't send all votes we receive during + consensus to the app ... ). + +2) Amensia attacks can not be easily detected - they require an interactive + protocol among all the validators to submit justification for their past + votes. Our best notion of [how to do this + currently](https://github.com/tendermint/tendermint/blob/c67154232ca8be8f5c21dff65d154127adc4f7bb/docs/spec/consensus/fork-detection.md) + is via a centralized + monitor service that is trusted for liveness to aggregate data from + current and past validators, but which produces a proof of misbehavior (ie. + via amnesia) that can be verified by anyone, including the blockchain. + Validators must submit all the votes they saw for the relevant consensus + height to justify their precommits. This is quite specific to the Tendermint + protocol and may change if the protocol is upgraded. Hence it would be awkward + to co-ordinate this from the app. + +3) Evidence gossipping is similar to tx gossipping, but it should be higher + priority. Since the mempool does not support any notion of priority yet, + evidence is gossipped through a distinct Evidence reactor. If we just treated + evidence like any other transaction, leaving it entirely to the application, + Tendermint would have no way to know how to prioritize it, unless/until we + significantly upgrade the mempool. Thus we would need to continue to treat evidence + distinctly and update the ABCI to either support sending Evidence through + CheckTx/DeliverTx, or to introduce new CheckEvidence/DeliverEvidence methods. + In either case we'd need to make more changes to ABCI then if Tendermint + handled things and we just added support for another evidence type that could be included + in BeginBlock. + +4) All ABCI application frameworks will benefit from most of the heavy lifting + being handled by Tendermint, rather than each of them needing to re-implement + all the evidence verification logic in each language. + +Arguments in favor of moving evidence handling to the application: + +5) Skipping lite clients require us to track the set of all validators that were + bonded over some period in case validators that are unbonding but still + slashable sign invalid headers to fool lite clients. The Cosmos-SDK + staking/slashing modules track this, as it's used for slashing. + Tendermint does not currently track this, though it does keep track of the + validator set at every height. This leans in favour of managing evidence in + the app to avoid redundantly managing the historical validator set data in + Tendermint + +6) Applications supporting cross-chain validation will be required to process + evidence from other chains. This data will come in the form of a transaction, + but it means the app will be required to have all the functionality to process + evidence, even if the evidence for its own chain is handled directly by + Tendermint. + +7) Evidence from lite clients may be large and constitute some form of DoS + vector against full nodes. Putting it in transactions allows it to engage the application's fee + mechanism to pay for cost of executions in the event the evidence is false. + This means the evidence submitter must be able to afford the fees for the + submission, but of course it should be refunded if the evidence is valid. + That said, the burden is mostly on full nodes, which don't necessarily benefit + from fees. + + +## Decision + +The above mostly seems to suggest that evidence detection belongs in Tendermint. +(5) does not impose particularly large obligations on Tendermint and (6) just +means the app can use Tendermint libraries. That said, (7) is potentially +cause for some concern, though it could still attack full nodes that weren't associated with validators +(ie. that don't benefit from fees). This could be handled out of band, for instance by +full nodes offering the light client service via payment channels or via some +other payment service. This can also be mitigated by banning client IPs if they +send bad data. Note the burden is on the client to actually send us a lot of +data in the first place. + +A separate ADR will describe how Tendermint will handle these new forms of +evidence, in terms of how it will engage the monitoring protocol described in +the [fork +detection](https://github.com/tendermint/tendermint/blob/c67154232ca8be8f5c21dff65d154127adc4f7bb/docs/spec/consensus/fork-detection.md) document, +and how it will track past validators and manage DoS issues. + +## Status + +Proposed. + +## Consequences + +### Positive + +- No real changes to ABCI +- Tendermint handles evidence for all apps + +### Neutral + +- Need to be careful about denial of service on the Tendermint RPC + +### Negative + +- Tendermint duplicates data by tracking all pubkeys that were validators during + the unbonding period diff --git a/docs/architecture/tendermint-core/adr-046-light-client-implementation.md b/docs/architecture/tendermint-core/adr-046-light-client-implementation.md new file mode 100644 index 0000000..b64cf95 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-046-light-client-implementation.md @@ -0,0 +1,169 @@ +# ADR 046: Lite Client Implementation + +## Changelog +* 13-02-2020: Initial draft +* 26-02-2020: Cross-checking the first header +* 28-02-2020: Bisection algorithm details +* 31-03-2020: Verify signature got changed + +## Context + +A `Client` struct represents a light client, connected to a single blockchain. + +The user has an option to verify headers using `VerifyHeader` or +`VerifyHeaderAtHeight` or `Update` methods. The latter method downloads the +latest header from primary and compares it with the currently trusted one. + +```go +type Client interface { + // verify new headers + VerifyHeaderAtHeight(height int64, now time.Time) (*types.SignedHeader, error) + VerifyHeader(newHeader *types.SignedHeader, newVals *types.ValidatorSet, now time.Time) error + Update(now time.Time) (*types.SignedHeader, error) + + // get trusted headers & validators + TrustedHeader(height int64) (*types.SignedHeader, error) + TrustedValidatorSet(height int64) (valSet *types.ValidatorSet, heightUsed int64, err error) + LastTrustedHeight() (int64, error) + FirstTrustedHeight() (int64, error) + + // query configuration options + ChainID() string + Primary() provider.Provider + Witnesses() []provider.Provider + + Cleanup() error +} +``` + +A new light client can either be created from scratch (via `NewClient`) or +using the trusted store (via `NewClientFromTrustedStore`). When there's some +data in the trusted store and `NewClient` is called, the light client will a) +check if stored header is more recent b) optionally ask the user whenever it +should rollback (no confirmation required by default). + +```go +func NewClient( + chainID string, + trustOptions TrustOptions, + primary provider.Provider, + witnesses []provider.Provider, + trustedStore store.Store, + options ...Option) (*Client, error) { +``` + +`witnesses` as argument (as opposite to `Option`) is an intentional choice, +made to increase security by default. At least one witness is required, +although, right now, the light client does not check that primary != witness. +When cross-checking a new header with witnesses, minimum number of witnesses +required to respond: 1. Note the very first header (`TrustOptions.Hash`) is +also cross-checked with witnesses for additional security. + +Due to bisection algorithm nature, some headers might be skipped. If the light +client does not have a header for height `X` and `VerifyHeaderAtHeight(X)` or +`VerifyHeader(H#X)` methods are called, these will perform either a) backwards +verification from the latest header back to the header at height `X` or b) +bisection verification from the first stored header to the header at height `X`. + +`TrustedHeader`, `TrustedValidatorSet` only communicate with the trusted store. +If some header is not there, an error will be returned indicating that +verification is required. + +```go +type Provider interface { + ChainID() string + + SignedHeader(height int64) (*types.SignedHeader, error) + ValidatorSet(height int64) (*types.ValidatorSet, error) +} +``` + +Provider is a full node usually, but can be another light client. The above +interface is thin and can accommodate many implementations. + +If provider (primary or witness) becomes unavailable for a prolonged period of +time, it will be removed to ensure smooth operation. + +Both `Client` and providers expose chain ID to track if there are on the same +chain. Note, when chain upgrades or intentionally forks, chain ID changes. + +The light client stores headers & validators in the trusted store: + +```go +type Store interface { + SaveSignedHeaderAndValidatorSet(sh *types.SignedHeader, valSet *types.ValidatorSet) error + DeleteSignedHeaderAndValidatorSet(height int64) error + + SignedHeader(height int64) (*types.SignedHeader, error) + ValidatorSet(height int64) (*types.ValidatorSet, error) + + LastSignedHeaderHeight() (int64, error) + FirstSignedHeaderHeight() (int64, error) + + SignedHeaderAfter(height int64) (*types.SignedHeader, error) + + Prune(size uint16) error + + Size() uint16 +} +``` + +At the moment, the only implementation is the `db` store (wrapper around the KV +database, used in Tendermint). In the future, remote adapters are possible +(e.g. `Postgresql`). + +```go +func Verify( + chainID string, + trustedHeader *types.SignedHeader, // height=X + trustedVals *types.ValidatorSet, // height=X or height=X+1 + untrustedHeader *types.SignedHeader, // height=Y + untrustedVals *types.ValidatorSet, // height=Y + trustingPeriod time.Duration, + now time.Time, + maxClockDrift time.Duration, + trustLevel tmmath.Fraction) error { +``` + +`Verify` pure function is exposed for a header verification. It handles both +cases of adjacent and non-adjacent headers. In the former case, it compares the +hashes directly (2/3+ signed transition). Otherwise, it verifies 1/3+ +(`trustLevel`) of trusted validators are still present in new validators. + +While `Verify` function is certainly handy, `VerifyAdjacent` and +`VerifyNonAdjacent` should be used most often to avoid logic errors. + +### Bisection algorithm details + +Non-recursive bisection algorithm was implemented despite the spec containing +the recursive version. There are two major reasons: + +1) Constant memory consumption => no risk of getting OOM (Out-Of-Memory) exceptions; +2) Faster finality (see Fig. 1). + +_Fig. 1: Differences between recursive and non-recursive bisections_ + +![Fig. 1](./img/adr-046-fig1.png) + +Specification of the non-recursive bisection can be found +[here](https://github.com/tendermint/spec/blob/zm_non-recursive-verification/spec/consensus/light-client/non-recursive-verification.md). + +## Status + +Implemented + +## Consequences + +### Positive + +* single `Client` struct, which is easy to use +* flexible interfaces for header providers and trusted storage + +### Negative + +* `Verify` needs to be aligned with the current spec + +### Neutral + +* `Verify` function might be misused (called with non-adjacent headers in + incorrectly implemented sequential verification) diff --git a/docs/architecture/tendermint-core/adr-047-handling-evidence-from-light-client.md b/docs/architecture/tendermint-core/adr-047-handling-evidence-from-light-client.md new file mode 100644 index 0000000..4fbc62f --- /dev/null +++ b/docs/architecture/tendermint-core/adr-047-handling-evidence-from-light-client.md @@ -0,0 +1,254 @@ +# ADR 047: Handling evidence from light client + +## Changelog +* 18-02-2020: Initial draft +* 24-02-2020: Second version +* 13-04-2020: Add PotentialAmnesiaEvidence and a few remarks +* 31-07-2020: Remove PhantomValidatorEvidence +* 14-08-2020: Introduce light traces (listed now as an alternative approach) +* 20-08-2020: Light client produces evidence when detected instead of passing to full node +* 16-09-2020: Post-implementation revision +* 15-03-2020: Ammends for the case of a forward lunatic attack + +### Glossary of Terms + +- a `LightBlock` is the unit of data that a light client receives, verifies and stores. +It is composed of a validator set, commit and header all at the same height. +- a **Trace** is seen as an array of light blocks across a range of heights that were +created as a result of skipping verification. +- a **Provider** is a full node that a light client is connected to and serves the light +client signed headers and validator sets. +- `VerifySkipping` (sometimes known as bisection or verify non-adjacent) is a method the +light client uses to verify a target header from a trusted header. The process involves verifying +intermediate headers in between the two by making sure that 1/3 of the validators that signed +the trusted header also signed the untrusted one. +- **Light Bifurcation Point**: If the light client was to run `VerifySkipping` with two providers +(i.e. a primary and a witness), the bifurcation point is the height that the headers +from each of these providers are different yet valid. This signals that one of the providers +may be trying to fool the light client. + +## Context + +The bisection method of header verification used by the light client exposes +itself to a potential attack if any block within the light clients trusted period has +a malicious group of validators with power that exceeds the light clients trust level +(default is 1/3). To improve light client (and overall network) security, the light +client has a detector component that compares the verified header provided by the +primary against witness headers. This ADR outlines the process of mitigating attacks +on the light client by using witness nodes to cross reference with. + +## Alternative Approaches + +A previously discussed approach to handling evidence was to pass all the data that the +light client had witnessed when it had observed diverging headers for the full node to +process.This was known as a light trace and had the following structure: + +```go +type ConflictingHeadersTrace struct { + Headers []*types.SignedHeader +} +``` + +This approach has the advantage of not requiring as much processing on the light +client side in the event that an attack happens. Although, this is not a significant +difference as the light client would in any case have to validate all the headers +from both witness and primary. Using traces would consume a large amount of bandwidth +and adds a DDOS vector to the full node. + + +## Decision + +The light client will be divided into two components: a `Verifier` (either sequential or +skipping) and a `Detector` (see [Informal's Detector](https://github.com/informalsystems/tendermint-rs/blob/master/docs/spec/lightclient/detection/detection.md)) +. The detector will take the trace of headers from the primary and check it against all +witnesses. For a witness with a diverging header, the detector will first verify the header +by bisecting through all the heights defined by the trace that the primary provided. If valid, +the light client will trawl through both traces and find the point of bifurcation where it +can proceed to extract any evidence (as is discussed in detail later). + +Upon successfully detecting the evidence, the light client will send it to both primary and +witness before halting. It will not send evidence to other peers nor continue to verify the +primary's header against any other header. + + +## Detailed Design + +The verification process of the light client will start from a trusted header and use a bisectional +algorithm to verify up to a header at a given height. This becomes the verified header (does not +mean that it is trusted yet). All headers that were verified in between are cached and known as +intermediary headers and the entire array is sometimes referred to as a trace. + +The light client's detector then takes all the headers and runs the detect function. + +```golang +func (c *Client) detectDivergence(primaryTrace []*types.LightBlock, now time.Time) error +``` + +The function takes the last header it received, the target header and compares it against all the witnesses +it has through the following function: + +```golang +func (c *Client) compareNewHeaderWithWitness(errc chan error, h *types.SignedHeader, + witness provider.Provider, witnessIndex int) +``` + +The err channel is used to send back all the outcomes so that they can be processed in parallel. +Invalid headers result in dropping the witness, lack of response or not having the headers is ignored +just as headers that have the same hash. Headers, however, +of a different hash then trigger the detection process between the primary and that particular witness. + +This begins with verification of the witness's header via skipping verification which is run in tande +with locating the Light Bifurcation Point + +![](./img/light-client-detector.png) + +This is done with: + +```golang +func (c *Client) examineConflictingHeaderAgainstTrace( + trace []*types.LightBlock, + targetBlock *types.LightBlock, + source provider.Provider, + now time.Time, + ) ([]*types.LightBlock, *types.LightBlock, error) +``` + +which performs the following + +1. Checking that the trusted header is the same. Currently, they should not theoretically be different +because witnesses cannot be added and removed after the client is initialized. But we do this any way +as a sanity check. If this fails we have to drop the witness. + +2. Querying and verifying the witness's headers using bisection at the same heights of all the +intermediary headers of the primary (In the above example this is A, B, C, D, F, H). If bisection fails +or the witness stops responding then we can call the witness faulty and drop it. + +3. We eventually reach a verified header by the witness which is not the same as the intermediary header +(In the above example this is E). This is the point of bifurcation (This could also be the last header). + +4. There is a unique case where the trace that is being examined against has blocks that have a greater +height than the targetBlock. This can occur as part of a forward lunatic attack where the primary has +provided a light block that has a height greater than the head of the chain (see Appendix B). In this +case, the light client will verify the sources blocks up to the targetBlock and return the block in the +trace that is directly after the targetBlock in height as the `ConflictingBlock` + +This function then returns the trace of blocks from the witness node between the common header and the +divergent header of the primary as it is likely, as seen in the example to the right, that multiple +headers where required in order to verify the divergent one. This trace will +be used later (as is also described later in this document). + +![](./img/bifurcation-point.png) + +Now, that an attack has been detected, the light client must form evidence to prove it. There are +three types of attacks that either the primary or witness could have done to try fool the light client +into verifying the wrong header: Lunatic, Equivocation and Amnesia. As the consequence is the same and +the data required to prove it is also very similar, we bundle these attack styles together in a single +evidence: + +```golang +type LightClientAttackEvidence struct { + ConflictingBlock *LightBlock + CommonHeight int64 +} +``` + +The light client takes the stance of first suspecting the primary. Given the bifurcation point found +above, it takes the two divergent headers and compares whether the one from the primary is valid with +respect to the one from the witness. This is done by calling `isInvalidHeader()` which looks to see if +any one of the deterministically derived header fields differ from one another. This could be one of +`ValidatorsHash`, `NextValidatorsHash`, `ConsensusHash`, `AppHash`, and `LastResultsHash`. +In this case we know it's a Lunatic attack and to help the witness verify it we send the height +of the common header which is 1 in the example above or C in the example above that. If all these +hashes are the same then we can infer that it is either Equivocation or Amnesia. In this case we send +the height of the diverged headers because we know that the validator sets are the same, hence the +malicious nodes are still bonded at that height. In the example above, this is height 10 and the +example above that it is the height at E. + +The light client now has the evidence and broadcasts it to the witness. + +However, it could have been that the header the light client used from the witness against the primary +was forged, so before halting the light client swaps the process and thus suspects the witness and +uses the primary to create evidence. It calls `examineConflictingHeaderAgainstTrace` this time using +the witness trace found earlier. +If the primary was malicious it is likely that it will not respond but if it is innocent then the +light client will produce the same evidence but this time the conflicting +block will come from the witness node instead of the primary. The evidence is then formed and sent to +the primary node. + +This then ends the process and the verify function that was called at the start returns the error to +the user. + +For a detailed overview of how each of these three attacks can be conducted please refer to the +[fork accountability spec](https://github.com/tendermint/tendermint/blob/main/spec/consensus/light-client/accountability.md). + +## Full Node Verification + +When a full node receives evidence from the light client it will need to verify +it for itself before gossiping it to peers and trying to commit it on chain. This process is outlined + in [ADR-059](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-059-evidence-composition-and-lifecycle.md). + +## Status + +Implemented + +## Consequences + +### Positive + +* Light client has increased security against Lunatic, Equivocation and Amnesia attacks. +* Do not need intermediate data structures to encapsulate the malicious behavior +* Generalized evidence makes the code simpler + +### Negative + +* Breaking change on the light client from versions 0.33.8 and below. Previous +versions will still send `ConflictingHeadersEvidence` but it won't be recognized +by the full node. Light clients will however still refuse the header and shut down. +* Amnesia attacks although detected, will not be able to be punished as it is not +clear from the current information which nodes behaved maliciously. +* Evidence module must handle both individual and grouped evidence. + +### Neutral + +## References + +* [Fork accountability spec](https://github.com/tendermint/tendermint/blob/main/spec/consensus/light-client/accountability.md) +* [ADR 056: Light client amnesia attacks](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-056-light-client-amnesia-attacks.md) +* [ADR-059: Evidence Composition and Lifecycle](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-059-evidence-composition-and-lifecycle.md) +* [Informal's Light Client Detector](https://github.com/informalsystems/tendermint-rs/blob/master/docs/spec/lightclient/detection/detection.md) + + +## Appendix A + +PhantomValidatorEvidence was used to capture when a validator that was still staked +(i.e. within the bonded period) but was not in the current validator set had voted for a block. + +In later discussions it was argued that although possible to keep phantom validator +evidence, any case a phantom validator that could have the capacity to be involved +in fooling a light client would have to be aided by 1/3+ lunatic validators. + +It would also be very unlikely that the new validators injected by the lunatic attack +would be validators that currently still have something staked. + +Not only this but there was a large degree of extra computation required in storing all +the currently staked validators that could possibly fall into the group of being +a phantom validator. Given this, it was removed. + +## Appendix B + +A unique flavor of lunatic attack is a forward lunatic attack. This is where a malicious +node provides a header with a height greater than the height of the blockchain. Thus there +are no witnesses capable of rebutting the malicious header. Such an attack will also +require an accomplice, i.e. at least one other witness to also return the same forged header. +Although such attacks can be any arbitrary height ahead, they must still remain within the +clock drift of the light clients real time. Therefore, to detect such an attack, a light +client will wait for a time + +``` +2 * MAX_CLOCK_DRIFT + LAG +``` + +for a witness to provide the latest block it has. Given the time constraints, if the witness +is operating at the head of the blockchain, it will have a header with an earlier height but +a later timestamp. This can be used to prove that the primary has submitted a lunatic header +which violates monotonically increasing time. diff --git a/docs/architecture/tendermint-core/adr-050-improved-trusted-peering.md b/docs/architecture/tendermint-core/adr-050-improved-trusted-peering.md new file mode 100644 index 0000000..c34ee42 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-050-improved-trusted-peering.md @@ -0,0 +1,58 @@ +# ADR 50: Improved Trusted Peering + +## Changelog +* 22-10-2019: Initial draft +* 05-11-2019: Modify `maximum-dial-period` to `persistent-peers-max-dial-period` + +## Context + +When `max-num-inbound-peers` or `max-num-outbound-peers` of a node is reached, the node cannot spare more slots to any peer +by inbound or outbound. Therefore, after a certain period of disconnection, any important peering can be lost indefinitely +because all slots are consumed by other peers, and the node stops trying to dial the peer anymore. + +This is happening because of two reasons, exponential backoff and absence of unconditional peering feature for trusted peers. + + +## Decision + +We would like to suggest solving this problem by introducing two parameters in `config.toml`, `unconditional-peer-ids` and +`persistent-peers-max-dial-period`. + +1) `unconditional-peer-ids` + +A node operator inputs list of ids of peers which are allowed to be connected by both inbound or outbound regardless of +`max-num-inbound-peers` or `max-num-outbound-peers` of user's node reached or not. + +2) `persistent-peers-max-dial-period` + +Terms between each dial to each persistent peer will not exceed `persistent-peers-max-dial-period` during exponential backoff. +Therefore, `dial-period` = min(`persistent-peers-max-dial-period`, `exponential-backoff-dial-period`) + +Alternative approach + +Persistent-peers is only for outbound, therefore it is not enough to cover the full utility of `unconditional-peer-ids`. +@creamers158(https://github.com/Creamers158) suggested putting id-only items into persistent-peers to be handled as +`unconditional-peer-ids`, but it needs very complicated struct exception for different structure of items in persistent-peers. +Therefore we decided to have `unconditional-peer-ids` to independently cover this use-case. + +## Status + +Proposed + +## Consequences + +### Positive + +A node operator can configure two new parameters in `config.toml` so that he/she can assure that tendermint will allow connections +from/to peers in `unconditional-peer-ids`. Also he/she can assure that every persistent peer will be dialed at least once in every +`persistent-peers-max-dial-period` term. It achieves more stable and persistent peering for trusted peers. + +### Negative + +The new feature introduces two new parameters in `config.toml` which needs explanation for node operators. + +### Neutral + +## References + +* two p2p feature enhancement proposal(https://github.com/tendermint/tendermint/issues/4053) diff --git a/docs/architecture/tendermint-core/adr-051-double-signing-risk-reduction.md b/docs/architecture/tendermint-core/adr-051-double-signing-risk-reduction.md new file mode 100644 index 0000000..429fed0 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-051-double-signing-risk-reduction.md @@ -0,0 +1,53 @@ +# ADR 051: Double Signing Risk Reduction + +## Changelog + +* 27-11-2019: Initial draft +* 13-01-2020: Separate into 2 ADR, This ADR will only cover Double signing Protection and ADR-052 handle Tendermint Mode +* 22-01-2020: change the title from "Double signing Protection" to "Double Signing Risk Reduction" + +## Context + +To provide a risk reduction method for double signing incidents mistakenly executed by validators +- Validators often mistakenly run duplicated validators to cause double-signing incident +- This proposed feature is to reduce the risk of mistaken double-signing incident by checking recent N blocks before voting begins +- When we think of such serious impact on double-signing incident, it is very reasonable to have multiple risk reduction algorithm built in node daemon + +## Decision + +We would like to suggest a double signing risk reduction method. + +- Methodology : query recent consensus results to find out whether node's consensus key is used on consensus recently or not +- When to check + - When the state machine starts `ConsensusReactor` after fully synced + - When the node is validator ( with privValidator ) + - When `cs.config.DoubleSignCheckHeight > 0` +- How to check + 1. When a validator is transformed from syncing status to fully synced status, the state machine check recent N blocks (`latest_height - double_sign_check_height`) to find out whether there exists consensus votes using the validator's consensus key + 2. If there exists votes from the validator's consensus key, exit state machine program +- Configuration + - We would like to suggest by introducing `double_sign_check_height` parameter in `config.toml` and cli, how many blocks state machine looks back to check votes + - `double_sign_check_height = {{ .Consensus.DoubleSignCheckHeight }}` in `config.toml` + - `tendermint node --consensus.double_sign_check_height` in cli + - State machine ignore checking procedure when `double_sign_check_height == 0` + +## Status + +Implemented + +## Consequences + +### Positive + +- Validators can avoid double signing incident by mistakes. (eg. If another validator node is voting on consensus, starting new validator node with same consensus key will cause panic stop of the state machine because consensus votes with the consensus key are found in recent blocks) +- We expect this method will prevent majority of double signing incident by mistakes. + +### Negative + +- When the risk reduction method is on, restarting a validator node will panic because the node itself voted on consensus with the same consensus key. So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic stop. + +### Neutral + +## References + +- Issue [#4059](https://github.com/tendermint/tendermint/issues/4059) : double-signing protection diff --git a/docs/architecture/tendermint-core/adr-052-tendermint-mode.md b/docs/architecture/tendermint-core/adr-052-tendermint-mode.md new file mode 100644 index 0000000..b9cba6a --- /dev/null +++ b/docs/architecture/tendermint-core/adr-052-tendermint-mode.md @@ -0,0 +1,85 @@ +# ADR 052: Tendermint Mode + +## Changelog + +* 27-11-2019: Initial draft from ADR-051 +* 13-01-2020: Separate ADR Tendermint Mode from ADR-051 +* 29-03-2021: Update info regarding defaults + +## Context + +- Full mode: full mode does not have the capability to become a validator. +- Validator mode : this mode is exactly same as existing state machine behavior. sync without voting on consensus, and participate consensus when fully synced +- Seed mode : lightweight seed node maintaining an address book, p2p like [TenderSeed](https://gitlab.com/polychainlabs/tenderseed) + +## Decision + +We would like to suggest a simple Tendermint mode abstraction. These modes will live under one binary, and when initializing a node the user will be able to specify which node they would like to create. + +- Which reactor, component to include for each node + - full + - switch, transport + - reactors + - mempool + - consensus + - evidence + - blockchain + - p2p/pex + - statesync + - rpc (safe connections only) + - *~~no privValidator(priv_validator_key.json, priv_validator_state.json)~~* + - validator + - switch, transport + - reactors + - mempool + - consensus + - evidence + - blockchain + - p2p/pex + - statesync + - rpc (safe connections only) + - with privValidator(priv_validator_key.json, priv_validator_state.json) + - seed + - switch, transport + - reactor + - p2p/pex +- Configuration, cli command + - We would like to suggest by introducing `mode` parameter in `config.toml` and cli + - `mode = "{{ .BaseConfig.Mode }}"` in `config.toml` + - `tendermint start --mode validator` in cli + - full | validator | seednode + - There will be no default. Users will need to specify when they run `tendermint init` +- RPC modification + - `host:26657/status` + - return empty `validator_info` when in full mode + - no rpc server in seednode +- Where to modify in codebase + - Add switch for `config.Mode` on `node/node.go:DefaultNewNode` + - If `config.Mode==validator`, call default `NewNode` (current logic) + - If `config.Mode==full`, call `NewNode` with `nil` `privValidator` (do not load or generation) + - Need to add exception routine for `nil` `privValidator` to related functions + - If `config.Mode==seed`, call `NewSeedNode` (seed node version of `node/node.go:NewNode`) + - Need to add exception routine for `nil` `reactor`, `component` to related functions + +## Status + +Implemented + +## Consequences + +### Positive + +- Node operators can choose mode when they run state machine according to the purpose of the node. +- Mode can prevent mistakes because users have to specify which mode they want to run via flag. (eg. If a user want to run a validator node, she/he should explicitly write down validator as mode) +- Different mode needs different reactors, resulting in efficient resource usage. + +### Negative + +- Users need to study how each mode operate and which capability it has. + +### Neutral + +## References + +- Issue [#2237](https://github.com/tendermint/tendermint/issues/2237) : Tendermint "mode" +- [TenderSeed](https://gitlab.com/polychainlabs/tenderseed) : A lightweight Tendermint Seed Node. diff --git a/docs/architecture/tendermint-core/adr-053-state-sync-prototype.md b/docs/architecture/tendermint-core/adr-053-state-sync-prototype.md new file mode 100644 index 0000000..0764058 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-053-state-sync-prototype.md @@ -0,0 +1,254 @@ +# ADR 053: State Sync Prototype + +State sync is now [merged](https://github.com/tendermint/tendermint/pull/4705). Up-to-date ABCI documentation is [available](https://github.com/tendermint/spec/pull/90), refer to it rather than this ADR for details. + +This ADR outlines the plan for an initial state sync prototype, and is subject to change as we gain feedback and experience. It builds on discussions and findings in [ADR-042](./adr-042-state-sync.md), see that for background information. + +## Changelog + +* 2020-01-28: Initial draft (Erik Grinaker) + +* 2020-02-18: Updates after initial prototype (Erik Grinaker) + * ABCI: added missing `reason` fields. + * ABCI: used 32-bit 1-based chunk indexes (was 64-bit 0-based). + * ABCI: moved `RequestApplySnapshotChunk.chain_hash` to `RequestOfferSnapshot.app_hash`. + * Gaia: snapshots must include node versions as well, both for inner and leaf nodes. + * Added experimental prototype info. + * Added open questions and implementation plan. + +* 2020-03-29: Strengthened and simplified ABCI interface (Erik Grinaker) + * ABCI: replaced `chunks` with `chunk_hashes` in `Snapshot`. + * ABCI: removed `SnapshotChunk` message. + * ABCI: renamed `GetSnapshotChunk` to `LoadSnapshotChunk`. + * ABCI: chunks are now exchanged simply as `bytes`. + * ABCI: chunks are now 0-indexed, for parity with `chunk_hashes` array. + * Reduced maximum chunk size to 16 MB, and increased snapshot message size to 4 MB. + +* 2020-04-29: Update with final released ABCI interface (Erik Grinaker) + +## Context + +State sync will allow a new node to receive a snapshot of the application state without downloading blocks or going through consensus. This bootstraps the node significantly faster than the current fast sync system, which replays all historical blocks. + +Background discussions and justifications are detailed in [ADR-042](./adr-042-state-sync.md). Its recommendations can be summarized as: + +* The application periodically takes full state snapshots (i.e. eager snapshots). + +* The application splits snapshots into smaller chunks that can be individually verified against a chain app hash. + +* Tendermint uses the light client to obtain a trusted chain app hash for verification. + +* Tendermint discovers and downloads snapshot chunks in parallel from multiple peers, and passes them to the application via ABCI to be applied and verified against the chain app hash. + +* Historical blocks are not backfilled, so state synced nodes will have a truncated block history. + +## Tendermint Proposal + +This describes the snapshot/restore process seen from Tendermint. The interface is kept as small and general as possible to give applications maximum flexibility. + +### Snapshot Data Structure + +A node can have multiple snapshots taken at various heights. Snapshots can be taken in different application-specified formats (e.g. MessagePack as format `1` and Protobuf as format `2`, or similarly for schema versioning). Each snapshot consists of multiple chunks containing the actual state data, for parallel downloads and reduced memory usage. + +```proto +message Snapshot { + uint64 height = 1; // The height at which the snapshot was taken + uint32 format = 2; // The application-specific snapshot format + uint32 chunks = 3; // Number of chunks in the snapshot + bytes hash = 4; // Arbitrary snapshot hash - should be equal only for identical snapshots + bytes metadata = 5; // Arbitrary application metadata +} +``` + +Chunks are exchanged simply as `bytes`, and cannot be larger than 16 MB. `Snapshot` messages should be less than 4 MB. + +### ABCI Interface + +```proto +// Lists available snapshots +message RequestListSnapshots {} + +message ResponseListSnapshots { + repeated Snapshot snapshots = 1; +} + +// Offers a snapshot to the application +message RequestOfferSnapshot { + Snapshot snapshot = 1; // snapshot offered by peers + bytes app_hash = 2; // light client-verified app hash for snapshot height + } + +message ResponseOfferSnapshot { + Result result = 1; + + enum Result { + accept = 0; // Snapshot accepted, apply chunks + abort = 1; // Abort all snapshot restoration + reject = 2; // Reject this specific snapshot, and try a different one + reject_format = 3; // Reject all snapshots of this format, and try a different one + reject_sender = 4; // Reject all snapshots from the sender(s), and try a different one + } +} + +// Loads a snapshot chunk +message RequestLoadSnapshotChunk { + uint64 height = 1; + uint32 format = 2; + uint32 chunk = 3; // Zero-indexed +} + +message ResponseLoadSnapshotChunk { + bytes chunk = 1; +} + +// Applies a snapshot chunk +message RequestApplySnapshotChunk { + uint32 index = 1; + bytes chunk = 2; + string sender = 3; + } + +message ResponseApplySnapshotChunk { + Result result = 1; + repeated uint32 refetch_chunks = 2; // Chunks to refetch and reapply (regardless of result) + repeated string reject_senders = 3; // Chunk senders to reject and ban (regardless of result) + + enum Result { + accept = 0; // Chunk successfully accepted + abort = 1; // Abort all snapshot restoration + retry = 2; // Retry chunk, combine with refetch and reject as appropriate + retry_snapshot = 3; // Retry snapshot, combine with refetch and reject as appropriate + reject_snapshot = 4; // Reject this snapshot, try a different one but keep sender rejections + } +} +``` + +### Taking Snapshots + +Tendermint is not aware of the snapshotting process at all, it is entirely an application concern. The following guarantees must be provided: + +* **Periodic:** snapshots must be taken periodically, not on-demand, for faster restores, lower load, and less DoS risk. + +* **Deterministic:** snapshots must be deterministic, and identical across all nodes - typically by taking a snapshot at given height intervals. + +* **Consistent:** snapshots must be consistent, i.e. not affected by concurrent writes - typically by using a data store that supports versioning and/or snapshot isolation. + +* **Asynchronous:** snapshots must be asynchronous, i.e. not halt block processing and state transitions. + +* **Chunked:** snapshots must be split into chunks of reasonable size (on the order of megabytes), and each chunk must be verifiable against the chain app hash. + +* **Garbage collected:** snapshots must be garbage collected periodically. + +### Restoring Snapshots + +Nodes should have options for enabling state sync and/or fast sync, and be provided a trusted header hash for the light client. + +When starting an empty node with state sync and fast sync enabled, snapshots are restored as follows: + +1. The node checks that it is empty, i.e. that it has no state nor blocks. + +2. The node contacts the given seeds to discover peers. + +3. The node contacts a set of full nodes, and verifies the trusted block header using the given hash via the light client. + +4. The node requests available snapshots via P2P from peers, via `RequestListSnapshots`. Peers will return the 10 most recent snapshots, one message per snapshot. + +5. The node aggregates snapshots from multiple peers, ordered by height and format (in reverse). If there are mismatches between different snapshots, the one hosted by the largest amount of peers is chosen. The node iterates over all snapshots in reverse order by height and format until it finds one that satisfies all of the following conditions: + + * The snapshot height's block is considered trustworthy by the light client (i.e. snapshot height is greater than trusted header and within unbonding period of the latest trustworthy block). + + * The snapshot's height or format hasn't been explicitly rejected by an earlier `RequestOfferSnapshot`. + + * The application accepts the `RequestOfferSnapshot` call. + +6. The node downloads chunks in parallel from multiple peers, via `RequestLoadSnapshotChunk`. Chunk messages cannot exceed 16 MB. + +7. The node passes chunks sequentially to the app via `RequestApplySnapshotChunk`. + +8. Once all chunks have been applied, the node compares the app hash to the chain app hash, and if they do not match it either errors or discards the state and starts over. + +9. The node switches to fast sync to catch up blocks that were committed while restoring the snapshot. + +10. The node switches to normal consensus mode. + +## Gaia Proposal + +This describes the snapshot process seen from Gaia, using format version `1`. The serialization format is unspecified, but likely to be compressed Amino or Protobuf. + +### Snapshot Metadata + +In the initial version there is no snapshot metadata, so it is set to an empty byte buffer. + +Once all chunks have been successfully built, snapshot metadata should be stored in a database and served via `RequestListSnapshots`. + +### Snapshot Chunk Format + +The Gaia data structure consists of a set of named IAVL trees. A root hash is constructed by taking the root hashes of each of the IAVL trees, then constructing a Merkle tree of the sorted name/hash map. + +IAVL trees are versioned, but a snapshot only contains the version relevant for the snapshot height. All historical versions are ignored. + +IAVL trees are insertion-order dependent, so key/value pairs must be set in an appropriate insertion order to produce the same tree branching structure. This insertion order can be found by doing a breadth-first scan of all nodes (including inner nodes) and collecting unique keys in order. However, the node hash also depends on the node's version, so snapshots must contain the inner nodes' version numbers as well. + +For the initial prototype, each chunk consists of a complete dump of all node data for all nodes in an entire IAVL tree. Thus the number of chunks equals the number of persistent stores in Gaia. No incremental verification of chunks is done, only a final app hash comparison at the end of the snapshot restoration. + +For a production version, it should be sufficient to store key/value/version for all nodes (leaf and inner) in insertion order, chunked in some appropriate way. If per-chunk verification is required, the chunk must also contain enough information to reconstruct the Merkle proofs all the way up to the root of the multistore, e.g. by storing a complete subtree's key/value/version data plus Merkle hashes of all other branches up to the multistore root. The exact approach will depend on tradeoffs between size, time, and verification. IAVL RangeProofs are not recommended, since these include redundant data such as proofs for intermediate and leaf nodes that can be derived from the above data. + +Chunks should be built greedily by collecting node data up to some size limit (e.g. 10 MB) and serializing it. Chunk data is stored in the file system as `snapshots///`, and a SHA-256 checksum is stored along with the snapshot metadata. + +### Snapshot Scheduling + +Snapshots should be taken at some configurable height interval, e.g. every 1000 blocks. All nodes should preferably have the same snapshot schedule, such that all nodes can serve chunks for a given snapshot. + +Taking consistent snapshots of IAVL trees is greatly simplified by them being versioned: simply snapshot the version that corresponds to the snapshot height, while concurrent writes create new versions. IAVL pruning must not prune a version that is being snapshotted. + +Snapshots must also be garbage collected after some configurable time, e.g. by keeping the latest `n` snapshots. + +## Resolved Questions + +* Is it OK for state-synced nodes to not have historical blocks nor historical IAVL versions? + + > Yes, this is as intended. Maybe backfill blocks later. + +* Do we need incremental chunk verification for first version? + + > No, we'll start simple. Can add chunk verification via a new snapshot format without any breaking changes in Tendermint. For adversarial conditions, maybe consider support for whitelisting peers to download chunks from. + +* Should the snapshot ABCI interface be a separate optional ABCI service, or mandatory? + + > Mandatory, to keep things simple for now. It will therefore be a breaking change and push the release. For apps using the Cosmos SDK, we can provide a default implementation that does not serve snapshots and errors when trying to apply them. + +* How can we make sure `ListSnapshots` data is valid? An adversary can provide fake/invalid snapshots to DoS peers. + + > For now, just pick snapshots that are available on a large number of peers. Maybe support whitelisting. We may consider e.g. placing snapshot manifests on the blockchain later. + +* Should we punish nodes that provide invalid snapshots? How? + + > No, these are full nodes not validators, so we can't punish them. Just disconnect from them and ignore them. + +* Should we call these snapshots? The SDK already uses the term "snapshot" for `PruningOptions.SnapshotEvery`, and state sync will introduce additional SDK options for snapshot scheduling and pruning that are not related to IAVL snapshotting or pruning. + + > Yes. Hopefully these concepts are distinct enough that we can refer to state sync snapshots and IAVL snapshots without too much confusion. + +* Should we store snapshot and chunk metadata in a database? Can we use the database for chunks? + + > As a first approach, store metadata in a database and chunks in the filesystem. + +* Should a snapshot at height H be taken before or after the block at H is processed? E.g. RPC `/commit` returns app_hash after _previous_ height, i.e. _before_ current height. + + > After commit. + +* Do we need to support all versions of blockchain reactor (i.e. fast sync)? + + > We should remove the v1 reactor completely once v2 has stabilized. + +* Should `ListSnapshots` be a streaming API instead of a request/response API? + + > No, just use a max message size. + +## Status + +Implemented + +## References + +* [ADR-042](./adr-042-state-sync.md) and its references diff --git a/docs/architecture/tendermint-core/adr-054-crypto-encoding-2.md b/docs/architecture/tendermint-core/adr-054-crypto-encoding-2.md new file mode 100644 index 0000000..64aa407 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-054-crypto-encoding-2.md @@ -0,0 +1,71 @@ +# ADR 054: Crypto encoding (part 2) + +## Changelog + +2020-2-27: Created +2020-4-16: Update + +## Context + +Amino has been a pain point of many users in the ecosystem. While Tendermint does not suffer greatly from the performance degradation introduced by amino, we are making an effort in moving the encoding format to a widely adopted format, [Protocol Buffers](https://developers.google.com/protocol-buffers). With this migration a new standard is needed for the encoding of keys. This will cause ecosystem wide breaking changes. + +Currently amino encodes keys as ` `. + +## Decision + +Previously Tendermint defined all the key types for use in Tendermint and the Cosmos-SDK. Going forward the Cosmos-SDK will define its own protobuf type for keys. This will allow Tendermint to only define the keys that are being used in the codebase (ed25519). +There is the the opportunity to only define the usage of ed25519 (`bytes`) and not have it be a `oneof`, but this would mean that the `oneof` work is only being postponed to a later date. When using the `oneof` protobuf type we will have to manually switch over the possible key types and then pass them to the interface which is needed. + +The approach that will be taken to minimize headaches for users is one where all encoding of keys will shift to protobuf and where amino encoding is relied on, there will be custom marshal and unmarshal functions. + +Protobuf messages: + +```proto +message PubKey { + oneof key { + bytes ed25519 = 1; + } + +message PrivKey { + oneof sum { + bytes ed25519 = 1; + } +} +``` + +> Note: The places where backwards compatibility is needed is still unclear. + +All modules currently do not rely on amino encoded bytes and keys are not amino encoded for genesis, therefore a hardfork upgrade is what will be needed to adopt these changes. + +This work will be broken out into a few PRs, this work will be merged into a proto-breakage branch, all PRs will be reviewed prior to being merged: + +1. Encoding of keys to protobuf and protobuf messages +2. Move Tendermint types to protobuf, mainly the ones that are being encoded. +3. Go one by one through the reactors and transition amino encoded messages to protobuf. +4. Test with cosmos-sdk and/or testnets repo. + +## Status + +Implemented + +## Consequences + +- Move keys to protobuf encoding, where backwards compatibility is needed, amino marshal and unmarshal functions will be used. + +### Positive + +- Protocol Buffer encoding will not change going forward. +- Removing amino overhead from keys will help with the KSM. +- Have a large ecosystem of supported languages. + +### Negative + +- Hardfork is required to integrate this into running chains. + +### Neutral + +## References + +> Are there any relevant PR comments, issues that led up to this, or articles referenced for why we made the given design choice? If so link them here! + +- {reference link} diff --git a/docs/architecture/tendermint-core/adr-055-protobuf-design.md b/docs/architecture/tendermint-core/adr-055-protobuf-design.md new file mode 100644 index 0000000..fa48c74 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-055-protobuf-design.md @@ -0,0 +1,61 @@ +# ADR 055: Protobuf Design + +## Changelog + +- 2020-4-15: Created (@marbar3778) +- 2020-6-18: Updated (@marbar3778) + +## Context + +Currently we use [go-amino](https://github.com/tendermint/go-amino) throughout Tendermint. Amino is not being maintained anymore (April 15, 2020) by the Tendermint team and has been found to have issues: + +- https://github.com/tendermint/go-amino/issues/286 +- https://github.com/tendermint/go-amino/issues/230 +- https://github.com/tendermint/go-amino/issues/121 + +These are a few of the known issues that users could run into. + +Amino enables quick prototyping and development of features. While this is nice, amino does not provide the performance and developer convenience that is expected. For Tendermint to see wider adoption as a BFT protocol engine a transition to an adopted encoding format is needed. Below are some possible options that can be explored. + +There are a few options to pick from: + +- `Protobuf`: Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. It is supported in countless languages and has been proven in production for many years. + +- `FlatBuffers`: FlatBuffers is an efficient cross platform serialization library. Flatbuffers are more efficient than Protobuf due to the fast that there is no parsing/unpacking to a second representation. FlatBuffers has been tested and used in production but is not widely adopted. + +- `CapnProto`: Cap’n Proto is an insanely fast data interchange format and capability-based RPC system. Cap'n Proto does not have a encoding/decoding step. It has not seen wide adoption throughout the industry. + +- @erikgrinaker - https://github.com/tendermint/tendermint/pull/4623#discussion_r401163501 + ``` + Cap'n'Proto is awesome. It was written by one of the original Protobuf developers to fix some of its issues, and supports e.g. random access to process huge messages without loading them into memory and an (opt-in) canonical form which would be very useful when determinism is needed (e.g. in the state machine). That said, I suspect Protobuf is the better choice due to wider adoption, although it makes me kind of sad since Cap'n'Proto is technically better. + ``` + +## Decision + +Transition Tendermint to Protobuf because of its performance and tooling. The Ecosystem behind Protobuf is vast and has outstanding [support for many languages](https://developers.google.com/protocol-buffers/docs/tutorials). + +We will be making this possible by keeping the current types in there current form (handwritten) and creating a `/proto` directory in which all the `.proto` files will live. Where encoding is needed, on disk and over the wire, we will call util functions that will transition the types from handwritten go types to protobuf generated types. This is inline with the recommended file structure from [buf](https://buf.build). You can find more information on this file structure [here](https://buf.build/docs/lint-checkers#file_layout). + +By going with this design we will enable future changes to types and allow for a more modular codebase. + +## Status + +Implemented + +## Consequences + +### Positive + +- Allows for modular types in the future +- Less refactoring +- Allows the proto files to be pulled into the spec repo in the future. +- Performance +- Tooling & support in multiple languages + +### Negative + +- When a developer is updating a type they need to make sure to update the proto type as well + +### Neutral + +## References diff --git a/docs/architecture/tendermint-core/adr-056-light-client-amnesia-attacks.md b/docs/architecture/tendermint-core/adr-056-light-client-amnesia-attacks.md new file mode 100644 index 0000000..e768af9 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-056-light-client-amnesia-attacks.md @@ -0,0 +1,170 @@ +# ADR 056: Light client amnesia attacks + +## Changelog + +- 02.04.20: Initial Draft +- 06.04.20: Second Draft +- 10.06.20: Post Implementation Revision +- 19.08.20: Short Term Amnesia Alteration +- 01.10.20: Status of Amnesia for 0.34 + +## Context + +Whilst most created evidence of malicious behavior is self evident such that any individual can verify them independently there are types of evidence, known collectively as global evidence, that require further collaboration from the network in order to accumulate enough information to create evidence that is individually verifiable and can therefore be processed through consensus. [Fork Accountability](https://github.com/tendermint/tendermint/blob/main/spec/consensus/light-client/accountability.md) has been coined to describe the entire process of detection, proving and punishing of malicious behavior. This ADR addresses specifically what a light client amnesia attack is and how it can be proven and the current decision around handling light client amnesia attacks. For information on evidence handling by the light client, it is recommended to read [ADR 47](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-047-handling-evidence-from-light-client.md). + +### Amnesia Attack + +The schematic below explains a scenario where an amnesia attack can occur such that two sets of honest nodes, C1 and C2, commit different blocks. + +![](./img/tm-amnesia-attack.png) + +1. C1 and F send PREVOTE messages for block A. +2. C1 sends PRECOMMIT for round 1 for block A. +3. A new round is started, C2 and F send PREVOTE messages for a different block B. +4. C2 and F then send PRECOMMIT messages for block B. +5. F later on creates PRECOMMITS for block A and combines it with those from C1 to form a block + + +This forged block can then be used to fool light clients trying to verify it. It must be stressed that there are a few more hurdles or dimensions to the attack to consider.For a more detailed walkthrough refer to Appendix A. + +## Decision + +The decision surrounding amnesia attacks has both a short term and long term component. In the long term, a more sturdy protocol will need to be fleshed out and implemented. There is already draft documents outlining what such a protocol would look like and the resources it would require (see references). Prior revisions however outlined a protocol which had been implemented (See Appendix B). It was agreed that it still required greater consideration and review given it's importance. It was therefore discussed, with the limited time frame set before 0.34, whether the protocol should be completely removed or if there should remain some logic in handling the aforementioned scenarios. + +The latter of the two options meant storing a record of all votes in any height with which there was more than one round. This information would then be accessible for applications if they wanted to perform some off-chain verification and punishment. + +In summary, this seemed like too much to ask of the application to implement only on a temporary basis, whilst not having the domain specific knowledge and considering such a difficult and unlikely attack. Therefore the short term decision is to identify when the attack has occurred and implement the detector algorithm highlighted in [ADR 47](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-047-handling-evidence-from-light-client.md) but to not implement any accountability protocol that would identify malicious validators and allow applications to punish them. This will hopefully change in the long term with the focus on eventually reaching a concrete and secure protocol with identifying and dealing with these attacks. + +## Implications + +- Light clients will still be able to detect amnesia attacks so long as the assumption of having at least one correct witness holds +- Light clients will gossip the attack to witnesses and halt thus failing to validate the incorrect block (and therefore not being fooled) +- Validators will propose and commit evidence of the amnesia attack on chain +- No evidence will be passed to the application indicting any malicious validators, thus meaning that no malicious validators will be punished for performing the attack +- If a light clients bubble of providers are all faulty the light client will falsely validate amnesia attacks as well as any other 1/3+ light client attack. + +## Status + +Implemented + +## Consequences + +### Positive + +Light clients are still able to prevent falsely validating a block. + +Already implemented. + +### Negative + +Light clients where all witnesses are faulty can be subject to an amnesia attack and verify a forged block that is not part of the chain. + +### Neutral + + +## References + +- [Fork accountability algorithm](https://docs.google.com/document/d/11ZhMsCj3y7zIZz4udO9l25xqb0kl7gmWqNpGVRzOeyY/edit) +- [Fork accountability spec](https://github.com/tendermint/tendermint/blob/main/spec/consensus/light-client/accountability.md) + +## Appendix A: Detailed Walkthrough of Performing a Light Client Amnesia Attack + +As the attacker, a prerequisite to this attack is first to observe or attempt to craft a block where a subset (less than ⅓) of correct validators sent precommit votes for a proposal in an earlier round and later received ⅔ prevotes for a different proposal thus changing their lock and correctly sending precommit votes (and later committing) for the proposal in the latter round. The second prerequisite is to have at least ⅓ validating power in that height (or enough voting power to have ⅔+ when combined with the precommits of the earlier round). + +To go back to how one may craft such a block, we begin with one of the validators in this cabal being the proposer. They propose a block with all the txs that they want to fool a light client with. The proposer then only relays this to the members of their cabal and a controlled subset of correct validators (less than ⅓). We will call ourselves f for faulty and c1 for this correct subset. + +Attackers need to rely on the assistance of some form of a network partition or on the nature of the sporadic voting to conjure their desired environment. The attackers need at least ⅓ of the validating power of the remaining correct validators, we shall denote this as c2, to not see ⅔ prevotes and thus not be locked on a block when it comes to the next round. If we have less than ⅓ remaining validators that don’t see this first proposal, then we will not have enough voting power to reach ⅔+ prevotes (the sum of f and c2) in the following round and thus change the lock of c1 such that we correctly commit the block in the latter round yet have enough precommits in the earlier round to fool the light client. Remember this is our desired scenario: to save all these precommit votes for a different (in this case earlier) proposed block. + +To try to break this down even further let’s go back to the first round. F sends c1 a proposal (and not c2), c1 in turn sends their prevotes to all whom they are connected to. This means that some will be received by c2. F then sends their prevotes just to c1. Now not all validators in c1 may be connected to each other, so perhaps some validators in c1 might not receive ⅔ (from their own cohort and from f) and thus not precommit. In other situations we may see a validator in c2 connected to all validators in c1. Therefore they too will receive ⅔ prevotes and thus precommit. We can conclude therefore that although targeting this c1 subset of validators, those that actually precommit may be somewhat different. The key is for the attackers to observe the n amount of precommits they need in round 1 where n is ⅔+ - f, whilst ensuring that n itself does not go over ⅓. If it does then less than ⅔ validators remain to be able to change the lock and commit the block in the later round. + +An extra dimension to this puzzle is the timeouts. Whilst c1 is relaying votes to its peers and these validators count closer towards the ⅔ threshold needed to send their precommit votes at any moment the timeout could be reached and thus the nodes will precommit nil and ignore any late prevote messages. + +This is all to say that such an attack is partly out of the attackers hands. All they can do is tweak the subset of validators that they first choose to gossip the proposal and modify the timings around when they send their prevotes until they reach the desired precondition: n precommits for an earlier proposal and ⅔ precommits for the later proposal. So this is up to the gods of non deterministic behavior to help them out with their plight. I’m not going to allocate the hours to calculate the probability but it could be in the magnitude of 1000’s of blocks trying to get this scenario before the precondition is met. + +Obviously, the probability becomes substantially higher as the cabal’s voting power nears ⅔. This is because both n decreases and there is greater tolerance to send prevotes to a greater amount of validators without going overboard and reaching the ⅓ precommit threshold in the first round which would mean they would have to try again. + +Once we’ve got our n, we can then forge the remaining signatures for that block (from the f) and bundle them all together and tada we have a forged signed header. + +Now we’ve done that, it’s time to find some light clients to fool. + +Also critical to this type of attack is that the light client that is connected to our nodes must request a light block at that specific height with which we forged this signed header but this shouldn’t be hard to do. To bring this back to a real context, say our faulty cabal, f, bought some groceries using atoms and then wanted to prove that they did, the grocery owner whips out their phone, runs the light client and f tells them the height they committed the transaction. + +An important note here is that because the validator sets are the same between the canonical and the forged block, this attack also works on light clients that verify sequentially. In fact, they are especially vulnerable because they currently don’t run the detector function afterwards. + +However, if our grocery owner verifies using the skipping algorithm, they will then run the detector and therefore they will compare with other witness nodes. Ideally for our attackers, if f has a lot of nodes exposing their rpc endpoints, then there is a chance that all the witnesses the light client has are faulty and thus we have a successful attack and the grocery owner has been fooled into handing f a few apples and carrots. + +However, there is a greater chance, especially if the light client is connected to quite a few other nodes that a divergence will be detected. The light client will figure out there was an amnesia attack and send the evidence to the witness to commit on chain. The grocery owner will see that verification failed and won't hand over the apples or carrots but also f won't be punished for their villainous behavior. This means that they can go over to the hairdressers and see if they can pull off the same stunt again. + +So this brings to the fore the current defenses that are in place. As long as there has not been a cabal of validators with greater than 1/3 power (or the trust level), the light clients verification algorithm will prevent any attempts to deceive it. Greater than this threshold and we rely on the detector as a second layer of defense to pick up on any attack. It's security is chiefly tied with the assumption that at least one of the witnesses is correct. If this fails then as illustrated above, the light client can be suceptible to amnesia (as well as equivocation and lunatic) attacks. + +The outstanding problem, if we indeed consider it big enough to be one, therefore lies in the incentivisation mechanism which is how f and other malicious validators are punished. This is decided by the application but it's up to Tendermint to identify them. With other forms of attacks the evidence lies in the precommits. But because an amnesia attack uses precommits from another round, which is information that is discarded by the consensus engine once the block is committed, it is difficult to understand which validators were in fact faulty. + +If we cast our minds back to what I previously wrote, part of an amnesia attack depends on getting n precommits from an earlier round. These are then bundled with the malicious validators' own signatures. This means that the light client nor full nodes are capable of distinguishing which of the signatures were correctly created as part of Tendermint consensus and which were forged later on. + +## Appendix B: Prior Amnesia Evidence Accountability Implementation + +As the distinction between these two attacks (amnesia and back to the past) can only be distinguished by confirming with all validators (to see if it is a full fork or a light fork), for the purpose of simplicity, these attacks will be treated as the same. + +Currently, the evidence reactor is used to simply broadcast and store evidence. The idea of creating a new reactor for the specific task of verifying these attacks was briefly discussed, but it is decided that the current evidence reactor will be extended. + +The process begins with a light client receiving conflicting headers (in the future this could also be a full node during fast sync or state sync), which it sends to a full node to analyze. As part of [evidence handling](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-047-handling-evidence-from-light-client.md), this is extracted into potential amnesia evidence when the validator voted in more than one round for a different block. + +```golang +type PotentialAmnesiaEvidence struct { + VoteA *types.Vote + VoteB *types.Vote + + Heightstamp int64 +} +``` + +*NOTE: There had been an earlier notion towards batching evidence against the entire set of validators all together but this has given way to individual processing predominantly to maintain consistency with the other forms of evidence. A more extensive breakdown can be found [here](https://github.com/tendermint/tendermint/issues/4729)* + +The evidence will contain the precommit votes for a validator that voted for both rounds. If the validator voted in more than two rounds, then they will have multiple `PotentialAmnesiaEvidence` against them hence it is possible that there is multiple evidence for a validator in a single height but not for a single round. The votes should be all valid and the height and time that the infringement was made should be within: + +`MaxEvidenceAge - ProofTrialPeriod` + +This trial period will be discussed later. + +Returning to the event of an amnesia attack, if we were to examine the behavior of the honest nodes, C1 and C2, in the schematic, C2 will not PRECOMMIT an earlier round, but it is likely, if a node in C1 were to receive +2/3 PREVOTE's or PRECOMMIT's for a higher round, that it would remove the lock and PREVOTE and PRECOMMIT for the later round. Therefore, unfortunately it is not a case of simply punishing all nodes that have double voted in the `PotentialAmnesiaEvidence`. + +Instead we use the Proof of Lock Change (PoLC) referred to in the [consensus spec](https://github.com/tendermint/tendermint/blob/main/spec/consensus/consensus.md#terms). When an honest node votes again for a different block in a later round +(which will only occur in very rare cases), it will generate the PoLC and store it in the evidence reactor for a time equal to the `MaxEvidenceAge` + +```golang +type ProofOfLockChange struct { + Votes []*types.Vote + PubKey crypto.PubKey +} +``` + +This can be either evidence of +2/3 PREVOTES or PRECOMMITS (either warrants the honest node the right to vote) and is valid, among other checks, so long as the PRECOMMIT vote of the node in V2 came after all the votes in the `ProofOfLockChange` i.e. it received +2/3 votes for a block and then voted for that block thereafter (F is unable to prove this). + +In the event that an honest node receives `PotentialAmnesiaEvidence` it will first `ValidateBasic()` and `Verify()` it and then will check if it is among the suspected nodes in the evidence. If so, it will retrieve the `ProofOfLockChange` and combine it with `PotentialAmensiaEvidence` to form `AmensiaEvidence`. All honest nodes that are part of the indicted group will have a time, measured in blocks, equal to `ProofTrialPeriod`, the aforementioned evidence paramter, to gossip their `AmnesiaEvidence` with their `ProofOfLockChange` + +```golang +type AmnesiaEvidence struct { + *types.PotentialAmnesiaEvidence + Polc *types.ProofOfLockChange +} +``` + +If the node is not required to submit any proof than it will simply broadcast the `PotentialAmnesiaEvidence`, stamp the height that it received the evidence and begin to wait out the trial period. It will ignore other `PotentialAmnesiaEvidence` gossiped at the same height and round. + +If a node receives `AmnesiaEvidence` that contains a valid `ProofOfClockChange` it will add it to the evidence store and replace any PotentialAmnesiaEvidence of the same height and round. At this stage, an amnesia evidence with polc, it is ready to be submitted to the chin. If a node receives `AmnesiaEvidence` with an empty polc it will ignore it as each honest node will conduct their own trial period to be sure that time was given for any other honest nodes to respond. + +There can only be one `AmnesiaEvidence` and one `PotentialAmneisaEvidence` stored for each attack (i.e. for each height). + +When, `state.LastBlockHeight > PotentialAmnesiaEvidence.timestamp + ProofTrialPeriod`, nodes will upgrade the corresponding `PotentialAmnesiaEvidence` and attach an empty `ProofOfLockChange`. Then honest validators of the current validator set can begin proposing the block that contains the `AmnesiaEvidence`. + +*NOTE: Even before the evidence is proposed and committed, the off-chain process of gossiping valid evidence could be + enough for honest nodes to recognize the fork and halt.* + +Other validators will vote `nil` if: + +- The Amnesia Evidence is not valid +- The Amensia Evidence is not within their own trial period i.e. too soon. +- They don't have the Amnesia Evidence and it is has an empty polc (each validator needs to run their own trial period of the evidence) +- Is of an AmnesiaEvidence that has already been committed to the chain. + +Finally it is important to stress that the protocol of having a trial period addresses attacks where a validator voted again for a different block at a later round and time. In the event, however, that the validator voted for an earlier round after voting for a later round i.e. `VoteA.Timestamp < VoteB.Timestamp && VoteA.Round > VoteB.Round` then this action is inexcusable and can be punished immediately without the need of a trial period. In this case, PotentialAmnesiaEvidence will be instantly upgraded to AmnesiaEvidence. diff --git a/docs/architecture/tendermint-core/adr-057-RPC.md b/docs/architecture/tendermint-core/adr-057-RPC.md new file mode 100644 index 0000000..aa87b82 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-057-RPC.md @@ -0,0 +1,90 @@ +# ADR 057: RPC + +## Changelog + +- 19-05-2020: created + +## Context + +Currently the RPC layer of Tendermint is using a variant of the JSON-RPC protocol. This ADR is meant to serve as a pro/con list for possible alternatives and JSON-RPC. + +There are currently two options being discussed: gRPC & JSON-RPC. + +### JSON-RPC + +JSON-RPC is a JSON-based RPC protocol. Tendermint has implemented its own variant of JSON-RPC which is not compatible with the [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification). + +**Pros:** + +- Easy to use & implement (by default) +- Well-known and well-understood by users and integrators +- Integrates reasonably well with web infrastructure (proxies, API gateways, service meshes, caches, etc) +- human readable encoding (by default) + +**Cons:** + +- No schema support +- RPC clients must be hand-written +- Streaming not built into protocol +- Underspecified types (e.g. numbers and timestamps) +- Tendermint has its own implementation (not standards compliant, maintenance overhead) + - High maintenance cost associated to this +- Stdlib `jsonrpc` package only supports JSON-RPC 1.0, no dominant package for JSON-RPC 2.0 +- Tooling around documentation/specification (e.g. Swagger) could be better +- JSON data is larger (offset by HTTP compression) +- Serializing is slow ([~100% marshal, ~400% unmarshal](https://github.com/alecthomas/go_serialization_benchmarks)); insignificant in absolute terms +- Specification was last updated in 2013 and is way behind Swagger/OpenAPI + +### gRPC + gRPC-gateway (REST + Swagger) + +gRPC is a high performant RPC framework. It has been battle tested by a large number of users and is heavily relied on and maintained by countless large corporations. + +**Pros:** + +- Efficient data retrieval for users, lite clients and other protocols +- Easily implemented in supported languages (Go, Dart, JS, TS, rust, Elixir, Haskell, ...) +- Defined schema with richer type system (Protocol Buffers) +- Can use common schemas and types across all protocols and data stores (RPC, ABCI, blocks, etc) +- Established conventions for forwards- and backwards-compatibility +- Bi-directional streaming +- Servers and clients are be autogenerated in many languages (e.g. Tendermint-rs) +- Auto-generated swagger documentation for REST API +- Backwards and forwards compatibility guarantees enforced at the protocol level. +- Can be used with different codecs (JSON, CBOR, ...) + +**Cons:** + +- Complex system involving cross-language schemas, code generation, and custom protocols +- Type system does not always map cleanly to native language type system; integration woes +- Many common types require Protobuf plugins (e.g. timestamps and duration) +- Generated code may be non-idiomatic and hard to use +- Migration will be disruptive and laborious + +## Decision + +> This section explains all of the details of the proposed solution, including implementation details. +> It should also describe affects / corollary items that may need to be changed as a part of this. +> If the proposed change will be large, please also indicate a way to do the change to maximize ease of review. +> (e.g. the optimal split of things to do between separate PR's) + +## Status + +> A decision may be "proposed" if it hasn't been agreed upon yet, or "accepted" once it is agreed upon. If a later ADR changes or reverses a decision, it may be marked as "deprecated" or "superseded" with a reference to its replacement. + +{Deprecated|Proposed|Accepted} + +## Consequences + +> This section describes the consequences, after applying the decision. All consequences should be summarized here, not just the "positive" ones. + +### Positive + +### Negative + +### Neutral + +## References + +> Are there any relevant PR comments, issues that led up to this, or articles referenced for why we made the given design choice? If so link them here! + +- {reference link} diff --git a/docs/architecture/tendermint-core/adr-058-event-hashing.md b/docs/architecture/tendermint-core/adr-058-event-hashing.md new file mode 100644 index 0000000..6c4bb63 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-058-event-hashing.md @@ -0,0 +1,122 @@ +# ADR 058: Event hashing + +## Changelog + +- 2020-07-17: initial version +- 2020-07-27: fixes after Ismail and Ethan's comments +- 2020-07-27: declined + +## Context + +Before [PR#4845](https://github.com/tendermint/tendermint/pull/4845), +`Header#LastResultsHash` was a root of the Merkle tree built from `DeliverTx` +results. Only `Code`, `Data` fields were included because `Info` and `Log` +fields are non-deterministic. + +At some point, we've added events to `ResponseBeginBlock`, `ResponseEndBlock`, +and `ResponseDeliverTx` to give applications a way to attach some additional +information to blocks / transactions. + +Many applications seem to have started using them since. + +However, before [PR#4845](https://github.com/tendermint/tendermint/pull/4845) +there was no way to prove that certain events were a part of the result +(_unless the application developer includes them into the state tree_). + +Hence, [PR#4845](https://github.com/tendermint/tendermint/pull/4845) was +opened. In it, `GasWanted` along with `GasUsed` are included when hashing +`DeliverTx` results. Also, events from `BeginBlock`, `EndBlock` and `DeliverTx` +results are hashed into the `LastResultsHash` as follows: + +- Since we do not expect `BeginBlock` and `EndBlock` to contain many events, + these will be Protobuf encoded and included in the Merkle tree as leaves. +- `LastResultsHash` therefore is the root hash of a Merkle tree w/ 3 leafs: + proto-encoded `ResponseBeginBlock#Events`, root hash of a Merkle tree build + from `ResponseDeliverTx` responses (Log, Info and Codespace fields are + ignored), and proto-encoded `ResponseEndBlock#Events`. +- Order of events is unchanged - same as received from the ABCI application. + +[Spec PR](https://github.com/tendermint/spec/pull/97/files) + +While it's certainly good to be able to prove something, introducing new events +or removing such becomes difficult because it breaks the `LastResultsHash`. It +means that every time you add, remove or update an event, you'll need a +hard-fork. And that is undoubtedly bad for applications, which are evolving and +don't have a stable events set. + +## Decision + +As a middle ground approach, the proposal is to add the +`Block#LastResultsEvents` consensus parameter that is a list of all events that +are to be hashed in the header. + +``` +@ proto/tendermint/abci/types.proto:295 @ message BlockParams { + int64 max_bytes = 1; + // Note: must be greater or equal to -1 + int64 max_gas = 2; + // List of events, which will be hashed into the LastResultsHash + repeated string last_results_events = 3; +} +``` + +Initially the list is empty. The ABCI application can change it via `InitChain` +or `EndBlock`. + +Example: + +```go +func (app *MyApp) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx { + //... + events := []abci.Event{ + { + Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: []byte("sender"), Value: []byte("Bob"), Index: true}, + }, + }, + } + return types.ResponseDeliverTx{Code: code.CodeTypeOK, Events: events} +} +``` + +For "transfer" event to be hashed, the `LastResultsEvents` must contain a +string "transfer". + +## Status + +Declined + +**Until there's more stability/motivation/use-cases/demand, the decision is to +push this entirely application side and just have apps which want events to be +provable to insert them into their application-side merkle trees. Of course +this puts more pressure on their application state and makes event proving +application specific, but it might help built up a better sense of use-cases +and how this ought to ultimately be done by Tendermint.** + +## Consequences + +### Positive + +1. networks can perform parameter change proposals to update this list as new events are added +2. allows networks to avoid having to do hard-forks +3. events can still be added at-will to the application w/o breaking anything + +### Negative + +1. yet another consensus parameter +2. more things to track in the tendermint state + +## References + +- [ADR 021](./adr-021-abci-events.md) +- [Indexing transactions](../app-dev/indexing-transactions.md) + +## Appendix A. Alternative proposals + +The other proposal was to add `Hash bool` flag to the `Event`, similarly to +`Index bool` EventAttribute's field. When `true`, Tendermint would hash it into +the `LastResultsEvents`. The downside is that the logic is implicit and depends +largely on the node's operator, who decides what application code to run. The +above proposal makes it (the logic) explicit and easy to upgrade via +governance. diff --git a/docs/architecture/tendermint-core/adr-059-evidence-composition-and-lifecycle.md b/docs/architecture/tendermint-core/adr-059-evidence-composition-and-lifecycle.md new file mode 100644 index 0000000..28f72ab --- /dev/null +++ b/docs/architecture/tendermint-core/adr-059-evidence-composition-and-lifecycle.md @@ -0,0 +1,306 @@ +# ADR 059: Evidence Composition and Lifecycle + +## Changelog + +- 04/09/2020: Initial Draft (Unabridged) +- 07/09/2020: First Version +- 13/03/2021: Ammendment to accomodate forward lunatic attack +- 29/06/2021: Add information about ABCI specific fields + +## Scope + +This document is designed to collate together and surface some predicaments involving evidence in Tendermint: both its composition and lifecycle. It then aims to find a solution to these. The scope does not extend to the verification nor detection of certain types of evidence but concerns itself mainly with the general form of evidence and how it moves from inception to application. + +## Background + +For a long time `DuplicateVoteEvidence`, formed in the consensus reactor, was the only evidence Tendermint had. It was produced whenever two votes from the same validator in the same round +was observed and thus it was designed that each evidence was for a single validator. It was predicted that there may come more forms of evidence and thus `DuplicateVoteEvidence` was used as the model for the `Evidence` interface and also for the form of the evidence data sent to the application. It is important to note that Tendermint concerns itself just with the detection and reporting of evidence and it is the responsibility of the application to exercise punishment. + +```go +type Evidence interface { //existing + Height() int64 // height of the offense + Time() time.Time // time of the offense + Address() []byte // address of the offending validator + Bytes() []byte // bytes which comprise the evidence + Hash() []byte // hash of the evidence + Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence + Equal(Evidence) bool // check equality of evidence + + ValidateBasic() error + String() string +} +``` + +```go +type DuplicateVoteEvidence struct { + VoteA *Vote + VoteB *Vote + + timestamp time.Time // taken from the block time +} +``` + +Tendermint has now introduced a new type of evidence to protect light clients from being attacked. This `LightClientAttackEvidence` (see [here](https://github.com/informalsystems/tendermint-rs/blob/31ca3e64ce90786c1734caf186e30595832297a4/docs/spec/lightclient/attacks/evidence-handling.md) for more information) is vastly different to `DuplicateVoteEvidence` in that it is physically a much different size containing a complete signed header and validator set. It is formed within the light client, not the consensus reactor and requires a lot more information from state to verify (`VerifyLightClientAttack(commonHeader, trustedHeader *SignedHeader, commonVals *ValidatorSet)` vs `VerifyDuplicateVote(chainID string, pubKey PubKey)`). Finally it batches validators together (a single piece of evidence that implicates multiple malicious validators at a height) as opposed to having individual evidence (each piece of evidence is per validator per height). This evidence stretches the existing mould that was used to accommodate new types of evidence and has thus caused us to reconsider how evidence should be formatted and processed. + +```go +type LightClientAttackEvidence struct { // proposed struct in spec + ConflictingBlock *LightBlock + CommonHeight int64 + Type AttackType // enum: {Lunatic|Equivocation|Amnesia} + + timestamp time.Time // taken from the block time at the common height +} +``` +*Note: These three attack types have been proven by the research team to be exhaustive* + +## Possible Approaches for Evidence Composition + +### Individual framework + +Evidence remains on a per validator basis. This causes the least disruption to the current processes but requires that we break `LightClientAttackEvidence` into several pieces of evidence for each malicious validator. This not only has performance consequences in that there are n times as many database operations and that the gossiping of evidence will require more bandwidth then necessary (by requiring a header for each piece) but it potentially impacts our ability to validate it. In batch form, the full node can run the same process the light client did to see that 1/3 validating power was present in both the common block and the conflicting block whereas this becomes more difficult to verify individually without opening the possibility that malicious validators forge evidence against innocent . Not only that, but `LightClientAttackEvidence` also deals with amnesia attacks which unfortunately have the characteristic where we know the set of validators involved but not the subset that were actually malicious (more to be said about this later). And finally splitting the evidence into individual pieces makes it difficult to understand the severity of the attack (i.e. the total voting power involved in the attack) + +#### An example of a possible implementation path + +We would ignore amnesia evidence (as individually it's hard to make) and revert to the initial split we had before where `DuplicateVoteEvidence` is also used for light client equivocation attacks and thus we only need `LunaticEvidence`. We would also most likely need to remove `Verify` from the interface as this isn't really something that can be used. + +``` go +type LunaticEvidence struct { // individual lunatic attack + header *Header + commonHeight int64 + vote *Vote + + timestamp time.Time // once again taken from the block time at the height of the common header +} +``` + +### Batch Framework + +The last approach of this category would be to consider batch only evidence. This works fine with `LightClientAttackEvidence` but would require alterations to `DuplicateVoteEvidence` which would most likely mean that the consensus would send conflicting votes to a buffer in the evidence module which would then wrap all the votes together per height before gossiping them to other nodes and trying to commit it on chain. At a glance this may improve IO and verification speed and perhaps more importantly grouping validators gives the application and Tendermint a better overview of the severity of the attack. + +However individual evidence has the advantage that it is easy to check if a node already has that evidence meaning we just need to check hashes to know that we've already verified this evidence before. Batching evidence would imply that each node may have a different combination of duplicate votes which may complicate things. + +#### An example of a possible implementation path + +`LightClientAttackEvidence` won't change but the evidence interface will need to look like the proposed one above and `DuplicateVoteEvidence` will need to change to encompass multiple double votes. A problem with batch evidence is that it needs to be unique to avoid people from submitting different permutations. + +## Decision + +The decision is to adopt a hybrid design. + +We allow individual and batch evidence to coexist together, meaning that verification is done depending on the evidence type and that the bulk of the work is done in the evidence pool itself (including forming the evidence to be sent to the application). + + +## Detailed Design + +Evidence has the following simple interface: + +```go +type Evidence interface { //proposed + Height() int64 // height of the offense + Bytes() []byte // bytes which comprise the evidence + Hash() []byte // hash of the evidence + ValidateBasic() error + String() string +} +``` + +The changing of the interface is backwards compatible as these methods are all present in the previous version of the interface. However, networks will need to upgrade to be able to process the new evidence as verification has changed. + +We have two concrete types of evidence that fulfil this interface + +```go +type LightClientAttackEvidence struct { + ConflictingBlock *LightBlock + CommonHeight int64 // the last height at which the primary provider and witness provider had the same header + + // abci specific information + ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block + TotalVotingPower int64 // total voting power of the validator set at the common height + Timestamp time.Time // timestamp of the block at the common height +} +``` +where the `Hash()` is the hash of the header and commonHeight. + +Note: It was also discussed whether to include the commit hash which captures the validators that signed the header. However this would open the opportunity for someone to propose multiple permutations of the same evidence (through different commit signatures) hence it was omitted. Consequentially, when it comes to verifying evidence in a block, for `LightClientAttackEvidence` we can't just check the hashes because someone could have the same hash as us but a different commit where less than 1/3 validators voted which would be an invalid version of the evidence. (see `fastCheck` for more details) + +```go +type DuplicateVoteEvidence { + VoteA *Vote + VoteB *Vote + + // abci specific information + TotalVotingPower int64 + ValidatorPower int64 + Timestamp time.Time +} +``` +where the `Hash()` is the hash of the two votes + +For both of these types of evidence, `Bytes()` represents the proto-encoded byte array format of the evidence and `ValidateBasic` is +an initial consistency check to make sure the evidence has a valid structure. + +### The Evidence Pool + +`LightClientAttackEvidence` is generated in the light client and `DuplicateVoteEvidence` in consensus. Both are sent to the evidence pool through `AddEvidence(ev Evidence) error`. The evidence pool's primary purpose is to verify evidence. It also gossips evidence to other peers' evidence pool and serves it to consensus so it can be committed on chain and the relevant information can be sent to the application in order to exercise punishment. When evidence is added, the pool first runs `Has(ev Evidence)` to check if it has already received it (by comparing hashes) and then `Verify(ev Evidence) error`. Once verified the evidence pool stores it it's pending database. There are two databases: one for pending evidence that is not yet committed and another of the committed evidence (to avoid committing evidence twice) + +#### Verification + +`Verify()` does the following: + +- Use the hash to see if we already have this evidence in our committed database. + +- Use the height to check if the evidence hasn't expired. + +- If it has expired then use the height to find the block header and check if the time has also expired in which case we drop the evidence + +- Then proceed with switch statement for each of the two evidence: + +For `DuplicateVote`: + +- Check that height, round, type and validator address are the same + +- Check that the Block ID is different + +- Check the look up table for addresses to make sure there already isn't evidence against this validator + +- Fetch the validator set and confirm that the address is in the set at the height of the attack + +- Check that the chain ID and signature is valid. + +For `LightClientAttack` + +- Fetch the common signed header and val set from the common height and use skipping verification to verify the conflicting header + +- Fetch the trusted signed header at the same height as the conflicting header and compare with the conflicting header to work out which type of attack it is and in doing so return the malicious validators. NOTE: If the node doesn't have the signed header at the height of the conflicting header, it instead fetches the latest header it has and checks to see if it can prove the evidence based on a violation of header time. This is known as forward lunatic attack. + + - If equivocation, return the validators that signed for the commits of both the trusted and signed header + + - If lunatic, return the validators from the common val set that signed in the conflicting block + + - If amnesia, return no validators (since we can't know which validators are malicious). This also means that we don't currently send amnesia evidence to the application, although we will introduce more robust amnesia evidence handling in future Tendermint Core releases + +- Check that the hashes of the conflicting header and the trusted header are different + +- In the case of a forward lunatic attack, where the trusted header height is less than the conflicting header height, the node checks that the time of the trusted header is later than the time of conflicting header. This proves that the conflicting header breaks monotonically increasing time. If the node doesn't have a trusted header with a later time then it is unable to validate the evidence for now. + +- Lastly, for each validator, check the look up table to make sure there already isn't evidence against this validator + +After verification we persist the evidence with the key `height/hash` to the pending evidence database in the evidence pool. + +#### ABCI Evidence + +Both evidence structures contain data (such as timestamp) that are necessary to be passed to the application but do not strictly constitute evidence of misbehavior. As such, these fields are verified last. If any of these fields are invalid to a node i.e. they don't correspond with their state, nodes will reconstruct a new evidence struct from the existing fields and repopulate the abci specific fields with their own state data. + +#### Broadcasting and receiving evidence + +The evidence pool also runs a reactor that broadcasts the newly validated +evidence to all connected peers. + +Receiving evidence from other evidence reactors works in the same manner as receiving evidence from the consensus reactor or a light client. + + +#### Proposing evidence on the block + +When it comes to prevoting and precomitting a proposal that contains evidence, the full node will once again +call upon the evidence pool to verify the evidence using `CheckEvidence(ev []Evidence)`: + +This performs the following actions: + +1. Loops through all the evidence to check that nothing has been duplicated + +2. For each evidence, run `fastCheck(ev evidence)` which works similar to `Has` but instead for `LightClientAttackEvidence` if it has the +same hash it then goes on to check that the validators it has are all signers in the commit of the conflicting header. If it doesn't pass fast check (because it hasn't seen the evidence before) then it will have to verify the evidence. + +3. runs `Verify(ev Evidence)` - Note: this also saves the evidence to the db as mentioned before. + + +#### Updating application and pool + +The final part of the lifecycle is when the block is committed and the `BlockExecutor` then updates state. As part of this process, the `BlockExecutor` gets the evidence pool to create a simplified format for the evidence to be sent to the application. This happens in `ApplyBlock` where the executor calls `Update(Block, State) []abci.Evidence`. + +```go +abciResponses.BeginBlock.ByzantineValidators = evpool.Update(block, state) +``` + +Here is the format of the evidence that the application will receive. As seen above, this is stored as an array within `BeginBlock`. +The changes to the application are minimal (it is still formed one for each malicious validator) with the exception of using an enum instead of a string for the evidence type. + +```go +type Evidence struct { + // either LightClientAttackEvidence or DuplicateVoteEvidence as an enum (abci.EvidenceType) + Type EvidenceType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.abci.EvidenceType" json:"type,omitempty"` + // The offending validator + Validator Validator `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator"` + // The height when the offense occurred + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + // The corresponding time where the offense occurred + Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"` + // Total voting power of the validator set in case the ABCI application does + // not store historical validators. + // https://github.com/tendermint/tendermint/issues/4581 + TotalVotingPower int64 `protobuf:"varint,5,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` +} +``` + + +This `Update()` function does the following: + +- Increments state which keeps track of both the current time and height used for measuring expiry + +- Marks evidence as committed and saves to db. This prevents validators from proposing committed evidence in the future + Note: the db just saves the height and the hash. There is no need to save the entire committed evidence + +- Forms ABCI evidence as such: (note for `DuplicateVoteEvidence` the validators array size is 1) + ```go + for _, val := range evInfo.Validators { + abciEv = append(abciEv, &abci.Evidence{ + Type: evType, // either DuplicateVote or LightClientAttack + Validator: val, // the offending validator (which includes the address, pubkey and power) + Height: evInfo.ev.Height(), // the height when the offense happened + Time: evInfo.time, // the time when the offense happened + TotalVotingPower: evInfo.totalVotingPower // the total voting power of the validator set + }) + } + ``` + +- Removes expired evidence from both pending and committed databases + +The ABCI evidence is then sent via the `BlockExecutor` to the application. + +#### Summary + +To summarize, we can see the lifecycle of evidence as such: + +![evidence_lifecycle](./img/evidence_lifecycle.png) + +Evidence is first detected and created in the light client and consensus reactor. It is verified and stored as `EvidenceInfo` and gossiped to the evidence pools in other nodes. The consensus reactor later communicates with the evidence pool to either retrieve evidence to be put into a block, or verify the evidence the consensus reactor has retrieved in a block. Lastly when a block is added to the chain, the block executor sends the committed evidence back to the evidence pool so a pointer to the evidence can be stored in the evidence pool and it can update it's height and time. Finally, it turns the committed evidence into ABCI evidence and through the block executor passes the evidence to the application so the application can handle it. + +## Status + +Implemented + +## Consequences + + + +### Positive + +- Evidence is better contained to the evidence pool / module +- LightClientAttack is kept together (easier for verification and bandwidth) +- Variations on commit sigs in LightClientAttack doesn't lead to multiple permutations and multiple evidence +- Address to evidence map prevents DOS attacks, where a single validator could DOS the network by flooding it with evidence submissions + +### Negative + +- Changes the `Evidence` interface and thus is a block breaking change +- Changes the ABCI `Evidence` and is thus a ABCI breaking change +- Unable to query evidence for address / time without evidence pool + +### Neutral + + +## References + + + +- [LightClientAttackEvidence](https://github.com/informalsystems/tendermint-rs/blob/31ca3e64ce90786c1734caf186e30595832297a4/docs/spec/lightclient/attacks/evidence-handling.md) diff --git a/docs/architecture/tendermint-core/adr-060-go-api-stability.md b/docs/architecture/tendermint-core/adr-060-go-api-stability.md new file mode 100644 index 0000000..ee335d2 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-060-go-api-stability.md @@ -0,0 +1,193 @@ +# ADR 060: Go API Stability + +## Changelog + +- 2020-09-08: Initial version. (@erikgrinaker) + +- 2020-09-09: Tweak accepted changes, add initial public API packages, add consequences. (@erikgrinaker) + +- 2020-09-17: Clarify initial public API. (@erikgrinaker) + +## Context + +With the release of Tendermint 1.0 we will adopt [semantic versioning](https://semver.org). One major implication is a guarantee that we will not make backwards-incompatible changes until Tendermint 2.0 (except in pre-release versions). In order to provide this guarantee for our Go API, we must clearly define which of our APIs are public, and what changes are considered backwards-compatible. + +Currently, we list packages that we consider public in our [README](https://github.com/tendermint/tendermint#versioning), but since we are still at version 0.x we do not provide any backwards compatiblity guarantees at all. + +### Glossary + +* **External project:** a different Git/VCS repository or code base. + +* **External package:** a different Go package, can be a child or sibling package in the same project. + +* **Internal code:** code not intended for use in external projects. + +* **Internal directory:** code under `internal/` which cannot be imported in external projects. + +* **Exported:** a Go identifier starting with an uppercase letter, which can therefore be accessed by an external package. + +* **Private:** a Go identifier starting with a lowercase letter, which therefore cannot be accessed by an external package unless via an exported field, variable, or function/method return value. + +* **Public API:** any Go identifier that can be imported or accessed by an external project, except test code in `_test.go` files. + +* **Private API:** any Go identifier that is not accessible via a public API, including all code in the internal directory. + +## Alternative Approaches + +- Split all public APIs out to separate Go modules in separate Git repositories, and consider all Tendermint code internal and not subject to API backwards compatibility at all. This was rejected, since it has been attempted by the Tendermint project earlier, resulting in too much dependency management overhead. + +- Simply document which APIs are public and which are private. This is the current approach, but users should not be expected to self-enforce this, the documentation is not always up-to-date, and external projects will often end up depending on internal code anyway. + +## Decision + +From Tendermint 1.0, all internal code (except private APIs) will be placed in a root-level [`internal` directory](https://golang.org/cmd/go/#hdr-Internal_Directories), which the Go compiler will block for use by external projects. All exported items outside of the `internal` directory are considered a public API and subject to backwards compatibility guarantees, except files ending in `_test.go`. + +The `crypto` package may be split out to a separate module in a separate repo. This is the main general-purpose package used by external projects, and is the only Tendermint dependency in e.g. IAVL which can cause some problems for projects depending on both IAVL and Tendermint. This will be decided after further discussion. + +The `tm-db` package will remain a separate module in a separate repo. The `crypto` package may possibly be split out, pending further discussion, as this is the main general-purpose package used by other projects. + +## Detailed Design + +### Public API + +When preparing our public API for 1.0, we should keep these principles in mind: + +- Limit the number of public APIs that we start out with - we can always add new APIs later, but we can't change or remove APIs once they're made public. + +- Before an API is made public, do a thorough review of the API to make sure it covers any future needs, can accomodate expected changes, and follows good API design practices. + +The following is the minimum set of public APIs that will be included in 1.0, in some form: + +- `abci` +- packages used for constructing nodes `config`, `libs/log`, and `version` +- Client APIs, i.e. `rpc/client`, `light`, and `privval`. +- `crypto` (possibly as a separate repo) + +We may offer additional APIs as well, following further discussions internally and with other stakeholders. However, public APIs for providing custom components (e.g. reactors and mempools) are not planned for 1.0, but may be added in a later 1.x version if this is something we want to offer. + +For comparison, the following are the number of Tendermint imports in the Cosmos SDK (excluding tests), which should be mostly satisfied by the planned APIs. + +``` + 1 github.com/tendermint/tendermint/abci/server + 73 github.com/tendermint/tendermint/abci/types + 2 github.com/tendermint/tendermint/cmd/tendermint/commands + 7 github.com/tendermint/tendermint/config + 68 github.com/tendermint/tendermint/crypto + 1 github.com/tendermint/tendermint/crypto/armor + 10 github.com/tendermint/tendermint/crypto/ed25519 + 2 github.com/tendermint/tendermint/crypto/encoding + 3 github.com/tendermint/tendermint/crypto/merkle + 3 github.com/tendermint/tendermint/crypto/sr25519 + 8 github.com/tendermint/tendermint/crypto/tmhash + 1 github.com/tendermint/tendermint/crypto/xsalsa20symmetric + 11 github.com/tendermint/tendermint/libs/bytes + 2 github.com/tendermint/tendermint/libs/bytes.HexBytes + 15 github.com/tendermint/tendermint/libs/cli + 2 github.com/tendermint/tendermint/libs/cli/flags + 2 github.com/tendermint/tendermint/libs/json + 30 github.com/tendermint/tendermint/libs/log + 1 github.com/tendermint/tendermint/libs/math + 11 github.com/tendermint/tendermint/libs/os + 4 github.com/tendermint/tendermint/libs/rand + 1 github.com/tendermint/tendermint/libs/strings + 5 github.com/tendermint/tendermint/light + 1 github.com/tendermint/tendermint/internal/mempool + 3 github.com/tendermint/tendermint/node + 5 github.com/tendermint/tendermint/internal/p2p + 4 github.com/tendermint/tendermint/privval + 10 github.com/tendermint/tendermint/proto/tendermint/crypto + 1 github.com/tendermint/tendermint/proto/tendermint/libs/bits + 24 github.com/tendermint/tendermint/proto/tendermint/types + 3 github.com/tendermint/tendermint/proto/tendermint/version + 2 github.com/tendermint/tendermint/proxy + 3 github.com/tendermint/tendermint/rpc/client + 1 github.com/tendermint/tendermint/rpc/client/http + 2 github.com/tendermint/tendermint/rpc/client/local + 3 github.com/tendermint/tendermint/rpc/core/types + 1 github.com/tendermint/tendermint/rpc/jsonrpc/server + 33 github.com/tendermint/tendermint/types + 2 github.com/tendermint/tendermint/types/time + 1 github.com/tendermint/tendermint/version +``` + +### Backwards-Compatible Changes + +In Go, [almost all API changes are backwards-incompatible](https://blog.golang.org/module-compatibility) and thus exported items in public APIs generally cannot be changed until Tendermint 2.0. The only backwards-compatible changes we can make to public APIs are: + +- Adding a package. + +- Adding a new identifier to the package scope (e.g. const, var, func, struct, interface, etc.). + +- Adding a new method to a struct. + +- Adding a new field to a struct, if the zero-value preserves any old behavior. + +- Changing the order of fields in a struct. + +- Adding a variadic parameter to a named function or struct method, if the function type itself is not assignable in any public APIs (e.g. a callback). + +- Adding a new method to an interface, or a variadic parameter to an interface method, _if the interface already has a private method_ (which prevents external packages from implementing it). + +- Widening a numeric type as long as it is a named type (e.g. `type Number int32` can change to `int64`, but not `int8` or `uint32`). + +Note that public APIs can expose private types (e.g. via an exported variable, field, or function/method return value), in which case the exported fields and methods on these private types are also part of the public API and covered by its backwards compatiblity guarantees. In general, private types should never be accessible via public APIs unless wrapped in an exported interface. + +Also note that if we accept, return, export, or embed types from a dependency, we assume the backwards compatibility responsibility for that dependency, and must make sure any dependency upgrades comply with the above constraints. + +We should run CI linters for minor version branches to enforce this, e.g. [apidiff](https://go.googlesource.com/exp/+/refs/heads/master/apidiff/README.md), [breakcheck](https://github.com/gbbr/breakcheck), and [apicombat](https://github.com/bradleyfalzon/apicompat). + +#### Accepted Breakage + +The above changes can still break programs in a few ways - these are _not_ considered backwards-incompatible changes, and users are advised to avoid this usage: + +- If a program uses unkeyed struct literals (e.g. `Foo{"bar", "baz"}`) and we add fields or change the field order, the program will no longer compile or may have logic errors. + +- If a program embeds two structs in a struct, and we add a new field or method to an embedded Tendermint struct which also exists in the other embedded struct, the program will no longer compile. + +- If a program compares two structs (e.g. with `==`), and we add a new field of an incomparable type (slice, map, func, or struct that contains these) to a Tendermint struct which is compared, the program will no longer compile. + +- If a program assigns a Tendermint function to an identifier, and we add a variadic parameter to the function signature, the program will no longer compile. + +### Strategies for API Evolution + +The API guarantees above can be fairly constraining, but are unavoidable given the Go language design. The following tricks can be employed where appropriate to allow us to make changes to the API: + +- We can add a new function or method with a different name that takes additional parameters, and have the old function call the new one. + +- Functions and methods can take an options struct instead of separate parameters, to allow adding new options - this is particularly suitable for functions that take many parameters and are expected to be extended, and especially for interfaces where we cannot add new methods with different parameters at all. + +- Interfaces can include a private method, e.g. `interface { private() }`, to make them unimplementable by external packages and thus allow us to add new methods to the interface without breaking other programs. Of course, this can't be used for interfaces that should be implementable externally. + +- We can use [interface upgrades](https://avtok.com/2014/11/05/interface-upgrades.html) to allow implementers of an existing interface to also implement a new interface, as long as the old interface can still be used - e.g. the new interface `BetterReader` may have a method `ReadBetter()`, and a function that takes a `Reader` interface as an input can check if the implementer also implements `BetterReader` and in that case call `ReadBetter()` instead of `Read()`. + +## Status + +Proposed + +## Consequences + +### Positive + +- Users can safely upgrade with less fear of applications breaking, and know whether an upgrade only includes bug fixes or also functional enhancements + +- External developers have a predictable and well-defined API to build on that will be supported for some time + +- Less synchronization between teams, since there is a clearer contract and timeline for changes and they happen less frequently + +- More documentation will remain accurate, since it's not chasing a moving target + +- Less time will be spent on code churn and more time spent on functional improvements, both for the community and for our teams + +### Negative + +- Many improvements, changes, and bug fixes will have to be postponed until the next major version, possibly for a year or more + +- The pace of development will slow down, since we must work within the existing API constraints, and spend more time planning public APIs + +- External developers may lose access to some currently exported APIs and functionality + +## References + +- [#4451: Place internal APIs under internal package](https://github.com/tendermint/tendermint/issues/4451) + +- [On Pluggability](https://docs.google.com/document/d/1G08LnwSyb6BAuCVSMF3EKn47CGdhZ5wPZYJQr4-bw58/edit?ts=5f609f11) diff --git a/docs/architecture/tendermint-core/adr-061-p2p-refactor-scope.md b/docs/architecture/tendermint-core/adr-061-p2p-refactor-scope.md new file mode 100644 index 0000000..35494ab --- /dev/null +++ b/docs/architecture/tendermint-core/adr-061-p2p-refactor-scope.md @@ -0,0 +1,109 @@ +# ADR 061: P2P Refactor Scope + +## Changelog + +- 2020-10-30: Initial version (@erikgrinaker) + +## Context + +The `p2p` package responsible for peer-to-peer networking is rather old and has a number of weaknesses, including tight coupling, leaky abstractions, lack of tests, DoS vulnerabilites, poor performance, custom protocols, and incorrect behavior. A refactor has been discussed for several years ([#2067](https://github.com/tendermint/tendermint/issues/2067)). + +Informal Systems are also building a Rust implementation of Tendermint, [Tendermint-rs](https://github.com/informalsystems/tendermint-rs), and plan to implement P2P networking support over the next year. As part of this work, they have requested adopting e.g. [QUIC](https://datatracker.ietf.org/doc/draft-ietf-quic-transport/) as a transport protocol instead of implementing the custom application-level `MConnection` stream multiplexing protocol that Tendermint currently uses. + +This ADR summarizes recent discussion with stakeholders on the scope of a P2P refactor. Specific designs and implementations will be submitted as separate ADRs. + +## Alternative Approaches + +There have been recurring proposals to adopt [LibP2P](https://libp2p.io) instead of maintaining our own P2P networking stack (see [#3696](https://github.com/tendermint/tendermint/issues/3696)). While this appears to be a good idea in principle, it would be a highly breaking protocol change, there are indications that we might have to fork and modify LibP2P, and there are concerns about the abstractions used. + +In discussions with Informal Systems we decided to begin with incremental improvements to the current P2P stack, add support for pluggable transports, and then gradually start experimenting with LibP2P as a transport layer. If this proves successful, we can consider adopting it for higher-level components at a later time. + +## Decision + +The P2P stack will be refactored and improved iteratively, in several phases: + +* **Phase 1:** code and API refactoring, maintaining protocol compatibility as far as possible. + +* **Phase 2:** additional transports and incremental protocol improvements. + +* **Phase 3:** disruptive protocol changes. + +The scope of phases 2 and 3 is still uncertain, and will be revisited once the preceding phases have been completed as we'll have a better sense of requirements and challenges. + +## Detailed Design + +Separate ADRs will be submitted for specific designs and changes in each phase, following research and prototyping. Below are objectives in order of priority. + +### Phase 1: Code and API Refactoring + +This phase will focus on improving the internal abstractions and implementations in the `p2p` package. As far as possible, it should not change the P2P protocol in a backwards-incompatible way. + +* Cleaner, decoupled abstractions for e.g. `Reactor`, `Switch`, and `Peer`. [#2067](https://github.com/tendermint/tendermint/issues/2067) [#5287](https://github.com/tendermint/tendermint/issues/5287) [#3833](https://github.com/tendermint/tendermint/issues/3833) + * Reactors should receive messages in separate goroutines or via buffered channels. [#2888](https://github.com/tendermint/tendermint/issues/2888) +* Improved peer lifecycle management. [#3679](https://github.com/tendermint/tendermint/issues/3679) [#3719](https://github.com/tendermint/tendermint/issues/3719) [#3653](https://github.com/tendermint/tendermint/issues/3653) [#3540](https://github.com/tendermint/tendermint/issues/3540) [#3183](https://github.com/tendermint/tendermint/issues/3183) [#3081](https://github.com/tendermint/tendermint/issues/3081) [#1356](https://github.com/tendermint/tendermint/issues/1356) + * Peer prioritization. [#2860](https://github.com/tendermint/tendermint/issues/2860) [#2041](https://github.com/tendermint/tendermint/issues/2041) +* Pluggable transports, with `MConnection` as one implementation. [#5587](https://github.com/tendermint/tendermint/issues/5587) [#2430](https://github.com/tendermint/tendermint/issues/2430) [#805](https://github.com/tendermint/tendermint/issues/805) +* Improved peer address handling. + * Address book refactor. [#4848](https://github.com/tendermint/tendermint/issues/4848) [#2661](https://github.com/tendermint/tendermint/issues/2661) + * Transport-agnostic peer addressing. [#5587](https://github.com/tendermint/tendermint/issues/5587) [#3782](https://github.com/tendermint/tendermint/issues/3782) [#3692](https://github.com/tendermint/tendermint/issues/3692) + * Improved detection and advertisement of own address. [#5588](https://github.com/tendermint/tendermint/issues/5588) [#4260](https://github.com/tendermint/tendermint/issues/4260) [#3716](https://github.com/tendermint/tendermint/issues/3716) [#1727](https://github.com/tendermint/tendermint/issues/1727) + * Support multiple IPs per peer. [#1521](https://github.com/tendermint/tendermint/issues/1521) [#2317](https://github.com/tendermint/tendermint/issues/2317) + +The refactor should attempt to address the following secondary objectives: testability, observability, performance, security, quality-of-service, backpressure, and DoS resilience. Much of this will be revisited as explicit objectives in phase 2. + +Ideally, the refactor should happen incrementally, with regular merges to `master` every few weeks. This will take more time overall, and cause frequent breaking changes to internal Go APIs, but it reduces the branch drift and gets the code tested sooner and more broadly. + +### Phase 2: Additional Transports and Protocol Improvements + +This phase will focus on protocol improvements and other breaking changes. The following are considered proposals that will need to be evaluated separately once the refactor is done. Additional proposals are likely to be added during phase 1. + +* QUIC transport. [#198](https://github.com/tendermint/spec/issues/198) +* Noise protocol for secret connection handshake. [#5589](https://github.com/tendermint/tendermint/issues/5589) [#3340](https://github.com/tendermint/tendermint/issues/3340) +* Peer ID in connection handshake. [#5590](https://github.com/tendermint/tendermint/issues/5590) +* Peer and service discovery (e.g. RPC nodes, state sync snapshots). [#5481](https://github.com/tendermint/tendermint/issues/5481) [#4583](https://github.com/tendermint/tendermint/issues/4583) +* Rate-limiting, backpressure, and QoS scheduling. [#4753](https://github.com/tendermint/tendermint/issues/4753) [#2338](https://github.com/tendermint/tendermint/issues/2338) +* Compression. [#2375](https://github.com/tendermint/tendermint/issues/2375) +* Improved metrics and tracing. [#3849](https://github.com/tendermint/tendermint/issues/3849) [#2600](https://github.com/tendermint/tendermint/issues/2600) +* Simplified P2P configuration options. + +### Phase 3: Disruptive Protocol Changes + +This phase covers speculative, wide-reaching proposals that are poorly defined and highly uncertain. They will be evaluated once the previous phases are done. + +* Adopt LibP2P. [#3696](https://github.com/tendermint/tendermint/issues/3696) +* Allow cross-reactor communication, possibly without channels. +* Dynamic channel advertisment, as reactors are enabled/disabled. [#4394](https://github.com/tendermint/tendermint/issues/4394) [#1148](https://github.com/tendermint/tendermint/issues/1148) +* Pubsub-style networking topology and pattern. +* Support multiple chain IDs in the same network. + +## Status + +Proposed + +## Consequences + +### Positive + +* Cleaner, simpler architecture that's easier to reason about and test, and thus hopefully less buggy. + +* Improved performance and robustness. + +* Reduced maintenance burden and increased interoperability by the possible adoption of standardized protocols such as QUIC and Noise. + +* Improved usability, with better observability, simpler configuration, and more automation (e.g. peer/service/address discovery, rate-limiting, and backpressure). + +### Negative + +* Maintaining our own P2P networking stack is resource-intensive. + +* Abstracting away the underlying transport may prevent usage of advanced transport features. + +* Breaking changes to APIs and protocols are disruptive to users. + +## References + +See issue links above. + +- [#2067: P2P Refactor](https://github.com/tendermint/tendermint/issues/2067) + +- [P2P refactor brainstorm document](https://docs.google.com/document/d/1FUTADZyLnwA9z7ndayuhAdAFRKujhh_y73D0ZFdKiOQ/edit?pli=1#) diff --git a/docs/architecture/tendermint-core/adr-062-p2p-architecture.md b/docs/architecture/tendermint-core/adr-062-p2p-architecture.md new file mode 100644 index 0000000..7c005c2 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-062-p2p-architecture.md @@ -0,0 +1,617 @@ +# ADR 062: P2P Architecture and Abstractions + +## Changelog + +- 2020-11-09: Initial version (@erikgrinaker) + +- 2020-11-13: Remove stream IDs, move peer errors onto channel, note on moving PEX into core (@erikgrinaker) + +- 2020-11-16: Notes on recommended reactor implementation patterns, approve ADR (@erikgrinaker) + +- 2021-02-04: Update with new P2P core and Transport API changes (@erikgrinaker). + +## Context + +In [ADR 061](adr-061-p2p-refactor-scope.md) we decided to refactor the peer-to-peer (P2P) networking stack. The first phase is to redesign and refactor the internal P2P architecture, while retaining protocol compatibility as far as possible. + +## Alternative Approaches + +Several variations of the proposed design were considered, including e.g. calling interface methods instead of passing messages (like the current architecture), merging channels with streams, exposing the internal peer data structure to reactors, being message format-agnostic via arbitrary codecs, and so on. This design was chosen because it has very loose coupling, is simpler to reason about and more convenient to use, avoids race conditions and lock contention for internal data structures, gives reactors better control of message ordering and processing semantics, and allows for QoS scheduling and backpressure in a very natural way. + +[multiaddr](https://github.com/multiformats/multiaddr) was considered as a transport-agnostic peer address format over regular URLs, but it does not appear to have very widespread adoption, and advanced features like protocol encapsulation and tunneling do not appear to be immediately useful to us. + +There were also proposals to use LibP2P instead of maintaining our own P2P stack, which were rejected (for now) in [ADR 061](adr-061-p2p-refactor-scope.md). + +The initial version of this ADR had a byte-oriented multi-stream transport API, but this had to be abandoned/postponed to maintain backwards-compatibility with the existing MConnection protocol which is message-oriented. See the rejected RFC in [tendermint/spec#227](https://github.com/tendermint/spec/pull/227) for details. + +## Decision + +The P2P stack will be redesigned as a message-oriented architecture, primarily relying on Go channels for communication and scheduling. It will use a message-oriented transport to binary messages with individual peers, bidirectional peer-addressable channels to send and receive Protobuf messages, a router to route messages between reactors and peers, and a peer manager to manage peer lifecycle information. Message passing is asynchronous with at-most-once delivery. + +## Detailed Design + +This ADR is primarily concerned with the architecture and interfaces of the P2P stack, not implementation details. The interfaces described here should therefore be considered a rough architecture outline, not a complete and final design. + +Primary design objectives have been: + +* Loose coupling between components, for a simpler, more robust, and test-friendly architecture. +* Pluggable transports (not necessarily networked). +* Better scheduling of messages, with improved prioritization, backpressure, and performance. +* Centralized peer lifecycle and connection management. +* Better peer address detection, advertisement, and exchange. +* Wire-level backwards compatibility with current P2P network protocols, except where it proves too obstructive. + +The main abstractions in the new stack are: + +* `Transport`: An arbitrary mechanism to exchange binary messages with a peer across a `Connection`. +* `Channel`: A bidirectional channel to asynchronously exchange Protobuf messages with peers using node ID addressing. +* `Router`: Maintains transport connections to relevant peers and routes channel messages. +* `PeerManager`: Manages peer lifecycle information, e.g. deciding which peers to dial and when, using a `peerStore` for storage. +* Reactor: A design pattern loosely defined as "something which listens on a channel and reacts to messages". + +These abstractions are illustrated in the following diagram (representing the internals of node A) and described in detail below. + +![P2P Architecture Diagram](img/adr-062-architecture.svg) + +### Transports + +Transports are arbitrary mechanisms for exchanging binary messages with a peer. For example, a gRPC transport would connect to a peer over TCP/IP and send data using the gRPC protocol, while an in-memory transport might communicate with a peer running in another goroutine using internal Go channels. Note that transports don't have a notion of a "peer" or "node" as such - instead, they establish connections between arbitrary endpoint addresses (e.g. IP address and port number), to decouple them from the rest of the P2P stack. + +Transports must satisfy the following requirements: + +* Be connection-oriented, and support both listening for inbound connections and making outbound connections using endpoint addresses. + +* Support sending binary messages with distinct channel IDs (although channels and channel IDs are a higher-level application protocol concept explained in the Router section, they are threaded through the transport layer as well for backwards compatibilty with the existing MConnection protocol). + +* Exchange the MConnection `NodeInfo` and public key via a node handshake, and possibly encrypt or sign the traffic as appropriate. + +The initial transport is a port of the current MConnection protocol currently used by Tendermint, and should be backwards-compatible at the wire level. An in-memory transport for testing has also been implemented. There are plans to explore a QUIC transport that may replace the MConnection protocol. + +The `Transport` interface is as follows: + +```go +// Transport is a connection-oriented mechanism for exchanging data with a peer. +type Transport interface { + // Protocols returns the protocols supported by the transport. The Router + // uses this to pick a transport for an Endpoint. + Protocols() []Protocol + + // Endpoints returns the local endpoints the transport is listening on, if any. + // How to listen is transport-dependent, e.g. MConnTransport uses Listen() while + // MemoryTransport starts listening via MemoryNetwork.CreateTransport(). + Endpoints() []Endpoint + + // Accept waits for the next inbound connection on a listening endpoint, blocking + // until either a connection is available or the transport is closed. On closure, + // io.EOF is returned and further Accept calls are futile. + Accept() (Connection, error) + + // Dial creates an outbound connection to an endpoint. + Dial(context.Context, Endpoint) (Connection, error) + + // Close stops accepting new connections, but does not close active connections. + Close() error +} +``` + +How the transport configures listening is transport-dependent, and not covered by the interface. This typically happens during transport construction, where a single instance of the transport is created and set to listen on an appropriate network interface before being passed to the router. + +#### Endpoints + +`Endpoint` represents a transport endpoint (e.g. an IP address and port). A connection always has two endpoints: one at the local node and one at the remote peer. Outbound connections to remote endpoints are made via `Dial()`, and inbound connections to listening endpoints are returned via `Accept()`. + +The `Endpoint` struct is: + +```go +// Endpoint represents a transport connection endpoint, either local or remote. +// +// Endpoints are not necessarily networked (see e.g. MemoryTransport) but all +// networked endpoints must use IP as the underlying transport protocol to allow +// e.g. IP address filtering. Either IP or Path (or both) must be set. +type Endpoint struct { + // Protocol specifies the transport protocol. + Protocol Protocol + + // IP is an IP address (v4 or v6) to connect to. If set, this defines the + // endpoint as a networked endpoint. + IP net.IP + + // Port is a network port (either TCP or UDP). If 0, a default port may be + // used depending on the protocol. + Port uint16 + + // Path is an optional transport-specific path or identifier. + Path string +} + +// Protocol identifies a transport protocol. +type Protocol string +``` + +Endpoints are arbitrary transport-specific addresses, but if they are networked they must use IP addresses and thus rely on IP as a fundamental packet routing protocol. This enables policies for address discovery, advertisement, and exchange - for example, a private `192.168.0.0/24` IP address should only be advertised to peers on that IP network, while the public address `8.8.8.8` may be advertised to all peers. Similarly, any port numbers if given must represent TCP and/or UDP port numbers, in order to use [UPnP](https://en.wikipedia.org/wiki/Universal_Plug_and_Play) to autoconfigure e.g. NAT gateways. + +Non-networked endpoints (without an IP address) are considered local, and will only be advertised to other peers connecting via the same protocol. For example, the in-memory transport used for testing uses `Endpoint{Protocol: "memory", Path: "foo"}` as an address for the node "foo", and this should only be advertised to other nodes using `Protocol: "memory"`. + +#### Connections + +A connection represents an established transport connection between two endpoints (i.e. two nodes), which can be used to exchange binary messages with logical channel IDs (corresponding to the higher-level channel IDs used in the router). Connections are set up either via `Transport.Dial()` (outbound) or `Transport.Accept()` (inbound). + +Once a connection is esablished, `Transport.Handshake()` must be called to perform a node handshake, exchanging node info and public keys to verify node identities. Node handshakes should not really be part of the transport layer (it's an application protocol concern), this exists for backwards-compatibility with the existing MConnection protocol which conflates the two. `NodeInfo` is part of the existing MConnection protocol, but does not appear to be documented in the specification -- refer to the Go codebase for details. + +The `Connection` interface is shown below. It omits certain additions that are currently implemented for backwards compatibility with the legacy P2P stack and are planned to be removed before the final release. + +```go +// Connection represents an established connection between two endpoints. +type Connection interface { + // Handshake executes a node handshake with the remote peer. It must be + // called once the connection is established, and returns the remote peer's + // node info and public key. The caller is responsible for validation. + Handshake(context.Context, NodeInfo, crypto.PrivKey) (NodeInfo, crypto.PubKey, error) + + // ReceiveMessage returns the next message received on the connection, + // blocking until one is available. Returns io.EOF if closed. + ReceiveMessage() (ChannelID, []byte, error) + + // SendMessage sends a message on the connection. Returns io.EOF if closed. + SendMessage(ChannelID, []byte) error + + // LocalEndpoint returns the local endpoint for the connection. + LocalEndpoint() Endpoint + + // RemoteEndpoint returns the remote endpoint for the connection. + RemoteEndpoint() Endpoint + + // Close closes the connection. + Close() error +} +``` + +This ADR initially proposed a byte-oriented multi-stream connection API that follows more typical networking API conventions (using e.g. `io.Reader` and `io.Writer` interfaces which easily compose with other libraries). This would also allow moving the responsibility for message framing, node handshakes, and traffic scheduling to the common router instead of reimplementing this across transports, and would allow making better use of multi-stream protocols such as QUIC. However, this would require minor breaking changes to the MConnection protocol which were rejected, see [tendermint/spec#227](https://github.com/tendermint/spec/pull/227) for details. This should be revisited when starting work on a QUIC transport. + +### Peer Management + +Peers are other Tendermint nodes. Each peer is identified by a unique `NodeID` (tied to the node's private key). + +#### Peer Addresses + +Nodes have one or more `NodeAddress` addresses expressed as URLs that they can be reached at. Examples of node addresses might be e.g.: + +* `mconn://nodeid@host.domain.com:25567/path` +* `memory:nodeid` + +Addresses are resolved into one or more transport endpoints, e.g. by resolving DNS hostnames into IP addresses. Peers should always be expressed as address URLs rather than endpoints (which are a lower-level transport construct). + +```go +// NodeID is a hex-encoded crypto.Address. It must be lowercased +// (for uniqueness) and of length 40. +type NodeID string + +// NodeAddress is a node address URL. It differs from a transport Endpoint in +// that it contains the node's ID, and that the address hostname may be resolved +// into multiple IP addresses (and thus multiple endpoints). +// +// If the URL is opaque, i.e. of the form "scheme:opaque", then the opaque part +// is expected to contain a node ID. +type NodeAddress struct { + NodeID NodeID + Protocol Protocol + Hostname string + Port uint16 + Path string +} + +// ParseNodeAddress parses a node address URL into a NodeAddress, normalizing +// and validating it. +func ParseNodeAddress(urlString string) (NodeAddress, error) + +// Resolve resolves a NodeAddress into a set of Endpoints, e.g. by expanding +// out a DNS hostname to IP addresses. +func (a NodeAddress) Resolve(ctx context.Context) ([]Endpoint, error) +``` + +#### Peer Manager + +The P2P stack needs to track a lot of internal state about peers, such as their addresses, connection state, priorities, availability, failures, retries, and so on. This responsibility has been separated out to a `PeerManager`, which track this state for the `Router` (but does not maintain the actual transport connections themselves, which is the router's responsibility). + +The `PeerManager` is a synchronous state machine, where all state transitions are serialized (implemented as synchronous method calls holding an exclusive mutex lock). Most peer state is intentionally kept internal, stored in a `peerStore` database that persists it as appropriate, and the external interfaces pass the minimum amount of information necessary in order to avoid shared state between router goroutines. This design significantly simplifies the model, making it much easier to reason about and test than if it was baked into the asynchronous ball of concurrency that the P2P networking core must necessarily be. As peer lifecycle events are expected to be relatively infrequent, this should not significantly impact performance either. + +The `Router` uses the `PeerManager` to request which peers to dial and evict, and reports in with peer lifecycle events such as connections, disconnections, and failures as they occur. The manager can reject these events (e.g. reject an inbound connection) by returning errors. This happens as follows: + +* Outbound connections, via `Transport.Dial`: + * `DialNext()`: returns a peer address to dial, or blocks until one is available. + * `DialFailed()`: reports a peer dial failure. + * `Dialed()`: reports a peer dial success. + * `Ready()`: reports the peer as routed and ready. + * `Disconnected()`: reports a peer disconnection. + +* Inbound connections, via `Transport.Accept`: + * `Accepted()`: reports an inbound peer connection. + * `Ready()`: reports the peer as routed and ready. + * `Disconnected()`: reports a peer disconnection. + +* Evictions, via `Connection.Close`: + * `EvictNext()`: returns a peer to disconnect, or blocks until one is available. + * `Disconnected()`: reports a peer disconnection. + +These calls have the following interface: + +```go +// DialNext returns a peer address to dial, blocking until one is available. +func (m *PeerManager) DialNext(ctx context.Context) (NodeAddress, error) + +// DialFailed reports a dial failure for the given address. +func (m *PeerManager) DialFailed(address NodeAddress) error + +// Dialed reports a successful outbound connection to the given address. +func (m *PeerManager) Dialed(address NodeAddress) error + +// Accepted reports a successful inbound connection from the given node. +func (m *PeerManager) Accepted(peerID NodeID) error + +// Ready reports the peer as fully routed and ready for use. +func (m *PeerManager) Ready(peerID NodeID) error + +// EvictNext returns a peer ID to disconnect, blocking until one is available. +func (m *PeerManager) EvictNext(ctx context.Context) (NodeID, error) + +// Disconnected reports a peer disconnection. +func (m *PeerManager) Disconnected(peerID NodeID) error +``` + +Internally, the `PeerManager` uses a numeric peer score to prioritize peers, e.g. when deciding which peers to dial next. The scoring policy has not yet been implemented, but should take into account e.g. node configuration such a `persistent_peers`, uptime and connection failures, performance, and so on. The manager will also attempt to automatically upgrade to better-scored peers by evicting lower-scored peers when a better one becomes available (e.g. when a persistent peer comes back online after an outage). + +The `PeerManager` should also have an API for reporting peer behavior from reactors that affects its score (e.g. signing a block increases the score, double-voting decreases it or even bans the peer), but this has not yet been designed and implemented. + +Additionally, the `PeerManager` provides `PeerUpdates` subscriptions that will receive `PeerUpdate` events whenever significant peer state changes happen. Reactors can use these e.g. to know when peers are connected or disconnected, and take appropriate action. This is currently fairly minimal: + +```go +// Subscribe subscribes to peer updates. The caller must consume the peer updates +// in a timely fashion and close the subscription when done, to avoid stalling the +// PeerManager as delivery is semi-synchronous, guaranteed, and ordered. +func (m *PeerManager) Subscribe() *PeerUpdates + +// PeerUpdate is a peer update event sent via PeerUpdates. +type PeerUpdate struct { + NodeID NodeID + Status PeerStatus +} + +// PeerStatus is a peer status. +type PeerStatus string + +const ( + PeerStatusUp PeerStatus = "up" // Connected and ready. + PeerStatusDown PeerStatus = "down" // Disconnected. +) + +// PeerUpdates is a real-time peer update subscription. +type PeerUpdates struct { ... } + +// Updates returns a channel for consuming peer updates. +func (pu *PeerUpdates) Updates() <-chan PeerUpdate + +// Close closes the peer updates subscription. +func (pu *PeerUpdates) Close() +``` + +The `PeerManager` will also be responsible for providing peer information to the PEX reactor that can be gossipped to other nodes. This requires an improved system for peer address detection and advertisement, that e.g. reliably detects peer and self addresses and only gossips private network addresses to other peers on the same network, but this system has not yet been fully designed and implemented. + +### Channels + +While low-level data exchange happens via the `Transport`, the high-level API is based on a bidirectional `Channel` that can send and receive Protobuf messages addressed by `NodeID`. A channel is identified by an arbitrary `ChannelID` identifier, and can exchange Protobuf messages of one specific type (since the type to unmarshal into must be predefined). Message delivery is asynchronous and at-most-once. + +The channel can also be used to report peer errors, e.g. when receiving an invalid or malignant message. This may cause the peer to be disconnected or banned depending on `PeerManager` policy, but should probably be replaced by a broader peer behavior API that can also report good behavior. + +A `Channel` has this interface: + +```go +// ChannelID is an arbitrary channel ID. +type ChannelID uint16 + +// Channel is a bidirectional channel to exchange Protobuf messages with peers. +type Channel struct { + ID ChannelID // Channel ID. + In <-chan Envelope // Inbound messages (peers to reactors). + Out chan<- Envelope // outbound messages (reactors to peers) + Error chan<- PeerError // Peer error reporting. + messageType proto.Message // Channel's message type, for e.g. unmarshaling. +} + +// Close closes the channel, also closing Out and Error. +func (c *Channel) Close() error + +// Envelope specifies the message receiver and sender. +type Envelope struct { + From NodeID // Sender (empty if outbound). + To NodeID // Receiver (empty if inbound). + Broadcast bool // Send to all connected peers, ignoring To. + Message proto.Message // Message payload. +} + +// PeerError is a peer error reported via the Error channel. +type PeerError struct { + NodeID NodeID + Err error +} +``` + +A channel can reach any connected peer, and will automatically (un)marshal the Protobuf messages. Message scheduling and queueing is a `Router` implementation concern, and can use any number of algorithms such as FIFO, round-robin, priority queues, etc. Since message delivery is not guaranteed, both inbound and outbound messages may be dropped, buffered, reordered, or blocked as appropriate. + +Since a channel can only exchange messages of a single type, it is often useful to use a wrapper message type with e.g. a Protobuf `oneof` field that specifies a set of inner message types that it can contain. The channel can automatically perform this (un)wrapping if the outer message type implements the `Wrapper` interface (see [Reactor Example](#reactor-example) for an example): + +```go +// Wrapper is a Protobuf message that can contain a variety of inner messages. +// If a Channel's message type implements Wrapper, the channel will +// automatically (un)wrap passed messages using the container type, such that +// the channel can transparently support multiple message types. +type Wrapper interface { + proto.Message + + // Wrap will take a message and wrap it in this one. + Wrap(proto.Message) error + + // Unwrap will unwrap the inner message contained in this message. + Unwrap() (proto.Message, error) +} +``` + +### Routers + +The router exeutes P2P networking for a node, taking instructions from and reporting events to the `PeerManager`, maintaining transport connections to peers, and routing messages between channels and peers. + +Practically all concurrency in the P2P stack has been moved into the router and reactors, while as many other responsibilities as possible have been moved into separate components such as the `Transport` and `PeerManager` that can remain largely synchronous. Limiting concurrency to a single core component makes it much easier to reason about since there is only a single concurrency structure, while the remaining components can be serial, simple, and easily testable. + +The `Router` has a very minimal API, since it is mostly driven by `PeerManager` and `Transport` events: + +```go +// Router maintains peer transport connections and routes messages between +// peers and channels. +type Router struct { + // Some details have been omitted below. + + logger log.Logger + options RouterOptions + nodeInfo NodeInfo + privKey crypto.PrivKey + peerManager *PeerManager + transports []Transport + + peerMtx sync.RWMutex + peerQueues map[NodeID]queue + + channelMtx sync.RWMutex + channelQueues map[ChannelID]queue +} + +// OpenChannel opens a new channel for the given message type. The caller must +// close the channel when done, before stopping the Router. messageType is the +// type of message passed through the channel. +func (r *Router) OpenChannel(id ChannelID, messageType proto.Message) (*Channel, error) + +// Start starts the router, connecting to peers and routing messages. +func (r *Router) Start() error + +// Stop stops the router, disconnecting from all peers and stopping message routing. +func (r *Router) Stop() error +``` + +All Go channel sends in the `Router` and reactors are blocking (the router also selects on signal channels for closure and shutdown). The responsibility for message scheduling, prioritization, backpressure, and load shedding is centralized in a core `queue` interface that is used at contention points (i.e. from all peers to a single channel, and from all channels to a single peer): + +```go +// queue does QoS scheduling for Envelopes, enqueueing and dequeueing according +// to some policy. Queues are used at contention points, i.e.: +// - Receiving inbound messages to a single channel from all peers. +// - Sending outbound messages to a single peer from all channels. +type queue interface { + // enqueue returns a channel for submitting envelopes. + enqueue() chan<- Envelope + + // dequeue returns a channel ordered according to some queueing policy. + dequeue() <-chan Envelope + + // close closes the queue. After this call enqueue() will block, so the + // caller must select on closed() as well to avoid blocking forever. The + // enqueue() and dequeue() channels will not be closed. + close() + + // closed returns a channel that's closed when the scheduler is closed. + closed() <-chan struct{} +} +``` + +The current implementation is `fifoQueue`, which is a simple unbuffered lossless queue that passes messages in the order they were received and blocks until the message is delivered (i.e. it is a Go channel). The router will need a more sophisticated queueing policy, but this has not yet been implemented. + +The internal `Router` goroutine structure and design is described in the `Router` GoDoc, which is included below for reference: + +```go +// On startup, three main goroutines are spawned to maintain peer connections: +// +// dialPeers(): in a loop, calls PeerManager.DialNext() to get the next peer +// address to dial and spawns a goroutine that dials the peer, handshakes +// with it, and begins to route messages if successful. +// +// acceptPeers(): in a loop, waits for an inbound connection via +// Transport.Accept() and spawns a goroutine that handshakes with it and +// begins to route messages if successful. +// +// evictPeers(): in a loop, calls PeerManager.EvictNext() to get the next +// peer to evict, and disconnects it by closing its message queue. +// +// When a peer is connected, an outbound peer message queue is registered in +// peerQueues, and routePeer() is called to spawn off two additional goroutines: +// +// sendPeer(): waits for an outbound message from the peerQueues queue, +// marshals it, and passes it to the peer transport which delivers it. +// +// receivePeer(): waits for an inbound message from the peer transport, +// unmarshals it, and passes it to the appropriate inbound channel queue +// in channelQueues. +// +// When a reactor opens a channel via OpenChannel, an inbound channel message +// queue is registered in channelQueues, and a channel goroutine is spawned: +// +// routeChannel(): waits for an outbound message from the channel, looks +// up the recipient peer's outbound message queue in peerQueues, and submits +// the message to it. +// +// All channel sends in the router are blocking. It is the responsibility of the +// queue interface in peerQueues and channelQueues to prioritize and drop +// messages as appropriate during contention to prevent stalls and ensure good +// quality of service. +``` + +### Reactor Example + +While reactors are a first-class concept in the current P2P stack (i.e. there is an explicit `p2p.Reactor` interface), they will simply be a design pattern in the new stack, loosely defined as "something which listens on a channel and reacts to messages". + +Since reactors have very few formal constraints, they can be implemented in a variety of ways. There is currently no recommended pattern for implementing reactors, to avoid overspecification and scope creep in this ADR. However, prototyping and developing a reactor pattern should be done early during implementation, to make sure reactors built using the `Channel` interface can satisfy the needs for convenience, deterministic tests, and reliability. + +Below is a trivial example of a simple echo reactor implemented as a function. The reactor will exchange the following Protobuf messages: + +```protobuf +message EchoMessage { + oneof inner { + PingMessage ping = 1; + PongMessage pong = 2; + } +} + +message PingMessage { + string content = 1; +} + +message PongMessage { + string content = 1; +} +``` + +Implementing the `Wrapper` interface for `EchoMessage` allows transparently passing `PingMessage` and `PongMessage` through the channel, where it will automatically be (un)wrapped in an `EchoMessage`: + +```go +func (m *EchoMessage) Wrap(inner proto.Message) error { + switch inner := inner.(type) { + case *PingMessage: + m.Inner = &EchoMessage_PingMessage{Ping: inner} + case *PongMessage: + m.Inner = &EchoMessage_PongMessage{Pong: inner} + default: + return fmt.Errorf("unknown message %T", inner) + } + return nil +} + +func (m *EchoMessage) Unwrap() (proto.Message, error) { + switch inner := m.Inner.(type) { + case *EchoMessage_PingMessage: + return inner.Ping, nil + case *EchoMessage_PongMessage: + return inner.Pong, nil + default: + return nil, fmt.Errorf("unknown message %T", inner) + } +} +``` + +The reactor itself would be implemented e.g. like this: + +```go +// RunEchoReactor wires up an echo reactor to a router and runs it. +func RunEchoReactor(router *p2p.Router, peerManager *p2p.PeerManager) error { + channel, err := router.OpenChannel(1, &EchoMessage{}) + if err != nil { + return err + } + defer channel.Close() + peerUpdates := peerManager.Subscribe() + defer peerUpdates.Close() + + return EchoReactor(context.Background(), channel, peerUpdates) +} + +// EchoReactor provides an echo service, pinging all known peers until the given +// context is canceled. +func EchoReactor(ctx context.Context, channel *p2p.Channel, peerUpdates *p2p.PeerUpdates) error { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + for { + select { + // Send ping message to all known peers every 5 seconds. + case <-ticker.C: + channel.Out <- Envelope{ + Broadcast: true, + Message: &PingMessage{Content: "👋"}, + } + + // When we receive a message from a peer, either respond to ping, output + // pong, or report peer error on unknown message type. + case envelope := <-channel.In: + switch msg := envelope.Message.(type) { + case *PingMessage: + channel.Out <- Envelope{ + To: envelope.From, + Message: &PongMessage{Content: msg.Content}, + } + + case *PongMessage: + fmt.Printf("%q replied with %q\n", envelope.From, msg.Content) + + default: + channel.Error <- PeerError{ + PeerID: envelope.From, + Err: fmt.Errorf("unexpected message %T", msg), + } + } + + // Output info about any peer status changes. + case peerUpdate := <-peerUpdates: + fmt.Printf("Peer %q changed status to %q", peerUpdate.PeerID, peerUpdate.Status) + + // Exit when context is canceled. + case <-ctx.Done(): + return nil + } + } +} +``` + +## Status + +Proposed + +Was partially implemented in v0.35 ([#5670](https://github.com/tendermint/tendermint/issues/5670)) + +## Consequences + +### Positive + +* Reduced coupling and simplified interfaces should lead to better understandability, increased reliability, and more testing. + +* Using message passing via Go channels gives better control of backpressure and quality-of-service scheduling. + +* Peer lifecycle and connection management is centralized in a single entity, making it easier to reason about. + +* Detection, advertisement, and exchange of node addresses will be improved. + +* Additional transports (e.g. QUIC) can be implemented and used in parallel with the existing MConn protocol. + +* The P2P protocol will not be broken in the initial version, if possible. + +### Negative + +* Fully implementing the new design as indended is likely to require breaking changes to the P2P protocol at some point, although the initial implementation shouldn't. + +* Gradually migrating the existing stack and maintaining backwards-compatibility will be more labor-intensive than simply replacing the entire stack. + +* A complete overhaul of P2P internals is likely to cause temporary performance regressions and bugs as the implementation matures. + +* Hiding peer management information inside the `PeerManager` may prevent certain functionality or require additional deliberate interfaces for information exchange, as a tradeoff to simplify the design, reduce coupling, and avoid race conditions and lock contention. + +### Neutral + +* Implementation details around e.g. peer management, message scheduling, and peer and endpoint advertisement are not yet determined. + +## References + +* [ADR 061: P2P Refactor Scope](adr-061-p2p-refactor-scope.md) +* [#5670 p2p: internal refactor and architecture redesign](https://github.com/tendermint/tendermint/issues/5670) diff --git a/docs/architecture/tendermint-core/adr-063-privval-grpc.md b/docs/architecture/tendermint-core/adr-063-privval-grpc.md new file mode 100644 index 0000000..b3ffb9a --- /dev/null +++ b/docs/architecture/tendermint-core/adr-063-privval-grpc.md @@ -0,0 +1,109 @@ +# ADR 063: Privval gRPC + +## Changelog + +- 23/11/2020: Initial Version (@marbar3778) + +## Context + +Validators use remote signers to help secure their keys. This system is Tendermint's recommended way to secure validators, but the path to integration with Tendermint's private validator client is plagued with custom protocols. + +Tendermint uses its own custom secure connection protocol (`SecretConnection`) and a raw tcp/unix socket connection protocol. The secure connection protocol until recently was exposed to man in the middle attacks and can take longer to integrate if not using Golang. The raw tcp connection protocol is less custom, but has been causing minute issues with users. + +Migrating Tendermint's private validator client to a widely adopted protocol, gRPC, will ease the current maintenance and integration burden experienced with the current protocol. + +## Decision + +After discussing with multiple stake holders, [gRPC](https://grpc.io/) was decided on to replace the current private validator protocol. gRPC is a widely adopted protocol in the micro-service and cloud infrastructure world. gRPC uses [protocol-buffers](https://developers.google.com/protocol-buffers) to describe its services, providing a language agnostic implementation. Tendermint uses protobuf for on disk and over the wire encoding already making the integration with gRPC simpler. + +## Alternative Approaches + +- JSON-RPC: We did not consider JSON-RPC because Tendermint uses protobuf extensively making gRPC a natural choice. + +## Detailed Design + +With the recent integration of [Protobuf](https://developers.google.com/protocol-buffers) into Tendermint the needed changes to migrate from the current private validator protocol to gRPC is not large. + +The [service definition](https://grpc.io/docs/what-is-grpc/core-concepts/#service-definition) for gRPC will be defined as: + +```proto + service PrivValidatorAPI { + rpc GetPubKey(tendermint.proto.privval.PubKeyRequest) returns (tendermint.proto.privval.PubKeyResponse); + rpc SignVote(tendermint.proto.privval.SignVoteRequest) returns (tendermint.proto.privval.SignedVoteResponse); + rpc SignProposal(tendermint.proto.privval.SignProposalRequest) returns (tendermint.proto.privval.SignedProposalResponse); + + message PubKeyRequest { + string chain_id = 1; + } + + // PubKeyResponse is a response message containing the public key. + message PubKeyResponse { + tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; + } + + // SignVoteRequest is a request to sign a vote + message SignVoteRequest { + tendermint.types.Vote vote = 1; + string chain_id = 2; + } + + // SignedVoteResponse is a response containing a signed vote or an error + message SignedVoteResponse { + tendermint.types.Vote vote = 1 [(gogoproto.nullable) = false]; + } + + // SignProposalRequest is a request to sign a proposal + message SignProposalRequest { + tendermint.types.Proposal proposal = 1; + string chain_id = 2; + } + + // SignedProposalResponse is response containing a signed proposal or an error + message SignedProposalResponse { + tendermint.types.Proposal proposal = 1 [(gogoproto.nullable) = false]; + } +} +``` + +> Note: Remote Singer errors are removed in favor of [grpc status error codes](https://grpc.io/docs/guides/error/). + +In previous versions of the remote signer, Tendermint acted as the server and the remote signer as the client. In this process the client established a long lived connection providing a way for the server to make requests to the client. In the new version it has been simplified. Tendermint is the client and the remote signer is the server. This follows client and server architecture and simplifies the previous protocol. + +#### Keep Alive + +If you have worked on the private validator system you will see that we are removing the `PingRequest` and `PingResponse` messages. These messages were used to create functionality which kept the connection alive. With gRPC there is a [keep alive feature](https://github.com/grpc/grpc/blob/master/doc/keepalive.md) that will be added along side the integration to provide the same functionality. + +#### Metrics + +Remote signers are crucial to operating secure and consistently up Validators. In the past there were no metrics to tell the operator if something is wrong other than the node not signing. Integrating metrics into the client and provided server will be done with [prometheus](https://github.com/grpc-ecosystem/go-grpc-prometheus). This will be integrated into node's prometheus export for node operators. + +#### Security + +[TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security) is widely adopted with the use of gRPC. There are various forms of TLS (one-way & two-way). One way is the client identifying who the server is, while two way is both parties identifying the other. For Tendermint's use case having both parties identifying each other provides adds an extra layer of security. This requires users to generate both client and server certificates for a TLS connection. + +An insecure option will be provided for users who do not wish to secure the connection. + +#### Upgrade Path + +This is a largely breaking change for validator operators. The optimal upgrade path would be to release gRPC in a minor release, allow key management systems to migrate to the new protocol. In the next major release the current system (raw tcp/unix) is removed. This allows users to migrate to the new system and not have to coordinate upgrading the key management system alongside a network upgrade. + +The upgrade of [tmkms](https://github.com/iqlusioninc/tmkms) will be coordinated with Iqlusion. They will be able to make the necessary upgrades to allow users to migrate to gRPC from the current protocol. + +## Status + +Accepted (tracked in +[\#9256](https://github.com/tendermint/tendermint/issues/9256)) + +### Positive + +- Use an adopted standard for secure communication. (TLS) +- Use an adopted communication protocol. (gRPC) +- Requests are multiplexed onto the tcp connection. (http/2) +- Language agnostic service definition. + +### Negative + +- Users will need to generate certificates to use TLS. (Added step) +- Users will need to find a supported gRPC supported key management system + +### Neutral diff --git a/docs/architecture/tendermint-core/adr-064-batch-verification.md b/docs/architecture/tendermint-core/adr-064-batch-verification.md new file mode 100644 index 0000000..94cf28f --- /dev/null +++ b/docs/architecture/tendermint-core/adr-064-batch-verification.md @@ -0,0 +1,90 @@ +# ADR 064: Batch Verification + +## Changelog + +- January 28, 2021: Created (@marbar3778) + +## Context + +Tendermint uses public private key cryptography for validator signing. When a block is proposed and voted on validators sign a message representing acceptance of a block, rejection is signaled via a nil vote. These signatures are also used to verify previous blocks are correct if a node is syncing. Currently, Tendermint requires each signature to be verified individually, this leads to a slow down of block times. + +Batch Verification is the process of taking many messages, keys, and signatures adding them together and verifying them all at once. The public key can be the same in which case it would mean a single user is signing many messages. In our case each public key is unique, each validator has their own and contribute a unique message. The algorithm can vary from curve to curve but the performance benefit, over single verifying messages, public keys and signatures is shared. + +## Alternative Approaches + +- Signature aggregation + - Signature aggregation is an alternative to batch verification. Signature aggregation leads to fast verification and smaller block sizes. At the time of writing this ADR there is on going work to enable signature aggregation in Tendermint. The reason why we have opted to not introduce it at this time is because every validator signs a unique message. + Signing a unique message prevents aggregation before verification. For example if we were to implement signature aggregation with BLS, there could be a potential slow down of 10x-100x in verification speeds. + +## Decision + +Adopt Batch Verification. + +## Detailed Design + +A new interface will be introduced. This interface will have three methods `NewBatchVerifier`, `Add` and `VerifyBatch`. + +```go +type BatchVerifier interface { + Add(key crypto.Pubkey, signature, message []byte) error // Add appends an entry into the BatchVerifier. + Verify() bool // Verify verifies all the entries in the BatchVerifier. If the verification fails it is unknown which entry failed and each entry will need to be verified individually. +} +``` + +- `NewBatchVerifier` creates a new verifier. This verifier will be populated with entries to be verified. +- `Add` adds an entry to the Verifier. Add accepts a public key and two slice of bytes (signature and message). +- `Verify` verifies all the entires. At the end of Verify if the underlying API does not reset the Verifier to its initial state (empty), it should be done here. This prevents accidentally reusing the verifier with entries from a previous verification. + +Above there is mention of an entry. An entry can be constructed in many ways depending on the needs of the underlying curve. A simple approach would be: + +```go +type entry struct { + pubKey crypto.Pubkey + signature []byte + message []byte +} +``` + +The main reason this approach is being taken is to prevent simple mistakes. Some APIs allow the user to create three slices and pass them to the `VerifyBatch` function but this relies on the user to safely generate all the slices (see example below). We would like to minimize the possibility of making a mistake. + +```go +func Verify(keys []crypto.Pubkey, signatures, messages[][]byte) bool +``` + +This change will not affect any users in anyway other than faster verification times. + +This new api will be used for verification in both consensus and block syncing. Within the current Verify functions there will be a check to see if the key types supports the BatchVerification API. If it does it will execute batch verification, if not single signature verification will be used. + +#### Consensus + + The process within consensus will be to wait for 2/3+ of the votes to be received, once they are received `Verify()` will be called to batch verify all the messages. The messages that come in after 2/3+ has been verified will be individually verified. + +#### Block Sync & Light Client + + The process for block sync & light client verification will be to verify only 2/3+ in a batch style. Since these processes are not participating in consensus there is no need to wait for more messages. + +If batch verifications fails for any reason, it will not be known which entry caused the failure. Verification will need to revert to single signature verification. + +Starting out, only ed25519 will support batch verification. + +## Status + +Implemented + +### Positive + +- Faster verification times, if the curve supports it + +### Negative + +- No way to see which key failed verification + - A failure means reverting back to single signature verification. + +### Neutral + +## References + +[Ed25519 Library](https://github.com/hdevalence/ed25519consensus) +[Ed25519 spec](https://ed25519.cr.yp.to/) +[Signature Aggregation for votes](https://github.com/tendermint/tendermint/issues/1319) +[Proposer-based timestamps](https://github.com/tendermint/tendermint/issues/2840) diff --git a/docs/architecture/tendermint-core/adr-065-custom-event-indexing.md b/docs/architecture/tendermint-core/adr-065-custom-event-indexing.md new file mode 100644 index 0000000..46942c7 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-065-custom-event-indexing.md @@ -0,0 +1,425 @@ +# ADR 065: Custom Event Indexing + +- [ADR 065: Custom Event Indexing](#adr-065-custom-event-indexing) + - [Changelog](#changelog) + - [Status](#status) + - [Context](#context) + - [Alternative Approaches](#alternative-approaches) + - [Decision](#decision) + - [Detailed Design](#detailed-design) + - [EventSink](#eventsink) + - [Supported Sinks](#supported-sinks) + - [`KVEventSink`](#kveventsink) + - [`PSQLEventSink`](#psqleventsink) + - [Configuration](#configuration) + - [Future Improvements](#future-improvements) + - [Consequences](#consequences) + - [Positive](#positive) + - [Negative](#negative) + - [Neutral](#neutral) + - [References](#references) + +## Changelog + +- April 1, 2021: Initial Draft (@alexanderbez) +- April 28, 2021: Specify search capabilities are only supported through the KV indexer (@marbar3778) +- May 19, 2021: Update the SQL schema and the eventsink interface (@jayt106) +- Aug 30, 2021: Update the SQL schema and the psql implementation (@creachadair) +- Oct 5, 2021: Clarify goals and implementation changes (@creachadair) + +## Status + +Implemented + +## Context + +Currently, Tendermint Core supports block and transaction event indexing through +the `tx_index.indexer` configuration. Events are captured in transactions and +are indexed via a `TxIndexer` type. Events are captured in blocks, specifically +from `BeginBlock` and `EndBlock` application responses, and are indexed via a +`BlockIndexer` type. Both of these types are managed by a single `IndexerService` +which is responsible for consuming events and sending those events off to be +indexed by the respective type. + +In addition to indexing, Tendermint Core also supports the ability to query for +both indexed transaction and block events via Tendermint's RPC layer. The ability +to query for these indexed events facilitates a great multitude of upstream client +and application capabilities, e.g. block explorers, IBC relayers, and auxiliary +data availability and indexing services. + +Currently, Tendermint only supports indexing via a `kv` indexer, which is supported +by an underlying embedded key/value store database. The `kv` indexer implements +its own indexing and query mechanisms. While the former is somewhat trivial, +providing a rich and flexible query layer is not as trivial and has caused many +issues and UX concerns for upstream clients and applications. + +The fragile nature of the proprietary `kv` query engine and the potential +performance and scaling issues that arise when a large number of consumers are +introduced, motivate the need for a more robust and flexible indexing and query +solution. + +## Alternative Approaches + +With regards to alternative approaches to a more robust solution, the only serious +contender that was considered was to transition to using [SQLite](https://www.sqlite.org/index.html). + +While the approach would work, it locks us into a specific query language and +storage layer, so in some ways it's only a bit better than our current approach. +In addition, the implementation would require the introduction of CGO into the +Tendermint Core stack, whereas right now CGO is only introduced depending on +the database used. + +## Decision + +We will adopt a similar approach to that of the Cosmos SDK's `KVStore` state +listening described in [ADR-038](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-038-state-listening.md). + +We will implement the following changes: + +- Introduce a new interface, `EventSink`, that all data sinks must implement. +- Augment the existing `tx_index.indexer` configuration to now accept a series + of one or more indexer types, i.e., sinks. +- Combine the current `TxIndexer` and `BlockIndexer` into a single `KVEventSink` + that implements the `EventSink` interface. +- Introduce an additional `EventSink` implementation that is backed by + [PostgreSQL](https://www.postgresql.org/). + - Implement the necessary schemas to support both block and transaction event indexing. +- Update `IndexerService` to use a series of `EventSinks`. + +In addition: + +- The Postgres indexer implementation will _not_ implement the proprietary `kv` + query language. Users wishing to write queries against the Postgres indexer + will connect to the underlying DBMS directly and use SQL queries based on the + indexing schema. + + Future custom indexer implementations will not be required to support the + proprietary query language either. + +- For now, the existing `kv` indexer will be left in place with its current + query support, but will be marked as deprecated in a subsequent release, and + the documentation will be updated to encourage users who need to query the + event index to migrate to the Postgres indexer. + +- In the future we may remove the `kv` indexer entirely, or replace it with a + different implementation; that decision is deferred as future work. + +- In the future, we may remove the index query endpoints from the RPC service + entirely; that decision is deferred as future work, but recommended. + + +## Detailed Design + +### EventSink + +We introduce the `EventSink` interface type that all supported sinks must implement. +The interface is defined as follows: + +```go +type EventSink interface { + IndexBlockEvents(types.EventDataNewBlockHeader) error + IndexTxEvents([]*abci.TxResult) error + + SearchBlockEvents(context.Context, *query.Query) ([]int64, error) + SearchTxEvents(context.Context, *query.Query) ([]*abci.TxResult, error) + + GetTxByHash([]byte) (*abci.TxResult, error) + HasBlock(int64) (bool, error) + + Type() EventSinkType + Stop() error +} +``` + +The `IndexerService` will accept a list of one or more `EventSink` types. During +the `OnStart` method it will call the appropriate APIs on each `EventSink` to +index both block and transaction events. + +### Supported Sinks + +We will initially support two `EventSink` types out of the box. + +#### `KVEventSink` + +This type of `EventSink` is a combination of the `TxIndexer` and `BlockIndexer` +indexers, both of which are backed by a single embedded key/value database. + +A bulk of the existing business logic will remain the same, but the existing APIs +mapped to the new `EventSink` API. Both types will be removed in favor of a single +`KVEventSink` type. + +The `KVEventSink` will be the only `EventSink` enabled by default, so from a UX +perspective, operators should not notice a difference apart from a configuration +change. + +We omit `EventSink` implementation details as it should be fairly straightforward +to map the existing business logic to the new APIs. + +#### `PSQLEventSink` + +This type of `EventSink` indexes block and transaction events into a [PostgreSQL](https://www.postgresql.org/). +database. We define and automatically migrate the following schema when the +`IndexerService` starts. + +The postgres eventsink will not support `tx_search`, `block_search`, `GetTxByHash` and `HasBlock`. + +```sql +-- Table Definition ---------------------------------------------- + +-- The blocks table records metadata about each block. +-- The block record does not include its events or transactions (see tx_results). +CREATE TABLE blocks ( + rowid BIGSERIAL PRIMARY KEY, + + height BIGINT NOT NULL, + chain_id VARCHAR NOT NULL, + + -- When this block header was logged into the sink, in UTC. + created_at TIMESTAMPTZ NOT NULL, + + UNIQUE (height, chain_id) +); + +-- Index blocks by height and chain, since we need to resolve block IDs when +-- indexing transaction records and transaction events. +CREATE INDEX idx_blocks_height_chain ON blocks(height, chain_id); + +-- The tx_results table records metadata about transaction results. Note that +-- the events from a transaction are stored separately. +CREATE TABLE tx_results ( + rowid BIGSERIAL PRIMARY KEY, + + -- The block to which this transaction belongs. + block_id BIGINT NOT NULL REFERENCES blocks(rowid), + -- The sequential index of the transaction within the block. + index INTEGER NOT NULL, + -- When this result record was logged into the sink, in UTC. + created_at TIMESTAMPTZ NOT NULL, + -- The hex-encoded hash of the transaction. + tx_hash VARCHAR NOT NULL, + -- The protobuf wire encoding of the TxResult message. + tx_result BYTEA NOT NULL, + + UNIQUE (block_id, index) +); + +-- The events table records events. All events (both block and transaction) are +-- associated with a block ID; transaction events also have a transaction ID. +CREATE TABLE events ( + rowid BIGSERIAL PRIMARY KEY, + + -- The block and transaction this event belongs to. + -- If tx_id is NULL, this is a block event. + block_id BIGINT NOT NULL REFERENCES blocks(rowid), + tx_id BIGINT NULL REFERENCES tx_results(rowid), + + -- The application-defined type label for the event. + type VARCHAR NOT NULL +); + +-- The attributes table records event attributes. +CREATE TABLE attributes ( + event_id BIGINT NOT NULL REFERENCES events(rowid), + key VARCHAR NOT NULL, -- bare key + composite_key VARCHAR NOT NULL, -- composed type.key + value VARCHAR NULL, + + UNIQUE (event_id, key) +); + +-- A joined view of events and their attributes. Events that do not have any +-- attributes are represented as a single row with empty key and value fields. +CREATE VIEW event_attributes AS + SELECT block_id, tx_id, type, key, composite_key, value + FROM events LEFT JOIN attributes ON (events.rowid = attributes.event_id); + +-- A joined view of all block events (those having tx_id NULL). +CREATE VIEW block_events AS + SELECT blocks.rowid as block_id, height, chain_id, type, key, composite_key, value + FROM blocks JOIN event_attributes ON (blocks.rowid = event_attributes.block_id) + WHERE event_attributes.tx_id IS NULL; + +-- A joined view of all transaction events. +CREATE VIEW tx_events AS + SELECT height, index, chain_id, type, key, composite_key, value, tx_results.created_at + FROM blocks JOIN tx_results ON (blocks.rowid = tx_results.block_id) + JOIN event_attributes ON (tx_results.rowid = event_attributes.tx_id) + WHERE event_attributes.tx_id IS NOT NULL; +``` + +The `PSQLEventSink` will implement the `EventSink` interface as follows +(some details omitted for brevity): + +```go +func NewEventSink(connStr, chainID string) (*EventSink, error) { + db, err := sql.Open(driverName, connStr) + // ... + + return &EventSink{ + store: db, + chainID: chainID, + }, nil +} + +func (es *EventSink) IndexBlockEvents(h types.EventDataNewBlockHeader) error { + ts := time.Now().UTC() + + return runInTransaction(es.store, func(tx *sql.Tx) error { + // Add the block to the blocks table and report back its row ID for use + // in indexing the events for the block. + blockID, err := queryWithID(tx, ` +INSERT INTO blocks (height, chain_id, created_at) + VALUES ($1, $2, $3) + ON CONFLICT DO NOTHING + RETURNING rowid; +`, h.Header.Height, es.chainID, ts) + // ... + + // Insert the special block meta-event for height. + if err := insertEvents(tx, blockID, 0, []abci.Event{ + makeIndexedEvent(types.BlockHeightKey, fmt.Sprint(h.Header.Height)), + }); err != nil { + return fmt.Errorf("block meta-events: %w", err) + } + // Insert all the block events. Order is important here, + if err := insertEvents(tx, blockID, 0, h.ResultBeginBlock.Events); err != nil { + return fmt.Errorf("begin-block events: %w", err) + } + if err := insertEvents(tx, blockID, 0, h.ResultEndBlock.Events); err != nil { + return fmt.Errorf("end-block events: %w", err) + } + return nil + }) +} + +func (es *EventSink) IndexTxEvents(txrs []*abci.TxResult) error { + ts := time.Now().UTC() + + for _, txr := range txrs { + // Encode the result message in protobuf wire format for indexing. + resultData, err := proto.Marshal(txr) + // ... + + // Index the hash of the underlying transaction as a hex string. + txHash := fmt.Sprintf("%X", types.Tx(txr.Tx).Hash()) + + if err := runInTransaction(es.store, func(tx *sql.Tx) error { + // Find the block associated with this transaction. + blockID, err := queryWithID(tx, ` +SELECT rowid FROM blocks WHERE height = $1 AND chain_id = $2; +`, txr.Height, es.chainID) + // ... + + // Insert a record for this tx_result and capture its ID for indexing events. + txID, err := queryWithID(tx, ` +INSERT INTO tx_results (block_id, index, created_at, tx_hash, tx_result) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT DO NOTHING + RETURNING rowid; +`, blockID, txr.Index, ts, txHash, resultData) + // ... + + // Insert the special transaction meta-events for hash and height. + if err := insertEvents(tx, blockID, txID, []abci.Event{ + makeIndexedEvent(types.TxHashKey, txHash), + makeIndexedEvent(types.TxHeightKey, fmt.Sprint(txr.Height)), + }); err != nil { + return fmt.Errorf("indexing transaction meta-events: %w", err) + } + // Index any events packaged with the transaction. + if err := insertEvents(tx, blockID, txID, txr.Result.Events); err != nil { + return fmt.Errorf("indexing transaction events: %w", err) + } + return nil + + }); err != nil { + return err + } + } + return nil +} + +// SearchBlockEvents is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) SearchBlockEvents(ctx context.Context, q *query.Query) ([]int64, error) + +// SearchTxEvents is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) SearchTxEvents(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) + +// GetTxByHash is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) GetTxByHash(hash []byte) (*abci.TxResult, error) + +// HasBlock is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) HasBlock(h int64) (bool, error) +``` + +### Configuration + +The current `tx_index.indexer` configuration would be changed to accept a list +of supported `EventSink` types instead of a single value. + +Example: + +```toml +[tx_index] + +indexer = [ + "kv", + "psql" +] +``` + +If the `indexer` list contains the `null` indexer, then no indexers will be used +regardless of what other values may exist. + +Additional configuration parameters might be required depending on what event +sinks are supplied to `tx_index.indexer`. The `psql` will require an additional +connection configuration. + +```toml +[tx_index] + +indexer = [ + "kv", + "psql" +] + +pqsql_conn = "postgresql://:@:/?" +``` + +Any invalid or misconfigured `tx_index` configuration should yield an error as +early as possible. + +## Future Improvements + +Although not technically required to maintain feature parity with the current +existing Tendermint indexer, it would be beneficial for operators to have a method +of performing a "re-index". Specifically, Tendermint operators could invoke an +RPC method that allows the Tendermint node to perform a re-indexing of all block +and transaction events between two given heights, H1 and H2, +so long as the block store contains the blocks and transaction results for all +the heights specified in a given range. + +## Consequences + +### Positive + +- A more robust and flexible indexing and query engine for indexing and search + block and transaction events. +- The ability to not have to support a custom indexing and query engine beyond + the legacy `kv` type. +- The ability to offload/proxy indexing and querying to the underling sink. +- Scalability and reliability that essentially comes "for free" from the underlying + sink, if it supports it. + +### Negative + +- The need to support multiple and potentially a growing set of custom `EventSink` + types. + +### Neutral + +## References + +- [Cosmos SDK ADR-038](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-038-state-listening.md) +- [PostgreSQL](https://www.postgresql.org/) +- [SQLite](https://www.sqlite.org/index.html) diff --git a/docs/architecture/tendermint-core/adr-066-e2e-testing.md b/docs/architecture/tendermint-core/adr-066-e2e-testing.md new file mode 100644 index 0000000..988c4d3 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-066-e2e-testing.md @@ -0,0 +1,140 @@ +# ADR 66: End-to-End Testing + +## Changelog + +- 2020-09-07: Initial draft (@erikgrinaker) +- 2020-09-08: Minor improvements (@erikgrinaker) +- 2021-04-12: Renamed from RFC 001 (@tessr) + +## Authors + +- Erik Grinaker (@erikgrinaker) + +## Context + +The current set of end-to-end tests under `test/` are very limited, mostly focusing on P2P testing in a standard configuration. They do not test various configurations (e.g. fast sync reactor versions, state sync, block pruning, genesis vs InitChain setup), nor do they test various network topologies (e.g. sentry node architecture). This leads to poor test coverage, which has caused several serious bugs to go unnoticed. + +We need an end-to-end test suite that can run a large number of combinations of configuration options, genesis settings, network topologies, ABCI interactions, and failure scenarios and check that the network is still functional. This ADR outlines the basic requirements and design for such a system. + +This ADR will not cover comprehensive chaos testing, only a few simple scenarios (e.g. abrupt process termination and network partitioning). Chaos testing of the core consensus algorithm should be implemented e.g. via Jepsen tests or a similar framework, or alternatively be added to these end-to-end tests at a later time. Similarly, malicious or adversarial behavior is out of scope for the first implementation, but may be added later. + +## Proposal + +### Functional Coverage + +The following lists the functionality we would like to test: + +#### Environments + +- **Topology:** single node, 4 nodes (seeds and persistent), sentry architecture, NAT (UPnP) +- **Networking:** IPv4, IPv6 +- **ABCI connection:** UNIX socket, TCP, gRPC +- **PrivVal:** file, UNIX socket, TCP + +#### Node/App Configurations + +- **Database:** goleveldb, cleveldb, boltdb, rocksdb, badgerdb +- **Fast sync:** disabled, v0, v2 +- **State sync:** disabled, enabled +- **Block pruning:** none, keep 20, keep 1, keep random +- **Role:** validator, full node +- **App persistence:** enabled, disabled +- **Node modes:** validator, full, light, seed + +#### Geneses + +- **Validators:** none (InitChain), given +- **Initial height:** 1, 1000 +- **App state:** none, given + +#### Behaviors + +- **Recovery:** stop/start, power cycling, validator outage, network partition, total network loss +- **Validators:** add, remove, change power +- **Evidence:** injection of DuplicateVoteEvidence and LightClientAttackEvidence + +### Functional Combinations + +Running separate tests for all combinations of the above functionality is not feasible, as there are millions of them. However, the functionality can be grouped into three broad classes: + +- **Global:** affects the entire network, needing a separate testnet for each combination (e.g. topology, network protocol, genesis settings) + +- **Local:** affects a single node, and can be varied per node in a testnet (e.g. ABCI/privval connections, database backend, block pruning) + +- **Temporal:** can be run after each other in the same testnet (e.g. recovery and validator changes) + +Thus, we can run separate testnets for all combinations of global options (on the order of 100). In each testnet, we run nodes with randomly generated node configurations optimized for broad coverage (i.e. if one node is using GoLevelDB, then no other node should use it if possible). And in each testnet, we sequentially and randomly pick nodes to stop/start, power cycle, add/remove, disconnect, and so on. + +All of the settings should be specified in a testnet configuration (or alternatively the seed that generated it) such that it can be retrieved from CI and debugged locally. + +A custom ABCI application will have to be built that can exhibit the necessary behavior (e.g. make validator changes, prune blocks, enable/disable persistence, and so on). + +### Test Stages + +Given a test configuration, the test runner has the following stages: + +- **Setup:** configures the Docker containers and networks, but does not start them. + +- **Initialization:** starts the Docker containers, performs fast sync/state sync. Accomodates for different start heights. + +- **Perturbation:** adds/removes validators, restarts nodes, perturbs networking, etc - liveness and readiness checked between each operation. + +- **Testing:** runs RPC tests independently against all network nodes, making sure data matches expectations and invariants hold. + +### Tests + +The general approach will be to put the network through a sequence of operations (see stages above), check basic liveness and readiness after each operation, and then once the network stabilizes run an RPC test suite against each node in the network. + +The test suite will do black-box testing against a single node's RPC service. We will be testing the behavior of the network as a whole, e.g. that a fast synced node correctly catches up to the chain head and serves basic block data via RPC. Thus the tests will not send e.g. P2P messages or examine the node database, as these are considered internal implementation details - if the network behaves correctly, presumably the internal components function correctly. Comprehensive component testing (e.g. each and every RPC method parameter) should be done via unit/integration tests. + +The tests must take into account the node configuration (e.g. some nodes may be pruned, others may not be validators), and should somehow be provided access to expected data (i.e. complete block headers for the entire chain). + +The test suite should use the Tendermint RPC client and the Tendermint light client, to exercise the client code as well. + +### Implementation Considerations + +The testnets should run in Docker Compose, both locally and in CI. This makes it easier to reproduce test failures locally. Supporting multiple test-runners (e.g. on VMs or Kubernetes) is out of scope. The same image should be used for all tests, with configuration passed via a mounted volume. + +There does not appear to be any off-the-shelf solutions that would do this for us, so we will have to roll our own on top of Docker Compose. This gives us more flexibility, but is estimated to be a few weeks of work. + +Testnets should be configured via a YAML file. These are used as inputs for the test runner, which e.g. generates Docker Compose configurations from them. An additional layer on top should generate these testnet configurations from a YAML file that specifies all the option combinations to test. + +Comprehensive testnets should run against master nightly. However, a small subset of representative testnets should run for each pull request, e.g. a four-node IPv4 network with state sync and fast sync. + +Tests should be written using the standard Go test framework (and e.g. Testify), with a helper function to fetch info from the test configuration. The test runner will run the tests separately for each network node, and the test must vary its expectations based on the node's configuration. + +It should be possible to launch a specific testnet and run individual test cases from the IDE or local terminal against a it. + +If possible, the existing `testnet` command should be extended to set up the network topologies needed by the end-to-end tests. + +## Status + +Implemented + +## Consequences + +### Positive + +- Comprehensive end-to-end test coverage of basic Tendermint functionality, exercising common code paths in the same way that users would + +- Test environments can easily be reproduced locally and debugged via standard tooling + +### Negative + +- Limited coverage of consensus correctness testing (e.g. Jepsen) + +- No coverage of malicious or adversarial behavior + +- Have to roll our own test framework, which takes engineering resources + +- Possibly slower CI times, depending on which tests are run + +- Operational costs and overhead, e.g. infrastructure costs and system maintenance + +### Neutral + +- No support for alternative infrastructure platforms, e.g. Kubernetes or VMs + +## References + +- [#5291: new end-to-end test suite](https://github.com/tendermint/tendermint/issues/5291) diff --git a/docs/architecture/tendermint-core/adr-067-mempool-refactor.md b/docs/architecture/tendermint-core/adr-067-mempool-refactor.md new file mode 100644 index 0000000..e50ff71 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-067-mempool-refactor.md @@ -0,0 +1,303 @@ +# ADR 067: Mempool Refactor + +- [ADR 067: Mempool Refactor](#adr-067-mempool-refactor) + - [Changelog](#changelog) + - [Status](#status) + - [Context](#context) + - [Current Design](#current-design) + - [Alternative Approaches](#alternative-approaches) + - [Prior Art](#prior-art) + - [Ethereum](#ethereum) + - [Diem](#diem) + - [Decision](#decision) + - [Detailed Design](#detailed-design) + - [CheckTx](#checktx) + - [Mempool](#mempool) + - [Eviction](#eviction) + - [Gossiping](#gossiping) + - [Performance](#performance) + - [Future Improvements](#future-improvements) + - [Consequences](#consequences) + - [Positive](#positive) + - [Negative](#negative) + - [Neutral](#neutral) + - [References](#references) + +## Changelog + +- April 19, 2021: Initial Draft (@alexanderbez) + +## Status + +Accepted + +## Context + +Tendermint Core has a reactor and data structure, mempool, that facilitates the +ephemeral storage of uncommitted transactions. Honest nodes participating in a +Tendermint network gossip these uncommitted transactions to each other if they +pass the application's `CheckTx`. In addition, block proposers select from the +mempool a subset of uncommitted transactions to include in the next block. + +Currently, the mempool in Tendermint Core is designed as a FIFO queue. In other +words, transactions are included in blocks as they are received by a node. There +currently is no explicit and prioritized ordering of these uncommitted transactions. +This presents a few technical and UX challenges for operators and applications. + +Namely, validators are not able to prioritize transactions by their fees or any +incentive aligned mechanism. In addition, the lack of prioritization also leads +to cascading effects in terms of DoS and various attack vectors on networks, +e.g. [cosmos/cosmos-sdk#8224](https://github.com/cosmos/cosmos-sdk/discussions/8224). + +Thus, Tendermint Core needs the ability for an application and its users to +prioritize transactions in a flexible and performant manner. Specifically, we're +aiming to either improve, maintain or add the following properties in the +Tendermint mempool: + +- Allow application-determined transaction priority. +- Allow efficient concurrent reads and writes. +- Allow block proposers to reap transactions efficiently by priority. +- Maintain a fixed mempool capacity by transaction size and evict lower priority + transactions to make room for higher priority transactions. +- Allow transactions to be gossiped by priority efficiently. +- Allow operators to specify a maximum TTL for transactions in the mempool before + they're automatically evicted if not selected for a block proposal in time. +- Ensure the design allows for future extensions, such as replace-by-priority and + allowing multiple pending transactions per sender, to be incorporated easily. + +Note, not all of these properties will be addressed by the proposed changes in +this ADR. However, this proposal will ensure that any unaddressed properties +can be addressed in an easy and extensible manner in the future. + +### Current Design + +![mempool](./img/mempool-v0.jpeg) + +At the core of the `v0` mempool reactor is a concurrent linked-list. This is the +primary data structure that contains `Tx` objects that have passed `CheckTx`. +When a node receives a transaction from another peer, it executes `CheckTx`, which +obtains a read-lock on the `*CListMempool`. If the transaction passes `CheckTx` +locally on the node, it is added to the `*CList` by obtaining a write-lock. It +is also added to the `cache` and `txsMap`, both of which obtain their own respective +write-locks and map a reference from the transaction hash to the `Tx` itself. + +Transactions are continuously gossiped to peers whenever a new transaction is added +to a local node's `*CList`, where the node at the front of the `*CList` is selected. +Another transaction will not be gossiped until the `*CList` notifies the reader +that there are more transactions to gossip. + +When a proposer attempts to propose a block, they will execute `ReapMaxBytesMaxGas` +on the reactor's `*CListMempool`. This call obtains a read-lock on the `*CListMempool` +and selects as many transactions as possible starting from the front of the `*CList` +moving to the back of the list. + +When a block is finally committed, a caller invokes `Update` on the reactor's +`*CListMempool` with all the selected transactions. Note, the caller must also +explicitly obtain a write-lock on the reactor's `*CListMempool`. This call +will remove all the supplied transactions from the `txsMap` and the `*CList`, both +of which obtain their own respective write-locks. In addition, the transaction +may also be removed from the `cache` which obtains it's own write-lock. + +## Alternative Approaches + +When considering which approach to take for a priority-based flexible and +performant mempool, there are two core candidates. The first candidate is less +invasive in the required set of protocol and implementation changes, which +simply extends the existing `CheckTx` ABCI method. The second candidate essentially +involves the introduction of new ABCI method(s) and would require a higher degree +of complexity in protocol and implementation changes, some of which may either +overlap or conflict with the upcoming introduction of [ABCI++](https://github.com/tendermint/tendermint/blob/main/docs/rfc/rfc-013-abci%2B%2B.md). + +For more information on the various approaches and proposals, please see the +[mempool discussion](https://github.com/tendermint/tendermint/discussions/6295). + +## Prior Art + +### Ethereum + +The Ethereum mempool, specifically [Geth](https://github.com/ethereum/go-ethereum), +contains a mempool, `*TxPool`, that contains various mappings indexed by account, +such as a `pending` which contains all processable transactions for accounts +prioritized by nonce. It also contains a `queue` which is the exact same mapping +except it contains not currently processable transactions. The mempool also +contains a `priced` index of type `*txPricedList` that is a priority queue based +on transaction price. + +### Diem + +The [Diem mempool](https://github.com/diem/diem/blob/master/mempool/README.md#implementation-details) +contains a similar approach to the one we propose. Specifically, the Diem mempool +contains a mapping from `Account:[]Tx`. On top of this primary mapping from account +to a list of transactions, are various indexes used to perform certain actions. + +The main index, `PriorityIndex`. is an ordered queue of transactions that are +“consensus-ready” (i.e., they have a sequence number which is sequential to the +current sequence number for the account). This queue is ordered by gas price so +that if a client is willing to pay more (than other clients) per unit of +execution, then they can enter consensus earlier. + +## Decision + +To incorporate a priority-based flexible and performant mempool in Tendermint Core, +we will introduce new fields, `priority` and `sender`, into the `ResponseCheckTx` +type. + +We will introduce a new versioned mempool reactor, `v1` and assume an implicit +version of the current mempool reactor as `v0`. In the new `v1` mempool reactor, +we largely keep the functionality the same as `v0` except we augment the underlying +data structures. Specifically, we keep a mapping of senders to transaction objects. +On top of this mapping, we index transactions to provide the ability to efficiently +gossip and reap transactions by priority. + +## Detailed Design + +### CheckTx + +We introduce the following new fields into the `ResponseCheckTx` type: + +```diff +message ResponseCheckTx { + uint32 code = 1; + bytes data = 2; + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 gas_wanted = 5 [json_name = "gas_wanted"]; + int64 gas_used = 6 [json_name = "gas_used"]; + repeated Event events = 7 [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; + string codespace = 8; ++ int64 priority = 9; ++ string sender = 10; +} +``` + +It is entirely up the application in determining how these fields are populated +and with what values, e.g. the `sender` could be the signer and fee payer +of the transaction, the `priority` could be the cumulative sum of the fee(s). + +Only `sender` is required, while `priority` can be omitted which would result in +using the default value of zero. + +### Mempool + +The existing concurrent-safe linked-list will be replaced by a thread-safe map +of ``, i.e a mapping from `sender` to a single `*Tx` object, where +each `*Tx` is the next valid and processable transaction from the given `sender`. + +On top of this mapping, we index all transactions by priority using a thread-safe +priority queue, i.e. a [max heap](https://en.wikipedia.org/wiki/Min-max_heap). +When a proposer is ready to select transactions for the next block proposal, +transactions are selected from this priority index by highest priority order. +When a transaction is selected and reaped, it is removed from this index and +from the `` mapping. + +We define `Tx` as the following data structure: + +```go +type Tx struct { + // Tx represents the raw binary transaction data. + Tx []byte + + // Priority defines the transaction's priority as specified by the application + // in the ResponseCheckTx response. + Priority int64 + + // Sender defines the transaction's sender as specified by the application in + // the ResponseCheckTx response. + Sender string + + // Index defines the current index in the priority queue index. Note, if + // multiple Tx indexes are needed, this field will be removed and each Tx + // index will have its own wrapped Tx type. + Index int +} +``` + +### Eviction + +Upon successfully executing `CheckTx` for a new `Tx` and the mempool is currently +full, we must check if there exists a `Tx` of lower priority that can be evicted +to make room for the new `Tx` with higher priority and with sufficient size +capacity left. + +If such a `Tx` exists, we find it by obtaining a read lock and sorting the +priority queue index. Once sorted, we find the first `Tx` with lower priority and +size such that the new `Tx` would fit within the mempool's size limit. We then +remove this `Tx` from the priority queue index as well as the `` +mapping. + +This will require additional `O(n)` space and `O(n*log(n))` runtime complexity. Note that the space complexity does not depend on the size of the tx. + +### Gossiping + +We keep the existing thread-safe linked list as an additional index. Using this +index, we can efficiently gossip transactions in the same manner as they are +gossiped now (FIFO). + +Gossiping transactions will not require locking any other indexes. + +### Performance + +Performance should largely remain unaffected apart from the space overhead of +keeping an additional priority queue index and the case where we need to evict +transactions from the priority queue index. There should be no reads which +block writes on any index + +## Future Improvements + +There are a few considerable ways in which the proposed design can be improved or +expanded upon. Namely, transaction gossiping and for the ability to support +multiple transactions from the same `sender`. + +With regards to transaction gossiping, we need empirically validate whether we +need to gossip by priority. In addition, the current method of gossiping may not +be the most efficient. Specifically, broadcasting all the transactions a node +has in it's mempool to it's peers. Rather, we should explore for the ability to +gossip transactions on a request/response basis similar to Ethereum and other +protocols. Not only does this reduce bandwidth and complexity, but also allows +for us to explore gossiping by priority or other dimensions more efficiently. + +Allowing for multiple transactions from the same `sender` is important and will +most likely be a needed feature in the future development of the mempool, but for +now it suffices to have the preliminary design agreed upon. Having the ability +to support multiple transactions per `sender` will require careful thought with +regards to the interplay of the corresponding ABCI application. Regardless, the +proposed design should allow for adaptations to support this feature in a +non-contentious and backwards compatible manner. + +## Consequences + +### Positive + +- Transactions are allowed to be prioritized by the application. + +### Negative + +- Increased size of the `ResponseCheckTx` Protocol Buffer type. +- Causal ordering is NOT maintained. + - It is possible that certain transactions broadcasted in a particular order may + pass `CheckTx` but not end up being committed in a block because they fail + `CheckTx` later. e.g. Consider Tx1 that sends funds from existing + account Alice to a _new_ account Bob with priority P1 and then later + Bob's _new_ account sends funds back to Alice in Tx2 with P2, + such that P2 > P1. If executed in this order, both + transactions will pass `CheckTx`. However, when a proposer is ready to select + transactions for the next block proposal, they will select Tx2 before + Tx1 and thus Tx2 will _fail_ because Tx1 must + be executed first. This is because there is a _causal ordering_, + Tx1 ➝ Tx2. These types of situations should be rare as + most transactions are not causally ordered and can be circumvented by simply + trying again at a later point in time or by ensuring the "child" priority is + lower than the "parent" priority. In other words, if parents always have + priories that are higher than their children, then the new mempool design will + maintain causal ordering. + +### Neutral + +- A transaction that passed `CheckTx` and entered the mempool can later be evicted + at a future point in time if a higher priority transaction entered while the + mempool was full. + +## References + +- [ABCI++](https://github.com/tendermint/tendermint/blob/main/docs/rfc/rfc-013-abci%2B%2B.md) +- [Mempool Discussion](https://github.com/tendermint/tendermint/discussions/6295) diff --git a/docs/architecture/tendermint-core/adr-068-reverse-sync.md b/docs/architecture/tendermint-core/adr-068-reverse-sync.md new file mode 100644 index 0000000..fa0c953 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-068-reverse-sync.md @@ -0,0 +1,97 @@ +# ADR 068: Reverse Sync + +## Changelog + +- 20 April 2021: Initial Draft (@cmwaters) + +## Status + +Proposed + +## Context + +The advent of state sync and block pruning gave rise to the opportunity for full nodes to participate in consensus without needing complete block history. This also introduced a problem with respect to evidence handling. Nodes that didn't have all the blocks within the evidence age were incapable of validating evidence, thus halting if that evidence was committed on chain. + +[ADR 068](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-068-reverse-sync.md) was published in response to this problem and modified the spec to add a minimum block history invariant. This predominantly sought to extend state sync so that it was capable of fetching and storing the `Header`, `Commit` and `ValidatorSet` (essentially a `LightBlock`) of the last `n` heights, where `n` was calculated based from the evidence age. + +This ADR sets out to describe the design of this state sync extension as well as modifications to the light client provider and the merging of tm store. + +## Decision + +The state sync reactor will be extended by introducing 2 new P2P messages (and a new channel). + +```protobuf +message LightBlockRequest { + uint64 height = 1; +} + +message LightBlockResponse { + tendermint.types.LightBlock light_block = 1; +} +``` + +This will be used by the "reverse sync" protocol that will fetch, verify and store prior light blocks such that the node can safely participate in consensus. + +Furthermore this allows for a new light client provider which offers the ability for the `StateProvider` to use the underlying P2P stack instead of RPC. + +## Detailed Design + +This section will focus first on the reverse sync (here we call it `backfill`) mechanism as a standalone protocol and then look to decribe how it integrates within the state sync reactor and how we define the new p2p light client provider. + +```go +// Backfill fetches, verifies, and stores necessary history +// to participate in consensus and validate evidence. +func (r *Reactor) backfill(state State) error {} +``` + +`State` is used to work out how far to go back, namely we need all light blocks that have: +- a height: `h >= state.LastBlockHeight - state.ConsensusParams.Evidence.MaxAgeNumBlocks` +- a time: `t >= state.LastBlockTime - state.ConsensusParams.Evidence.MaxAgeDuration` + +Reverse Sync relies on two components: A `Dispatcher` and a `BlockQueue`. The `Dispatcher` is a pattern taken from a similar [PR](https://github.com/tendermint/tendermint/pull/4508). It is wired to the `LightBlockChannel` and allows for concurrent light block requests by shifting through a linked list of peers. This abstraction has the nice quality that it can also be used as an array of light providers for a P2P based light client. + +The `BlockQueue` is a data structure that allows for multiple workers to fetch light blocks, serializing them for the main thread which picks them off the end of the queue, verifies the hashes and persists them. + +### Integration with State Sync + +Reverse sync is a blocking process that runs directly after syncing state and before transitioning into either fast sync or consensus. + +Prior, the state sync service was not connected to any db, instead it passed the state and commit back to the node. For reverse sync, state sync will be given access to both the `StateStore` and `BlockStore` to be able to write `Header`'s, `Commit`'s and `ValidatorSet`'s and read them so as to serve other state syncing peers. + +This also means adding new methods to these respective stores in order to persist them + +### P2P Light Client Provider + +As mentioned previously, the `Dispatcher` is capable of handling requests to multiple peers. We can therefore simply peel off a `blockProvider` instance which is assigned to each peer. By giving it the chain ID, the `blockProvider` is capable of doing a basic validation of the light block before returning it to the client. + +It's important to note that because state sync doesn't have access to the evidence channel it is incapable of allowing the light client to report evidence thus `ReportEvidence` is a no op. This is not too much of a concern for reverse sync but will need to be addressed for pure p2p light clients. + +### Pruning + +A final small note is with pruning. This ADR will introduce changes that will not allow an application to prune blocks that are within the evidence age. + +## Future Work + +This ADR tries to remain within the scope of extending state sync, however the changes made opens the door for several areas to be followed up: +- Properly integrate p2p messaging in the light client package. This will require adding the evidence channel so the light client is capable of reporting evidence. We may also need to rethink the providers model (i.e. currently providers are only added on start up) +- Merge and clean up the tendermint stores (state, block and evidence). This ADR adds new methods to both the state and block store for saving headers, commits and validator sets. This doesn't quite fit with the current struct (i.e. only `BlockMeta`s instead of `Header`s are saved). We should explore consolidating this for the sake of atomicity and the opportunity for batching. There are also other areas for changes such as the way we store block parts. See [here](https://github.com/tendermint/tendermint/issues/5383) and [here](https://github.com/tendermint/tendermint/issues/4630) for more context. +- Explore opportunistic reverse sync. Technically we don't need to reverse sync if no evidence is observed. I've tried to design the protocol such that it could be possible to move it across to the evidence package if we see fit. Thus only when evidence is seen where we don't have the necessary data, do we perform a reverse sync. The problem with this is that imagine we are in consensus and some evidence pops up requiring us to first fetch and verify the last 10,000 blocks. There's no way a node could do this (sequentially) and vote before the round finishes. Also as we don't punish invalid evidence, a malicious node could easily spam the chain just to get a bunch of "stateless" nodes to perform a bunch of useless work. +- Explore full reverse sync. Currently we only fetch light blocks. There might be benefits in the future to fetch and persist entire blocks especially if we give control to the application to do this. + +## Consequences + +### Positive + +- All nodes should have sufficient history to validate all types of evidence +- State syncing nodes can use the p2p layer for light client verification of state. This has better UX and could be faster but I haven't benchmarked. + +### Negative + +- Introduces more code = more maintenance + +### Neutral + +## References + +- [Reverse Sync RFC](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-068-reverse-sync.md) +- [Original Issue](https://github.com/tendermint/tendermint/issues/5617) diff --git a/docs/architecture/tendermint-core/adr-069-flexible-node-initialization.md b/docs/architecture/tendermint-core/adr-069-flexible-node-initialization.md new file mode 100644 index 0000000..4c36356 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-069-flexible-node-initialization.md @@ -0,0 +1,268 @@ +# ADR 069: Flexible Node Initialization + +## Changlog + +- 2021-06-09: Initial Draft (@tychoish) + +- 2021-07-21: Major Revision (@tychoish) + +## Status + +Proposed. + +## Context + +In an effort to support [Go-API-Stability](./adr-060-go-api-stability.md), +during the 0.35 development cycle, we have attempted to reduce the the API +surface area by moving most of the interface of the `node` package into +unexported functions, as well as moving the reactors to an `internal` +package. Having this coincide with the 0.35 release made a lot of sense +because these interfaces were _already_ changing as a result of the `p2p` +[refactor](./adr-061-p2p-refactor-scope.md), so it made sense to think a bit +more about how tendermint exposes this API. + +While the interfaces of the P2P layer and most of the node package are already +internalized, this precludes some operational patterns that are important to +users who use tendermint as a library. Specifically, introspecting the +tendermint node service and replacing components is not supported in the latest +version of the code, and some of these use cases would require maintaining a +vendor copy of the code. Adding these features requires rather extensive +(internal/implementation) changes to the `node` and `rpc` packages, and this +ADR describes a model for changing the way that tendermint nodes initialize, in +service of providing this kind of functionality. + +We consider node initialization, because the current implemention +provides strong connections between all components, as well as between +the components of the node and the RPC layer, and being able to think +about the interactions of these components will help enable these +features and help define the requirements of the node package. + +## Alternative Approaches + +These alternatives are presented to frame the design space and to +contextualize the decision in terms of product requirements. These +ideas are not inherently bad, and may even be possible or desireable +in the (distant) future, and merely provide additional context for how +we, in the moment came to our decision(s). + +### Do Nothing + +The current implementation is functional and sufficient for the vast +majority of use cases (e.g., all users of the Cosmos-SDK as well as +anyone who runs tendermint and the ABCI application in separate +processes). In the current implementation, and even previous versions, +modifying node initialization or injecting custom components required +copying most of the `node` package, which required such users +to maintain a vendored copy of tendermint. + +While this is (likely) not tenable in the long term, as users do want +more modularity, and the current service implementation is brittle and +difficult to maintain, in the short term it may be possible to delay +implementation somewhat. Eventually, however, we will need to make the +`node` package easier to maintain and reason about. + +### Generic Service Pluggability + +One possible system design would export interfaces (in the Golang +sense) for all components of the system, to permit runtime dependency +injection of all components in the system, so that users can compose +tendermint nodes of arbitrary user-supplied components. + +Although this level of customization would provide benefits, it would be a huge +undertaking (particularly with regards to API design work) that we do not have +scope for at the moment. Eventually providing support for some kinds of +pluggability may be useful, so the current solution does not explicitly +foreclose the possibility of this alternative. + +### Abstract Dependency Based Startup and Shutdown + +The main proposal in this document makes tendermint node initialization simpler +and more abstract, but the system lacks a number of +features which daemon/service initialization could provide, such as a +system allowing the authors of services to control initialization and shutdown order +of components using dependency relationships. + +Such a system could work by allowing services to declare +initialization order dependencies to other reactors (by ID, perhaps) +so that the node could decide the initialization based on the +dependencies declared by services rather than requiring the node to +encode this logic directly. + +This level of configuration is probably more complicated than is needed. Given +that the authors of components in the current implementation of tendermint +already *do* need to know about other components, a dependency-based system +would probably be overly-abstract at this stage. + +## Decisions + +- To the greatest extent possible, factor the code base so that + packages are responsible for their own initialization, and minimize + the amount of code in the `node` package itself. + +- As a design goal, reduce direct coupling and dependencies between + components in the implementation of `node`. + +- Begin iterating on a more-flexible internal framework for + initializing tendermint nodes to make the initatilization process + less hard-coded by the implementation of the node objects. + + - Reactors should not need to expose their interfaces *within* the + implementation of the node type + + - This refactoring should be entirely opaque to users. + + - These node initialization changes should not require a + reevaluation of the `service.Service` or a generic initialization + orchestration framework. + +- Do not proactively provide a system for injecting + components/services within a tendtermint node, though make it + possible to retrofit this kind of plugability in the future if + needed. + +- Prioritize implementation of p2p-based statesync reactor to obviate + need for users to inject a custom state-sync provider. + +## Detailed Design + +The [current +nodeImpl](https://github.com/tendermint/tendermint/blob/main/node/node.go#L47) +includes direct references to the implementations of each of the +reactors, which should be replaced by references to `service.Service` +objects. This will require moving construction of the [rpc +service](https://github.com/tendermint/tendermint/blob/main/node/node.go#L771) +into the constructor of +[makeNode](https://github.com/tendermint/tendermint/blob/main/node/node.go#L126). One +possible implementation of this would be to eliminate the current +`ConfigureRPC` method on the node package and instead [configure it +here](https://github.com/tendermint/tendermint/pull/6798/files#diff-375d57e386f20eaa5f09f02bb9d28bfc48ac3dca18d0325f59492208219e5618R441). + +To avoid adding complexity to the `node` package, we will add a +composite service implementation to the `service` package +that implements `service.Service` and is composed of a sequence of +underlying `service.Service` objects and handles their +startup/shutdown in the specified sequential order. + +Consensus, blocksync (*née* fast sync), and statesync all depend on +each other, and have significant initialization dependencies that are +presently encoded in the `node` package. As part of this change, a +new package/component (likely named `blocks` located at +`internal/blocks`) will encapsulate the initialization of these block +management areas of the code. + +### Injectable Component Option + +This section briefly describes a possible implementation for +user-supplied services running within a node. This should not be +implemented unless user-supplied components are a hard requirement for +a user. + +In order to allow components to be replaced, a new public function +will be added to the public interface of `node` with a signature that +resembles the following: + +```go +func NewWithServices(conf *config.Config, + logger log.Logger, + cf proxy.ClientCreator, + gen *types.GenesisDoc, + srvs []service.Service, +) (service.Service, error) { +``` + +The `service.Service` objects will be initialized in the order supplied, after +all pre-configured/default services have started (and shut down in reverse +order). The given services may implement additional interfaces, allowing them +to replace specific default services. `NewWithServices` will validate input +service lists with the following rules: + +- None of the services may already be running. +- The caller may not supply more than one replacement reactor for a given + default service type. + +If callers violate any of these rules, `NewWithServices` will return +an error. To retract support for this kind of operation in the future, +the function can be modified to *always* return an error. + +## Consequences + +### Positive + +- The node package will become easier to maintain. + +- It will become easier to add additional services within tendermint + nodes. + +- It will become possible to replace default components in the node + package without vendoring the tendermint repo and modifying internal + code. + +- The current end-to-end (e2e) test suite will be able to prevent any + regressions, and the new functionality can be thoroughly unit tested. + +- The scope of this project is very narrow, which minimizes risk. + +### Negative + +- This increases our reliance on the `service.Service` interface which + is probably not an interface that we want to fully commit to. + +- This proposal implements a fairly minimal set of functionality and + leaves open the possibility for many additional features which are + not included in the scope of this proposal. + +### Neutral + +N/A + +## Open Questions + +- To what extent does this new initialization framework need to accommodate + the legacy p2p stack? Would it be possible to delay a great deal of this + work to the 0.36 cycle to avoid this complexity? + + - Answer: _depends on timing_, and the requirement to ship pluggable reactors in 0.35. + +- Where should additional public types be exported for the 0.35 + release? + + Related to the general project of API stabilization we want to deprecate + the `types` package, and move its contents into a new `pkg` hierarchy; + however, the design of the `pkg` interface is currently underspecified. + If `types` is going to remain for the 0.35 release, then we should consider + the impact of using multiple organizing modalities for this code within a + single release. + +## Future Work + +- Improve or simplify the `service.Service` interface. There are some + pretty clear limitations with this interface as written (there's no + way to timeout slow startup or shut down, the cycle between the + `service.BaseService` and `service.Service` implementations is + troubling, the default panic in `OnReset` seems troubling.) + +- As part of the refactor of `service.Service` have all services/nodes + respect the lifetime of a `context.Context` object, and avoid the + current practice of creating `context.Context` objects in p2p and + reactor code. This would be required for in-process multi-tenancy. + +- Support explicit dependencies between components and allow for + parallel startup, so that different reactors can startup at the same + time, where possible. + +## References + +- [the component + graph](https://peter.bourgon.org/go-for-industrial-programming/#the-component-graph) + as a framing for internal service construction. + +## Appendix + +### Dependencies + +There's a relationship between the blockchain and consensus reactor +described by the following dependency graph makes replacing some of +these components more difficult relative to other reactors or +components. + +![consensus blockchain dependency graph](./img/consensus_blockchain.png) diff --git a/docs/architecture/tendermint-core/adr-071-proposer-based-timestamps.md b/docs/architecture/tendermint-core/adr-071-proposer-based-timestamps.md new file mode 100644 index 0000000..8402840 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-071-proposer-based-timestamps.md @@ -0,0 +1,333 @@ +# ADR 71: Proposer-Based Timestamps + +## Changelog + + - July 15 2021: Created by @williambanfield + - Aug 4 2021: Draft completed by @williambanfield + - Aug 5 2021: Draft updated to include data structure changes by @williambanfield + - Aug 20 2021: Language edits completed by @williambanfield + - Oct 25 2021: Update the ADR to match updated spec from @cason by @williambanfield + - Nov 10 2021: Additional language updates by @williambanfield per feedback from @cason + - Feb 2 2022: Synchronize logic for timely with latest version of the spec by @williambanfield + +## Status + + **Accepted** + +## Context + +Tendermint currently provides a monotonically increasing source of time known as [BFTTime](https://github.com/tendermint/tendermint/blob/main/spec/consensus/bft-time.md). +This mechanism for producing a source of time is reasonably simple. +Each correct validator adds a timestamp to each `Precommit` message it sends. +The timestamp it sends is either the validator's current known Unix time or one millisecond greater than the previous block time, depending on which value is greater. +When a block is produced, the proposer chooses the block timestamp as the weighted median of the times in all of the `Precommit` messages the proposer received. +The weighting is proportional to the amount of voting power, or stake, a validator has on the network. +This mechanism for producing timestamps is both deterministic and byzantine fault tolerant. + +This current mechanism for producing timestamps has a few drawbacks. +Validators do not have to agree at all on how close the selected block timestamp is to their own currently known Unix time. +Additionally, any amount of voting power `>1/3` may directly control the block timestamp. +As a result, it is quite possible that the timestamp is not particularly meaningful. + +These drawbacks present issues in the Tendermint protocol. +Timestamps are used by light clients to verify blocks. +Light clients rely on correspondence between their own currently known Unix time and the block timestamp to verify blocks they see; +However, their currently known Unix time may be greatly divergent from the block timestamp as a result of the limitations of `BFTTime`. + +The proposer-based timestamps specification suggests an alternative approach for producing block timestamps that remedies these issues. +Proposer-based timestamps alter the current mechanism for producing block timestamps in two main ways: + +1. The block proposer is amended to offer up its currently known Unix time as the timestamp for the next block instead of the `BFTTime`. +1. Correct validators only approve the proposed block timestamp if it is close enough to their own currently known Unix time. + +The result of these changes is a more meaningful timestamp that cannot be controlled by `<= 2/3` of the validator voting power. +This document outlines the necessary code changes in Tendermint to implement the corresponding [proposer-based timestamps specification](https://github.com/tendermint/tendermint/tree/main/spec/consensus/proposer-based-timestamp). + +## Alternative Approaches + +### Remove timestamps altogether + +Computer clocks are bound to skew for a variety of reasons. +Using timestamps in our protocol means either accepting the timestamps as not reliable or impacting the protocol’s liveness guarantees. +This design requires impacting the protocol’s liveness in order to make the timestamps more reliable. +An alternate approach is to remove timestamps altogether from the block protocol. +`BFTTime` is deterministic but may be arbitrarily inaccurate. +However, having a reliable source of time is quite useful for applications and protocols built on top of a blockchain. + +We therefore decided not to remove the timestamp. +Applications often wish for some transactions to occur on a certain day, on a regular period, or after some time following a different event. +All of these require some meaningful representation of agreed upon time. +The following protocols and application features require a reliable source of time: +* Tendermint Light Clients [rely on correspondence between their known time](https://github.com/tendermint/tendermint/blob/main/spec/light-client/verification/README.md#definitions-1) and the block time for block verification. +* Tendermint Evidence validity is determined [either in terms of heights or in terms of time](https://github.com/tendermint/tendermint/blob/8029cf7a0fcc89a5004e173ec065aa48ad5ba3c8/spec/consensus/evidence.md#verification). +* Unbonding of staked assets in the Cosmos Hub [occurs after a period of 21 days](https://github.com/cosmos/governance/blob/ce75de4019b0129f6efcbb0e752cd2cc9e6136d3/params-change/Staking.md#unbondingtime). +* IBC packets can use either a [timestamp or a height to timeout packet delivery](https://docs.cosmos.network/v0.45/ibc/overview.html#acknowledgements) + +Finally, inflation distribution in the Cosmos Hub uses an approximation of time to calculate an annual percentage rate. +This approximation of time is calculated using [block heights with an estimated number of blocks produced in a year](https://github.com/cosmos/governance/blob/master/params-change/Mint.md#blocksperyear). +Proposer-based timestamps will allow this inflation calculation to use a more meaningful and accurate source of time. + + +## Decision + +Implement proposer-based timestamps and remove `BFTTime`. + +## Detailed Design + +### Overview + +Implementing proposer-based timestamps will require a few changes to Tendermint’s code. +These changes will be to the following components: +* The `internal/consensus/` package. +* The `state/` package. +* The `Vote`, `CommitSig` and `Header` types. +* The consensus parameters. + +### Changes to `CommitSig` + +The [CommitSig](https://github.com/tendermint/tendermint/blob/a419f4df76fe4aed668a6c74696deabb9fe73211/types/block.go#L604) struct currently contains a timestamp. +This timestamp is the current Unix time known to the validator when it issued a `Precommit` for the block. +This timestamp is no longer used and will be removed in this change. + +`CommitSig` will be updated as follows: + +```diff +type CommitSig struct { + BlockIDFlag BlockIDFlag `json:"block_id_flag"` + ValidatorAddress Address `json:"validator_address"` +-- Timestamp time.Time `json:"timestamp"` + Signature []byte `json:"signature"` +} +``` + +### Changes to `Vote` messages + +`Precommit` and `Prevote` messages use a common [Vote struct](https://github.com/tendermint/tendermint/blob/a419f4df76fe4aed668a6c74696deabb9fe73211/types/vote.go#L50). +This struct currently contains a timestamp. +This timestamp is set using the [voteTime](https://github.com/tendermint/tendermint/blob/e8013281281985e3ada7819f42502b09623d24a0/internal/consensus/state.go#L2241) function and therefore vote times correspond to the current Unix time known to the validator, provided this time is greater than the timestamp of the previous block. +For precommits, this timestamp is used to construct the [CommitSig that is included in the block in the LastCommit](https://github.com/tendermint/tendermint/blob/e8013281281985e3ada7819f42502b09623d24a0/types/block.go#L754) field. +For prevotes, this field is currently unused. +Proposer-based timestamps will use the timestamp that the proposer sets into the block and will therefore no longer require that a timestamp be included in the vote messages. +This timestamp is therefore no longer useful as part of consensus and may optionally be dropped from the message. + +`Vote` will be updated as follows: + +```diff +type Vote struct { + Type tmproto.SignedMsgType `json:"type"` + Height int64 `json:"height"` + Round int32 `json:"round"` + BlockID BlockID `json:"block_id"` // zero if vote is nil. +-- Timestamp time.Time `json:"timestamp"` + ValidatorAddress Address `json:"validator_address"` + ValidatorIndex int32 `json:"validator_index"` + Signature []byte `json:"signature"` +} +``` + +### New consensus parameters + +The proposer-based timestamp specification includes a pair of new parameters that must be the same among all validators. +These parameters are `PRECISION`, and `MSGDELAY`. + +The `PRECISION` and `MSGDELAY` parameters are used to determine if the proposed timestamp is acceptable. +A validator will only Prevote a proposal if the proposal timestamp is considered `timely`. +A proposal timestamp is considered `timely` if it is within `PRECISION` and `MSGDELAY` of the Unix time known to the validator. +More specifically, a proposal timestamp is `timely` if `proposalTimestamp - PRECISION ≤ validatorLocalTime ≤ proposalTimestamp + PRECISION + MSGDELAY`. + +Because the `PRECISION` and `MSGDELAY` parameters must be the same across all validators, they will be added to the [consensus parameters](https://github.com/tendermint/tendermint/blob/main/proto/tendermint/types/params.proto#L11) as [durations](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration). + +The consensus parameters will be updated to include this `Synchrony` field as follows: + +```diff +type ConsensusParams struct { + Block BlockParams `json:"block"` + Evidence EvidenceParams `json:"evidence"` + Validator ValidatorParams `json:"validator"` + Version VersionParams `json:"version"` +++ Synchrony SynchronyParams `json:"synchrony"` +} +``` + +```go +type SynchronyParams struct { + MessageDelay time.Duration `json:"message_delay"` + Precision time.Duration `json:"precision"` +} +``` + +### Changes to the block proposal step + +#### Proposer selects block timestamp + +Tendermint currently uses the `BFTTime` algorithm to produce the block's `Header.Timestamp`. +The [proposal logic](https://github.com/tendermint/tendermint/blob/68ca65f5d79905abd55ea999536b1a3685f9f19d/internal/state/state.go#L269) sets the weighted median of the times in the `LastCommit.CommitSigs` as the proposed block's `Header.Timestamp`. + +In proposer-based timestamps, the proposer will still set a timestamp into the `Header.Timestamp`. +The timestamp the proposer sets into the `Header` will change depending on if the block has previously received a [polka](https://github.com/tendermint/tendermint/blob/053651160f496bb44b107a434e3e6482530bb287/docs/introduction/what-is-tendermint.md#consensus-overview) or not. + +#### Proposal of a block that has not previously received a polka + +If a proposer is proposing a new block then it will set the Unix time currently known to the proposer into the `Header.Timestamp` field. +The proposer will also set this same timestamp into the `Timestamp` field of the `Proposal` message that it issues. + +#### Re-proposal of a block that has previously received a polka + +If a proposer is re-proposing a block that has previously received a polka on the network, then the proposer does not update the `Header.Timestamp` of that block. +Instead, the proposer simply re-proposes the exact same block. +This way, the proposed block has the exact same block ID as the previously proposed block and the validators that have already received that block do not need to attempt to receive it again. + +The proposer will set the re-proposed block's `Header.Timestamp` as the `Proposal` message's `Timestamp`. + +#### Proposer waits + +Block timestamps must be monotonically increasing. +In `BFTTime`, if a validator’s clock was behind, the [validator added 1 millisecond to the previous block’s time and used that in its vote messages](https://github.com/tendermint/tendermint/blob/e8013281281985e3ada7819f42502b09623d24a0/internal/consensus/state.go#L2246). +A goal of adding proposer-based timestamps is to enforce some degree of clock synchronization, so having a mechanism that completely ignores the Unix time of the validator time no longer works. +Validator clocks will not be perfectly in sync. +Therefore, the proposer’s current known Unix time may be less than the previous block's `Header.Time`. +If the proposer’s current known Unix time is less than the previous block's `Header.Time`, the proposer will sleep until its known Unix time exceeds it. + +This change will require amending the [defaultDecideProposal](https://github.com/tendermint/tendermint/blob/822893615564cb20b002dd5cf3b42b8d364cb7d9/internal/consensus/state.go#L1180) method. +This method should now schedule a timeout that fires when the proposer’s time is greater than the previous block's `Header.Time`. +When the timeout fires, the proposer will finally issue the `Proposal` message. + +### Changes to proposal validation rules + +The rules for validating a proposed block will be modified to implement proposer-based timestamps. +We will change the validation logic to ensure that a proposal is `timely`. + +Per the proposer-based timestamps spec, `timely` only needs to be checked if a block has not received a +2/3 majority of `Prevotes` in a round. +If a block previously received a +2/3 majority of prevotes in a previous round, then +2/3 of the voting power considered the block's timestamp near enough to their own currently known Unix time in that round. + +The validation logic will be updated to check `timely` for blocks that did not previously receive +2/3 prevotes in a round. +Receiving +2/3 prevotes in a round is frequently referred to as a 'polka' and we will use this term for simplicity. + +#### Current timestamp validation logic + +To provide a better understanding of the changes needed to timestamp validation, we will first detail how timestamp validation works currently in Tendermint. + +The [validBlock function](https://github.com/tendermint/tendermint/blob/c3ae6f5b58e07b29c62bfdc5715b6bf8ae5ee951/state/validation.go#L14) currently [validates the proposed block timestamp in three ways](https://github.com/tendermint/tendermint/blob/c3ae6f5b58e07b29c62bfdc5715b6bf8ae5ee951/state/validation.go#L118). +First, the validation logic checks that this timestamp is greater than the previous block’s timestamp. + +Second, it validates that the block timestamp is correctly calculated as the weighted median of the timestamps in the [block’s LastCommit](https://github.com/tendermint/tendermint/blob/e8013281281985e3ada7819f42502b09623d24a0/types/block.go#L48). + +Finally, the validation logic authenticates the timestamps in the `LastCommit.CommitSig`. +The cryptographic signature in each `CommitSig` is created by signing a hash of fields in the block with the voting validator’s private key. +One of the items in this `signedBytes` hash is the timestamp in the `CommitSig`. +To authenticate the `CommitSig` timestamp, the validator authenticating votes builds a hash of fields that includes the `CommitSig` timestamp and checks this hash against the signature. +This takes place in the [VerifyCommit function](https://github.com/tendermint/tendermint/blob/e8013281281985e3ada7819f42502b09623d24a0/types/validation.go#L25). + +#### Remove unused timestamp validation logic + +`BFTTime` validation is no longer applicable and will be removed. +This means that validators will no longer check that the block timestamp is a weighted median of `LastCommit` timestamps. +Specifically, we will remove the call to [MedianTime in the validateBlock function](https://github.com/tendermint/tendermint/blob/4db71da68e82d5cb732b235eeb2fd69d62114b45/state/validation.go#L117). +The `MedianTime` function can be completely removed. + +Since `CommitSig`s will no longer contain a timestamp, the validator authenticating a commit will no longer include the `CommitSig` timestamp in the hash of fields it builds to check against the cryptographic signature. + +#### Timestamp validation when a block has not received a polka + +The [POLRound](https://github.com/tendermint/tendermint/blob/68ca65f5d79905abd55ea999536b1a3685f9f19d/types/proposal.go#L29) in the `Proposal` message indicates which round the block received a polka. +A negative value in the `POLRound` field indicates that the block has not previously been proposed on the network. +Therefore the validation logic will check for timely when `POLRound < 0`. + +When a validator receives a `Proposal` message, the validator will check that the `Proposal.Timestamp` is at most `PRECISION` greater than the current Unix time known to the validator, and at maximum `PRECISION + MSGDELAY` less than the current Unix time known to the validator. +If the timestamp is not within these bounds, the proposed block will not be considered `timely`. + +Once a full block matching the `Proposal` message is received, the validator will also check that the timestamp in the `Header.Timestamp` of the block matches this `Proposal.Timestamp`. +Using the `Proposal.Timestamp` to check `timely` allows for the `MSGDELAY` parameter to be more finely tuned since `Proposal` messages do not change sizes and are therefore faster to gossip than full blocks across the network. + +A validator will also check that the proposed timestamp is greater than the timestamp of the block for the previous height. +If the timestamp is not greater than the previous block's timestamp, the block will not be considered valid, which is the same as the current logic. + +#### Timestamp validation when a block has received a polka + +When a block is re-proposed that has already received a +2/3 majority of `Prevote`s on the network, the `Proposal` message for the re-proposed block is created with a `POLRound` that is `>= 0`. +A validator will not check that the `Proposal` is `timely` if the propose message has a non-negative `POLRound`. +If the `POLRound` is non-negative, each validator will simply ensure that it received the `Prevote` messages for the proposed block in the round indicated by `POLRound`. + +If the validator does not receive `Prevote` messages for the proposed block before the proposal timeout, then it will prevote nil. +Validators already check that +2/3 prevotes were seen in `POLRound`, so this does not represent a change to the prevote logic. + +A validator will also check that the proposed timestamp is greater than the timestamp of the block for the previous height. +If the timestamp is not greater than the previous block's timestamp, the block will not be considered valid, which is the same as the current logic. + +Additionally, this validation logic can be updated to check that the `Proposal.Timestamp` matches the `Header.Timestamp` of the proposed block, but it is less relevant since checking that votes were received is sufficient to ensure the block timestamp is correct. + +#### Relaxation of the 'Timely' check + +The `Synchrony` parameters, `MessageDelay` and `Precision` provide a means to bound the timestamp of a proposed block. +Selecting values that are too small presents a possible liveness issue for the network. +If a Tendermint network selects a `MessageDelay` parameter that does not accurately reflect the time to broadcast a proposal message to all of the validators on the network, nodes will begin rejecting proposals from otherwise correct proposers because these proposals will appear to be too far in the past. + +`MessageDelay` and `Precision` are planned to be configured as `ConsensusParams`. +A very common way to update `ConsensusParams` is by executing a transaction included in a block that specifies new values for them. +However, if the network is unable to produce blocks because of this liveness issue, no such transaction may be executed. +To prevent this dangerous condition, we will add a relaxation mechanism to the `Timely` predicate. +If consensus takes more than 10 rounds to produce a block for any reason, the `MessageDelay` will be doubled. +This doubling will continue for each subsequent 10 rounds of consensus. +This will enable chains that selected too small of a value for the `MessageDelay` parameter to eventually issue a transaction and readjust the parameters to more accurately reflect the broadcast time. + +This liveness issue is not as problematic for chains with very small `Precision` values. +Operators can more easily readjust local validator clocks to be more aligned. +Additionally, chains that wish to increase a small `Precision` value can still take advantage of the `MessageDelay` relaxation, waiting for the `MessageDelay` value to grow significantly and issuing proposals with timestamps that are far in the past of their peers. + +For more discussion of this, see [issue 371](https://github.com/tendermint/spec/issues/371). + +### Changes to the prevote step + +Currently, a validator will prevote a proposal in one of three cases: + +* Case 1: Validator has no locked block and receives a valid proposal. +* Case 2: Validator has a locked block and receives a valid proposal matching its locked block. +* Case 3: Validator has a locked block, sees a valid proposal not matching its locked block but sees +2/3 prevotes for the proposal’s block, either in the current round or in a round greater than or equal to the round in which it locked its locked block. + +The only change we will make to the prevote step is to what a validator considers a valid proposal as detailed above. + +### Changes to the precommit step + +The precommit step will not require much modification. +Its proposal validation rules will change in the same ways that validation will change in the prevote step with the exception of the `timely` check: precommit validation will never check that the timestamp is `timely`. + +### Remove voteTime Completely + +[voteTime](https://github.com/tendermint/tendermint/blob/822893615564cb20b002dd5cf3b42b8d364cb7d9/internal/consensus/state.go#L2229) is a mechanism for calculating the next `BFTTime` given both the validator's current known Unix time and the previous block timestamp. +If the previous block timestamp is greater than the validator's current known Unix time, then voteTime returns a value one millisecond greater than the previous block timestamp. +This logic is used in multiple places and is no longer needed for proposer-based timestamps. +It should therefore be removed completely. + +## Future Improvements + +* Implement BLS signature aggregation. +By removing fields from the `Precommit` messages, we are able to aggregate signatures. + +## Consequences + +### Positive + +* `<2/3` of validators can no longer influence block timestamps. +* Block timestamp will have stronger correspondence to real time. +* Improves the reliability of light client block verification. +* Enables BLS signature aggregation. +* Enables evidence handling to use time instead of height for evidence validity. + +### Neutral + +* Alters Tendermint’s liveness properties. +Liveness now requires that all correct validators have synchronized clocks within a bound. +Liveness will now also require that validators’ clocks move forward, which was not required under `BFTTime`. + +### Negative + +* May increase the length of the propose step if there is a large skew between the previous proposer and the current proposer’s local Unix time. +This skew will be bound by the `PRECISION` value, so it is unlikely to be too large. + +* Current chains with block timestamps far in the future will either need to pause consensus until after the erroneous block timestamp or must maintain synchronized but very inaccurate clocks. + +## References + +* [PBTS Spec](https://github.com/tendermint/tendermint/tree/main/spec/consensus/proposer-based-timestamp) +* [BFTTime spec](https://github.com/tendermint/tendermint/blob/main/spec/consensus/bft-time.md) +* [Issue 371](https://github.com/tendermint/spec/issues/371) diff --git a/docs/architecture/tendermint-core/adr-072-request-for-comments.md b/docs/architecture/tendermint-core/adr-072-request-for-comments.md new file mode 100644 index 0000000..8ed6621 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-072-request-for-comments.md @@ -0,0 +1,105 @@ +# ADR 72: Restore Requests for Comments + +## Changelog + +- 20-Aug-2021: Initial draft (@creachadair) + +## Status + +Implemented + +## Context + +In the past, we kept a collection of Request for Comments (RFC) documents in `docs/rfc`. +Prior to the creation of the ADR process, these documents were used to document +design and implementation decisions about Tendermint Core. The RFC directory +was removed in favor of ADRs, in commit 3761aa69 (PR +[\#6345](https://github.com/tendermint/tendermint/pull/6345)). + +For issues where an explicit design decision or implementation change is +required, an ADR is generally preferable to an open-ended RFC: An ADR is +relatively narrowly-focused, identifies a specific design or implementation +question, and documents the consensus answer to that question. + +Some discussions are more open-ended, however, or don't require a specific +decision to be made (yet). Such conversations are still valuable to document, +and several members of the Tendermint team have been doing so by writing gists +or Google docs to share them around. That works well enough in the moment, but +gists do not support any kind of collaborative editing, and both gists and docs +are hard to discover after the fact. Google docs have much better collaborative +editing, but are worse for discoverability, especially when contributors span +different Google accounts. + +Discoverability is important, because these kinds of open-ended discussions are +useful to people who come later -- either as new team members or as outside +contributors seeking to use and understand the thoughts behind our designs and +the architectural decisions that arose from those discussion. + +With these in mind, I propose that: + +- We re-create a new, initially empty `docs/rfc` directory in the repository, + and use it to capture these kinds of open-ended discussions in supplement to + ADRs. + +- Unlike in the previous RFC scheme, documents in this new directory will + _not_ be used directly for decision-making. This is the key difference + between an RFC and an ADR. + + Instead, an RFC will exist to document background, articulate general + principles, and serve as a historical record of discussion and motivation. + + In this system, an RFC may _only_ result in a decision indirectly, via ADR + documents created in response to the RFC. + + **In short:** If a decision is required, write an ADR; otherwise if a + sufficiently broad discussion is needed, write an RFC. + +Just so that there is a consistent format, I also propose that: + +- RFC files are named `rfc-XXX-title.{md,rst,txt}` and are written in plain + text, Markdown, or ReStructured Text. + +- Like an ADR, an RFC should include a high-level change log at the top of the + document, and sections for: + + * Abstract: A brief, high-level synopsis of the topic. + * Background: Any background necessary to understand the topic. + * Discussion: Detailed discussion of the issue being considered. + +- Unlike an ADR, an RFC does _not_ include sections for Decisions, Detailed + Design, or evaluation of proposed solutions. If an RFC leads to a proposal + for an actual architectural change, that must be recorded in an ADR in the + usual way, and may refer back to the RFC in its References section. + +## Alternative Approaches + +Leaving aside implementation details, the main alternative to this proposal is +to leave things as they are now, with ADRs as the only log of record and other +discussions being held informally in whatever medium is convenient at the time. + +## Decision + +(pending) + +## Detailed Design + +- Create a new `docs/rfc` directory in the `tendermint` repository. Note that + this proposal intentionally does _not_ pull back the previous contents of + that path from Git history, as those documents were appropriately merged into + the ADR process. + +- Create a `README.md` for RFCs that explains the rules and their relationship + to ADRs. + +- Create an `rfc-template.md` file for RFC files. + +## Consequences + +### Positive + +- We will have a more discoverable place to record open-ended discussions that + do not immediately result in a design change. + +### Negative + +- Potentially some people could be confused about the RFC/ADR distinction. diff --git a/docs/architecture/tendermint-core/adr-073-libp2p.md b/docs/architecture/tendermint-core/adr-073-libp2p.md new file mode 100644 index 0000000..ad13a59 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-073-libp2p.md @@ -0,0 +1,235 @@ +# ADR 073: Adopt LibP2P + +## Changelog + +- 2021-11-02: Initial Draft (@tychoish) + +## Status + +Proposed. + +## Context + + +As part of the 0.35 development cycle, the Tendermint team completed +the first phase of the work described in ADRs 61 and 62, which included a +large scale refactoring of the reactors and the p2p message +routing. This replaced the switch and many of the other legacy +components without breaking protocol or network-level +interoperability and left the legacy connection/socket handling code. + +Following the release, the team has reexamined the state of the code +and the design, as well as Tendermint's requirements. The notes +from that process are available in the [P2P Roadmap +RFC][rfc]. + +This ADR supersedes the decisions made in ADRs 60 and 61, but +builds on the completed portions of this work. Previously, the +boundaries of peer management, message handling, and the higher level +business logic (e.g., "the reactors") were intermingled, and core +elements of the p2p system were responsible for the orchestration of +higher-level business logic. Refactoring the legacy components +made it more obvious that this entanglement of responsibilities +had outsized influence on the entire implementation, making +it difficult to iterate within the current abstractions. +It would not be viable to maintain interoperability with legacy +systems while also achieving many of our broader objectives. + +LibP2P is a thoroughly-specified implementation of a peer-to-peer +networking stack, designed specifically for systems such as +ours. Adopting LibP2P as the basis of Tendermint will allow the +Tendermint team to focus more of their time on other differentiating +aspects of the system, and make it possible for the ecosystem as a +whole to take advantage of tooling and efforts of the LibP2P +platform. + +## Alternative Approaches + +As discussed in the [P2P Roadmap RFC][rfc], the primary alternative would be to +continue development of Tendermint's home-grown peer-to-peer +layer. While that would give the Tendermint team maximal control +over the peer system, the current design is unexceptional on its +own merits, and the prospective maintenance burden for this system +exceeds our tolerances for the medium term. + +Tendermint can and should differentiate itself not on the basis of +its networking implementation or peer management tools, but providing +a consistent operator experience, a battle-tested consensus algorithm, +and an ergonomic user experience. + +## Decision + +Tendermint will adopt libp2p during the 0.37 development cycle, +replacing the bespoke Tendermint P2P stack. This will remove the +`Endpoint`, `Transport`, `Connection`, and `PeerManager` abstractions +and leave the reactors, `p2p.Router` and `p2p.Channel` +abstractions. + +LibP2P may obviate the need for a dedicated peer exchange (PEX) +reactor, which would also in turn obviate the need for a dedicated +seed mode. If this is the case, then all of this functionality would +be removed. + +If it turns out (based on the advice of Protocol Labs) that it makes +sense to maintain separate pubsub or gossipsub topics +per-message-type, then the `Router` abstraction could also +be entirely subsumed. + +## Detailed Design + +### Implementation Changes + +The seams in the P2P implementation between the higher level +constructs (reactors), the routing layer (`Router`) and the lower +level connection and peer management code make this operation +relatively straightforward to implement. A key +goal in this design is to minimize the impact on the reactors +(potentially entirely,) and completely remove the lower level +components (e.g., `Transport`, `Connection` and `PeerManager`) using the +separation afforded by the `Router` layer. The current state of the +code makes these changes relatively surgical, and limited to a small +number of methods: + +- `p2p.Router.OpenChannel` will still return a `Channel` structure + which will continue to serve as a pipe between the reactors and the + `Router`. The implementation will no longer need the queue + implementation, and will instead start goroutines that + are responsible for routing the messages from the channel to libp2p + fundamentals, replacing the current `p2p.Router.routeChannel`. + +- The current `p2p.Router.dialPeers` and `p2p.Router.acceptPeers`, + are responsible for establishing outbound and inbound connections, + respectively. These methods will be removed, along with + `p2p.Router.openConnection`, and the libp2p connection manager will + be responsible for maintaining network connectivity. + +- The `p2p.Channel` interface will change to replace Go + channels with a more functional interface for sending messages. + New methods on this object will take contexts to support safe + cancellation, and return errors, and will block rather than + running asynchronously. The `Out` channel through which + reactors send messages to Peers, will be replaced by a `Send` + method, and the Error channel will be replaced by an `Error` + method. + +- Reactors will be passed an interface that will allow them to + access Peer information from libp2p. This will supplant the + `p2p.PeerUpdates` subscription. + +- Add some kind of heartbeat message at the application level + (e.g. with a reactor,) potentially connected to libp2p's DHT to be + used by reactors for service discovery, message targeting, or other + features. + +- Replace the existing/legacy handshake protocol with [Noise](http://www.noiseprotocol.org/noise.html). + +This project will initially use the TCP-based transport protocols within +libp2p. QUIC is also available as an option that we may implement later. +We will not support mixed networks in the initial release, but will +revisit that possibility later if there is a demonstrated need. + +### Upgrade and Compatibility + +Because the routers and all current P2P libraries are `internal` +packages and not part of the public API, the only changes to the public +API surface area of Tendermint will be different configuration +file options, replacing the current P2P options with options relevant +to libp2p. + +However, it will not be possible to run a network with both networking +stacks active at once, so the upgrade to the version of Tendermint +will need to be coordinated between all nodes of the network. This is +consistent with the expectations around upgrades for Tendermint moving +forward, and will help manage both the complexity of the project and +the implementation timeline. + +## Open Questions + +- What is the role of Protocol Labs in the implementation of libp2p in + tendermint, both during the initial implementation and on an ongoing + basis thereafter? + +- Should all P2P traffic for a given node be pushed to a single topic, + so that a topic maps to a specific ChainID, or should + each reactor (or type of message) have its own topic? How many + topics can a libp2p network support? Is there testing that validates + the capabilities? + +- Tendermint presently provides a very coarse QoS-like functionality + using priorities based on message-type. + This intuitively/theoretically ensures that evidence and consensus + messages don't get starved by blocksync/statesync messages. It's + unclear if we can or should attempt to replicate this with libp2p. + +- What kind of QoS functionality does libp2p provide and what kind of + metrics does libp2p provide about it's QoS functionality? + +- Is it possible to store additional (and potentially arbitrary) + information into the DHT as part of the heartbeats between nodes, + such as the latest height, and then access that in the + reactors. How frequently can the DHT be updated? + +- Does it make sense to have reactors continue to consume inbound + messages from a Channel (`In`) or is there another interface or + pattern that we should consider? + + - We should avoid exposing Go channels when possible, and likely + some kind of alternate iterator likely makes sense for processing + messages within the reactors. + +- What are the security and protocol implications of tracking + information from peer heartbeats and exposing that to reactors? + +- How much (or how little) configuration can Tendermint provide for + libp2p, particularly on the first release? + + - In general, we should not support byo-functionality for libp2p + components within Tendermint, and reduce the configuration surface + area, as much as possible. + +- What are the best ways to provide request/response semantics for + reactors on top of libp2p? Will it be possible to add + request/response semantics in a future release or is there + anticipatory work that needs to be done as part of the initial + release? + +## Consequences + +### Positive + +- Reduce the maintenance burden for the Tendermint Core team by + removing a large swath of legacy code that has proven to be + difficult to modify safely. + +- Remove the responsibility for maintaining and developing the entire + peer management system (p2p) and stack. + +- Provide users with a more stable peer and networking system, + Tendermint can improve operator experience and network stability. + +### Negative + +- By deferring to library implementations for peer management and + networking, Tendermint loses some flexibility for innovating at the + peer and networking level. However, Tendermint should be innovating + primarily at the consensus layer, and libp2p does not preclude + optimization or development in the peer layer. + +- Libp2p is a large dependency and Tendermint would become dependent + upon Protocol Labs' release cycle and prioritization for bug + fixes. If this proves onerous, it's possible to maintain a vendor + fork of relevant components as needed. + +### Neutral + +- N/A + +## References + +- [ADR 61: P2P Refactor Scope][adr61] +- [ADR 62: P2P Architecture][adr62] +- [P2P Roadmap RFC][rfc] + +[adr61]: ./adr-061-p2p-refactor-scope.md +[adr62]: ./adr-062-p2p-architecture.md +[rfc]: ../rfc/rfc-000-p2p-roadmap.rst diff --git a/docs/architecture/tendermint-core/adr-074-timeout-params.md b/docs/architecture/tendermint-core/adr-074-timeout-params.md new file mode 100644 index 0000000..3aa75b1 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-074-timeout-params.md @@ -0,0 +1,203 @@ +# ADR 74: Migrate Timeout Parameters to Consensus Parameters + +## Changelog + +- 03-Jan-2022: Initial draft (@williambanfield) +- 13-Jan-2022: Updated to indicate work on upgrade path needed (@williambanfield) + +## Status + +Proposed + +## Context + +### Background + +Tendermint's consensus timeout parameters are currently configured locally by each validator +in the validator's [config.toml][config-toml]. +This means that the validators on a Tendermint network may have different timeouts +from each other. There is no reason for validators on the same network to configure +different timeout values. Proper functioning of the Tendermint consensus algorithm +relies on these parameters being uniform across validators. + +The configurable values are as follows: + +* `TimeoutPropose` + * How long the consensus algorithm waits for a proposal block before issuing a prevote. + * If no prevote arrives by `TimeoutPropose`, then the consensus algorithm will issue a nil prevote. +* `TimeoutProposeDelta` + * How much the `TimeoutPropose` grows each round. +* `TimeoutPrevote` + * How long the consensus algorithm waits after receiving +2/3 prevotes with + no quorum for a value before issuing a precommit for nil. + (See the [arXiv paper][arxiv-paper], Algorithm 1, Line 34) +* `TimeoutPrevoteDelta` + * How much the `TimeoutPrevote` increases with each round. +* `TimeoutPrecommit` + * How long the consensus algorithm waits after receiving +2/3 precommits that + do not have a quorum for a value before entering the next round. + (See the [arXiv paper][arxiv-paper], Algorithm 1, Line 47) +* `TimeoutPrecommitDelta` + * How much the `TimeoutPrecommit` increases with each round. +* `TimeoutCommit` + * How long the consensus algorithm waits after committing a block but before starting the new height. + * This gives a validator a chance to receive slow precommits. +* `SkipTimeoutCommit` + * Make progress as soon as the node has 100% of the precommits. + + +### Overview of Change + +We will consolidate the timeout parameters and migrate them from the node-local +`config.toml` file into the network-global consensus parameters. + +The 8 timeout parameters will be consolidated down to 6. These will be as follows: + +* `TimeoutPropose` + * Same as current `TimeoutPropose`. +* `TimeoutProposeDelta` + * Same as current `TimeoutProposeDelta`. +* `TimeoutVote` + * How long validators wait for votes in both the prevote + and precommit phase of the consensus algorithm. This parameter subsumes + the current `TimeoutPrevote` and `TimeoutPrecommit` parameters. +* `TimeoutVoteDelta` + * How much the `TimeoutVote` will grow each successive round. + This parameter subsumes the current `TimeoutPrevoteDelta` and `TimeoutPrecommitDelta` + parameters. +* `TimeoutCommit` + * Same as current `TimeoutCommit`. +* `BypassCommitTimeout` + * Same as current `SkipTimeoutCommit`, renamed for clarity. + +A safe default will be provided by Tendermint for each of these parameters and +networks will be able to update the parameters as they see fit. Local updates +to these parameters will no longer be possible; instead, the application will control +updating the parameters. Applications using the Cosmos SDK will be automatically be +able to change the values of these consensus parameters [via a governance proposal][cosmos-sdk-consensus-params]. + +This change is low-risk. While parameters are locally configurable, many running chains +do not change them from their default values. For example, initializing +a node on Osmosis, Terra, and the Cosmos Hub using the their `init` command produces +a `config.toml` with Tendermint's default values for these parameters. + +### Why this parameter consolidation? + +Reducing the number of parameters is good for UX. Fewer superfluous parameters makes +running and operating a Tendermint network less confusing. + +The Prevote and Precommit messages are both similar sizes, require similar amounts +of processing so there is no strong need for them to be configured separately. + +The `TimeoutPropose` parameter governs how long Tendermint will wait for the proposed +block to be gossiped. Blocks are much larger than votes and therefore tend to be +gossiped much more slowly. It therefore makes sense to keep `TimeoutPropose` and +the `TimeoutProposeDelta` as parameters separate from the vote timeouts. + +`TimeoutCommit` is used by chains to ensure that the network waits for the votes from +slower validators before proceeding to the next height. Without this timeout, the votes +from slower validators would consistently not be included in blocks and those validators +would not be counted as 'up' from the chain's perspective. Being down damages a validator's +reputation and causes potential stakers to think twice before delegating to that validator. + +`TimeoutCommit` also prevents the network from producing the next height as soon as validators +on the fastest hardware with a summed voting power of +2/3 of the network's total have +completed execution of the block. Allowing the network to proceed as soon as the fastest ++2/3 completed execution would have a cumulative effect over heights, eventually +leaving slower validators unable to participate in consensus at all. `TimeoutCommit` +therefore allows networks to have greater variability in hardware. Additional +discussion of this can be found in [tendermint issue 5911][tendermint-issue-5911-comment] +and [spec issue 359][spec-issue-359]. + +## Alternative Approaches + +### Hardcode the parameters + +Many Tendermint networks run on similar cloud-hosted infrastructure. Therefore, +they have similar bandwidth and machine resources. The timings for propagating votes +and blocks are likely to be reasonably similar across networks. As a result, the +timeout parameters are good candidates for being hardcoded. Hardcoding the timeouts +in Tendermint would mean entirely removing these parameters from any configuration +that could be altered by either an application or a node operator. Instead, +Tendermint would ship with a set of timeouts and all applications using Tendermint +would use this exact same set of values. + +While Tendermint nodes often run with similar bandwidth and on similar cloud-hosted +machines, there are enough points of variability to make configuring +consensus timeouts meaningful. Namely, Tendermint network topologies are likely to be +very different from chain to chain. Additionally, applications may vary greatly in +how long the `Commit` phase may take. Applications that perform more work during `Commit` +require a longer `TimeoutCommit` to allow the application to complete its work +and be prepared for the next height. + +## Decision + +The decision has been made to implement this work, with the caveat that the +specific mechanism for introducing the new parameters to chains is still ongoing. + +## Detailed Design + +### New Consensus Parameters + +A new `TimeoutParams` `message` will be added to the [params.proto file][consensus-params-proto]. +This message will have the following form: + +```proto +message TimeoutParams { + google.protobuf.Duration propose = 1; + google.protobuf.Duration propose_delta = 2; + google.protobuf.Duration vote = 3; + google.protobuf.Duration vote_delta = 4; + google.protobuf.Duration commit = 5; + bool bypass_commit_timeout = 6; +} +``` + +This new message will be added as a field into the [`ConsensusParams` +message][consensus-params-proto]. The same default values that are [currently +set for these parameters][current-timeout-defaults] in the local configuration +file will be used as the defaults for these new consensus parameters in the +[consensus parameter defaults][default-consensus-params]. + +The new consensus parameters will be subject to the same +[validity rules][time-param-validation] as the current configuration values, +namely, each value must be non-negative. + +### Migration + +The new `ConsensusParameters` will be added during an upcoming release. In this +release, the old `config.toml` parameters will cease to control the timeouts and +an error will be logged on nodes that continue to specify these values. The specific +mechanism by which these parameters will added to a chain is being discussed in +[RFC-009][rfc-009] and will be decided ahead of the next release. + +The specific mechanism for adding these parameters depends on work related to +[soft upgrades][soft-upgrades], which is still ongoing. + +## Consequences + +### Positive + +* Timeout parameters will be equal across all of the validators in a Tendermint network. +* Remove superfluous timeout parameters. + +### Negative + +### Neutral + +* Timeout parameters require consensus to change. + +## References + +[conseusus-params-proto]: https://github.com/tendermint/spec/blob/a00de7199f5558cdd6245bbbcd1d8405ccfb8129/proto/tendermint/types/params.proto#L11 +[hashed-params]: https://github.com/tendermint/tendermint/blob/7cdf560173dee6773b80d1c574a06489d4c394fe/types/params.go#L49 +[default-consensus-params]: https://github.com/tendermint/tendermint/blob/7cdf560173dee6773b80d1c574a06489d4c394fe/types/params.go#L79 +[current-timeout-defaults]: https://github.com/tendermint/tendermint/blob/7cdf560173dee6773b80d1c574a06489d4c394fe/config/config.go#L955 +[config-toml]: https://github.com/tendermint/tendermint/blob/5cc980698a3402afce76b26693ab54b8f67f038b/config/toml.go#L425-L440 +[cosmos-sdk-consensus-params]: https://github.com/cosmos/cosmos-sdk/issues/6197 +[time-param-validation]: https://github.com/tendermint/tendermint/blob/7cdf560173dee6773b80d1c574a06489d4c394fe/config/config.go#L1038 +[tendermint-issue-5911-comment]: https://github.com/tendermint/tendermint/issues/5911#issuecomment-973560381 +[spec-issue-359]: https://github.com/tendermint/spec/issues/359 +[arxiv-paper]: https://arxiv.org/pdf/1807.04938.pdf +[soft-upgrades]: https://github.com/tendermint/spec/pull/222 +[rfc-009]: https://github.com/tendermint/tendermint/pull/7524 diff --git a/docs/architecture/tendermint-core/adr-075-rpc-subscription.md b/docs/architecture/tendermint-core/adr-075-rpc-subscription.md new file mode 100644 index 0000000..4c325f4 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-075-rpc-subscription.md @@ -0,0 +1,684 @@ +# ADR 075: RPC Event Subscription Interface + +## Changelog + +- 01-Mar-2022: Update long-polling interface (@creachadair). +- 10-Feb-2022: Updates to reflect implementation. +- 26-Jan-2022: Marked accepted. +- 22-Jan-2022: Updated and expanded (@creachadair). +- 20-Nov-2021: Initial draft (@creachadair). + +--- +## Status + +Accepted + +--- +## Background & Context + +For context, see [RFC 006: Event Subscription][rfc006]. + +The [Tendermint RPC service][rpc-service] permits clients to subscribe to the +event stream generated by a consensus node. This allows clients to observe the +state of the consensus network, including details of the consensus algorithm +state machine, proposals, transaction delivery, and block completion. The +application may also attach custom key-value attributes to events to expose +application-specific details to clients. + +The event subscription API in the RPC service currently comprises three methods: + +1. `subscribe`: A request to subscribe to the events matching a specific + [query expression][query-grammar]. Events can be filtered by their key-value + attributes, including custom attributes provided by the application. + +2. `unsubscribe`: A request to cancel an existing subscription based on its + query expression. + +3. `unsubscribe_all`: A request to cancel all existing subscriptions belonging + to the client. + +There are some important technical and UX issues with the current RPC event +subscription API. The rest of this ADR outlines these problems in detail, and +proposes a new API scheme intended to address them. + +### Issue 1: Persistent connections + +To subscribe to a node's event stream, a client needs a persistent connection +to the node. Unlike the other methods of the service, for which each call is +serviced by a short-lived HTTP round trip, subscription delivers a continuous +stream of events to the client by hijacking the HTTP channel for a websocket. +The stream (and hence the HTTP request) persists until either the subscription +is explicitly canceled, or the connection is closed. + +There are several problems with this API: + +1. **Expensive per-connection state**: The server must maintain a substantial + amount of state per subscriber client: + + - The current implementation uses a [WebSocket][ws] for each active + subscriber. The connection must be maintained even if there are no + matching events for a given client. + + The server can drop idle connections to save resources, but doing so + terminates all subscriptions on those connections and forces those clients + to re-connect, adding additional resource churn for the server. + + - In addition, the server maintains a separate buffer of undelivered events + for each client. This is to reduce the dual risks that a client will miss + events, and that a slow client could "push back" on the publisher, + impeding the progress of consensus. + + Because event traffic is quite bursty, queues can potentially take up a + lot of memory. Moreover, each subscriber may have a different filter + query, so the server winds up having to duplicate the same events among + multiple subscriber queues. Not only does this add memory pressure, but it + does so most at the worst possible time, i.e., when the server is already + under load from high event traffic. + +2. **Operational access control is difficult**: The server's websocket + interface exposes _all_ the RPC service endpoints, not only the subscription + methods. This includes methods that allow callers to inject arbitrary + transactions (`broadcast_tx_*`) and evidence (`broadcast_evidence`) into the + network, remove transactions (`remove_tx`), and request arbitrary amounts of + chain state. + + Filtering requests to the GET endpoint is straightforward: A reverse proxy + like [nginx][nginx] can easily filter methods by URL path. Filtering POST + requests takes a bit more work, but can be managed with a filter program + that speaks [FastCGI][fcgi] and parses JSON-RPC request bodies. + + Filtering the websocket interface requires a dedicated proxy implementation. + Although nginx can [reverse-proxy websockets][rp-ws], it does not support + filtering websocket traffic via FastCGI. The operator would need to either + implement a custom [nginx extension module][ng-xm] or build and run a + standalone proxy that implements websocket and filters each session. Apart + from the work, this also makes the system even more resource intensive, as + well as introducing yet another connection that could potentially time out + or stall on full buffers. + + Even for the simple case of restricting access to only event subscription, + there is no easy solution currently: Once a caller has access to the + websocket endpoint, it has complete access to the RPC service. + +### Issue 2: Inconvenient client API + +The subscription interface has some inconvenient features for the client as +well as the server. These include: + +1. **Non-standard protocol:** The RPC service is mostly [JSON-RPC 2.0][jsonrpc2], + but the subscription interface diverges from the standard. + + In a standard JSON-RPC 2.0 call, the client initiates a request to the + server with a unique ID, and the server concludes the call by sending a + reply for that ID. The `subscribe` implementation, however, sends multiple + responses to the client's request: + + - The client sends `subscribe` with some ID `x` and the desired query + + - The server responds with ID `x` and an empty confirmation response. + + - The server then (repeatedly) sends event result responses with ID `x`, one + for each item with a matching event. + + Standard JSON-RPC clients will reject the subsequent replies, as they + announce a request ID (`x`) that is already complete. This means a caller + has to implement Tendermint-specific handling for these responses. + + Moreover, the result format is different between the initial confirmation + and the subsequent responses. This means a caller has to implement special + logic for decoding the first response versus the subsequent ones. + +2. **No way to detect data loss:** The subscriber connection can be terminated + for many reasons. Even ignoring ordinary network issues (e.g., packet loss): + + - The server will drop messages and/or close the websocket if its write + buffer fills, or if the queue of undelivered matching events is not + drained fast enough. The client has no way to discover that messages were + dropped even if the connection remains open. + + - Either the client or the server may close the websocket if the websocket + PING and PONG exchanges are not handled correctly, or frequently enough. + Even if correctly implemented, this may fail if the system is under high + load and cannot service those control messages in a timely manner. + + When the connection is terminated, the server drops all the subscriptions + for that client (as if it had called `unsubscribe_all`). Even if the client + reconnects, any events that were published during the period between the + disconnect and re-connect and re-subscription will be silently lost, and the + client has no way to discover that it missed some relevant messages. + +3. **No way to replay old events:** Even if a client knew it had missed some + events (due to a disconnection, for example), the API provides no way for + the client to "play back" events it may have missed. + +4. **Large response sizes:** Some event data can be quite large, and there can + be substantial duplication across items. The API allows the client to select + _which_ events are reported, but has no way to control which parts of a + matching event it wishes to receive. + + This can be costly on the server (which has to marshal those data into + JSON), the network, and the client (which has to unmarshal the result and + then pick through for the components that are relevant to it). + + Besides being inefficient, this also contributes to some of the persistent + connection issues mentioned above, e.g., filling up the websocket write + buffer and forcing the server to queue potentially several copies of a large + value in memory. + +5. **Client identity is tied to network address:** The Tendermint event API + identifies each subscriber by a (Client ID, Query) pair. In the RPC service, + the query is provided by the client, but the client ID is set to the TCP + address of the client (typically "host:port" or "ip:port"). + + This means that even if the server did _not_ drop subscriptions immediately + when the websocket connection is closed, a client may not be able to + reattach to its existing subscription. Dialing a new connection is likely + to result in a different port (and, depending on their own proxy setup, + possibly a different public IP). + + In isolation, this problem would be easy to work around with a new + subscription parameter, but it would require several other changes to the + handling of event subscriptions for that workaround to become useful. + +--- +## Decision + +To address the described problems, we will: + +1. Introduce a new API for event subscription to the Tendermint RPC service. + The proposed API is described in [Detailed Design](#detailed-design) below. + +2. This new API will target the Tendermint v0.36 release, during which the + current ("streaming") API will remain available as-is, but deprecated. + +3. The streaming API will be entirely removed in release v0.37, which will + require all users of event subscription to switch to the new API. + +> **Point for discussion:** Given that ABCI++ and PBTS are the main priorities +> for v0.36, it would be fine to slip the first phase of this work to v0.37. +> Unless there is a time problem, however, the proposed design does not disrupt +> the work on ABCI++ or PBTS, and will not increase the scope of breaking +> changes. Therefore the plan is to begin in v0.36 and slip only if necessary. + +--- +## Detailed Design + +### Design Goals + +Specific goals of this design include: + +1. Remove the need for a persistent connection to each subscription client. + Subscribers should use the same HTTP request flow for event subscription + requests as for other RPC calls. + +2. The server retains minimal state (possibly none) per-subscriber. In + particular: + + - The server does not buffer unconsumed writes nor queue undelivered events + on a per-client basis. + - A client that stalls or goes idle does not cost the server any resources. + - Any event data that is buffered or stored is shared among _all_ + subscribers, and is not duplicated per client. + +3. Slow clients have no impact (or minimal impact) on the rate of progress of + the consensus algorithm, beyond the ambient overhead of servicing individual + RPC requests. + +4. Clients can tell when they have missed events matching their subscription, + within some reasonable (configurable) window of time, and can "replay" + events within that window to catch up. + +5. Nice to have: It should be easy to use the event subscription API from + existing standard tools and libraries, including command-line use for + testing and experimentation. + +### Definitions + +- The **event stream** of a node is a single, time-ordered, heterogeneous + stream of event items. + +- Each **event item** comprises an **event datum** (for example, block header + metadata for a new-block event), and zero or more optional **events**. + +- An **event** means the [ABCI `Event` data type][abci-event], which comprises + a string type and zero or more string key-value **event attributes**. + + The use of the new terms "event item" and "event datum" is to avert confusion + between the values that are published to the event bus (what we call here + "event items") and the ABCI `Event` data type. + +- The node assigns each event item a unique identifier string called a + **cursor**. A cursor must be unique among all events published by a single + node, but it is not required to be unique globally across nodes. + + Cursors are time-ordered so that given event items A and B, if A was + published before B, then cursor(A) < cursor(B) in lexicographic order. + + A minimum viable cursor implementation is a tuple consisting of a timestamp + and a sequence number (e.g., `16CCC798FB5F4670-0123`). However, it may also + be useful to append basic type information to a cursor, to allow efficient + filtering (e.g., `16CCC87E91869050-0091:BeginBlock`). + + The initial implementation will use the minimum viable format. + +### Discussion + +The node maintains an **event log**, a shared ordered record of the events +published to its event bus within an operator-configurable time window. The +initial implementation will store the event log in-memory, and the operator +will be given two per-node configuration settings. Note, these names are +provisional: + +- `[rpc] event-log-window-size`: A duration before the latest published event, + during which the node will retain event items published. Setting this value + to zero disables event subscription. + +- `[rpc] event-log-max-items`: A maximum number of event items that the node + will retain within the time window. If the number of items exceeds this + value, the node discardes the oldest items in the window. Setting this value + to zero means that no limit is imposed on the number of items. + +The node will retain all events within the time window, provided they do not +exceed the maximum number. These config parameters allow the operator to +loosely regulate how much memory and storage the node allocates to the event +log. The client can use the server reply to tell whether the events it wants +are still available from the event log. + +The event log is shared among all subscribers to the node. + +> **Discussion point:** Should events persist across node restarts? +> +> The current event API does not persist events across restarts, so this new +> design does not either. Note, however, that we may "spill" older event data +> to disk as a way of controlling memory use. Such usage is ephemeral, however, +> and does not need to be tracked as node data (e.g., it could be temp files). + +### Query API + +To retrieve event data, the client will call the (new) RPC method `events`. +The parameters of this method will correspond to the following Go types: + +```go +type EventParams struct { + // Optional filter spec. If nil or empty, all items are eligible. + Filter *Filter `json:"filter"` + + // The maximum number of eligible results to return. + // If zero or negative, the server will report a default number. + MaxResults int `json:"max_results"` + + // Return only items after this cursor. If empty, the limit is just + // before the the beginning of the event log. + After string `json:"after"` + + // Return only items before this cursor. If empty, the limit is just + // after the head of the event log. + Before string `json:"before"` + + // Wait for up to this long for events to be available. + WaitTime time.Duration `json:"wait_time"` +} + +type Filter struct { + Query string `json:"query"` +} +``` + +> **Discussion point:** The initial implementation will not cache filter +> queries for the client. If this turns out to be a performance issue in +> production, the service can keep a small shared cache of compiled queries. +> Given the improvements from #7319 et seq., this should not be necessary. + +> **Discussion point:** For the initial implementation, the new API will use +> the existing query language as-is. Future work may extend the Filter message +> with a more structured and/or expressive query surface, but that is beyond +> the scope of this design. + +The semantics of the request are as follows: An item in the event log is +**eligible** for a query if: + +- It is newer than the `after` cursor (if set). +- It is older than the `before` cursor (if set). +- It matches the filter (if set). + +Among the eligible items in the log, the server returns up to `max_results` of +the newest items, in reverse order of cursor. If `max_results` is unset the +server chooses a number to return, and will cap `max_results` at a sensible +limit. + +The `wait_time` parameter is used to effect polling. If `before` is empty and +no items are available, the server will wait for up to `wait_time` for matching +items to arrive at the head of the log. If `wait_time` is zero or negative, the +server will wait for a default (positive) interval. + +If `before` non-empty, `wait_time` is ignored: new results are only added to +the head of the log, so there is no need to wait. This allows the client to +poll for new data, and "page" backward through matching event items. This is +discussed in more detail below. + +The server will set a sensible cap on the maximum `wait_time`, overriding +client-requested intervals longer than that. + +A successful reply from the `events` request corresponds to the following Go +types: + +```go +type EventReply struct { + // The items matching the request parameters, from newest + // to oldest, if any were available within the timeout. + Items []*EventItem `json:"items"` + + // This is true if there is at least one older matching item + // available in the log that was not returned. + More bool `json:"more"` + + // The cursor of the oldest item in the log at the time of this reply, + // or "" if the log is empty. + Oldest string `json:"oldest"` + + // The cursor of the newest item in the log at the time of this reply, + // or "" if the log is empty. + Newest string `json:"newest"` +} + +type EventItem struct { + // The cursor of this item. + Cursor string `json:"cursor"` + + // The encoded event data for this item. + // The type identifies the structure of the value. + Data struct { + Type string `json:"type"` + Value json.RawMessage `json:"value"` + } `json:"data"` +} +``` + +The `oldest` and `newest` fields of the reply report the cursors of the oldest +and newest items (of any kind) recorded in the event log at the time of the +reply, or are `""` if the log is empty. + +The `data` field contains the type-specific event datum. The datum carries any +ABCI events that may have been defined. + +> **Discussion point**: Based on [issue #7273][i7273], I did not include a +> separate field in the response for the ABCI events, since it duplicates data +> already stored elsewhere in the event data. + +The semantics of the reply are as follows: + +- If `items` is non-empty: + + - Items are ordered from newest to oldest. + + - If `more` is true, there is at least one additional, older item in the + event log that was not returned (in excess of `max_results`). + + In this case the client can fetch the next page by setting `before` in a + new request, to the cursor of the oldest item fetched (i.e., the last one + in `items`). + + - Otherwise (if `more` is false), all the matching results have been + reported (pagination is complete). + + - The first element of `items` identifies the newest item considered. + Subsequent poll requests can set `after` to this cursor to skip items + that were already retrieved. + +- If `items` is empty: + + - If the `before` was set in the request, there are no further eligible + items for this query in the log (pagination is complete). + + This is just a safety case; the client can detect this without issuing + another call by consulting the `more` field of the previous reply. + + - If the `before` was empty in the request, no eligible items were + available before the `wait_time` expired. The client may poll again to + wait for more event items. + +A client can store cursor values to detect data loss and to recover from +crashes and connectivity issues: + +- After a crash, the client requests events after the newest cursor it has + seen. If the reply indicates that cursor is no longer in range, the client + may (conservatively) conclude some event data may have been lost. + +- On the other hand, if it _is_ in range, the client can then page back through + the results that it missed, and then resume polling. As long as its recovery + cursor does not age out before it finishes, the client can be sure it has all + the relevant results. + +### Other Notes + +- The new API supports two general "modes" of operation: + + 1. In ordinary operation, clients will **long-poll** the head of the event + log for new events matching their criteria (by setting a `wait_time` and + no `before`). + + 2. If there are more events than the client requested, or if the client needs + to to read older events to recover from a stall or crash, clients will + **page** backward through the event log (by setting `before` and `after`). + +- While the new API requires explicit polling by the client, it makes better + use of the node's existing HTTP infrastructure (e.g., connection pools). + Moreover, the direct implementation is easier to use from standard tools and + client libraries for HTTP and JSON-RPC. + + Explicit polling does shift the burden of timeliness to the client. That is + arguably preferable, however, given that the RPC service is ancillary to the + node's primary goal, viz., consensus. The details of polling can be easily + hidden from client applications with simple libraries. + +- The format of a cursor is considered opaque to the client. Clients must not + parse cursor values, but they may rely on their ordering properties. + +- To maintain the event log, the server must prune items outside the time + window and in excess of the item limit. + + The initial implementation will do this by checking the tail of the event log + after each new item is published. If the number of items in the log exceeds + the item limit, it will delete oldest items until the log is under the limit; + then discard any older than the time window before the latest. + + To minimize coordination interference between the publisher (the event bus) + and the subcribers (the `events` service handlers), the event log will be + stored as a persistent linear queue with shared structure (a cons list). A + single reader-writer mutex will guard the "head" of the queue where new + items are published: + + - **To publish a new item**, the publisher acquires the write lock, conses a + new item to the front of the existing queue, and replaces the head pointer + with the new item. + + - **To scan the queue**, a reader acquires the read lock, captures the head + pointer, and then releases the lock. The rest of its request can be served + without holding a lock, since the queue structure will not change. + + When a reader wants to wait, it will yield the lock and wait on a condition + that is signaled when the publisher swings the pointer. + + - **To prune the queue**, the publisher (who is the sole writer) will track + the queue length and the age of the oldest item separately. When the + length and or age exceed the configured bounds, it will construct a new + queue spine on the same items, discarding out-of-band values. + + Pruning can be done while the publisher already holds the write lock, or + could be done outside the lock entirely: Once the new queue is constructed, + the lock can be re-acquired to swing the pointer. This costs some extra + allocations for the cons cells, but avoids duplicating any event items. + The pruning step is a simple linear scan down the first (up to) max-items + elements of the queue, to find the breakpoint of age and length. + + Moreover, the publisher can amortize the cost of pruning by item count, if + necessary, by pruning length "more aggressively" than the configuration + requires (e.g., reducing to 3/4 of the maximum rather than 1/1). + + The state of the event log before the publisher acquires the lock: + ![Before publish and pruning](./img/adr-075-log-before.png) + + After the publisher has added a new item and pruned old ones: + ![After publish and pruning](./img/adr-075-log-after.png) + +### Migration Plan + +This design requires that clients eventually migrate to the new event +subscription API, but provides a full release cycle with both APIs in place to +make this burden more tractable. The migration strategy is broadly: + +**Phase 1**: Release v0.36. + +- Implement the new `events` endpoint, keeping the existing methods as they are. +- Update the Go clients to support the new `events` endpoint, and handle polling. +- Update the old endpoints to log annoyingly about their own deprecation. +- Write tutorials about how to migrate client usage. + +At or shortly after release, we should proactively update the Cosmos SDK to use +the new API, to remove a disincentive to upgrading. + +**Phase 2**: Release v0.37 + +- During development, we should actively seek out any existing users of the + streaming event subscription API and help them migrate. +- Possibly also: Spend some time writing clients for JS, Rust, et al. +- Release: Delete the old implementation and all the websocket support code. + +> **Discussion point**: Even though the plan is to keep the existing service, +> we might take the opportunity to restrict the websocket endpoint to _only_ +> the event streaming service, removing the other endpoints. To minimize the +> disruption for users in the v0.36 cycle, I have decided not to do this for +> the first phase. +> +> If we wind up pushing this design into v0.37, however, we should re-evaulate +> this partial turn-down of the websocket. + +### Future Work + +- This design does not immediately address the problem of allowing the client + to control which data are reported back for event items. That concern is + deferred to future work. However, it would be straightforward to extend the + filter and/or the request parameters to allow more control. + +- The node currently stores a subset of event data (specifically the block and + transaction events) for use in reindexing. While these data are redundant + with the event log described in this document, they are not sufficient to + cover event subscription, as they omit other event types. + + In the future we should investigate consolidating or removing event data from + the state store entirely. For now this issue is out of scope for purposes of + updating the RPC API. We may be able to piggyback on the database unification + plans (see [RFC 001][rfc001]) to store the event log separately, so its + pruning policy does not need to be tied to the block and state stores. + +- This design reuses the existing filter query language from the old API. In + the future we may want to use a more structured and/or expressive query. The + Filter object can be extended with more fields as needed to support this. + +- Some users have trouble communicating with the RPC service because of + configuration problems like improperly-set CORS policies. While this design + does not address those issues directly, we might want to revisit how we set + policies in the RPC service to make it less susceptible to confusing errors + caused by misconfiguration. + +--- +## Consequences + +- ✅ Reduces the number of transport options for RPC. Supports [RFC 002][rfc002]. +- ️✅ Removes the primary non-standard use of JSON-RPC. +- ⛔️ Forces clients to migrate to a different API (eventually). +- ↕️ API requires clients to poll, but this reduces client state on the server. +- ↕️ We have to maintain both implementations for a whole release, but this + gives clients time to migrate. + +--- +## Alternative Approaches + +The following alternative approaches were considered: + +1. **Leave it alone.** Since existing tools mostly already work with the API as + it stands today, we could leave it alone and do our best to improve its + performance and reliability. + + Based on many issues reported by users and node operators (e.g., + [#3380][i3380], [#6439][i6439], [#6729][i6729], [#7247][i7247]), the + problems described here affect even the existing use that works. Investing + further incremental effort in the existing API is unlikely to address these + issues. + +2. **Design a better streaming API.** Instead of polling, we might try to + design a better "streaming" API for event subscription. + + A significant advantage of switching away from streaming is to remove the + need for persistent connections between the node and subscribers. A new + streaming protocol design would lose that advantage, and would still need a + way to let clients recover and replay. + + This approach might look better if we decided to use a different protocol + for event subscription, say gRPC instead of JSON-RPC. That choice, however, + would be just as breaking for existing clients, for marginal benefit. + Moreover, this option increases both the complexity and the resource cost on + the node implementation. + + Given that resource consumption and complexity are important considerations, + this option was not chosen. + +3. **Defer to an external event broker.** We might remove the entire event + subscription infrastructure from the node, and define an optional interface + to allow the node to publish all its events to an external event broker, + such as Apache Kafka. + + This has the advantage of greatly simplifying the node, but at a great cost + to the node operator: To enable event subscription in this design, the + operator has to stand up and maintain a separate process in communion with + the node, and configuration changes would have to be coordinated across + both. + + Moreover, this approach would be highly disruptive to existing client use, + and migration would probably require switching to third-party libraries. + Despite the potential benefits for the node itself, the costs to operators + and clients seems too large for this to be the best option. + + Publishing to an external event broker might be a worthwhile future project, + if there is any demand for it. That decision is out of scope for this design, + as it interacts with the design of the indexer as well. + +--- +## References + +- [RFC 006: Event Subscription][rfc006] +- [Tendermint RPC service][rpc-service] +- [Event query grammar][query-grammar] +- [RFC 6455: The WebSocket protocol][ws] +- [JSON-RPC 2.0 Specification][jsonrpc2] +- [Nginx proxy server][nginx] + - [Proxying websockets][rp-ws] + - [Extension modules][ng-xm] +- [FastCGI][fcgi] +- [RFC 001: Storage Engines & Database Layer][rfc001] +- [RFC 002: Interprocess Communication in Tendermint][rfc002] +- Issues: + - [rpc/client: test that client resubscribes upon disconnect][i3380] (#3380) + - [Too high memory usage when creating many events subscriptions][i6439] (#6439) + - [Tendermint emits events faster than clients can pull them][i6729] (#6729) + - [indexer: unbuffered event subscription slow down the consensus][i7247] (#7247) + - [rpc: remove duplication of events when querying][i7273] (#7273) + +[rfc006]: https://github.com/tendermint/tendermint/blob/main/docs/rfc/rfc-006-event-subscription.md +[rpc-service]: https://github.com/tendermint/tendermint/blob/main/rpc/openapi/openapi.yaml +[query-grammar]: https://pkg.go.dev/github.com/tendermint/tendermint@master/internal/pubsub/query/syntax +[ws]: https://datatracker.ietf.org/doc/html/rfc6455 +[jsonrpc2]: https://www.jsonrpc.org/specification +[nginx]: https://nginx.org/en/docs/ +[fcgi]: http://www.mit.edu/~yandros/doc/specs/fcgi-spec.html +[rp-ws]: https://nginx.org/en/docs/http/websocket.html + +[ng-xm]: https://www.nginx.com/resources/wiki/extending/ +[abci-event]: https://pkg.go.dev/github.com/tendermint/tendermint/abci/types#Event +[rfc001]: https://github.com/tendermint/tendermint/blob/main/docs/rfc/rfc-001-storage-engine.rst +[rfc002]: https://github.com/tendermint/tendermint/blob/main/docs/rfc/rfc-002-ipc-ecosystem.md +[i3380]: https://github.com/tendermint/tendermint/issues/3380 +[i6439]: https://github.com/tendermint/tendermint/issues/6439 +[i6729]: https://github.com/tendermint/tendermint/issues/6729 +[i7247]: https://github.com/tendermint/tendermint/issues/7247 +[i7273]: https://github.com/tendermint/tendermint/issues/7273 diff --git a/docs/architecture/tendermint-core/adr-076-combine-spec-repo.md b/docs/architecture/tendermint-core/adr-076-combine-spec-repo.md new file mode 100644 index 0000000..e5f2ed9 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-076-combine-spec-repo.md @@ -0,0 +1,112 @@ +# ADR 076: Combine Spec and Tendermint Repositories + +## Changelog + +- 2022-02-04: Initial Draft. (@tychoish) + +## Status + +Implemented + +## Context + +While the specification for Tendermint was originally in the same +repository as the Go implementation, at some point the specification +was split from the core repository and maintained separately from the +implementation. While this makes sense in promoting a conceptual +separation of specification and implementation, in practice this +separation was a premature optimization, apparently aimed at supporting +alternate implementations of Tendermint. + +The operational and documentary burden of maintaining a separate +spec repo has not returned value to justify its cost. There are no active +projects to develop alternate implementations of Tendermint based on the +common specification, and having separate repositories creates an ongoing +burden to coordinate versions, documentation, and releases. + +## Decision + +The specification repository will be merged back into the Tendermint +core repository. + +Stakeholders including representatives from the maintainers of the +spec, the Go implementation, and the Tendermint Rust library, agreed +to merge the repositories in the Tendermint core dev meeting on 27 +January 2022, including @williambanfield @cmwaters @creachadair and +@thanethomson. + +## Alternative Approaches + +The main alternative we considered was to keep separate repositories, +and to introduce a coordinated versioning scheme between the two, so +that users could figure out which spec versions go with which versions +of the core implementation. + +We decided against this on the grounds that it would further complicate +the release process for _both_ repositories, without mitigating any of +the other existing issues. + +## Detailed Design + +Clone and merge the master branch of the `tendermint/spec` repository +as a branch of the `tendermint/tendermint`, to ensure the commit history +of both repositories remains intact. + +### Implementation Instructions + +1. Within the `tendermint` repository, execute the following commands + to add a new branch with the history of the master branch of `spec`: + + ```bash + git remote add spec git@github.com:tendermint/spec.git + git fetch spec + git checkout -b spec-master spec/master + mkdir spec + git ls-tree -z --name-only HEAD | xargs -0 -I {} git mv {} subdir/ + git commit -m "spec: organize specification prior to merge" + git checkout -b spec-merge-mainline origin/master + git merge --allow-unrelated-histories spec-master + ``` + + This merges the spec into the `tendermint/tendermint` repository as + a normal branch. This commit can also be backported to the 0.35 + branch, if needed. + +2. Migrate outstanding issues from `tendermint/spec` to the + `tendermint/tendermint` repository. + +3. In the specification repository, add redirect to the README and mark + the repository as archived. + + +## Consequences + +### Positive + +Easier maintenance for the specification will obviate a number of +complicated and annoying versioning problems, and will help prevent the +possibility of the specification and the implementation drifting apart. + +Additionally, co-locating the specification will help encourage +cross-pollination and collaboration, between engineers focusing on the +specification and the protocol and engineers focusing on the implementation. + +### Negative + +Co-locating the spec and Go implementation has the potential effect of +prioritizing the Go implementation with regards to the spec, and +making it difficult to think about alternate implementations of the +Tendermint algorithm. Although we may want to foster additional +Tendermint implementations in the future, this isn't an active goal +in our current roadmap, and *not* merging these repos doesn't +change the fact that the Go implementation of Tendermint is already the +primary implementation. + +### Neutral + +N/A + +## References + +- https://github.com/tendermint/tendermint/tree/main/spec +- https://github.com/tendermint/tendermint diff --git a/docs/architecture/tendermint-core/adr-077-block-retention.md b/docs/architecture/tendermint-core/adr-077-block-retention.md new file mode 100644 index 0000000..d72def5 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-077-block-retention.md @@ -0,0 +1,109 @@ +# ADR 077: Configurable Block Retention + +## Changelog + +- 2020-03-23: Initial draft (@erikgrinaker) +- 2020-03-25: Use local config for snapshot interval (@erikgrinaker) +- 2020-03-31: Use ABCI commit response for block retention hint +- 2020-04-02: Resolved open questions +- 2021-02-11: Migrate to tendermint repo (Originally [RFC 001](https://github.com/tendermint/spec/pull/84)) + +## Author(s) + +- Erik Grinaker (@erikgrinaker) + +## Context + +Currently, all Tendermint nodes contain the complete sequence of blocks from genesis up to some height (typically the latest chain height). This will no longer be true when the following features are released: + +- [Block pruning](https://github.com/tendermint/tendermint/issues/3652): removes historical blocks and associated data (e.g. validator sets) up to some height, keeping only the most recent blocks. + +- [State sync](https://github.com/tendermint/tendermint/issues/828): bootstraps a new node by syncing state machine snapshots at a given height, but not historical blocks and associated data. + +To maintain the integrity of the chain, the use of these features must be coordinated such that necessary historical blocks will not become unavailable or lost forever. In particular: + +- Some nodes should have complete block histories, for auditability, querying, and bootstrapping. + +- The majority of nodes should retain blocks longer than the Cosmos SDK unbonding period, for light client verification. + +- Some nodes must take and serve state sync snapshots with snapshot intervals less than the block retention periods, to allow new nodes to state sync and then replay blocks to catch up. + +- Applications may not persist their state on commit, and require block replay on restart. + +- Only a minority of nodes can be state synced within the unbonding period, for light client verification and to serve block histories for catch-up. + +However, it is unclear if and how we should enforce this. It may not be possible to technically enforce all of these without knowing the state of the entire network, but it may also be unrealistic to expect this to be enforced entirely through social coordination. This is especially unfortunate since the consequences of misconfiguration can be permanent chain-wide data loss. + +## Proposal + +Add a new field `retain_height` to the ABCI `ResponseCommit` message: + +```proto +service ABCIApplication { + rpc Commit(RequestCommit) returns (ResponseCommit); +} + +message RequestCommit {} + +message ResponseCommit { + // reserve 1 + bytes data = 2; // the Merkle root hash + uint64 retain_height = 3; // the oldest block height to retain +} +``` + +Upon ABCI `Commit`, which finalizes execution of a block in the state machine, Tendermint removes all data for heights lower than `retain_height`. This allows the state machine to control block retention, which is preferable since only it can determine the significance of historical blocks. By default (i.e. with `retain_height=0`) all historical blocks are retained. + +Removed data includes not only blocks, but also headers, commit info, consensus params, validator sets, and so on. In the first iteration this will be done synchronously, since the number of heights removed for each run is assumed to be small (often 1) in the typical case. It can be made asynchronous at a later time if this is shown to be necessary. + +Since `retain_height` is dynamic, it is possible for it to refer to a height which has already been removed. For example, commit at height 100 may return `retain_height=90` while commit at height 101 may return `retain_height=80`. This is allowed, and will be ignored - it is the application's responsibility to return appropriate values. + +State sync will eventually support backfilling heights, via e.g. a snapshot metadata field `backfill_height`, but in the initial version it will have a fully truncated block history. + +## Cosmos SDK Example + +As an example, we'll consider how the Cosmos SDK might make use of this. The specific details should be discussed in a separate SDK proposal. + +The returned `retain_height` would be the lowest height that satisfies: + +- Unbonding time: the time interval in which validators can be economically punished for misbehavior. Blocks in this interval must be auditable e.g. by the light client. + +- IAVL snapshot interval: the block interval at which the underlying IAVL database is persisted to disk, e.g. every 10000 heights. Blocks since the last IAVL snapshot must be available for replay on application restart. + +- State sync snapshots: blocks since the _oldest_ available snapshot must be available for state sync nodes to catch up (oldest because a node may be restoring an old snapshot while a new snapshot was taken). + +- Local config: archive nodes may want to retain more or all blocks, e.g. via a local config option `min-retain-blocks`. There may also be a need to vary rentention for other nodes, e.g. sentry nodes which do not need historical blocks. + +![Cosmos SDK block retention diagram](img/block-retention.png) + +## Status + +Implemented + +## Consequences + +### Positive + +- Application-specified block retention allows the application to take all relevant factors into account and prevent necessary blocks from being accidentally removed. + +- Node operators can independently decide whether they want to provide complete block histories (if local configuration for this is provided) and snapshots. + +### Negative + +- Social coordination is required to run archival nodes, failure to do so may lead to permanent loss of historical blocks. + +- Social coordination is required to run snapshot nodes, failure to do so may lead to inability to run state sync, and inability to bootstrap new nodes at all if no archival nodes are online. + +### Neutral + +- Reduced block retention requires application changes, and cannot be controlled directly in Tendermint. + +- Application-specified block retention may set a lower bound on disk space requirements for all nodes. + +## References + +- State sync ADR: + +- State sync issue: + +- Block pruning issue: diff --git a/docs/architecture/tendermint-core/adr-078-nonzero-genesis.md b/docs/architecture/tendermint-core/adr-078-nonzero-genesis.md new file mode 100644 index 0000000..8c833fd --- /dev/null +++ b/docs/architecture/tendermint-core/adr-078-nonzero-genesis.md @@ -0,0 +1,82 @@ +# ADR 078: Non-Zero Genesis + +## Changelog + +- 2020-07-26: Initial draft (@erikgrinaker) +- 2020-07-28: Use weak chain linking, i.e. `predecessor` field (@erikgrinaker) +- 2020-07-31: Drop chain linking (@erikgrinaker) +- 2020-08-03: Add `State.InitialHeight` (@erikgrinaker) +- 2021-02-11: Migrate to tendermint repo (Originally [RFC 002](https://github.com/tendermint/spec/pull/119)) + +## Author(s) + +- Erik Grinaker (@erikgrinaker) + +## Context + +The recommended upgrade path for block protocol-breaking upgrades is currently to hard fork the +chain (see e.g. [`cosmoshub-3` upgrade](https://blog.cosmos.network/cosmos-hub-3-upgrade-announcement-39c9da941aee). +This is done by halting all validators at a predetermined height, exporting the application +state via application-specific tooling, and creating an entirely new chain using the exported +application state. + +As far as Tendermint is concerned, the upgraded chain is a completely separate chain, with e.g. +a new chain ID and genesis file. Notably, the new chain starts at height 1, and has none of the +old chain's block history. This causes problems for integrators, e.g. coin exchanges and +wallets, that assume a monotonically increasing height for a given blockchain. Users also find +it confusing that a given height can now refer to distinct states depending on the chain +version. + +An ideal solution would be to always retain block backwards compatibility in such a way that chain +history is never lost on upgrades. However, this may require a significant amount of engineering +work that is not viable for the planned Stargate release (Tendermint 0.34), and may prove too +restrictive for future development. + +As a first step, allowing the new chain to start from an initial height specified in the genesis +file would at least provide monotonically increasing heights. There was a proposal to include the +last block header of the previous chain as well, but since the genesis file is not verified and +hashed (only specific fields are) this would not be trustworthy. + +External tooling will be required to map historical heights onto e.g. archive nodes that contain +blocks from previous chain version. Tendermint will not include any such functionality. + +## Proposal + +Tendermint will allow chains to start from an arbitrary initial height: + +- A new field `initial_height` is added to the genesis file, defaulting to `1`. It can be set to any +non-negative integer, and `0` is considered equivalent to `1`. + +- A new field `InitialHeight` is added to the ABCI `RequestInitChain` message, with the same value +and semantics as the genesis field. + +- A new field `InitialHeight` is added to the `state.State` struct, where `0` is considered invalid. + Including the field here simplifies implementation, since the genesis value does not have to be + propagated throughout the code base separately, but it is not strictly necessary. + +ABCI applications may have to be updated to handle arbitrary initial heights, otherwise the initial +block may fail. + +## Status + +Implemented + +## Consequences + +### Positive + +- Heights can be unique throughout the history of a "logical" chain, across hard fork upgrades. + +### Negative + +- Upgrades still cause loss of block history. + +- Integrators will have to map height ranges to specific archive nodes/networks to query history. + +### Neutral + +- There is no explicit link to the last block of the previous chain. + +## References + +- [#2543: Allow genesis file to start from non-zero height w/ prev block header](https://github.com/tendermint/tendermint/issues/2543) diff --git a/docs/architecture/tendermint-core/adr-079-ed25519-verification.md b/docs/architecture/tendermint-core/adr-079-ed25519-verification.md new file mode 100644 index 0000000..a3b2e80 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-079-ed25519-verification.md @@ -0,0 +1,58 @@ +# ADR 079: Ed25519 Verification + +## Changelog + +- 2020-08-21: Initial RFC +- 2021-02-11: Migrate RFC to tendermint repo (Originally [RFC 003](https://github.com/tendermint/spec/pull/144)) + +## Author(s) + +- Marko (@marbar3778) + +## Context + +Ed25519 keys are the only supported key types for Tendermint validators currently. Tendermint-Go wraps the ed25519 key implementation from the go standard library. As more clients are implemented to communicate with the canonical Tendermint implementation (Tendermint-Go) different implementations of ed25519 will be used. Due to [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032.html) not guaranteeing implementation compatibility, Tendermint clients must to come to an agreement of how to guarantee implementation compatibility. [Zcash](https://z.cash/) has multiple implementations of their client and have identified this as a problem as well. The team at Zcash has made a proposal to address this issue, [Zcash improvement proposal 215](https://zips.z.cash/zip-0215). + +## Proposal + +- Tendermint-Go would adopt [hdevalence/ed25519consensus](https://github.com/hdevalence/ed25519consensus). + - This library is implements `ed25519.Verify()` in accordance to zip-215. Tendermint-go will continue to use `crypto/ed25519` for signing and key generation. + +- Tendermint-rs would adopt [ed25519-zebra](https://github.com/ZcashFoundation/ed25519-zebra) + - related [issue](https://github.com/informalsystems/tendermint-rs/issues/355) + +Signature verification is one of the major bottlenecks of Tendermint-go, batch verification can not be used unless it has the same consensus rules, ZIP 215 makes verification safe in consensus critical areas. + +This change constitutes a breaking changes, therefore must be done in a major release. No changes to validator keys or operations will be needed for this change to be enabled. + +This change has no impact on signature aggregation. To enable this signature aggregation Tendermint will have to use different signature schema (Schnorr, BLS, ...). Secondly, this change will enable safe batch verification for the Tendermint-Go client. Batch verification for the rust client is already supported in the library being used. + +As part of the acceptance of this proposal it would be best to contract or discuss with a third party the process of conducting a security review of the go library. + +## Status + +Accepted (implicitly tracked in +[\#9186](https://github.com/tendermint/tendermint/issues/9186)) + +## Consequences + +### Positive + +- Consistent signature verification across implementations +- Enable safe batch verification + +### Negative + +#### Tendermint-Go + +- Third_party dependency + - library has not gone through a security review. + - unclear maintenance schedule +- Fragmentation of the ed25519 key for the go implementation, verification is done using a third party library while the rest + uses the go standard library + +### Neutral + +## References + +[It’s 255:19AM. Do you know what your validation criteria are?](https://hdevalence.ca/blog/2020-10-04-its-25519am) diff --git a/docs/architecture/tendermint-core/adr-080-reverse-sync.md b/docs/architecture/tendermint-core/adr-080-reverse-sync.md new file mode 100644 index 0000000..df367b0 --- /dev/null +++ b/docs/architecture/tendermint-core/adr-080-reverse-sync.md @@ -0,0 +1,203 @@ +# ADR 080: ReverseSync - fetching historical data + +## Changelog + +- 2021-02-11: Migrate to tendermint repo (Originally [RFC 005](https://github.com/tendermint/spec/pull/224)) +- 2021-04-19: Use P2P to gossip necessary data for reverse sync. +- 2021-03-03: Simplify proposal to the state sync case. +- 2021-02-17: Add notes on asynchronicity of processes. +- 2020-12-10: Rename backfill blocks to reverse sync. +- 2020-11-25: Initial draft. + +## Author(s) + +- Callum Waters (@cmwaters) + +## Context + +Two new features: [Block pruning](https://github.com/tendermint/tendermint/issues/3652) +and [State sync](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-042-state-sync.md) +meant nodes no longer needed a complete history of the blockchain. This +introduced some challenges of its own which were covered and subsequently +tackled with [RFC-001](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-077-block-retention.md). +The RFC allowed applications to set a block retention height; an upper bound on +what blocks would be pruned. However nodes who state sync past this upper bound +(which is necessary as snapshots must be saved within the trusting period for +the assisting light client to verify) have no means of backfilling the blocks +to meet the retention limit. This could be a problem as nodes who state sync and +then eventually switch to consensus (or fast sync) may not have the block and +validator history to verify evidence causing them to panic if they see 2/3 +commit on what the node believes to be an invalid block. + +Thus, this RFC sets out to instil a minimum block history invariant amongst +honest nodes. + +## Proposal + +A backfill mechanism can simply be defined as an algorithm for fetching, +verifying and storing, headers and validator sets of a height prior to the +current base of the node's blockchain. In matching the terminology used for +other data retrieving protocols (i.e. fast sync and state sync), we +call this method **ReverseSync**. + +We will define the mechanism in four sections: + +- Usage +- Design +- Verification +- Termination + +### Usage + +For now, we focus purely on the case of a state syncing node, whom after +syncing to a height will need to verify historical data in order to be capable +of processing new blocks. We can denote the earliest height that the node will +need to verify and store in order to be able to verify any evidence that might +arise as the `max_historical_height`/`time`. Both height and time are necessary +as this maps to the BFT time used for evidence expiration. After acquiring +`State`, we calculate these parameters as: + +```go +max_historical_height = max(state.InitialHeight, state.LastBlockHeight - state.ConsensusParams.EvidenceAgeHeight) +max_historical_time = max(GenesisTime, state.LastBlockTime.Sub(state.ConsensusParams.EvidenceAgeTime)) +``` + +Before starting either fast sync or consensus, we then run the following +synchronous process: + +```go +func ReverseSync(max_historical_height int64, max_historical_time time.Time) error +``` + +Where we fetch and verify blocks until a block `A` where +`A.Height <= max_historical_height` and `A.Time <= max_historical_time`. + +Upon successfully reverse syncing, a node can now safely continue. As this +feature is only used as part of state sync, one can think of this as merely an +extension to it. + +In the future we may want to extend this functionality to allow nodes to fetch +historical blocks for reasons of accountability or data accessibility. + +### Design + +This section will provide a high level overview of some of the more important +characteristics of the design, saving the more tedious details as an ADR. + +#### P2P + +Implementation of this RFC will require the addition of a new channel and two +new messages. + +```proto +message LightBlockRequest { + uint64 height = 1; +} +``` + +```proto +message LightBlockResponse { + Header header = 1; + Commit commit = 2; + ValidatorSet validator_set = 3; +} +``` + +The P2P path may also enable P2P networked light clients and a state sync that +also doesn't need to rely on RPC. + +### Verification + +ReverseSync is used to fetch the following data structures: + +- `Header` +- `Commit` +- `ValidatorSet` + +Nodes will also need to be able to verify these. This can be achieved by first +retrieving the header at the base height from the block store. From this trusted +header, the node hashes each of the three data structures and checks that they are correct. + +1. The trusted header's last block ID matches the hash of the new header + + ```go + header[height].LastBlockID == hash(header[height-1]) + ``` + +2. The trusted header's last commit hash matches the hash of the new commit + + ```go + header[height].LastCommitHash == hash(commit[height-1]) + ``` + +3. Given that the node now trusts the new header, check that the header's validator set + hash matches the hash of the validator set + + ```go + header[height-1].ValidatorsHash == hash(validatorSet[height-1]) + ``` + +### Termination + +ReverseSync draws a lot of parallels with fast sync. An important consideration +for fast sync that also extends to ReverseSync is termination. ReverseSync will +finish it's task when one of the following conditions have been met: + +1. It reaches a block `A` where `A.Height <= max_historical_height` and +`A.Time <= max_historical_time`. +2. None of it's peers reports to have the block at the height below the +processes current block. +3. A global timeout. + +This implies that we can't guarantee adequate history and thus the term +"invariant" can't be used in the strictest sense. In the case that the first +condition isn't met, the node will log an error and optimistically attempt +to continue with either fast sync or consensus. + +## Alternative Solutions + +The need for a minimum block history invariant stems purely from the need to +validate evidence (although there may be some application relevant needs as +well). Because of this, an alternative, could be to simply trust whatever the +2/3+ majority has agreed upon and in the case where a node is at the head of the +blockchain, you simply abstain from voting. + +As it stands, if 2/3+ vote on evidence you can't verify, in the same manner if +2/3+ vote on a header that a node sees as invalid (perhaps due to a different +app hash), the node will halt. + +Another alternative is the method with which the relevant data is retrieved. +Instead of introducing new messages to the P2P layer, RPC could have been used +instead. + +The aforementioned data is already available via the following RPC endpoints: +`/commit` for `Header`'s' and `/validators` for `ValidatorSet`'s'. It was +decided predominantly due to the instability of the current RPC infrastructure +that P2P be used instead. + +## Status + +Proposed + +## Consequences + +### Positive + +- Ensures a minimum block history invariant for honest nodes. This will allow + nodes to verify evidence. + +### Negative + +- Statesync will be slower as more processing is required. + +### Neutral + +- By having validator sets served through p2p, this would make it easier to +extend p2p support to light clients and state sync. +- In the future, it may also be possible to extend this feature to allow for +nodes to freely fetch and verify prior blocks + +## References + +- [RFC-001: Block retention](https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-077-block-retention.md) +- [Original issue](https://github.com/tendermint/tendermint/issues/4629) diff --git a/docs/architecture/tendermint-core/adr-081-protobuf-mgmt.md b/docs/architecture/tendermint-core/adr-081-protobuf-mgmt.md new file mode 100644 index 0000000..2c5bf8e --- /dev/null +++ b/docs/architecture/tendermint-core/adr-081-protobuf-mgmt.md @@ -0,0 +1,201 @@ +# ADR 081: Protocol Buffers Management + +## Changelog + +- 2022-02-28: First draft + +## Status + +Accepted + +[Tracking issue](https://github.com/tendermint/tendermint/issues/8121) + +## Context + +At present, we manage the [Protocol Buffers] schema files ("protos") that define +our wire-level data formats within the Tendermint repository itself (see the +[`proto`](../../proto/) directory). Recently, we have been making use of [Buf], +both locally and in CI, in order to generate Go stubs, and lint and check +`.proto` files for breaking changes. + +The version of Buf used at the time of this decision was `v1beta1`, and it was +discussed in [\#7975] and in weekly calls as to whether we should upgrade to +`v1` and harmonize our approach with that used by the Cosmos SDK. The team +managing the Cosmos SDK was primarily interested in having our protos versioned +and easily accessible from the [Buf] registry. + +The three main sets of stakeholders for the `.proto` files and their needs, as +currently understood, are as follows. + +1. Tendermint needs Go code generated from `.proto` files. +2. Consumers of Tendermint's `.proto` files, specifically projects that want to + interoperate with Tendermint and need to generate code for their own + programming language, want to be able to access these files in a reliable and + efficient way. +3. The Tendermint Core team wants to provide stable interfaces that are as easy + as possible to maintain, on which consumers can depend, and to be able to + notify those consumers promptly when those interfaces change. To this end, we + want to: + 1. Prevent any breaking changes from being introduced in minor/patch releases + of Tendermint. Only major version updates should be able to contain + breaking interface changes. + 2. Prevent generated code from diverging from the Protobuf schema files. + +There was also discussion surrounding the notion of automated documentation +generation and hosting, but it is not clear at this time whether this would be +that valuable to any of our stakeholders. What will, of course, be valuable at +minimum would be better documentation (in comments) of the `.proto` files +themselves. + +## Alternative Approaches + +### Meeting stakeholders' needs + +1. Go stub generation from protos. We could use: + 1. [Buf]. This approach has been rather cumbersome up to this point, and it + is not clear what Buf really provides beyond that which `protoc` provides + to justify the additional complexity in configuring Buf for stub + generation. + 2. [protoc] - the Protocol Buffers compiler. +2. Notification of breaking changes: + 1. Buf in CI for all pull requests to *release* branches only (and not on + `master`). + 2. Buf in CI on every pull request to every branch (this was the case at the + time of this decision, and the team decided that the signal-to-noise ratio + for this approach was too low to be of value). +3. `.proto` linting: + 1. Buf in CI on every pull request +4. `.proto` formatting: + 1. [clang-format] locally and a [clang-format GitHub Action] in CI to check + that files are formatted properly on every pull request. +5. Sharing of `.proto` files in a versioned, reliable manner: + 1. Consumers could simply clone the Tendermint repository, check out a + specific commit, tag or branch and manually copy out all of the `.proto` + files they need. This requires no effort from the Tendermint Core team and + will continue to be an option for consumers. The drawback of this approach + is that it requires manual coding/scripting to implement and is brittle in + the face of bigger changes. + 2. Uploading our `.proto` files to Buf's registry on every release. This is + by far the most seamless for consumers of our `.proto` files, but requires + the dependency on Buf. This has the additional benefit that the Buf + registry will automatically [generate and host + documentation][buf-docs-gen] for these protos. + 3. We could create a process that, upon release, creates a `.zip` file + containing our `.proto` files. + +### Popular alternatives to Buf + +[Prototool] was not considered as it appears deprecated, and the ecosystem seems +to be converging on Buf at this time. + +### Tooling complexity + +The more tools we have in our build/CI processes, the more complex and fragile +repository/CI management becomes, and the longer it takes to onboard new team +members. Maintainability is a core concern here. + +### Buf sustainability and costs + +One of the primary considerations regarding the usage of Buf is whether, for +example, access to its registry will eventually become a +paid-for/subscription-based service and whether this is valuable enough for us +and the ecosystem to pay for such a service. At this time, it appears as though +Buf will never charge for hosting open source projects' protos. + +Another consideration was Buf's sustainability as a project - what happens when +their resources run out? Will there be a strong and broad enough open source +community to continue maintaining it? + +### Local Buf usage options + +Local usage of Buf (i.e. not in CI) can be accomplished in two ways: + +1. Installing the relevant tools individually. +2. By way of its [Docker image][buf-docker]. + +Local installation of Buf requires developers to manually keep their toolchains +up-to-date. The Docker option comes with a number of complexities, including +how the file system permissions of code generated by a Docker container differ +between platforms (e.g. on Linux, Buf-generated code ends up being owned by +`root`). + +The trouble with the Docker-based approach is that we make use of the +[gogoprotobuf] plugin for `protoc`. Continuing to use the Docker-based approach +to using Buf will mean that we will have to continue building our own custom +Docker image with embedded gogoprotobuf. + +Along these lines, we could eventually consider coming up with a [Nix]- or +[redo]-based approach to developer tooling to ensure tooling consistency across +the team and for anyone who wants to be able to contribute to Tendermint. + +## Decision + +1. We will adopt Buf for now for proto generation, linting, breakage checking + and its registry (mainly in CI, with optional usage locally). +2. Failing CI when checking for breaking changes in `.proto` files will only + happen when performing minor/patch releases. +3. Local tooling will be favored over Docker-based tooling. + +## Detailed Design + +We currently aim to: + +1. Update to Buf `v1` to facilitate linting, breakage checking and uploading to + the Buf registry. +2. Configure CI appropriately for proto management: + 1. Uploading protos to the Buf registry on every release (e.g. the + [approach][cosmos-sdk-buf-registry-ci] used by the Cosmos SDK). + 2. Linting on every pull request (e.g. the + [approach][cosmos-sdk-buf-linting-ci] used by the Cosmos SDK). The linter + passing should be considered a requirement for accepting PRs. + 3. Checking for breaking changes in minor/patch version releases and failing + CI accordingly - see [\#8003]. + 4. Add [clang-format GitHub Action] to check `.proto` file formatting. Format + checking should be considered a requirement for accepting PRs. +3. Update the Tendermint [`Makefile`](../../Makefile) to primarily facilitate + local Protobuf stub generation, linting, formatting and breaking change + checking. More specifically: + 1. This includes removing the dependency on Docker and introducing the + dependency on local toolchain installation. CI-based equivalents, where + relevant, will rely on specific GitHub Actions instead of the Makefile. + 2. Go code generation will rely on `protoc` directly. + +## Consequences + +### Positive + +- We will still offer Go stub generation, proto linting and breakage checking. +- Breakage checking will only happen on minor/patch releases to increase the + signal-to-noise ratio in CI. +- Versioned protos will be made available via Buf's registry upon every release. + +### Negative + +- Developers/contributors will need to install the relevant Protocol + Buffers-related tooling (Buf, gogoprotobuf, clang-format) locally in order to + build, lint, format and check `.proto` files for breaking changes. + +### Neutral + +## References + +- [Protocol Buffers] +- [Buf] +- [\#7975] +- [protoc] - The Protocol Buffers compiler + +[Protocol Buffers]: https://developers.google.com/protocol-buffers +[Buf]: https://buf.build/ +[\#7975]: https://github.com/tendermint/tendermint/pull/7975 +[protoc]: https://github.com/protocolbuffers/protobuf +[clang-format]: https://clang.llvm.org/docs/ClangFormat.html +[clang-format GitHub Action]: https://github.com/marketplace/actions/clang-format-github-action +[buf-docker]: https://hub.docker.com/r/bufbuild/buf +[cosmos-sdk-buf-registry-ci]: https://github.com/cosmos/cosmos-sdk/blob/e6571906043b6751951a42b6546431b1c38b05bd/.github/workflows/proto-registry.yml +[cosmos-sdk-buf-linting-ci]: https://github.com/cosmos/cosmos-sdk/blob/e6571906043b6751951a42b6546431b1c38b05bd/.github/workflows/proto.yml#L15 +[\#8003]: https://github.com/tendermint/tendermint/issues/8003 +[Nix]: https://nixos.org/ +[gogoprotobuf]: https://github.com/cosmos/gogoproto +[Prototool]: https://github.com/uber/prototool +[buf-docs-gen]: https://docs.buf.build/bsr/documentation +[redo]: https://redo.readthedocs.io/en/latest/ diff --git a/docs/architecture/tendermint-core/img/adr-046-fig1.png b/docs/architecture/tendermint-core/img/adr-046-fig1.png new file mode 100644 index 0000000..add579b Binary files /dev/null and b/docs/architecture/tendermint-core/img/adr-046-fig1.png differ diff --git a/docs/architecture/tendermint-core/img/adr-062-architecture.svg b/docs/architecture/tendermint-core/img/adr-062-architecture.svg new file mode 100644 index 0000000..0addc90 --- /dev/null +++ b/docs/architecture/tendermint-core/img/adr-062-architecture.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/architecture/tendermint-core/img/adr-075-log-after.png b/docs/architecture/tendermint-core/img/adr-075-log-after.png new file mode 100644 index 0000000..b47fa4f Binary files /dev/null and b/docs/architecture/tendermint-core/img/adr-075-log-after.png differ diff --git a/docs/architecture/tendermint-core/img/adr-075-log-before.png b/docs/architecture/tendermint-core/img/adr-075-log-before.png new file mode 100644 index 0000000..f5a9691 Binary files /dev/null and b/docs/architecture/tendermint-core/img/adr-075-log-before.png differ diff --git a/docs/architecture/tendermint-core/img/bc-reactor-refactor.png b/docs/architecture/tendermint-core/img/bc-reactor-refactor.png new file mode 100644 index 0000000..4197f12 Binary files /dev/null and b/docs/architecture/tendermint-core/img/bc-reactor-refactor.png differ diff --git a/docs/architecture/tendermint-core/img/bc-reactor.png b/docs/architecture/tendermint-core/img/bc-reactor.png new file mode 100644 index 0000000..e1e42f4 Binary files /dev/null and b/docs/architecture/tendermint-core/img/bc-reactor.png differ diff --git a/docs/architecture/tendermint-core/img/bifurcation-point.png b/docs/architecture/tendermint-core/img/bifurcation-point.png new file mode 100644 index 0000000..fae7404 Binary files /dev/null and b/docs/architecture/tendermint-core/img/bifurcation-point.png differ diff --git a/docs/architecture/tendermint-core/img/block-retention.png b/docs/architecture/tendermint-core/img/block-retention.png new file mode 100644 index 0000000..7fdb545 Binary files /dev/null and b/docs/architecture/tendermint-core/img/block-retention.png differ diff --git a/docs/architecture/tendermint-core/img/blockchain-reactor-v1.png b/docs/architecture/tendermint-core/img/blockchain-reactor-v1.png new file mode 100644 index 0000000..a0da1f4 Binary files /dev/null and b/docs/architecture/tendermint-core/img/blockchain-reactor-v1.png differ diff --git a/docs/architecture/tendermint-core/img/blockchain-reactor-v2.png b/docs/architecture/tendermint-core/img/blockchain-reactor-v2.png new file mode 100644 index 0000000..6162add Binary files /dev/null and b/docs/architecture/tendermint-core/img/blockchain-reactor-v2.png differ diff --git a/docs/architecture/tendermint-core/img/blockchain-v2-channels.png b/docs/architecture/tendermint-core/img/blockchain-v2-channels.png new file mode 100644 index 0000000..9fd6f0f Binary files /dev/null and b/docs/architecture/tendermint-core/img/blockchain-v2-channels.png differ diff --git a/docs/architecture/tendermint-core/img/consensus_blockchain.png b/docs/architecture/tendermint-core/img/consensus_blockchain.png new file mode 100644 index 0000000..bcd6db7 Binary files /dev/null and b/docs/architecture/tendermint-core/img/consensus_blockchain.png differ diff --git a/docs/architecture/tendermint-core/img/evidence_lifecycle.png b/docs/architecture/tendermint-core/img/evidence_lifecycle.png new file mode 100644 index 0000000..013584c Binary files /dev/null and b/docs/architecture/tendermint-core/img/evidence_lifecycle.png differ diff --git a/docs/architecture/tendermint-core/img/formula1.png b/docs/architecture/tendermint-core/img/formula1.png new file mode 100644 index 0000000..fda8634 Binary files /dev/null and b/docs/architecture/tendermint-core/img/formula1.png differ diff --git a/docs/architecture/tendermint-core/img/formula2.png b/docs/architecture/tendermint-core/img/formula2.png new file mode 100644 index 0000000..f9cef31 Binary files /dev/null and b/docs/architecture/tendermint-core/img/formula2.png differ diff --git a/docs/architecture/tendermint-core/img/light-client-detector.png b/docs/architecture/tendermint-core/img/light-client-detector.png new file mode 100644 index 0000000..142586b Binary files /dev/null and b/docs/architecture/tendermint-core/img/light-client-detector.png differ diff --git a/docs/architecture/tendermint-core/img/mempool-v0.jpeg b/docs/architecture/tendermint-core/img/mempool-v0.jpeg new file mode 100644 index 0000000..2c98c57 Binary files /dev/null and b/docs/architecture/tendermint-core/img/mempool-v0.jpeg differ diff --git a/docs/architecture/tendermint-core/img/pbts-message.png b/docs/architecture/tendermint-core/img/pbts-message.png new file mode 100644 index 0000000..07f3f09 Binary files /dev/null and b/docs/architecture/tendermint-core/img/pbts-message.png differ diff --git a/docs/architecture/tendermint-core/img/state-sync.png b/docs/architecture/tendermint-core/img/state-sync.png new file mode 100644 index 0000000..f0fdb27 Binary files /dev/null and b/docs/architecture/tendermint-core/img/state-sync.png differ diff --git a/docs/architecture/tendermint-core/img/tags1.png b/docs/architecture/tendermint-core/img/tags1.png new file mode 100644 index 0000000..1b48e48 Binary files /dev/null and b/docs/architecture/tendermint-core/img/tags1.png differ diff --git a/docs/architecture/tendermint-core/img/tm-amnesia-attack.png b/docs/architecture/tendermint-core/img/tm-amnesia-attack.png new file mode 100644 index 0000000..3268d44 Binary files /dev/null and b/docs/architecture/tendermint-core/img/tm-amnesia-attack.png differ diff --git a/docs/core/README.md b/docs/core/README.md new file mode 100644 index 0000000..c96163c --- /dev/null +++ b/docs/core/README.md @@ -0,0 +1,23 @@ +--- +order: 1 +parent: + title: Core + order: 4 +--- + +# Overview + +This section dives into the internals of the CometBFT's implementation. + +- [Using CometBFT](./using-cometbft.md) +- [Configuration](./configuration.md) +- [Running in Production](./running-in-production.md) +- [Metrics](./metrics.md) +- [Validators](./validators.md) +- [Subscribing to events](./subscription.md) +- [Block Structure](./block-structure.md) +- [RPC](./rpc.md) +- [Block Sync](./block-sync.md) +- [State Sync](./state-sync.md) +- [Mempool](./mempool.md) +- [Light Client](./light-client.md) diff --git a/docs/core/block-structure.md b/docs/core/block-structure.md new file mode 100644 index 0000000..ef30e78 --- /dev/null +++ b/docs/core/block-structure.md @@ -0,0 +1,19 @@ +--- +order: 8 +--- + +# Block Structure + +The CometBFT consensus engine records all agreements by a 2/3+ of nodes +into a blockchain, which is replicated among all nodes. This blockchain is +accessible via various RPC endpoints, mainly `/block?height=` to get the full +block, as well as `/blockchain?minHeight=_&maxHeight=_` to get a list of +headers. But what exactly is stored in these blocks? + +The [specification][data_structures] contains a detailed description of each +component - that's the best place to get started. + +To dig deeper, check out the [types package documentation][types]. + +[data_structures]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/data_structures.md +[types]: https://pkg.go.dev/github.com/cometbft/cometbft/types diff --git a/docs/core/block-sync.md b/docs/core/block-sync.md new file mode 100644 index 0000000..bd3369d --- /dev/null +++ b/docs/core/block-sync.md @@ -0,0 +1,49 @@ +--- +order: 10 +--- + +# Block Sync + +*Formerly known as Fast Sync* + +In a proof of work blockchain, syncing with the chain is the same +process as staying up-to-date with the consensus: download blocks, and +look for the one with the most total work. In proof-of-stake, the +consensus process is more complex, as it involves rounds of +communication between the nodes to determine what block should be +committed next. Using this process to sync up with the blockchain from +scratch can take a very long time. It's much faster to just download +blocks and check the merkle tree of validators than to run the real-time +consensus gossip protocol. + +## Using Block Sync + +When starting from scratch, nodes will use the Block Sync mode. +In this mode, the CometBFT daemon +will sync hundreds of times faster than if it used the real-time consensus +process. Once caught up, the daemon will switch out of Block Sync and into the +normal consensus mode. After running for some time, the node is considered +`caught up` if it has at least one peer and its height is at least as high as +the max reported peer height. See [the IsCaughtUp +method](https://github.com/cometbft/cometbft/blob/v0.38.x/blocksync/pool.go#L168). + +Note: While there have historically been multiple versions of blocksync, v0, v1, and v2, all versions +other than v0 have been deprecated in favor of the simplest and most well understood algorithm. + +```toml +####################################################### +### Block Sync Configuration Options ### +####################################################### +[blocksync] + +# Block Sync version to use: +# +# In v0.37, v1 and v2 of the block sync protocols were deprecated. +# Please use v0 instead. +# +# 1) "v0" - the default block sync implementation +version = "v0" +``` + +If we're lagging sufficiently, we should go back to block syncing, but +this is an [open issue](https://github.com/tendermint/tendermint/issues/129). diff --git a/docs/core/configuration.md b/docs/core/configuration.md new file mode 100644 index 0000000..457cacf --- /dev/null +++ b/docs/core/configuration.md @@ -0,0 +1,623 @@ +--- +order: 3 +--- + +# Configuration + +CometBFT can be configured via a TOML file in +`$CMTHOME/config/config.toml`. Some of these parameters can be overridden by +command-line flags. For most users, the options in the `##### main base configuration options #####` are intended to be modified while config options +further below are intended for advance power users. + +## Options + +The default configuration file create by `cometbft init` has all +the parameters set with their default values. It will look something +like the file below, however, double check by inspecting the +`config.toml` created with your version of `cometbft` installed: + +```toml +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +# NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or +# relative to the home directory (e.g. "data"). The home directory is +# "$HOME/.cometbft" by default, but could be changed via $CMTHOME env variable +# or --home cmd flag. + +# The version of the CometBFT binary that created or +# last modified the config file. Do not modify this. +version = "0.38.0" + +####################################################################### +### Main Base Config Options ### +####################################################################### + +# TCP or UNIX socket address of the ABCI application, +# or the name of an ABCI application compiled in with the CometBFT binary +proxy_app = "tcp://127.0.0.1:26658" + +# A custom human readable name for this node +moniker = "anonymous" + +# Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb +# * goleveldb (github.com/syndtr/goleveldb) +# - UNMAINTAINED +# - stable +# - pure go +# - stable +# * cleveldb (uses levigo wrapper) +# - fast +# - requires gcc +# - use cleveldb build tag (go build -tags cleveldb) +# * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) +# - EXPERIMENTAL +# - may be faster is some use-cases (random reads - indexer) +# - use boltdb build tag (go build -tags boltdb) +# * rocksdb (uses github.com/tecbot/gorocksdb) +# - EXPERIMENTAL +# - requires gcc +# - use rocksdb build tag (go build -tags rocksdb) +# * badgerdb (uses github.com/dgraph-io/badger) +# - EXPERIMENTAL +# - use badgerdb build tag (go build -tags badgerdb) +db_backend = "goleveldb" + +# Database directory +db_dir = "data" + +# Output level for logging, including package level options +log_level = "info" + +# Output format: 'plain' (colored text) or 'json' +log_format = "plain" + +##### additional base config options ##### + +# Path to the JSON file containing the initial validator set and other meta data +genesis_file = "config/genesis.json" + +# Path to the JSON file containing the private key to use as a validator in the consensus protocol +priv_validator_key_file = "config/priv_validator_key.json" + +# Path to the JSON file containing the last sign state of a validator +priv_validator_state_file = "data/priv_validator_state.json" + +# TCP or UNIX socket address for CometBFT to listen on for +# connections from an external PrivValidator process +priv_validator_laddr = "" + +# Path to the JSON file containing the private key to use for node authentication in the p2p protocol +node_key_file = "config/node_key.json" + +# Mechanism to connect to the ABCI application: socket | grpc +abci = "socket" + +# If true, query the ABCI app on connecting to a new peer +# so the app can decide if we should keep the connection or not +filter_peers = false + + +####################################################################### +### Advanced Configuration Options ### +####################################################################### + +####################################################### +### RPC Server Configuration Options ### +####################################################### +[rpc] + +# TCP or UNIX socket address for the RPC server to listen on +laddr = "tcp://127.0.0.1:26657" + +# A list of origins a cross-domain request can be executed from +# Default value '[]' disables cors support +# Use '["*"]' to allow any origin +cors_allowed_origins = [] + +# A list of methods the client is allowed to use with cross-domain requests +cors_allowed_methods = ["HEAD", "GET", "POST", ] + +# A list of non simple headers the client is allowed to use with cross-domain requests +cors_allowed_headers = ["Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time", ] + +# TCP or UNIX socket address for the gRPC server to listen on +# NOTE: This server only supports /broadcast_tx_commit +grpc_laddr = "" + +# Maximum number of simultaneous connections. +# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +grpc_max_open_connections = 900 + +# Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool +unsafe = false + +# Maximum number of simultaneous connections (including WebSocket). +# Does not include gRPC connections. See grpc_max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +max_open_connections = 900 + +# Maximum number of unique clientIDs that can /subscribe +# If you're using /broadcast_tx_commit, set to the estimated maximum number +# of broadcast_tx_commit calls per block. +max_subscription_clients = 100 + +# Maximum number of unique queries a given client can /subscribe to +# If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to +# the estimated # maximum number of broadcast_tx_commit calls per block. +max_subscriptions_per_client = 5 + +# Experimental parameter to specify the maximum number of events a node will +# buffer, per subscription, before returning an error and closing the +# subscription. Must be set to at least 100, but higher values will accommodate +# higher event throughput rates (and will use more memory). +experimental_subscription_buffer_size = 200 + +# Experimental parameter to specify the maximum number of RPC responses that +# can be buffered per WebSocket client. If clients cannot read from the +# WebSocket endpoint fast enough, they will be disconnected, so increasing this +# parameter may reduce the chances of them being disconnected (but will cause +# the node to use more memory). +# +# Must be at least the same as "experimental_subscription_buffer_size", +# otherwise connections could be dropped unnecessarily. This value should +# ideally be somewhat higher than "experimental_subscription_buffer_size" to +# accommodate non-subscription-related RPC responses. +experimental_websocket_write_buffer_size = 200 + +# If a WebSocket client cannot read fast enough, at present we may +# silently drop events instead of generating an error or disconnecting the +# client. +# +# Enabling this experimental parameter will cause the WebSocket connection to +# be closed instead if it cannot read fast enough, allowing for greater +# predictability in subscription behavior. +experimental_close_on_slow_client = false + +# How long to wait for a tx to be committed during /broadcast_tx_commit. +# WARNING: Using a value larger than 10s will result in increasing the +# global HTTP write timeout, which applies to all connections and endpoints. +# See https://github.com/tendermint/tendermint/issues/3435 +timeout_broadcast_tx_commit = "10s" + +# Maximum number of requests that can be sent in a JSON-RPC batch request. +# Possible values: number greater than 0. +# If the number of requests sent in a JSON-RPC batch exceed the maximum batch +# size configured, an error will be returned. +# The default value is set to `10`, which will limit the number of requests +# to 10 requests per a JSON-RPC batch request. +# If you don't want to enforce a maximum number of requests for a batch +# request set this value to `0`. +max_request_batch_size = 10 + +# Maximum size of request body, in bytes +max_body_bytes = 1000000 + +# Maximum size of request header, in bytes +max_header_bytes = 1048576 + +# The path to a file containing certificate that is used to create the HTTPS server. +# Might be either absolute path or path related to CometBFT's config directory. +# If the certificate is signed by a certificate authority, +# the certFile should be the concatenation of the server's certificate, any intermediates, +# and the CA's certificate. +# NOTE: both tls_cert_file and tls_key_file must be present for CometBFT to create HTTPS server. +# Otherwise, HTTP server is run. +tls_cert_file = "" + +# The path to a file containing matching private key that is used to create the HTTPS server. +# Might be either absolute path or path related to CometBFT's config directory. +# NOTE: both tls-cert-file and tls-key-file must be present for CometBFT to create HTTPS server. +# Otherwise, HTTP server is run. +tls_key_file = "" + +# pprof listen address (https://golang.org/pkg/net/http/pprof) +pprof_laddr = "" + +####################################################### +### P2P Configuration Options ### +####################################################### +[p2p] + +# Address to listen for incoming connections +laddr = "tcp://0.0.0.0:26656" + +# Address to advertise to peers for them to dial. If empty, will use the same +# port as the laddr, and will introspect on the listener to figure out the +# address. IP and port are required. Example: 159.89.10.97:26656 +external_address = "" + +# Comma separated list of seed nodes to connect to +seeds = "" + +# Comma separated list of nodes to keep persistent connections to +persistent_peers = "" + +# Path to address book +addr_book_file = "config/addrbook.json" + +# Set true for strict address routability rules +# Set false for private or local networks +addr_book_strict = true + +# Maximum number of inbound peers +max_num_inbound_peers = 40 + +# Maximum number of outbound peers to connect to, excluding persistent peers +max_num_outbound_peers = 10 + +# List of node IDs, to which a connection will be (re)established ignoring any existing limits +unconditional_peer_ids = "" + +# Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) +persistent_peers_max_dial_period = "0s" + +# Time to wait before flushing messages out on the connection +flush_throttle_timeout = "100ms" + +# Maximum size of a message packet payload, in bytes +max_packet_msg_payload_size = 1024 + +# Rate at which packets can be sent, in bytes/second +send_rate = 5120000 + +# Rate at which packets can be received, in bytes/second +recv_rate = 5120000 + +# Set true to enable the peer-exchange reactor +pex = true + +# Seed mode, in which node constantly crawls the network and looks for +# peers. If another node asks it for addresses, it responds and disconnects. +# +# Does not work if the peer-exchange reactor is disabled. +seed_mode = false + +# Comma separated list of peer IDs to keep private (will not be gossiped to other peers) +private_peer_ids = "" + +# Toggle to disable guard against peers connecting from the same ip. +allow_duplicate_ip = false + +# Peer connection configuration. +handshake_timeout = "20s" +dial_timeout = "3s" + +####################################################### +### Mempool Configuration Option ### +####################################################### +[mempool] + +# The type of mempool for this node to use. +# +# Possible types: +# - "flood" : concurrent linked list mempool with flooding gossip protocol +# (default) +# - "nop" : nop-mempool (short for no operation; the ABCI app is responsible +# for storing, disseminating and proposing txs). "create_empty_blocks=false" is +# not supported. +type = "flood" + +# Recheck (default: true) defines whether CometBFT should recheck the +# validity for all remaining transaction in the mempool after a block. +# Since a block affects the application state, some transactions in the +# mempool may become invalid. If this does not apply to your application, +# you can disable rechecking. +recheck = true + +# Broadcast (default: true) defines whether the mempool should relay +# transactions to other peers. Setting this to false will stop the mempool +# from relaying transactions to other peers until they are included in a +# block. In other words, if Broadcast is disabled, only the peer you send +# the tx to will see it until it is included in a block. +broadcast = true + +# WalPath (default: "") configures the location of the Write Ahead Log +# (WAL) for the mempool. The WAL is disabled by default. To enable, set +# wal_dir to where you want the WAL to be written (e.g. +# "data/mempool.wal"). +wal_dir = "" + +# Maximum number of transactions in the mempool +size = 5000 + +# Limit the total size of all txs in the mempool. +# This only accounts for raw transactions (e.g. given 1MB transactions and +# max_txs_bytes=5MB, mempool will only accept 5 transactions). +max_txs_bytes = 1073741824 + +# Size of the cache (used to filter transactions we saw earlier) in transactions +cache_size = 10000 + +# Do not remove invalid transactions from the cache (default: false) +# Set to true if it's not possible for any invalid transaction to become valid +# again in the future. +keep-invalid-txs-in-cache = false + +# Maximum size of a single transaction. +# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. +max_tx_bytes = 1048576 + +# Maximum size of a batch of transactions to send to a peer +# Including space needed by encoding (one varint per transaction). +# XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 +max_batch_bytes = 0 + +####################################################### +### State Sync Configuration Options ### +####################################################### +[statesync] +# State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine +# snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in +# the network to take and serve state machine snapshots. State sync is not attempted if the node +# has any local state (LastBlockHeight > 0). The node will have a truncated block history, +# starting from the height of the snapshot. +enable = false + +# RPC servers (comma-separated) for light client verification of the synced state machine and +# retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding +# header hash obtained from a trusted source, and a period during which validators can be trusted. +# +# For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 +# weeks) during which they can be financially punished (slashed) for misbehavior. +rpc_servers = "" +trust_height = 0 +trust_hash = "" +trust_period = "168h0m0s" + +# Time to spend discovering snapshots before initiating a restore. +discovery_time = "15s" + +# Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). +# Will create a new, randomly named directory within, and remove it when done. +temp_dir = "" + +# The timeout duration before re-requesting a chunk, possibly from a different +# peer (default: 1 minute). +chunk_request_timeout = "10s" + +# The number of concurrent chunk fetchers to run (default: 1). +chunk_fetchers = "4" + +# Maximum number of chunks allowed in a snapshot (default: 100000). +max_snapshot_chunks = 100000 + +####################################################### +### Block Sync Configuration Options ### +####################################################### +[blocksync] + +# Block Sync version to use: +# +# In v0.37, v1 and v2 of the block sync protocols were deprecated. +# Please use v0 instead. +# +# 1) "v0" - the default block sync implementation +version = "v0" + +####################################################### +### Consensus Configuration Options ### +####################################################### +[consensus] + +wal_file = "data/cs.wal/wal" + +# How long we wait for a proposal block before prevoting nil +timeout_propose = "3s" +# How much timeout_propose increases with each round +timeout_propose_delta = "500ms" +# How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) +timeout_prevote = "1s" +# How much the timeout_prevote increases with each round +timeout_prevote_delta = "500ms" +# How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) +timeout_precommit = "1s" +# How much the timeout_precommit increases with each round +timeout_precommit_delta = "500ms" +# How long we wait after committing a block, before starting on the new +# height (this gives us a chance to receive some more precommits, even +# though we already have +2/3). +timeout_commit = "1s" + +# How many blocks to look back to check existence of the node's consensus votes before joining consensus +# When non-zero, the node will panic upon restart +# if the same consensus key was used to sign {double_sign_check_height} last blocks. +# So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. +double_sign_check_height = 0 + +# Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) +skip_timeout_commit = false + +# EmptyBlocks mode and possible interval between empty blocks +create_empty_blocks = true +create_empty_blocks_interval = "0s" + +# Reactor sleep duration parameters +peer_gossip_sleep_duration = "100ms" +peer_query_maj23_sleep_duration = "2s" + +####################################################### +### Storage Configuration Options ### +####################################################### +[storage] + +# Set to true to discard ABCI responses from the state store, which can save a +# considerable amount of disk space. Set to false to ensure ABCI responses are +# persisted. ABCI responses are required for /block_results RPC queries, and to +# reindex events in the command-line tool. +discard_abci_responses = false + +####################################################### +### Transaction Indexer Configuration Options ### +####################################################### +[tx_index] + +# What indexer to use for transactions +# +# The application will set which txs to index. In some cases a node operator will be able +# to decide which txs to index based on configuration set in the application. +# +# Options: +# 1) "null" +# 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). +# - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. +# 3) "psql" - the indexer services backed by PostgreSQL. +# When "kv" or "psql" is chosen "tx.height" and "tx.hash" will always be indexed. +indexer = "kv" + +# The PostgreSQL connection configuration, the connection format: +# postgresql://:@:/? +psql-conn = "" + +####################################################### +### Instrumentation Configuration Options ### +####################################################### +[instrumentation] + +# When true, Prometheus metrics are served under /metrics on +# PrometheusListenAddr. +# Check out the documentation for the list of available metrics. +prometheus = false + +# Address to listen for Prometheus collector(s) connections +prometheus_listen_addr = ":26660" + +# Maximum number of simultaneous connections. +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = 3 + +# Instrumentation namespace +namespace = "cometbft" + + ``` + +## Empty blocks VS no empty blocks + +### create_empty_blocks = true + +If `create_empty_blocks` is set to `true` in your config, blocks will be created ~ every second (with default consensus parameters). You can regulate the delay between blocks by changing the `timeout_commit`. E.g. `timeout_commit = "10s"` should result in ~ 10 second blocks. + +### create_empty_blocks = false + +In this setting, blocks are created when transactions received. + +Note after the block H, CometBFT creates something we call a "proof block" (only if the application hash changed) H+1. The reason for this is to support proofs. If you have a transaction in block H that changes the state to X, the new application hash will only be included in block H+1. If after your transaction is committed, you want to get a light-client proof for the new state (X), you need the new block to be committed in order to do that because the new block has the new application hash for the state X. That's why we make a new (empty) block if the application hash changes. Otherwise, you won't be able to make a proof for the new state. + +Plus, if you set `create_empty_blocks_interval` to something other than the default (`0`), CometBFT will be creating empty blocks even in the absence of transactions every `create_empty_blocks_interval.` For instance, with `create_empty_blocks = false` and `create_empty_blocks_interval = "30s"`, CometBFT will only create blocks if there are transactions, or after waiting 30 seconds without receiving any transactions. + +## Consensus timeouts explained + +There's a variety of information about timeouts in [Running in +production](./running-in-production.md#configuration-parameters). +You can also find more detailed explanation in the paper describing +the Tendermint consensus algorithm, adopted by CometBFT: [The latest +gossip on BFT consensus](https://arxiv.org/abs/1807.04938). + +```toml +[consensus] +... + +timeout_propose = "3s" +timeout_propose_delta = "500ms" +timeout_prevote = "1s" +timeout_prevote_delta = "500ms" +timeout_precommit = "1s" +timeout_precommit_delta = "500ms" +timeout_commit = "1s" +``` + +Note that in a successful round, the only timeout that we absolutely wait no +matter what is `timeout_commit`. +Here's a brief summary of the timeouts: + +- `timeout_propose` = how long a validator should wait for a proposal block before prevoting nil +- `timeout_propose_delta` = how much `timeout_propose` increases with each round +- `timeout_prevote` = how long a validator should wait after receiving +2/3 prevotes for + anything (ie. not a single block or nil) +- `timeout_prevote_delta` = how much the `timeout_prevote` increases with each round +- `timeout_precommit` = how long a validator should wait after receiving +2/3 precommits for + anything (ie. not a single block or nil) +- `timeout_precommit_delta` = how much the `timeout_precommit` increases with each round +- `timeout_commit` = how long a validator should wait after committing a block, before starting + on the new height (this gives us a chance to receive some more precommits, + even though we already have +2/3) + +### The adverse effect of using inconsistent `timeout_propose` in a network + +Here's an interesting question. What happens if a particular validator sets a +very small `timeout_propose`, as compared to the rest of the network? + +Imagine there are only two validators in your network: Alice and Bob. Bob sets +`timeout_propose` to 0s. Alice uses the default value of 3s. Let's say they +both have an equal voting power. Given the proposer selection algorithm is a +weighted round-robin, you may expect Alice and Bob to take turns proposing +blocks, and the result like: + +``` +#1 block - Alice +#2 block - Bob +#3 block - Alice +#4 block - Bob +... +``` + +What happens in reality is, however, a little bit different: + +``` +#1 block - Bob +#2 block - Bob +#3 block - Bob +#4 block - Bob +``` + +That's because Bob doesn't wait for a proposal from Alice (prevotes `nil`). +This leaves Alice no chances to commit a block. Note that every block Bob +creates needs a vote from Alice to constitute 2/3+. Bob always gets one because +Alice has `timeout_propose` set to 3s. Alice never gets one because Bob has it +set to 0s. + +Imagine now there are ten geographically distributed validators. One of them +(Bob) sets `timeout_propose` to 0s. Others have it set to 3s. Now, Bob won't be +able to move with his own speed because it still needs 2/3 votes of the other +validators and it takes time to propagate those. I.e., the network moves with +the speed of time to accumulate 2/3+ of votes (prevotes & precommits), not with +the speed of the fastest proposer. + +> Isn't block production determined by voting power? + +If it were determined solely by voting power, it wouldn't be possible to ensure +liveness. Timeouts exist because the network can't rely on a single proposer +being available and must move on if such is not responding. + +> How can we address situations where someone arbitrarily adjusts their block +> production time to gain an advantage? + +The impact shown above is negligible in a decentralized network with enough +decentralization. + +### The adverse effect of using inconsistent `timeout_commit` in a network + +Let's look at the same scenario as before. There are ten geographically +distributed validators. One of them (Bob) sets `timeout_commit` to 0s. Others +have it set to 1s (the default value). Now, Bob will be the fastest producer +because he doesn't wait for additional precommits after creating a block. If +waiting for precommits (`timeout_commit`) is not incentivized, Bob will accrue +more rewards compared to the other 9 validators. + +This is because Bob has the advantage of broadcasting its proposal early (1 +second earlier than the others). But it also makes it possible for Bob to miss +a proposal from another validator and prevote `nil` due to him starting +`timeout_propose` earlier. I.e., if Bob's `timeout_commit` is too low comparing +to other validators, then he might miss some proposals and get slashed for +inactivity. diff --git a/docs/core/how-to-read-logs.md b/docs/core/how-to-read-logs.md new file mode 100644 index 0000000..94d7744 --- /dev/null +++ b/docs/core/how-to-read-logs.md @@ -0,0 +1,141 @@ +--- +order: 7 +--- + +# How to read logs + +## Walkabout example + +We first create three connections (mempool, consensus and query) to the +application (running `kvstore` locally in this case). + +```sh +I[10-04|13:54:27.364] Starting multiAppConn module=proxy impl=multiAppConn +I[10-04|13:54:27.366] Starting localClient module=abci-client connection=query impl=localClient +I[10-04|13:54:27.366] Starting localClient module=abci-client connection=mempool impl=localClient +I[10-04|13:54:27.367] Starting localClient module=abci-client connection=consensus impl=localClient +``` + +Then CometBFT and the application perform a handshake. + +```sh +I[10-04|13:54:27.367] ABCI Handshake module=consensus appHeight=90 appHash=E0FBAFBF6FCED8B9786DDFEB1A0D4FA2501BADAD +I[10-04|13:54:27.368] ABCI Replay Blocks module=consensus appHeight=90 storeHeight=90 stateHeight=90 +I[10-04|13:54:27.368] Completed ABCI Handshake - CometBFT and App are synced module=consensus appHeight=90 appHash=E0FBAFBF6FCED8B9786DDFEB1A0D4FA2501BADAD +``` + +After that, we start a few more things like the event switch and reactors. + +```sh +I[10-04|13:54:27.374] Starting EventSwitch module=types impl=EventSwitch +I[10-04|13:54:27.375] This node is a validator module=consensus +I[10-04|13:54:27.379] Starting Node module=main impl=Node +I[10-04|13:54:27.381] Local listener module=p2p ip=:: port=26656 +I[10-04|13:54:30.386] Starting DefaultListener module=p2p impl=Listener(@10.0.2.15:26656) +I[10-04|13:54:30.387] Starting P2P Switch module=p2p impl="P2P Switch" +I[10-04|13:54:30.387] Starting MempoolReactor module=mempool impl=MempoolReactor +I[10-04|13:54:30.387] Starting BlockchainReactor module=blockchain impl=BlockchainReactor +I[10-04|13:54:30.387] Starting ConsensusReactor module=consensus impl=ConsensusReactor +I[10-04|13:54:30.387] ConsensusReactor module=consensus fastSync=false +I[10-04|13:54:30.387] Starting ConsensusState module=consensus impl=ConsensusState +I[10-04|13:54:30.387] Starting WAL module=consensus wal=/home/vagrant/.cometbft/data/cs.wal/wal impl=WAL +I[10-04|13:54:30.388] Starting TimeoutTicker module=consensus impl=TimeoutTicker +``` + +Notice the second row where CometBFT reports that "This node is a +validator". It also could be just an observer (regular node). + +Next we replay all the messages from the WAL. + +```sh +I[10-04|13:54:30.390] Catchup by replaying consensus messages module=consensus height=91 +I[10-04|13:54:30.390] Replay: New Step module=consensus height=91 round=0 step=RoundStepNewHeight +I[10-04|13:54:30.390] Replay: Done module=consensus +``` + +"Started node" message signals that everything is ready for work. + +```sh +I[10-04|13:54:30.391] Starting RPC HTTP server on tcp socket 0.0.0.0:26657 module=rpc-server +I[10-04|13:54:30.392] Started node module=main nodeInfo="NodeInfo{id: DF22D7C92C91082324A1312F092AA1DA197FA598DBBFB6526E, moniker: anonymous, network: test-chain-3MNw2N [remote , listen 10.0.2.15:26656], version: 0.11.0-10f361fc ([wire_version=0.6.2 p2p_version=0.5.0 consensus_version=v1/0.2.2 rpc_version=0.7.0/3 tx_index=on rpc_addr=tcp://0.0.0.0:26657])}" +``` + +Next follows a standard block creation cycle, where we enter a new +round, propose a block, receive more than 2/3 of prevotes, then +precommits and finally have a chance to commit a block. For details, +please refer to [Byzantine Consensus Algorithm](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/consensus/consensus.md). + +```sh +I[10-04|13:54:30.393] enterNewRound(91/0). Current: 91/0/RoundStepNewHeight module=consensus +I[10-04|13:54:30.393] enterPropose(91/0). Current: 91/0/RoundStepNewRound module=consensus +I[10-04|13:54:30.393] enterPropose: Our turn to propose module=consensus proposer=125B0E3C5512F5C2B0E1109E31885C4511570C42 privValidator="PrivValidator{125B0E3C5512F5C2B0E1109E31885C4511570C42 LH:90, LR:0, LS:3}" +I[10-04|13:54:30.394] Signed proposal module=consensus height=91 round=0 proposal="Proposal{91/0 1:21B79872514F (-1,:0:000000000000) {/10EDEDD7C84E.../}}" +I[10-04|13:54:30.397] Received complete proposal block module=consensus height=91 hash=F671D562C7B9242900A286E1882EE64E5556FE9E +I[10-04|13:54:30.397] enterPrevote(91/0). Current: 91/0/RoundStepPropose module=consensus +I[10-04|13:54:30.397] enterPrevote: ProposalBlock is valid module=consensus height=91 round=0 +I[10-04|13:54:30.398] Signed and pushed vote module=consensus height=91 round=0 vote="Vote{0:125B0E3C5512 91/00/1(Prevote) F671D562C7B9 {/89047FFC21D8.../}}" err=null +I[10-04|13:54:30.401] Added to prevote module=consensus vote="Vote{0:125B0E3C5512 91/00/1(Prevote) F671D562C7B9 {/89047FFC21D8.../}}" prevotes="VoteSet{H:91 R:0 T:1 +2/3:F671D562C7B9242900A286E1882EE64E5556FE9E:1:21B79872514F BA{1:X} map[]}" +I[10-04|13:54:30.401] enterPrecommit(91/0). Current: 91/0/RoundStepPrevote module=consensus +I[10-04|13:54:30.401] enterPrecommit: +2/3 prevoted proposal block. Locking module=consensus hash=F671D562C7B9242900A286E1882EE64E5556FE9E +I[10-04|13:54:30.402] Signed and pushed vote module=consensus height=91 round=0 vote="Vote{0:125B0E3C5512 91/00/2(Precommit) F671D562C7B9 {/80533478E41A.../}}" err=null +I[10-04|13:54:30.404] Added to precommit module=consensus vote="Vote{0:125B0E3C5512 91/00/2(Precommit) F671D562C7B9 {/80533478E41A.../}}" precommits="VoteSet{H:91 R:0 T:2 +2/3:F671D562C7B9242900A286E1882EE64E5556FE9E:1:21B79872514F BA{1:X} map[]}" +I[10-04|13:54:30.404] enterCommit(91/0). Current: 91/0/RoundStepPrecommit module=consensus +I[10-04|13:54:30.405] Finalizing commit of block with 0 txs module=consensus height=91 hash=F671D562C7B9242900A286E1882EE64E5556FE9E root=E0FBAFBF6FCED8B9786DDFEB1A0D4FA2501BADAD +I[10-04|13:54:30.405] Block{ + Header{ + ChainID: test-chain-3MNw2N + Height: 91 + Time: 2017-10-04 13:54:30.393 +0000 UTC + NumTxs: 0 + LastBlockID: F15AB8BEF9A6AAB07E457A6E16BC410546AA4DC6:1:D505DA273544 + LastCommit: 56FEF2EFDB8B37E9C6E6D635749DF3169D5F005D + Data: + Validators: CE25FBFF2E10C0D51AA1A07C064A96931BC8B297 + App: E0FBAFBF6FCED8B9786DDFEB1A0D4FA2501BADAD + }#F671D562C7B9242900A286E1882EE64E5556FE9E + Data{ + + }# + Commit{ + BlockID: F15AB8BEF9A6AAB07E457A6E16BC410546AA4DC6:1:D505DA273544 + Precommits: Vote{0:125B0E3C5512 90/00/2(Precommit) F15AB8BEF9A6 {/FE98E2B956F0.../}} + }#56FEF2EFDB8B37E9C6E6D635749DF3169D5F005D +}#F671D562C7B9242900A286E1882EE64E5556FE9E module=consensus +I[10-04|13:54:30.408] Executed block module=state height=91 validTxs=0 invalidTxs=0 +I[10-04|13:54:30.410] Committed state module=state height=91 txs=0 hash=E0FBAFBF6FCED8B9786DDFEB1A0D4FA2501BADAD +I[10-04|13:54:30.410] Recheck txs module=mempool numtxs=0 height=91 +``` + +## List of modules + +Here is the list of modules you may encounter in CometBFT's log and a +little overview what they do. + +- `abci-client` As mentioned in [Application Development Guide](../app-dev/abci-cli.md), CometBFT acts as an ABCI + client with respect to the application and maintains 3 connections: + mempool, consensus and query. The code used by CometBFT can + be found [here](https://github.com/cometbft/cometbft/blob/v0.38.x/abci/client). +- `blockchain` Provides storage, pool (a group of peers), and reactor + for both storing and exchanging blocks between peers. +- `consensus` The heart of CometBFT, which is the + implementation of the consensus algorithm. Includes two + "submodules": `wal` (write-ahead logging) for ensuring data + integrity and `replay` to replay blocks and messages on recovery + from a crash. +- `events` Simple event notification system. The list of events can be + found + [here](https://github.com/cometbft/cometbft/blob/v0.38.x/types/events.go). + You can subscribe to them by calling `subscribe` RPC method. Refer + to [RPC docs](./rpc.md) for additional information. +- `mempool` Mempool module handles all incoming transactions, whenever + they are coming from peers or the application. +- `p2p` Provides an abstraction around peer-to-peer communication. For + more details, please check out the + [README](https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/README.md). +- `rpc` [CometBFT's RPC](./rpc.md). +- `rpc-server` RPC server. For implementation details, please read the + [doc.go](https://github.com/cometbft/cometbft/blob/v0.38.x/rpc/jsonrpc/doc.go). +- `state` Represents the latest state and execution submodule, which + executes blocks against the application. +- `types` A collection of the publicly exposed types and methods to + work with them. diff --git a/docs/core/light-client.md b/docs/core/light-client.md new file mode 100644 index 0000000..48c53c4 --- /dev/null +++ b/docs/core/light-client.md @@ -0,0 +1,69 @@ +--- +order: 13 +--- + +# Light Client + +Light clients are an important part of the complete blockchain system for most +applications. CometBFT provides unique speed and security properties for +light client applications. + +See our [light +package](https://pkg.go.dev/github.com/cometbft/cometbft/light?tab=doc). + +## Overview + +The objective of the light client protocol is to get a commit for a recent +block hash where the commit includes a majority of signatures from the last +known validator set. From there, all the application state is verifiable with +[merkle proofs](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/encoding.md#iavl-tree). + +## Properties + +- You get the full collateralized security benefits of CometBFT; no + need to wait for confirmations. +- You get the full speed benefits of CometBFT; transactions + commit instantly. +- You can get the most recent version of the application state + non-interactively (without committing anything to the blockchain). For + example, this means that you can get the most recent value of a name from the + name-registry without worrying about fork censorship attacks, without posting + a commit and waiting for confirmations. It's fast, secure, and free! + +## Where to obtain trusted height & hash + +[Trust Options](https://pkg.go.dev/github.com/cometbft/cometbft/light?tab=doc#TrustOptions) + +One way to obtain semi-trusted hash & height is to query multiple full nodes +and compare their hashes: + +```bash +$ curl -s https://233.123.0.140:26657:26657/commit | jq "{height: .result.signed_header.header.height, hash: .result.signed_header.commit.block_id.hash}" +{ + "height": "273", + "hash": "188F4F36CBCD2C91B57509BBF231C777E79B52EE3E0D90D06B1A25EB16E6E23D" +} +``` + +## Running a light client as an HTTP proxy server + +CometBFT comes with a built-in `cometbft light` command, which can be used +to run a light client proxy server, verifying CometBFT RPC. All calls that +can be tracked back to a block header by a proof will be verified before +passing them back to the caller. Other than that, it will present the same +interface as a full CometBFT node. + +You can start the light client proxy server by running `cometbft light `, +with a variety of flags to specify the primary node, the witness nodes (which cross-check +the information provided by the primary), the hash and height of the trusted header, +and more. + +For example: + +```bash +$ cometbft light supernova -p tcp://233.123.0.140:26657 \ + -w tcp://179.63.29.15:26657,tcp://144.165.223.135:26657 \ + --height=10 --hash=37E9A6DD3FA25E83B22C18835401E8E56088D0D7ABC6FD99FCDC920DD76C1C57 +``` + +For additional options, run `cometbft light --help`. diff --git a/docs/core/mempool.md b/docs/core/mempool.md new file mode 100644 index 0000000..be3496a --- /dev/null +++ b/docs/core/mempool.md @@ -0,0 +1,103 @@ +--- +order: 12 +--- + +# Mempool + +A mempool (a contraction of memory and pool) is a node’s data structure for +storing information on uncommitted transactions. It acts as a sort of waiting +room for transactions that have not yet been committed. + +CometBFT currently supports two types of mempools: `flood` and `nop`. + +## 1. Flood + +The `flood` mempool stores transactions in a concurrent linked list. When a new +transaction is received, it first checks if there's a space for it (`size` and +`max_txs_bytes` config options) and that it's not too big (`max_tx_bytes` config +option). Then, it checks if this transaction has already been seen before by using +an LRU cache (`cache_size` regulates the cache's size). If all checks pass and +the transaction is not in the cache (meaning it's new), the ABCI +[`CheckTxAsync`][1] method is called. The ABCI application validates the +transaction using its own rules. + +If the transaction is deemed valid by the ABCI application, it's added to the linked list. + +The mempool's name (`flood`) comes from the dissemination mechanism. When a new +transaction is added to the linked list, the mempool sends it to all connected +peers. Peers themselves gossip this transaction to their peers and so on. One +can say that each transaction "floods" the network, hence the name `flood`. + +Note there are experimental config options +`experimental_max_gossip_connections_to_persistent_peers` and +`experimental_max_gossip_connections_to_non_persistent_peers` to limit the +number of peers a transaction is broadcasted to. Also, you can turn off +broadcasting with `broadcast` config option. + +After each committed block, CometBFT rechecks all uncommitted transactions (can +be disabled with the `recheck` config option) by repeatedly calling the ABCI +`CheckTxAsync`. + +### Transaction ordering + +Currently, there's no ordering of transactions other than the order they've +arrived (via RPC or from other nodes). + +So the only way to specify the order is to send them to a single node. + +valA: + +- `tx1` +- `tx2` +- `tx3` + +If the transactions are split up across different nodes, there's no way to +ensure they are processed in the expected order. + +valA: + +- `tx1` +- `tx2` + +valB: + +- `tx3` + +If valB is the proposer, the order might be: + +- `tx3` +- `tx1` +- `tx2` + +If valA is the proposer, the order might be: + +- `tx1` +- `tx2` +- `tx3` + +That said, if the transactions contain some internal value, like an +order/nonce/sequence number, the application can reject transactions that are +out of order. So if a node receives `tx3`, then `tx1`, it can reject `tx3` and then +accept `tx1`. The sender can then retry sending `tx3`, which should probably be +rejected until the node has seen `tx2`. + +## 2. Nop + +`nop` (short for no operation) mempool is used when the ABCI application developer wants to +build their own mempool. When `type = "nop"`, transactions are not stored anywhere +and are not gossiped to other peers using the P2P network. + +Submitting a transaction via the existing RPC methods (`BroadcastTxSync`, +`BroadcastTxAsync`, and `BroadcastTxCommit`) will always result in an error. + +Because there's no way for the consensus to know if transactions are available +to be committed, the node will always create blocks, which can be empty +sometimes. Using `consensus.create_empty_blocks=false` is prohibited in such +cases. + +The ABCI application becomes responsible for storing, disseminating, and +proposing transactions using [`PrepareProposal`][2]. The concrete design is up +to the ABCI application developers. + +[1]: ../../spec/abci/abci++_methods.md#checktx +[2]: ../../spec/abci/abci++_methods.md#prepareproposal \ No newline at end of file diff --git a/docs/core/metrics.md b/docs/core/metrics.md new file mode 100644 index 0000000..2c1d876 --- /dev/null +++ b/docs/core/metrics.md @@ -0,0 +1,75 @@ +--- +order: 5 +--- + +# Metrics + +CometBFT can report and serve the Prometheus metrics, which in their turn can +be consumed by Prometheus collector(s). + +This functionality is disabled by default. + +To enable the Prometheus metrics, set `instrumentation.prometheus=true` in your +config file. Metrics will be served under `/metrics` on 26660 port by default. +Listen address can be changed in the config file (see +`instrumentation.prometheus\_listen\_addr`). + +## List of available metrics + +The following metrics are available: + +| **Name** | **Type** | **Tags** | **Description** | +|--------------------------------------------|-----------|------------------|--------------------------------------------------------------------------------------------------------------------------------------------| +| abci\_connection\_method\_timing\_seconds | Histogram | method, type | Timings for each of the ABCI methods | +| blocksync\_syncing | Gauge | | Either 0 (not block syncing) or 1 (syncing) | +| consensus\_height | Gauge | | Height of the chain | +| consensus\_validators | Gauge | | Number of validators | +| consensus\_validators\_power | Gauge | | Total voting power of all validators | +| consensus\_validator\_power | Gauge | | Voting power of the node if in the validator set | +| consensus\_validator\_last\_signed\_height | Gauge | | Last height the node signed a block, if the node is a validator | +| consensus\_validator\_missed\_blocks | Gauge | | Total amount of blocks missed for the node, if the node is a validator | +| consensus\_missing\_validators | Gauge | | Number of validators who did not sign | +| consensus\_missing\_validators\_power | Gauge | | Total voting power of the missing validators | +| consensus\_byzantine\_validators | Gauge | | Number of validators who tried to double sign | +| consensus\_byzantine\_validators\_power | Gauge | | Total voting power of the byzantine validators | +| consensus\_block\_interval\_seconds | Histogram | | Time between this and last block (Block.Header.Time) in seconds | +| consensus\_rounds | Gauge | | Number of rounds | +| consensus\_num\_txs | Gauge | | Number of transactions | +| consensus\_total\_txs | Gauge | | Total number of transactions committed | +| consensus\_block\_parts | Counter | peer\_id | Number of blockparts transmitted by peer | +| consensus\_latest\_block\_height | Gauge | | /status sync\_info number | +| consensus\_block\_size\_bytes | Gauge | | Block size in bytes | +| consensus\_step\_duration | Histogram | step | Histogram of durations for each step in the consensus protocol | +| consensus\_round\_duration | Histogram | | Histogram of durations for all the rounds that have occurred since the process started | +| consensus\_block\_gossip\_parts\_received | Counter | matches\_current | Number of block parts received by the node | +| consensus\_quorum\_prevote\_delay | Gauge | | Interval in seconds between the proposal timestamp and the timestamp of the earliest prevote that achieved a quorum | +| consensus\_full\_prevote\_delay | Gauge | | Interval in seconds between the proposal timestamp and the timestamp of the latest prevote in a round where all validators voted | +| consensus\_vote\_extension\_receive\_count | Counter | status | Number of vote extensions received | +| consensus\_proposal\_receive\_count | Counter | status | Total number of proposals received by the node since process start | +| consensus\_proposal\_create\_count | Counter | | Total number of proposals created by the node since process start | +| consensus\_round\_voting\_power\_percent | Gauge | vote\_type | A value between 0 and 1.0 representing the percentage of the total voting power per vote type received within a round | +| consensus\_late\_votes | Counter | vote\_type | Number of votes received by the node since process start that correspond to earlier heights and rounds than this node is currently in. | +| p2p\_message\_send\_bytes\_total | Counter | message\_type | Number of bytes sent to all peers per message type | +| p2p\_message\_receive\_bytes\_total | Counter | message\_type | Number of bytes received from all peers per message type | +| p2p\_peers | Gauge | | Number of peers node's connected to | +| p2p\_peer\_receive\_bytes\_total | Counter | peer\_id, chID | Number of bytes per channel received from a given peer | +| p2p\_peer\_send\_bytes\_total | Counter | peer\_id, chID | Number of bytes per channel sent to a given peer | +| p2p\_peer\_pending\_send\_bytes | Gauge | peer\_id | Number of pending bytes to be sent to a given peer | +| p2p\_num\_txs | Gauge | peer\_id | Number of transactions submitted by each peer\_id | +| p2p\_pending\_send\_bytes | Gauge | peer\_id | Amount of data pending to be sent to peer | +| mempool\_size | Gauge | | Number of uncommitted transactions | +| mempool\_tx\_size\_bytes | Histogram | | Transaction sizes in bytes | +| mempool\_failed\_txs | Counter | | Number of failed transactions | +| mempool\_recheck\_times | Counter | | Number of transactions rechecked in the mempool | +| state\_block\_processing\_time | Histogram | | Time spent processing FinalizeBlock in ms | +| state\_consensus\_param\_updates | Counter | | Number of consensus parameter updates returned by the application since process start | +| state\_validator\_set\_updates | Counter | | Number of validator set updates returned by the application since process start | +| statesync\_syncing | Gauge | | Either 0 (not state syncing) or 1 (syncing) | + +## Useful queries + +Percentage of missing + byzantine validators: + +```md +((consensus\_byzantine\_validators\_power + consensus\_missing\_validators\_power) / consensus\_validators\_power) * 100 +``` diff --git a/docs/core/rpc.md b/docs/core/rpc.md new file mode 100644 index 0000000..143e152 --- /dev/null +++ b/docs/core/rpc.md @@ -0,0 +1,15 @@ +--- +order: 9 +--- + +# RPC + +The RPC documentation is hosted here: + +- [OpenAPI reference](../rpc) + + diff --git a/docs/core/running-in-production.md b/docs/core/running-in-production.md new file mode 100644 index 0000000..1714c1c --- /dev/null +++ b/docs/core/running-in-production.md @@ -0,0 +1,413 @@ +--- +order: 4 +--- + +# Running in production + +## Database + +By default, CometBFT uses the `syndtr/goleveldb` package for its in-process +key-value database. If you want maximal performance, it may be best to install +the real C-implementation of LevelDB and compile CometBFT to use that using +`make build COMETBFT_BUILD_OPTIONS=cleveldb`. See the [install +instructions](../guides/install.md) for details. + +CometBFT keeps multiple distinct databases in the `$CMTHOME/data`: + +- `blockstore.db`: Keeps the entire blockchain - stores blocks, + block commits, and block metadata, each indexed by height. Used to sync new + peers. +- `evidence.db`: Stores all verified evidence of misbehavior. +- `state.db`: Stores the current blockchain state (i.e. height, validators, + consensus params). Only grows if consensus params or validators change. Also + used to temporarily store intermediate results during block processing. +- `tx_index.db`: Indexes transactions and by tx hash and height. The tx results are indexed if they are added to the `FinalizeBlock` response in the application. + +By default, CometBFT will only index transactions by their hash and height, if +you want the result events to be indexed, see [indexing +transactions](../app-dev/indexing-transactions.md) for for details. + +Applications can expose block pruning strategies to the node operator. +Please read the documentation of your application to find out more details. + +Applications can use [state sync](./state-sync.md) to help nodes bootstrap quickly. + +## Logging + +Default logging level (`log_level = "main:info,state:info,statesync:info,*:error"`) should suffice for +normal operation mode. Read [this +post](https://blog.cosmos.network/one-of-the-exciting-new-features-in-0-10-0-release-is-smart-log-level-flag-e2506b4ab756) +for details on how to configure `log_level` config variable. Some of the +modules can be found [here](./how-to-read-logs.md#list-of-modules). If +you're trying to debug CometBFT or asked to provide logs with debug +logging level, you can do so by running CometBFT with +`--log_level="*:debug"`. + +## Write Ahead Logs (WAL) + +CometBFT uses write ahead logs for the consensus (`cs.wal`) and the mempool +(`mempool.wal`). Both WALs have a max size of 1GB and are automatically rotated. + +### Consensus WAL + +The `consensus.wal` is used to ensure we can recover from a crash at any point +in the consensus state machine. +It writes all consensus messages (timeouts, proposals, block part, or vote) +to a single file, flushing to disk before processing messages from its own +validator. Since CometBFT validators are expected to never sign a conflicting vote, the +WAL ensures we can always recover deterministically to the latest state of the consensus without +using the network or re-signing any consensus messages. + +If your `consensus.wal` is corrupted, see [below](#wal-corruption). + +### Mempool WAL + +The `mempool.wal` logs all incoming transactions before running CheckTx, but is +otherwise not used in any programmatic way. It's just a kind of manual +safe guard. Note the mempool provides no durability guarantees - a tx sent to one or many nodes +may never make it into the blockchain if those nodes crash before being able to +propose it. Clients must monitor their transactions by subscribing over websockets, +polling for them, or using `/broadcast_tx_commit`. In the worst case, transactions can be +resent from the mempool WAL manually. + +For the above reasons, the `mempool.wal` is disabled by default. To enable, set +`mempool.wal_dir` to where you want the WAL to be located (e.g. +`data/mempool.wal`). + +## DoS Exposure and Mitigation + +Validators are supposed to setup [Sentry Node Architecture](./validators.md) +to prevent Denial-of-Service attacks. + +### P2P + +The core of the CometBFT peer-to-peer system is `MConnection`. Each +connection has `MaxPacketMsgPayloadSize`, which is the maximum packet +size and bounded send & receive queues. One can impose restrictions on +send & receive rate per connection (`SendRate`, `RecvRate`). + +The number of open P2P connections can become quite large, and hit the operating system's open +file limit (since TCP connections are considered files on UNIX-based systems). Nodes should be +given a sizable open file limit, e.g. 8192, via `ulimit -n 8192` or other deployment-specific +mechanisms. + +### RPC + +#### Attack Exposure and Mitigation + +**It is generally not recommended for RPC endpoints to be exposed publicly, and +especially so if the node in question is a validator**, as the CometBFT RPC does +not currently provide advanced security features. Public exposure of RPC +endpoints without appropriate protection can make the associated node vulnerable +to a variety of attacks. + +It is entirely up to operators to ensure, if nodes' RPC endpoints have to be +exposed publicly, that appropriate measures have been taken to mitigate against +attacks. Some examples of mitigation measures include, but are not limited to: + +- Never publicly exposing the RPC endpoints of validators (i.e. if the RPC + endpoints absolutely have to be exposed, ensure you do so only on full nodes + and with appropriate protection) +- Correct usage of rate-limiting, authentication and caching (e.g. as provided + by reverse proxies like [nginx](https://nginx.org/) and/or DDoS protection + services like [Cloudflare](https://www.cloudflare.com)) +- Only exposing the specific endpoints absolutely necessary for the relevant use + cases (configurable via nginx/Cloudflare/etc.) + +If no expertise is available to the operator to assist with securing nodes' RPC +endpoints, it is strongly recommended to never expose those endpoints publicly. + +**Under no condition should any of the [unsafe RPC endpoints](../rpc/#/Unsafe) +ever be exposed publicly.** + +#### Endpoints Returning Multiple Entries + +Endpoints returning multiple entries are limited by default to return 30 +elements (100 max). See the [RPC Documentation](https://docs.cometbft.com/v0.38/rpc/) +for more information. + +## Debugging CometBFT + +If you ever have to debug CometBFT, the first thing you should probably do is +check out the logs. See [How to read logs](./how-to-read-logs.md), where we +explain what certain log statements mean. + +If, after skimming through the logs, things are not clear still, the next thing +to try is querying the `/status` RPC endpoint. It provides the necessary info: +whenever the node is syncing or not, what height it is on, etc. + +```bash +curl http(s)://{ip}:{rpcPort}/status +``` + +`/dump_consensus_state` will give you a detailed overview of the consensus +state (proposer, latest validators, peers states). From it, you should be able +to figure out why, for example, the network had halted. + +```bash +curl http(s)://{ip}:{rpcPort}/dump_consensus_state +``` + +There is a reduced version of this endpoint - `/consensus_state`, which returns +just the votes seen at the current height. + +If, after consulting with the logs and above endpoints, you still have no idea +what's happening, consider using `cometbft debug kill` sub-command. This +command will scrap all the available info and kill the process. See +[Debugging](../tools/debugging.md) for the exact format. + +You can inspect the resulting archive yourself or create an issue on +[Github](https://github.com/cometbft/cometbft). Before opening an issue +however, be sure to check if there's [no existing +issue](https://github.com/cometbft/cometbft/issues) already. + +## Monitoring CometBFT + +Each CometBFT instance has a standard `/health` RPC endpoint, which responds +with 200 (OK) if everything is fine and 500 (or no response) - if something is +wrong. + +Other useful endpoints include mentioned earlier `/status`, `/net_info` and +`/validators`. + +CometBFT also can report and serve Prometheus metrics. See +[Metrics](./metrics.md). + +`cometbft debug dump` sub-command can be used to periodically dump useful +information into an archive. See [Debugging](../tools/debugging.md) for more +information. + +## What happens when my app dies + +You are supposed to run CometBFT under a [process +supervisor](https://en.wikipedia.org/wiki/Process_supervision) (like +systemd or runit). It will ensure CometBFT is always running (despite +possible errors). + +Getting back to the original question, if your application dies, +CometBFT will panic. After a process supervisor restarts your +application, CometBFT should be able to reconnect successfully. The +order of restart does not matter for it. + +## Signal handling + +We catch SIGINT and SIGTERM and try to clean up nicely. For other +signals we use the default behavior in Go: +[Default behavior of signals in Go programs](https://golang.org/pkg/os/signal/#hdr-Default_behavior_of_signals_in_Go_programs). + +## Corruption + +**NOTE:** Make sure you have a backup of the CometBFT data directory. + +### Possible causes + +Remember that most corruption is caused by hardware issues: + +- RAID controllers with faulty / worn out battery backup, and an unexpected power loss +- Hard disk drives with write-back cache enabled, and an unexpected power loss +- Cheap SSDs with insufficient power-loss protection, and an unexpected power-loss +- Defective RAM +- Defective or overheating CPU(s) + +Other causes can be: + +- Database systems configured with fsync=off and an OS crash or power loss +- Filesystems configured to use write barriers plus a storage layer that ignores write barriers. LVM is a particular culprit. +- CometBFT bugs +- Operating system bugs +- Admin error (e.g., directly modifying CometBFT data-directory contents) + +(Source: ) + +### WAL Corruption + +If consensus WAL is corrupted at the latest height and you are trying to start +CometBFT, replay will fail with panic. + +Recovering from data corruption can be hard and time-consuming. Here are two approaches you can take: + +1. Delete the WAL file and restart CometBFT. It will attempt to sync with other peers. +2. Try to repair the WAL file manually: + +1) Create a backup of the corrupted WAL file: + + ```sh + cp "$CMTHOME/data/cs.wal/wal" > /tmp/corrupted_wal_backup + ``` + +2) Use `./scripts/wal2json` to create a human-readable version: + + ```sh + ./scripts/wal2json/wal2json "$CMTHOME/data/cs.wal/wal" > /tmp/corrupted_wal + ``` + +3) Search for a "CORRUPTED MESSAGE" line. +4) By looking at the previous message and the message after the corrupted one + and looking at the logs, try to rebuild the message. If the consequent + messages are marked as corrupted too (this may happen if length header + got corrupted or some writes did not make it to the WAL ~ truncation), + then remove all the lines starting from the corrupted one and restart + CometBFT. + + ```sh + $EDITOR /tmp/corrupted_wal + ``` + +5) After editing, convert this file back into binary form by running: + + ```sh + ./scripts/json2wal/json2wal /tmp/corrupted_wal $CMTHOME/data/cs.wal/wal + ``` + +## Hardware + +### Processor and Memory + +While actual specs vary depending on the load and validators count, minimal +requirements are: + +- 1GB RAM +- 25GB of disk space +- 1.4 GHz CPU + +SSD disks are preferable for applications with high transaction throughput. + +Recommended: + +- 2GB RAM +- 100GB SSD +- x64 2.0 GHz 2v CPU + +While for now, CometBFT stores all the history and it may require significant +disk space over time, we are planning to implement state syncing (See [this +issue](https://github.com/tendermint/tendermint/issues/828)). So, storing all +the past blocks will not be necessary. + +### Validator signing on 32 bit architectures (or ARM) + +Both our `ed25519` and `secp256k1` implementations require constant time +`uint64` multiplication. Non-constant time crypto can (and has) leaked +private keys on both `ed25519` and `secp256k1`. This doesn't exist in hardware +on 32 bit x86 platforms ([source](https://bearssl.org/ctmul.html)), and it +depends on the compiler to enforce that it is constant time. It's unclear at +this point whenever the Golang compiler does this correctly for all +implementations. + +**We do not support nor recommend running a validator on 32 bit architectures OR +the "VIA Nano 2000 Series", and the architectures in the ARM section rated +"S-".** + +### Operating Systems + +CometBFT can be compiled for a wide range of operating systems thanks to Go +language (the list of \$OS/\$ARCH pairs can be found +[here](https://golang.org/doc/install/source#environment)). + +While we do not favor any operation system, more secure and stable Linux server +distributions (like CentOS) should be preferred over desktop operation systems +(like Mac OS). + +### Miscellaneous + +NOTE: if you are going to use CometBFT in a public domain, make sure +you read [hardware recommendations](https://cosmos.network/validators) for a validator in the +Cosmos network. + +## Configuration parameters + +- `p2p.flush_throttle_timeout` +- `p2p.max_packet_msg_payload_size` +- `p2p.send_rate` +- `p2p.recv_rate` + +If you are going to use CometBFT in a private domain and you have a +private high-speed network among your peers, it makes sense to lower +flush throttle timeout and increase other params. + +```toml +[p2p] + +send_rate=20000000 # 2MB/s +recv_rate=20000000 # 2MB/s +flush_throttle_timeout=10 +max_packet_msg_payload_size=10240 # 10KB +``` + +- `mempool.recheck` + +After every block, CometBFT rechecks every transaction left in the +mempool to see if transactions committed in that block affected the +application state, so some of the transactions left may become invalid. +If that does not apply to your application, you can disable it by +setting `mempool.recheck=false`. + +- `mempool.broadcast` + +Setting this to false will stop the mempool from relaying transactions +to other peers until they are included in a block. It means only the +peer you send the tx to will see it until it is included in a block. + +- `consensus.skip_timeout_commit` + +We want `skip_timeout_commit=false` when there is economics on the line +because proposers should wait to hear for more votes. But if you don't +care about that and want the fastest consensus, you can skip it. It will +be kept false by default for public deployments (e.g. [Cosmos +Hub](https://hub.cosmos.network/)) while for enterprise +applications, setting it to true is not a problem. + +- `consensus.peer_gossip_sleep_duration` + +You can try to reduce the time your node sleeps before checking if +theres something to send its peers. + +- `consensus.timeout_commit` + +You can also try lowering `timeout_commit` (time we sleep before +proposing the next block). + +- `p2p.addr_book_strict` + +By default, CometBFT checks whenever a peer's address is routable before +saving it to the address book. The address is considered as routable if the IP +is [valid and within allowed ranges](https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/netaddress.go#L258). + +This may not be the case for private or local networks, where your IP range is usually +strictly limited and private. If that case, you need to set `addr_book_strict` +to `false` (turn it off). + +- `rpc.max_open_connections` + +By default, the number of simultaneous connections is limited because most OS +give you limited number of file descriptors. + +If you want to accept greater number of connections, you will need to increase +these limits. + +[Sysctls to tune the system to be able to open more connections](https://github.com/satori-com/tcpkali/blob/master/doc/tcpkali.man.md#sysctls-to-tune-the-system-to-be-able-to-open-more-connections) + +The process file limits must also be increased, e.g. via `ulimit -n 8192`. + +...for N connections, such as 50k: + +```md +kern.maxfiles=10000+2*N # BSD +kern.maxfilesperproc=100+2*N # BSD +kern.ipc.maxsockets=10000+2*N # BSD +fs.file-max=10000+2*N # Linux +net.ipv4.tcp_max_orphans=N # Linux + +# For load-generating clients. +net.ipv4.ip_local_port_range="10000 65535" # Linux. +net.inet.ip.portrange.first=10000 # BSD/Mac. +net.inet.ip.portrange.last=65535 # (Enough for N < 55535) +net.ipv4.tcp_tw_reuse=1 # Linux +net.inet.tcp.maxtcptw=2*N # BSD + +# If using netfilter on Linux: +net.netfilter.nf_conntrack_max=N +echo $((N/8)) > /sys/module/nf_conntrack/parameters/hashsize +``` + +The similar option exists for limiting the number of gRPC connections - +`rpc.grpc_max_open_connections`. diff --git a/docs/core/state-sync.md b/docs/core/state-sync.md new file mode 100644 index 0000000..e02c0d6 --- /dev/null +++ b/docs/core/state-sync.md @@ -0,0 +1,50 @@ +--- +order: 11 +--- + +# State Sync + +With block sync a node is downloading all of the data of an application from genesis and verifying it. +With state sync your node will download data related to the head or near the head of the chain and verify the data. +This leads to drastically shorter times for joining a network. + +## Using State Sync + +State sync will continuously work in the background to supply nodes with chunked data when bootstrapping. + +> NOTE: Before trying to use state sync, see if the application you are operating a node for supports it. + +Under the state sync section in `config.toml` you will find multiple settings that need to be configured in order for your node to use state sync. + +Lets breakdown the settings: + +- `enable`: Enable is to inform the node that you will be using state sync to bootstrap your node. +- `rpc_servers`: RPC servers are needed because state sync utilizes the light client for verification. + - 2 servers are required, more is always helpful. +- `temp_dir`: Temporary directory is store the chunks in the machines local storage, If nothing is set it will create a directory in `/tmp` + +The next information you will need to acquire it through publicly exposed RPC's or a block explorer which you trust. + +- `trust_height`: Trusted height defines at which height your node should trust the chain. +- `trust_hash`: Trusted hash is the hash in the `BlockID` corresponding to the trusted height. +- `trust_period`: Trust period is the period in which headers can be verified. + > :warning: This value should be significantly smaller than the unbonding period. + +If you are relying on publicly exposed RPC's to get the need information, you can use `curl` and [`jq`][jq]. + +Example: + +```bash +curl -s https://233.123.0.140:26657/commit | jq "{height: .result.signed_header.header.height, hash: .result.signed_header.commit.block_id.hash}" +``` + +The response will be: + +```json +{ + "height": "273", + "hash": "188F4F36CBCD2C91B57509BBF231C777E79B52EE3E0D90D06B1A25EB16E6E23D" +} +``` + +[jq]: https://jqlang.github.io/jq/ diff --git a/docs/core/subscription.md b/docs/core/subscription.md new file mode 100644 index 0000000..a5d0910 --- /dev/null +++ b/docs/core/subscription.md @@ -0,0 +1,96 @@ +--- +order: 7 +--- + +# Subscribing to events via Websocket + +CometBFT emits different events, which you can subscribe to via +[Websocket](https://en.wikipedia.org/wiki/WebSocket). This can be useful +for third-party applications (for analysis) or for inspecting state. + +[List of events](https://godoc.org/github.com/cometbft/cometbft/types#pkg-constants) + +To connect to a node via websocket from the CLI, you can use a tool such as +[wscat](https://github.com/websockets/wscat) and run: + +```sh +wscat -c ws://127.0.0.1:26657/websocket +``` + +NOTE: If your node's RPC endpoint is TLS-enabled, utilize the scheme `wss` instead of `ws`. + +You can subscribe to any of the events above by calling the `subscribe` RPC +method via Websocket along with a valid query. + +```json +{ + "jsonrpc": "2.0", + "method": "subscribe", + "id": 0, + "params": { + "query": "tm.event='NewBlock'" + } +} +``` + +Check out [API docs](https://docs.cometbft.com/v0.38/rpc/) for +more information on query syntax and other options. + +You can also use tags, given you had included them into FinalizeBlock +response, to query transaction results. See [Indexing +transactions](../app-dev/indexing-transactions.md) for details. + +## Query parameter and event type restrictions + +While CometBFT imposes no restrictions on the application with regards to the type of +the event output, there are several considerations that need to be taken into account +when querying events with numeric values. + +- Queries convert all numeric event values to `big.Float` , provided by `math/big`. Integers +are converted into a float with a precision equal to the number of bits needed +to represent this integer. This is done to avoid precision loss for big integers when they +are converted with the default precision (`64`). +- When comparing two values, if either one of them is a float, the other one will be represented +as a big float. Integers are again parsed as big floats with a precision equal to the number +of bits required to represent them. +- As with all floating point comparisons, comparing floats with decimal values can lead to imprecise +results. +- Queries cannot include negative numbers + +Prior to version `v0.38.x`, floats were not supported as query parameters. + +## ValidatorSetUpdates + +When validator set changes, ValidatorSetUpdates event is published. The +event carries a list of pubkey/power pairs. The list is the same +CometBFT receives from ABCI application (see [EndBlock +section](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/abci++_methods.md#endblock) in +the ABCI spec). + +Response: + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "query": "tm.event='ValidatorSetUpdates'", + "data": { + "type": "tendermint/event/ValidatorSetUpdates", + "value": { + "validator_updates": [ + { + "address": "09EAD022FD25DE3A02E64B0FE9610B1417183EE4", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "ww0z4WaZ0Xg+YI10w43wTWbBmM3dpVza4mmSQYsd0ck=" + }, + "voting_power": "10", + "proposer_priority": "0" + } + ] + } + } + } +} +``` diff --git a/docs/core/using-cometbft.md b/docs/core/using-cometbft.md new file mode 100644 index 0000000..9e572f8 --- /dev/null +++ b/docs/core/using-cometbft.md @@ -0,0 +1,571 @@ +--- +order: 2 +--- + +# Using CometBFT + +This is a guide to using the `cometbft` program from the command line. +It assumes only that you have the `cometbft` binary installed and have +some rudimentary idea of what CometBFT and ABCI are. + +You can see the help menu with `cometbft --help`, and the version +number with `cometbft version`. + +## Directory Root + +The default directory for blockchain data is `~/.cometbft`. Override +this by setting the `CMTHOME` environment variable. + +## Initialize + +Initialize the root directory by running: + +```sh +cometbft init +``` + +This will create a new private key (`priv_validator_key.json`), and a +genesis file (`genesis.json`) containing the associated public key, in +`$CMTHOME/config`. This is all that's necessary to run a local testnet +with one validator. + +For more elaborate initialization, see the testnet command: + +```sh +cometbft testnet --help +``` + +### Genesis + +The `genesis.json` file in `$CMTHOME/config/` defines the initial +CometBFT state upon genesis of the blockchain ([see +definition](https://github.com/cometbft/cometbft/blob/v0.38.x/types/genesis.go)). + +#### Fields + +- `genesis_time`: Official time of blockchain start. +- `chain_id`: ID of the blockchain. **This must be unique for + every blockchain.** If your testnet blockchains do not have unique + chain IDs, you will have a bad time. The ChainID must be less than 50 symbols. +- `initial_height`: Height at which CometBFT should begin at. If a blockchain is conducting a network upgrade, + starting from the stopped height brings uniqueness to previous heights. +- `consensus_params` ([see spec](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/data_structures.md#consensusparams)) + - `block` + - `max_bytes`: Max block size, in bytes. + - `max_gas`: Max gas per block. + - `evidence` + - `max_age_num_blocks`: Max age of evidence, in blocks. The basic formula + for calculating this is: MaxAgeDuration / {average block time}. + - `max_age_duration`: Max age of evidence, in time. It should correspond + with an app's "unbonding period" or other similar mechanism for handling + [Nothing-At-Stake + attacks](https://vitalik.ca/general/2017/12/31/pos_faq.html#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). + - `max_bytes`: This sets the maximum size in bytes of evidence that can be committed + in a single block and should fall comfortably under the max block bytes. + - `validator` + - `pub_key_types`: Public key types validators can use. + - `version` + - `app_version`: ABCI application version. +- `validators`: List of initial validators. Note this may be overridden entirely by the + application, and may be left empty to make explicit that the + application will initialize the validator set upon `InitChain`. + - `pub_key`: The first element specifies the key type, + using the declared `PubKeyName` for the adopted + [key type](https://github.com/cometbft/cometbft/blob/v0.38.x/crypto/ed25519/ed25519.go#L36). + The second element are the pubkey bytes. + - `power`: The validator's voting power. + - `name`: Name of the validator (optional). +- `app_hash`: The expected application hash (as returned by the + `ResponseInfo` ABCI message) upon genesis. If the app's hash does + not match, CometBFT will panic. +- `app_state`: The application state (e.g. initial distribution + of tokens). + +> :warning: **ChainID must be unique to every blockchain. Reusing old chainID can cause issues** + +#### Sample genesis.json + +```json +{ + "genesis_time": "2023-01-21T11:17:42.341227868Z", + "chain_id": "test-chain-ROp9KF", + "initial_height": "0", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "-1", + }, + "evidence": { + "max_age_num_blocks": "100000", + "max_age_duration": "172800000000000", + "max_bytes": 51200, + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + } + }, + "validators": [ + { + "address": "B547AB87E79F75A4A3198C57A8C2FDAF8628CB47", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "P/V6GHuZrb8rs/k1oBorxc6vyXMlnzhJmv7LmjELDys=" + }, + "power": "10", + "name": "" + } + ], + "app_hash": "" +} +``` + +## Run + +To run a CometBFT node, use: + +```bash +cometbft node +``` + +By default, CometBFT will try to connect to an ABCI application on +`tcp://127.0.0.1:26658`. If you have the `kvstore` ABCI app installed, run it in +another window. If you don't, kill CometBFT and run an in-process version of +the `kvstore` app: + +```bash +cometbft node --proxy_app=kvstore +``` + +After a few seconds, you should see blocks start streaming in. Note that blocks +are produced regularly, even if there are no transactions. See [No Empty +Blocks](#no-empty-blocks), below, to modify this setting. + +CometBFT supports in-process versions of the `counter`, `kvstore`, and `noop` +apps that ship as examples with `abci-cli`. It's easy to compile your app +in-process with CometBFT if it's written in Go. If your app is not written in +Go, run it in another process, and use the `--proxy_app` flag to specify the +address of the socket it is listening on, for instance: + +```bash +cometbft node --proxy_app=/var/run/abci.sock +``` + +You can find out what flags are supported by running `cometbft node --help`. + +## Transactions + +To send a transaction, use `curl` to make requests to the CometBFT RPC +server, for example: + +```sh +curl http://localhost:26657/broadcast_tx_commit?tx=\"abcd\" +``` + +We can see the chain's status at the `/status` end-point: + +```sh +curl http://localhost:26657/status | json_pp +``` + +and the `latest_app_hash` in particular: + +```sh +curl http://localhost:26657/status | json_pp | grep latest_app_hash +``` + +Visit `http://localhost:26657` in your browser to see the list of other +endpoints. Some take no arguments (like `/status`), while others specify +the argument name and use `_` as a placeholder. + + +> TIP: Find the RPC Documentation [here](https://docs.cometbft.com/v0.38/rpc/) + +### Formatting + +The following nuances when sending/formatting transactions should be +taken into account: + +With `GET`: + +To send a UTF8 string byte array, quote the value of the tx parameter: + +```sh +curl 'http://localhost:26657/broadcast_tx_commit?tx="hello"' +``` + +which sends a 5 byte transaction: "h e l l o" \[68 65 6c 6c 6f\]. + +Note the URL must be wrapped with single quotes, else bash will ignore +the double quotes. To avoid the single quotes, escape the double quotes: + +```sh +curl http://localhost:26657/broadcast_tx_commit?tx=\"hello\" +``` + +Using a special character: + +```sh +curl 'http://localhost:26657/broadcast_tx_commit?tx="€5"' +``` + +sends a 4 byte transaction: "€5" (UTF8) \[e2 82 ac 35\]. + +To send as raw hex, omit quotes AND prefix the hex string with `0x`: + +```sh +curl http://localhost:26657/broadcast_tx_commit?tx=0x01020304 +``` + +which sends a 4 byte transaction: \[01 02 03 04\]. + +With `POST` (using `json`), the raw hex must be `base64` encoded: + +```sh +curl --data-binary '{"jsonrpc":"2.0","id":"anything","method":"broadcast_tx_commit","params": {"tx": "AQIDBA=="}}' -H 'content-type:text/plain;' http://localhost:26657 +``` + +which sends the same 4 byte transaction: \[01 02 03 04\]. + +Note that raw hex cannot be used in `POST` transactions. + +## Reset + +> :warning: **UNSAFE** Only do this in development and only if you can +afford to lose all blockchain data! + + +To reset a blockchain, stop the node and run: + +```sh +cometbft unsafe_reset_all +``` + +This command will remove the data directory and reset private validator and +address book files. + +## Configuration + +CometBFT uses a `config.toml` for configuration. For details, see [the +config specification](./configuration.md). + +Notable options include the socket address of the application +(`proxy_app`), the listening address of the CometBFT peer +(`p2p.laddr`), and the listening address of the RPC server +(`rpc.laddr`). + +Some fields from the config file can be overwritten with flags. + +## No Empty Blocks + +While the default behavior of `cometbft` is still to create blocks +approximately once per second, it is possible to disable empty blocks or +set a block creation interval. In the former case, blocks will be +created when there are new transactions or when the AppHash changes. + +To configure CometBFT to not produce empty blocks unless there are +transactions or the app hash changes, run CometBFT with this +additional flag: + +```sh +cometbft node --consensus.create_empty_blocks=false +``` + +or set the configuration via the `config.toml` file: + +```toml +[consensus] +create_empty_blocks = false +``` + +Remember: because the default is to _create empty blocks_, avoiding +empty blocks requires the config option to be set to `false`. + +The block interval setting allows for a delay (in time.Duration format [ParseDuration](https://golang.org/pkg/time/#ParseDuration)) between the +creation of each new empty block. It can be set with this additional flag: + +```sh +--consensus.create_empty_blocks_interval="5s" +``` + +or set the configuration via the `config.toml` file: + +```toml +[consensus] +create_empty_blocks_interval = "5s" +``` + +With this setting, empty blocks will be produced every 5s if no block +has been produced otherwise, regardless of the value of +`create_empty_blocks`. + +## Broadcast API + +Earlier, we used the `broadcast_tx_commit` endpoint to send a +transaction. When a transaction is sent to a CometBFT node, it will +run via `CheckTx` against the application. If it passes `CheckTx`, it +will be included in the mempool, broadcasted to other peers, and +eventually included in a block. + +Since there are multiple phases to processing a transaction, we offer +multiple endpoints to broadcast a transaction: + +```md +/broadcast_tx_async +/broadcast_tx_sync +/broadcast_tx_commit +``` + +These correspond to no-processing, processing through the mempool, and +processing through a block, respectively. That is, `broadcast_tx_async`, +will return right away without waiting to hear if the transaction is +even valid, while `broadcast_tx_sync` will return with the result of +running the transaction through `CheckTx`. Using `broadcast_tx_commit` +will wait until the transaction is committed in a block or until some +timeout is reached, but will return right away if the transaction does +not pass `CheckTx`. The return value for `broadcast_tx_commit` includes +two fields, `check_tx` and `deliver_tx`, pertaining to the result of +running the transaction through those ABCI messages. + +The benefit of using `broadcast_tx_commit` is that the request returns +after the transaction is committed (i.e. included in a block), but that +can take on the order of a second. For a quick result, use +`broadcast_tx_sync`, but the transaction will not be committed until +later, and by that point its effect on the state may change. + +Note the mempool does not provide strong guarantees - just because a tx passed +CheckTx (ie. was accepted into the mempool), doesn't mean it will be committed, +as nodes with the tx in their mempool may crash before they get to propose. +For more information, see the [mempool +write-ahead-log](./running-in-production.md#mempool-wal) + +## CometBFT Networks + +When `cometbft init` is run, both a `genesis.json` and +`priv_validator_key.json` are created in `~/.cometbft/config`. The +`genesis.json` might look like: + +```json +{ + "validators" : [ + { + "pub_key" : { + "value" : "h3hk+QE8c6QLTySp8TcfzclJw/BG79ziGB/pIA+DfPE=", + "type" : "tendermint/PubKeyEd25519" + }, + "power" : 10, + "name" : "" + } + ], + "app_hash" : "", + "chain_id" : "test-chain-rDlYSN", + "genesis_time" : "0001-01-01T00:00:00Z" +} +``` + +And the `priv_validator_key.json`: + +```json +{ + "last_step" : 0, + "last_round" : "0", + "address" : "B788DEDE4F50AD8BC9462DE76741CCAFF87D51E2", + "pub_key" : { + "value" : "h3hk+QE8c6QLTySp8TcfzclJw/BG79ziGB/pIA+DfPE=", + "type" : "tendermint/PubKeyEd25519" + }, + "last_height" : "0", + "priv_key" : { + "value" : "JPivl82x+LfVkp8i3ztoTjY6c6GJ4pBxQexErOCyhwqHeGT5ATxzpAtPJKnxNx/NyUnD8Ebv3OIYH+kgD4N88Q==", + "type" : "tendermint/PrivKeyEd25519" + } +} +``` + +The `priv_validator_key.json` actually contains a private key, and should +thus be kept absolutely secret; for now we work with the plain text. +Note the `last_` fields, which are used to prevent us from signing +conflicting messages. + +Note also that the `pub_key` (the public key) in the +`priv_validator_key.json` is also present in the `genesis.json`. + +The genesis file contains the list of public keys which may participate +in the consensus, and their corresponding voting power. Greater than 2/3 +of the voting power must be active (i.e. the corresponding private keys +must be producing signatures) for the consensus to make progress. In our +case, the genesis file contains the public key of our +`priv_validator_key.json`, so a CometBFT node started with the default +root directory will be able to make progress. Voting power uses an int64 +but must be positive, thus the range is: 0 through 9223372036854775807. +Because of how the current proposer selection algorithm works, we do not +recommend having voting powers greater than 10\^12 (ie. 1 trillion). + +If we want to add more nodes to the network, we have two choices: we can +add a new validator node, who will also participate in the consensus by +proposing blocks and voting on them, or we can add a new non-validator +node, who will not participate directly, but will verify and keep up +with the consensus protocol. + +### Peers + +#### Seed + +A seed node is a node who relays the addresses of other peers which they know +of. These nodes constantly crawl the network to try to get more peers. The +addresses which the seed node relays get saved into a local address book. Once +these are in the address book, you will connect to those addresses directly. +Basically the seed nodes job is just to relay everyones addresses. You won't +connect to seed nodes once you have received enough addresses, so typically you +only need them on the first start. The seed node will immediately disconnect +from you after sending you some addresses. + +#### Persistent Peer + +Persistent peers are people you want to be constantly connected with. If you +disconnect you will try to connect directly back to them as opposed to using +another address from the address book. On restarts you will always try to +connect to these peers regardless of the size of your address book. + +All peers relay peers they know of by default. This is called the peer exchange +protocol (PEX). With PEX, peers will be gossiping about known peers and forming +a network, storing peer addresses in the addrbook. Because of this, you don't +have to use a seed node if you have a live persistent peer. + +#### Connecting to Peers + +To connect to peers on start-up, specify them in the +`$CMTHOME/config/config.toml` or on the command line. Use `seeds` to +specify seed nodes, and +`persistent_peers` to specify peers that your node will maintain +persistent connections with. + +For example, + +```sh +cometbft node --p2p.seeds "f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656,0491d373a8e0fcf1023aaf18c51d6a1d0d4f31bd@5.6.7.8:26656" +``` + +Alternatively, you can use the `/dial_seeds` endpoint of the RPC to +specify seeds for a running node to connect to: + +```sh +curl 'localhost:26657/dial_seeds?seeds=\["f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656","0491d373a8e0fcf1023aaf18c51d6a1d0d4f31bd@5.6.7.8:26656"\]' +``` + +Note, with PEX enabled, you +should not need seeds after the first start. + +If you want CometBFT to connect to specific set of addresses and +maintain a persistent connection with each, you can use the +`--p2p.persistent_peers` flag or the corresponding setting in the +`config.toml` or the `/dial_peers` RPC endpoint to do it without +stopping CometBFT instance. + +```sh +cometbft node --p2p.persistent_peers "429fcf25974313b95673f58d77eacdd434402665@10.11.12.13:26656,96663a3dd0d7b9d17d4c8211b191af259621c693@10.11.12.14:26656" + +curl 'localhost:26657/dial_peers?persistent=true&peers=\["429fcf25974313b95673f58d77eacdd434402665@10.11.12.13:26656","96663a3dd0d7b9d17d4c8211b191af259621c693@10.11.12.14:26656"\]' +``` + +### Adding a Non-Validator + +Adding a non-validator is simple. Just copy the original `genesis.json` +to `~/.cometbft/config` on the new machine and start the node, +specifying seeds or persistent peers as necessary. If no seeds or +persistent peers are specified, the node won't make any blocks, because +it's not a validator, and it won't hear about any blocks, because it's +not connected to the other peer. + +### Adding a Validator + +The easiest way to add new validators is to do it in the `genesis.json`, +before starting the network. For instance, we could make a new +`priv_validator_key.json`, and copy it's `pub_key` into the above genesis. + +We can generate a new `priv_validator_key.json` with the command: + +```sh +cometbft gen_validator +``` + +Now we can update our genesis file. For instance, if the new +`priv_validator_key.json` looks like: + +```json +{ + "address" : "5AF49D2A2D4F5AD4C7C8C4CC2FB020131E9C4902", + "pub_key" : { + "value" : "l9X9+fjkeBzDfPGbUM7AMIRE6uJN78zN5+lk5OYotek=", + "type" : "tendermint/PubKeyEd25519" + }, + "priv_key" : { + "value" : "EDJY9W6zlAw+su6ITgTKg2nTZcHAH1NMTW5iwlgmNDuX1f35+OR4HMN88ZtQzsAwhETq4k3vzM3n6WTk5ii16Q==", + "type" : "tendermint/PrivKeyEd25519" + }, + "last_step" : 0, + "last_round" : "0", + "last_height" : "0" +} +``` + +then the new `genesis.json` will be: + +```json +{ + "validators" : [ + { + "pub_key" : { + "value" : "h3hk+QE8c6QLTySp8TcfzclJw/BG79ziGB/pIA+DfPE=", + "type" : "tendermint/PubKeyEd25519" + }, + "power" : 10, + "name" : "" + }, + { + "pub_key" : { + "value" : "l9X9+fjkeBzDfPGbUM7AMIRE6uJN78zN5+lk5OYotek=", + "type" : "cometbft/PubKeyEd25519" + }, + "power" : 10, + "name" : "" + } + ], + "app_hash" : "", + "chain_id" : "test-chain-rDlYSN", + "genesis_time" : "0001-01-01T00:00:00Z" +} +``` + +Update the `genesis.json` in `~/.cometbft/config`. Copy the genesis +file and the new `priv_validator_key.json` to the `~/.cometbft/config` on +a new machine. + +Now run `cometbft node` on both machines, and use either +`--p2p.persistent_peers` or the `/dial_peers` to get them to peer up. +They should start making blocks, and will only continue to do so as long +as both of them are online. + +To make a CometBFT network that can tolerate one of the validators +failing, you need at least four validator nodes (e.g., 2/3). + +Updating validators in a live network is supported but must be +explicitly programmed by the application developer. See the [application +developers guide](../app-dev/abci-cli.md) for more details. + +### Local Network + +To run a network locally, say on a single machine, you must change the `_laddr` +fields in the `config.toml` (or using the flags) so that the listening +addresses of the various sockets don't conflict. Additionally, you must set +`addr_book_strict=false` in the `config.toml`, otherwise CometBFT's p2p +library will deny making connections to peers with the same IP address. + +### Upgrading + +See the +[UPGRADING.md](https://github.com/cometbft/cometbft/blob/v0.38.x/UPGRADING.md) +guide. You may need to reset your chain between major breaking releases. +Although, we expect CometBFT to have fewer breaking releases in the future +(especially after 1.0 release). diff --git a/docs/core/validators.md b/docs/core/validators.md new file mode 100644 index 0000000..9d138dc --- /dev/null +++ b/docs/core/validators.md @@ -0,0 +1,101 @@ +--- +order: 6 +--- + +# Validators + +Validators are responsible for committing new blocks in the blockchain. +These validators participate in the consensus protocol by broadcasting +_votes_ which contain cryptographic signatures signed by each +validator's private key. + +Some Proof-of-Stake consensus algorithms aim to create a "completely" +decentralized system where all stakeholders (even those who are not always +available online) participate in the committing of blocks. CometBFT has a +different approach to block creation. Validators are expected to be online, and +the set of validators is permissioned/curated by the ABCI application. +Proof-of-stake is not required, but can be implemented on top of CometBFT +consensus. That is, validators may be required to post collateral on-chain, +off-chain, or may not be required to post any collateral at all. + +Validators have a cryptographic key-pair and an associated amount of +"voting power". Voting power need not be the same. + +## Becoming a Validator + +There are two ways to become validator. + +1. They can be pre-established in the [genesis state](./using-cometbft.md#genesis) +2. The ABCI app responds to the FinalizeBlock message with changes to the + existing validator set. + +## Setting up a Validator + +When setting up a validator there are countless ways to configure your setup. This guide is aimed at showing one of them, the sentry node design. This design is mainly for DDoS prevention. + +### Network Layout + +![ALT Network Layout](../imgs/sentry_layout.png) + +The diagram is based on AWS, other cloud providers will have similar solutions to design a solution. Running nodes is not limited to cloud providers, you can run nodes on bare metal systems as well. The architecture will be the same no matter which setup you decide to go with. + +The proposed network diagram is similar to the classical backend/frontend separation of services in a corporate environment. The “backend” in this case is the private network of the validator in the data center. The data center network might involve multiple subnets, firewalls and redundancy devices, which is not detailed on this diagram. The important point is that the data center allows direct connectivity to the chosen cloud environment. Amazon AWS has “Direct Connect”, while Google Cloud has “Partner Interconnect”. This is a dedicated connection to the cloud provider (usually directly to your virtual private cloud instance in one of the regions). + +All sentry nodes (the “frontend”) connect to the validator using this private connection. The validator does not have a public IP address to provide its services. + +Amazon has multiple availability zones within a region. One can install sentry nodes in other regions too. In this case the second, third and further regions need to have a private connection to the validator node. This can be achieved by VPC Peering (“VPC Network Peering” in Google Cloud). In this case, the second, third and further region sentry nodes will be directed to the first region and through the direct connect to the data center, arriving to the validator. + +A more persistent solution (not detailed on the diagram) is to have multiple direct connections to different regions from the data center. This way VPC Peering is not mandatory, although still beneficial for the sentry nodes. This overcomes the risk of depending on one region. It is more costly. + +### Local Configuration + +![ALT Local Configuration](../imgs/sentry_local_config.png) + +The validator will only talk to the sentry that are provided, the sentry nodes will communicate to the validator via a secret connection and the rest of the network through a normal connection. The sentry nodes do have the option of communicating with each other as well. + +When initializing nodes there are five parameters in the `config.toml` that may need to be altered. + +- `pex:` boolean. This turns the peer exchange reactor on or off for a node. When `pex=false`, only the `persistent_peers` list is available for connection. +- `persistent_peers:` a comma separated list of `nodeID@ip:port` values that define a list of peers that are expected to be online at all times. This is necessary at first startup because by setting `pex=false` the node will not be able to join the network. +- `unconditional_peer_ids:` comma separated list of nodeID's. These nodes will be connected to no matter the limits of inbound and outbound peers. This is useful for when sentry nodes have full address books. +- `private_peer_ids:` comma separated list of nodeID's. These nodes will not be gossiped to the network. This is an important field as you do not want your validator IP gossiped to the network. +- `addr_book_strict:` boolean. By default nodes with a routable address will be considered for connection. If this setting is turned off (false), non-routable IP addresses, like addresses in a private network can be added to the address book. +- `double_sign_check_height` int64 height. How many blocks to look back to check existence of the node's consensus votes before joining consensus When non-zero, the node will panic upon restart if the same consensus key was used to sign `double_sign_check_height` last blocks. So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. + +#### Validator Node Configuration + +| Config Option | Setting | +| ------------------------ | -------------------------- | +| pex | false | +| persistent_peers | list of sentry nodes | +| private_peer_ids | none | +| unconditional_peer_ids | optionally sentry node IDs | +| addr_book_strict | false | +| double_sign_check_height | 10 | + +The validator node should have `pex=false` so it does not gossip to the entire network. The persistent peers will be your sentry nodes. Private peers can be left empty as the validator is not trying to hide who it is communicating with. Setting unconditional peers is optional for a validator because they will not have a full address books. + +#### Sentry Node Configuration + +| Config Option | Setting | +| ---------------------- | --------------------------------------------- | +| pex | true | +| persistent_peers | validator node, optionally other sentry nodes | +| private_peer_ids | validator node ID | +| unconditional_peer_ids | validator node ID, optionally sentry node IDs | +| addr_book_strict | false | + +The sentry nodes should be able to talk to the entire network hence why `pex=true`. The persistent peers of a sentry node will be the validator, and optionally other sentry nodes. The sentry nodes should make sure that they do not gossip the validator's ip, to do this you must put the validators nodeID as a private peer. The unconditional peer IDs will be the validator ID and optionally other sentry nodes. + +> Note: Do not forget to secure your node's firewalls when setting them up. + +More Information can be found at these links: + +- +- + +### Validator keys + +Protecting a validator's consensus key is the most important factor to take in when designing your setup. The key that a validator is given upon creation of the node is called a consensus key, it has to be online at all times in order to vote on blocks. It is **not recommended** to merely hold your private key in the default json file (`priv_validator_key.json`). Fortunately, the [Interchain Foundation](https://interchain.io) has worked with a team to build a key management server for validators. You can find documentation on how to use it [here](https://github.com/iqlusioninc/tmkms), it is used extensively in production. You are not limited to using this tool, there are also [HSMs](https://safenet.gemalto.com/data-encryption/hardware-security-modules-hsms/), there is not a recommended HSM. + +Currently CometBFT uses [Ed25519](https://ed25519.cr.yp.to/) keys which are widely supported across the security sector and HSMs. diff --git a/docs/explanation/core/metrics.md b/docs/explanation/core/metrics.md new file mode 100644 index 0000000..adccb51 --- /dev/null +++ b/docs/explanation/core/metrics.md @@ -0,0 +1,92 @@ +--- +order: 5 +--- + +# Metrics + +CometBFT can report and serve the Prometheus metrics, which in their turn can +be consumed by Prometheus collector(s). + +This functionality is disabled by default. + +To enable the Prometheus metrics, set `instrumentation.prometheus=true` in your +config file. Metrics will be served under `/metrics` on 26660 port by default. +Listen address can be changed in the config file (see +`instrumentation.prometheus\_listen\_addr`). + +## List of available metrics + +The following metrics are available: + +| **Name** | **Type** | **Tags** | **Description** | +| ------------------------------------------------------- | --------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | +| abci\_connection\_method\_timing\_seconds | Histogram | method, type | Timings for each of the ABCI methods | +| blocksync\_syncing | Gauge | | Either 0 (not block syncing) or 1 (syncing) | +| consensus\_height | Gauge | | Height of the chain | +| consensus\_validators | Gauge | | Number of validators | +| consensus\_validators\_power | Gauge | validator\_address | Total voting power of all validators | +| consensus\_validator\_power | Gauge | validator\_address | Voting power of the node if in the validator set | +| consensus\_validator\_last\_signed\_height | Gauge | validator\_address | Last height the node signed a block, if the node is a validator | +| consensus\_validator\_missed\_blocks | Gauge | | Total amount of blocks missed for the node, if the node is a validator | +| consensus\_missing\_validators | Gauge | | Number of validators who did not sign | +| consensus\_missing\_validators\_power | Gauge | | Total voting power of the missing validators | +| consensus\_byzantine\_validators | Gauge | | Number of validators who tried to double sign | +| consensus\_byzantine\_validators\_power | Gauge | | Total voting power of the byzantine validators | +| consensus\_block\_interval\_seconds | Histogram | | Time between this and last block (Block.Header.Time) in seconds | +| consensus\_rounds | Gauge | | Number of rounds | +| consensus\_num\_txs | Gauge | | Number of transactions | +| consensus\_total\_txs | Gauge | | Total number of transactions committed | +| consensus\_block\_parts | Counter | peer\_id | Number of blockparts transmitted by peer | +| consensus\_latest\_block\_height | Gauge | | /status sync\_info number | +| consensus\_block\_size\_bytes | Gauge | | Block size in bytes | +| consensus\_step\_duration\_seconds | Histogram | step | Histogram of durations for each step in the consensus protocol | +| consensus\_round\_duration\_seconds | Histogram | | Histogram of durations for all the rounds that have occurred since the process started | +| consensus\_block\_gossip\_parts\_received | Counter | matches\_current | Number of block parts received by the node | +| consensus\_quorum\_prevote\_delay | Gauge | proposer\_address | Interval in seconds between the proposal timestamp and the timestamp of the earliest prevote that achieved a quorum | +| consensus\_full\_prevote\_delay | Gauge | proposer\_address | Interval in seconds between the proposal timestamp and the timestamp of the latest prevote in a round where all validators voted | +| consensus\_vote\_extension\_receive\_count | Counter | status | Number of vote extensions received | +| consensus\_proposal\_receive\_count | Counter | status | Total number of proposals received by the node since process start | +| consensus\_proposal\_create\_count | Counter | | Total number of proposals created by the node since process start | +| consensus\_round\_voting\_power\_percent | Gauge | vote\_type | A value between 0 and 1.0 representing the percentage of the total voting power per vote type received within a round | +| consensus\_late\_votes | Counter | vote\_type | Number of votes received by the node since process start that correspond to earlier heights and rounds than this node is currently in. | +| consensus\_duplicate\_vote | Counter | | Number of times we received a duplicate vote. | +| consensus\_duplicate\_block\_part | Counter | | Number of times we received a duplicate block part. | +| consensus\_proposal\_timestamp\_difference | Histogram | is\_timely | Difference between the timestamp in the proposal message and the local time of the validator at the time it received the message. | +| p2p\_message\_send\_bytes\_total | Counter | message\_type | Number of bytes sent to all peers per message type | +| p2p\_message\_receive\_bytes\_total | Counter | message\_type | Number of bytes received from all peers per message type | +| p2p\_peers | Gauge | | Number of peers node's connected to | +| p2p\_peer\_pending\_send\_bytes | Gauge | peer\_id | Number of pending bytes to be sent to a given peer | +| p2p\_recv\_rate\_limiter\_delay | Counter | peer\_id | Time in seconds spent sleeping by the receive rate limiter, in seconds. | +| p2p\_send\_rate\_limiter\_delay | Counter | peer\_id | Time in seconds spent sleeping by the send rate limiter, in seconds. | +| mempool\_size | Gauge | | Number of uncommitted transactions in the mempool | +| mempool\_size\_bytes | Gauge | | Total size of the mempool in bytes | +| mempool\_tx\_size\_bytes | Histogram | | Histogram of transaction sizes in bytes | +| mempool\_evicted\_txs | Counter | | Number of transactions that make it into the mempool and were later evicted for being invalid | +| mempool\_failed\_txs | Counter | | Number of transactions that failed to make it into the mempool for being invalid | +| mempool\_rejected\_txs | Counter | | Number of transactions that failed to make it into the mempool due to resource limits | +| mempool\_recheck\_times | Counter | | Number of times transactions are rechecked in the mempool | +| mempool\_already\_received\_txs | Counter | | Number of times transactions were received more than once | +| mempool\_active\_outbound\_connections | Gauge | | Number of connections being actively used for gossiping transaction (experimental) | +| mempool\_recheck\_duration\_seconds | Gauge | | Cumulative time spent rechecking transactions | +| state\_consensus\_param\_updates | Counter | | Number of consensus parameter updates returned by the application since process start | +| state\_validator\_set\_updates | Counter | | Number of validator set updates returned by the application since process start | +| state\_pruning\_service\_block\_retain\_height | Gauge | | Accepted block retain height set by the data companion | +| state\_pruning\_service\_block\_results\_retain\_height | Gauge | | Accepted block results retain height set by the data companion | +| state\_pruning\_service\_tx\_indexer\_retain\_height | Gauge | | Accepted transactions indices retain height set by the data companion | +| state\_pruning\_service\_block\_indexer\_retain\_height | Gauge | | Accepted blocks indices retain height set by the data companion | +| state\_application\_block\_retain\_height | Gauge | | Accepted block retain height set by the application | +| state\_block\_store\_base\_height | Gauge | | First height at which a block is available | +| state\_abciresults\_base\_height | Gauge | | First height at which ABCI results are available | +| state\_tx\_indexer\_base\_height | Gauge | | First height at which tx indices are available | +| state\_block\_indexer\_base\_height | Gauge | | First height at which block indices are available | +| state\_store\_access\_duration\_seconds | Histogram | method | Duration of accesses to the state store labeled by which method was called on the store | +| state\_fire\_block\_events\_delay\_seconds | Gauge | | Duration of event firing related to a new block | +| statesync\_syncing | Gauge | | Either 0 (not state syncing) or 1 (syncing) | + +## Useful queries + +Percentage of missing + byzantine validators: + +```md +((consensus\_byzantine\_validators\_power + consensus\_missing\_validators\_power) / consensus\_validators\_power) * 100 +``` diff --git a/docs/guides/README.md b/docs/guides/README.md new file mode 100644 index 0000000..8b7130c --- /dev/null +++ b/docs/guides/README.md @@ -0,0 +1,12 @@ +--- +order: false +parent: + order: 2 +--- + +# Guides + +- [Installing CometBFT](./install.md) +- [Quick-start using CometBFT](./quick-start.md) +- [Creating a built-in application in Go](./go-built-in.md) +- [Creating an external application in Go](./go.md) diff --git a/docs/guides/go-built-in.md b/docs/guides/go-built-in.md new file mode 100644 index 0000000..1620665 --- /dev/null +++ b/docs/guides/go-built-in.md @@ -0,0 +1,798 @@ +--- +order: 2 +--- + +# Creating a built-in application in Go + +## Guide Assumptions + +This guide is designed for beginners who want to get started with a CometBFT +application from scratch. It does not assume that you have any prior +experience with CometBFT. + +CometBFT is a service that provides a Byzantine Fault Tolerant consensus engine +for state-machine replication. The replicated state-machine, or "application", can be written +in any language that can send and receive protocol buffer messages in a client-server model. +Applications written in Go can also use CometBFT as a library and run the service in the same +process as the application. + +By following along this tutorial you will create a CometBFT application called kvstore, +a (very) simple distributed BFT key-value store. +The application will be written in Go and +some understanding of the Go programming language is expected. +If you have never written Go, you may want to go through [Learn X in Y minutes +Where X=Go](https://learnxinyminutes.com/docs/go/) first, to familiarize +yourself with the syntax. + +Note: Please use the latest released version of this guide and of CometBFT. +We strongly advise against using unreleased commits for your development. + +### Built-in app vs external app + +On the one hand, to get maximum performance you can run your application in +the same process as the CometBFT, as long as your application is written in Go. +[Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is written +this way. +This is the approach followed in this tutorial. + +On the other hand, having a separate application might give you better security +guarantees as two processes would be communicating via established binary protocol. +CometBFT will not have access to application's state. +If that is the way you wish to proceed, use the [Creating an application in Go](./go.md) guide instead of this one. + +## 1.1 Installing Go + +Verify that you have the latest version of Go installed (refer to the [official guide for installing Go](https://golang.org/doc/install)): + +```bash +$ go version +go version go1.22.11 darwin/amd64 +``` + +## 1.2 Creating a new Go project + +We'll start by creating a new Go project. + +```bash +mkdir kvstore +``` + +Inside the example directory, create a `main.go` file with the following content: + +```go +package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, CometBFT") +} +``` + +When run, this should print "Hello, CometBFT" to the standard output. + +```bash +cd kvstore +$ go run main.go +Hello, CometBFT +``` + +We are going to use [Go modules](https://github.com/golang/go/wiki/Modules) for +dependency management, so let's start by including a dependency on the latest version of +CometBFT, `v0.38.0` in this example. + +```bash +go mod init kvstore +go get github.com/cometbft/cometbft@v0.38.0 +``` + +After running the above commands you will see two generated files, `go.mod` and `go.sum`. +The go.mod file should look similar to: + +```go +module kvstore + +go 1.22 + +require ( +github.com/cometbft/cometbft v0.38.0 +) +``` + +XXX: CometBFT `v0.38.0` uses a slightly outdated `gogoproto` library, which +may fail to compile with newer Go versions. To avoid any compilation errors, +upgrade `gogoproto` manually: + +```bash +go get github.com/cosmos/gogoproto@v1.4.11 +``` + +As you write the kvstore application, you can rebuild the binary by +pulling any new dependencies and recompiling it. + +```bash +go get +go build +``` + +## 1.3 Writing a CometBFT application + +CometBFT communicates with the application through the Application +BlockChain Interface (ABCI). The messages exchanged through the interface are +defined in the ABCI [protobuf +file](https://github.com/cometbft/cometbft/blob/v0.38.x/proto/tendermint/abci/types.proto). + +We begin by creating the basic scaffolding for an ABCI application by +creating a new type, `KVStoreApplication`, which implements the +methods defined by the `abcitypes.Application` interface. + +Create a file called `app.go` with the following contents: + +```go +package main + +import ( + abcitypes "github.com/cometbft/cometbft/abci/types" + "context" +) + +type KVStoreApplication struct{} + +var _ abcitypes.Application = (*KVStoreApplication)(nil) + +func NewKVStoreApplication() *KVStoreApplication { + return &KVStoreApplication{} +} + +func (app *KVStoreApplication) Info(_ context.Context, info *abcitypes.RequestInfo) (*abcitypes.ResponseInfo, error) { + return &abcitypes.ResponseInfo{}, nil +} + +func (app *KVStoreApplication) Query(_ context.Context, req *abcitypes.RequestQuery) (*abcitypes.ResponseQuery, error) { + return &abcitypes.ResponseQuery{}, nil +} + +func (app *KVStoreApplication) CheckTx(_ context.Context, check *abcitypes.RequestCheckTx) (*abcitypes.ResponseCheckTx, error) { + return &abcitypes.ResponseCheckTx{}, nil +} + +func (app *KVStoreApplication) InitChain(_ context.Context, chain *abcitypes.RequestInitChain) (*abcitypes.ResponseInitChain, error) { + return &abcitypes.ResponseInitChain{}, nil +} + +func (app *KVStoreApplication) PrepareProposal(_ context.Context, proposal *abcitypes.RequestPrepareProposal) (*abcitypes.ResponsePrepareProposal, error) { + return &abcitypes.ResponsePrepareProposal{}, nil +} + +func (app *KVStoreApplication) ProcessProposal(_ context.Context, proposal *abcitypes.RequestProcessProposal) (*abcitypes.ResponseProcessProposal, error) { + return &abcitypes.ResponseProcessProposal{}, nil +} + +func (app *KVStoreApplication) FinalizeBlock(_ context.Context, req *abcitypes.RequestFinalizeBlock) (*abcitypes.ResponseFinalizeBlock, error) { + return &abcitypes.ResponseFinalizeBlock{}, nil +} + +func (app KVStoreApplication) Commit(_ context.Context, commit *abcitypes.RequestCommit) (*abcitypes.ResponseCommit, error) { + return &abcitypes.ResponseCommit{}, nil +} + +func (app *KVStoreApplication) ListSnapshots(_ context.Context, snapshots *abcitypes.RequestListSnapshots) (*abcitypes.ResponseListSnapshots, error) { + return &abcitypes.ResponseListSnapshots{}, nil +} + +func (app *KVStoreApplication) OfferSnapshot(_ context.Context, snapshot *abcitypes.RequestOfferSnapshot) (*abcitypes.ResponseOfferSnapshot, error) { + return &abcitypes.ResponseOfferSnapshot{}, nil +} + +func (app *KVStoreApplication) LoadSnapshotChunk(_ context.Context, chunk *abcitypes.RequestLoadSnapshotChunk) (*abcitypes.ResponseLoadSnapshotChunk, error) { + return &abcitypes.ResponseLoadSnapshotChunk{}, nil +} + +func (app *KVStoreApplication) ApplySnapshotChunk(_ context.Context, chunk *abcitypes.RequestApplySnapshotChunk) (*abcitypes.ResponseApplySnapshotChunk, error) { + return &abcitypes.ResponseApplySnapshotChunk{Result: abcitypes.ResponseApplySnapshotChunk_ACCEPT}, nil +} + +func (app KVStoreApplication) ExtendVote(_ context.Context, extend *abcitypes.RequestExtendVote) (*abcitypes.ResponseExtendVote, error) { + return &abcitypes.ResponseExtendVote{}, nil +} + +func (app *KVStoreApplication) VerifyVoteExtension(_ context.Context, verify *abcitypes.RequestVerifyVoteExtension) (*abcitypes.ResponseVerifyVoteExtension, error) { + return &abcitypes.ResponseVerifyVoteExtension{}, nil +} +``` + +The types used here are defined in the CometBFT library and were added as a dependency +to the project when you ran `go get`. If your IDE is not recognizing the types, go ahead and run the command again. + +```bash +go get github.com/cometbft/cometbft@v0.38.0 +``` + +Now go back to the `main.go` and modify the `main` function so it matches the following, +where an instance of the `KVStoreApplication` type is created. + +```go +func main() { + fmt.Println("Hello, CometBFT") + + _ = NewKVStoreApplication() +} +``` + +You can recompile and run the application now by running `go get` and `go build`, but it does +not do anything. +So let's revisit the code adding the logic needed to implement our minimal key/value store +and to start it along with the CometBFT Service. + +### 1.3.1 Add a persistent data store + +Our application will need to write its state out to persistent storage so that it +can stop and start without losing all of its data. + +For this tutorial, we will use [BadgerDB](https://github.com/dgraph-io/badger), a +fast embedded key-value store. + +First, add Badger as a dependency of your go module using the `go get` command: + +`go get github.com/dgraph-io/badger/v3` + +Next, let's update the application and its constructor to receive a handle to the database, as follows: + +```go +type KVStoreApplication struct { + db *badger.DB + onGoingBlock *badger.Txn +} + +var _ abcitypes.Application = (*KVStoreApplication)(nil) + +func NewKVStoreApplication(db *badger.DB) *KVStoreApplication { + return &KVStoreApplication{db: db} +} +``` + +The `onGoingBlock` keeps track of the Badger transaction that will update the application's state when a block +is completed. Don't worry about it for now, we'll get to that later. + +Next, update the `import` stanza at the top to include the Badger library: + +```go +import( + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +Finally, update the `main.go` file to invoke the updated constructor: + +```go + _ = NewKVStoreApplication(nil) +``` + +### 1.3.2 CheckTx + +When CometBFT receives a new transaction from a client, or from another full node, +CometBFT asks the application if the transaction is acceptable, using the `CheckTx` method. +Invalid transactions will not be shared with other nodes and will not become part of any blocks and, therefore, will not be executed by the application. + +In our application, a transaction is a string with the form `key=value`, indicating a key and value to write to the store. + +The most basic validation check we can perform is to check if the transaction conforms to the `key=value` pattern. +For that, let's add the following helper method to app.go: + +```go +func (app *KVStoreApplication) isValid(tx []byte) uint32 { + // check format + parts := bytes.Split(tx, []byte("=")) + if len(parts) != 2 { + return 1 + } + + return 0 +} +``` + +Now you can rewrite the `CheckTx` method to use the helper function: + +```go +func (app *KVStoreApplication) CheckTx(_ context.Context, check *abcitypes.RequestCheckTx) (*abcitypes.ResponseCheckTx, error) { + code := app.isValid(check.Tx) + return &abcitypes.ResponseCheckTx{Code: code}, nil +} +``` + +While this `CheckTx` is simple and only validates that the transaction is well-formed, +it is very common for `CheckTx` to make more complex use of the state of an application. +For example, you may refuse to overwrite an existing value, or you can associate +versions to the key/value pairs and allow the caller to specify a version to +perform a conditional update. + +Depending on the checks and on the conditions violated, the function may return +different values, but any response with a non-zero code will be considered invalid +by CometBFT. Our `CheckTx` logic returns 0 to CometBFT when a transaction passes +its validation checks. The specific value of the code is meaningless to CometBFT. +Non-zero codes are logged by CometBFT so applications can provide more specific +information on why the transaction was rejected. + +Note that `CheckTx` does not execute the transaction, it only verifies that the transaction could be executed. We do not know yet if the rest of the network has agreed to accept this transaction into a block. + +Finally, make sure to add the `bytes` package to the `import` stanza at the top of `app.go`: + +```go +import( + "bytes" + + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +### 1.3.3 FinalizeBlock + +When the CometBFT consensus engine has decided on the block, the block is transferred to the +application via `FinalizeBlock`. +`FinalizeBlock` is an ABCI method introduced in CometBFT `v0.38.0`. This replaces the functionality provided previously (pre-`v0.38.0`) by the combination of ABCI methods `BeginBlock`, `DeliverTx`, and `EndBlock`. `FinalizeBlock`'s parameters are an aggregation of those in `BeginBlock`, `DeliverTx`, and `EndBlock`. + +This method is responsible for executing the block and returning a response to the consensus engine. +Providing a single `FinalizeBlock` method to signal the finalization of a block simplifies the ABCI interface and increases flexibility in the execution pipeline. + +The `FinalizeBlock` method executes the block, including any necessary transaction processing and state updates, and returns a `ResponseFinalizeBlock` object which contains any necessary information about the executed block. + +**Note:** `FinalizeBlock` only prepares the update to be made and does not change the state of the application. The state change is actually committed in a later stage i.e. in `commit` phase. + +Note that, to implement these calls in our application we're going to make use of Badger's transaction mechanism. We will always refer to these as Badger transactions, not to confuse them with the transactions included in the blocks delivered by CometBFT, the _application transactions_. + +First, let's create a new Badger transaction during `FinalizeBlock`. All application transactions in the current block will be executed within this Badger transaction. +Next, let's modify `FinalizeBlock` to add the `key` and `value` to the Badger transaction every time our application processes a new application transaction from the list received through `RequestFinalizeBlock`. + +Note that we check the validity of the transaction _again_ during `FinalizeBlock`. + +```go +func (app *KVStoreApplication) FinalizeBlock(_ context.Context, req *abcitypes.RequestFinalizeBlock) (*abcitypes.ResponseFinalizeBlock, error) { + var txs = make([]*abcitypes.ExecTxResult, len(req.Txs)) + + app.onGoingBlock = app.db.NewTransaction(true) + for i, tx := range req.Txs { + if code := app.isValid(tx); code != 0 { + log.Printf("Error: invalid transaction index %v", i) + txs[i] = &abcitypes.ExecTxResult{Code: code} + } else { + parts := bytes.SplitN(tx, []byte("="), 2) + key, value := parts[0], parts[1] + log.Printf("Adding key %s with value %s", key, value) + + if err := app.onGoingBlock.Set(key, value); err != nil { + log.Panicf("Error writing to database, unable to execute tx: %v", err) + } + + log.Printf("Successfully added key %s with value %s", key, value) + + txs[i] = &abcitypes.ExecTxResult{} + } + } + + return &abcitypes.ResponseFinalizeBlock{ + TxResults: txs, + }, nil +} +``` + +Transactions are not guaranteed to be valid when they are delivered to an application, even if they were valid when they were proposed. + +This can happen if the application state is used to determine transaction validity. +The application state may have changed between the initial execution of `CheckTx` and the transaction delivery in `FinalizeBlock` in a way that rendered the transaction no longer valid. + +**Note** that `FinalizeBlock` cannot yet commit the Badger transaction we were building during the block execution. + +Other methods, such as `Query`, rely on a consistent view of the application's state, the application should only update its state by committing the Badger transactions when the full block has been delivered and the Commit method is invoked. + +The `Commit` method tells the application to make permanent the effects of +the application transactions. +Let's update the method to terminate the pending Badger transaction and +persist the resulting state: + +```go +func (app KVStoreApplication) Commit(_ context.Context, commit *abcitypes.RequestCommit) (*abcitypes.ResponseCommit, error) { + return &abcitypes.ResponseCommit{}, app.onGoingBlock.Commit() +} +``` + +Finally, make sure to add the log library to the `import` stanza as well: + +```go +import ( + "bytes" + "log" + + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +You may have noticed that the application we are writing will crash if it receives +an unexpected error from the Badger database during the `FinalizeBlock` or `Commit` methods. +This is not an accident. If the application received an error from the database, there +is no deterministic way for it to make progress so the only safe option is to terminate. +Once the application is restarted, the transactions in the block that failed execution will +be re-executed and should succeed if the Badger error was transient. + +### 1.3.4 Query + +When a client tries to read some information from the `kvstore`, the request will be +handled in the `Query` method. To do this, let's rewrite the `Query` method in `app.go`: + +```go +func (app *KVStoreApplication) Query(_ context.Context, req *abcitypes.RequestQuery) (*abcitypes.ResponseQuery, error) { + resp := abcitypes.ResponseQuery{Key: req.Data} + + dbErr := app.db.View(func(txn *badger.Txn) error { + item, err := txn.Get(req.Data) + if err != nil { + if err != badger.ErrKeyNotFound { + return err + } + resp.Log = "key does not exist" + return nil + } + + return item.Value(func(val []byte) error { + resp.Log = "exists" + resp.Value = val + return nil + }) + }) + if dbErr != nil { + log.Panicf("Error reading database, unable to execute query: %v", dbErr) + } + return &resp, nil +} +``` + +Since it reads only committed data from the store, transactions that are part of a block +that is being processed are not reflected in the query result. + +### 1.3.5 PrepareProposal and ProcessProposal + +`PrepareProposal` and `ProcessProposal` are methods introduced in CometBFT v0.37.0 +to give the application more control over the construction and processing of transaction blocks. + +When CometBFT sees that valid transactions (validated through `CheckTx`) are available to be +included in blocks, it groups some of these transactions and then gives the application a chance +to modify the group by invoking `PrepareProposal`. + +The application is free to modify the group before returning from the call, as long as the resulting set +does not use more bytes than `RequestPrepareProposal.max_tx_bytes` +For example, the application may reorder, add, or even remove transactions from the group to improve the +execution of the block once accepted. + +In the following code, the application simply returns the unmodified group of transactions: + +```go +func (app *KVStoreApplication) PrepareProposal(_ context.Context, proposal *abcitypes.RequestPrepareProposal) (*abcitypes.ResponsePrepareProposal, error) { + return &abcitypes.ResponsePrepareProposal{Txs: proposal.Txs}, nil +} +``` + +Once a proposed block is received by a node, the proposal is passed to the application to give +its blessing before voting to accept the proposal. + +This mechanism may be used for different reasons, for example to deal with blocks manipulated +by malicious nodes, in which case the block should not be considered valid. + +The following code simply accepts all proposals: + +```go +func (app *KVStoreApplication) ProcessProposal(_ context.Context, proposal *abcitypes.RequestProcessProposal) (*abcitypes.ResponseProcessProposal, error) { + return &abcitypes.ResponseProcessProposal{Status: abcitypes.ResponseProcessProposal_ACCEPT}, nil +} +``` + +## 1.4 Starting an application and a CometBFT instance in the same process + +Now that we have the basic functionality of our application in place, let's put +it all together inside of our `main.go` file. + +Change the contents of your `main.go` file to the following. + +```go +package main + +import ( + "flag" + "fmt" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + "log" + "os" + "os/signal" + "path/filepath" + "syscall" + + "github.com/dgraph-io/badger/v3" + "github.com/spf13/viper" + cfg "github.com/cometbft/cometbft/config" + cmtflags "github.com/cometbft/cometbft/libs/cli/flags" + cmtlog "github.com/cometbft/cometbft/libs/log" + nm "github.com/cometbft/cometbft/node" +) + +var homeDir string + +func init() { + flag.StringVar(&homeDir, "cmt-home", "", "Path to the CometBFT config directory (if empty, uses $HOME/.cometbft)") +} + +func main() { + flag.Parse() + if homeDir == "" { + homeDir = os.ExpandEnv("$HOME/.cometbft") + } + + config := cfg.DefaultConfig() + config.SetRoot(homeDir) + viper.SetConfigFile(fmt.Sprintf("%s/%s", homeDir, "config/config.toml")) + + if err := viper.ReadInConfig(); err != nil { + log.Fatalf("Reading config: %v", err) + } + if err := viper.Unmarshal(config); err != nil { + log.Fatalf("Decoding config: %v", err) + } + if err := config.ValidateBasic(); err != nil { + log.Fatalf("Invalid configuration data: %v", err) + } + dbPath := filepath.Join(homeDir, "badger") + db, err := badger.Open(badger.DefaultOptions(dbPath)) + + if err != nil { + log.Fatalf("Opening database: %v", err) + } + defer func() { + if err := db.Close(); err != nil { + log.Printf("Closing database: %v", err) + } + }() + + app := NewKVStoreApplication(db) + + pv := privval.LoadFilePV( + config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile(), + ) + + nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) + if err != nil { + log.Fatalf("failed to load node's key: %v", err) + } + + logger := cmtlog.NewTMLogger(cmtlog.NewSyncWriter(os.Stdout)) + logger, err = cmtflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel) + + if err != nil { + log.Fatalf("failed to parse log level: %v", err) + } + + node, err := nm.NewNode( + config, + pv, + nodeKey, + proxy.NewLocalClientCreator(app), + nm.DefaultGenesisDocProviderFunc(config), + cfg.DefaultDBProvider, + nm.DefaultMetricsProvider(config.Instrumentation), + logger, + ) + + if err != nil { + log.Fatalf("Creating node: %v", err) + } + + node.Start() + defer func() { + node.Stop() + node.Wait() + }() + + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + <-c +} +``` + +This is a huge blob of code, so let's break it down into pieces. + +First, we use [viper](https://github.com/spf13/viper) to load the CometBFT configuration files, which we will generate later: + +```go +config := cfg.DefaultValidatorConfig() + +config.SetRoot(homeDir) + +viper.SetConfigFile(fmt.Sprintf("%s/%s", homeDir, "config/config.toml")) +if err := viper.ReadInConfig(); err != nil { + log.Fatalf("Reading config: %v", err) +} +if err := viper.Unmarshal(config); err != nil { + log.Fatalf("Decoding config: %v", err) +} +if err := config.ValidateBasic(); err != nil { + log.Fatalf("Invalid configuration data: %v", err) +} +``` + +Next, we initialize the Badger database and create an app instance. + +```go +dbPath := filepath.Join(homeDir, "badger") +db, err := badger.Open(badger.DefaultOptions(dbPath)) +if err != nil { + log.Fatalf("Opening database: %v", err) +} +defer func() { + if err := db.Close(); err != nil { + log.Fatalf("Closing database: %v", err) + } +}() + +app := NewKVStoreApplication(db) +``` + +We use `FilePV`, which is a private validator (i.e. thing which signs consensus +messages). Normally, you would use `SignerRemote` to connect to an external +[HSM](https://kb.certus.one/hsm.html). + +```go +pv := privval.LoadFilePV( + config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile(), +) +``` + +`nodeKey` is needed to identify the node in a p2p network. + +```go +nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) +if err != nil { + return nil, fmt.Errorf("failed to load node's key: %w", err) +} +``` + +Now we have everything set up to run the CometBFT node. We construct +a node by passing it the configuration, the logger, a handle to our application and +the genesis information: + +```go +node, err := nm.NewNode( + config, + pv, + nodeKey, + proxy.NewLocalClientCreator(app), + nm.DefaultGenesisDocProviderFunc(config), + cfg.DefaultDBProvider, + nm.DefaultMetricsProvider(config.Instrumentation), + logger) + +if err != nil { + log.Fatalf("Creating node: %v", err) +} +``` + +Finally, we start the node, i.e., the CometBFT service inside our application: + +```go +node.Start() +defer func() { + node.Stop() + node.Wait() +}() +``` + +The additional logic at the end of the file allows the program to catch SIGTERM. This means that the node can shut down gracefully when an operator tries to kill the program: + +```go +c := make(chan os.Signal, 1) +signal.Notify(c, os.Interrupt, syscall.SIGTERM) +<-c +``` + +## 1.5 Initializing and Running + +Our application is almost ready to run, but first we'll need to populate the CometBFT configuration files. +The following command will create a `cometbft-home` directory in your project and add a basic set of configuration files in `cometbft-home/config/`. +For more information on what these files contain see [the configuration documentation](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/core/configuration.md). + +From the root of your project, run: + +```bash +go run github.com/cometbft/cometbft/cmd/cometbft@v0.38.0 init --home /tmp/cometbft-home +``` + +You should see an output similar to the following: + +```bash +I[2023-25-04|09:06:34.444] Generated private validator module=main keyFile=/tmp/cometbft-home/config/priv_validator_key.json stateFile=/tmp/cometbft-home/data/priv_validator_state.json +I[2023-25-04|09:06:34.444] Generated node key module=main path=/tmp/cometbft-home/config/node_key.json +I[2023-25-04|09:06:34.444] Generated genesis file module=main path=/tmp/cometbft-home/config/genesis.json +``` + +Now rebuild the app: + +```bash +go build -mod=mod # use -mod=mod to automatically refresh the dependencies +``` + +Everything is now in place to run your application. Run: + +```bash +./kvstore -cmt-home /tmp/cometbft-home +``` + +The application will start and you should see a continuous output starting with: + +```bash +badger 2023-04-25 09:08:50 INFO: All 0 tables opened in 0s +badger 2023-04-25 09:08:50 INFO: Discard stats nextEmptySlot: 0 +badger 2023-04-25 09:08:50 INFO: Set nextTxnTs to 0 +I[2023-04-25|09:08:50.085] service start module=proxy msg="Starting multiAppConn service" impl=multiAppConn +I[2023-04-25|09:08:50.085] service start module=abci-client connection=query msg="Starting localClient service" impl=localClient +I[2023-04-25|09:08:50.085] service start module=abci-client connection=snapshot msg="Starting localClient service" impl=localClient +... +``` + +More importantly, the application using CometBFT is producing blocks 🎉🎉 and you can see this reflected in the log output in lines like this: + +```bash +I[2023-04-25|09:08:52.147] received proposal module=consensus proposal="Proposal{2/0 (F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C:1:C73D3D1273F2, -1) AD19AE292A45 @ 2023-04-25T12:08:52.143393Z}" +I[2023-04-25|09:08:52.152] received complete proposal block module=consensus height=2 hash=F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C +I[2023-04-25|09:08:52.160] finalizing commit of block module=consensus height=2 hash=F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C root= num_txs=0 +I[2023-04-25|09:08:52.167] executed block module=state height=2 num_valid_txs=0 num_invalid_txs=0 +I[2023-04-25|09:08:52.171] committed state module=state height=2 num_txs=0 app_hash= +``` + +The blocks, as you can see from the `num_valid_txs=0` part, are empty, but let's remedy that next. + +## 1.6 Using the application + +Let's try submitting a transaction to our new application. +Open another terminal window and run the following curl command: + +```bash +curl -s 'localhost:26657/broadcast_tx_commit?tx="cometbft=rocks"' +``` + +If everything went well, you should see a response indicating which height the +transaction was included in the blockchain. + +Finally, let's make sure that transaction really was persisted by the application. +Run the following command: + +```bash +curl -s 'localhost:26657/abci_query?data="cometbft"' +``` + +Let's examine the response object that this request returns. +The request returns a `json` object with a `key` and `value` field set. + +```json +... + "key": "dGVuZGVybWludA==", + "value": "cm9ja3M=", +... +``` + +Those values don't look like the `key` and `value` we sent to CometBFT. +What's going on here? + +The response contains a `base64` encoded representation of the data we submitted. +To get the original value out of this data, we can use the `base64` command line utility: + +```bash +echo "cm9ja3M=" | base64 -d +``` + +## Outro + +Hope you could run everything smoothly. If you have any difficulties running through this tutorial, reach out to us via [discord](https://discord.com/invite/interchain) or open a new [issue](https://github.com/cometbft/cometbft/issues/new/choose) on Github. diff --git a/docs/guides/go.md b/docs/guides/go.md new file mode 100644 index 0000000..606a6a5 --- /dev/null +++ b/docs/guides/go.md @@ -0,0 +1,710 @@ +--- +order: 1 +--- + +# Creating an application in Go + +## Guide Assumptions + +This guide is designed for beginners who want to get started with a CometBFT +application from scratch. It does not assume that you have any prior +experience with CometBFT. + +CometBFT is a service that provides a Byzantine Fault Tolerant consensus engine +for state-machine replication. The replicated state-machine, or "application", can be written +in any language that can send and receive protocol buffer messages in a client-server model. +Applications written in Go can also use CometBFT as a library and run the service in the same +process as the application. + +By following along this tutorial you will create a CometBFT application called kvstore, +a (very) simple distributed BFT key-value store. +The application will be written in Go and +some understanding of the Go programming language is expected. +If you have never written Go, you may want to go through [Learn X in Y minutes +Where X=Go](https://learnxinyminutes.com/docs/go/) first, to familiarize +yourself with the syntax. + +Note: Please use the latest released version of this guide and of CometBFT. +We strongly advise against using unreleased commits for your development. + +### Built-in app vs external app + +On the one hand, to get maximum performance you can run your application in +the same process as the CometBFT, as long as your application is written in Go. +[Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is written +this way. +If that is the way you wish to proceed, use the [Creating a built-in application in Go](./go-built-in.md) guide instead of this one. + +On the other hand, having a separate application might give you better security +guarantees as two processes would be communicating via established binary protocol. +CometBFT will not have access to application's state. +This is the approach followed in this tutorial. + +## 1.1 Installing Go + +Verify that you have the latest version of Go installed (refer to the [official guide for installing Go](https://golang.org/doc/install)): + +```bash +$ go version +go version go1.22.11 darwin/amd64 +``` + +## 1.2 Creating a new Go project + +We'll start by creating a new Go project. + +```bash +mkdir kvstore +``` + +Inside the example directory, create a `main.go` file with the following content: + +```go +package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, CometBFT") +} +``` + +When run, this should print "Hello, CometBFT" to the standard output. + +```bash +cd kvstore +$ go run main.go +Hello, CometBFT +``` + +We are going to use [Go modules](https://github.com/golang/go/wiki/Modules) for +dependency management, so let's start by including a dependency on the latest version of +CometBFT, `v0.38.0` in this example. + +```bash +go mod init kvstore +go get github.com/cometbft/cometbft@v0.38.0 +``` + +After running the above commands you will see two generated files, `go.mod` and `go.sum`. +The go.mod file should look similar to: + +```go +module kvstore + +go 1.22 + +require ( +github.com/cometbft/cometbft v0.38.0 +) +``` + +XXX: CometBFT `v0.38.0` uses a slightly outdated `gogoproto` library, which +may fail to compile with newer Go versions. To avoid any compilation errors, +upgrade `gogoproto` manually: + +```bash +go get github.com/cosmos/gogoproto@v1.4.11 +``` + +As you write the kvstore application, you can rebuild the binary by +pulling any new dependencies and recompiling it. + +```bash +go get +go build +``` + +## 1.3 Writing a CometBFT application + +CometBFT communicates with the application through the Application +BlockChain Interface (ABCI). The messages exchanged through the interface are +defined in the ABCI [protobuf +file](https://github.com/cometbft/cometbft/blob/v0.38.x/proto/tendermint/abci/types.proto). + +We begin by creating the basic scaffolding for an ABCI application by +creating a new type, `KVStoreApplication`, which implements the +methods defined by the `abcitypes.Application` interface. + +Create a file called `app.go` with the following contents: + +```go +package main + +import ( + abcitypes "github.com/cometbft/cometbft/abci/types" + "context" +) + +type KVStoreApplication struct{} + +var _ abcitypes.Application = (*KVStoreApplication)(nil) + +func NewKVStoreApplication() *KVStoreApplication { + return &KVStoreApplication{} +} + +func (app *KVStoreApplication) Info(_ context.Context, info *abcitypes.RequestInfo) (*abcitypes.ResponseInfo, error) { + return &abcitypes.ResponseInfo{}, nil +} + +func (app *KVStoreApplication) Query(_ context.Context, req *abcitypes.RequestQuery) (*abcitypes.ResponseQuery, error) { + return &abcitypes.ResponseQuery{}, nil +} + +func (app *KVStoreApplication) CheckTx(_ context.Context, check *abcitypes.RequestCheckTx) (*abcitypes.ResponseCheckTx, error) { + return &abcitypes.ResponseCheckTx{Code: code}, nil +} + +func (app *KVStoreApplication) InitChain(_ context.Context, chain *abcitypes.RequestInitChain) (*abcitypes.ResponseInitChain, error) { + return &abcitypes.ResponseInitChain{}, nil +} + +func (app *KVStoreApplication) PrepareProposal(_ context.Context, proposal *abcitypes.RequestPrepareProposal) (*abcitypes.ResponsePrepareProposal, error) { + return &abcitypes.ResponsePrepareProposal{}, nil +} + +func (app *KVStoreApplication) ProcessProposal(_ context.Context, proposal *abcitypes.RequestProcessProposal) (*abcitypes.ResponseProcessProposal, error) { + return &abcitypes.ResponseProcessProposal{}, nil +} + +func (app *KVStoreApplication) FinalizeBlock(_ context.Context, req *abcitypes.RequestFinalizeBlock) (*abcitypes.ResponseFinalizeBlock, error) { + return &abcitypes.ResponseFinalizeBlock{}, nil +} + +func (app KVStoreApplication) Commit(_ context.Context, commit *abcitypes.RequestCommit) (*abcitypes.ResponseCommit, error) { + return &abcitypes.ResponseCommit{}, nil +} + +func (app *KVStoreApplication) ListSnapshots(_ context.Context, snapshots *abcitypes.RequestListSnapshots) (*abcitypes.ResponseListSnapshots, error) { + return &abcitypes.ResponseListSnapshots{}, nil +} + +func (app *KVStoreApplication) OfferSnapshot(_ context.Context, snapshot *abcitypes.RequestOfferSnapshot) (*abcitypes.ResponseOfferSnapshot, error) { + return &abcitypes.ResponseOfferSnapshot{}, nil +} + +func (app *KVStoreApplication) LoadSnapshotChunk(_ context.Context, chunk *abcitypes.RequestLoadSnapshotChunk) (*abcitypes.ResponseLoadSnapshotChunk, error) { + return &abcitypes.ResponseLoadSnapshotChunk{}, nil +} + +func (app *KVStoreApplication) ApplySnapshotChunk(_ context.Context, chunk *abcitypes.RequestApplySnapshotChunk) (*abcitypes.ResponseApplySnapshotChunk, error) { + + return &abcitypes.ResponseApplySnapshotChunk{Result: abcitypes.ResponseApplySnapshotChunk_ACCEPT}, nil +} + +func (app KVStoreApplication) ExtendVote(_ context.Context, extend *abcitypes.RequestExtendVote) (*abcitypes.ResponseExtendVote, error) { + return &abcitypes.ResponseExtendVote{}, nil +} + +func (app *KVStoreApplication) VerifyVoteExtension(_ context.Context, verify *abcitypes.RequestVerifyVoteExtension) (*abcitypes.ResponseVerifyVoteExtension, error) { + return &abcitypes.ResponseVerifyVoteExtension{}, nil +} +``` + +The types used here are defined in the CometBFT library and were added as a dependency +to the project when you ran `go get`. If your IDE is not recognizing the types, go ahead and run the command again. + +```bash +go get github.com/cometbft/cometbft@v0.38.0 +``` + +Now go back to the `main.go` and modify the `main` function so it matches the following, +where an instance of the `KVStoreApplication` type is created. + +```go +func main() { + fmt.Println("Hello, CometBFT") + + _ = NewKVStoreApplication() +} +``` + +You can recompile and run the application now by running `go get` and `go build`, but it does +not do anything. +So let's revisit the code adding the logic needed to implement our minimal key/value store +and to start it along with the CometBFT Service. + +### 1.3.1 Add a persistent data store + +Our application will need to write its state out to persistent storage so that it +can stop and start without losing all of its data. + +For this tutorial, we will use [BadgerDB](https://github.com/dgraph-io/badger), a +a fast embedded key-value store. + +First, add Badger as a dependency of your go module using the `go get` command: + +`go get github.com/dgraph-io/badger/v3` + +Next, let's update the application and its constructor to receive a handle to the database, as follows: + +```go +type KVStoreApplication struct { + db *badger.DB + onGoingBlock *badger.Txn +} + +var _ abcitypes.Application = (*KVStoreApplication)(nil) + +func NewKVStoreApplication(db *badger.DB) *KVStoreApplication { + return &KVStoreApplication{db: db} +} +``` + +The `onGoingBlock` keeps track of the Badger transaction that will update the application's state when a block +is completed. Don't worry about it for now, we'll get to that later. + +Next, update the `import` stanza at the top to include the Badger library: + +```go +import( + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +Finally, update the `main.go` file to invoke the updated constructor: + +```go +_ = NewKVStoreApplication(nil) +``` + +### 1.3.2 CheckTx + +When CometBFT receives a new transaction from a client, or from another full node, +CometBFT asks the application if the transaction is acceptable, using the `CheckTx` method. +Invalid transactions will not be shared with other nodes and will not become part of any blocks and, therefore, will not be executed by the application. + +In our application, a transaction is a string with the form `key=value`, indicating a key and value to write to the store. + +The most basic validation check we can perform is to check if the transaction conforms to the `key=value` pattern. +For that, let's add the following helper method to app.go: + +```go +func (app *KVStoreApplication) isValid(tx []byte) uint32 { + // check format + parts := bytes.Split(tx, []byte("=")) + if len(parts) != 2 { + return 1 + } + return 0 +} +``` + +Now you can rewrite the `CheckTx` method to use the helper function: + +```go +func (app *KVStoreApplication) CheckTx(_ context.Context, check *abcitypes.RequestCheckTx) (*abcitypes.ResponseCheckTx, error) { + code := app.isValid(check.Tx) + return &abcitypes.ResponseCheckTx{Code: code}, nil +} +``` + +While this `CheckTx` is simple and only validates that the transaction is well-formed, +it is very common for `CheckTx` to make more complex use of the state of an application. +For example, you may refuse to overwrite an existing value, or you can associate +versions to the key/value pairs and allow the caller to specify a version to +perform a conditional update. + +Depending on the checks and on the conditions violated, the function may return +different values, but any response with a non-zero code will be considered invalid +by CometBFT. Our `CheckTx` logic returns 0 to CometBFT when a transaction passes +its validation checks. The specific value of the code is meaningless to CometBFT. +Non-zero codes are logged by CometBFT so applications can provide more specific +information on why the transaction was rejected. + +Note that `CheckTx` does not execute the transaction, it only verifies that that the transaction could be executed. We do not know yet if the rest of the network has agreed to accept this transaction into a block. + +Finally, make sure to add the bytes package to the `import` stanza at the top of `app.go`: + +```go +import( + "bytes" + + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +### 1.3.3 FinalizeBlock + +When the CometBFT consensus engine has decided on the block, the block is transferred to the +application via the `FinalizeBlock` method. +`FinalizeBlock` is an ABCI method introduced in CometBFT `v0.38.0`. This replaces the functionality provided previously (pre-`v0.38.0`) by the combination of ABCI methods `BeginBlock`, `DeliverTx`, and `EndBlock`. +`FinalizeBlock`'s parameters are an aggregation of those in `BeginBlock`, `DeliverTx`, and `EndBlock`. + +This method is responsible for executing the block and returning a response to the consensus engine. +Providing a single `FinalizeBlock` method to signal the finalization of a block simplifies the ABCI interface and increases flexibility in the execution pipeline. + +The `FinalizeBlock` method executes the block, including any necessary transaction processing and state updates, and returns a `ResponseFinalizeBlock` object which contains any necessary information about the executed block. + +**Note:** `FinalizeBlock` only prepares the update to be made and does not change the state of the application. The state change is actually committed in a later stage i.e. in `commit` phase. + +Note that, to implement these calls in our application we're going to make use of Badger's transaction mechanism. We will always refer to these as Badger transactions, not to confuse them with the transactions included in the blocks delivered by CometBFT, the _application transactions_. + +First, let's create a new Badger transaction during `FinalizeBlock`. All application transactions in the current block will be executed within this Badger transaction. +Next, let's modify `FinalizeBlock` to add the `key` and `value` to the database transaction every time our application processes a new application transaction from the list received through `RequestFinalizeBlock`. + +Note that we check the validity of the transaction _again_ during `FinalizeBlock`. + +```go +func (app *KVStoreApplication) FinalizeBlock(_ context.Context, req *abcitypes.RequestFinalizeBlock) (*abcitypes.ResponseFinalizeBlock, error) { + var txs = make([]*abcitypes.ExecTxResult, len(req.Txs)) + + app.onGoingBlock = app.db.NewTransaction(true) + for i, tx := range req.Txs { + if code := app.isValid(tx); code != 0 { + log.Printf("Error in tx in if") + txs[i] = &abcitypes.ExecTxResult{Code: code} + } else { + parts := bytes.SplitN(tx, []byte("="), 2) + key, value := parts[0], parts[1] + log.Printf("Adding key %s with value %s", key, value) + + if err := app.onGoingBlock.Set(key, value); err != nil { + log.Panicf("Error writing to database, unable to execute tx: %v", err) + } + log.Printf("Successfully added key %s with value %s", key, value) + + txs[i] = &abcitypes.ExecTxResult{} + } + } + + return &abcitypes.ResponseFinalizeBlock{ + TxResults: txs, + }, nil +} +``` + +Transactions are not guaranteed to be valid when they are delivered to an application, even if they were valid when they were proposed. + +This can happen if the application state is used to determine transaction validity. The application state may have changed between the initial execution of `CheckTx` and the transaction delivery in `FinalizeBlock` in a way that rendered the transaction no longer valid. + +**Note** that `FinalizeBlock` cannot yet commit the Badger transaction we were building during the block execution. + +Other methods, such as `Query`, rely on a consistent view of the application's state, the application should only update its state by committing the Badger transactions when the full block has been delivered and the `Commit` method is invoked. + +The `Commit` method tells the application to make permanent the effects of the application transactions. +Let's update the method to terminate the pending Badger transaction and persist the resulting state: + +```go +func (app KVStoreApplication) Commit(_ context.Context, commit *abcitypes.RequestCommit) (*abcitypes.ResponseCommit, error) { + return &abcitypes.ResponseCommit{}, app.onGoingBlock.Commit() +} +``` + +Finally, make sure to add the log library to the `import` stanza as well: + +```go +import ( + "bytes" + "log" + + "github.com/dgraph-io/badger/v3" + abcitypes "github.com/cometbft/cometbft/abci/types" +) +``` + +You may have noticed that the application we are writing will crash if it receives +an unexpected error from the Badger database during the `FinalizeBlock` or `Commit` methods. +This is not an accident. If the application received an error from the database, there +is no deterministic way for it to make progress so the only safe option is to terminate. + +### 1.3.4 Query + +When a client tries to read some information from the `kvstore`, the request will be +handled in the `Query` method. To do this, let's rewrite the `Query` method in `app.go`: + +```go +func (app *KVStoreApplication) Query(_ context.Context, req *abcitypes.RequestQuery) (*abcitypes.ResponseQuery, error) { + resp := abcitypes.ResponseQuery{Key: req.Data} + + dbErr := app.db.View(func(txn *badger.Txn) error { + item, err := txn.Get(req.Data) + if err != nil { + if err != badger.ErrKeyNotFound { + return err + } + resp.Log = "key does not exist" + return nil + } + + return item.Value(func(val []byte) error { + resp.Log = "exists" + resp.Value = val + return nil + }) + }) + if dbErr != nil { + log.Panicf("Error reading database, unable to execute query: %v", dbErr) + } + return &resp, nil +} +``` + +Since it reads only committed data from the store, transactions that are part of a block +that is being processed are not reflected in the query result. + +### 1.3.5 PrepareProposal and ProcessProposal + +`PrepareProposal` and `ProcessProposal` are methods introduced in CometBFT v0.37.0 +to give the application more control over the construction and processing of transaction blocks. + +When CometBFT sees that valid transactions (validated through `CheckTx`) are available to be +included in blocks, it groups some of these transactions and then gives the application a chance +to modify the group by invoking `PrepareProposal`. + +The application is free to modify the group before returning from the call, as long as the resulting set +does not use more bytes than `RequestPrepareProposal.max_tx_bytes`. +For example, the application may reorder, add, or even remove transactions from the group to improve the +execution of the block once accepted. + +In the following code, the application simply returns the unmodified group of transactions: + +```go +func (app *KVStoreApplication) PrepareProposal(_ context.Context, proposal *abcitypes.RequestPrepareProposal) (*abcitypes.ResponsePrepareProposal, error) { + return &abcitypes.ResponsePrepareProposal{Txs: proposal.Txs}, nil +} +``` + +Once a proposed block is received by a node, the proposal is passed to the +application to determine its validity before voting to accept the proposal. + +This mechanism may be used for different reasons, for example to deal with blocks manipulated +by malicious nodes, in which case the block should not be considered valid. + +The following code simply accepts all proposals: + +```go +func (app *KVStoreApplication) ProcessProposal(_ context.Context, proposal *abcitypes.RequestProcessProposal) (*abcitypes.ResponseProcessProposal, error) { + return &abcitypes.ResponseProcessProposal{Status: abcitypes.ResponseProcessProposal_ACCEPT}, nil +} +``` + +## 1.4 Starting an application and a CometBFT instance + +Now that we have the basic functionality of our application in place, let's put +it all together inside of our `main.go` file. + +Change the contents of your `main.go` file to the following. + +```go +package main + +import ( + "flag" + "fmt" + abciserver "github.com/cometbft/cometbft/abci/server" + "log" + "os" + "os/signal" + "path/filepath" + "syscall" + + "github.com/dgraph-io/badger/v3" + cmtlog "github.com/cometbft/cometbft/libs/log" +) + +var homeDir string +var socketAddr string + +func init() { + flag.StringVar(&homeDir, "kv-home", "", "Path to the kvstore directory (if empty, uses $HOME/.kvstore)") + flag.StringVar(&socketAddr, "socket-addr", "unix://example.sock", "Unix domain socket address (if empty, uses \"unix://example.sock\"") +} + +func main() { + flag.Parse() + if homeDir == "" { + homeDir = os.ExpandEnv("$HOME/.kvstore") + } + + dbPath := filepath.Join(homeDir, "badger") + db, err := badger.Open(badger.DefaultOptions(dbPath)) + if err != nil { + log.Fatalf("Opening database: %v", err) + } + + defer func() { + if err := db.Close(); err != nil { + log.Fatalf("Closing database: %v", err) + } + }() + + app := NewKVStoreApplication(db) + logger := cmtlog.NewTMLogger(cmtlog.NewSyncWriter(os.Stdout)) + + server := abciserver.NewSocketServer(socketAddr, app) + server.SetLogger(logger) + + if err := server.Start(); err != nil { + fmt.Fprintf(os.Stderr, "error starting socket server: %v", err) + + os.Exit(1) + } + defer server.Stop() + + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + <-c +} +``` + +This is a huge blob of code, so let's break it down into pieces. + +First, we initialize the Badger database and create an app instance: + +```go +dbPath := filepath.Join(homeDir, "badger") +db, err := badger.Open(badger.DefaultOptions(dbPath)) +if err != nil { + log.Fatalf("Opening database: %v", err) +} +defer func() { + if err := db.Close(); err != nil { + log.Fatalf("Closing database: %v", err) + } +}() + +app := NewKVStoreApplication(db) +``` + +Then we start the ABCI server and add some signal handling to gracefully stop +it upon receiving SIGTERM or Ctrl-C. CometBFT will act as a client, +which connects to our server and send us transactions and other messages. + +```go +server := abciserver.NewSocketServer(socketAddr, app) +server.SetLogger(logger) + +if err := server.Start(); err != nil { + fmt.Fprintf(os.Stderr, "error starting socket server: %v", err) + os.Exit(1) +} +defer server.Stop() + +c := make(chan os.Signal, 1) +signal.Notify(c, os.Interrupt, syscall.SIGTERM) +<-c +``` + +## 1.5 Initializing and Running + +Our application is almost ready to run, but first we'll need to populate the CometBFT configuration files. +The following command will create a `cometbft-home` directory in your project and add a basic set of configuration files in `cometbft-home/config/`. +For more information on what these files contain see [the configuration documentation](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/core/configuration.md). + +From the root of your project, run: + +```bash +go run github.com/cometbft/cometbft/cmd/cometbft@v0.38.0 init --home /tmp/cometbft-home +``` + +You should see an output similar to the following: + +```bash +I[2023-04-25|09:06:34.444] Generated private validator module=main keyFile=/tmp/cometbft-home/config/priv_validator_key.json stateFile=/tmp/cometbft-home/data/priv_validator_state.json +I[2023-04-25|09:06:34.444] Generated node key module=main path=/tmp/cometbft-home/config/node_key.json +I[2023-04-25|09:06:34.444] Generated genesis file module=main path=/tmp/cometbft-home/config/genesis.json +``` + +Now rebuild the app: + +```bash +go build -mod=mod # use -mod=mod to automatically refresh the dependencies +``` + +Everything is now in place to run your application. Run: + +```bash +./kvstore -kv-home /tmp/badger-home +``` + +The application will start and you should see an output similar to the following: + +```bash +badger 2023-04-25 17:01:28 INFO: All 0 tables opened in 0s +badger 2023-04-25 17:01:28 INFO: Discard stats nextEmptySlot: 0 +badger 2023-04-25 17:01:28 INFO: Set nextTxnTs to 0 +I[2023-04-25|17:01:28.726] service start msg="Starting ABCIServer service" impl=ABCIServer +I[2023-04-25|17:01:28.726] Waiting for new connection... +``` + +Then we need to start CometBFT service and point it to our application. +Open a new terminal window and cd to the same folder where the app is running. +Then execute the following command: + +```bash +go run github.com/cometbft/cometbft/cmd/cometbft@v0.38.0 node --home /tmp/cometbft-home --proxy_app=unix://example.sock +``` + +This should start the full node and connect to our ABCI application, which will be +reflected in the application output. + +```sh +I[2023-04-25|17:07:08.124] service start msg="Starting ABCIServer service" impl=ABCIServer +I[2023-04-25|17:07:08.124] Waiting for new connection... +I[2023-04-25|17:08:12.702] Accepted a new connection +I[2023-04-25|17:08:12.703] Waiting for new connection... +I[2023-04-25|17:08:12.703] Accepted a new connection +I[2023-04-25|17:08:12.703] Waiting for new connection... +``` + +Also, the application using CometBFT Core is producing blocks 🎉🎉 and you can see this reflected in the log output of the service in lines like this: + +```bash +I[2023-04-25|09:08:52.147] received proposal module=consensus proposal="Proposal{2/0 (F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C:1:C73D3D1273F2, -1) AD19AE292A45 @ 2023-04-25T12:08:52.143393Z}" +I[2023-04-25|09:08:52.147] received proposal module=consensus proposal="Proposal{2/0 (F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C:1:C73D3D1273F2, -1) AD19AE292A45 @ 2023-04-25T12:08:52.143393Z}" +I[2023-04-25|09:08:52.152] received complete proposal block module=consensus height=2 hash=F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C +I[2023-04-25|09:08:52.160] finalizing commit of block module=consensus height=2 hash=F518444C0E348270436A73FD0F0B9DFEA758286BEB29482F1E3BEA75330E825C root= num_txs=0 +I[2023-04-25|09:08:52.167] executed block module=state height=2 num_valid_txs=0 num_invalid_txs=0 +I[2023-04-25|09:08:52.171] committed state module=state height=2 num_txs=0 app_hash= +``` + +The blocks, as you can see from the `num_valid_txs=0` part, are empty, but let's remedy that next. + +## 1.6 Using the application + +Let's try submitting a transaction to our new application. +Open another terminal window and run the following curl command: + +```bash +curl -s 'localhost:26657/broadcast_tx_commit?tx="cometbft=rocks"' +``` + +If everything went well, you should see a response indicating which height the +transaction was included in the blockchain. + +Finally, let's make sure that transaction really was persisted by the application. +Run the following command: + +```bash +curl -s 'localhost:26657/abci_query?data="cometbft"' +``` + +Let's examine the response object that this request returns. +The request returns a `json` object with a `key` and `value` field set. + +```json +... + "key": "dGVuZGVybWludA==", + "value": "cm9ja3M=", +... +``` + +Those values don't look like the `key` and `value` we sent to CometBFT. +What's going on here? + +The response contains a `base64` encoded representation of the data we submitted. +To get the original value out of this data, we can use the `base64` command line utility: + +```bash +echo "cm9ja3M=" | base64 -d +``` + +## Outro + +Hope you could run everything smoothly. If you have any difficulties running through this tutorial, reach out to us via [discord](https://discord.com/invite/interchain) or open a new [issue](https://github.com/cometbft/cometbft/issues/new/choose) on Github. diff --git a/docs/guides/install.md b/docs/guides/install.md new file mode 100644 index 0000000..93a3026 --- /dev/null +++ b/docs/guides/install.md @@ -0,0 +1,125 @@ +--- +order: 3 +--- + +# Install CometBFT + +## From Go Package + +Install the latest version of CometBFT's Go package: + +```sh +go install github.com/cometbft/cometbft/cmd/cometbft@latest +``` + +Install a specific version of CometBFT's Go package: + +```sh +go install github.com/cometbft/cometbft/cmd/cometbft@v0.38 +``` + +## From Binary + +To download pre-built binaries, see the [releases page](https://github.com/cometbft/cometbft/releases). + +## From Source + +You'll need `go` [installed](https://golang.org/doc/install) and the required +environment variables set, which can be done with the following commands: + +```sh +echo export GOPATH=\"\$HOME/go\" >> ~/.bash_profile +echo export PATH=\"\$PATH:\$GOPATH/bin\" >> ~/.bash_profile +``` + +### Get Source Code + +```sh +git clone https://github.com/cometbft/cometbft.git +cd cometbft +``` + +### Compile + +```sh +make install +``` + +to put the binary in `$GOPATH/bin` or use: + +```sh +make build +``` + +to put the binary in `./build`. + +_DISCLAIMER_ The binary of CometBFT is build/installed without the DWARF +symbol table. If you would like to build/install CometBFT with the DWARF +symbol and debug information, remove `-s -w` from `BUILD_FLAGS` in the make +file. + +The latest CometBFT is now installed. You can verify the installation by +running: + +```sh +cometbft version +``` + +## Reinstall + +If you already have CometBFT installed, and you make updates, simply + +```sh +make install +``` + +To upgrade, run + +```sh +git pull origin main +make install +``` + +## Compile with CLevelDB support + +Install [LevelDB](https://github.com/google/leveldb) (minimum version is 1.7). + +Install LevelDB with snappy (optionally). Below are commands for Ubuntu: + +```sh +sudo apt-get update +sudo apt install build-essential + +sudo apt-get install libsnappy-dev + +wget https://github.com/google/leveldb/archive/v1.23.tar.gz && \ + tar -zxvf v1.23.tar.gz && \ + cd leveldb-1.23/ && \ + make && \ + sudo cp -r out-static/lib* out-shared/lib* /usr/local/lib/ && \ + cd include/ && \ + sudo cp -r leveldb /usr/local/include/ && \ + sudo ldconfig && \ + rm -f v1.23.tar.gz +``` + +Set a database backend to `cleveldb`: + +```toml +# config/config.toml +db_backend = "cleveldb" +``` + +To install CometBFT, run: + +```sh +CGO_LDFLAGS="-lsnappy" make install COMETBFT_BUILD_OPTIONS=cleveldb +``` + +or run: + +```sh +CGO_LDFLAGS="-lsnappy" make build COMETBFT_BUILD_OPTIONS=cleveldb +``` + +which puts the binary in `./build`. diff --git a/docs/guides/quick-start.md b/docs/guides/quick-start.md new file mode 100644 index 0000000..92a6341 --- /dev/null +++ b/docs/guides/quick-start.md @@ -0,0 +1,164 @@ +--- +order: 2 +--- + +# Quick Start + +## Overview + +This is a quick start guide. If you have a vague idea about how CometBFT +works and want to get started right away, continue. + +## Install + +See the [install guide](./install.md). + +## Initialization + +Running: + +```sh +cometbft init +``` + +will create the required files for a single, local node. + +These files are found in `$HOME/.cometbft`: + +```sh +$ ls $HOME/.cometbft + +config data + +$ ls $HOME/.cometbft/config/ + +config.toml genesis.json node_key.json priv_validator.json +``` + +For a single, local node, no further configuration is required. +Configuring a cluster is covered further below. + +## Local Node + +Start CometBFT with a simple in-process application: + +```sh +cometbft node --proxy_app=kvstore +``` + +> Note: `kvstore` is a non persistent app, if you would like to run an application with persistence run `--proxy_app=persistent_kvstore` + +and blocks will start to stream in: + +```sh +I[01-06|01:45:15.592] Executed block module=state height=1 validTxs=0 invalidTxs=0 +I[01-06|01:45:15.624] Committed state module=state height=1 txs=0 appHash= +``` + +Check the status with: + +```sh +curl -s localhost:26657/status +``` + +### Sending Transactions + +With the KVstore app running, we can send transactions: + +```sh +curl -s 'localhost:26657/broadcast_tx_commit?tx="abcd"' +``` + +and check that it worked with: + +```sh +curl -s 'localhost:26657/abci_query?data="abcd"' +``` + +We can send transactions with a key and value too: + +```sh +curl -s 'localhost:26657/broadcast_tx_commit?tx="name=satoshi"' +``` + +and query the key: + +```sh +curl -s 'localhost:26657/abci_query?data="name"' +``` + +where the value is returned in hex. + +## Cluster of Nodes + +First create four Ubuntu cloud machines. The following was tested on Digital +Ocean Ubuntu 16.04 x64 (3GB/1CPU, 20GB SSD). We'll refer to their respective IP +addresses below as IP1, IP2, IP3, IP4. + +Then, `ssh` into each machine and install CometBFT following the [instructions](./install.md). + +Next, use the `cometbft testnet` command to create four directories of config files (found in `./mytestnet`) and copy each directory to the relevant machine in the cloud, so that each machine has `$HOME/mytestnet/node[0-3]` directory. + +Before you can start the network, you'll need peers identifiers (IPs are not enough and can change). We'll refer to them as ID1, ID2, ID3, ID4. + +```sh +cometbft show_node_id --home ./mytestnet/node0 +cometbft show_node_id --home ./mytestnet/node1 +cometbft show_node_id --home ./mytestnet/node2 +cometbft show_node_id --home ./mytestnet/node3 +``` + +Here's a handy Bash script to compile the persistent peers string, which will +be needed for our next step: + +```bash +#!/bin/bash + +# Check if the required argument is provided +if [ $# -eq 0 ]; then + echo "Usage: $0 ..." + exit 1 +fi + +# Command to run on each IP +BASE_COMMAND="cometbft show_node_id --home ./mytestnet/node" + +# Initialize an array to store results +PERSISTENT_PEERS="" + +# Iterate through provided IPs +for i in "${!@}"; do + IP="${!i}" + NODE_IDX=$((i - 1)) # Adjust for zero-based indexing + + echo "Getting ID of $IP (node $NODE_IDX)..." + + # Run the command on the current IP and capture the result + ID=$($BASE_COMMAND$NODE_IDX) + + # Store the result in the array + PERSISTENT_PEERS+="$ID@$IP:26656" + + # Add a comma if not the last IP + if [ $i -lt $# ]; then + PERSISTENT_PEERS+="," + fi +done + +echo "$PERSISTENT_PEERS" +``` + +Finally, from each machine, run: + +```sh +cometbft node --home ./mytestnet/node0 --proxy_app=kvstore --p2p.persistent_peers="ID1@IP1:26656,ID2@IP2:26656,ID3@IP3:26656,ID4@IP4:26656" +cometbft node --home ./mytestnet/node1 --proxy_app=kvstore --p2p.persistent_peers="ID1@IP1:26656,ID2@IP2:26656,ID3@IP3:26656,ID4@IP4:26656" +cometbft node --home ./mytestnet/node2 --proxy_app=kvstore --p2p.persistent_peers="ID1@IP1:26656,ID2@IP2:26656,ID3@IP3:26656,ID4@IP4:26656" +cometbft node --home ./mytestnet/node3 --proxy_app=kvstore --p2p.persistent_peers="ID1@IP1:26656,ID2@IP2:26656,ID3@IP3:26656,ID4@IP4:26656" +``` + +Note that after the third node is started, blocks will start to stream in +because >2/3 of validators (defined in the `genesis.json`) have come online. +Persistent peers can also be specified in the `config.toml`. See [here](../core/configuration.md) for more information about configuration options. + +Transactions can then be sent as covered in the single, local node example above. diff --git a/docs/imgs/abci.png b/docs/imgs/abci.png new file mode 100644 index 0000000..a05511c Binary files /dev/null and b/docs/imgs/abci.png differ diff --git a/docs/imgs/consensus_logic.png b/docs/imgs/consensus_logic.png new file mode 100644 index 0000000..a7f973b Binary files /dev/null and b/docs/imgs/consensus_logic.png differ diff --git a/docs/imgs/contributing.png b/docs/imgs/contributing.png new file mode 100644 index 0000000..e4be44c Binary files /dev/null and b/docs/imgs/contributing.png differ diff --git a/docs/imgs/light_client_bisection_alg.png b/docs/imgs/light_client_bisection_alg.png new file mode 100644 index 0000000..34f9a27 Binary files /dev/null and b/docs/imgs/light_client_bisection_alg.png differ diff --git a/docs/imgs/sentry_layout.png b/docs/imgs/sentry_layout.png new file mode 100644 index 0000000..40cc7ae Binary files /dev/null and b/docs/imgs/sentry_layout.png differ diff --git a/docs/imgs/sentry_local_config.png b/docs/imgs/sentry_local_config.png new file mode 100644 index 0000000..575cef5 Binary files /dev/null and b/docs/imgs/sentry_local_config.png differ diff --git a/docs/introduction/README.md b/docs/introduction/README.md new file mode 100644 index 0000000..a7383c1 --- /dev/null +++ b/docs/introduction/README.md @@ -0,0 +1,330 @@ +--- +order: 1 +parent: + title: Introduction + order: 1 +--- + +# What is CometBFT + +CometBFT is software for securely and consistently replicating an +application on many machines. By securely, we mean that CometBFT works +as long as less than 1/3 of machines fail in arbitrary ways. By consistently, +we mean that every non-faulty machine sees the same transaction log and +computes the same state. Secure and consistent replication is a +fundamental problem in distributed systems; it plays a critical role in +the fault tolerance of a broad range of applications, from currencies, +to elections, to infrastructure orchestration, and beyond. + +The ability to tolerate machines failing in arbitrary ways, including +becoming malicious, is known as Byzantine fault tolerance (BFT). The +theory of BFT is decades old, but software implementations have only +became popular recently, due largely to the success of "blockchain +technology" like Bitcoin and Ethereum. Blockchain technology is just a +reformalization of BFT in a more modern setting, with emphasis on +peer-to-peer networking and cryptographic authentication. The name +derives from the way transactions are batched in blocks, where each +block contains a cryptographic hash of the previous one, forming a +chain. + +CometBFT consists of two chief technical components: a blockchain +consensus engine and a generic application interface. +The consensus engine, +which is based on [Tendermint consensus algorithm][tendermint-paper], +ensures that the same transactions are +recorded on every machine in the same order. The application interface, +called the Application BlockChain Interface (ABCI), delivers the transactions +to applications for processing. Unlike other +blockchain and consensus solutions, which come pre-packaged with built +in state machines (like a fancy key-value store, or a quirky scripting +language), developers can use CometBFT for BFT state machine +replication of applications written in whatever programming language and +development environment is right for them. + +CometBFT is designed to be easy-to-use, simple-to-understand, highly +performant, and useful for a wide variety of distributed applications. + +## CometBFT vs. X + +CometBFT is broadly similar to two classes of software. The first +class consists of distributed key-value stores, like Zookeeper, etcd, +and consul, which use non-BFT consensus. The second class is known as +"blockchain technology", and consists of both cryptocurrencies like +Bitcoin and Ethereum, and alternative distributed ledger designs like +Hyperledger's Burrow. + +### Zookeeper, etcd, consul + +Zookeeper, etcd, and consul are all implementations of key-value stores +atop a classical, non-BFT consensus algorithm. Zookeeper uses an +algorithm called Zookeeper Atomic Broadcast, while etcd and consul use +the Raft log replication algorithm. A +typical cluster contains 3-5 machines, and can tolerate crash failures +in less than 1/2 of the machines (e.g., 1 out of 3 or 2 out of 5), +but even a single Byzantine fault can jeopardize the whole system. + +Each offering provides a slightly different implementation of a +featureful key-value store, but all are generally focused around +providing basic services to distributed systems, such as dynamic +configuration, service discovery, locking, leader-election, and so on. + +CometBFT is in essence similar software, but with two key differences: + +- It is Byzantine Fault Tolerant, meaning it can only tolerate less than 1/3 + of machines failing, but those failures can include arbitrary behavior - + including hacking and malicious attacks. +- It does not specify a + particular application, like a fancy key-value store. Instead, it + focuses on arbitrary state machine replication, so developers can build + the application logic that's right for them, from key-value store to + cryptocurrency to e-voting platform and beyond. + +### Bitcoin, Ethereum, etc + +[Tendermint consensus algorithm][tendermint-paper], adopted by CometBFT, +emerged in the tradition of cryptocurrencies like Bitcoin, +Ethereum, etc. with the goal of providing a more efficient and secure +consensus algorithm than Bitcoin's Proof of Work. In the early days, +Tendermint consensus-based blockchains had a simple currency built in, and to participate in +consensus, users had to "bond" units of the currency into a security +deposit which could be revoked if they misbehaved -this is what made +Tendermint consensus a Proof-of-Stake algorithm. + +Since then, CometBFT has evolved to be a general purpose blockchain +consensus engine that can host arbitrary application states. That means +it can be used as a plug-and-play replacement for the consensus engines +of other blockchain software. So one can take the current Ethereum code +base, whether in Rust, or Go, or Haskell, and run it as an ABCI +application using CometBFT. Indeed, [we did that with +Ethereum](https://github.com/cosmos/ethermint). And we plan to do +the same for Bitcoin, ZCash, and various other deterministic +applications as well. + +Another example of a cryptocurrency application built on CometBFT is +[the Cosmos network](http://cosmos.network). + +### Other Blockchain Projects + +[Fabric](https://github.com/hyperledger/fabric) takes a similar approach +to CometBFT, but is more opinionated about how the state is managed, +and requires that all application behavior runs in potentially many +docker containers, modules it calls "chaincode". It uses an +implementation of [PBFT](http://pmg.csail.mit.edu/papers/osdi99.pdf). +from a team at IBM that is [augmented to handle potentially +non-deterministic +chaincode](https://drops.dagstuhl.de/opus/volltexte/2017/7093/pdf/LIPIcs-OPODIS-2016-24.pdf). +It is possible to implement this docker-based behavior as an ABCI app in +CometBFT, though extending CometBFT to handle non-determinism +remains for future work. + +[Burrow](https://github.com/hyperledger/burrow) is an implementation of +the Ethereum Virtual Machine and Ethereum transaction mechanics, with +additional features for a name-registry, permissions, and native +contracts, and an alternative blockchain API. It uses CometBFT as its +consensus engine, and provides a particular application state. + +## ABCI Overview + +The [Application BlockChain Interface +(ABCI)](https://github.com/cometbft/cometbft/tree/v0.38.x/abci) +allows for Byzantine Fault Tolerant replication of applications +written in any programming language. + +### Motivation + +Thus far, all blockchains "stacks" (such as +[Bitcoin](https://github.com/bitcoin/bitcoin)) have had a monolithic +design. That is, each blockchain stack is a single program that handles +all the concerns of a decentralized ledger; this includes P2P +connectivity, the "mempool" broadcasting of transactions, consensus on +the most recent block, account balances, Turing-complete contracts, +user-level permissions, etc. + +Using a monolithic architecture is typically bad practice in computer +science. It makes it difficult to reuse components of the code, and +attempts to do so result in complex maintenance procedures for forks of +the codebase. This is especially true when the codebase is not modular +in design and suffers from "spaghetti code". + +Another problem with monolithic design is that it limits you to the +language of the blockchain stack (or vice versa). In the case of +Ethereum which supports a Turing-complete bytecode virtual-machine, it +limits you to languages that compile down to that bytecode; while the +[list](https://github.com/pirapira/awesome-ethereum-virtual-machine#programming-languages-that-compile-into-evm) +is growing, it is still very limited. + +In contrast, our approach is to decouple the consensus engine and P2P +layers from the details of the state of the particular +blockchain application. We do this by abstracting away the details of +the application to an interface, which is implemented as a socket +protocol. + +### Intro to ABCI + +[CometBFT](https://github.com/cometbft/cometbft), the +"consensus engine", communicates with the application via a socket +protocol that satisfies the ABCI, the CometBFT Socket Protocol. + +To draw an analogy, let's talk about a well-known cryptocurrency, +Bitcoin. Bitcoin is a cryptocurrency blockchain where each node +maintains a fully audited Unspent Transaction Output (UTXO) database. If +one wanted to create a Bitcoin-like system on top of ABCI, CometBFT +would be responsible for + +- Sharing blocks and transactions between nodes +- Establishing a canonical/immutable order of transactions + (the blockchain) + +The application will be responsible for + +- Maintaining the UTXO database +- Validating cryptographic signatures of transactions +- Preventing transactions from spending non-existent transactions +- Allowing clients to query the UTXO database. + +CometBFT is able to decompose the blockchain design by offering a very +simple API (i.e. the ABCI) between the application process and consensus +process. + +The ABCI consists of 3 primary message types that get delivered from the +core to the application. The application replies with corresponding +response messages. + +The messages are specified here: [ABCI Message +Types](https://github.com/cometbft/cometbft/blob/v0.38.x/proto/tendermint/abci/types.proto). + +The **FinalizeBlock** message is the work horse of the application. Each +transaction in the blockchain is finalized within this message. The +application needs to validate each transaction received with the +**FinalizeBlock** message against the current state, application protocol, +and the cryptographic credentials of the transaction. FinalizeBlock only +prepares the update to be made and does not change the state of the application. +The state change is actually committed in a later stage i.e. in commit phase. + +The **CheckTx** message is used for validating transactions. +CometBFT's mempool first checks the +validity of a transaction with **CheckTx**, and only relays valid +transactions to its peers. For instance, an application may check an +incrementing sequence number in the transaction and return an error upon +**CheckTx** if the sequence number is old. Alternatively, they might use +a capabilities based system that requires capabilities to be renewed +with every transaction. + +The **Commit** message is used to compute a cryptographic commitment to +the current application state, to be placed into the next block header. +This has some handy properties. Inconsistencies in updating that state +will now appear as blockchain forks which catches a whole class of +programming errors. This also simplifies the development of secure +lightweight clients, as Merkle-hash proofs can be verified by checking +against the block hash, and that the block hash is signed by a quorum. + +There can be multiple ABCI socket connections to an application. +CometBFT creates four ABCI connections to the application; one +for the validation of transactions when broadcasting in the mempool, one for +the consensus engine to run block proposals, one for creating snapshots of the +application state, and one more for querying the application state. + +It's probably evident that application designers need to very carefully +design their message handlers to create a blockchain that does anything +useful but this architecture provides a place to start. The diagram +below illustrates the flow of messages via ABCI. + +![abci](../imgs/abci.png) + +## A Note on Determinism + +The logic for blockchain transaction processing must be deterministic. +If the application logic weren't deterministic, consensus would not be +reached among the CometBFT replica nodes. + +Solidity on Ethereum is a great language of choice for blockchain +applications because, among other reasons, it is a completely +deterministic programming language. However, it's also possible to +create deterministic applications using existing popular languages like +Java, C++, Python, or Go, by avoiding +sources of non-determinism such as: + +- random number generators (without deterministic seeding) +- race conditions on threads (or avoiding threads altogether) +- the system clock +- uninitialized memory (in unsafe programming languages like C + or C++) +- [floating point + arithmetic](http://gafferongames.com/networking-for-game-programmers/floating-point-determinism/) +- language features that are random (e.g. map iteration in Go) + +While programmers can avoid non-determinism by being careful, it is also +possible to create a special linter or static analyzer for each language +to check for determinism. In the future we may work with partners to +create such tools. + +## Consensus Overview + +CometBFT adopts [Tendermint consensus][tendermint-paper], +an easy-to-understand, mostly asynchronous, BFT consensus algorithm. +The algorithm follows a simple state machine that looks like this: + +![consensus-logic](../imgs/consensus_logic.png) + +Participants in the algorithm are called **validators**; they take turns +proposing blocks of transactions and voting on them. Blocks are +committed in a chain, with one block at each **height**. A block may +fail to be committed, in which case the algorithm moves to the next +**round**, and a new validator gets to propose a block for that height. +Two stages of voting are required to successfully commit a block; we +call them **pre-vote** and **pre-commit**. + +There is a picture of a couple doing the polka because validators are +doing something like a polka dance. When more than two-thirds of the +validators pre-vote for the same block, we call that a **polka**. Every +pre-commit must be justified by a polka in the same round. +A block is committed when +more than 2/3 of validators pre-commit for the same block in the same +round. + +Validators may fail to commit a block for a number of reasons; the +current proposer may be offline, or the network may be slow. Tendermint consensus +allows them to establish that a validator should be skipped. Validators +wait a small amount of time to receive a complete proposal block from +the proposer before voting to move to the next round. This reliance on a +timeout is what makes Tendermint consensus a weakly synchronous algorithm, rather +than an asynchronous one. However, the rest of the algorithm is +asynchronous, and validators only make progress after hearing from more +than two-thirds of the validator set. A simplifying element of +Tendermint consensus is that it uses the same mechanism to commit a block as it +does to skip to the next round. + +Assuming less than one-third of the validators are Byzantine, Tendermint consensus algorithm +guarantees that safety will never be violated - that is, validators will +never commit conflicting blocks at the same height. To do this it +introduces a few **locking** rules which modulate which paths can be +followed in the flow diagram. Once a validator precommits a block, it is +locked on that block. Then, + +1. it must prevote for the block it is locked on +2. it can only unlock, and precommit for a new block, if there is a + polka for that block in a later round + +## Stake + +In many systems, not all validators will have the same "weight" in the +consensus protocol. Thus, we are not so much interested in one-third or +two-thirds of the validators, but in those proportions of the total +voting power, which may not be uniformly distributed across individual +validators. + +Since CometBFT can replicate arbitrary applications, it is possible to +define a currency, and denominate the voting power in that currency. +When voting power is denominated in a native currency, the system is +often referred to as Proof-of-Stake. Validators can be forced, by logic +in the application, to "bond" their currency holdings in a security +deposit that can be destroyed if they're found to misbehave in the +consensus protocol. This adds an economic element to the security of the +protocol, allowing one to quantify the cost of violating the assumption +that less than one-third of voting power is Byzantine. + +The [Cosmos Network](https://cosmos.network) is designed to use this +Proof-of-Stake mechanism across an array of cryptocurrencies implemented +as ABCI applications. + +[tendermint-paper]: https://arxiv.org/abs/1807.04938 diff --git a/docs/networks/README.md b/docs/networks/README.md new file mode 100644 index 0000000..12f12ef --- /dev/null +++ b/docs/networks/README.md @@ -0,0 +1,13 @@ +--- +order: 1 +parent: + title: Networks + order: 5 +--- + +# Overview + +Use [Docker Compose](./docker-compose.md) to spin up CometBFT testnets on your +local machine. + +See the `cometbft testnet --help` command for more help initializing testnets. diff --git a/docs/networks/docker-compose.md b/docs/networks/docker-compose.md new file mode 100644 index 0000000..6c9290c --- /dev/null +++ b/docs/networks/docker-compose.md @@ -0,0 +1,179 @@ +--- +order: 2 +--- + +# Docker Compose + +With Docker Compose, you can spin up local testnets with a single command. + +## Requirements + +1. [Install CometBFT](../guides/install.md) +2. [Install docker](https://docs.docker.com/engine/installation/) +3. [Install docker-compose](https://docs.docker.com/compose/install/) + +## Build + +Build the `cometbft` binary and, optionally, the `cometbft/localnode` +docker image. + +Note the binary will be mounted into the container so it can be updated without +rebuilding the image. + +```sh +# Build the linux binary in ./build +make build-linux + +# (optionally) Build cometbft/localnode image +make build-docker-localnode +``` + +## Run a testnet + +To start a 4 node testnet run: + +```sh +make localnet-start +``` + +The nodes bind their RPC servers to ports 26657, 26660, 26662, and 26664 on the +host. + +This file creates a 4-node network using the localnode image. + +The nodes of the network expose their P2P and RPC endpoints to the host machine +on ports 26656-26657, 26659-26660, 26661-26662, and 26663-26664 respectively. + +To update the binary, just rebuild it and restart the nodes: + +```sh +make build-linux +make localnet-start +``` + +## Configuration + +The `make localnet-start` creates files for a 4-node testnet in `./build` by +calling the `cometbft testnet` command. + +The `./build` directory is mounted to the `/cometbft` mount point to attach +the binary and config files to the container. + +To change the number of validators / non-validators change the `localnet-start` Makefile target [here](../../Makefile): + +```makefile +localnet-start: localnet-stop + @if ! [ -f build/node0/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/cometbft:Z cometbft/localnode testnet --v 5 --n 3 --o . --populate-persistent-peers --starting-ip-address 192.167.10.2 ; fi + docker compose up -d +``` + +The command now will generate config files for 5 validators and 3 +non-validators. Along with generating new config files the docker-compose file needs to be edited. +Adding 4 more nodes is required in order to fully utilize the config files that were generated. + +```yml + node3: # bump by 1 for every node + container_name: node3 # bump by 1 for every node + image: "cometbft/localnode" + environment: + - ID=3 + - LOG=${LOG:-cometbft.log} + ports: + - "26663-26664:26656-26657" # Bump 26663-26664 by one for every node + volumes: + - ./build:/cometbft:Z + networks: + localnet: + ipv4_address: 192.167.10.5 # bump the final digit by 1 for every node +``` + +Before running it, don't forget to cleanup the old files: + +```sh +# Clear the build folder +rm -rf ./build/node* +``` + +## Configuring ABCI containers + +To use your own ABCI applications with 4-node setup edit the [docker-compose.yaml](https://github.com/cometbft/cometbft/blob/v0.38.x/docker-compose.yml) file and add images to your ABCI application. + +```yml + abci0: + container_name: abci0 + image: "abci-image" + build: + context: . + dockerfile: abci.Dockerfile + command: + networks: + localnet: + ipv4_address: 192.167.10.6 + + abci1: + container_name: abci1 + image: "abci-image" + build: + context: . + dockerfile: abci.Dockerfile + command: + networks: + localnet: + ipv4_address: 192.167.10.7 + + abci2: + container_name: abci2 + image: "abci-image" + build: + context: . + dockerfile: abci.Dockerfile + command: + networks: + localnet: + ipv4_address: 192.167.10.8 + + abci3: + container_name: abci3 + image: "abci-image" + build: + context: . + dockerfile: abci.Dockerfile + command: + networks: + localnet: + ipv4_address: 192.167.10.9 + +``` + +Override the [command](https://github.com/cometbft/cometbft/blob/v0.38.x/networks/local/localnode/Dockerfile#L11) in each node to connect to it's ABCI. + +```yml + node0: + container_name: node0 + image: "cometbft/localnode" + ports: + - "26656-26657:26656-26657" + environment: + - ID=0 + - LOG=$${LOG:-cometbft.log} + volumes: + - ./build:/cometbft:Z + command: node --proxy_app=tcp://abci0:26658 + networks: + localnet: + ipv4_address: 192.167.10.2 +``` + +Similarly do for node1, node2 and node3 then [run testnet](#run-a-testnet). + +## Logging + +Log is saved under the attached volume, in the `cometbft.log` file. If the +`LOG` environment variable is set to `stdout` at start, the log is not saved, +but printed on the screen. + +## Special binaries + +If you have multiple binaries with different names, you can specify which one +to run with the `BINARY` environment variable. The path of the binary is relative +to the attached volume. diff --git a/docs/presubmit.sh b/docs/presubmit.sh new file mode 100755 index 0000000..192df44 --- /dev/null +++ b/docs/presubmit.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# +# This script verifies that each document in the docs and architecture +# directory has a corresponding table-of-contents entry in its README file. +# +# This can be run manually from the command line. +# It is also run in CI via the docs-toc.yml workflow. +# +set -euo pipefail + +readonly base="$(dirname $0)" +cd "$base" + +readonly workdir="$(mktemp -d)" +trap "rm -fr -- '$workdir'" EXIT + +checktoc() { + local dir="$1" + local tag="$2"'-*-*' + local out="$workdir/${dir}.out.txt" + ( + cd "$dir" >/dev/null + find . -maxdepth 1 -type f -name "$tag" -not -exec grep -q "({})" README.md ';' -print + ) > "$out" + if [[ -s "$out" ]] ; then + echo "-- The following files in $dir lack a ToC entry: +" + cat "$out" + return 1 + fi +} + +err=0 + +# Verify that each RFC and ADR has a ToC entry in its README file. +checktoc architecture adr || ((err++)) +checktoc rfc rfc || ((err++)) + +exit $err diff --git a/docs/qa/CometBFT-QA-34.md b/docs/qa/CometBFT-QA-34.md new file mode 100644 index 0000000..8a78296 --- /dev/null +++ b/docs/qa/CometBFT-QA-34.md @@ -0,0 +1,370 @@ +--- +order: 1 +parent: + title: CometBFT QA Results v0.34.x + description: This is a report on the results obtained when running v0.34.x on testnets + order: 3 +--- + +# CometBFT QA Results v0.34.x + +## v0.34.x - From Tendermint Core to CometBFT + +This section reports on the QA process we followed before releasing the first `v0.34.x` version +from our CometBFT repository. + +The changes with respect to the last version of `v0.34.x` +(namely `v0.34.26`, released from the Informal Systems' Tendermint Core fork) +are minimal, and focus on rebranding our fork of Tendermint Core to CometBFT at places +where there is no substantial risk of breaking compatibility +with earlier Tendermint Core versions of `v0.34.x`. + +Indeed, CometBFT versions of `v0.34.x` (`v0.34.27` and subsequent) should fulfill +the following compatibility-related requirements. + +* Operators can easily upgrade a `v0.34.x` version of Tendermint Core to CometBFT. +* Upgrades from Tendermint Core to CometBFT can be uncoordinated for versions of the `v0.34.x` branch. +* Nodes running CometBFT must be interoperable with those running Tendermint Core in the same chain, + as long as all are running a `v0.34.x` version. + +These QA tests focus on the third bullet, whereas the first two bullets are tested using our _e2e tests_. + +It would be prohibitively time consuming to test mixed networks of all combinations of existing `v0.34.x` +versions, combined with the CometBFT release candidate under test. +Therefore our testing focuses on the last Tendermint Core version (`v0.34.26`) and the CometBFT release +candidate under test. + +We run the _200 node test_, but not the _rotating node test_. The effort of running the latter +is not justified given the amount and nature of the changes we are testing with respect to the +full QA cycle run previously on `v0.34.x`. +Since the changes to the system's logic are minimal, we are interested in these performance requirements: + +* The CometBFT release candidate under test performs similarly to Tendermint Core (i.e., the baseline) + * when used at scale (i.e., in a large network of CometBFT nodes) + * when used at scale in a mixed network (i.e., some nodes are running CometBFT + and others are running an older Tendermint Core version) + +Therefore we carry out a complete run of the _200-node test_ on the following networks: + +* A homogeneous 200-node testnet, where all nodes are running the CometBFT release candidate under test. +* A mixed network where 1/2 (99 out of 200) of the nodes are running the CometBFT release candidate under test, + and the rest (101 out of 200) are running Tendermint Core `v0.34.26`. +* A mixed network where 1/3 (66 out of 200) of the nodes are running the CometBFT release candidate under test, + and the rest (134 out of 200) are running Tendermint Core `v0.34.26`. +* A mixed network where 2/3 (133 out of 200) of the nodes are running the CometBFT release candidate under test, + and the rest (67 out of 200) are running Tendermint Core `v0.34.26`. + +## Configuration and Results +In the following sections we provide the results of the _200 node test_. +Each section reports the baseline results (for reference), the homogeneous network scenario (all CometBFT nodes), +and the mixed networks with 1/2, 1/3 and 2/3 of Tendermint Core nodes. + +### Saturation Point + +As the CometBFT release candidate under test has minimal changes +with respect to Tendermint Core `v0.34.26`, other than the rebranding changes, +we can confidently reuse the results from the `v0.34.x` baseline test regarding +the [saturation point](TMCore-QA-34.md#finding-the-saturation-point). + +Therefore, we will simply use a load of (`r=200,c=2`) +(see the explanation [here](TMCore-QA-34.md#finding-the-saturation-point)) on all experiments. + +We also include the baseline results for quick reference and comparison. + +### Experiments + +On each of the three networks, the test consists of 4 experiments, with the goal of +ensuring the data obtained is consistent across experiments. + +On each of the networks, we pick only one representative run to present and discuss the +results. + + +## Examining latencies +For each network the figures plot the four experiments carried out with the network. +We can see that the latencies follow comparable patterns across all experiments. + +Unique identifiers, UUID, for each execution are presented on top of each graph. +We refer to these UUID to indicate to the representative runs. + +### CometBFT Homogeneous network + +![latencies](img34/homogeneous/all_experiments.png) + +### 1/2 Tendermint Core - 1/2 CometBFT + +![latencies](img34/cmt1tm1/all_experiments.png) + +### 1/3 Tendermint Core - 2/3 CometBFT + +![latencies](img34/cmt2tm1/all_experiments.png) + +### 2/3 Tendermint Core - 1/3 CometBFT + +![latencies_all_tm2_3_cmt1_3](img34/v034_200node_tm2cmt1/all_experiments.png) + + +## Prometheus Metrics + +This section reports on the key Prometheus metrics extracted from the following experiments. + +* Baseline results: `v0.34.x`, obtained in October 2022 and reported [here](TMCore-QA-34.md). +* CometBFT homogeneous network: experiment with UUID starting with `be8c`. +* Mixed network, 1/2 Tendermint Core `v0.34.26` and 1/2 running CometBFT: experiment with UUID starting with `04ee`. +* Mixed network, 1/3 Tendermint Core `v0.34.26` and 2/3 running CometBFT: experiment with UUID starting with `fc5e`. +* Mixed network, 2/3 Tendermint Core `v0.34.26` and 1/3 running CometBFT: experiment with UUID starting with `4759`. + +We make explicit comparisons between the baseline and the homogenous setups, but refrain from +commenting on the mixed network experiment unless they show some exceptional results. + +### Mempool Size + +For each reported experiment we show two graphs. +The first shows the evolution over time of the cumulative number of transactions +inside all full nodes' mempools at a given time. + +The second one shows the evolution of the average over all full nodes. + +#### Baseline + +![mempool-cumulative](img34/baseline/mempool_size.png) + +![mempool-avg](img34/baseline/avg_mempool_size.png) + +#### CometBFT Homogeneous network + +The results for the homogeneous network and the baseline are similar in terms of outstanding transactions. + +![mempool-cumulative-homogeneous](img34/homogeneous/mempool_size.png) + +![mempool-avg-homogeneous](img34/homogeneous/avg_mempool_size.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![mempool size](img34/cmt1tm1/mempool_size.png) + +![average mempool size](img34/cmt1tm1/avg_mempool_size.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![mempool size](img34/cmt2tm1/mempool_size.png) + +![average mempool size](img34/cmt2tm1/avg_mempool_size.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +![mempool_tm2_3_cmt_1_3](img34/v034_200node_tm2cmt1/mempool_size.png) + +![mempool-avg_tm2_3_cmt_1_3](img34/v034_200node_tm2cmt1/avg_mempool_size.png) + +### Consensus Rounds per Height + +The following graphs show the rounds needed to complete each height and agree on a block. + +A value of `0` shows that only one round was required (with id `0`), and a value of `1` shows that two rounds were required. + +#### Baseline +We can see that round 1 is reached with a certain frequency. + +![rounds](img34/baseline/rounds.png) + +#### CometBFT Homogeneous network + +Most heights finished in round 0, some nodes needed to advance to round 1 at various moments, +and a few nodes even needed to advance to round 2 at one point. +This coincides with the time at which we observed the biggest peak in mempool size +on the corresponding plot, shown above. + +![rounds-homogeneous](img34/homogeneous/rounds.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![peers](img34/cmt1tm1/rounds.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![peers](img34/cmt2tm1/rounds.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +![rounds-tm2_3_cmt1_3](img34/v034_200node_tm2cmt1/rounds.png) + +### Peers + +The following plots show how many peers a node had throughtout the experiment. + +The thick red dashed line represents the moving average over a sliding window of 20 seconds. + +#### Baseline + +The following graph shows the that the number of peers was stable throughout the experiment. +Seed nodes typically have a higher number of peers. +The fact that non-seed nodes reach more than 50 peers is due to +[#9548](https://github.com/tendermint/tendermint/issues/9548). + +![peers](img34/baseline/peers.png) + +#### CometBFT Homogeneous network + +The results for the homogeneous network are very similar to the baseline. +The only difference being that the seed nodes seem to loose peers in the middle of the experiment. +However this cannot be attributed to the differences in the code, which are mainly rebranding. + +![peers-homogeneous](img34/homogeneous/peers.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![peers](img34/cmt1tm1/peers.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![peers](img34/cmt2tm1/peers.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +As in the homogeneous case, there is some variation in the number of peers for some nodes. +These, however, do not affect the average. + +![peers-tm2_3_cmt1_3](img34/v034_200node_tm2cmt1/peers.png) + +### Blocks Produced per Minute, Transactions Processed per Minute + +The following plot show the rate of block production and the rate of transactions delivered, throughout the experiments. + +In both graphs, rates are calculated over a sliding window of 20 seconds. +The thick red dashed line show the rates' moving averages. + +#### Baseline + +The average number of blocks/minute oscilate between 10 and 40. + +![heights](img34/baseline/block_rate_regular.png) + +The number of transactions/minute tops around 30k. + +![total-txs](img34/baseline/total_txs_rate_regular.png) + + +#### CometBFT Homogeneous network + +The plot showing the block production rate shows that the rate oscillates around 20 blocks/minute, +mostly within the same range as the baseline. + +![heights-homogeneous-rate](img34/homogeneous/block_rate_regular.png) + +The plot showing the transaction rate shows the rate stays around 20000 transactions per minute, +also topping around 30k. + +![txs-homogeneous-rate](img34/homogeneous/total_txs_rate_regular.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![height rate](img34/cmt1tm1/block_rate_regular.png) + +![transaction rate](img34/cmt1tm1/total_txs_rate_regular.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![height rate](img34/cmt2tm1/block_rate_regular.png) + +![transaction rate](img34/cmt2tm1/total_txs_rate_regular.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +![height rate](img34/v034_200node_tm2cmt1/block_rate_regular.png) + +![transaction rate](img34/v034_200node_tm2cmt1/total_txs_rate_regular.png) + +### Memory Resident Set Size + +The following graphs show the Resident Set Size (RSS) of all monitored processes and the average value. + +#### Baseline + +![rss](img34/baseline/memory.png) + +![rss-avg](img34/baseline/avg_memory.png) + +#### CometBFT Homogeneous network + +This is the plot for the homogeneous network, which is slightly more stable than the baseline over +the time of the experiment. + +![rss-homogeneous](img34/homogeneous/memory.png) + +And this is the average plot. It oscillates around 560 MiB, which is noticeably lower than the baseline. + +![rss-avg-homogeneous](img34/homogeneous/avg_memory.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![rss](img34/cmt1tm1/memory.png) + +![rss average](img34/cmt1tm1/avg_memory.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![rss](img34/cmt2tm1/memory.png) + +![rss average](img34/cmt2tm1/avg_memory.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +![rss](img34/v034_200node_tm2cmt1/memory.png) + +![rss average](img34/v034_200node_tm2cmt1/avg_memory.png) + +### CPU utilization + +The following graphs show the `load1` of nodes, as typically shown in the first line of the Unix `top` +command, and their average value. + +#### Baseline + +![load1](img34/baseline/cpu.png) + +![load1-avg](img34/baseline/avg_cpu.png) + +#### CometBFT Homogeneous network + +The load in the homogenous network is, similarly to the baseline case, below 5 and, therefore, normal. + +![load1-homogeneous](img34/homogeneous/cpu.png) + +As expected, the average plot also looks similar. + +![load1-homogeneous-avg](img34/homogeneous/avg_cpu.png) + +#### 1/2 Tendermint Core - 1/2 CometBFT + +![load1](img34/cmt1tm1/cpu.png) + +![average load1](img34/cmt1tm1/avg_cpu.png) + +#### 1/3 Tendermint Core - 2/3 CometBFT + +![load1](img34/cmt2tm1/cpu.png) + +![average load1](img34/cmt2tm1/avg_cpu.png) + +#### 2/3 Tendermint Core - 1/3 CometBFT + +![load1](img34/v034_200node_tm2cmt1/cpu.png) + +![average load1](img34/v034_200node_tm2cmt1/avg_cpu.png) + +## Test Results + +The comparison of the baseline results and the homogeneous case show that both scenarios had similar numbers and are therefore equivalent. + +The mixed nodes cases show that networks operate normally with a mix of compatible Tendermint Core and CometBFT versions. +Although not the main goal, a comparison of metric numbers with the homogenous case and the baseline scenarios show similar results and therefore we can conclude that mixing compatible Tendermint Core and CometBFT introduces not performance degradation. + +A conclusion of these tests is shown in the following table, along with the commit versions used in the experiments. + +| Scenario | Date | Version | Result | +|--|--|--|--| +|CometBFT Homogeneous network | 2023-02-08 | 3b783434f26b0e87994e6a77c5411927aad9ce3f | Pass +|1/2 Tendermint Core
1/2 CometBFT | 2023-02-14 | CometBFT: 3b783434f26b0e87994e6a77c5411927aad9ce3f
Tendermint Core: 66c2cb63416e66bff08e11f9088e21a0ed142790 | Pass| +|1/3 Tendermint Core
2/3 CometBFT | 2023-02-08 | CometBFT: 3b783434f26b0e87994e6a77c5411927aad9ce3f
Tendermint Core: 66c2cb63416e66bff08e11f9088e21a0ed142790 | Pass| +|2/3 Tendermint Core
1/3 CometBFT | 2023-02-08 | CometBFT: 3b783434f26b0e87994e6a77c5411927aad9ce3f
Tendermint Core: 66c2cb63416e66bff08e11f9088e21a0ed142790 | Pass | diff --git a/docs/qa/CometBFT-QA-37.md b/docs/qa/CometBFT-QA-37.md new file mode 100644 index 0000000..5256fcd --- /dev/null +++ b/docs/qa/CometBFT-QA-37.md @@ -0,0 +1,157 @@ +--- +order: 1 +parent: + title: CometBFT QA Results v0.37.x + description: This is a report on the results obtained when running CometBFT v0.37.x on testnets + order: 5 +--- + +# CometBFT QA Results v0.37.x + +This iteration of the QA was run on CometBFT `v0.37.0-alpha3`, the first `v0.37.x` version from the CometBFT repository. + +The changes with respect to the baseline, `TM v0.37.x` as of Oct 12, 2022 (Commit: 1cf9d8e276afe8595cba960b51cd056514965fd1), include the rebranding of our fork of Tendermint Core to CometBFT and several improvements, described in the CometBFT [CHANGELOG](https://github.com/cometbft/cometbft/blob/v0.37.0-alpha.3/CHANGELOG.md). + +## Testbed + +As in other iterations of our QA process, we have used a 200-node network as testbed, plus nodes to introduce load and collect metrics. + +### Saturation point + +As in previous iterations, in our QA experiments, the system is subjected to a load slightly under a saturation point. +The method to identify the saturation point is explained [here](TMCore-QA-34.md#finding-the-saturation-point) and its application to the baseline is described [here](TMCore-QA-37.md#finding-the-saturation-point). +We use the same saturation point, that is, `c`, the number of connections created by the load runner process to the target node, is 2 and `r`, the rate or number of transactions issued per second, is 200. + +## Examining latencies + +The following figure plots six experiments carried out with the network. +Unique identifiers, UUID, for each execution are presented on top of each graph. + +![latencies](img37/200nodes_cmt037/all_experiments.png) + +We can see that the latencies follow comparable patterns across all experiments. +Therefore, in the following sections we will only present the results for one representative run, chosen randomly, with UUID starting with `75cb89a8`. + +![latencies](img37/200nodes_cmt037/e_75cb89a8-f876-4698-82f3-8aaab0b361af.png). + +For reference, the following figure shows the latencies of different configuration of the baseline. +`c=02 r=200` corresponds to the same configuration as in this experiment. + +![all-latencies](img37/200nodes_tm037/v037_200node_latencies.png) + +As can be seen, latencies are similar. + +## Prometheus Metrics on the Chosen Experiment + +This section further examines key metrics for this experiment extracted from Prometheus data regarding the chosen experiment. + +### Mempool Size + +The mempool size, a count of the number of transactions in the mempool, was shown to be stable and homogeneous at all full nodes. +It did not exhibit any unconstrained growth. +The plot below shows the evolution over time of the cumulative number of transactions inside all full nodes' mempools at a given time. + +![mempoool-cumulative](img37/200nodes_cmt037/mempool_size.png) + +The following picture shows the evolution of the average mempool size over all full nodes, which mostly oscilates between 1500 and 2000 outstanding transactions. + +![mempool-avg](img37/200nodes_cmt037/avg_mempool_size.png) + +The peaks observed coincide with the moments when some nodes reached round 1 of consensus (see below). + + +The behavior is similar to the observed in the baseline, presented next. + +![mempool-cumulative-baseline](img37/200nodes_tm037/mempool_size.png) + +![mempool-avg-baseline](img37/200nodes_tm037/avg_mempool_size.png) + + +### Peers + +The number of peers was stable at all nodes. +It was higher for the seed nodes (around 140) than for the rest (between 16 and 78). +The red dashed line denotes the average value. + +![peers](img37/200nodes_cmt037/peers.png) + +Just as in the baseline, shown next, the fact that non-seed nodes reach more than 50 peers is due to [\#9548]. + +![peers](img37/200nodes_tm037/peers.png) + + +### Consensus Rounds per Height + +Most heights took just one round, that is, round 0, but some nodes needed to advance to round 1 and eventually round 2. + +![rounds](img37/200nodes_cmt037/rounds.png) + +The following specific run of the baseline presented better results, only requiring up to round 1, but reaching higher rounds is not uncommon in the corresponding software version. + +![rounds](img37/200nodes_tm037/rounds.png) + +### Blocks Produced per Minute, Transactions Processed per Minute + +The following plot shows the rate in which blocks were created, from the point of view of each node. +That is, it shows when each node learned that a new block had been agreed upon. + +![heights](img37/200nodes_cmt037/block_rate.png) + +For most of the time when load was being applied to the system, most of the nodes stayed around 20 to 25 blocks/minute. + +The spike to more than 175 blocks/minute is due to a slow node catching up. + +The collective spike on the right of the graph marks the end of the load injection, when blocks become smaller (empty) and impose less strain on the network. +This behavior is reflected in the following graph, which shows the number of transactions processed per minute. + +![total-txs](img37/200nodes_cmt037/total_txs_rate.png) + +The baseline experienced a similar behavior, shown in the following two graphs. +The first depicts the block rate. + +![heights-baseline](img37/200nodes_tm037/block_rate_regular.png) + +The second plots the transaction rate. + +![total-txs-baseline](img37/200nodes_tm037/total_txs_rate_regular.png) + +### Memory Resident Set Size + +The Resident Set Size of all monitored processes is plotted below, with maximum memory usage of 2GB. + +![rss](img37/200nodes_cmt037/memory.png) + +A similar behavior was shown in the baseline, presented next. + +![rss](img37/200nodes_tm037/memory.png) + +The memory of all processes went down as the load as removed, showing no signs of unconstrained growth. + + +#### CPU utilization + +The best metric from Prometheus to gauge CPU utilization in a Unix machine is `load1`, +as it usually appears in the +[output of `top`](https://www.digitalocean.com/community/tutorials/load-average-in-linux). + +It is contained below 5 on most nodes, as seen in the following graph. + +![load1](img37/200nodes_cmt037/cpu.png) + +A similar behavior was seen in the baseline. + +![load1-baseline](img37/200nodes_tm037/cpu.png) + + +## Test Results + +The comparison against the baseline results show that both scenarios had similar numbers and are therefore equivalent. + +A conclusion of these tests is shown in the following table, along with the commit versions used in the experiments. + +| Scenario | Date | Version | Result | +|--|--|--|--| +|CometBFT | 2023-02-14 | v0.37.0-alpha3 (bef9a830e7ea7da30fa48f2cc236b1f465cc5833) | Pass + + +[\#9548]: https://github.com/tendermint/tendermint/issues/9548 diff --git a/docs/qa/CometBFT-QA-38.md b/docs/qa/CometBFT-QA-38.md new file mode 100644 index 0000000..1102702 --- /dev/null +++ b/docs/qa/CometBFT-QA-38.md @@ -0,0 +1,556 @@ +--- +order: 1 +parent: + title: CometBFT QA Results v0.38.x + description: This is a report on the results obtained when running CometBFT v0.38.x on testnets + order: 5 +--- + +# CometBFT QA Results v0.38.x + +This iteration of the QA was run on CometBFT `v0.38.0-alpha.2`, the second +`v0.38.x` version from the CometBFT repository. + +The changes with respect to the baseline, `v0.37.0-alpha.3` from Feb 21, 2023, +include the introduction of the `FinalizeBlock` method to complete the full +range of ABCI++ functionality (ABCI 2.0), and other several improvements +described in the +[CHANGELOG](https://github.com/cometbft/cometbft/blob/v0.38.0-alpha.2/CHANGELOG.md). + +## Issues discovered + +* (critical, fixed) [\#539] and [\#546] - This bug causes the proposer to crash in + `PrepareProposal` because it does not have extensions while it should. + This happens mainly when the proposer was catching up. +* (critical, fixed) [\#562] - There were several bugs in the metrics-related + logic that were causing panics when the testnets were started. + +## 200 Node Testnet + +As in other iterations of our QA process, we have used a 200-node network as +testbed, plus nodes to introduce load and collect metrics. + +### Saturation point + +As in previous iterations of our QA experiments, we first find the transaction +load on which the system begins to show a degraded performance. Then we run the +experiments with the system subjected to a load slightly under the saturation +point. The method to identify the saturation point is explained +[here](CometBFT-QA-34.md#saturation-point) and its application to the baseline +is described [here](TMCore-QA-37.md#finding-the-saturation-point). + +The following table summarizes the results for the different experiments +(extracted from +[`v038_report_tabbed.txt`](img38/200nodes/v038_report_tabbed.txt)). The X axis +(`c`) is the number of connections created by the load runner process to the +target node. The Y axis (`r`) is the rate or number of transactions issued per +second. + +| | c=1 | c=2 | c=4 | +| ------ | --------: | --------: | ----: | +| r=200 | 17800 | **33259** | 33259 | +| r=400 | **35600** | 41565 | 41384 | +| r=800 | 36831 | 38686 | 40816 | +| r=1600 | 40600 | 45034 | 39830 | + +We can observe in the table that the system is saturated beyond the diagonal +defined by the entries `c=1,r=400` and `c=2,r=200`. Entries in the diagonal have +the same amount of transaction load, so we can consider them equivalent. For the +chosen diagonal, the expected number of processed transactions is `1 * 400 tx/s * 89 s = 35600`. +(Note that we use 89 out of 90 seconds of the experiment because the last transaction batch +coincides with the end of the experiment and is thus not sent.) The experiments in the diagonal +below expect double that number, that is, `1 * 800 tx/s * 89 s = 71200`, but the +system is not able to process such load, thus it is saturated. + +Therefore, for the rest of these experiments, we chose `c=1,r=400` as the +configuration. We could have chosen the equivalent `c=2,r=200`, which is the same +used in our baseline version, but for simplicity we decided to use the one with +only one connection. + +Also note that, compared to the previous QA tests, we have tried to find the +saturation point within a higher range of load values for the rate `r`. In +particular we run tests with `r` equal to or above `200`, while in the previous +tests `r` was `200` or lower. In particular, for our baseline version we didn't +run the experiment on the configuration `c=1,r=400`. + +For comparison, this is the table with the baseline version, where the +saturation point is beyond the diagonal defined by `r=200,c=2` and `r=100,c=4`. + +| | c=1 | c=2 | c=4 | +| ----- | ----: | --------: | --------: | +| r=25 | 2225 | 4450 | 8900 | +| r=50 | 4450 | 8900 | 17800 | +| r=100 | 8900 | 17800 | **35600** | +| r=200 | 17800 | **35600** | 38660 | + +### Latencies + +The following figure plots the latencies of the experiment carried out with the +configuration `c=1,r=400`. + +![latency-1-400](img38/200nodes/e_de676ecf-038e-443f-a26a-27915f29e312.png). + +For reference, the following figure shows the latencies of one of the +experiments for `c=2,r=200` in the baseline. + +![latency-2-200-37](img37/200nodes_cmt037/e_75cb89a8-f876-4698-82f3-8aaab0b361af.png) + +As can be seen, in most cases the latencies are very similar, and in some cases, +the baseline has slightly higher latencies than the version under test. Thus, +from this small experiment, we can say that the latencies measured on the two +versions are equivalent, or at least that the version under test is not worse +than the baseline. + +### Prometheus Metrics on the Chosen Experiment + +This section further examines key metrics for this experiment extracted from +Prometheus data regarding the chosen experiment with configuration `c=1,r=400`. + +#### Mempool Size + +The mempool size, a count of the number of transactions in the mempool, was +shown to be stable and homogeneous at all full nodes. It did not exhibit any +unconstrained growth. The plot below shows the evolution over time of the +cumulative number of transactions inside all full nodes' mempools at a given +time. + +![mempoool-cumulative](img38/200nodes/mempool_size.png) + +The following picture shows the evolution of the average mempool size over all +full nodes, which mostly oscilates between 1000 and 2500 outstanding +transactions. + +![mempool-avg](img38/200nodes/avg_mempool_size.png) + +The peaks observed coincide with the moments when some nodes reached round 1 of +consensus (see below). + +The behavior is similar to the observed in the baseline, presented next. + +![mempool-cumulative-baseline](img37/200nodes_cmt037/mempool_size.png) + +![mempool-avg-baseline](img37/200nodes_cmt037/avg_mempool_size.png) + + +#### Peers + +The number of peers was stable at all nodes. It was higher for the seed nodes +(around 140) than for the rest (between 20 and 70 for most nodes). The red +dashed line denotes the average value. + +![peers](img38/200nodes/peers.png) + +Just as in the baseline, shown next, the fact that non-seed nodes reach more +than 50 peers is due to [\#9548]. + +![peers](img37/200nodes_cmt037/peers.png) + + +#### Consensus Rounds per Height + +Most heights took just one round, that is, round 0, but some nodes needed to +advance to round 1. + +![rounds](img38/200nodes/rounds.png) + +The following specific run of the baseline required some nodes to reach round 1. + +![rounds](img37/200nodes_cmt037/rounds.png) + + +#### Blocks Produced per Minute, Transactions Processed per Minute + +The following plot shows the rate in which blocks were created, from the point +of view of each node. That is, it shows when each node learned that a new block +had been agreed upon. + +![heights](img38/200nodes/block_rate.png) + +For most of the time when load was being applied to the system, most of the +nodes stayed around 20 blocks/minute. + +The spike to more than 100 blocks/minute is due to a slow node catching up. + +The baseline experienced a similar behavior. + +![heights-baseline](img37/200nodes_cmt037/block_rate.png) + +The collective spike on the right of the graph marks the end of the load +injection, when blocks become smaller (empty) and impose less strain on the +network. This behavior is reflected in the following graph, which shows the +number of transactions processed per minute. + +![total-txs](img38/200nodes/total_txs_rate.png) + +The following is the transaction processing rate of the baseline, which is +similar to above. + +![total-txs-baseline](img37/200nodes_cmt037/total_txs_rate.png) + + +#### Memory Resident Set Size + +The following graph shows the Resident Set Size of all monitored processes, with +maximum memory usage of 1.6GB, slightly lower than the baseline shown after. + +![rss](img38/200nodes/memory.png) + +A similar behavior was shown in the baseline, with even a slightly higher memory +usage. + +![rss](img37/200nodes_cmt037/memory.png) + +The memory of all processes went down as the load is removed, showing no signs +of unconstrained growth. + + +#### CPU utilization + +##### Comparison to baseline + +The best metric from Prometheus to gauge CPU utilization in a Unix machine is +`load1`, as it usually appears in the [output of +`top`](https://www.digitalocean.com/community/tutorials/load-average-in-linux). + +The load is contained below 5 on most nodes, as seen in the following graph. + +![load1](img38/200nodes/cpu.png) + +The baseline had a similar behavior. + +![load1-baseline](img37/200nodes_cmt037/cpu.png) + +##### Impact of vote extension signature verification + +It is important to notice that the baseline (`v0.37.x`) does not implement vote extensions, +whereas the version under test (`v0.38.0-alpha.2`) _does_ implement them, and they are +configured to be activated since height 1. +The e2e application used in these tests verifies all received vote extension signatures (up to 175) +twice per height: upon `PrepareProposal` (for sanity) and upon `ProcessProposal` (to demonstrate how +real applications can do it). + +The fact that there is no noticeable difference in the CPU utilization plots of +the baseline and `v0.38.0-alpha.2` means that re-verifying up 175 vote extension signatures twice +(besides the initial verification done by CometBFT when receiving them from the network) +has no performance impact in the current version of the system: the bottlenecks are elsewhere. +Thus, we should focus on optimizing other parts of the system: the ones that cause the current +bottlenecks (mempool gossip duplication, leaner proposal structure, optimized consensus gossip). + +### Test Results + +The comparison against the baseline results show that both scenarios had similar +numbers and are therefore equivalent. + +A conclusion of these tests is shown in the following table, along with the +commit versions used in the experiments. + +| Scenario | Date | Version | Result | +| -------- | ---------- | ---------------------------------------------------------- | ------ | +| 200-node | 2023-05-21 | v0.38.0-alpha.2 (1f524d12996204f8fd9d41aa5aca215f80f06f5e) | Pass | + + +## Rotating Node Testnet + +We use `c=1,r=400` as load, which can be considered a safe workload, as it was close to (but below) +the saturation point in the 200 node testnet. This testnet has less nodes (10 validators and 25 full nodes). + +Importantly, the baseline considered in this section is `v0.37.0-alpha.2` (Tendermint Core), +which is **different** from the one used in the [previous section](method.md#200-node-testnet). +The reason is that this testnet was not re-tested for `v0.37.0-alpha.3` (CometBFT), +since it was not deemed necessary. + +Unlike in the baseline tests, the version of CometBFT used for these tests is _not_ affected by [\#9539], +which was fixed right after having run rotating testnet for `v0.37`. +As a result, the load introduced in this iteration of the test is higher as transactions do not get rejected. + +### Latencies + +The plot of all latencies can be seen here. + +![rotating-all-latencies](img38/rotating/rotating_latencies.png) + +Which is similar to the baseline. + +![rotating-all-latencies](img37/200nodes_tm037/v037_rotating_latencies.png) + +The average increase of about 1 second with respect to the baseline is due to the higher +transaction load produced (remember the baseline was affected by [\#9539], whereby most transactions +produced were rejected by `CheckTx`). + +### Prometheus Metrics + +The set of metrics shown here roughly match those shown on the baseline (`v0.37`) for the same experiment. +We also show the baseline results for comparison. + +#### Blocks and Transactions per minute + +This following plot shows the blocks produced per minute. + +![rotating-heights](img38/rotating/rotating_block_rate.png) + +This is similar to the baseline, shown below. + +![rotating-heights-bl](img37/rotating/rotating_block_rate.png) + +The following plot shows only the heights reported by ephemeral nodes, both when they were blocksyncing +and when they were running consensus. +The second plot is the baseline plot for comparison. The baseline lacks the heights when the nodes were +blocksyncing as that metric was implemented afterwards. + +![rotating-heights-ephe](img38/rotating/rotating_eph_heights.png) + +![rotating-heights-ephe-bl](img37/rotating/rotating_eph_heights.png) + +We seen that heights follow a similar pattern in both plots: they grow in length as the experiment advances. + +The following plot shows the transactions processed per minute. + +![rotating-total-txs](img38/rotating/rotating_txs_rate.png) + +For comparison, this is the baseline plot. + +![rotating-total-txs-bl](img37/rotating/rotating_txs_rate.png) + +We can see the rate is much lower in the baseline plot. +The reason is that the baseline was affected by [\#9539], whereby `CheckTx` rejected most transactions +produced by the load runner. + +#### Peers + +The plot below shows the evolution of the number of peers throughout the experiment. + +![rotating-peers](img38/rotating/rotating_peers.png) + +This is the baseline plot, for comparison. + +![rotating-peers-bl](img37/rotating/rotating_peers.png) + +The plotted values and their evolution are comparable in both plots. + +For further details on these plots, see the [this section](./TMCore-QA-34.md#peers-1). + +#### Memory Resident Set Size + +The average Resident Set Size (RSS) over all processes is notably bigger on `v0.38.0-alpha.2` than on the baseline. +The reason for this is, again, the fact that `CheckTx` was rejecting most transactions submitted on the baseline +and therefore the overall transaction load was lower on the baseline. +This is consistent with the difference seen in the transaction rate plots +in the [previous section](#blocks-and-transactions-per-minute). + +![rotating-rss-avg](img38/rotating/rotating_avg_memory.png) + +![rotating-rss-avg-bl](img37/rotating/rotating_avg_memory.png) + +#### CPU utilization + +The plots show metric `load1` for all nodes for `v0.38.0-alpha.2` and for the baseline. + +![rotating-load1](img38/rotating/rotating_cpu.png) + +![rotating-load1-bl](img37/rotating/rotating_cpu.png) + +In both cases, it is contained under 5 most of the time, which is considered normal load. +The load seems to be more important on `v0.38.0-alpha.2` on average because of the bigger +number of transactions processed per minute as compared to the baseline. + +### Test Result + +| Scenario | Date | Version | Result | +| -------- | ---------- | ---------------------------------------------------------- | ------ | +| Rotating | 2023-05-23 | v0.38.0-alpha.2 (e9abb116e29beb830cf111b824c8e2174d538838) | Pass | + + + +## Vote Extensions Testbed + +In this testnet we evaluate the effect of varying the sizes of vote extensions added to pre-commit votes on the performance of CometBFT. +The test uses the Key/Value store in our [[end-to-end]] test framework, which has the following simplified flow: + +1. When validators send their pre-commit votes to a block of height $i$, they first extend the vote as they see fit in `ExtendVote`. +2. When a proposer for height $i+1$ creates a block to propose, in `PrepareProposal`, it prepends the transactions with a special transaction, which modifies a reserved key. The transaction value is derived from the extensions from height $i$; in this example, the value is derived from the vote extensions and includes the set itself, hexa encoded as string. +3. When a validator sends their pre-vote for the block proposed in $i+1$, they first double check in `ProcessProposal` that the special transaction in the block was properly built by the proposer. +4. When validators send their pre-commit for the block proposed in $i+1$, they first extend the vote, and the steps repeat for heights $i+2$ and so on. + +For this test, extensions are random sequences of bytes with a predefined `vote_extension_size`. +Hence, two effects are seen on the network. +First, pre-commit vote message sizes will increase by the specified `vote_extension_size` and, second, block messages will increase by twice `vote_extension_size`, given then hexa encoding of extensions, times the number of extensions received, i.e. at least 2/3 of 175. + +All tests were performed on commit d5baba237ab3a04c1fd4a7b10927ba2e6a2aab27, which corresponds to v0.38.0-alpha.2 plus commits to add the ability to vary the vote extension sizes to the test application. +Although the same commit is used for the baseline, in this configuration the behavior observed is the same as in the "vanilla" v0.38.0-alpha.2 test application, that is, vote extensions are 8-byte integers, compressed as variable size integers instead of a random sequence of size `vote_extension_size`. + +The following table summarizes the test cases. + +| Name | Extension Size (bytes) | Date | +| -------- | ---------------------- | ---------- | +| baseline | 8 (varint) | 2023-05-26 | +| 2k | 2048 | 2023-05-29 | +| 4k | 4094 | 2023-05-29 | +| 8k | 8192 | 2023-05-26 | +| 16k | 16384 | 2023-05-26 | +| 32k | 32768 | 2023-05-26 | + + +### Latency + +The following figures show the latencies observed on each of the 5 runs of each experiment; +the redline shows the average of each run. +It can be easily seen from these graphs that the larger the vote extension size, the more latency varies and the more common higher latencies become. +Even in the case of extensions of size 2k, the mean latency goes from below 5s to nearly 10s. + +**Baseline** + +![](img38/voteExtensions/all_experiments_baseline.png) + +**2k** + +![](img38/voteExtensions/all_experiments_2k.png) + +**4k** + +![](img38/voteExtensions/all_experiments_4k.png) + +**8k** + +![](img38/voteExtensions/all_experiments_8k.png) + +**16k** + +![](img38/voteExtensions/all_experiments_16k.png) + +**32k** + +![](img38/voteExtensions/all_experiments_32k.png) + +The following graphs combine all the runs of the same experiment. +They show that latency variation greatly increases with the increase of vote extensions. +In particular, for the 16k and 32k cases, the system goes through large gaps without transaction delivery. +As discussed later, this is the result of heights taking multiple rounds to finish and new transactions being held until the next block is agreed upon. + +| | | +| ---------------------------------------------------------- | ------------------------------------------------ | +| baseline ![](img38/voteExtensions/all_c1r400_baseline.png) | 2k ![](img38/voteExtensions/all_c1r400_2k.png) | +| 4k ![](img38/voteExtensions/all_c1r400_4k.png) | 8k ![](img38/voteExtensions/all_c1r400_8k.png) | +| 16k ![](img38/voteExtensions/all_c1r400_16k.png) | 32k ![](img38/voteExtensions/all_c1r400_32k.png) | + + +### Blocks and Transactions per minute + +The following plots show the blocks produced per minute and transactions processed per minute. +We have divided the presentation in an overview section, which shows the metrics for the whole experiment (five runs) and a detailed sample, which shows the metrics for the first of the five runs. +We repeat the approach for the other metrics as well. +The dashed red line shows the moving average over a 20s window. + +#### Overview + +It is clear from the overview plots that as the vote extension sizes increase, the rate of block creation decreases. +Although the rate of transaction processing also decreases, it does not seem to decrease as fast. + +| Experiment | Block creation rate | Transaction rate | +| ------------ | ----------------------------------------------------------- | ------------------------------------------------------------- | +| **baseline** | ![block rate](img38/voteExtensions/baseline_block_rate.png) | ![txs rate](img38/voteExtensions/baseline_total_txs_rate.png) | +| **2k** | ![block rate](img38/voteExtensions/02k_block_rate.png) | ![txs rate](img38/voteExtensions/02k_total_txs_rate.png) | +| **4k** | ![block rate](img38/voteExtensions/04k_block_rate.png) | ![txs rate](img38/voteExtensions/04k_total_txs_rate.png) | +| **8k** | ![block rate](img38/voteExtensions/8k_block_rate.png) | ![txs rate](img38/voteExtensions/08k_total_txs_rate.png) | +| **16k** | ![block rate](img38/voteExtensions/16k_block_rate.png) | ![txs rate](img38/voteExtensions/16k_total_txs_rate.png) | +| **32k** | ![block rate](img38/voteExtensions/32k_block_rate.png) | ![txs rate](img38/voteExtensions/32k_total_txs_rate.png) | + +#### First run + +| Experiment | Block creation rate | Transaction rate | +| ------------ | ------------------------------------------------------------- | --------------------------------------------------------------- | +| **baseline** | ![block rate](img38/voteExtensions/baseline_1_block_rate.png) | ![txs rate](img38/voteExtensions/baseline_1_total_txs_rate.png) | +| **2k** | ![block rate](img38/voteExtensions/02k_1_block_rate.png) | ![txs rate](img38/voteExtensions/02k_1_total_txs_rate.png) | +| **4k** | ![block rate](img38/voteExtensions/04k_1_block_rate.png) | ![txs rate](img38/voteExtensions/04k_1_total_txs_rate.png) | +| **8k** | ![block rate](img38/voteExtensions/08k_1_block_rate.png) | ![txs rate](img38/voteExtensions/08k_1_total_txs_rate.png) | +| **16k** | ![block rate](img38/voteExtensions/16k_1_block_rate.png) | ![txs rate](img38/voteExtensions/16k_1_total_txs_rate.png) | +| **32k** | ![block rate](img38/voteExtensions/32k_1_block_rate.png) | ![txs rate](img38/voteExtensions/32k_1_total_txs_rate.png) | + + +### Number of rounds + +The effect of vote extensions are also felt on the number of rounds needed to reach consensus. +The following graphs show the number of the highest round required to reach consensus during the whole experiment. + +In the baseline and low vote extension lengths, most blocks were agreed upon during round 0. +As the load increases, more and more rounds were required. +In the 32k case se see round 5 being reached frequently. + +| Experiment | Number of Rounds per block | +| ------------ | ------------------------------------------------------------- | +| **baseline** | ![number of rounds](img38/voteExtensions/baseline_rounds.png) | +| **2k** | ![number of rounds](img38/voteExtensions/02k_rounds.png) | +| **4k** | ![number of rounds](img38/voteExtensions/04k_rounds.png) | +| **8k** | ![number of rounds](img38/voteExtensions/08k_rounds.png) | +| **16k** | ![number of rounds](img38/voteExtensions/16k_rounds.png) | +| **32k** | ![number of rounds](img38/voteExtensions/32k_rounds.png) | + + +We conjecture that the reason is that the timeouts used are inadequate for the extra traffic in the network. + +### CPU + +The CPU usage reached the same peaks on all tests, but the following graphs show that with larger Vote Extensions, nodes take longer to reduce the CPU usage. +This could mean that a backlog of processing is forming during the execution of the tests with larger extensions. + + +| Experiment | CPU | +| ------------ | ----------------------------------------------------- | +| **baseline** | ![cpu-avg](img38/voteExtensions/baseline_avg_cpu.png) | +| **2k** | ![cpu-avg](img38/voteExtensions/02k_avg_cpu.png) | +| **4k** | ![cpu-avg](img38/voteExtensions/04k_avg_cpu.png) | +| **8k** | ![cpu-avg](img38/voteExtensions/08k_avg_cpu.png) | +| **16k** | ![cpu-avg](img38/voteExtensions/16k_avg_cpu.png) | +| **32k** | ![cpu-avg](img38/voteExtensions/32k_avg_cpu.png) | + +### Resident Memory + +The same conclusion reached for CPU usage may be drawn for the memory. +That is, that a backlog of work is formed during the tests and catching up (freeing of memory) happens after the test is done. + +A more worrying trend is that the bottom of the memory usage seems to increase in between runs. +We have investigated this in longer runs and confirmed that there is no such a trend. + + + +| Experiment | Resident Set Size | +| ------------ | -------------------------------------------------------- | +| **baseline** | ![rss-avg](img38/voteExtensions/baseline_avg_memory.png) | +| **2k** | ![rss-avg](img38/voteExtensions/02k_avg_memory.png) | +| **4k** | ![rss-avg](img38/voteExtensions/04k_avg_memory.png) | +| **8k** | ![rss-avg](img38/voteExtensions/08k_avg_memory.png) | +| **16k** | ![rss-avg](img38/voteExtensions/16k_avg_memory.png) | +| **32k** | ![rss-avg](img38/voteExtensions/32k_avg_memory.png) | + +### Mempool size + +This metric shows how many transactions are outstanding in the nodes' mempools. +Observe that in all runs, the average number of transactions in the mempool quickly drops to near zero between runs. + + +| Experiment | Resident Set Size | +| ------------ | ------------------------------------------------------------------ | +| **baseline** | ![mempool-avg](img38/voteExtensions/baseline_avg_mempool_size.png) | +| **2k** | ![mempool-avg](img38/voteExtensions/02k_avg_mempool_size.png) | +| **4k** | ![mempool-avg](img38/voteExtensions/04k_avg_mempool_size.png) | +| **8k** | ![mempool-avg](img38/voteExtensions/08k_avg_mempool_size.png) | +| **16k** | ![mempool-avg](img38/voteExtensions/16k_avg_mempool_size.png) | +| **32k** | ![mempool-avg](img38/voteExtensions/32k_avg_mempool_size.png) | + + + + + +### Results + +| Scenario | Date | Version | Result | +| -------- | ---------- | ------------------------------------------------------------------------------------- | ------ | +| VESize | 2023-05-23 | v0.38.0-alpha.2 + varying vote extensions (9fc711b6514f99b2dc0864fc703cb81214f01783) | N/A | + + + +[\#9539]: https://github.com/tendermint/tendermint/issues/9539 +[\#9548]: https://github.com/tendermint/tendermint/issues/9548 +[\#539]: https://github.com/cometbft/cometbft/issues/539 +[\#546]: https://github.com/cometbft/cometbft/issues/546 +[\#562]: https://github.com/cometbft/cometbft/issues/562 +[end-to-end]: https://github.com/cometbft/cometbft/tree/main/test/e2e diff --git a/docs/qa/README.md b/docs/qa/README.md new file mode 100644 index 0000000..701da81 --- /dev/null +++ b/docs/qa/README.md @@ -0,0 +1,26 @@ +--- +order: 1 +parent: + title: CometBFT Quality Assurance + description: This is a report on the process followed and results obtained when running v0.34.x on testnets + order: 6 +--- + +# CometBFT Quality Assurance + +This directory keeps track of the process followed by the CometBFT team +for Quality Assurance before cutting a release. +This directory is to live in multiple branches. On each release branch, +the contents of this directory reflect the status of the process +at the time the Quality Assurance process was applied for that release. + +File [method](./method.md) keeps track of the process followed to obtain the results +used to decide if a release is passing the Quality Assurance process. +The results obtained in each release are stored in their own directory. +The following releases have undergone the Quality Assurance process, and the corresponding reports include detailed information on tests and comparison with the baseline. + +* [TM v0.34.x](TMCore-QA-34.md) - Tested prior to releasing Tendermint Core v0.34.22. +* [v0.34.x](CometBFT-QA-34.md) - Tested prior to releasing v0.34.27, using TM v0.34.x results as baseline. +* [TM v0.37.x](TMCore-QA-37.md) - Tested prior to releasing TM v0.37.x, using TM v0.34.x results as baseline. +* [v0.37.x](CometBFT-QA-37.md) - Tested on CometBFT v0.37.0-alpha3, using TM v0.37.x results as baseline. +* [v0.38.x](CometBFT-QA-38.md) - Tested on v0.38.0-alpha.2, using v0.37.x results as baseline. diff --git a/docs/qa/TMCore-QA-34.md b/docs/qa/TMCore-QA-34.md new file mode 100644 index 0000000..1f3cae6 --- /dev/null +++ b/docs/qa/TMCore-QA-34.md @@ -0,0 +1,277 @@ +--- +order: 1 +parent: + title: Tendermint Core QA Results v0.34.x + description: This is a report on the results obtained when running v0.34.x on testnets + order: 2 +--- + +# Tendermint Core QA Results v0.34.x + +## 200 Node Testnet + +### Finding the Saturation Point + +The first goal when examining the results of the tests is identifying the saturation point. +The saturation point is a setup with a transaction load big enough to prevent the testnet +from being stable: the load runner tries to produce slightly more transactions than can +be processed by the testnet. + +The following table summarizes the results for v0.34.x, for the different experiments +(extracted from file [`v034_report_tabbed.txt`](img34/v034_report_tabbed.txt)). + +The X axis of this table is `c`, the number of connections created by the load runner process to the target node. +The Y axis of this table is `r`, the rate or number of transactions issued per second. + +| | c=1 | c=2 | c=4 | +| :--- | ----: | ----: | ----: | +| r=25 | 2225 | 4450 | 8900 | +| r=50 | 4450 | 8900 | 17800 | +| r=100 | 8900 | 17800 | 35600 | +| r=200 | 17800 | 35600 | 38660 | + +The table shows the number of 1024-byte-long transactions that were produced by the load runner, +and processed by Tendermint Core, during the 90 seconds of the experiment's duration. +Each cell in the table refers to an experiment with a particular number of websocket connections (`c`) +to a chosen validator, and the number of transactions per second that the load runner +tries to produce (`r`). Note that the overall load that the tool attempts to generate is $c \cdot r$. + +We can see that the saturation point is beyond the diagonal that spans cells + +* `r=200,c=2` +* `r=100,c=4` + +given that the total number of transactions should be close to the product rate X the number of connections x experiment time. + +All experiments below the saturation diagonal (`r=200,c=4`) have in common that the total +number of transactions processed is noticeably less than the product $c \cdot r \cdot 89$ (89 seconds, since the last batch never gets sent), +which is the expected number of transactions when the system is able to deal well with the +load. +With (`r=200,c=4`), we obtained 38660 whereas the theoretical number of transactions should +have been $200 \cdot 4 \cdot 89 = 71200$. + +At this point, we chose an experiment at the limit of the saturation diagonal, +in order to further study the performance of this release. +**The chosen experiment is (`r=200,c=2`)**. + +This is a plot of the CPU load (average over 1 minute, as output by `top`) of the load runner for (`r=200,c=2`), +where we can see that the load stays close to 0 most of the time. + +![load-load-runner](img34/v034_r200c2_load-runner.png) + +### Examining latencies + +The method described [here](method.md) allows us to plot the latencies of transactions +for all experiments. + +![all-latencies](img34/v034_200node_latencies.png) + +As we can see, even the experiments beyond the saturation diagonal managed to keep +transaction latency stable (i.e. not constantly increasing). +Our interpretation for this is that contention within Tendermint Core was propagated, +via the websockets, to the load runner, +hence the load runner could not produce the target load, but a fraction of it. + +Further examination of the Prometheus data (see below), showed that the mempool contained many transactions +at steady state, but did not grow much without quickly returning to this steady state. This demonstrates +that Tendermint Core network was able to process transactions at least as quickly as they +were submitted to the mempool. Finally, the test script made sure that, at the end of an experiment, the +mempool was empty so that all transactions submitted to the chain were processed. + +Finally, the number of points present in the plot appears to be much less than expected given the +number of transactions in each experiment, particularly close to or above the saturation diagonal. +This is a visual effect of the plot; what appear to be points in the plot are actually potentially huge +clusters of points. To corroborate this, we have zoomed in the plot above by setting (carefully chosen) +tiny axis intervals. The cluster shown below looks like a single point in the plot above. + +![all-latencies-zoomed](img34/v034_200node_latencies_zoomed.png) + +The plot of latencies can we used as a baseline to compare with other releases. + +The following plot summarizes average latencies versus overall throughput +across different numbers of WebSocket connections to the node into which +transactions are being loaded. + +![latency-vs-throughput](img34/v034_latency_throughput.png) + +### Prometheus Metrics on the Chosen Experiment + +As mentioned [above](#finding-the-saturation-point), the chosen experiment is `r=200,c=2`. +This section further examines key metrics for this experiment extracted from Prometheus data. + +#### Mempool Size + +The mempool size, a count of the number of transactions in the mempool, was shown to be stable and homogeneous +at all full nodes. It did not exhibit any unconstrained growth. +The plot below shows the evolution over time of the cumulative number of transactions inside all full nodes' mempools +at a given time. +The two spikes that can be observed correspond to a period where consensus instances proceeded beyond the initial round +at some nodes. + +![mempool-cumulative](img34/v034_r200c2_mempool_size.png) + +The plot below shows evolution of the average over all full nodes, which oscillates between 1500 and 2000 +outstanding transactions. + +![mempool-avg](img34/v034_r200c2_mempool_size_avg.png) + +The peaks observed coincide with the moments when some nodes proceeded beyond the initial round of consensus (see below). + +#### Peers + +The number of peers was stable at all nodes. +It was higher for the seed nodes (around 140) than for the rest (between 21 and 74). +The fact that non-seed nodes reach more than 50 peers is due to #9548. + +![peers](img34/v034_r200c2_peers.png) + +#### Consensus Rounds per Height + +Most nodes used only round 0 for most heights, but some nodes needed to advance to round 1 for some heights. + +![rounds](img34/v034_r200c2_rounds.png) + +#### Blocks Produced per Minute, Transactions Processed per Minute + +The blocks produced per minute are the slope of this plot. + +![heights](img34/v034_r200c2_heights.png) + +Over a period of 2 minutes, the height goes from 530 to 569. +This results in an average of 19.5 blocks produced per minute. + +The transactions processed per minute are the slope of this plot. + +![total-txs](img34/v034_r200c2_total-txs.png) + +Over a period of 2 minutes, the total goes from 64525 to 100125 transactions, +resulting in 17800 transactions per minute. However, we can see in the plot that +all transactions in the load are processed long before the two minutes. +If we adjust the time window when transactions are processed (approx. 105 seconds), +we obtain 20343 transactions per minute. + +#### Memory Resident Set Size + +Resident Set Size of all monitored processes is plotted below. + +![rss](img34/v034_r200c2_rss.png) + +The average over all processes oscillates around 1.2 GiB and does not demonstrate unconstrained growth. + +![rss-avg](img34/v034_r200c2_rss_avg.png) + +#### CPU utilization + +The best metric from Prometheus to gauge CPU utilization in a Unix machine is `load1`, +as it usually appears in the +[output of `top`](https://www.digitalocean.com/community/tutorials/load-average-in-linux). + +![load1](img34/v034_r200c2_load1.png) + +It is contained in most cases below 5, which is generally considered acceptable load. + +### Test Result + +**Result: N/A** (v0.34.x is the baseline) + +Date: 2022-10-14 + +Version: 3ec6e424d6ae4c96867c2dcf8310572156068bb6 + +## Rotating Node Testnet + +For this testnet, we will use a load that can safely be considered below the saturation +point for the size of this testnet (between 13 and 38 full nodes): `c=4,r=800`. + +N.B.: The version of CometBFT used for these tests is affected by #9539. +However, the reduced load that reaches the mempools is orthogonal to functionality +we are focusing on here. + +### Latencies + +The plot of all latencies can be seen in the following plot. + +![rotating-all-latencies](img34/v034_rotating_latencies.png) + +We can observe there are some very high latencies, towards the end of the test. +Upon suspicion that they are duplicate transactions, we examined the latencies +raw file and discovered there are more than 100K duplicate transactions. + +The following plot shows the latencies file where all duplicate transactions have +been removed, i.e., only the first occurrence of a duplicate transaction is kept. + +![rotating-all-latencies-uniq](img34/v034_rotating_latencies_uniq.png) + +This problem, existing in `v0.34.x`, will need to be addressed, perhaps in the same way +we addressed it when running the 200 node test with high loads: increasing the `cache_size` +configuration parameter. + +### Prometheus Metrics + +The set of metrics shown here are less than for the 200 node experiment. +We are only interested in those for which the catch-up process (blocksync) may have an impact. + +#### Blocks and Transactions per minute + +Just as shown for the 200 node test, the blocks produced per minute are the gradient of this plot. + +![rotating-heights](img34/v034_rotating_heights.png) + +Over a period of 5229 seconds, the height goes from 2 to 3638. +This results in an average of 41 blocks produced per minute. + +The following plot shows only the heights reported by ephemeral nodes +(which are also included in the plot above). Note that the _height_ metric +is only showed _once the node has switched to consensus_, hence the gaps +when nodes are killed, wiped out, started from scratch, and catching up. + +![rotating-heights-ephe](img34/v034_rotating_heights_ephe.png) + +The transactions processed per minute are the gradient of this plot. + +![rotating-total-txs](img34/v034_rotating_total-txs.png) + +The small lines we see periodically close to `y=0` are the transactions that +ephemeral nodes start processing when they are caught up. + +Over a period of 5229 minutes, the total goes from 0 to 387697 transactions, +resulting in 4449 transactions per minute. We can see some abrupt changes in +the plot's gradient. This will need to be investigated. + +#### Peers + +The plot below shows the evolution in peers throughout the experiment. +The periodic changes observed are due to the ephemeral nodes being stopped, +wiped out, and recreated. + +![rotating-peers](img34/v034_rotating_peers.png) + +The validators' plots are concentrated at the higher part of the graph, whereas the ephemeral nodes +are mostly at the lower part. + +#### Memory Resident Set Size + +The average Resident Set Size (RSS) over all processes seems stable, and slightly growing toward the end. +This might be related to the increased in transaction load observed above. + +![rotating-rss-avg](img34/v034_rotating_rss_avg.png) + +The memory taken by the validators and the ephemeral nodes (when they are up) is comparable. + +#### CPU utilization + +The plot shows metric `load1` for all nodes. + +![rotating-load1](img34/v034_rotating_load1.png) + +It is contained under 5 most of the time, which is considered normal load. +The purple line, which follows a different pattern is the validator receiving all +transactions, via RPC, from the load runner process. + +### Test Result + +**Result: N/A** + +Date: 2022-10-10 + +Version: a28c987f5a604ff66b515dd415270063e6fb069d diff --git a/docs/qa/TMCore-QA-37.md b/docs/qa/TMCore-QA-37.md new file mode 100644 index 0000000..4c40bfd --- /dev/null +++ b/docs/qa/TMCore-QA-37.md @@ -0,0 +1,324 @@ +--- +order: 1 +parent: + title: Tendermint Core QA Results v0.37.x + description: This is a report on the results obtained when running TM v0.37.x on testnets + order: 4 +--- + +# Tendermint Core QA Results v0.37.x + +## Issues discovered + +During this iteration of the QA process, the following issues were found: + +* (critical, fixed) [\#9533] - This bug caused full nodes to sometimes get stuck + when blocksyncing, requiring a manual restart to unblock them. Importantly, + this bug was also present in v0.34.x and the fix was also backported in + [\#9534]. +* (critical, fixed) [\#9539] - `loadtime` is very likely to include more than + one "=" character in transactions, with is rejected by the e2e application. +* (critical, fixed) [\#9581] - Absent prometheus label makes CometBFT crash + when enabling Prometheus metric collection +* (non-critical, not fixed) [\#9548] - Full nodes can go over 50 connected + peers, which is not intended by the default configuration. +* (non-critical, not fixed) [\#9537] - With the default mempool cache setting, + duplicated transactions are not rejected when gossipped and eventually flood + all mempools. The 200 node testnets were thus run with a value of 200000 (as + opposed to the default 10000) + +## 200 Node Testnet + +### Finding the Saturation Point + +The first goal is to identify the saturation point and compare it with the baseline (v0.34.x). +For further details, see [this paragraph](TMCore-QA-34.md#finding-the-saturation-point) +in the baseline version. + +The following table summarizes the results for v0.37.x, for the different experiments +(extracted from file [`v037_report_tabbed.txt`](img37/200nodes_tm037/v037_report_tabbed.txt)). + +The X axis of this table is `c`, the number of connections created by the load runner process to the target node. +The Y axis of this table is `r`, the rate or number of transactions issued per second. + +| | c=1 | c=2 | c=4 | +| :--- | ----: | ----: | ----: | +| r=25 | 2225 | 4450 | 8900 | +| r=50 | 4450 | 8900 | 17800 | +| r=100 | 8900 | 17800 | 35600 | +| r=200 | 17800 | 35600 | 38660 | + +For comparison, this is the table with the baseline version. + +| | c=1 | c=2 | c=4 | +| :--- | ----: | ----: | ----: | +| r=25 | 2225 | 4450 | 8900 | +| r=50 | 4450 | 8900 | 17800 | +| r=100 | 8900 | 17800 | 35400 | +| r=200 | 17800 | 35600 | 37358 | + +The saturation point is beyond the diagonal: + +* `r=200,c=2` +* `r=100,c=4` + +which is at the same place as the baseline. For more details on the saturation point, see +[this paragraph](TMCore-QA-34.md#finding-the-saturation-point) in the baseline version. + +The experiment chosen to examine Prometheus metrics is the same as in the baseline: +**`r=200,c=2`**. + +The load runner's CPU load was negligible (near 0) when running `r=200,c=2`. + +### Examining latencies + +The method described [here](method.md) allows us to plot the latencies of transactions +for all experiments. + +![all-latencies](img37/200nodes_tm037/v037_200node_latencies.png) + +The data seen in the plot is similar to that of the baseline. + +![all-latencies-bl](img34/v034_200node_latencies.png) + +Therefore, for further details on these plots, +see [this paragraph](CometBFT-QA-34.md#examining-latencies) in the baseline version. + +The following plot summarizes average latencies versus overall throughputs +across different numbers of WebSocket connections to the node into which +transactions are being loaded. + +![latency-vs-throughput](img37/200nodes_tm037/v037_latency_throughput.png) + +This is similar to that of the baseline plot: + +![latency-vs-throughput-bl](img34/v034_latency_throughput.png) + +### Prometheus Metrics on the Chosen Experiment + +As mentioned [above](#finding-the-saturation-point), the chosen experiment is `r=200,c=2`. +This section further examines key metrics for this experiment extracted from Prometheus data. + +#### Mempool Size + +The mempool size, a count of the number of transactions in the mempool, was shown to be stable and homogeneous +at all full nodes. It did not exhibit any unconstrained growth. +The plot below shows the evolution over time of the cumulative number of transactions inside all full nodes' mempools +at a given time. + +![mempool-cumulative](img37/200nodes_tm037/v037_r200c2_mempool_size.png) + +The plot below shows evolution of the average over all full nodes, which oscillate between 1500 and 2000 outstanding transactions. + +![mempool-avg](img37/200nodes_tm037/v037_r200c2_mempool_size_avg.png) + +The peaks observed coincide with the moments when some nodes reached round 1 of consensus (see below). + +**These plots yield similar results to the baseline**: + +![mempool-cumulative-bl](img34/v034_r200c2_mempool_size.png) + +![mempool-avg-bl](img34/v034_r200c2_mempool_size_avg.png) + +#### Peers + +The number of peers was stable at all nodes. +It was higher for the seed nodes (around 140) than for the rest (between 16 and 78). + +![peers](img37/200nodes_tm037/v037_r200c2_peers.png) + +Just as in the baseline, the fact that non-seed nodes reach more than 50 peers is due to #9548. + +**This plot yields similar results to the baseline**: + +![peers-bl](img34/v034_r200c2_peers.png) + +#### Consensus Rounds per Height + +Most heights took just one round, but some nodes needed to advance to round 1 at some point. + +![rounds](img37/200nodes_tm037/v037_r200c2_rounds.png) + +**This plot yields slightly better results than the baseline**: + +![rounds-bl](img34/v034_r200c2_rounds.png) + +#### Blocks Produced per Minute, Transactions Processed per Minute + +The blocks produced per minute are the gradient of this plot. + +![heights](img37/200nodes_tm037/v037_r200c2_heights.png) + +Over a period of 2 minutes, the height goes from 477 to 524. +This results in an average of 23.5 blocks produced per minute. + +The transactions processed per minute are the gradient of this plot. + +![total-txs](img37/200nodes_tm037/v037_r200c2_total-txs.png) + +Over a period of 2 minutes, the total goes from 64525 to 100125 transactions, +resulting in 17800 transactions per minute. However, we can see in the plot that +all transactions in the load are process long before the two minutes. +If we adjust the time window when transactions are processed (approx. 90 seconds), +we obtain 23733 transactions per minute. + +**These plots yield similar results to the baseline**: + +![heights-bl](img34/v034_r200c2_heights.png) + +![total-txs](img34/v034_r200c2_total-txs.png) + +#### Memory Resident Set Size + +Resident Set Size of all monitored processes is plotted below. + +![rss](img37/200nodes_tm037/v037_r200c2_rss.png) + +The average over all processes oscillates around 380 MiB and does not demonstrate unconstrained growth. + +![rss-avg](img37/200nodes_tm037/v037_r200c2_rss_avg.png) + +**These plots yield similar results to the baseline**: + +![rss-bl](img34/v034_r200c2_rss.png) + +![rss-avg-bl](img34/v034_r200c2_rss_avg.png) + +#### CPU utilization + +The best metric from Prometheus to gauge CPU utilization in a Unix machine is `load1`, +as it usually appears in the +[output of `top`](https://www.digitalocean.com/community/tutorials/load-average-in-linux). + +![load1](img37/200nodes_tm037/v037_r200c2_load1.png) + +It is contained below 5 on most nodes. + +**This plot yields similar results to the baseline**: + +![load1](img34/v034_r200c2_load1.png) + +### Test Result + +**Result: PASS** + +Date: 2022-10-14 + +Version: 1cf9d8e276afe8595cba960b51cd056514965fd1 + +## Rotating Node Testnet + +We use the same load as in the baseline: `c=4,r=800`. + +Just as in the baseline tests, the version of CometBFT used for these tests is affected by #9539. +See this paragraph in the [baseline report](method.md#rotating-node-testnet) for further details. +Finally, note that this setup allows for a fairer comparison between this version and the baseline. + +### Latencies + +The plot of all latencies can be seen here. + +![rotating-all-latencies](img37/200nodes_tm037/v037_rotating_latencies.png) + +Which is similar to the baseline. + +![rotating-all-latencies-bl](img34/v034_rotating_latencies_uniq.png) + +Note that we are comparing against the baseline plot with _unique_ +transactions. This is because the problem with duplicate transactions +detected during the baseline experiment did not show up for `v0.37`, +which is _not_ proof that the problem is not present in `v0.37`. + +### Prometheus Metrics + +The set of metrics shown here match those shown on the baseline (`v0.34`) for the same experiment. +We also show the baseline results for comparison. + +#### Blocks and Transactions per minute + +The blocks produced per minute are the gradient of this plot. + +![rotating-heights](img37/200nodes_tm037/v037_rotating_heights.png) + +Over a period of 4446 seconds, the height goes from 5 to 3323. +This results in an average of 45 blocks produced per minute, +which is similar to the baseline, shown below. + +![rotating-heights-bl](img34/v034_rotating_heights.png) + +The following two plots show only the heights reported by ephemeral nodes. +The second plot is the baseline plot for comparison. + +![rotating-heights-ephe](img37/200nodes_tm037/v037_rotating_heights_ephe.png) + +![rotating-heights-ephe-bl](img34/v034_rotating_heights_ephe.png) + +By the length of the segments, we can see that ephemeral nodes in `v0.37` +catch up slightly faster. + +The transactions processed per minute are the gradient of this plot. + +![rotating-total-txs](img37/200nodes_tm037/v037_rotating_total-txs.png) + +Over a period of 3852 seconds, the total goes from 597 to 267298 transactions in one of the validators, +resulting in 4154 transactions per minute, which is slightly lower than the baseline, +although the baseline had to deal with duplicate transactions. + +For comparison, this is the baseline plot. + +![rotating-total-txs-bl](img34/v034_rotating_total-txs.png) + +#### Peers + +The plot below shows the evolution of the number of peers throughout the experiment. + +![rotating-peers](img37/200nodes_tm037/v037_rotating_peers.png) + +This is the baseline plot, for comparison. + +![rotating-peers-bl](img34/v034_rotating_peers.png) + +The plotted values and their evolution are comparable in both plots. + +For further details on these plots, see the baseline report. + +#### Memory Resident Set Size + +The average Resident Set Size (RSS) over all processes looks slightly more stable +on `v0.37` (first plot) than on the baseline (second plot). + +![rotating-rss-avg](img37/200nodes_tm037/v037_rotating_rss_avg.png) + +![rotating-rss-avg-bl](img34/v034_rotating_rss_avg.png) + +The memory taken by the validators and the ephemeral nodes when they are up is comparable (not shown in the plots), +just as observed in the baseline. + +#### CPU utilization + +The plot shows metric `load1` for all nodes. + +![rotating-load1](img37/200nodes_tm037/v037_rotating_load1.png) + +![rotating-load1-bl](img34/v034_rotating_load1.png) + +In both cases, it is contained under 5 most of the time, which is considered normal load. +The green line in the `v0.37` plot and the purple line in the baseline plot (`v0.34`) +correspond to the validators receiving all transactions, via RPC, from the load runner process. +In both cases, they oscillate around 5 (normal load). The main difference is that other +nodes are generally less loaded in `v0.37`. + +### Test Result + +**Result: PASS** + +Date: 2022-10-10 + +Version: 155110007b9d8b83997a799016c1d0844c8efbaf + +[\#9533]: https://github.com/tendermint/tendermint/pull/9533 +[\#9534]: https://github.com/tendermint/tendermint/pull/9534 +[\#9539]: https://github.com/tendermint/tendermint/issues/9539 +[\#9548]: https://github.com/tendermint/tendermint/issues/9548 +[\#9537]: https://github.com/tendermint/tendermint/issues/9537 +[\#9581]: https://github.com/tendermint/tendermint/issues/9581 diff --git a/docs/qa/img34/baseline/avg_cpu.png b/docs/qa/img34/baseline/avg_cpu.png new file mode 100644 index 0000000..c921c2d Binary files /dev/null and b/docs/qa/img34/baseline/avg_cpu.png differ diff --git a/docs/qa/img34/baseline/avg_memory.png b/docs/qa/img34/baseline/avg_memory.png new file mode 100644 index 0000000..510824b Binary files /dev/null and b/docs/qa/img34/baseline/avg_memory.png differ diff --git a/docs/qa/img34/baseline/avg_mempool_size.png b/docs/qa/img34/baseline/avg_mempool_size.png new file mode 100644 index 0000000..b7e1496 Binary files /dev/null and b/docs/qa/img34/baseline/avg_mempool_size.png differ diff --git a/docs/qa/img34/baseline/block_rate_regular.png b/docs/qa/img34/baseline/block_rate_regular.png new file mode 100644 index 0000000..1d29d9e Binary files /dev/null and b/docs/qa/img34/baseline/block_rate_regular.png differ diff --git a/docs/qa/img34/baseline/cpu.png b/docs/qa/img34/baseline/cpu.png new file mode 100644 index 0000000..cb7c5b7 Binary files /dev/null and b/docs/qa/img34/baseline/cpu.png differ diff --git a/docs/qa/img34/baseline/memory.png b/docs/qa/img34/baseline/memory.png new file mode 100644 index 0000000..1247ca8 Binary files /dev/null and b/docs/qa/img34/baseline/memory.png differ diff --git a/docs/qa/img34/baseline/mempool_size.png b/docs/qa/img34/baseline/mempool_size.png new file mode 100644 index 0000000..0851b77 Binary files /dev/null and b/docs/qa/img34/baseline/mempool_size.png differ diff --git a/docs/qa/img34/baseline/peers.png b/docs/qa/img34/baseline/peers.png new file mode 100644 index 0000000..ab14597 Binary files /dev/null and b/docs/qa/img34/baseline/peers.png differ diff --git a/docs/qa/img34/baseline/rounds.png b/docs/qa/img34/baseline/rounds.png new file mode 100644 index 0000000..325e9d0 Binary files /dev/null and b/docs/qa/img34/baseline/rounds.png differ diff --git a/docs/qa/img34/baseline/total_txs_rate_regular.png b/docs/qa/img34/baseline/total_txs_rate_regular.png new file mode 100644 index 0000000..987df6f Binary files /dev/null and b/docs/qa/img34/baseline/total_txs_rate_regular.png differ diff --git a/docs/qa/img34/cmt1tm1/all_experiments.png b/docs/qa/img34/cmt1tm1/all_experiments.png new file mode 100644 index 0000000..e765da4 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/all_experiments.png differ diff --git a/docs/qa/img34/cmt1tm1/avg_cpu.png b/docs/qa/img34/cmt1tm1/avg_cpu.png new file mode 100644 index 0000000..29256f2 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/avg_cpu.png differ diff --git a/docs/qa/img34/cmt1tm1/avg_memory.png b/docs/qa/img34/cmt1tm1/avg_memory.png new file mode 100644 index 0000000..f9789f5 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/avg_memory.png differ diff --git a/docs/qa/img34/cmt1tm1/avg_mempool_size.png b/docs/qa/img34/cmt1tm1/avg_mempool_size.png new file mode 100644 index 0000000..2ce1ac9 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/avg_mempool_size.png differ diff --git a/docs/qa/img34/cmt1tm1/block_rate_regular.png b/docs/qa/img34/cmt1tm1/block_rate_regular.png new file mode 100644 index 0000000..37b6d8e Binary files /dev/null and b/docs/qa/img34/cmt1tm1/block_rate_regular.png differ diff --git a/docs/qa/img34/cmt1tm1/cpu.png b/docs/qa/img34/cmt1tm1/cpu.png new file mode 100644 index 0000000..10e9ce2 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/cpu.png differ diff --git a/docs/qa/img34/cmt1tm1/memory.png b/docs/qa/img34/cmt1tm1/memory.png new file mode 100644 index 0000000..df8548f Binary files /dev/null and b/docs/qa/img34/cmt1tm1/memory.png differ diff --git a/docs/qa/img34/cmt1tm1/mempool_size.png b/docs/qa/img34/cmt1tm1/mempool_size.png new file mode 100644 index 0000000..fd0ba54 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/mempool_size.png differ diff --git a/docs/qa/img34/cmt1tm1/peers.png b/docs/qa/img34/cmt1tm1/peers.png new file mode 100644 index 0000000..442d73a Binary files /dev/null and b/docs/qa/img34/cmt1tm1/peers.png differ diff --git a/docs/qa/img34/cmt1tm1/rounds.png b/docs/qa/img34/cmt1tm1/rounds.png new file mode 100644 index 0000000..2d04af2 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/rounds.png differ diff --git a/docs/qa/img34/cmt1tm1/total_txs_rate_regular.png b/docs/qa/img34/cmt1tm1/total_txs_rate_regular.png new file mode 100644 index 0000000..a638b71 Binary files /dev/null and b/docs/qa/img34/cmt1tm1/total_txs_rate_regular.png differ diff --git a/docs/qa/img34/cmt2tm1/all_experiments.png b/docs/qa/img34/cmt2tm1/all_experiments.png new file mode 100644 index 0000000..520ce81 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/all_experiments.png differ diff --git a/docs/qa/img34/cmt2tm1/avg_cpu.png b/docs/qa/img34/cmt2tm1/avg_cpu.png new file mode 100644 index 0000000..a42d2c6 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/avg_cpu.png differ diff --git a/docs/qa/img34/cmt2tm1/avg_memory.png b/docs/qa/img34/cmt2tm1/avg_memory.png new file mode 100644 index 0000000..a25b397 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/avg_memory.png differ diff --git a/docs/qa/img34/cmt2tm1/avg_mempool_size.png b/docs/qa/img34/cmt2tm1/avg_mempool_size.png new file mode 100644 index 0000000..e50fff8 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/avg_mempool_size.png differ diff --git a/docs/qa/img34/cmt2tm1/block_rate_regular.png b/docs/qa/img34/cmt2tm1/block_rate_regular.png new file mode 100644 index 0000000..e441b07 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/block_rate_regular.png differ diff --git a/docs/qa/img34/cmt2tm1/cpu.png b/docs/qa/img34/cmt2tm1/cpu.png new file mode 100644 index 0000000..29c9eb4 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/cpu.png differ diff --git a/docs/qa/img34/cmt2tm1/memory.png b/docs/qa/img34/cmt2tm1/memory.png new file mode 100644 index 0000000..bd5e8f7 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/memory.png differ diff --git a/docs/qa/img34/cmt2tm1/mempool_size.png b/docs/qa/img34/cmt2tm1/mempool_size.png new file mode 100644 index 0000000..8e8e818 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/mempool_size.png differ diff --git a/docs/qa/img34/cmt2tm1/peers.png b/docs/qa/img34/cmt2tm1/peers.png new file mode 100644 index 0000000..e2601b7 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/peers.png differ diff --git a/docs/qa/img34/cmt2tm1/rounds.png b/docs/qa/img34/cmt2tm1/rounds.png new file mode 100644 index 0000000..9ebaf00 Binary files /dev/null and b/docs/qa/img34/cmt2tm1/rounds.png differ diff --git a/docs/qa/img34/cmt2tm1/total_txs_rate_regular.png b/docs/qa/img34/cmt2tm1/total_txs_rate_regular.png new file mode 100644 index 0000000..ddb217e Binary files /dev/null and b/docs/qa/img34/cmt2tm1/total_txs_rate_regular.png differ diff --git a/docs/qa/img34/homogeneous/all_experiments.png b/docs/qa/img34/homogeneous/all_experiments.png new file mode 100644 index 0000000..a432f2d Binary files /dev/null and b/docs/qa/img34/homogeneous/all_experiments.png differ diff --git a/docs/qa/img34/homogeneous/avg_cpu.png b/docs/qa/img34/homogeneous/avg_cpu.png new file mode 100644 index 0000000..c99c900 Binary files /dev/null and b/docs/qa/img34/homogeneous/avg_cpu.png differ diff --git a/docs/qa/img34/homogeneous/avg_memory.png b/docs/qa/img34/homogeneous/avg_memory.png new file mode 100644 index 0000000..22c8a19 Binary files /dev/null and b/docs/qa/img34/homogeneous/avg_memory.png differ diff --git a/docs/qa/img34/homogeneous/avg_mempool_size.png b/docs/qa/img34/homogeneous/avg_mempool_size.png new file mode 100644 index 0000000..1c02d46 Binary files /dev/null and b/docs/qa/img34/homogeneous/avg_mempool_size.png differ diff --git a/docs/qa/img34/homogeneous/block_rate_regular.png b/docs/qa/img34/homogeneous/block_rate_regular.png new file mode 100644 index 0000000..6d32b97 Binary files /dev/null and b/docs/qa/img34/homogeneous/block_rate_regular.png differ diff --git a/docs/qa/img34/homogeneous/cpu.png b/docs/qa/img34/homogeneous/cpu.png new file mode 100644 index 0000000..295d099 Binary files /dev/null and b/docs/qa/img34/homogeneous/cpu.png differ diff --git a/docs/qa/img34/homogeneous/memory.png b/docs/qa/img34/homogeneous/memory.png new file mode 100644 index 0000000..2f0a53b Binary files /dev/null and b/docs/qa/img34/homogeneous/memory.png differ diff --git a/docs/qa/img34/homogeneous/mempool_size.png b/docs/qa/img34/homogeneous/mempool_size.png new file mode 100644 index 0000000..2249a46 Binary files /dev/null and b/docs/qa/img34/homogeneous/mempool_size.png differ diff --git a/docs/qa/img34/homogeneous/peers.png b/docs/qa/img34/homogeneous/peers.png new file mode 100644 index 0000000..80de6ae Binary files /dev/null and b/docs/qa/img34/homogeneous/peers.png differ diff --git a/docs/qa/img34/homogeneous/rounds.png b/docs/qa/img34/homogeneous/rounds.png new file mode 100644 index 0000000..2413d1a Binary files /dev/null and b/docs/qa/img34/homogeneous/rounds.png differ diff --git a/docs/qa/img34/homogeneous/total_txs_rate_regular.png b/docs/qa/img34/homogeneous/total_txs_rate_regular.png new file mode 100644 index 0000000..6ccfe14 Binary files /dev/null and b/docs/qa/img34/homogeneous/total_txs_rate_regular.png differ diff --git a/docs/qa/img34/v034_200node_latencies.png b/docs/qa/img34/v034_200node_latencies.png new file mode 100644 index 0000000..310c584 Binary files /dev/null and b/docs/qa/img34/v034_200node_latencies.png differ diff --git a/docs/qa/img34/v034_200node_latencies_zoomed.png b/docs/qa/img34/v034_200node_latencies_zoomed.png new file mode 100644 index 0000000..7b89faa Binary files /dev/null and b/docs/qa/img34/v034_200node_latencies_zoomed.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/all_experiments.png b/docs/qa/img34/v034_200node_tm2cmt1/all_experiments.png new file mode 100644 index 0000000..c3b5960 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/all_experiments.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/avg_cpu.png b/docs/qa/img34/v034_200node_tm2cmt1/avg_cpu.png new file mode 100644 index 0000000..1fe3a1c Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/avg_cpu.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/avg_memory.png b/docs/qa/img34/v034_200node_tm2cmt1/avg_memory.png new file mode 100644 index 0000000..f3f045c Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/avg_memory.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/avg_mempool_size.png b/docs/qa/img34/v034_200node_tm2cmt1/avg_mempool_size.png new file mode 100644 index 0000000..624cf12 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/avg_mempool_size.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/block_rate_regular.png b/docs/qa/img34/v034_200node_tm2cmt1/block_rate_regular.png new file mode 100644 index 0000000..756a272 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/block_rate_regular.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/c2r200_merged.png b/docs/qa/img34/v034_200node_tm2cmt1/c2r200_merged.png new file mode 100644 index 0000000..1feae3c Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/c2r200_merged.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/cpu.png b/docs/qa/img34/v034_200node_tm2cmt1/cpu.png new file mode 100644 index 0000000..ea1eadc Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/cpu.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/memory.png b/docs/qa/img34/v034_200node_tm2cmt1/memory.png new file mode 100644 index 0000000..68018c3 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/memory.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/mempool_size.png b/docs/qa/img34/v034_200node_tm2cmt1/mempool_size.png new file mode 100644 index 0000000..05da64a Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/mempool_size.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/peers.png b/docs/qa/img34/v034_200node_tm2cmt1/peers.png new file mode 100644 index 0000000..d179384 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/peers.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/rounds.png b/docs/qa/img34/v034_200node_tm2cmt1/rounds.png new file mode 100644 index 0000000..a4b289b Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/rounds.png differ diff --git a/docs/qa/img34/v034_200node_tm2cmt1/total_txs_rate_regular.png b/docs/qa/img34/v034_200node_tm2cmt1/total_txs_rate_regular.png new file mode 100644 index 0000000..d8d6543 Binary files /dev/null and b/docs/qa/img34/v034_200node_tm2cmt1/total_txs_rate_regular.png differ diff --git a/docs/qa/img34/v034_latency_throughput.png b/docs/qa/img34/v034_latency_throughput.png new file mode 100644 index 0000000..3de3fdb Binary files /dev/null and b/docs/qa/img34/v034_latency_throughput.png differ diff --git a/docs/qa/img34/v034_r200c2_heights.png b/docs/qa/img34/v034_r200c2_heights.png new file mode 100644 index 0000000..bac9b16 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_heights.png differ diff --git a/docs/qa/img34/v034_r200c2_load-runner.png b/docs/qa/img34/v034_r200c2_load-runner.png new file mode 100644 index 0000000..a11f1c3 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_load-runner.png differ diff --git a/docs/qa/img34/v034_r200c2_load1.png b/docs/qa/img34/v034_r200c2_load1.png new file mode 100644 index 0000000..79deb84 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_load1.png differ diff --git a/docs/qa/img34/v034_r200c2_mempool_size.png b/docs/qa/img34/v034_r200c2_mempool_size.png new file mode 100644 index 0000000..a69bf10 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_mempool_size.png differ diff --git a/docs/qa/img34/v034_r200c2_mempool_size_avg.png b/docs/qa/img34/v034_r200c2_mempool_size_avg.png new file mode 100644 index 0000000..6a0b3b9 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_mempool_size_avg.png differ diff --git a/docs/qa/img34/v034_r200c2_peers.png b/docs/qa/img34/v034_r200c2_peers.png new file mode 100644 index 0000000..4c81325 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_peers.png differ diff --git a/docs/qa/img34/v034_r200c2_rounds.png b/docs/qa/img34/v034_r200c2_rounds.png new file mode 100644 index 0000000..a99c458 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_rounds.png differ diff --git a/docs/qa/img34/v034_r200c2_rss.png b/docs/qa/img34/v034_r200c2_rss.png new file mode 100644 index 0000000..a9625c9 Binary files /dev/null and b/docs/qa/img34/v034_r200c2_rss.png differ diff --git a/docs/qa/img34/v034_r200c2_rss_avg.png b/docs/qa/img34/v034_r200c2_rss_avg.png new file mode 100644 index 0000000..d2b590f Binary files /dev/null and b/docs/qa/img34/v034_r200c2_rss_avg.png differ diff --git a/docs/qa/img34/v034_r200c2_total-txs.png b/docs/qa/img34/v034_r200c2_total-txs.png new file mode 100644 index 0000000..95905ba Binary files /dev/null and b/docs/qa/img34/v034_r200c2_total-txs.png differ diff --git a/docs/qa/img34/v034_report_tabbed.txt b/docs/qa/img34/v034_report_tabbed.txt new file mode 100644 index 0000000..18d0785 --- /dev/null +++ b/docs/qa/img34/v034_report_tabbed.txt @@ -0,0 +1,52 @@ +Experiment ID: 3d5cf4ef-1a1a-4b46-aa2d-da5643d2e81e │Experiment ID: 80e472ec-13a1-4772-a827-3b0c907fb51d │Experiment ID: 07aca6cf-c5a4-4696-988f-e3270fc6333b + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 25 │ Rate: 25 │ Rate: 25 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 2225 │ Total Valid Tx: 4450 │ Total Valid Tx: 8900 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 599.404362ms │ Minimum Latency: 448.145181ms │ Minimum Latency: 412.485729ms + Maximum Latency: 3.539686885s │ Maximum Latency: 3.237392049s │ Maximum Latency: 12.026665368s + Average Latency: 1.441485349s │ Average Latency: 1.441267946s │ Average Latency: 2.150192457s + Standard Deviation: 541.049869ms │ Standard Deviation: 525.040007ms │ Standard Deviation: 2.233852478s + │ │ +Experiment ID: 953dc544-dd40-40e8-8712-20c34c3ce45e │Experiment ID: d31fc258-16e7-45cd-9dc8-13ab87bc0b0a │Experiment ID: 15d90a7e-b941-42f4-b411-2f15f857739e + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 50 │ Rate: 50 │ Rate: 50 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 4450 │ Total Valid Tx: 8900 │ Total Valid Tx: 17800 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 482.046942ms │ Minimum Latency: 435.458913ms │ Minimum Latency: 510.746448ms + Maximum Latency: 3.761483455s │ Maximum Latency: 7.175583584s │ Maximum Latency: 6.551497882s + Average Latency: 1.450408183s │ Average Latency: 1.681673116s │ Average Latency: 1.738083875s + Standard Deviation: 587.560056ms │ Standard Deviation: 1.147902047s │ Standard Deviation: 943.46522ms + │ │ +Experiment ID: 9a0b9980-9ce6-4db5-a80a-65ca70294b87 │Experiment ID: df8fa4f4-80af-4ded-8a28-356d15018b43 │Experiment ID: d0e41c2c-89c0-4f38-8e34-ca07adae593a + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 100 │ Rate: 100 │ Rate: 100 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 8900 │ Total Valid Tx: 17800 │ Total Valid Tx: 35600 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 477.417219ms │ Minimum Latency: 564.29247ms │ Minimum Latency: 840.71089ms + Maximum Latency: 6.63744785s │ Maximum Latency: 6.988553219s │ Maximum Latency: 9.555312398s + Average Latency: 1.561216103s │ Average Latency: 1.76419063s │ Average Latency: 3.200941683s + Standard Deviation: 1.011333552s │ Standard Deviation: 1.068459423s │ Standard Deviation: 1.732346601s + │ │ +Experiment ID: 493df3ee-4a36-4bce-80f8-6d65da66beda │Experiment ID: 13060525-f04f-46f6-8ade-286684b2fe50 │Experiment ID: 1777cbd2-8c96-42e4-9ec7-9b21f2225e4d + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 200 │ Rate: 200 │ Rate: 200 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 17800 │ Total Valid Tx: 35600 │ Total Valid Tx: 38660 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 493.705261ms │ Minimum Latency: 955.090573ms │ Minimum Latency: 1.9485821s + Maximum Latency: 7.440921872s │ Maximum Latency: 10.086673491s │ Maximum Latency: 17.73103976s + Average Latency: 1.875510582s │ Average Latency: 3.438130099s │ Average Latency: 8.143862237s + Standard Deviation: 1.304336995s │ Standard Deviation: 1.966391574s │ Standard Deviation: 3.943140002s + diff --git a/docs/qa/img34/v034_rotating_heights.png b/docs/qa/img34/v034_rotating_heights.png new file mode 100644 index 0000000..1e99aed Binary files /dev/null and b/docs/qa/img34/v034_rotating_heights.png differ diff --git a/docs/qa/img34/v034_rotating_heights_ephe.png b/docs/qa/img34/v034_rotating_heights_ephe.png new file mode 100644 index 0000000..46b865c Binary files /dev/null and b/docs/qa/img34/v034_rotating_heights_ephe.png differ diff --git a/docs/qa/img34/v034_rotating_latencies.png b/docs/qa/img34/v034_rotating_latencies.png new file mode 100644 index 0000000..7c04701 Binary files /dev/null and b/docs/qa/img34/v034_rotating_latencies.png differ diff --git a/docs/qa/img34/v034_rotating_latencies_uniq.png b/docs/qa/img34/v034_rotating_latencies_uniq.png new file mode 100644 index 0000000..e00dcce Binary files /dev/null and b/docs/qa/img34/v034_rotating_latencies_uniq.png differ diff --git a/docs/qa/img34/v034_rotating_load1.png b/docs/qa/img34/v034_rotating_load1.png new file mode 100644 index 0000000..ae699ea Binary files /dev/null and b/docs/qa/img34/v034_rotating_load1.png differ diff --git a/docs/qa/img34/v034_rotating_peers.png b/docs/qa/img34/v034_rotating_peers.png new file mode 100644 index 0000000..4c8d6f1 Binary files /dev/null and b/docs/qa/img34/v034_rotating_peers.png differ diff --git a/docs/qa/img34/v034_rotating_rss_avg.png b/docs/qa/img34/v034_rotating_rss_avg.png new file mode 100644 index 0000000..61fdfb1 Binary files /dev/null and b/docs/qa/img34/v034_rotating_rss_avg.png differ diff --git a/docs/qa/img34/v034_rotating_total-txs.png b/docs/qa/img34/v034_rotating_total-txs.png new file mode 100644 index 0000000..0cc6e11 Binary files /dev/null and b/docs/qa/img34/v034_rotating_total-txs.png differ diff --git a/docs/qa/img37/200nodes_cmt037/all_experiments.png b/docs/qa/img37/200nodes_cmt037/all_experiments.png new file mode 100644 index 0000000..9d72cc6 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/all_experiments.png differ diff --git a/docs/qa/img37/200nodes_cmt037/avg_mempool_size.png b/docs/qa/img37/200nodes_cmt037/avg_mempool_size.png new file mode 100644 index 0000000..b00ab06 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/avg_mempool_size.png differ diff --git a/docs/qa/img37/200nodes_cmt037/block_rate.png b/docs/qa/img37/200nodes_cmt037/block_rate.png new file mode 100644 index 0000000..4a529b6 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/block_rate.png differ diff --git a/docs/qa/img37/200nodes_cmt037/cpu.png b/docs/qa/img37/200nodes_cmt037/cpu.png new file mode 100644 index 0000000..ed9a182 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/cpu.png differ diff --git a/docs/qa/img37/200nodes_cmt037/e_75cb89a8-f876-4698-82f3-8aaab0b361af.png b/docs/qa/img37/200nodes_cmt037/e_75cb89a8-f876-4698-82f3-8aaab0b361af.png new file mode 100644 index 0000000..c33260a Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/e_75cb89a8-f876-4698-82f3-8aaab0b361af.png differ diff --git a/docs/qa/img37/200nodes_cmt037/memory.png b/docs/qa/img37/200nodes_cmt037/memory.png new file mode 100644 index 0000000..de52763 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/memory.png differ diff --git a/docs/qa/img37/200nodes_cmt037/mempool_size.png b/docs/qa/img37/200nodes_cmt037/mempool_size.png new file mode 100644 index 0000000..5342709 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/mempool_size.png differ diff --git a/docs/qa/img37/200nodes_cmt037/peers.png b/docs/qa/img37/200nodes_cmt037/peers.png new file mode 100644 index 0000000..312d856 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/peers.png differ diff --git a/docs/qa/img37/200nodes_cmt037/rounds.png b/docs/qa/img37/200nodes_cmt037/rounds.png new file mode 100644 index 0000000..75549b3 Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/rounds.png differ diff --git a/docs/qa/img37/200nodes_cmt037/total_txs_rate.png b/docs/qa/img37/200nodes_cmt037/total_txs_rate.png new file mode 100644 index 0000000..fd999bf Binary files /dev/null and b/docs/qa/img37/200nodes_cmt037/total_txs_rate.png differ diff --git a/docs/qa/img37/200nodes_tm037/avg_mempool_size.png b/docs/qa/img37/200nodes_tm037/avg_mempool_size.png new file mode 100644 index 0000000..e8336d1 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/avg_mempool_size.png differ diff --git a/docs/qa/img37/200nodes_tm037/block_rate_regular.png b/docs/qa/img37/200nodes_tm037/block_rate_regular.png new file mode 100644 index 0000000..95cf2d1 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/block_rate_regular.png differ diff --git a/docs/qa/img37/200nodes_tm037/cpu.png b/docs/qa/img37/200nodes_tm037/cpu.png new file mode 100644 index 0000000..84a4ba6 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/cpu.png differ diff --git a/docs/qa/img37/200nodes_tm037/memory.png b/docs/qa/img37/200nodes_tm037/memory.png new file mode 100644 index 0000000..2a9e50a Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/memory.png differ diff --git a/docs/qa/img37/200nodes_tm037/mempool_size.png b/docs/qa/img37/200nodes_tm037/mempool_size.png new file mode 100644 index 0000000..76ccbc2 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/mempool_size.png differ diff --git a/docs/qa/img37/200nodes_tm037/peers.png b/docs/qa/img37/200nodes_tm037/peers.png new file mode 100644 index 0000000..f6df41a Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/peers.png differ diff --git a/docs/qa/img37/200nodes_tm037/rounds.png b/docs/qa/img37/200nodes_tm037/rounds.png new file mode 100644 index 0000000..2b90e96 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/rounds.png differ diff --git a/docs/qa/img37/200nodes_tm037/total_txs_rate_regular.png b/docs/qa/img37/200nodes_tm037/total_txs_rate_regular.png new file mode 100644 index 0000000..ee5ec99 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/total_txs_rate_regular.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_200node_latencies.png b/docs/qa/img37/200nodes_tm037/v037_200node_latencies.png new file mode 100644 index 0000000..9134377 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_200node_latencies.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_latency_throughput.png b/docs/qa/img37/200nodes_tm037/v037_latency_throughput.png new file mode 100644 index 0000000..520617c Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_latency_throughput.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_heights.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_heights.png new file mode 100644 index 0000000..cc4a14c Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_heights.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_load1.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_load1.png new file mode 100644 index 0000000..ec33f48 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_load1.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size.png new file mode 100644 index 0000000..381d34d Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size_avg.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size_avg.png new file mode 100644 index 0000000..1d66868 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_mempool_size_avg.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_peers.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_peers.png new file mode 100644 index 0000000..2496d45 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_peers.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_rounds.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_rounds.png new file mode 100644 index 0000000..e3c4c7e Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_rounds.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_rss.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_rss.png new file mode 100644 index 0000000..d374399 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_rss.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_rss_avg.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_rss_avg.png new file mode 100644 index 0000000..ea09356 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_rss_avg.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_r200c2_total-txs.png b/docs/qa/img37/200nodes_tm037/v037_r200c2_total-txs.png new file mode 100644 index 0000000..ff47279 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_r200c2_total-txs.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_report_tabbed.txt b/docs/qa/img37/200nodes_tm037/v037_report_tabbed.txt new file mode 100644 index 0000000..35f1fe2 --- /dev/null +++ b/docs/qa/img37/200nodes_tm037/v037_report_tabbed.txt @@ -0,0 +1,52 @@ +Experiment ID: af129eae-7039-4c76-8c37-cff9ac636a84 │Experiment ID: 0f88bd33-9bf0-4197-8d1d-9a737c301ec6 │Experiment ID: 88227cad-2ba8-4eb6-b493-041d8120b46f + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 25 │ Rate: 25 │ Rate: 25 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 2225 │ Total Valid Tx: 4450 │ Total Valid Tx: 8900 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 506.248587ms │ Minimum Latency: 469.53452ms │ Minimum Latency: 588.900721ms + Maximum Latency: 3.032125789s │ Maximum Latency: 6.548830955s │ Maximum Latency: 6.533739843s + Average Latency: 1.427767726s │ Average Latency: 1.448582257s │ Average Latency: 1.717432341s + Standard Deviation: 524.11782ms │ Standard Deviation: 768.684133ms │ Standard Deviation: 1.000015768s + │ │ +Experiment ID: f03d39bd-0233-4b3c-b461-543445ae1d4b │Experiment ID: 46674f1c-e591-4e36-bb9b-f375c19fc475 │Experiment ID: 5385c159-8d4d-455b-bced-dcd4a3209988 + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 50 │ Rate: 50 │ Rate: 50 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 4450 │ Total Valid Tx: 8900 │ Total Valid Tx: 17800 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 477.46027ms │ Minimum Latency: 455.757111ms │ Minimum Latency: 594.749081ms + Maximum Latency: 2.483895394s │ Maximum Latency: 2.904715695s │ Maximum Latency: 9.294950389s + Average Latency: 1.407374662s │ Average Latency: 1.397385779s │ Average Latency: 2.621122536s + Standard Deviation: 505.150067ms │ Standard Deviation: 551.67603ms │ Standard Deviation: 1.772725794s + │ │ +Experiment ID: 9161b4a7-d75c-455f-b82d-2b5235d533cf │Experiment ID: 993a13a8-9db1-4b2b-9c20-71a5b85e4bbf │Experiment ID: ad1eb9e1-f4d6-41fd-9ba7-0f1f7dde1e3e + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 100 │ Rate: 100 │ Rate: 100 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 8900 │ Total Valid Tx: 17800 │ Total Valid Tx: 35400 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 448.050467ms │ Minimum Latency: 605.436195ms │ Minimum Latency: 1.16816912s + Maximum Latency: 3.789711139s │ Maximum Latency: 7.292770222s │ Maximum Latency: 11.378681842s + Average Latency: 1.451342158s │ Average Latency: 2.07457999s │ Average Latency: 3.918384209s + Standard Deviation: 644.075973ms │ Standard Deviation: 1.230204022s │ Standard Deviation: 2.172400458s + │ │ +Experiment ID: 3cbe9c3d-9c43-4c9f-b5ca-b567d20bbd57 │Experiment ID: af836c5e-d9b6-4d5d-971c-2fc7f07aa2a0 │Experiment ID: 77606397-4989-41d4-b13b-f1f4d1af063f + │ │ + Connections: 1 │ Connections: 2 │ Connections: 4 + Rate: 200 │ Rate: 200 │ Rate: 200 + Size: 1024 │ Size: 1024 │ Size: 1024 + │ │ + Total Valid Tx: 17800 │ Total Valid Tx: 35600 │ Total Valid Tx: 37358 + Total Negative Latencies: 0 │ Total Negative Latencies: 0 │ Total Negative Latencies: 0 + Minimum Latency: 519.984701ms │ Minimum Latency: 820.755087ms │ Minimum Latency: 1.712574804s + Maximum Latency: 12.609056712s │ Maximum Latency: 9.260798095s │ Maximum Latency: 25.739223696s + Average Latency: 2.717853101s │ Average Latency: 3.477731881s │ Average Latency: 8.547725264s + Standard Deviation: 2.390778155s │ Standard Deviation: 1.675000913s │ Standard Deviation: 4.76961569s + diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_heights.png b/docs/qa/img37/200nodes_tm037/v037_rotating_heights.png new file mode 100644 index 0000000..6170db5 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_heights.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_heights_ephe.png b/docs/qa/img37/200nodes_tm037/v037_rotating_heights_ephe.png new file mode 100644 index 0000000..1477eb0 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_heights_ephe.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_latencies.png b/docs/qa/img37/200nodes_tm037/v037_rotating_latencies.png new file mode 100644 index 0000000..985bb4c Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_latencies.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_load1.png b/docs/qa/img37/200nodes_tm037/v037_rotating_load1.png new file mode 100644 index 0000000..7404a0c Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_load1.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_peers.png b/docs/qa/img37/200nodes_tm037/v037_rotating_peers.png new file mode 100644 index 0000000..9e140d7 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_peers.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_rss_avg.png b/docs/qa/img37/200nodes_tm037/v037_rotating_rss_avg.png new file mode 100644 index 0000000..44355e6 Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_rss_avg.png differ diff --git a/docs/qa/img37/200nodes_tm037/v037_rotating_total-txs.png b/docs/qa/img37/200nodes_tm037/v037_rotating_total-txs.png new file mode 100644 index 0000000..046559f Binary files /dev/null and b/docs/qa/img37/200nodes_tm037/v037_rotating_total-txs.png differ diff --git a/docs/qa/img37/rotating/rotating_avg_memory.png b/docs/qa/img37/rotating/rotating_avg_memory.png new file mode 100644 index 0000000..f7f12ac Binary files /dev/null and b/docs/qa/img37/rotating/rotating_avg_memory.png differ diff --git a/docs/qa/img37/rotating/rotating_block_rate.png b/docs/qa/img37/rotating/rotating_block_rate.png new file mode 100644 index 0000000..b76135e Binary files /dev/null and b/docs/qa/img37/rotating/rotating_block_rate.png differ diff --git a/docs/qa/img37/rotating/rotating_cpu.png b/docs/qa/img37/rotating/rotating_cpu.png new file mode 100644 index 0000000..a778ac3 Binary files /dev/null and b/docs/qa/img37/rotating/rotating_cpu.png differ diff --git a/docs/qa/img37/rotating/rotating_eph_heights.png b/docs/qa/img37/rotating/rotating_eph_heights.png new file mode 100644 index 0000000..f7d503d Binary files /dev/null and b/docs/qa/img37/rotating/rotating_eph_heights.png differ diff --git a/docs/qa/img37/rotating/rotating_peers.png b/docs/qa/img37/rotating/rotating_peers.png new file mode 100644 index 0000000..b6640cf Binary files /dev/null and b/docs/qa/img37/rotating/rotating_peers.png differ diff --git a/docs/qa/img37/rotating/rotating_txs_rate.png b/docs/qa/img37/rotating/rotating_txs_rate.png new file mode 100644 index 0000000..0eb773b Binary files /dev/null and b/docs/qa/img37/rotating/rotating_txs_rate.png differ diff --git a/docs/qa/img38/200nodes/avg_mempool_size.png b/docs/qa/img38/200nodes/avg_mempool_size.png new file mode 100644 index 0000000..2feb4a0 Binary files /dev/null and b/docs/qa/img38/200nodes/avg_mempool_size.png differ diff --git a/docs/qa/img38/200nodes/block_rate.png b/docs/qa/img38/200nodes/block_rate.png new file mode 100644 index 0000000..5d7c7d2 Binary files /dev/null and b/docs/qa/img38/200nodes/block_rate.png differ diff --git a/docs/qa/img38/200nodes/c1r400.png b/docs/qa/img38/200nodes/c1r400.png new file mode 100644 index 0000000..3332f16 Binary files /dev/null and b/docs/qa/img38/200nodes/c1r400.png differ diff --git a/docs/qa/img38/200nodes/cpu.png b/docs/qa/img38/200nodes/cpu.png new file mode 100644 index 0000000..761cff5 Binary files /dev/null and b/docs/qa/img38/200nodes/cpu.png differ diff --git a/docs/qa/img38/200nodes/e_de676ecf-038e-443f-a26a-27915f29e312.png b/docs/qa/img38/200nodes/e_de676ecf-038e-443f-a26a-27915f29e312.png new file mode 100644 index 0000000..ef9de26 Binary files /dev/null and b/docs/qa/img38/200nodes/e_de676ecf-038e-443f-a26a-27915f29e312.png differ diff --git a/docs/qa/img38/200nodes/memory.png b/docs/qa/img38/200nodes/memory.png new file mode 100644 index 0000000..b08fde1 Binary files /dev/null and b/docs/qa/img38/200nodes/memory.png differ diff --git a/docs/qa/img38/200nodes/mempool_size.png b/docs/qa/img38/200nodes/mempool_size.png new file mode 100644 index 0000000..d59eada Binary files /dev/null and b/docs/qa/img38/200nodes/mempool_size.png differ diff --git a/docs/qa/img38/200nodes/peers.png b/docs/qa/img38/200nodes/peers.png new file mode 100644 index 0000000..727993c Binary files /dev/null and b/docs/qa/img38/200nodes/peers.png differ diff --git a/docs/qa/img38/200nodes/rounds.png b/docs/qa/img38/200nodes/rounds.png new file mode 100644 index 0000000..d68f3fb Binary files /dev/null and b/docs/qa/img38/200nodes/rounds.png differ diff --git a/docs/qa/img38/200nodes/total_txs_rate.png b/docs/qa/img38/200nodes/total_txs_rate.png new file mode 100644 index 0000000..41ba0ba Binary files /dev/null and b/docs/qa/img38/200nodes/total_txs_rate.png differ diff --git a/docs/qa/img38/200nodes/v038_report_tabbed.txt b/docs/qa/img38/200nodes/v038_report_tabbed.txt new file mode 100644 index 0000000..16abcc5 --- /dev/null +++ b/docs/qa/img38/200nodes/v038_report_tabbed.txt @@ -0,0 +1,40 @@ +Experiment ID: 93024f38-a008-443d-9aa7-9ac44c9fe15b Experiment ID: d65a486e-4712-41b5-9f41-97e491895d2e Experiment ID: 9c39184b-b8c7-46a2-bacb-40f9961fb7a1 + Connections: 1 Connections: 2 Connections: 4 + Rate: 200 Rate: 200 Rate: 200 + Size: 1024 Size: 1024 Size: 1024 + Total Valid Tx: 17800 Total Valid Tx: 33259 Total Valid Tx: 33259 + Total Negative Latencies: 0 Total Negative Latencies: 0 Total Negative Latencies: 0 + Minimum Latency: 562.805076ms Minimum Latency: 894.026089ms Minimum Latency: 2.166875257s + Maximum Latency: 7.623963559s Maximum Latency: 16.941216187s Maximum Latency: 15.701598288s + Average Latency: 1.860012628s Average Latency: 4.033134276s Average Latency: 7.592412668s + Standard Deviation: 1.169158915s Standard Deviation: 3.427243686s Standard Deviation: 2.951797195s +Experiment ID: de676ecf-038e-443f-a26a-27915f29e312 Experiment ID: 39d571b8-f39b-4aec-bd6a-e94f28a42a63 Experiment ID: 5b855105-60b5-4c2d-ba5c-fdad0213765c + Connections: 1 Connections: 2 Connections: 4 + Rate: 400 Rate: 400 Rate: 400 + Size: 1024 Size: 1024 Size: 1024 + Total Valid Tx: 35600 Total Valid Tx: 41565 Total Valid Tx: 41384 + Total Negative Latencies: 0 Total Negative Latencies: 0 Total Negative Latencies: 0 + Minimum Latency: 565.640641ms Minimum Latency: 1.650712046s Minimum Latency: 2.796290248s + Maximum Latency: 10.051316705s Maximum Latency: 15.897581951s Maximum Latency: 20.124431723s + Average Latency: 3.499369173s Average Latency: 8.635543807s Average Latency: 10.596146863s + Standard Deviation: 1.926805844s Standard Deviation: 2.535678364s Standard Deviation: 3.193742233s +Experiment ID: db10ca9e-6cf8-4dc9-9284-6e767e4b4346 Experiment ID: f57af87d-d342-41f7-a0eb-baa87a4b2257 Experiment ID: 32819ea0-1a59-41de-8aa6-b70f68697520 + Connections: 1 Connections: 2 Connections: 4 + Rate: 800 Rate: 800 Rate: 800 + Size: 1024 Size: 1024 Size: 1024 + Total Valid Tx: 36831 Total Valid Tx: 38686 Total Valid Tx: 40816 + Total Negative Latencies: 0 Total Negative Latencies: 0 Total Negative Latencies: 0 + Minimum Latency: 1.203966853s Minimum Latency: 728.863446ms Minimum Latency: 1.559342549s + Maximum Latency: 21.411365818s Maximum Latency: 24.349050642s Maximum Latency: 25.791215028s + Average Latency: 9.213156739s Average Latency: 11.194994374s Average Latency: 11.950851892s + Standard Deviation: 4.909584729s Standard Deviation: 5.199186587s Standard Deviation: 4.315394253s +Experiment ID: 587762c4-3fd4-4799-9f3b-9e6971b353ba Experiment ID: 489b2623-a3e4-453f-a771-5d05e7de4a1f Experiment ID: 98605df2-3b16-46db-8675-2980bc84ea2b + Connections: 1 Connections: 2 Connections: 4 + Rate: 1600 Rate: 1600 Rate: 1600 + Size: 1024 Size: 1024 Size: 1024 + Total Valid Tx: 40600 Total Valid Tx: 45034 Total Valid Tx: 39830 + Total Negative Latencies: 0 Total Negative Latencies: 0 Total Negative Latencies: 0 + Minimum Latency: 998.07523ms Minimum Latency: 1.43819209s Minimum Latency: 1.50664776s + Maximum Latency: 18.565312759s Maximum Latency: 17.098811297s Maximum Latency: 20.346885373s + Average Latency: 8.78128586s Average Latency: 8.957419021s Average Latency: 12.113245591s + Standard Deviation: 3.305897473s Standard Deviation: 2.734640455s Standard Deviation: 4.029854219s diff --git a/docs/qa/img38/rotating/rotating_avg_memory.png b/docs/qa/img38/rotating/rotating_avg_memory.png new file mode 100644 index 0000000..7a1964c Binary files /dev/null and b/docs/qa/img38/rotating/rotating_avg_memory.png differ diff --git a/docs/qa/img38/rotating/rotating_block_rate.png b/docs/qa/img38/rotating/rotating_block_rate.png new file mode 100644 index 0000000..d630552 Binary files /dev/null and b/docs/qa/img38/rotating/rotating_block_rate.png differ diff --git a/docs/qa/img38/rotating/rotating_cpu.png b/docs/qa/img38/rotating/rotating_cpu.png new file mode 100644 index 0000000..7e00c6a Binary files /dev/null and b/docs/qa/img38/rotating/rotating_cpu.png differ diff --git a/docs/qa/img38/rotating/rotating_eph_heights.png b/docs/qa/img38/rotating/rotating_eph_heights.png new file mode 100644 index 0000000..5e99a76 Binary files /dev/null and b/docs/qa/img38/rotating/rotating_eph_heights.png differ diff --git a/docs/qa/img38/rotating/rotating_latencies.png b/docs/qa/img38/rotating/rotating_latencies.png new file mode 100644 index 0000000..1f4f696 Binary files /dev/null and b/docs/qa/img38/rotating/rotating_latencies.png differ diff --git a/docs/qa/img38/rotating/rotating_peers.png b/docs/qa/img38/rotating/rotating_peers.png new file mode 100644 index 0000000..28d288c Binary files /dev/null and b/docs/qa/img38/rotating/rotating_peers.png differ diff --git a/docs/qa/img38/rotating/rotating_txs_rate.png b/docs/qa/img38/rotating/rotating_txs_rate.png new file mode 100644 index 0000000..65b245e Binary files /dev/null and b/docs/qa/img38/rotating/rotating_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/02k_1_block_rate.png b/docs/qa/img38/voteExtensions/02k_1_block_rate.png new file mode 100644 index 0000000..b0c85c7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/02k_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/02k_1_total_txs_rate.png new file mode 100644 index 0000000..0baaa6d Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/02k_avg_cpu.png b/docs/qa/img38/voteExtensions/02k_avg_cpu.png new file mode 100644 index 0000000..b4ecaba Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/02k_avg_memory.png b/docs/qa/img38/voteExtensions/02k_avg_memory.png new file mode 100644 index 0000000..05e5ea8 Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/02k_avg_mempool_size.png b/docs/qa/img38/voteExtensions/02k_avg_mempool_size.png new file mode 100644 index 0000000..32be4b7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/02k_block_rate.png b/docs/qa/img38/voteExtensions/02k_block_rate.png new file mode 100644 index 0000000..9ace41d Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/02k_rounds.png b/docs/qa/img38/voteExtensions/02k_rounds.png new file mode 100644 index 0000000..4d3d419 Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/02k_total_txs_rate.png b/docs/qa/img38/voteExtensions/02k_total_txs_rate.png new file mode 100644 index 0000000..e1fe3f3 Binary files /dev/null and b/docs/qa/img38/voteExtensions/02k_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/04k_1_block_rate.png b/docs/qa/img38/voteExtensions/04k_1_block_rate.png new file mode 100644 index 0000000..e6f3ad8 Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/04k_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/04k_1_total_txs_rate.png new file mode 100644 index 0000000..adc5845 Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/04k_avg_cpu.png b/docs/qa/img38/voteExtensions/04k_avg_cpu.png new file mode 100644 index 0000000..61934aa Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/04k_avg_memory.png b/docs/qa/img38/voteExtensions/04k_avg_memory.png new file mode 100644 index 0000000..ae51d43 Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/04k_avg_mempool_size.png b/docs/qa/img38/voteExtensions/04k_avg_mempool_size.png new file mode 100644 index 0000000..446f884 Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/04k_block_rate.png b/docs/qa/img38/voteExtensions/04k_block_rate.png new file mode 100644 index 0000000..cd64fca Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/04k_rounds.png b/docs/qa/img38/voteExtensions/04k_rounds.png new file mode 100644 index 0000000..08149df Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/04k_total_txs_rate.png b/docs/qa/img38/voteExtensions/04k_total_txs_rate.png new file mode 100644 index 0000000..8e9f93f Binary files /dev/null and b/docs/qa/img38/voteExtensions/04k_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/08k_1_avg_mempool_size.png b/docs/qa/img38/voteExtensions/08k_1_avg_mempool_size.png new file mode 100644 index 0000000..9c8e862 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_1_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/08k_1_block_rate.png b/docs/qa/img38/voteExtensions/08k_1_block_rate.png new file mode 100644 index 0000000..61d77d2 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/08k_1_rounds.png b/docs/qa/img38/voteExtensions/08k_1_rounds.png new file mode 100644 index 0000000..8df11c9 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_1_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/08k_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/08k_1_total_txs_rate.png new file mode 100644 index 0000000..e6b95c3 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/08k_avg_cpu.png b/docs/qa/img38/voteExtensions/08k_avg_cpu.png new file mode 100644 index 0000000..87ffa50 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/08k_avg_memory.png b/docs/qa/img38/voteExtensions/08k_avg_memory.png new file mode 100644 index 0000000..8e630f7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/08k_avg_mempool_size.png b/docs/qa/img38/voteExtensions/08k_avg_mempool_size.png new file mode 100644 index 0000000..be7974e Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/08k_rounds.png b/docs/qa/img38/voteExtensions/08k_rounds.png new file mode 100644 index 0000000..cdef792 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/08k_total_txs_rate.png b/docs/qa/img38/voteExtensions/08k_total_txs_rate.png new file mode 100644 index 0000000..219a339 Binary files /dev/null and b/docs/qa/img38/voteExtensions/08k_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/16k_1_avg_mempool_size.png b/docs/qa/img38/voteExtensions/16k_1_avg_mempool_size.png new file mode 100644 index 0000000..980d5dc Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_1_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/16k_1_block_rate.png b/docs/qa/img38/voteExtensions/16k_1_block_rate.png new file mode 100644 index 0000000..a38074d Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/16k_1_rounds.png b/docs/qa/img38/voteExtensions/16k_1_rounds.png new file mode 100644 index 0000000..b53dcd4 Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_1_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/16k_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/16k_1_total_txs_rate.png new file mode 100644 index 0000000..5dcaa5f Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/16k_avg_cpu.png b/docs/qa/img38/voteExtensions/16k_avg_cpu.png new file mode 100644 index 0000000..8d86883 Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/16k_avg_memory.png b/docs/qa/img38/voteExtensions/16k_avg_memory.png new file mode 100644 index 0000000..b4259be Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/16k_avg_mempool_size.png b/docs/qa/img38/voteExtensions/16k_avg_mempool_size.png new file mode 100644 index 0000000..4116f85 Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/16k_block_rate.png b/docs/qa/img38/voteExtensions/16k_block_rate.png new file mode 100644 index 0000000..c0e1a6b Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/16k_rounds.png b/docs/qa/img38/voteExtensions/16k_rounds.png new file mode 100644 index 0000000..0440a8a Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/16k_total_txs_rate.png b/docs/qa/img38/voteExtensions/16k_total_txs_rate.png new file mode 100644 index 0000000..738f506 Binary files /dev/null and b/docs/qa/img38/voteExtensions/16k_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/32k_1_avg_mempool_size.png b/docs/qa/img38/voteExtensions/32k_1_avg_mempool_size.png new file mode 100644 index 0000000..6b7c562 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_1_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/32k_1_block_rate.png b/docs/qa/img38/voteExtensions/32k_1_block_rate.png new file mode 100644 index 0000000..378e4a7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/32k_1_rounds.png b/docs/qa/img38/voteExtensions/32k_1_rounds.png new file mode 100644 index 0000000..14da7d2 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_1_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/32k_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/32k_1_total_txs_rate.png new file mode 100644 index 0000000..ec458d2 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/32k_avg_cpu.png b/docs/qa/img38/voteExtensions/32k_avg_cpu.png new file mode 100644 index 0000000..4eb9a70 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/32k_avg_memory.png b/docs/qa/img38/voteExtensions/32k_avg_memory.png new file mode 100644 index 0000000..d6a94f2 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/32k_avg_mempool_size.png b/docs/qa/img38/voteExtensions/32k_avg_mempool_size.png new file mode 100644 index 0000000..0ef216d Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/32k_block_rate.png b/docs/qa/img38/voteExtensions/32k_block_rate.png new file mode 100644 index 0000000..914d119 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/32k_rounds.png b/docs/qa/img38/voteExtensions/32k_rounds.png new file mode 100644 index 0000000..23779c2 Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/32k_total_txs_rate.png b/docs/qa/img38/voteExtensions/32k_total_txs_rate.png new file mode 100644 index 0000000..fe5a7cf Binary files /dev/null and b/docs/qa/img38/voteExtensions/32k_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/8k_block_rate.png b/docs/qa/img38/voteExtensions/8k_block_rate.png new file mode 100644 index 0000000..2c4064a Binary files /dev/null and b/docs/qa/img38/voteExtensions/8k_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_16k.png b/docs/qa/img38/voteExtensions/all_c1r400_16k.png new file mode 100644 index 0000000..0a94af5 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_16k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_2k.png b/docs/qa/img38/voteExtensions/all_c1r400_2k.png new file mode 100644 index 0000000..f8ba7a7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_2k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_32k.png b/docs/qa/img38/voteExtensions/all_c1r400_32k.png new file mode 100644 index 0000000..f784bbf Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_32k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_4k.png b/docs/qa/img38/voteExtensions/all_c1r400_4k.png new file mode 100644 index 0000000..258bfab Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_4k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_64k.png b/docs/qa/img38/voteExtensions/all_c1r400_64k.png new file mode 100644 index 0000000..2105413 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_64k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_8k.png b/docs/qa/img38/voteExtensions/all_c1r400_8k.png new file mode 100644 index 0000000..2e3c001 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_8k.png differ diff --git a/docs/qa/img38/voteExtensions/all_c1r400_baseline.png b/docs/qa/img38/voteExtensions/all_c1r400_baseline.png new file mode 100644 index 0000000..70b86a8 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_c1r400_baseline.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_16k.png b/docs/qa/img38/voteExtensions/all_experiments_16k.png new file mode 100644 index 0000000..a395bd7 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_16k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_2k.png b/docs/qa/img38/voteExtensions/all_experiments_2k.png new file mode 100644 index 0000000..e4f2867 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_2k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_32k.png b/docs/qa/img38/voteExtensions/all_experiments_32k.png new file mode 100644 index 0000000..e9ce46b Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_32k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_4k.png b/docs/qa/img38/voteExtensions/all_experiments_4k.png new file mode 100644 index 0000000..e63a965 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_4k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_64k.png b/docs/qa/img38/voteExtensions/all_experiments_64k.png new file mode 100644 index 0000000..42fb30a Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_64k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_8k.png b/docs/qa/img38/voteExtensions/all_experiments_8k.png new file mode 100644 index 0000000..9a25a58 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_8k.png differ diff --git a/docs/qa/img38/voteExtensions/all_experiments_baseline.png b/docs/qa/img38/voteExtensions/all_experiments_baseline.png new file mode 100644 index 0000000..893c277 Binary files /dev/null and b/docs/qa/img38/voteExtensions/all_experiments_baseline.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_1_avg_mempool_size.png b/docs/qa/img38/voteExtensions/baseline_1_avg_mempool_size.png new file mode 100644 index 0000000..55c2e1c Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_1_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_1_block_rate.png b/docs/qa/img38/voteExtensions/baseline_1_block_rate.png new file mode 100644 index 0000000..43f5994 Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_1_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_1_rounds.png b/docs/qa/img38/voteExtensions/baseline_1_rounds.png new file mode 100644 index 0000000..6e85c69 Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_1_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_1_total_txs_rate.png b/docs/qa/img38/voteExtensions/baseline_1_total_txs_rate.png new file mode 100644 index 0000000..5d6a315 Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_1_total_txs_rate.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_avg_cpu.png b/docs/qa/img38/voteExtensions/baseline_avg_cpu.png new file mode 100644 index 0000000..85a1c88 Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_avg_cpu.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_avg_memory.png b/docs/qa/img38/voteExtensions/baseline_avg_memory.png new file mode 100644 index 0000000..5a728fd Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_avg_memory.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_avg_mempool_size.png b/docs/qa/img38/voteExtensions/baseline_avg_mempool_size.png new file mode 100644 index 0000000..f36b92e Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_avg_mempool_size.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_block_rate.png b/docs/qa/img38/voteExtensions/baseline_block_rate.png new file mode 100644 index 0000000..323589c Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_block_rate.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_rounds.png b/docs/qa/img38/voteExtensions/baseline_rounds.png new file mode 100644 index 0000000..b8e3e1b Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_rounds.png differ diff --git a/docs/qa/img38/voteExtensions/baseline_total_txs_rate.png b/docs/qa/img38/voteExtensions/baseline_total_txs_rate.png new file mode 100644 index 0000000..23f8370 Binary files /dev/null and b/docs/qa/img38/voteExtensions/baseline_total_txs_rate.png differ diff --git a/docs/qa/method.md b/docs/qa/method.md new file mode 100644 index 0000000..09761f8 --- /dev/null +++ b/docs/qa/method.md @@ -0,0 +1,262 @@ +--- +order: 1 +parent: + title: Method + order: 1 +--- + +# Method + +This document provides a detailed description of the QA process. +It is intended to be used by engineers reproducing the experimental setup for future tests of CometBFT. + +The (first iteration of the) QA process as described [in the RELEASES.md document][releases] +was applied to version v0.34.x in order to have a set of results acting as benchmarking baseline. +This baseline is then compared with results obtained in later versions. + +Out of the testnet-based test cases described in [the releases document][releases] we focused on two of them: +_200 Node Test_, and _Rotating Nodes Test_. + +[releases]: https://github.com/cometbft/cometbft/blob/v0.38.x/RELEASES.md#large-scale-testnets + +## Software Dependencies + +### Infrastructure Requirements to Run the Tests + +* An account at Digital Ocean (DO), with a high droplet limit (>202) +* The machine to orchestrate the tests should have the following installed: + * A clone of the [testnet repository][testnet-repo] + * This repository contains all the scripts mentioned in the remainder of this section + * [Digital Ocean CLI][doctl] + * [Terraform CLI][Terraform] + * [Ansible CLI][Ansible] + +[testnet-repo]: https://github.com/cometbft/qa-infra +[Ansible]: https://docs.ansible.com/ansible/latest/index.html +[Terraform]: https://www.terraform.io/docs +[doctl]: https://docs.digitalocean.com/reference/doctl/how-to/install/ + +### Requirements for Result Extraction + +* [Prometheus DB][prometheus] to collect metrics from nodes +* Prometheus DB to process queries (may be different node from the previous) +* blockstore DB of one of the full nodes in the testnet + + +[prometheus]: https://prometheus.io/ + +## 200 Node Testnet + +### Running the test + +This section explains how the tests were carried out for reproducibility purposes. + +1. [If you haven't done it before] + Follow steps 1-4 of the `README.md` at the top of the testnet repository to configure Terraform, and `doctl`. +2. Copy file `testnets/testnet200.toml` onto `testnet.toml` (do NOT commit this change) +3. Set the variable `VERSION_TAG` in the `Makefile` to the git hash that is to be tested. + * If you are running the base test, which implies an homogeneous network (all nodes are running the same version), + then make sure makefile variable `VERSION2_WEIGHT` is set to 0 + * If you are running a mixed network, set the variable `VERSION2_TAG` to the other version you want deployed + in the network. + Then adjust the weight variables `VERSION_WEIGHT` and `VERSION2_WEIGHT` to configure the + desired proportion of nodes running each of the two configured versions. +4. Follow steps 5-10 of the `README.md` to configure and start the 200 node testnet + * WARNING: Do NOT forget to run `make terraform-destroy` as soon as you are done with the tests (see step 9) +5. As a sanity check, connect to the Prometheus node's web interface (port 9090) + and check the graph for the `cometbft_consensus_height` metric. All nodes + should be increasing their heights. + + * You can find the Prometheus node's IP address in `ansible/hosts` under section `[prometheus]`. + * The following URL will display the metrics `cometbft_consensus_height` and `cometbft_mempool_size`: + + ``` + http://:9090/classic/graph?g0.range_input=1h&g0.expr=cometbft_consensus_height&g0.tab=0&g1.range_input=1h&g1.expr=cometbft_mempool_size&g1.tab=0 + ``` + +6. You now need to start the load runner that will produce transaction load. + * If you don't know the saturation load of the version you are testing, you need to discover it. + * Run `make loadrunners-init`. This will copy the loader scripts to the + `testnet-load-runner` node and install the load tool. + * Find the IP address of the `testnet-load-runner` node in + `ansible/hosts` under section `[loadrunners]`. + * `ssh` into `testnet-load-runner`. + * Edit the script `/root/200-node-loadscript.sh` in the load runner + node to provide the IP address of a full node (for example, + `validator000`). This node will receive all transactions from the + load runner node. + * Run `/root/200-node-loadscript.sh` from the load runner node. + * This script will take about 40 mins to run, so it is suggested to + first run `tmux` in case the ssh session breaks. + * It is running 90-seconds-long experiments in a loop with different + loads. + * If you already know the saturation load, you can simply run the test (several times) for 90 seconds with a load somewhat + below saturation: + * set makefile variables `LOAD_CONNECTIONS`, `LOAD_TX_RATE`, to values that will produce the desired transaction load. + * set `LOAD_TOTAL_TIME` to 90 (seconds). + * run "make runload" and wait for it to complete. You may want to run this several times so the data from different runs can be compared. +7. Run `make retrieve-data` to gather all relevant data from the testnet into the orchestrating machine + * Alternatively, you may want to run `make retrieve-prometheus-data` and `make retrieve-blockstore` separately. + The end result will be the same. + * `make retrieve-blockstore` accepts the following values in makefile variable `RETRIEVE_TARGET_HOST` + * `any`: (which is the default) picks up a full node and retrieves the blockstore from that node only. + * `all`: retrieves the blockstore from all full nodes; this is extremely slow, and consumes plenty of bandwidth, + so use it with care. + * the name of a particular full node (e.g., `validator01`): retrieves the blockstore from that node only. +8. Verify that the data was collected without errors + * at least one blockstore DB for a CometBFT validator + * the Prometheus database from the Prometheus node + * for extra care, you can run `zip -T` on the `prometheus.zip` file and (one of) the `blockstore.db.zip` file(s) +9. **Run `make terraform-destroy`** + * Don't forget to type `yes`! Otherwise you're in trouble. + +### Result Extraction + +The method for extracting the results described here is highly manual (and exploratory) at this stage. +The CometBFT team should improve it at every iteration to increase the amount of automation. + +#### Steps + +1. Unzip the blockstore into a directory +2. To identify saturation points + 1. Extract the latency report for all the experiments. + * Run these commands from the directory containing the `blockstore.db` folder. + * It is advisable to adjust the hash in the `go run` command to the latest possible. + * ```bash + mkdir results + go run github.com/cometbft/cometbft/test/loadtime/cmd/report@3003ef7 --database-type goleveldb --data-dir ./ > results/report.txt + ``` + 2. File `report.txt` contains an unordered list of experiments with varying concurrent connections and transaction rate. + You will need to separate data per experiment. + + * Create files `report01.txt`, `report02.txt`, `report04.txt` and, for each experiment in file `report.txt`, + copy its related lines to the filename that matches the number of connections, for example + + ```bash + for cnum in 1 2 4; do echo "$cnum"; grep "Connections: $cnum" results/report.txt -B 2 -A 10 > results/report$cnum.txt; done + ``` + + * Sort the experiments in `report01.txt` in ascending tx rate order. Likewise for `report02.txt` and `report04.txt`. + * Otherwise just keep `report.txt`, and skip to the next step. + 4. Generate file `report_tabbed.txt` by showing the contents `report01.txt`, `report02.txt`, `report04.txt` side by side + * This effectively creates a table where rows are a particular tx rate and columns are a particular number of websocket connections. + * Combine the column files into a single table file: + * Replace tabs by spaces in all column files. For example, + `sed -i.bak 's/\t/ /g' results/report1.txt`. + * Merge the new column files into one: + `paste results/report1.txt results/report2.txt results/report4.txt | column -s $'\t' -t > report_tabbed.txt` + +3. To generate a latency vs throughput plot, extract the data as a CSV + * ```bash + go run github.com/cometbft/cometbft/test/loadtime/cmd/report@3003ef7 --database-type goleveldb --data-dir ./ --csv results/raw.csv + ``` + * Follow the instructions for the [`latency_throughput.py`] script. + This plot is useful to visualize the saturation point. + * Alternatively, follow the instructions for the [`latency_plotter.py`] script. + This script generates a series of plots per experiment and configuration that may + help with visualizing Latency vs Throughput variation. + +[`latency_throughput.py`]: https://github.com/cometbft/cometbft/tree/v0.38.x/scripts/qa/reporting#latency-vs-throughput-plotting +[`latency_plotter.py`]: https://github.com/cometbft/cometbft/tree/v0.38.x/scripts/qa/reporting#latency-vs-throughput-plotting-version-2 + +#### Extracting Prometheus Metrics + +1. Stop the prometheus server if it is running as a service (e.g. a `systemd` unit). +2. Unzip the prometheus database retrieved from the testnet, and move it to replace the + local prometheus database. +3. Start the prometheus server and make sure no error logs appear at start up. +4. Identify the time window you want to plot in your graphs. +5. Execute the [`prometheus_plotter.py`] script for the time window. + +[`prometheus_plotter.py`]: https://github.com/cometbft/cometbft/tree/v0.38.x/scripts/qa/reporting#prometheus-metrics + +## Rotating Node Testnet + +### Running the test + +This section explains how the tests were carried out for reproducibility purposes. + +1. [If you haven't done it before] + Follow steps 1-4 of the `README.md` at the top of the testnet repository to configure Terraform, and `doctl`. +2. Copy file `testnet_rotating.toml` onto `testnet.toml` (do NOT commit this change) +3. Set variable `VERSION_TAG` to the git hash that is to be tested. +4. Run `make terraform-apply EPHEMERAL_SIZE=25` + * WARNING: Do NOT forget to run `make terraform-destroy` as soon as you are done with the tests +5. Follow steps 6-10 of the `README.md` to configure and start the "stable" part of the rotating node testnet +6. As a sanity check, connect to the Prometheus node's web interface and check the graph for the `tendermint_consensus_height` metric. + All nodes should be increasing their heights. +7. On a different shell, + * run `make runload LOAD_CONNECTIONS=X LOAD_TX_RATE=Y LOAD_TOTAL_TIME=Z` + * `X` and `Y` should reflect a load below the saturation point (see, e.g., + [this paragraph](./TMCore-QA-34.md#finding-the-saturation-point) for further info) + * `Z` (in seconds) should be big enough to keep running throughout the test, until we manually stop it in step 9. + In principle, a good value for `Z` is `7200` (2 hours) +8. Run `make rotate` to start the script that creates the ephemeral nodes, and kills them when they are caught up. + * WARNING: If you run this command from your laptop, the laptop needs to be up and connected for the full length + of the experiment. + * [This](http://:9090/classic/graph?g0.range_input=100m&g0.expr=cometbft_consensus_height%7Bjob%3D~%22ephemeral.*%22%7D%20or%20cometbft_blocksync_latest_block_height%7Bjob%3D~%22ephemeral.*%22%7D&g0.tab=0&g1.range_input=100m&g1.expr=cometbft_mempool_size%7Bjob!~%22ephemeral.*%22%7D&g1.tab=0&g2.range_input=100m&g2.expr=cometbft_consensus_num_txs%7Bjob!~%22ephemeral.*%22%7D&g2.tab=0) + is an example Prometheus URL you can use to monitor the test case's progress +9. When the height of the chain reaches 3000, stop the `make runload` script. +10. When the rotate script has made two iterations (i.e., all ephemeral nodes have caught up twice) + after height 3000 was reached, stop `make rotate` +11. Run `make stop-network` +12. Run `make retrieve-data` to gather all relevant data from the testnet into the orchestrating machine +13. Verify that the data was collected without errors + * at least one blockstore DB for a CometBFT validator + * the Prometheus database from the Prometheus node + * for extra care, you can run `zip -T` on the `prometheus.zip` file and (one of) the `blockstore.db.zip` file(s) +14. **Run `make terraform-destroy`** + +Steps 8 to 10 are highly manual at the moment and will be improved in next iterations. + +### Result Extraction + +In order to obtain a latency plot, follow the instructions above for the 200 node experiment, +but the `results.txt` file contains only one experiment. + +As for prometheus, the same method as for the 200 node experiment can be applied. + +## Vote Extensions Testnet + +### Running the test + +This section explains how the tests were carried out for reproducibility purposes. + +1. [If you haven't done it before] + Follow steps 1-4 of the `README.md` at the top of the testnet repository to configure Terraform, and `doctl`. +2. Copy file `varyVESize.toml` onto `testnet.toml` (do NOT commit this change). +3. Set variable `VERSION_TAG` in the `Makefile` to the git hash that is to be tested. +4. Follow steps 5-10 of the `README.md` to configure and start the testnet + * WARNING: Do NOT forget to run `make terraform-destroy` as soon as you are done with the tests +5. Configure the load runner to produce the desired transaction load. + * set makefile variables `ROTATE_CONNECTIONS`, `ROTATE_TX_RATE`, to values that will produce the desired transaction load. + * set `ROTATE_TOTAL_TIME` to 150 (seconds). + * set `ITERATIONS` to the number of iterations that each configuration should run for. +6. Execute steps 5-10 of the `README.md` file at the testnet repository. + +7. Repeat the following steps for each desired `vote_extension_size` + 1. Update the configuration (you can skip this step if you didn't change the `vote_extension_size`) + * Update the `vote_extensions_size` in the `testnet.toml` to the desired value. + * `make configgen` + * `ANSIBLE_SSH_RETRIES=10 ansible-playbook ./ansible/re-init-testapp.yaml -u root -i ./ansible/hosts --limit=validators -e "testnet_dir=testnet" -f 20` + * `make restart` + 2. Run the test + * `make runload` + This will repeat the tests `ITERATIONS` times every time it is invoked. + 3. Collect your data + * `make retrieve-data` + Gathers all relevant data from the testnet into the orchestrating machine, inside folder `experiments`. + Two subfolders are created, one blockstore DB for a CometBFT validator and one for the Prometheus DB data. + * Verify that the data was collected without errors with `zip -T` on the `prometheus.zip` file and (one of) the `blockstore.db.zip` file(s). +8. Clean up your setup. + * `make terraform-destroy`; don't forget that you need to type **yes** for it to complete. + + +### Result Extraction + +In order to obtain a latency plot, follow the instructions above for the 200 node experiment, but: + +* The `results.txt` file contains only one experiment +* Therefore, no need for any `for` loops + +As for Prometheus, the same method as for the 200 node experiment can be applied. diff --git a/docs/rfc/README.md b/docs/rfc/README.md new file mode 100644 index 0000000..dc30987 --- /dev/null +++ b/docs/rfc/README.md @@ -0,0 +1,45 @@ +--- +order: 1 +parent: + order: false +--- + +# Requests for Comments + +A Request for Comments (RFC) is a record of discussion on an open-ended topic +related to the design and implementation of CometBFT, for which no +immediate decision is required. + +The purpose of an RFC is to serve as a historical record of a high-level +discussion that might otherwise only be recorded in an ad-hoc way (for example, +via gists or Google docs) that are difficult to discover for someone after the +fact. An RFC _may_ give rise to more specific architectural _decisions_ for +CometBFT, but those decisions must be recorded separately in +[Architecture Decision Records (ADR)](../architecture/). + +As a rule of thumb, if you can articulate a specific question that needs to be +answered, write an ADR. If you need to explore the topic and get input from +others to know what questions need to be answered, an RFC may be appropriate. + +## RFC Content + +An RFC should provide: + +- A **changelog**, documenting when and how the RFC has changed. +- An **abstract**, briefly summarizing the topic so the reader can quickly tell + whether it is relevant to their interest. +- Any **background** a reader will need to understand and participate in the + substance of the discussion (links to other documents are fine here). +- The **discussion**, the primary content of the document. + +The [rfc-template.md](./rfc-template.md) file includes placeholders for these +sections. + +## Table of Contents + +The RFCs listed below are exclusively relevant to CometBFT. For historical RFCs +relating to Tendermint Core prior to forking, please see +[this list](./tendermint-core/). + + +- [RFC-100: ABCI Vote Extension Propagation](./rfc-100-abci-vote-extension-propag.md) diff --git a/docs/rfc/rfc-100-abci-vote-extension-propag.md b/docs/rfc/rfc-100-abci-vote-extension-propag.md new file mode 100644 index 0000000..3130c60 --- /dev/null +++ b/docs/rfc/rfc-100-abci-vote-extension-propag.md @@ -0,0 +1,742 @@ +# RFC 100: ABCI Vote Extension Propagation + +## Changelog + +- 11-Apr-2022: Initial draft (@sergio-mena). +- 15-Apr-2022: Addressed initial comments. First complete version (@sergio-mena). +- 09-May-2022: Addressed all outstanding comments (@sergio-mena). +- 09-May-2022: Add section on upgrade path (@wbanfield) +- 02-Mar-2023: Migrated to CometBFT RFCs. New number: RFC 100 (@sergio-mena). +- 03-Mar-2023: Added "changes needed" to solutions in upgrade path section (@sergio-mena) + +## Abstract + +According to the +[ABCI 2.0 specification][abci-2-0], +a validator MUST provide a signed vote extension for each non-`nil` precommit vote +of height *h* that it uses to propose a block in height *h+1*. When a validator is up to +date, this is easy to do, but when a validator needs to catch up this is far from trivial as this data +cannot be retrieved from the blockchain. + +This RFC presents and compares the different options to address this problem, which have been proposed +in several discussions by the CometBFT team. + +## Document Structure + +The RFC is structured as follows. In the [Background](#background) section, +subsections [Problem Description](#problem-description) and [Cases to Address](#cases-to-address) +explain the problem at hand from a high level perspective, i.e., abstracting away from the current +CometBFT implementation. In contrast, subsection +[Current Catch-up Mechanisms](#current-catch-up-mechanisms) delves into the details of the current +CometBFT code. + +In the [Discussion](#discussion) section, subsection [Solutions Proposed](#solutions-proposed) is also +worded abstracting away from implementation details, whilst subsections +[Feasibility of the Proposed Solutions](#feasibility-of-the-proposed-solutions) and +[Current Limitations and Possible Implementations](#current-limitations-and-possible-implementations) +analyze the viability of one of the proposed solutions in the context of CometBFT's architecture +based on reactors. +Subsection [Upgrade Path](#upgrade-path) discusses how a CometBFT node can upgrade +from a version predating vote extensions, to one featuring it. +Finally, [Formalization Work](#formalization-work) briefly discusses the work +still needed to demonstrate the correctness of the chosen solution. + +The high level subsections are aimed at readers who are familiar with consensus algorithms, in +particular with the Tendermint algorithm described [here](https://arxiv.org/abs/1807.04938), +but who are not necessarily +acquainted with the details of the CometBFT codebase. The other subsections, which go into +implementation details, are best understood by engineers with deep knowledge of the implementation of +CometBFT's blocksync and consensus reactors. + +## Background + +### Basic Definitions + +This document assumes that all validators have equal voting power for the sake of simplicity. This is done +without loss of generality. + +There are two types of votes in the Tendermint algorithm: *prevotes* and *precommits*. +Votes can be `nil` or refer to a proposed block. This RFC focuses on precommits, +also known as *precommit votes*. In this document we sometimes call them simply *votes*. + +Validators send precommit votes to their peer nodes in *precommit messages*. According to the +[ABCI 2.0 specification][abci-2-0], +a precommit message MUST also contain a *vote extension*. +This mandatory vote extension can be empty, but MUST be signed with the same key as the precommit +vote (i.e., the sending validator's). +Nevertheless, the vote extension is signed independently from the vote, so a vote can be separated from +its extension. +The reason for vote extensions to be mandatory in precommit messages is that, otherwise, a (malicious) +node can omit a vote extension while still providing/forwarding/sending the corresponding precommit vote. + +The validator set at height *h* is denoted *valseth*. A *commit* for height *h* consists of more +than *2nh/3* precommit votes voting for a block *b*, where *nh* denotes the size of +*valseth*. A commit does not contain `nil` precommit votes, and all votes in it refer to the +same block. An *extended commit* is a *commit* where every precommit vote has its respective vote extension +attached. + +### Problem Description + +In [ABCI 1.0][abci-1-0] and previous versions (e.g. [ABCI 0.17.0][abci-0-17-0]), +for any height *h*, a validator *v* MUST have the decided block *b* and a commit for +height *h* in order to decide at height *h*. Then, *v* just needs a commit for height *h* to propose at +height *h+1*, in the rounds of *h+1* where *v* is a proposer. + +In [ABCI 2.0][abci-2-0], +the information that a validator *v* MUST have to be able to decide in *h* does not change with +respect to pre-existing ABCI: the decided block *b* and a commit for *h*. +In contrast, for proposing in *h+1*, a commit for *h* is not enough: *v* MUST now have an extended +commit. + +When a validator takes an active part in consensus at height *h*, it has all the data it needs in memory, +in its consensus state, to decide on *h* and propose in *h+1*. Things are not so easy in the cases when +*v* cannot take part in consensus because it is late (e.g., it falls behind, it crashes +and recovers, or it just starts after the others). If *v* does not take part, it cannot actively +gather precommit messages (which include vote extensions) in order to decide. +Before ABCI 2.0, this was not a problem: full nodes are supposed to persist past blocks in the block store, +so other nodes would realise that *v* is late and send it the missing decided block at height *h* and +the corresponding commit (kept in block *h+1*) so that *v* can catch up. +However, we cannot apply this catch-up technique for ABCI 2.0, as the vote extensions, which are part +of the needed *extended commit* are not part of the blockchain. + +### Cases to Address + +Before we tackle the description of the possible cases we need to address, let us describe the following +incremental improvement to the ABCI 2.0 logic. Upon decision, a full node persists (e.g., in the block +store) the extended commit that allowed the node to decide. For the moment, let us assume the node only +needs to keep its *most recent* extended commit, and MAY remove any older extended commits from persistent +storage. +This improvement is so obvious that all solutions described in the [Discussion](#discussion) section use +it as a building block. Moreover, it completely addresses by itself some of the cases described in this +subsection. + +We now describe the cases (i.e. possible *runs* of the system) that have been raised in different +discussions and need to be addressed. They are (roughly) ordered from easiest to hardest to deal with. + +- **(a)** *Happy path: all validators advance together, no crash*. + + This case is included for completeness. All validators have taken part in height *h*. + Even if some of them did not manage to send a precommit message for the decided block, they all + receive enough precommit messages to be able to decide. As vote extensions are mandatory in + precommit messages, every validator *v* trivially has all the information, namely the decided block + and the extended commit, needed to propose in height *h+1* for the rounds in which *v* is the + proposer. + + No problem to solve here. + +- **(b)** *All validators advance together, then all crash at the same height*. + + This case has been raised in some discussions, the main concern being whether the vote extensions + for the previous height would be lost across the network. With the improvement described above, + namely persisting the latest extended commit at decision time, this case is solved. + When a crashed validator recovers, it recovers the last extended commit from persistent storage + and handshakes with the Application. + If need be, it also reconstructs messages for the unfinished height + (including all precommits received) from the WAL. + Then, the validator can resume where it was at the time of the crash. Thus, as extensions are + persisted, either in the WAL (in the form of received precommit messages), or in the latest + extended commit, the only way that vote extensions needed to start the next height could be lost + forever would be if all validators crashed and never recovered (e.g. disk corruption). + Since a *correct* node MUST eventually recover, this violates the assumption of more than + *2nh/3* correct validators for every height *h*. + + No problem to solve here. + +- **(c)** *Lagging majority*. + + Let us assume the validator set does not change between *h* and *h+1*. + It is not possible by the nature of the Tendermint algorithm, which requires more + than *2nh/3* precommit votes for some round of height *h* in order to make progress. + So, only up to *nh/3* validators can lag behind. + + On the other hand, for the case where there are changes to the validator set between *h* and + *h+1* please see case (d) below, where the extreme case is discussed. + +- **(d)** *Validator set changes completely between* h *and* h+1. + + If sets *valseth* and *valseth+1* are disjoint, + more than *2nh/3* of validators in height *h* should + have actively participated in conensus in *h*. So, as of height *h*, only a minority of validators + in *h* can be lagging behind, although they could all lag behind from *h+1* on, as they are no + longer validators, only full nodes. This situation falls under the assumptions of case (h) below. + + As for validators in *valseth+1*, as they were not validators as of height *h*, they + could all be lagging behind by that time. However, by the time *h* finishes and *h+1* begins, the + chain will halt until more than *2nh+1/3* of them have caught up and started consensus + at height *h+1*. If set *valseth+1* does not change in *h+2* and subsequent + heights, only up to *nh+1/3* validators will be able to lag behind. Thus, we have + converted this case into case (h) below. + +- **(e)** *Enough validators crash to block the rest*. + + In this case, blockchain progress halts, i.e. surviving full nodes keep increasing rounds + indefinitely, until some of the crashed validators are able to recover. + Those validators that recover first will handshake with the Application and recover at the height + they crashed, which is still the same the nodes that did not crash are stuck in, so they don't need + to catch up. + Further, they had persisted the extended commit for the previous height. Nothing to solve. + + For those validators recovering later, we are in case (h) below. + +- **(f)** *Some validators crash, but not enough to block progress*. + + When the correct processes that crashed recover, they handshake with the Application and resume at + the height they were at when they crashed. As the blockchain did not stop making progress, the + recovered processes are likely to have fallen behind with respect to the progressing majority. + + At this point, the recovered processes are in case (h) below. + +- **(g)** *A new full node starts*. + + The reasoning here also applies to the case when more than one full node are starting. + When the full node starts from scratch, it has no state (its current height is 0). Ignoring + statesync for the time being, the node just needs to catch up by applying past blocks one by one + (after verifying them). + + Thus, the node is in case (h) below. + +- **(h)** *Advancing majority, lagging minority* + + In this case, some nodes are late. More precisely, at the present time, a set of full nodes, + denoted *Lhp*, are falling behind + (e.g., temporary disconnection or network partition, memory thrashing, crashes, new nodes) + an arbitrary + number of heights: + between *hs* and *hp*, where *hs < hp*, and + *hp* is the highest height + any correct full node has reached so far. + + The correct full nodes that reached *hp* were able to decide for *hp-1*. + Therefore, less than *nhp-1/3* validators of *hp-1* can be part + of *Lhp*, since enough up-to-date validators needed to actively participate + in consensus for *hp-1*. + + Since, at the present time, + no node in *Lhp* took part in any consensus between + *hs* and *hp-1*, + the reasoning above can be extended to validator set changes between *hs* and + *hp-1*. This results in the following restriction on the full nodes that can be part of *Lhp*. + + - ∀ *h*, where *hs ≤ h < hp*, + | *valseth* ∩ *Lhp* | *< nh/3* + + So, full nodes that are validators at some height h between *hs* and *hp-1* + can be in *Lhp*, but not more than 1/3 of those acting as validators in + the same height. + If this property does not hold for a particular height *h*, where + *hs ≤ h < hp*, CometBFT could not have progressed beyond *h* and + therefore no full node could have reached *hp* (a contradiction). + + These lagging nodes in *Lhp* need to catch up. They have to obtain the + information needed to make + progress from other nodes. For each height *h* between *hs* and *hp-2*, + this includes the decided block for *h*, and the + precommit votes also for *deciding h* (which can be extracted from the block at height *h+1*). + + At a given height *hc* (where possibly *hc << hp*), + a full node in *Lhp* will consider itself *caught up*, based on the + (maybe out of date) information it is getting from its peers. Then, the node needs to be ready to + propose at height *hc+1*, which requires having received the vote extensions for + *hc*. + As the vote extensions are *not* stored in the blocks, and it is difficult to have strong + guarantees on *when* a late node considers itself caught up, providing the late node with the right + vote extensions for the right height poses a problem. + +At this point, we have described and compared all cases raised in discussions leading up to this +RFC. The list above aims at being exhaustive. The analysis of each case included above makes all of +them converge into case (h). + +### Current Catch-up Mechanisms + +We now briefly describe the current catch-up mechanisms in the reactors concerned in CometBFT. + +#### Statesync + +Full nodes optionally run statesync just after starting, when they start from scratch. +If statesync succeeds, an Application snapshot is installed, and CometBFT jumps from height 0 directly +to the height the Application snapshop represents, without applying the block of any previous height. +Some light blocks are received and stored in the block store for running light-client verification of +all the skipped blocks. Light blocks are incomplete blocks, typically containing the header and the +canonical commit but, e.g., no transactions. They are stored in the block store as "signed headers". + +The statesync reactor is not really relevant for solving the problem discussed in this RFC. We will +nevertheless mention it when needed; in particular, to understand some corner cases. + +#### Blocksync + +The blocksync reactor kicks in after start up or recovery. +At startup, if statesync is enabled, blocksync starts just after statesync +and sends the following messages to its peers: + +- `StatusRequest` to query the height its peers are currently at, and +- `BlockRequest`, asking for blocks of heights the local node is missing. + +Using `BlockResponse` messages received from peers, the blocksync reactor validates each received +block using the block of the following height, saves the block in the block store, and sends the +block to the Application for execution (it effectively simulates the node *deciding* on that height). + +If blocksync has validated and applied the block for the height *previous* to the highest seen in +a `StatusResponse` message, or if no progress has been made after a timeout, the node considers +itself as caught up and switches to the consensus reactor. + +#### Consensus Reactor + +The consensus reactor runs the full Tendermint algorithm. For a validator this means it has to +propose blocks, and send/receive prevote/precommit messages, as mandated by the algorithm, +before it can decide and move on to the next height. + +If a full node that is running the consensus reactor falls behind at height *h*, when a peer node +realises this it will retrieve the canonical commit of *h+1* from the block store, and *convert* +it into a set of precommit votes and will send those to the late node. + +## Discussion + +### Solutions Proposed + +These are the solutions proposed in discussions leading up to this RFC. + +- **Solution 0.** *Vote extensions are made **best effort** in the specification*. + + This is the simplest solution, considered as a way to provide vote extensions in a simple enough + way so that it can be a first available version in ABCI 2.0. + It consists in changing the specification so as to not *require* that precommit votes used upon + `PrepareProposal` contain their corresponding vote extensions. In other words, we render vote + extensions optional. + There are strong implications stemming from such a relaxation of the original specification. + + - As a vote extension is signed *separately* from the vote it is extending, an intermediate node + can now remove (i.e., censor) vote extensions from precommit messages at will. + - Further, there is no point anymore in the spec requiring the Application to accept a vote extension + passed via `VerifyVoteExtension` to consider a precommit message valid in its entirety. Remember + this behavior of `VerifyVoteExtension` is adding a constraint to CometBFT's conditions for + liveness. + In this situation, it is better and simpler to just drop the vote extension rejected by the + Application via `VerifyVoteExtension`, but still consider the precommit vote itself valid as long + as its signature verifies. + +- **Solution 1.** *Include vote extensions in the blockchain*. + + Another obvious solution, which has somehow been considered in the past, is to include the vote + extensions and their signatures in the blockchain. + The blockchain would thus include the extended commit, rather than a regular commit, as the structure + to be canonicalized in the next block. + With this solution, the current mechanisms implemented both in the blocksync and consensus reactors + would still be correct, as all the information a node needs to catch up, and to start proposing when + it considers itself as caught-up, can now be recovered from past blocks saved in the block store. + + This solution has two main drawbacks. + + - As the block format must change, upgrading a chain requires a hard fork. Furthermore, + all existing light client implementations will stop working until they are upgraded to deal with + the new format (e.g., how certain hashes calculated and/or how certain signatures are checked). + For instance, let us consider IBC, which relies on light clients. An IBC connection between + two chains will be broken if only one chain upgrades. + - The extra information (i.e., the vote extensions) that is now kept in the blockchain is not really + needed *at every height* for a late node to catch up. + - This information is only needed to be able to *propose* at the height the validator considers + itself as caught-up. If a validator is indeed late for height *h*, it is useless (although + correct) for it to call `PrepareProposal`, or `ExtendVote`, since the block is already decided. + - Moreover, some use cases require pretty sizeable vote extensions, which would result in an + important waste of space in the blockchain. + +- **Solution 2.** *Skip* propose *step in Tendermint algorithm*. + + This solution consists in modifying the Tendermint algorithm to skip the *send proposal* step in + heights where the node does not have the required vote extensions to populate the call to + `PrepareProposal`. The main idea behind this is that it should only happen when the validator is late + and, therefore, up-to-date validators have already proposed (and decided) for that height. + A small variation of this solution is, rather than skipping the *send proposal* step, the validator + sends a special *empty* or *bottom* (⊥) proposal to signal other nodes that it is not ready to propose + at (any round of) the current height. + + The appeal of this solution is its simplicity. A possible implementation does not need to extend + the data structures, or change the current catch-up mechanisms implemented in the blocksync or + in the consensus reactors. When we lack the needed information (vote extensions), we simply rely + on another correct validator to propose a valid block in other rounds of the current height. + + However, this solution can be attacked by a byzantine node in the network in the following way. + Let us consider the following scenario: + + - all validators in *valseth* send out precommit messages, with vote extensions, + for height *h*, round 0, roughly at the same time, + - all those precommit messages contain non-`nil` precommit votes, which vote for block *b* + - all those precommit messages sent in height *h*, round 0, and all messages sent in + height *h*, round *r > 0* get delayed indefinitely, so, + - all validators in *valseth* keep waiting for enough precommit + messages for height *h*, round 0, needed for deciding in height *h* + - an intermediate (malicious) full node *m* manages to receive block *b*, and gather more than + *2nh/3* precommit messages for height *h*, round 0, + - one way or another, the solution should have either (a) a mechanism for a full node to *tell* + another full node it is late, or (b) a mechanism for a full node to conclude it is late based + on other full nodes' messages; any of these mechanisms should, at the very least, + require the late node receiving the decided block and a commit (not necessarily an extended + commit) for *h*, + - node *m* uses the gathered precommit messages to build a commit for height *h*, round 0, + - in order to convince full nodes that they are late, node *m* either (a) *tells* them they + are late, or (b) shows them it (i.e. *m*) is ahead, by sending them block *b*, along with the + commit for height *h*, round 0, + - all full nodes conclude they are late from *m*'s behavior, and use block *b* and the commit for + height *h*, round 0, to decide on height *h*, and proceed to height *h+1*. + + At this point, *all* correct full nodes, including all correct validators in *valseth+1*, have advanced + to height *h+1* believing they are late, and so, expecting the *hypothetical* leading majority of + validators in *valseth+1* to propose for *h+1*. As a result, the blockchain + grinds to a halt. + A (rather complex) ad-hoc mechanism would need to be carried out by node operators to roll + back all validators to the precommit step of height *h*, round *r*, so that they can regenerate + vote extensions (remember the contents of vote extensions are non-deterministic) and continue execution. + +- **Solution 3.** *Require extended commits to be available at switching time*. + + This one is more involved than all previous solutions, and builds on an idea present in Solution 2: + vote extensions are actually not needed for CometBFT to make progress as long as the + validator is *certain* it is late. + + We define two modes. The first is denoted *catch-up mode*, and CometBFT only calls + `FinalizeBlock` for each height when in this mode. The second is denoted *consensus mode*, in + which the validator considers itself up to date and fully participates in consensus and calls + `PrepareProposal`/`ProcessProposal`, `ExtendVote`, and `VerifyVoteExtension`, before calling + `FinalizeBlock`. + + The catch-up mode does not need vote extension information to make progress, as all it needs is the + decided block at each height to call `FinalizeBlock` and keep the state-machine replication making + progress. The consensus mode, on the other hand, does need vote extension information when + starting every height. + + Validators are in consensus mode by default. When a validator in consensus mode falls behind + for whatever reason, e.g. cases (b), (d), (e), (f), (g), or (h) above, we introduce the following + key safety property: + + - for every height *hp*, a full node *f* in *hp* refuses to switch to catch-up + mode **until** there exists a height *h'* such that: + - *p* has received and (light-client) verified the blocks of + all heights *h*, where *hp ≤ h ≤ h'* + - it has received an extended commit for *h'* and has verified: + - the precommit vote signatures in the extended commit + - the vote extension signatures in the extended commit: each is signed with the same + key as the precommit vote it extends + + If the condition above holds for *hp*, namely receiving a valid sequence of blocks in + *f*'s future, and an extended commit corresponding to the last block in the sequence, then + node *f*: + + - switches to catch-up mode, + - applies all blocks between *hp* and *h'* (calling `FinalizeBlock` only), and + - switches back to consensus mode using the extended commit for *h'* to propose in the rounds of + *h' + 1* where it is the proposer. + + This mechanism, together with the invariant it uses, ensures that the node cannot be attacked by + being fed a block without extensions to make it believe it is late, in a similar way as explained + for Solution 2. + + This solution works as long as the blockchain has vote extensions from genesis, + i.e. it uses ABCI 2.0 from the start. + In contrast, it cannot be used without modifications by a blockchain upgrading + from a previous version of CometBFT that did not implement vote extensions. + In that case, the safety property required to switch to catch-up mode may never hold. + See section [Upgrade Path](#upgrade-path) for further details. + +### Feasibility of the Proposed Solutions + +Solution 0, besides the drawbacks described in the previous section, provides guarantees that are +weaker than the rest. The Application does not have the assurance that more than *2nh/3* vote +extensions will *always* be available when calling `PrepareProposal` at height *h+1*. +This level of guarantees is probably not strong enough for vote extensions to be useful for some +important use cases that motivated them in the first place, e.g., encrypted mempool transactions. + +Solution 1, while being simple in that the changes needed in the current CometBFT codebase would +be rather small, is changing the block format, and would therefore require all blockchains using +ABCI 1.0 or earlier to hard-fork when upgrading to ABCI 2.0. + +Since Solution 2 can be attacked, one might prefer Solution 3, even if it is more involved +to implement. Further, we must elaborate on how we can turn Solution 3, described in abstract +terms in the previous section, into a concrete implementation compatible with the current +CometBFT codebase. + +### Current Limitations and Possible Implementations + +The main limitations affecting the current version of CometBFT are the following. + +- The current version of the blocksync reactor does not use the full + [light client verification][light-client-spec] + algorithm to validate blocks coming from other peers. +- The code being structured into the blocksync and consensus reactors, only switching from the + blocksync reactor to the consensus reactor is supported; switching in the opposite direction is + not supported. Alternatively, the consensus reactor could have a mechanism allowing a late node + to catch up by skipping calls to `PrepareProposal`/`ProcessProposal`, and + `ExtendVote`/`VerifyVoteExtension` and only calling `FinalizeBlock` for each height. + Such a mechanism does not exist at the time of writing this RFC (2023-03-02). + +The blocksync reactor featuring light client verification is among the CometBFT team's current priorities. +So it is best if this RFC does not try to delve into that problem, but just makes sure +its outcomes are compatible with that effort. + +In subsection [Cases to Address](#cases-to-address), we concluded that we can focus on +solving case (h) in theoretical terms. +However, as the current CometBFT version does not yet support switching back to blocksync once a +node has switched to consensus, we need to split case (h) into two cases. When a full node needs to +catch up... + +- **(h.1)** ... it has not switched yet from the blocksync reactor to the consensus reactor, or + +- **(h.2)** ... it has already switched to the consensus reactor. + +This is important in order to discuss the different possible implementations. + +#### Base Implementation: Persist and Propagate Extended Commit History + +In order to circumvent the fact that we cannot switch from the consensus reactor back to blocksync, +rather than just keeping the few most recent extended commits, nodes will need to keep +and gossip a backlog of extended commits so that the consensus reactor can still propose and decide +in out-of-date heights (even if those proposals will be useless). + +The base implementation - which will be part of the first release of ABCI 2.0 - consists in the conservative +approach of persisting in the block store *all* extended commits for which we have also stored +the full block. Currently, when statesync is run at startup, it saves light blocks. +This base implementation does not seek +to receive or persist extended commits for those light blocks as they would not be of any use. + +Then, we modify the blocksync reactor so that peers *always* send requested full blocks together +with the corresponding extended commit in the `BlockResponse` messages. This guarantees that the +block store being reconstructed by blocksync has the same information as that of peers that are +up to date (at least starting from the latest snapshot applied by statesync before starting blocksync). +Thus, blocksync has all the data it requires to switch to the consensus reactor, as long as one of +the following exit conditions are met: + +- The node is still at height 0 (where no commit or extended commit is needed). +- The node has processed at least 1 block in blocksync. +- The node recovered and, after handshaking with the Application, it realizes it had persisted + an extended commit in its block store for the height previous to the one it is to start. + +The second condition is needed in case the node has installed an Application snapshot during statesync. +If that is the case, at the time blocksync starts, the block store only has the data statesync has saved: +light blocks, and no extended commits. +Hence we need to blocksync at least one block from another node, which will be sent with its corresponding extended commit, before we can switch to consensus. + +A chain might be started at a height *hi > 0*, all other heights +*h < hi* being non-existent. In this case, the chain is still considered to be at height 0 before +block *hi* is applied, so the first condition above allows the node to switch to consensus even +if blocksync has not processed any block (which is always the case if all nodes are starting from scratch). + +The third condition is needed to ensure liveness in the case where all validators crash at the same height. +Without the third condition, they all would wait to blocksync at least one block upon recovery. +However, as all validators crashed no further block can be produced and thus blocksync would block forever. + +When a validator falls behind while having already switched to the consensus reactor, a peer node can +simply retrieve the extended commit for the required height from the block store and reconstruct a set of +precommit votes together with their extensions and send them in the form of precommit messages to the +validator falling behind, regardless of whether the peer node holds the extended commit because it +actually participated in that consensus and thus received the precommit messages, or it received the extended commit via a `BlockResponse` message while running blocksync itself. + +This base implementation requires a few changes to the consensus reactor: + +- upon saving the block for a given height in the block store at decision time, save the + corresponding extended commit as well +- in the catch-up mechanism, when a node realizes that another peer is more than 2 heights + behind, it uses the extended commit (rather than the canonical commit as done previously) to + reconstruct the precommit votes with their corresponding extensions + +The changes to the blocksync reactor are more substantial: + +- the `BlockResponse` message is extended to include the extended commit of the same height as + the block included in the response (just as they are stored in the block store) +- structure `bpRequester` is likewise extended to hold the received extended commits coming in + `BlockResponse` messages +- method `PeekTwoBlocks` is modified to also return the extended commit corresponding to the first block +- when successfully verifying a received block, the reactor saves the block along with + its corresponding extended commit in the block store + +The two main drawbacks of this base implementation are: + +- the increased size taken by the block store, in particular with big extensions +- the increased bandwidth taken by the new format of `BlockResponse` + +#### Possible Optimization: Pruning the Extended Commit History + +If we cannot switch from the consensus reactor back to the blocksync reactor we cannot prune the extended commit backlog in the block store without sacrificing the implementation's correctness. The asynchronous +nature of our distributed system model allows a process to fall behind an arbitrary number of +heights, and thus all extended commits need to be kept *just in case* a node that late had +previously switched to the consensus reactor. + +However, there is a possibility to optimize the base implementation. Every time we enter a new height, +we could prune from the block store all extended commits that are more than *d* heights in the past. +Then, we need to handle two new situations, roughly equivalent to cases (h.1) and (h.2) described above. + +- (h.1) A node starts from scratch or recovers after a crash. In this case, we need to modify the + blocksync reactor's base implementation. + - when receiving a `BlockResponse` message, it MUST accept that the extended commit set to `nil`, + - when sending a `BlockResponse` message, if the block store contains the extended commit for that + height, it MUST set it in the message, otherwise it sets it to `nil`, + - the exit conditions used for the base implementation are no longer valid; the only reliable exit + condition now consists in making sure that the last block processed by blocksync was received with + the corresponding commit, and not `nil`; this extended commit will allow the node to switch from + the blocksync reactor to the consensus reactor and immediately act as a proposer if required. +- (h.2) A node already running the consensus reactor falls behind beyond *d* heights. In principle, + the node will be stuck forever as no other node can provide the vote extensions it needs to make + progress (they all have pruned the corresponding extended commit). + However we can manually have the node crash and recover as a workaround. This effectively converts + this case into (h.1). + +Finally, note that it makes sense to pair this optimization with the `retain_height` ABCI parameter. +Whenever we prune blocks from the block store due to `retain_height`, +we also prune the corresponding extended commit. +This is problematic both in (h.1) and (h.2), as a node that falls behind the lowest value +of `retain_height` in the rest of the network will never be able to catch up. +Nevertheless, this problem predates ABCI 2.0, and vote extensions do not make it worse. + +### Upgrade Path + +ABCI 2.0 will be the first version to implement vote extensions. +Upgrading a blockchain to ABCI 2.0 from a previous version MUST be feasible via a coordinated upgrade: +a blockchain upgrading to ABCI 2.0 should not be forced to hard fork (i.e. create a new chain). + +Vote extensions pose an issue for CometBFT upgrades. +Blockchains that perform a coordinated upgrade from ABCI 1.0 to ABCI 2.0 will attempt +to produce the first height running ABCI 2.0 without vote extension data from the previous height. +As explained in previous sections, blockchains running ABCI 2.0 *require* vote extension data in each +[PrepareProposal](https://github.com/cometbft/cometbft/blob/feature/abci++vef/proto/tendermint/abci/types.proto#L134) +call. + +#### New `ConsensusParam` + +To facilitate the upgrade and provide applications a mechanism to require vote extensions, +we introduce a new +[`ConsensusParam`](https://github.com/cometbft/cometbft/blob/38a4cae/proto/tendermint/types/params.proto#L13) +to transition the chain from maintaining no history of vote extensions to requiring vote extensions. +This parameter is an `int64` representing the first height where vote extensions +will be required for votes to be considered valid. + +The initial value of this `ConsensusParam` is 0, +which is also its implicit value in versions prior to ABCI 2.0, +denoting that an extension-enabling height has not been decided yet. +Once the upgrade to ABCI 2.0 has taken place, +the value MAY be set to some height, *he*, +which MUST be higher than the current height of the chain. +From the moment when the `ConsensusParam` > 0, +for all heights *h ≥ he*, the consensus algorithm will +reject any votes that do not have vote extension data as invalid. +Likewise, for all heights *h < he*, any votes that *do* have vote extensions +will be considered an error condition. +Height *he* is somewhat special, as calls to `PrepareProposal` MUST NOT +have vote extension data, but all precommit votes in that height MUST carry a vote extension. +Height *he + 1* is the first height for which `PrepareProposal` MUST have vote +extension data and all precommit votes in that height MUST have a vote extension. + +#### Upgrading and Transitioning to Vote Extensions + +Just after upgrading (via coordinated upgrade) to ABCI 2.0, vote extensions stay disabled, +as the Application needs to decide on a future height to be set for transitioning to vote extensions. +The earliest this can happen is *hu + 1*, where *hu* denotes the upgrade height, +i.e., the height at which all nodes will start when they restart with the upgraded binary. + +Once a node reaches the configured height *he*, the parameter is disallowed from changing. +Vote extensions cannot flip from being required to being optional. +This is enforced by the `ConsensusParam` validation logic. Forcing vote extensions to +be required beyond the configured height simplifies the logic for transitioning +from optional to required since all checks will only need to understand if the +chain *ever* enabled vote extensions in the past. Additionally, the major known +uses cases of vote extensions such as threshold decryption and oracle data will +be *central* components of the applications that use vote extensions. Flipping +vote extensions to be no longer required will fundamentally change the behavior +of the application and is therefore not valuable to these applications. + +Additional discussion and implementation of this upgrade strategy can be found +in GitHub [issue 8453][toggle-vote-extensions]. + +We now explain the changes we need to introduce in key solutions/implementation proposed in previous sections +so that they still work in the presence of an upgrade to ABCI 2.0. +For simplicity, in any conditions comparing a height to *he*, +if *he* is 0 (not set yet) then the condition assumes *he = ∞*. + +#### Changes Required in Solution 3 + +These are the changes needed in Solution 3, as defined in section [Solutions Proposed](#solutions-proposed) +so that it works properly with upgrades. + +First, we need to extend the safety property, which is key to that solution, +to take the agreed extension-enabling height into account. + +The key change is in the switching height *h'*: + +- for every height *hp*, a full node *f* in *hp* refuses to switch to catch-up + mode **until** there exists a height *h'* such that: + - *p* has received and (light-client) verified the blocks of + all heights *h*, where *hp ≤ h ≤ h'* + - if *h' > he* + - it has received an extended commit for *h'* and has verified: + - the precommit vote signatures in the extended commit + - the vote extension signatures in the extended commit: each is signed with the same + key as the precommit vote it extends + +Note that, since the (light-client) verification is the only requirement for all *h' ≤ h*, +the property falls back to the pre-ABCI 2.0 requirements for block sync in those heights. + +#### Changes Required in the Base Implementation + +The base implementation as defined in section +[Base Implementation](#base-implementation-persist-and-propagate-extended-commit-history) +cannot work as such when a blockchain upgrades, and thus it needs the following modifications. + +Firstly, the conditions for switching to consensus listed in section +[Base Implementation](#base-implementation-persist-and-propagate-extended-commit-history) +remain valid, but we need to add a new condition. + +- The node is still at a height *h < he*. + +We have taken the changes required by the base implementation, +initially decribed in section +[Base Implementation](#base-implementation-persist-and-propagate-extended-commit-history), +and adapted them so that +they support upgrading to ABCI 2.0 in the terms described earlier in this section: + +Changes to the consensus reactor: + +- upon saving the block for a given height *h* in the block store at decision time + - if *h ≥ he*, save the corresponding extended commit as well + - if *h < he*, follow the logic implemented prior to ABCI 2.0 +- in the catch-up mechanism, when a node *f* realizes that another peer is at height *hp*, + which is more than 2 heights behind, + - if *hp ≥ he*, *f* uses the extended commit to + reconstruct the precommit votes with their corresponding extensions + - if *hp < he*, *f* uses the canonical commit to reconstruct the precommit votes, + as done for ABCI 1.0 and earlier + +Changes to the blocksync reactor: + +- the `BlockResponse` message is extended to *optionally* include the extended commit of the same height as + the block included in the response (just as they are stored in the block store) +- structure `bpRequester` is likewise extended to *optionally* hold received extended commits coming in + `BlockResponse` messages +- method `PeekTwoBlocks` is modified in the following way + - if the first block's height *h ≥ he*, it returns the block together with the extended commit corresponding to the first block + - if the first block's height *h < he*, it returns the block and `nil` as extended commit +- when successfully verifying a received block, + - if the block's height *h ≥ he*, the reactor saves the block, + along with its corresponding extended commit in the block store + - if the block's height *h < he*, the reactor saves the block in the block store, + and `nil` as extended commit + +### Formalization Work + +A formalization work to show or prove the correctness of the different use cases and solutions +presented here (and any other that may be found) needs to be carried out. +A question that needs a precise answer is how many extended commits (one?, two?) a node needs +to keep in persistent memory when implementing Solution 3 described above without CometBFT's +current limitations. +Another important invariant we need to prove formally is that the set of vote extensions +required to make progress will always be held somewhere in the network. + +## References + +- [ABCI 0.17.0 specification][abci-0-17-0] +- [ABCI 1.0 specification][abci-1-0] +- [ABCI 2.0 specification][abci-2-0] +- [Light client verification][light-client-spec] +- [Empty vote extensions issue](https://github.com/tendermint/tendermint/issues/8174) +- [Toggle vote extensions issue][toggle-vote-extensions] + +[abci-0-17-0]: https://github.com/cometbft/cometbft/blob/v0.34.x/spec/abci/README.md +[abci-1-0]: https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/README.md +[abci-2-0]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/README.md +[light-client-spec]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/README.md +[toggle-vote-extensions]: https://github.com/tendermint/tendermint/issues/8453 diff --git a/docs/rfc/rfc-template.md b/docs/rfc/rfc-template.md new file mode 100644 index 0000000..a48f49d --- /dev/null +++ b/docs/rfc/rfc-template.md @@ -0,0 +1,35 @@ +# RFC {RFC-NUMBER}: {TITLE} + +## Changelog + +- {date}: {changelog} + +## Abstract + +> A brief high-level synopsis of the topic of discussion for this RFC, ideally +> just a few sentences. This should help the reader quickly decide whether the +> rest of the discussion is relevant to their interest. + +## Background + +> Any context or orientation needed for a reader to understand and participate +> in the substance of the Discussion. If necessary, this section may include +> links to other documentation or sources rather than restating existing +> material, but should provide enough detail that the reader can tell what they +> need to read to be up-to-date. + +### References + +> Links to external materials needed to follow the discussion may be added here. +> +> In addition, if the discussion in a request for comments leads to any design +> decisions, it may be helpful to add links to the ADR documents here after the +> discussion has settled. + +## Discussion + +> This section contains the core of the discussion. +> +> There is no fixed format for this section, but ideally changes to this +> section should be updated before merging to reflect any discussion that took +> place on the PR that made those changes. diff --git a/docs/rfc/tendermint-core/README.md b/docs/rfc/tendermint-core/README.md new file mode 100644 index 0000000..75cee91 --- /dev/null +++ b/docs/rfc/tendermint-core/README.md @@ -0,0 +1,41 @@ +--- +order: 1 +parent: + order: false +--- + +# Tendermint Core Requests for Comments + +This document serves as a historical reference for all RFCs that were logged +during the development of Tendermint Core. + +This list is frozen as-is, and new RFCs should be added [here](../). + +## Table of Contents + +- [RFC-000: P2P Roadmap](./rfc-000-p2p-roadmap.rst) +- [RFC-001: Storage Engines](./rfc-001-storage-engine.rst) +- [RFC-002: Interprocess Communication](./rfc-002-ipc-ecosystem.md) +- [RFC-003: Performance Taxonomy](./rfc-003-performance-questions.md) +- [RFC-004: E2E Test Framework Enhancements](./rfc-004-e2e-framework.rst) +- [RFC-005: Event System](./rfc-005-event-system.rst) +- [RFC-006: Event Subscription](./rfc-006-event-subscription.md) +- [RFC-007: Deterministic Proto Byte Serialization](./rfc-007-deterministic-proto-bytes.md) +- [RFC-008: Don't Panic](./rfc-008-do-not-panic.md) +- [RFC-009: Consensus Parameter Upgrades](./rfc-009-consensus-parameter-upgrades.md) +- [RFC-010: P2P Light Client](./rfc-010-p2p-light-client.rst) +- [RFC-011: Delete Gas](./rfc-011-delete-gas.md) +- [RFC-012: Event Indexing Revisited](./rfc-012-custom-indexing.md) +- [RFC-013: ABCI++](./rfc-013-abci++.md) +- [RFC-014: Semantic Versioning](./rfc-014-semantic-versioning.md) +- [RFC-015: ABCI++ Tx Mutation](./rfc-015-abci++-tx-mutation.md) +- [RFC-016: Node Architecture](./rfc-016-node-architecture.md) +- [RFC-017: ABCI++ Vote Extension Propagation](./rfc-017-abci++-vote-extension-propag.md) +- [RFC-018: BLS Signature Aggregation Exploration](./rfc-018-bls-agg-exploration.md) +- [RFC-019: Configuration File Versioning](./rfc-019-config-version.md) +- [RFC-020: Onboarding Projects](./rfc-020-onboarding-projects.rst) +- [RFC-021: The Future of the Socket Protocol](./rfc-021-socket-protocol.md) +- [RFC-023: Semi-permanent Testnet](./rfc-023-semi-permanent-testnet.md) +- [RFC-024: Block Structure Consolidation](./rfc-024-block-structure-consolidation.md) +- [RFC-025: Application Defined Transaction Storage](./rfc-025-support-app-side-mempool.md) +- [RFC-027: P2P Message Bandwidth Report](./rfc-027-p2p-message-bandwidth-report.md) diff --git a/docs/rfc/tendermint-core/images/abci++.png b/docs/rfc/tendermint-core/images/abci++.png new file mode 100644 index 0000000..8121354 Binary files /dev/null and b/docs/rfc/tendermint-core/images/abci++.png differ diff --git a/docs/rfc/tendermint-core/images/abci.png b/docs/rfc/tendermint-core/images/abci.png new file mode 100644 index 0000000..69c7368 Binary files /dev/null and b/docs/rfc/tendermint-core/images/abci.png differ diff --git a/docs/rfc/tendermint-core/images/node-dependency-tree.svg b/docs/rfc/tendermint-core/images/node-dependency-tree.svg new file mode 100644 index 0000000..fd0e04c --- /dev/null +++ b/docs/rfc/tendermint-core/images/node-dependency-tree.svg @@ -0,0 +1,3 @@ + + +
Node
Node
Statesync
Statesync
Blocksync
Blocksync
Consensus
Consensus
Mempool
Mempool
Evidence
Evidence
Block Executor
Block Executor
Blockchain
Blockchain
Evidence
Evidence
PEX
PEX
Peer Store
Peer Store
Peer Networking
Peer Networking
RPC External
RPC External
ABCI Layer
ABCI Layer
Events System
Events System
RPC Internal
RPC Internal
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/docs/rfc/tendermint-core/images/receive-rate-all.png b/docs/rfc/tendermint-core/images/receive-rate-all.png new file mode 100644 index 0000000..9effd7a Binary files /dev/null and b/docs/rfc/tendermint-core/images/receive-rate-all.png differ diff --git a/docs/rfc/tendermint-core/images/send-rate-all.png b/docs/rfc/tendermint-core/images/send-rate-all.png new file mode 100644 index 0000000..b92a7cc Binary files /dev/null and b/docs/rfc/tendermint-core/images/send-rate-all.png differ diff --git a/docs/rfc/tendermint-core/images/top-3-percent-receive.png b/docs/rfc/tendermint-core/images/top-3-percent-receive.png new file mode 100644 index 0000000..6547fc9 Binary files /dev/null and b/docs/rfc/tendermint-core/images/top-3-percent-receive.png differ diff --git a/docs/rfc/tendermint-core/images/top-3-percent-send.png b/docs/rfc/tendermint-core/images/top-3-percent-send.png new file mode 100644 index 0000000..7103c31 Binary files /dev/null and b/docs/rfc/tendermint-core/images/top-3-percent-send.png differ diff --git a/docs/rfc/tendermint-core/rfc-000-p2p-roadmap.rst b/docs/rfc/tendermint-core/rfc-000-p2p-roadmap.rst new file mode 100644 index 0000000..c803402 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-000-p2p-roadmap.rst @@ -0,0 +1,316 @@ +==================== +RFC 000: P2P Roadmap +==================== + +Changelog +--------- + +- 2021-08-20: Completed initial draft and distributed via a gist +- 2021-08-25: Migrated as an RFC and changed format + +Abstract +-------- + +This document discusses the future of peer network management in Tendermint, with +a particular focus on features, semantics, and a proposed roadmap. +Specifically, we consider libp2p as a tool kit for implementing some fundamentals. + +Background +---------- + +For the 0.35 release cycle the switching/routing layer of Tendermint was +replaced. This work was done "in place," and produced a version of Tendermint +that was backward-compatible and interoperable with previous versions of the +software. While there are new p2p/peer management constructs in the new +version (e.g. ``PeerManager`` and ``Router``), the main effect of this change +was to simplify the ways that other components within Tendermint interacted with +the peer management layer, and to make it possible for higher-level components +(specifically the reactors), to be used and tested more independently. + +This refactoring, which was a major undertaking, was entirely necessary to +enable areas for future development and iteration on this aspect of +Tendermint. There are also a number of potential user-facing features that +depend heavily on the p2p layer: additional transport protocols, transport +compression, improved resilience to network partitions. These improvements to +modularity, stability, and reliability of the p2p system will also make +ongoing maintenance and feature development easier in the rest of Tendermint. + +Critique of Current Peer-to-Peer Infrastructure +--------------------------------------- + +The current (refactored) P2P stack is an improvement on the previous iteration +(legacy), but as of 0.35, there remains room for improvement in the design and +implementation of the P2P layer. + +Some limitations of the current stack include: + +- heavy reliance on buffering to avoid backups in the flow of components, + which is fragile to maintain and can lead to unexpected memory usage + patterns and forces the routing layer to make decisions about when messages + should be discarded. + +- the current p2p stack relies on convention (rather than the compiler) to + enforce the API boundaries and conventions between reactors and the router, + making it very easy to write "wrong" reactor code or introduce a bad + dependency. + +- the current stack is probably more complex and difficult to maintain because + the legacy system must coexist with the new components in 0.35. When the + legacy stack is removed there are some simple changes that will become + possible and could reduce the complexity of the new system. (e.g. `#6598 + `_.) + +- the current stack encapsulates a lot of information about peers, and makes it + difficult to expose that information to monitoring/observability tools. This + general opacity also makes it difficult to interact with the peer system + from other areas of the code base (e.g. tests, reactors). + +- the legacy stack provided some control to operators to force the system to + dial new peers or seed nodes or manipulate the topology of the system _in + situ_. The current stack can't easily provide this, and while the new stack + may have better behavior, it does leave operators hands tied. + +Some of these issues will be resolved early in the 0.36 cycle, with the +removal of the legacy components. + +The 0.36 release also provides the opportunity to make changes to the +protocol, as the release will not be compatible with previous releases. + +Areas for Development +--------------------- + +These sections describe features that may make sense to include in a Phase 2 of +a P2P project. + +Internal Message Passing +~~~~~~~~~~~~~~~~~~~~~~~~ + +Currently, there's no provision for intranode communication using the P2P +layer, which means when two reactors need to interact with each other they +have to have dependencies on each other's interfaces, and +initialization. Changing these interactions (e.g. transitions between +blocksync and consensus) from procedure calls to message passing. + +This is a relatively simple change and could be implemented with the following +components: + +- a constant to represent "local" delivery as the ``To`` field on + ``p2p.Envelope``. + +- special path for routing local messages that doesn't require message + serialization (protobuf marshalling/unmarshaling). + +Adding these semantics, particularly if in conjunction with synchronous +semantics provides a solution to dependency graph problems currently present +in the Tendermint codebase, which will simplify development, make it possible +to isolate components for testing. + +Eventually, this will also make it possible to have a logical Tendermint node +running in multiple processes or in a collection of containers, although the +usecase of this may be debatable. + +Synchronous Semantics (Paired Request/Response) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the current system, all messages are sent with fire-and-forget semantics, +and there's no coupling between a request sent via the p2p layer, and a +response. These kinds of semantics would simplify the implementation of +state and block sync reactors, and make intra-node message passing more +powerful. + +For some interactions, like gossiping transactions between the mempools of +different nodes, fire-and-forget semantics make sense, but for other +operations the missing link between requests/responses leads to either +inefficiency when a node fails to respond or becomes unavailable, or code that +is just difficult to follow. + +To support this kind of work, the protocol would need to accommodate some kind +of request/response ID to allow identifying out-of-order responses over a +single connection. Additionally, expanded the programming model of the +``p2p.Channel`` to accommodate some kind of _future_ or similar paradigm to +make it viable to write reactor code without needing for the reactor developer +to wrestle with lower level concurrency constructs. + + +Timeout Handling (QoS) +~~~~~~~~~~~~~~~~~~~~~~ + +Currently, all timeouts, buffering, and QoS features are handled at the router +layer, and the reactors are implemented in ways that assume/require +asynchronous operation. This both increases the required complexity at the +routing layer, and means that misbehavior at the reactor level is difficult to +detect or attribute. Additionally, the current system provides three main +parameters to control quality of service: + +- buffer sizes for channels and queues. + +- priorities for channels + +- queue implementation details for shedding load. + +These end up being quite coarse controls, and changing the settings are +difficult because as the queues and channels are able to buffer large numbers +of messages it can be hard to see the impact of a given change, particularly +in our extant test environment. In general, we should endeavor to: + +- set real timeouts, via contexts, on most message send operations, so that + senders rather than queues can be responsible for timeout + logic. Additionally, this will make it possible to avoid sending messages + during shutdown. + +- reduce (to the greatest extent possible) the amount of buffering in + channels and the queues, to more readily surface backpressure and reduce the + potential for buildup of stale messages. + +Stream Based Connection Handling +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Currently the transport layer is message based, which makes sense from a +mental model of how the protocol works, but makes it more difficult to +implement transports and connection types, as it forces a higher level view of +the connection and interaction which makes it harder to implement for novel +transport types and makes it more likely that message-based caching and rate +limiting will be implemented at the transport layer rather than at a more +appropriate level. + +The transport then, would be responsible for negotiating the connection and the +handshake and otherwise behave like a socket/file descriptor with ``Read`` and +``Write`` methods. + +While this was included in the initial design for the new P2P layer, it may be +obviated entirely if the transport and peer layer is replaced with libp2p, +which is primarily stream based. + +Service Discovery +~~~~~~~~~~~~~~~~~ + +In the current system, Tendermint assumes that all nodes in a network are +largely equivalent, and nodes tend to be "chatty" making many requests of +large numbers of peers and waiting for peers to (hopefully) respond. While +this works and has allowed Tendermint to get to a certain point, this both +produces a theoretical scaling bottle neck and makes it harder to test and +verify components of the system. + +In addition to peer's identity and connection information, peers should be +able to advertise a number of services or capabilities, and node operators or +developers should be able to specify peer capability requirements (e.g. target +at least -percent of peers with capability.) + +These capabilities may be useful in selecting peers to send messages to, it +may make sense to extend Tendermint's message addressing capability to allow +reactors to send messages to groups of peers based on role rather than only +allowing addressing to one or all peers. + +Having a good service discovery mechanism may pair well with the synchronous +semantics (request/response) work, as it allows reactors to "make a request of +a peer with capability and wait for the response," rather force the +reactors to need to track the capabilities or state of specific peers. + +Solutions +--------- + +Continued Homegrown Implementation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The current peer system is homegrown and is conceptually compatible with the +needs of the project, and while there are limitations to the system, the p2p +layer is not (currently as of 0.35) a major source of bugs or friction during +development. + +However, the current implementation makes a number of allowances for +interoperability, and there are a collection of iterative improvements that +should be considered in the next couple of releases. To maintain the current +implementation, upcoming work would include: + +- change the ``Transport`` mechanism to facilitate easier implementations. + +- implement different ``Transport`` handlers to be able to manage peer + connections using different protocols (e.g. QUIC, etc.) + +- entirely remove the constructs and implementations of the legacy peer + implementation. + +- establish and enforce clearer chains of responsibility for connection + establishment (e.g. handshaking, setup,) which is currently shared between + three components. + +- report better metrics regarding the into the state of peers and network + connectivity, which are opaque outside of the system. This is constrained at + the moment as a side effect of the split responsibility for connection + establishment. + +- extend the PEX system to include service information so that nodes in the + network weren't necessarily homogeneous. + +While maintaining a bespoke peer management layer would seem to distract from +development of core functionality, the truth is that (once the legacy code is +removed,) the scope of the peer layer is relatively small from a maintenance +perspective, and having control at this layer might actually afford the +project with the ability to more rapidly iterate on some features. + +LibP2P +~~~~~~ + +LibP2P provides components that, approximately, account for the +``PeerManager`` and ``Transport`` components of the current (new) P2P +stack. The Go APIs seem reasonable, and being able to externalize the +implementation details of peer and connection management seems like it could +provide a lot of benefits, particularly in supporting a more active ecosystem. + +In general the API provides the kind of stream-based, multi-protocol +supporting, and idiomatic baseline for implementing a peer layer. Additionally +because it handles peer exchange and connection management at a lower +level, by using libp2p it'd be possible to remove a good deal of code in favor +of just using libp2p. Having said that, Tendermint's P2P layer covers a +greater scope (e.g. message routing to different peers) and that layer is +something that Tendermint might want to retain. + +The are a number of unknowns that require more research including how much of +a peer database the Tendermint engine itself needs to maintain, in order to +support higher level operations (consensus, statesync), but it might be the +case that our internal systems need to know much less about peers than +otherwise specified. Similarly, the current system has a notion of peer +scoring that cannot be communicated to libp2p, which may be fine as this is +only used to support peer exchange (PEX,) which would become a property libp2p +and not expressed in it's current higher-level form. + +In general, the effort to switch to libp2p would involve: + +- timing it during an appropriate protocol-breaking window, as it doesn't seem + viable to support both libp2p *and* the current p2p protocol. + +- providing some in-memory testing network to support the use case that the + current ``p2p.MemoryNetwork`` provides. + +- re-homing the ``p2p.Router`` implementation on top of libp2p components to + be able to maintain the current reactor implementations. + +Open question include: + +- how much local buffering should we be doing? It sort of seems like we should + figure out what the expected behavior is for libp2p for QoS-type + functionality, and if our requirements mean that we should be implementing + this on top of things ourselves? + +- if Tendermint was going to use libp2p, how would libp2p's stability + guarantees (protocol, etc.) impact/constrain Tendermint's stability + guarantees? + +- what kind of introspection does libp2p provide, and to what extend would + this change or constrain the kind of observability that Tendermint is able + to provide? + +- how do efforts to select "the best" (healthy, close, well-behaving, etc.) + peers work out if Tendermint is not maintaining a local peer database? + +- would adding additional higher level semantics (internal message passing, + request/response pairs, service discovery, etc.) facilitate removing some of + the direct linkages between constructs/components in the system and reduce + the need for Tendermint nodes to maintain state about its peers? + +References +---------- + +- `Tracking Ticket for P2P Refactor Project `_ +- `ADR 61: P2P Refactor Scope <../architecture/adr-061-p2p-refactor-scope.md>`_ +- `ADR 62: P2P Architecture and Abstraction <../architecture/adr-062-p2p-architecture.md>`_ diff --git a/docs/rfc/tendermint-core/rfc-001-storage-engine.rst b/docs/rfc/tendermint-core/rfc-001-storage-engine.rst new file mode 100644 index 0000000..3ec1d27 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-001-storage-engine.rst @@ -0,0 +1,179 @@ +=========================================== +RFC 001: Storage Engines and Database Layer +=========================================== + +Changelog +--------- + +- 2021-04-19: Initial Draft (gist) +- 2021-09-02: Migrated to RFC folder, with some updates + +Abstract +-------- + +The aspect of Tendermint that's responsible for persistence and storage (often +"the database" internally) represents a bottle neck in the architecture of the +platform, that the 0.36 release presents a good opportunity to correct. The +current storage engine layer provides a great deal of flexibility that is +difficult for users to leverage or benefit from, while also making it harder +for Tendermint Core developers to deliver improvements on storage engine. This +RFC discusses the possible improvements to this layer of the system. + +Background +---------- + +Tendermint has a very thin common wrapper that makes Tendermint itself +(largely) agnostic to the data storage layer (within the realm of the popular +key-value/embedded databases.) This flexibility is not particularly useful: +the benefits of a specific database engine in the context of Tendermint is not +particularly well understood, and the maintenance burden for multiple backends +is not commensurate with the benefit provided. Additionally, because the data +storage layer is handled generically, and most tests run with an in-memory +framework, it's difficult to take advantage of any higher-level features of a +database engine. + +Ideally, developers within Tendermint will be able to interact with persisted +data via an interface that can function, approximately like an object +store, and this storage interface will be able to accommodate all existing +persistence workloads (e.g. block storage, local peer management information +like the "address book", crash-recovery log like the WAL.) In addition to +providing a more ergonomic interface and new semantics, by selecting a single +storage engine tendermint can use native durability and atomicity features of +the storage engine and simplify its own implementations. + +Data Access Patterns +~~~~~~~~~~~~~~~~~~~~ + +Tendermint's data access patterns have the following characteristics: + +- aggregate data size often exceeds memory. + +- data is rarely mutated after it's written for most data (e.g. blocks), but + small amounts of working data is persisted by nodes and is frequently + mutated (e.g. peer information, validator information.) + +- read patterns can be quite random. + +- crash resistance and crash recovery, provided by write-ahead-logs (in + consensus, and potentially for the mempool) should allow the system to + resume work after an unexpected shut down. + +Project Goals +~~~~~~~~~~~~~ + +As we think about replacing the current persistence layer, we should consider +the following high level goals: + +- drop dependencies on storage engines that have a CGo dependency. + +- encapsulate data format and data storage from higher-level services + (e.g. reactors) within tendermint. + +- select a storage engine that does not incur any additional operational + complexity (e.g. database should be embedded.) + +- provide database semantics with sufficient ACID, snapshots, and + transactional support. + +Open Questions +~~~~~~~~~~~~~~ + +The following questions remain: + +- what kind of data-access concurrency does tendermint require? + +- would tendermint users SDK/etc. benefit from some shared database + infrastructure? + + - In earlier conversations it seemed as if the SDK has selected Badger and + RocksDB for their storage engines, and it might make sense to be able to + (optionally) pass a handle to a Badger instance between the libraries in + some cases. + +- what are typical data sizes, and what kinds of memory sizes can we expect + operators to be able to provide? + +- in addition to simple persistence, what kind of additional semantics would + tendermint like to enjoy (e.g. transactional semantics, unique constraints, + indexes, in-place-updates, etc.)? + +Decision Framework +~~~~~~~~~~~~~~~~~~ + +Given the constraint of removing the CGo dependency, the decision is between +"badger" and "boltdb" (in the form of the etcd/CoreOS fork,) as low level. On +top of this and somewhat orthogonally, we must also decide on the interface to +the database and how the larger application will have to interact with the +database layer. Users of the data layer shouldn't ever need to interact with +raw byte slices from the database, and should mostly have the experience of +interacting with Go-types. + +Badger is more consistently developed and has a broader feature set than +Bolt. At the same time, Badger is likely more memory intensive and may have +more overhead in terms of open file handles given it's model. At first glance, +Badger is the obvious choice: it's actively developed and it has a lot of +features that could be useful. Bolt is not without some benefits: it's stable +and is maintained by the etcd folks, it's simpler model (single memory mapped +file, etc,) may be easier to reason about. + +I propose that we consider the following specific questions about storage +engines: + +- does Badger's evolving development, which may result in data file format + changes in the future, and could restrict our access to using the latest + version of the library between major upgrades, present a problem? + +- do we do we have goals/concerns about memory footprint that Badger may + prevent us from hitting, particularly as data sets grow over time? + +- what kind of additional tooling might we need/like to build (dump/restore, + etc.)? + +- do we want to run unit/integration tests against a data files on disk rather + than relying exclusively on the memory database? + +Project Scope +~~~~~~~~~~~~~ + +This project will consist of the following aspects: + +- selecting a storage engine, and modifying the tendermint codebase to + disallow any configuration of the storage engine outside of the tendermint. + +- remove the dependency on the current tm-db interfaces and replace with some + internalized, safe, and ergonomic interface for data persistence with all + required database semantics. + +- update core tendermint code to use the new interface and data tools. + +Next Steps +~~~~~~~~~~ + +- circulate the RFC, and discuss options with appropriate stakeholders. + +- write brief ADR to summarize decisions around technical decisions reached + during the RFC phase. + +References +---------- + +- `bolddb `_ +- `badger `_ +- `badgerdb overview `_ +- `botldb overview `_ +- `boltdb vs badger `_ +- `bolthold `_ +- `badgerhold `_ +- `Pebble `_ +- `SDK Issue Regarding IVAL `_ +- `SDK Discussion about SMT/IVAL `_ + +Discussion +---------- + +- All things being equal, my tendency would be to use badger, with badgerhold + (if that makes sense) for its ergonomics and indexing capabilities, which + will require some small selection of wrappers for better write transaction + support. This is a weakly held tendency/belief and I think it would be + useful for the RFC process to build consensus (or not) around this basic + assumption. diff --git a/docs/rfc/tendermint-core/rfc-002-ipc-ecosystem.md b/docs/rfc/tendermint-core/rfc-002-ipc-ecosystem.md new file mode 100644 index 0000000..4bcb0f0 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-002-ipc-ecosystem.md @@ -0,0 +1,420 @@ +# RFC 002: Interprocess Communication (IPC) in Tendermint + +## Changelog + +- 08-Sep-2021: Initial draft (@creachadair). + + +## Abstract + +Communication in Tendermint among consensus nodes, applications, and operator +tools all use different message formats and transport mechanisms. In some +cases there are multiple options. Having all these options complicates both the +code and the developer experience, and hides bugs. To support a more robust, +trustworthy, and usable system, we should document which communication paths +are essential, which could be removed or reduced in scope, and what we can +improve for the most important use cases. + +This document proposes a variety of possible improvements of varying size and +scope. Specific design proposals should get their own documentation. + + +## Background + +The Tendermint state replication engine has a complex IPC footprint. + +1. Consensus nodes communicate with each other using a networked peer-to-peer + message-passing protocol. + +2. Consensus nodes communicate with the application whose state is being + replicated via the [Application BlockChain Interface (ABCI)][abci]. + +3. Consensus nodes export a network-accessible [RPC service][rpc-service] to + support operations (bootstrapping, debugging) and synchronization of [light clients][light-client]. + This interface is also used by the [`tendermint` CLI][tm-cli]. + +4. Consensus nodes export a gRPC service exposing a subset of the methods of + the RPC service described by (3). This was intended to simplify the + implementation of tools that already use gRPC to communicate with an + application (via the Cosmos SDK), and wanted to also talk to the consensus + node without implementing yet another RPC protocol. + + The gRPC interface to the consensus node has been deprecated and is slated + for removal in the forthcoming Tendermint v0.36 release. + +5. Consensus nodes may optionally communicate with a "remote signer" that holds + a validator key and can provide public keys and signatures to the consensus + node. One of the stated goals of this configuration is to allow the signer + to be run on a private network, separate from the consensus node, so that a + compromise of the consensus node from the public network would be less + likely to expose validator keys. + +## Discussion: Transport Mechanisms + +### Remote Signer Transport + +A remote signer communicates with the consensus node in one of two ways: + +1. "Raw": Using a TCP or Unix-domain socket which carries varint-prefixed + protocol buffer messages. In this mode, the consensus node is the server, + and the remote signer is the client. + + This mode has been deprecated, and is intended to be removed. + +2. gRPC: This mode uses the same protobuf messages as "Raw" node, but uses a + standard encrypted gRPC HTTP/2 stub as the transport. In this mode, the + remote signer is the server and the consensus node is the client. + + +### ABCI Transport + +In ABCI, the _application_ is the server, and the Tendermint consensus engine +is the client. Most applications implement the server using the [Cosmos SDK][cosmos-sdk], +which handles low-level details of the ABCI interaction and provides a +higher-level interface to the rest of the application. The SDK is written in Go. + +Beneath the SDK, the application communicates with Tendermint core in one of +two ways: + +- In-process direct calls (for applications written in Go and compiled against + the Tendermint code). This is an optimization for the common case where an + application is written in Go, to save on the overhead of marshaling and + unmarshaling requests and responses within the same process: + [`abci/client/local_client.go`][local-client] + +- A custom remote procedure protocol built on wire-format protobuf messages + using a socket (the "socket protocol"): [`abci/server/socket_server.go`][socket-server] + +The SDK also provides a [gRPC service][sdk-grpc] accessible from outside the +application, allowing transactions to be broadcast to the network, look up +transactions, and simulate transaction costs. + + +### RPC Transport + +The consensus node RPC service allows callers to query consensus parameters +(genesis data, transactions, commits), node status (network info, health +checks), application state (abci_query, abci_info), mempool state, and other +attributes of the node and its application. The service also provides methods +allowing transactions and evidence to be injected ("broadcast") into the +blockchain. + +The RPC service is exposed in several ways: + +- HTTP GET: Queries may be sent as URI parameters, with method names in the path. + +- HTTP POST: Queries may be sent as JSON-RPC request messages in the body of an + HTTP POST request. The server uses a custom implementation of JSON-RPC that + is not fully compatible with the [JSON-RPC 2.0 spec][json-rpc], but handles + the common cases. + +- Websocket: Queries may be sent as JSON-RPC request messages via a websocket. + This transport uses more or less the same JSON-RPC plumbing as the HTTP POST + handler. + + The websocket endpoint also includes three methods that are _only_ exported + via websocket, which appear to support event subscription. + +- gRPC: A subset of queries may be issued in protocol buffer format to the gRPC + interface described above under (4). As noted, this endpoint is deprecated + and will be removed in v0.36. + +### Opportunities for Simplification + +**Claim:** There are too many IPC mechanisms. + +The preponderance of ABCI usage is via the Cosmos SDK, which means the +application and the consensus node are compiled together into a single binary, +and the consensus node calls the ABCI methods of the application directly as Go +functions. + +We also need a true IPC transport to support ABCI applications _not_ written in +Go. There are also several known applications written in Rust, for example +(including [Anoma](https://github.com/anoma/anoma), Penumbra, +[Oasis](https://github.com/oasisprotocol/oasis-core), Twilight, and +[Nomic](https://github.com/nomic-io/nomic)). Ideally we will have at most one +such transport "built-in": More esoteric cases can be handled by a custom proxy. +Pragmatically, gRPC is probably the right choice here. + +The primary consumers of the multi-headed "RPC service" today are the light +client and the `tendermint` command-line client. There is probably some local +use via curl, but I expect that is mostly ad hoc. Ethan reports that nodes are +often configured with the ports to the RPC service blocked, which is good for +security but complicates use by the light client. + +### Context: Remote Signer Issues + +Since the remote signer needs a secure communication channel to exchange keys +and signatures, and is expected to run truly remotely from the node (i.e., on a +separate physical server), there is not a whole lot we can do here. We should +finish the deprecation and removal of the "raw" socket protocol between the +consensus node and remote signers, but the use of gRPC is appropriate. + +The main improvement we can make is to simplify the implementation quite a bit, +once we no longer need to support both "raw" and gRPC transports. + +### Context: ABCI Issues + +In the original design of ABCI, the presumption was that all access to the +application should be mediated by the consensus node. The idea is that outside +access could change application state and corrupt the consensus process, which +relies on the application to be deterministic. Of course, even without outside +access an application could behave nondeterministically, but allowing other +programs to send it requests was seen as courting trouble. + +Conversely, users noted that most of the time, tools written for a particular +application don't want to talk to the consensus module directly. The +application "owns" the state machine the consensus engine is replicating, so +tools that care about application state should talk to the application. +Otherwise, they would have to bake in knowledge about Tendermint (e.g., its +interfaces and data structures) just because of the mediation. + +For clients to talk directly to the application, however, there is another +concern: The consensus node is the ABCI _client_, so it is inconvenient for the +application to "push" work into the consensus module via ABCI itself. The +current implementation works around this by calling the consensus node's RPC +service, which exposes an `ABCIQuery` kitchen-sink method that allows the +application a way to poke ABCI messages in the other direction. + +Without this RPC method, you could work around this (at least in principle) by +having the consensus module "poll" the application for work that needs done, +but that has unsatisfactory implications for performance and robustness, as +well as being harder to understand. + +There has apparently been discussion about trying to make a more bidirectional +communication between the consensus node and the application, but this issue +seems to still be unresolved. + +Another complication of ABCI is that it requires the application (server) to +maintain [four separate connections][abci-conn]: One for "consensus" operations +(BeginBlock, EndBlock, DeliverTx, Commit), one for "mempool" operations, one +for "query" operations, and one for "snapshot" (state synchronization) operations. +The rationale seems to have been that these groups of operations should be able +to proceed concurrently with each other. In practice, it results in a very complex +state management problem to coordinate state updates between the separate streams. +While application authors in Go are mostly insulated from that complexity by the +Cosmos SDK, the plumbing to maintain those separate streams is complicated, hard +to understand, and we suspect it contains concurrency bugs and/or lock contention +issues affecting performance that are subtle and difficult to pin down. + +Even without changing the semantics of any ABCI operations, this code could be +made smaller and easier to debug by separating the management of concurrency +and locking from the IPC transport: If all requests and responses are routed +through one connection, the server can explicitly maintain priority queues for +requests and responses, and make less-conservative decisions about when locks +are (or aren't) required to synchronize state access. With independent queues, +the server must lock conservatively, and no optimistic scheduling is practical. + +This would be a tedious implementation change, but should be achievable without +breaking any of the existing interfaces. More importantly, it could potentially +address a lot of difficult concurrency and performance problems we currently +see anecdotally but have difficultly isolating because of how intertwined these +separate message streams are at runtime. + +TODO: Impact of ABCI++ for this topic? + +### Context: RPC Issues + +The RPC system serves several masters, and has a complex surface area. I +believe there are some improvements that can be exposed by separating some of +these concerns. + +The Tendermint light client currently uses the RPC service to look up blocks +and transactions, and to forward ABCI queries to the application. The light +client proxy uses the RPC service via a websocket. The Cosmos IBC relayer also +uses the RPC service via websocket to watch for transaction events, and uses +the `ABCIQuery` method to fetch information and proofs for posted transactions. + +Some work is already underway toward using P2P message passing rather than RPC +to synchronize light client state with the rest of the network. IBC relaying, +however, requires access to the event system, which is currently not accessible +except via the RPC interface. Event subscription _could_ be exposed via P2P, +but that is a larger project since it adds P2P communication load, and might +thus have an impact on the performance of consensus. + +If event subscription can be moved into the P2P network, we could entirely +remove the websocket transport, even for clients that still need access to the +RPC service. Until then, we may still be able to reduce the scope of the +websocket endpoint to _only_ event subscription, by moving uses of the RPC +server as a proxy to ABCI over to the gRPC interface. + +Having the RPC server still makes sense for local bootstrapping and operations, +but can be further simplified. Here are some specific proposals: + +- Remove the HTTP GET interface entirely. + +- Simplify JSON-RPC plumbing to remove unnecessary reflection and wrapping. + +- Remove the gRPC interface (this is already planned for v0.36). + +- Separate the websocket interface from the rest of the RPC service, and + restrict it to only event subscription. + + Eventually we should try to emove the websocket interface entirely, but we + will need to revisit that (probably in a new RFC) once we've done some of the + easier things. + +These changes would preserve the ability of operators to issue queries with +curl (but would require using JSON-RPC instead of URI parameters). That would +be a little less user-friendly, but for a use case that should not be that +prevalent. + +These changes would also preserve compatibility with existing JSON-RPC based +code paths like the `tendermint` CLI and the light client (even ahead of +further work to remove that dependency). + +**Design goal:** An operator should be able to disable non-local access to the +RPC server on any node in the network without impairing the ability of the +network to function for service of state replication, including light clients. + +**Design principle:** All communication required to implement and monitor the +consensus network should use P2P, including the various synchronizations. + +### Options for ABCI Transport + +The majority of current usage is in Go, and the majority of that is mediated by +the Cosmos SDK, which uses the "direct call" interface. There is probably some +opportunity to clean up the implementation of that code, notably by inverting +which interface is at the "top" of the abstraction stack (currently it acts +like an RPC interface, and escape-hatches into the direct call). However, this +general approach works fine and doesn't need to be fundamentally changed. + +For applications _not_ written in Go, the two remaining options are the +"socket" protocol (another variation on varint-prefixed protobuf messages over +an unstructured stream) and gRPC. It would be nice if we could get rid of one +of these to reduce (unneeded?) optionality. + +Since both the socket protocol and gRPC depend on protocol buffers, the +"socket" protocol is the most obvious choice to remove. While gRPC is more +complex, the set of languages that _have_ protobuf support but _lack_ gRPC +support is small. Moreover, gRPC is already widely used in the rest of the +ecosystem (including the Cosmos SDK). + +If some use case did arise later that can't work with gRPC, it would not be too +difficult for that application author to write a little proxy (in Go) that +bridges the convenient SDK APIs into a simpler protocol than gRPC. + +**Design principle:** It is better for an uncommon special case to carry the +burdens of its specialness, than to bake an escape hatch into the infrastructure. + +**Recommendation:** We should deprecate and remove the socket protocol. + +### Options for RPC Transport + +[ADR 057][adr-57] proposes using gRPC for the Tendermint RPC implementation. +This is still possible, but if we are able to simplify and decouple the +concerns as described above, I do not think it should be necessary. + +While JSON-RPC is not the best possible RPC protocol for all situations, it has +some advantages over gRPC for our domain. Specifically: + +- It is easy to call JSON-RPC manually from the command-line, which helps with + a common concern for the RPC service, local debugging and operations. + + Relatedly: JSON is relatively easy for humans to read and write, and it can + be easily copied and pasted to share sample queries and debugging results in + chat, issue comments, and so on. Ideally, the RPC service will not be used + for activities where the costs of a text protocol are important compared to + its legibility and manual usability benefits. + +- gRPC has an enormous dependency footprint for both clients and servers, and + many of the features it provides to support security and performance + (encryption, compression, streaming, etc.) are mostly irrelevant to local + use. Tendermint already needs to include a gRPC client for the remote signer, + but if we can avoid the need for a _client_ to depend on gRPC, that is a win + for usability. + +- If we intend to migrate light clients off RPC to use P2P entirely, there is + no advantage to forcing a temporary migration to gRPC along the way; and once + the light client is not dependent on the RPC service, the efficiency of the + protocol is much less important. + +- We can still get the benefits of generated data types using protocol buffers, even + without using gRPC: + + - Protobuf defines a standard JSON encoding for all message types so + languages with protobuf support do not need to worry about type mapping + oddities. + + - Using JSON means that even languages _without_ good protobuf support can + implement the protocol with a bit more work, and I expect this situation to + be rare. + +Even if a language lacks a good standard JSON-RPC mechanism, the protocol is +lightweight and can be implemented by simple send/receive over TCP or +Unix-domain sockets with no need for code generation, encryption, etc. gRPC +uses a complex HTTP/2 based transport that is not easily replicated. + +### Future Work + +The background and proposals sketched above focus on the existing structure of +Tendermint and improvements we can make in the short term. It is worthwhile to +also consider options for longer-term broader changes to the IPC ecosystem. +The following outlines some ideas at a high level: + +- **Consensus service:** Today, the application and the consensus node are + nominally connected only via ABCI. Tendermint was originally designed with + the assumption that all communication with the application should be mediated + by the consensus node. Based on further experience, however, the design goal + is now that the _application_ should be the mediator of application state. + + As noted above, however, ABCI is a client/server protocol, with the + application as the server. For outside clients that turns out to have been a + good choice, but it complicates the relationship between the application and + the consensus node: Previously transactions were entered via the node, now + they are entered via the app. + + We have worked around this by using the Tendermint RPC service to give the + application a "back channel" to the consensus node, so that it can push + transactions back into the consensus network. But the RPC service exposes a + lot of other functionality, too, including event subscription, block and + transaction queries, and a lot of node status information. + + Even if we can't easily "fix" the orientation of the ABCI relationship, we + could improve isolation by splitting out the parts of the RPC service that + the application needs as a back-channel, and sharing those _only_ with the + application. By defining a "consensus service", we could give the application + a way to talk back limited to only the capabilities it needs. This approach + has the benefit that we could do it without breaking existing use, and if we + later did "fix" the ABCI directionality, we could drop the special case + without disrupting the rest of the RPC interface. + +- **Event service:** Right now, the IBC relayer relies on the Tendermint RPC + service to provide a stream of block and transaction events, which it uses to + discover which transactions need relaying to other chains. While I think + that event subscription should eventually be handled via P2P, we could gain + some immediate benefit by splitting out event subscription from the rest of + the RPC service. + + In this model, an event subscription service would be exposed on the public + network, but on a different endpoint. This would remove the need for the RPC + service to support the websocket protocol, and would allow operators to + isolate potentially sensitive status query results from the public network. + + At the moment the relayers also use the RPC service to get block data for + synchronization, but work is already in progress to handle that concern via + the P2P layer. Once that's done, event subscription could be separated. + +Separating parts of the existing RPC service is not without cost: It might +require additional connection endpoints, for example, though it is also not too +difficult for multiple otherwise-independent services to share a connection. + +In return, though, it would become easier to reduce transport options and for +operators to independently control access to sensitive data. Considering the +viability and implications of these ideas is beyond the scope of this RFC, but +they are documented here since they follow from the background we have already +discussed. + +## References + +[abci]: https://github.com/tendermint/tendermint/tree/main/spec/abci +[rpc-service]: https://docs.tendermint.com/v0.34/rpc/ +[light-client]: https://docs.tendermint.com/v0.34/tendermint-core/light-client.html +[tm-cli]: https://github.com/tendermint/tendermint/tree/main/cmd/tendermint +[cosmos-sdk]: https://github.com/cosmos/cosmos-sdk/ +[local-client]: https://github.com/tendermint/tendermint/blob/main/abci/client/local_client.go +[socket-server]: https://github.com/tendermint/tendermint/blob/main/abci/server/socket_server.go +[sdk-grpc]: https://pkg.go.dev/github.com/cosmos/cosmos-sdk/types/tx#ServiceServer +[json-rpc]: https://www.jsonrpc.org/specification +[abci-conn]: https://github.com/tendermint/tendermint/blob/main/spec/abci/abci++_basic_concepts.md +[adr-57]: https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-057-RPC.md diff --git a/docs/rfc/tendermint-core/rfc-003-performance-questions.md b/docs/rfc/tendermint-core/rfc-003-performance-questions.md new file mode 100644 index 0000000..62d68b3 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-003-performance-questions.md @@ -0,0 +1,284 @@ +# RFC 003: Taxonomy of potential performance issues in Tendermint + +## Changelog + +- 2021-09-02: Created initial draft (@wbanfield) +- 2021-09-14: Add discussion of the event system (@wbanfield) + +## Abstract + +This document discusses the various sources of performance issues in Tendermint and +attempts to clarify what work may be required to understand and address them. + +## Background + +Performance, loosely defined as the ability of a software process to perform its work +quickly and efficiently under load and within reasonable resource limits, is a frequent +topic of discussion in the Tendermint project. +To effectively address any issues with Tendermint performance we need to +categorize the various issues, understand their potential sources, and gauge their +impact on users. + +Categorizing the different known performance issues will allow us to discuss and fix them +more systematically. This document proposes a rough taxonomy of performance issues +and highlights areas where more research into potential performance problems is required. + +Understanding Tendermint's performance limitations will also be critically important +as we make changes to many of its subsystems. Performance is a central concern for +upcoming decisions regarding the `p2p` protocol, RPC message encoding and structure, +database usage and selection, and consensus protocol updates. + + +## Discussion + +This section attempts to delineate the different sections of Tendermint functionality +that are often cited as having performance issues. It raises questions and suggests +lines of inquiry that may be valuable for better understanding Tendermint's performance issues. + +As a note: We should avoid quickly adding many microbenchmarks or package level benchmarks. +These are prone to being worse than useless as they can obscure what _should_ be +focused on: performance of the system from the perspective of a user. We should, +instead, tune performance with an eye towards user needs and actions users make. These users comprise +both operators of Tendermint chains and the people generating transactions for +Tendermint chains. Both of these sets of users are largely aligned in wanting an end-to-end +system that operates quickly and efficiently. + +REQUEST: The list below may be incomplete, if there are additional sections that are often +cited as creating poor performance, please comment so that they may be included. + +### P2P + +#### Claim: Tendermint cannot scale to large numbers of nodes + +A complaint has been reported that Tendermint networks cannot scale to large numbers of nodes. +The listed number of nodes a user reported as causing issue was in the thousands. +We don't currently have evidence about what the upper-limit of nodes that Tendermint's +P2P stack can scale to. + +We need to more concretely understand the source of issues and determine what layer +is causing a problem. It's possible that the P2P layer, in the absence of any reactors +sending data, is perfectly capable of managing thousands of peer connections. For +a reasonable networking and application setup, thousands of connections should not present any +issue for the application. + +We need more data to understand the problem directly. We want to drive the popularity +and adoption of Tendermint and this will mean allowing for chains with more validators. +We should follow up with users experiencing this issue. We may then want to add +a series of metrics to the P2P layer to better understand the inefficiencies it produces. + +The following metrics can help us understand the sources of latency in the Tendermint P2P stack: + +- Number of messages sent and received per second +- Time of a message spent on the P2P layer send and receive queues + +The following metrics exist and should be leveraged in addition to those added: + +- Number of peers node's connected to +- Number of bytes per channel sent and received from each peer + +### Sync + +#### Claim: Block Syncing is slow + +Bootstrapping a new node in a network to the height of the rest of the network is believed to +take longer than users would like. Block sync requires fetching all of the blocks from +peers and placing them into the local disk for storage. A useful line of inquiry +is understanding how quickly a perfectly tuned system _could_ fetch all of the state +over a network so that we understand how much overhead Tendermint actually adds. + +The operation is likely to be _incredibly_ dependent on the environment in which +the node is being run. The factors that will influence syncing include: + +1. Number of peers that a syncing node may fetch from. +2. Speed of the disk that a validator is writing to. +3. Speed of the network connection between the different peers that node is +syncing from. + +We should calculate how quickly this operation _could possibly_ complete for common chains and nodes. +To calculate how quickly this operation could possibly complete, we should assume that +a node is reading at line-rate of the NIC and writing at the full drive speed to its +local storage. Comparing this theoretical upper-limit to the actual sync times +observed by node operators will give us a good point of comparison for understanding +how much overhead Tendermint incurs. + +We should additionally add metrics to the blocksync operation to more clearly pinpoint +slow operations. The following metrics should be added to the block syncing operation: + +- Time to fetch and validate each block +- Time to execute a block +- Blocks sync'd per unit time + +### Application + +Applications performing complex state transitions have the potential to bottleneck +the Tendermint node. + +#### Claim: ABCI block delivery could cause slowdown + +ABCI delivers blocks in several methods: `BeginBlock`, `DeliverTx`, `EndBlock`, `Commit`. + +Tendermint delivers transactions one-by-one via the `DeliverTx` call. Most of the +transaction delivery in Tendermint occurs asynchronously and therefore appears unlikely to +form a bottleneck in ABCI. + +After delivering all transactions, Tendermint then calls the `Commit` ABCI method. +Tendermint [locks all access to the mempool][abci-commit-description] while `Commit` +proceeds. This means that an application that is slow to execute all of its +transactions or finalize state during the `Commit` method will prevent any new +transactions from being added to the mempool. Apps that are slow to commit will +prevent consensus from proceeded to the next consensus height since Tendermint +cannot validate block proposals or produce block proposals without the +AppHash obtained from the `Commit` method. We should add a metric for each +step in the ABCI protocol to track the amount of time that a node spends communicating +with the application at each step. + +#### Claim: ABCI serialization overhead causes slowdown + +The most common way to run a Tendermint application is using the Cosmos-SDK. +The Cosmos-SDK runs the ABCI application within the same process as Tendermint. +When an application is run in the same process as Tendermint, a serialization penalty +is not paid. This is because the local ABCI client does not serialize method calls +and instead passes the protobuf type through directly. This can be seen +in [local_client.go][abci-local-client-code]. + +Serialization and deserialization in the gRPC and socket protocol ABCI methods +may cause slowdown. While these may cause issue, they are not part of the primary +usecase of Tendermint and do not necessarily need to be addressed at this time. + +### RPC + +#### Claim: The Query API is slow + +The query API locks a mutex across the ABCI connections. This causes consensus to +slow during queries, as ABCI is no longer able to make progress. This is known +to be causing issue in the cosmos-sdk and is being addressed [in the sdk][sdk-query-fix] +but a more robust solution may be required. Adding metrics to each ABCI client connection +and message as described in the Application section of this document would allow us +to further introspect the issue here. + +#### Claim: RPC Serialization may cause slowdown + +The Tendermint RPC uses a modified version of JSON-RPC. This RPC powers the `broadcast_tx_*` methods, +which is a critical method for adding transactions to Tendermint at the moment. This method is +likely invoked quite frequently on popular networks. Being able to perform efficiently +on this common and critical operation is very important. The current JSON-RPC implementation +relies heavily on type introspection via reflection, which is known to be very slow in +Go. We should therefore produce benchmarks of this method to determine how much overhead +we are adding to what, is likely to be, a very common operation. + +The other JSON-RPC methods are much less critical to the core functionality of Tendermint. +While there may other points of performance consideration within the RPC, methods that do not +receive high volumes of requests should not be prioritized for performance consideration. + +NOTE: Previous discussion of the RPC framework was done in [ADR 57][adr-57] and +there is ongoing work to inspect and alter the JSON-RPC framework in [RFC 002][rfc-002]. +Much of these RPC-related performance considerations can either wait until the work of RFC 002 work is done or be +considered concordantly with the in-flight changes to the JSON-RPC. + +### Protocol + +#### Claim: Gossiping messages is a slow process + +Currently, for any validator to successfully vote in a consensus _step_, it must +receive votes from greater than 2/3 of the validators on the network. In many cases, +it's preferable to receive as many votes as possible from correct validators. + +This produces a quadratic increase in messages that are communicated as more validators join the network. +(Each of the N validators must communicate with all other N-1 validators). + +This large number of messages communicated per step has been identified to impact +performance of the protocol. Given that the number of messages communicated has been +identified as a bottleneck, it would be extremely valuable to gather data on how long +it takes for popular chains with many validators to gather all votes within a step. + +Metrics that would improve visibility into this include: + +- Amount of time for a node to gather votes in a step. +- Amount of time for a node to gather all block parts. +- Number of votes each node sends to gossip (i.e. not its own votes, but votes it is +transmitting for a peer). +- Total number of votes each node sends to receives (A node may receive duplicate votes +so understanding how frequently this occurs will be valuable in evaluating the performance +of the gossip system). + +#### Claim: Hashing Txs causes slowdown in Tendermint + +Using a faster hash algorithm for Tx hashes is currently a point of discussion +in Tendermint. Namely, it is being considered as part of the [modular hashing proposal][modular-hashing]. +It is currently unknown if hashing transactions in the Mempool forms a significant bottleneck. +Although it does not appear to be documented as slow, there are a few open github +issues that indicate a possible user preference for a faster hashing algorithm, +including [issue 2187][issue-2187] and [issue 2186][issue-2186]. + +It is likely worth investigating what order of magnitude Tx hashing takes in comparison to other +aspects of adding a Tx to the mempool. It is not currently clear if the rate of adding Tx +to the mempool is a source of user pain. We should not endeavor to make large changes to +consensus critical components without first being certain that the change is highly +valuable and impactful. + +### Digital Signatures + +#### Claim: Verification of digital signatures may cause slowdown in Tendermint + +Working with cryptographic signatures can be computationally expensive. The cosmos +hub uses [ed25519 signatures][hub-signature]. The library performing signature +verification in Tendermint on votes is [benchmarked][ed25519-bench] to be able to perform an `ed25519` +signature in 75μs on a decently fast CPU. A validator in the Cosmos Hub performs +3 sets of verifications on the signatures of the 140 validators in the Hub +in a consensus round, during block verification, when verifying the prevotes, and +when verifying the precommits. With no batching, this would be roughly `3ms` per +round. It is quite unlikely, therefore, that this accounts for any serious amount +of the ~7 seconds of block time per height in the Hub. + +This may cause slowdown when syncing, since the process needs to constantly verify +signatures. It's possible that improved signature aggregation will lead to improved +light client or other syncing performance. In general, a metric should be added +to track block rate while blocksyncing. + +#### Claim: Our use of digital signatures in the consensus protocol contributes to performance issue + +Currently, Tendermint's digital signature verification requires that all validators +receive all vote messages. Each validator must receive the complete digital signature +along with the vote message that it corresponds to. This means that all N validators +must receive messages from at least 2/3 of the N validators in each consensus +round. Given the potential for oddly shaped network topologies and the expected +variable network roundtrip times of a few hundred milliseconds in a blockchain, +it is highly likely that this amount of gossiping is leading to a significant amount +of the slowdown in the Cosmos Hub and in Tendermint consensus. + +### Tendermint Event System + +#### Claim: The event system is a bottleneck in Tendermint + +The Tendermint Event system is used to communicate and store information about +internal Tendermint execution. The system uses channels internally to send messages +to different subscribers. Sending an event [blocks on the internal channel][event-send]. +The default configuration is to [use an unbuffered channel for event publishes][event-buffer-capacity]. +Several consumers of the event system also use an unbuffered channel for reads. +An example of this is the [event indexer][event-indexer-unbuffered], which takes an +unbuffered subscription to the event system. The result is that these unbuffered readers +can cause writes to the event system to block or slow down depending on contention in the +event system. This has implications for the consensus system, which [publishes events][consensus-event-send]. +To better understand the performance of the event system, we should add metrics to track the timing of +event sends. The following metrics would be a good start for tracking this performance: + +- Time in event send, labeled by Event Type +- Time in event receive, labeled by subscriber +- Event throughput, measured in events per unit time. + +### References + +[modular-hashing]: https://github.com/tendermint/tendermint/pull/6773 +[issue-2186]: https://github.com/tendermint/tendermint/issues/2186 +[issue-2187]: https://github.com/tendermint/tendermint/issues/2187 +[rfc-002]: https://github.com/tendermint/tendermint/pull/6913 +[adr-57]: https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-057-RPC.md +[abci-commit-description]: https://github.com/tendermint/tendermint/blob/main/spec/abci/abci++_methods.md#commit +[abci-local-client-code]: https://github.com/tendermint/tendermint/blob/511bd3eb7f037855a793a27ff4c53c12f085b570/abci/client/local_client.go#L84 +[hub-signature]: https://github.com/cosmos/gaia/blob/0ecb6ed8a244d835807f1ced49217d54a9ca2070/docs/resources/genesis.md#consensus-parameters +[ed25519-bench]: https://github.com/oasisprotocol/curve25519-voi/blob/d2e7fc59fe38c18ca990c84c4186cba2cc45b1f9/PERFORMANCE.md +[event-send]: https://github.com/tendermint/tendermint/blob/5bd3b286a2b715737f6d6c33051b69061d38f8ef/libs/pubsub/pubsub.go#L338 +[event-buffer-capacity]: https://github.com/tendermint/tendermint/blob/5bd3b286a2b715737f6d6c33051b69061d38f8ef/types/event_bus.go#L14 +[event-indexer-unbuffered]: https://github.com/tendermint/tendermint/blob/5bd3b286a2b715737f6d6c33051b69061d38f8ef/state/indexer/indexer_service.go#L39 +[consensus-event-send]: https://github.com/tendermint/tendermint/blob/5bd3b286a2b715737f6d6c33051b69061d38f8ef/internal/consensus/state.go#L1573 +[sdk-query-fix]: https://github.com/cosmos/cosmos-sdk/pull/10045 diff --git a/docs/rfc/tendermint-core/rfc-004-e2e-framework.rst b/docs/rfc/tendermint-core/rfc-004-e2e-framework.rst new file mode 100644 index 0000000..62ca34a --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-004-e2e-framework.rst @@ -0,0 +1,213 @@ +======================================== +RFC 004: E2E Test Framework Enhancements +======================================== + +Changelog +--------- + +- 2021-09-14: started initial draft (@tychoish) + +Abstract +-------- + +This document discusses a series of improvements to the e2e test framework +that we can consider during the next few releases to help boost confidence in +Tendermint releases, and improve developer efficiency. + +Background +---------- + +During the 0.35 release cycle, the E2E tests were a source of great +value, helping to identify a number of bugs before release. At the same time, +the tests were not consistently passing during this time, thereby reducing +their value, and forcing the core development team to allocate time and energy +to maintaining and chasing down issues with the e2e tests and the test +harness. The experience of this release cycle calls to mind a series of +improvements to the test framework, and this document attempts to capture +these improvements, along with motivations, and potential for impact. + +Projects +-------- + +Flexible Workload Generation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Presently the e2e suite contains a single workload generation pattern, which +exists simply to ensure that the test networks have some work during their +runs. However, the shape and volume of the work is very consistent and is very +gentle to help ensure test reliability. + +We don't need a complex workload generation framework, but being able to have +a few different workload shapes available for test networks, both generated and +hand-crafted, would be useful. + +Workload patterns/configurations might include: + +- transaction targeting patterns (include light nodes, round robin, target + individual nodes) + +- variable transaction size over time. + +- transaction broadcast option (synchronously, checked, fire-and-forget, + mixed). + +- number of transactions to submit. + +- non-transaction workloads: (evidence submission, query, event subscription.) + +Configurable Generator +~~~~~~~~~~~~~~~~~~~~~~ + +The nightly e2e suite is defined by the `testnet generator +`_, +and it's difficult to add dimensions or change the focus of the test suite in +any way without modifying the implementation of the generator. If the +generator were more configurable, potentially via a file rather than in +the Go implementation, we could modify the focus of the test suite on the +fly. + +Features that we might want to configure: + +- number of test networks to generate of various topologies, to improve + coverage of different configurations. + +- test application configurations (to modify the latency of ABCI calls, etc.) + +- size of test networks. + +- workload shape and behavior. + +- initial sync and catch-up configurations. + +The workload generator currently provides runtime options for limiting the +generator to specific types of P2P stacks, and for generating multiple groups +of test cases to support parallelism. The goal is to extend this pattern and +avoid hardcoding the matrix of test cases in the generator code. Once the +testnet configuration generation behavior is configurable at runtime, +developers may be able to use the e2e framework to validate changes before +landing changes that break e2e tests a day later. + +In addition to the autogenerated suite, it might make sense to maintain a +small collection of hand-crafted cases that exercise configurations of +concern, to run as part of the nightly (or less frequent) loop. + +Implementation Plan Structure +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As a development team, we should determine the features should impact the e2e +testing early in the development cycle, and if we intend to modify the e2e +tests to exercise a feature, we should identify this early and begin the +integration process as early as possible. + +To facilitate this, we should adopt a practice whereby we exercise specific +features that are currently under development more rigorously in the e2e +suite, and then as development stabilizes we can reduce the number or weight +of these features in the suite. + +As of 0.35 there are essentially two end to end tests: the suite of 64 +generated test networks, and the hand crafted `ci.toml` test case. The +generated test cases help provide systemtic coverage, while the `ci` run +provides coverage for a large number of features. + +Reduce Cycle Time +~~~~~~~~~~~~~~~~~ + +One of the barriers to leveraging the e2e framework, and one of the challenges +in debugging failures, is the cycle time of running a single test iteration is +quite high: 5 minutes to build the docker image, plus the time to run the test +or tests. + +There are a number of improvements and enhancements that can reduce the cycle +time in practice: + +- reduce the amount of time required to build the docker image used in these + tests. Without the dependency on CGo, the tendermint binaries could be + (cross) compiled outside of the docker container and then injected into + them, which would take better advantage of docker's native caching, + although, without the dependency on CGo there would be no hard requirement + for the e2e tests to use docker. + +- support test parallelism. Because of the way the testnets are orchestrated + a single system can really only run one network at a time. For executions + (local or remote) with more resources, there's no reason to run a few + networks in parallel to reduce the feedback time. + +- prune testnet configurations that are unlikely to provide good signal, to + shorten the time to feedback. + +- apply some kind of tiered approach to test execution, to improve the + legibility of the test result. For example order tests by the dependency of + their features, or run test networks without perturbations before running + that configuration with perturbations, to be able to isolate the impact of + specific features. + +- orchestrate the test harness directly from go test rather than via a special + harness and shell scripts so e2e tests may more naively fit into developers + existing workflows. + +Many of these improvements, particularly, reducing the build time will also +reduce the time to get feedback during automated builds. + +Deeper Insights +~~~~~~~~~~~~~~~ + +When a test network fails, it's incredibly difficult to understand _why_ the +network failed, as the current system provides very little insight into the +system outside of the process logs. When a test network stalls or fails +developers should be able to quickly and easily get a sense of the state of +the network and all nodes. + +Improvements in persuit of this goal, include functionality that would help +node operators in production environments by improving the quality and utility +of the logging messages and other reported metrics, but also provide some +tools to collect and aggregate this data for developers in the context of test +networks. + +- Interleave messages from all nodes in the network to be able to correlate + events during the test run. + +- Collect structured metrics of the system operation (CPU/MEM/IO) during the + test run, as well as from each tendermint/application process. + +- Build (simple) tools to be able to render and summarize the data collected + during the test run to answer basic questions about test outcome. + +Flexible Assertions +~~~~~~~~~~~~~~~~~~~ + +Currently, all assertions run for every test network, which makes the +assertions pretty bland, and the framework primarily useful as a smoke-test +framework, but it might be useful to be able to write and run different +tests for different configurations. This could allow us to test outside of the +happy-path. + +In general our existing assertions occupy a fraction of the total test time, +so the relative cost of adding a few extra test assertions would be of limited +cost, and could help build confidence. + +Additional Kinds of Testing +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The existing e2e suite, exercises networks of nodes that have homogeneous +tendermint version, stable configuration, that are expected to make +progress. There are many other possible test configurations that may be +interesting to engage with. These could include dimensions, such as: + +- Multi-version testing to exercise our compatibility guarantees for networks + that might have different tendermint versions. + +- As a flavor or mult-version testing, include upgrade testing, to build + confidence in migration code and procedures. + +- Additional test applications, particularly practical-type applciations + including some that use gaiad and/or the cosmos-sdk. Test-only applications + that simulate other kinds of applications (e.g. variable application + operation latency.) + +- Tests of "non-viable" configurations that ensure that forbidden combinations + lead to halts. + +References +---------- + +- `ADR 66: End-to-End Testing <../architecture/adr-066-e2e-testing.md>`_ diff --git a/docs/rfc/tendermint-core/rfc-005-event-system.rst b/docs/rfc/tendermint-core/rfc-005-event-system.rst new file mode 100644 index 0000000..3c6e145 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-005-event-system.rst @@ -0,0 +1,122 @@ +===================== +RFC 005: Event System +===================== + +Changelog +--------- + +- 2021-09-17: Initial Draft (@tychoish) + +Abstract +-------- + +The event system within Tendermint, which supports a lot of core +functionality, also represents a major infrastructural liability. As part of +our upcoming review of the RPC interfaces and our ongoing thoughts about +stability and performance, as well as the preparation for Tendermint 1.0, we +should revisit the design and implementation of the event system. This +document discusses both the current state of the system and potential +directions for future improvement. + +Background +---------- + +Current State of Events +~~~~~~~~~~~~~~~~~~~~~~~ + +The event system makes it possible for clients, both internal and external, +to receive notifications of state replication events, such as new blocks, +new transactions, validator set changes, as well as intermediate events during +consensus. Because the event system is very cross cutting, the behavior and +performance of the event publication and subscription system has huge impacts +for all of Tendermint. + +The subscription service is exposed over the RPC interface, but also powers +the indexing (e.g. to an external database,) and is the mechanism by which +`BroadcastTxCommit` is able to wait for transactions to land in a block. + +The current pubsub mechanism relies on a couple of buffered channels, +primarily between all event creators and subscribers, but also for each +subscription. The result of this design is that, in some situations with the +right collection of slow subscription consumers the event system can put +backpressure on the consensus state machine and message gossiping in the +network, thereby causing nodes to lag. + +Improvements +~~~~~~~~~~~~ + +The current system relies on implicit, bounded queues built by the buffered channels, +and though threadsafe, can force all activity within Tendermint to serialize, +which does not need to happen. Additionally, timeouts for subscription +consumers related to the implementation of the RPC layer, may complicate the +use of the system. + +References +~~~~~~~~~~ + +- Legacy Implementation + - `publication of events `_ + - `send operation `_ + - `send loop `_ +- Related RFCs + - `RFC 002: IPC Ecosystem <./rfc-002-ipc-ecosystem.md>`_ + - `RFC 003: Performance Questions <./rfc-003-performance-questions.md>`_ + +Discussion +---------- + +Changes to Published Events +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As part of this process, the Tendermint team should do a study of the existing +event types and ensure that there are viable production use cases for +subscriptions to all event types. Instinctively it seems plausible that some +of the events may not be useable outside of tendermint, (e.g. ``TimeoutWait`` +or ``NewRoundStep``) and it might make sense to remove them. Certainly, it +would be good to make sure that we don't maintain infrastructure for unused or +un-useful message indefinitely. + +Blocking Subscription +~~~~~~~~~~~~~~~~~~~~~ + +The blocking subscription mechanism makes it possible to have *send* +operations into the subscription channel be un-buffered (the event processing +channel is still buffered.) In the blocking case, events from one subscription +can block processing that event for other non-blocking subscriptions. The main +case, it seems for blocking subscriptions is ensuring that a transaction has +been committed to a block for ``BroadcastTxCommit``. Removing blocking +subscriptions entirely, and potentially finding another way to implement +``BroadcastTxCommit``, could lead to important simplifications and +improvements to throughput without requiring large changes. + +Subscription Identification +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before `#6386 `_, all +subscriptions were identified by the combination of a client ID and a query, +and with that change, it became possible to identify all subscription given +only an ID, but compatibility with the legacy identification means that there's a +good deal of legacy code as well as client side efficiency that could be +improved. + +Pubsub Changes +~~~~~~~~~~~~~~ + +The pubsub core should be implemented in a way that removes the possibility of +backpressure from the event system to impact the core system *or* for one +subscription to impact the behavior of another area of the +system. Additionally, because the current system is implemented entirely in +terms of a collection of buffered channels, the event system (and large +numbers of subscriptions) can be a source of memory pressure. + +These changes could include: + +- explicit cancellation and timeouts promulgated from callers (e.g. RPC end + points, etc,) this should be done using contexts. + +- subscription system should be able to spill to disk to avoid putting memory + pressure on the core behavior of the node (consensus, gossip). + +- subscriptions implemented as cursors rather than channels, with either + condition variables to simulate the existing "push" API or a client side + iterator API with some kind of long polling-type interface. diff --git a/docs/rfc/tendermint-core/rfc-006-event-subscription.md b/docs/rfc/tendermint-core/rfc-006-event-subscription.md new file mode 100644 index 0000000..e027a9d --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-006-event-subscription.md @@ -0,0 +1,204 @@ +# RFC 006: Event Subscription + +## Changelog + +- 30-Oct-2021: Initial draft (@creachadair) + +## Abstract + +The Tendermint consensus node allows clients to subscribe to its event stream +via methods on its RPC service. The ability to view the event stream is +valuable for clients, but the current implementation has some deficiencies that +make it difficult for some clients to use effectively. This RFC documents these +issues and discusses possible approaches to solving them. + + +## Background + +A running Tendermint consensus node exports a [JSON-RPC service][rpc-service] +that provides a [large set of methods][rpc-methods] for inspecting and +interacting with the node. One important cluster of these methods are the +`subscribe`, `unsubscribe`, and `unsubscribe_all` methods, which permit clients +to subscribe to a filtered stream of the [events generated by the node][events] +as it runs. + +Unlike the other methods of the service, the methods in the "event +subscription" cluster are not accessible via [ordinary HTTP GET or POST +requests][rpc-transport], but require upgrading the HTTP connection to a +[websocket][ws]. This is necessary because the `subscribe` request needs a +persistent channel to deliver results back to the client, and an ordinary HTTP +connection does not reliably persist across multiple requests. Since these +methods do not work properly without a persistent channel, they are _only_ +exported via a websocket connection, and are not routed for plain HTTP. + + +## Discussion + +There are some operational problems with the current implementation of event +subscription in the RPC service: + +- **Event delivery is not valid JSON-RPC.** When a client issues a `subscribe` + request, the server replies (correctly) with an initial empty acknowledgement + (`{}`). After that, each matching event is delivered "unsolicited" (without + another request from the client), as a separate [response object][json-response] + with the same ID as the initial request. + + This matters because it means a standard JSON-RPC client library can't + interact correctly with the event subscription mechanism. + + Even for clients that can handle unsolicited values pushed by the server, + these responses are invalid: They have an ID, so they cannot be treated as + [notifications][json-notify]; but the ID corresponds to a request that was + already completed. In practice, this means that general-purpose JSON-RPC + libraries cannot use this method correctly -- it requires a custom client. + + The Go RPC client from the Tendermint core can support this case, but clients + in other languages have no easy solution. + + This is the cause of issue [#2949][issue2949]. + +- **Subscriptions are terminated by disconnection.** When the connection to the + client is interrupted, the subscription is silently dropped. + + This is a reasonable behavior, but it matters because a client whose + subscription is dropped gets no useful error feedback, just a closed + connection. Should they try again? Is the node overloaded? Was the client + too slow? Did the caller forget to respond to pings? Debugging these kinds + of failures is unnecessarily painful. + + Websockets compound this, because websocket connections time out if no + traffic is seen for a while, and keeping them alive requires active + cooperation between the client and server. With a plain TCP socket, liveness + is handled transparently by the keepalive mechanism. On a websocket, + however, one side has to occasionally send a PING (if the connection is + otherwise idle). The other side must return a matching PONG in time, or the + connection is dropped. Apart from being tedious, this is highly susceptible + to CPU load. + + The Tendermint Go implementation automatically sends and responds to pings. + Clients in other languages (or not wanting to use the Tendermint libraries) + need to handle it explicitly. This burdens the client for no practical + benefit: A subscriber has no information about when matching events may be + available, so it shouldn't have to participate in keeping the connection + alive. + +- **Mismatched load profiles.** Most of the RPC service is mainly important for + low-volume local use, either by the application the node serves (e.g., the + ABCI methods) or by the node operator (e.g., the info methods). Event + subscription is important for remote clients, and may represent a much higher + volume of traffic. + + This matters because both are using the same JSON-RPC mechanism. For + low-volume local use, the ergonomics of JSON-RPC are a good fit: It's easy to + issue queries from the command line (e.g., using `curl`) or to write scripts + that call the RPC methods to monitor the running node. + + For high-volume remote use, JSON-RPC is not such a good fit: Even leaving + aside the non-standard delivery protocol mentioned above, the time and memory + cost of encoding event data matters for the stability of the node when there + can be potentially hundreds of subscribers. Moreover, a subscription is + long-lived compared to most RPC methods, in that it may persist as long the + node is active. + +- **Mismatched security profiles.** The RPC service exports several methods + that should not be open to arbitrary remote callers, both for correctness + reasons (e.g., `remove_tx` and `broadcast_tx_*`) and for operational + stability reasons (e.g., `tx_search`). A node may still need to expose + events, however, to support UI tools. + + This matters, because all the methods share the same network endpoint. While + it is possible to block the top-level GET and POST handlers with a proxy, + exposing the `/websocket` handler exposes not _only_ the event subscription + methods, but the rest of the service as well. + +### Possible Improvements + +There are several things we could do to improve the experience of developers +who need to subscribe to events from the consensus node. These are not all +mutually exclusive. + +1. **Split event subscription into a separate service**. Instead of exposing + event subscription on the same endpoint as the rest of the RPC service, + dedicate a separate endpoint on the node for _only_ event subscription. The + rest of the RPC services (_sans_ events) would remain as-is. + + This would make it easy to disable or firewall outside access to sensitive + RPC methods, without blocking access to event subscription (and vice versa). + This is probably worth doing, even if we don't take any of the other steps + described here. + +2. **Use a different protocol for event subscription.** There are various ways + we could approach this, depending how much we're willing to shake up the + current API. Here are sketches of a few options: + + - Keep the websocket, but rework the API to be more JSON-RPC compliant, + perhaps by converting event delivery into notifications. This is less + up-front change for existing clients, but retains all of the existing + implementation complexity, and doesn't contribute much toward more serious + performance and UX improvements later. + + - Switch from websocket to plain HTTP, and rework the subscription API to + use a more conventional request/response pattern instead of streaming. + This is a little more up-front work for existing clients, but leverages + better library support for clients not written in Go. + + The protocol would become more chatty, but we could mitigate that with + batching, and in return we would get more control over what to do about + slow clients: Instead of simply silently dropping them, as we do now, we + could drop messages and signal the client that they missed some data ("M + dropped messages since your last poll"). + + This option is probably the best balance between work, API change, and + benefit, and has a nice incidental effect that it would be easier to debug + subscriptions from the command-line, like the other RPC methods. + + - Switch to gRPC: Preserves a persistent connection and gives us a more + efficient binary wire format (protobuf), at the cost of much more work for + clients and harder debugging. This may be the best option if performance + and server load are our top concerns. + + Given that we are currently using JSON-RPC, however, I'm not convinced the + costs of encoding and sending messages on the event subscription channel + are the limiting factor on subscription efficiency, however. + +3. **Delegate event subscriptions to a proxy.** Give responsibility for + managing event subscription to a proxy that runs separately from the node, + and switch the node to push events to the proxy (like a webhook) instead of + serving subscribers directly. This is more work for the operator (another + process to configure and run) but may scale better for big networks. + + I mention this option for completeness, but making this change would be a + fairly substantial project. If we want to consider shifting responsibility + for event subscription outside the node anyway, we should probably be more + systematic about it. For a more principled approach, see point (4) below. + +4. **Move event subscription downstream of indexing.** We are already planning + to give applications more control over event indexing. By extension, we + might allow the application to also control how events are filtered, + queried, and subscribed. Having the application control these concerns, + rather than the node, might make life easier for developers building UI and + tools for that application. + + This is a much larger change, so I don't think it is likely to be practical + in the near-term, but it's worth considering as a broader option. Some of + the existing code for filtering and selection could be made more reusable, + so applications would not need to reinvent everything. + + +## References + +- [Tendermint RPC service][rpc-service] +- [Tendermint RPC routes][rpc-methods] +- [Discussion of the event system][events] +- [Discussion about RPC transport options][rpc-transport] (from RFC 002) +- [RFC 6455: The websocket protocol][ws] +- [JSON-RPC 2.0 Specification](https://www.jsonrpc.org/specification) + +[rpc-service]: https://docs.tendermint.com/v0.34/rpc/ +[rpc-methods]: https://github.com/tendermint/tendermint/blob/main/rpc/core/routes.go#L12 +[events]: ./rfc-005-event-system.rst +[rpc-transport]: ./rfc-002-ipc-ecosystem.md#rpc-transport +[ws]: https://datatracker.ietf.org/doc/html/rfc6455 +[json-response]: https://www.jsonrpc.org/specification#response_object +[json-notify]: https://www.jsonrpc.org/specification#notification +[issue2949]: https://github.com/tendermint/tendermint/issues/2949 diff --git a/docs/rfc/tendermint-core/rfc-007-deterministic-proto-bytes.md b/docs/rfc/tendermint-core/rfc-007-deterministic-proto-bytes.md new file mode 100644 index 0000000..acb1cf9 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-007-deterministic-proto-bytes.md @@ -0,0 +1,138 @@ +# RFC 007 : Deterministic Proto Byte Serialization + +## Changelog + +- 09-Dec-2021: Initial draft (@williambanfield). + +## Abstract + +This document discusses the issue of stable byte-representation of serialized messages +within Tendermint and describes a few possible routes that could be taken to address it. + +## Background + +We use the byte representations of wire-format proto messages to produce +and verify hashes of data within the Tendermint codebase as well as for +producing and verifying cryptographic signatures over these signed bytes. + +The protocol buffer [encoding spec][proto-spec-encoding] does not guarantee that the byte representation +of a protocol buffer message will be the same between two calls to an encoder. +While there is a mode to force the encoder to produce the same byte representation +of messages within a single binary, these guarantees are not good enough for our +use case in Tendermint. We require multiple different versions of a binary running +Tendermint to be able to inter-operate. Additionally, we require that multiple different +systems written in _different languages_ be able to participate in different aspects +of the protocols of Tendermint and be able to verify the integrity of the messages +they each produce. + +While this has not yet created a problem that we know of in a running network, we should +make sure to provide stronger guarantees around the serialized representation of the messages +used within the Tendermint consensus algorithm to prevent any issue from occurring. + + +## Discussion + +Proto has the following points of variability that can produce non-deterministic byte representation: + +1. Encoding order of fields within a message. + +Proto allows fields to be encoded in any order and even be repeated. + +2. Encoding order of elements of a repeated field. + +`repeated` fields in a proto message can be serialized in any order. + +3. Presence or absence of default values. + +Types in proto have defined default values similar to Go's zero values. +Writing or omitting a default value are both legal ways of encoding a wire message. + +4. Serialization of 'unknown' fields. + +Unknown fields can be present when a message is created by a binary with a newer +version of the proto that contains fields that the deserializer in a different +binary does not yet know about. Deserializers in binaries that do not know about the field +will maintain the bytes of the unknown field but not place them into the deserialized structure. + +We have a few options to consider when producing this stable representation. + +### Options for deterministic byte representation + +#### Use only compliant serializers and constrain field usage + +According to [Cosmos-SDK ADR-27][cosmos-sdk-adr-27], when message types obey a simple +set of rules, gogoproto produces a consistent byte representation of serialized messages. +This seems promising, although more research is needed to guarantee gogoproto always +produces a consistent set of bytes on serialized messages. This would solve the problem +within Tendermint as written in Go, but would require ensuring that there are similar +serializers written in other languages that produce the same output as gogoproto. + +#### Reorder serialized bytes to ensure determinism + +The serialized form of a proto message can be transformed into a canonical representation +by applying simple rules to the serialized bytes. Re-ordering the serialized bytes +would allow Tendermint to produce a canonical byte representation without having to +simultaneously maintain a custom proto marshaller. + +This could be implemented as a function in many languages that performed the following +producing bytes to sign or hashing: + +1. Does not add any of the data from unknown fields into the type to hash. + +Tendermint should not run into a case where it needs to verify the integrity of +data with unknown fields for the following reasons: + +The purpose of checking hash equality within Tendermint is to ensure that +its local copy of data matches the data that the network agreed on. There should +therefore not be a case where a process is checking hash equality using data that it did not expect +to receive. What the data represent may be opaque to the process, such as when checking the +transactions in a block, _but the process will still have expected to receive this data_, +despite not understanding what their internal structure is. It's not clear what it would +mean to verify that a block contains data that a process does not know about. + +The same reasoning applies for signature verification within Tendermint. Processes +verify that a digital signature signed over a set of bytes by locally reconstructing the +data structure that the digital signature signed using the process's local data. + +2. Reordered all message fields to be in tag-sorted order. + +Tag-sorting top-level fields will place all fields of the same tag in a adjacent +to eachother within the serialized representation. + +3. Reordered the contents of all `repeated` fields to be in lexicographically sorted order. + +`repeated` fields will appear in a message as having the same tag but will contain different +contents. Therefore, lexicographical sorting will produce a stable ordering of +fields with the same tag. + +4. Deleted all default values from the byte representation. + +Encoders can include default values or omit them. Most encoders appear to omit them +but we may wish to delete them just to be safe. + +5. Recursively performed these operations on any length-delimited subfields. + +Length delimited fields may contain messages, strings, or just bytes. However, +it's not possible to know what data is being represented by such a field. +A 'string' may happen to have the same structure as an embedded message and we cannot +disambiguate. For this reason, we must apply these same rules to all subfields that +may contain messages. Because we cannot know if we have totally mangled the interior 'string' +or not, this data should never be deserialized or used for anything beyond hashing. + +A **prototype** implementation by @creachadair of this can be found in [the wirepb repo][wire-pb]. +This could be implemented in multiple languages more simply than ensuring that there are +canonical proto serializers that match in each language. + +### Future work + +We should add clear documentation to the Tendermint codebase every time we +compare hashes of proto messages or use proto serialized bytes to produces a +digital signatures that we have been careful to ensure that the hashes are performed +properly. + +### References + +[proto-spec-encoding]: https://developers.google.com/protocol-buffers/docs/encoding +[cosmos-sdk-adr-27]: https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-027-deterministic-protobuf-serialization.md +[wire-pb]: https://github.com/creachadair/wirepb + diff --git a/docs/rfc/tendermint-core/rfc-008-do-not-panic.md b/docs/rfc/tendermint-core/rfc-008-do-not-panic.md new file mode 100644 index 0000000..f340883 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-008-do-not-panic.md @@ -0,0 +1,139 @@ +# RFC 008: Don't Panic + +## Changelog + +- 2021-12-17: initial draft (@tychoish) + +## Abstract + +Today, the Tendermint core codebase has panics in a number of cases as +a response to exceptional situations. These panics complicate testing, +and might make tendermint components difficult to use as a library in +some circumstances. This document outlines a project of converting +panics to errors and describes the situations where its safe to +panic. + +## Background + +Panics in Go are a great mechanism for aborting the current execution +for truly exceptional situations (e.g. memory errors, data corruption, +processes initialization); however, because they resemble exceptions +in other languages, it can be easy to over use them in the +implementation of software architectures. This certainly happened in +the history of Tendermint, and as we embark on the project of +stabilizing the package, we find ourselves in the right moment to +reexamine our use of panics, and largely where panics happen in the +code base. + +There are still some situations where panics are acceptable and +desireable, but it's important that Tendermint, as a project, comes to +consensus--perhaps in the text of this document--on the situations +where it is acceptable to panic. + +### References + +- [Defer Panic and Recover](https://go.dev/blog/defer-panic-and-recover) +- [Why Go gets exceptions right](https://dave.cheney.net/tag/panic) +- [Don't panic](https://dave.cheney.net/practical-go/presentations/gophercon-singapore-2019.html#_dont_panic) + +## Discussion + +### Acceptable Panics + +#### Initialization + +It is unambiguously safe (and desireable) to panic in `init()` +functions in response to any kind of error. These errors are caught by +tests, and occur early enough in process initialization that they +won't cause unexpected runtime crashes. + +Other code that is called early in process initialization MAY panic, +in some situations if it's not possible to return an error or cause +the process to abort early, although these situations should be +vanishingly slim. + +#### Data Corruption + +If Tendermint code encounters an inconsistency that could be +attributed to data corruption or a logical impossibility it is safer +to panic and crash the process than continue to attempt to make +progress in these situations. + +Examples including reading data out of the storage engine that +is invalid or corrupt, or encountering an ambiguous situation where +the process should halt. Generally these forms of corruption are +detected after interacting with a trusted but external data source, +and reflect situations where the author thinks its safer to terminate +the process immediately rather than allow execution to continue. + +#### Unrecoverable Consensus Failure + +In general, a panic should be used in the case of unrecoverable +consensus failures. If a process detects that the network is +behaving in an incoherent way and it does not have a clearly defined +and mechanism for recovering, the process should panic. + +#### Static Validity + +It is acceptable to panic for invariant violations, within a library +or package, in situations that should be statically impossible, +because there is no way to make these kinds of assertions at compile +time. + +For example, type-asserting `interface{}` values returned by +`container/list` and `container/heap` (and similar), is acceptable, +because package authors should have exclusive control of the inputs to +these containers. Packages should not expose the ability to add +arbitrary values to these data structures. + +#### Controlled Panics Within Libraries + +In some algorithms with highly recursive structures or very nested +call patterns, using a panic, in combination with conditional recovery +handlers results in more manageable code. Ultimately this is a limited +application, and implementations that use panics internally should +only recover conditionally, filtering out panics rather than ignoring +or handling all panics. + +#### Request Handling + +Code that handles responses to incoming/external requests +(e.g. `http.Handler`) should avoid panics, but practice this isn't +totally possible, and it makes sense that request handlers have some +kind of default recovery mechanism that will prevent one request from +terminating a service. + +### Unacceptable Panics + +In **no** other situation is it acceptable for the code to panic: + +- there should be **no** controlled panics that callers are required + to handle across library/package boundaries. +- callers of library functions should not expect panics. +- ensuring that arbitrary go routines can't panic. +- ensuring that there are no arbitrary panics in core production code, + espically code that can run at any time during the lifetime of a + process. +- all test code and fixture should report normal test assertions with + a mechanism like testify's `require` assertion rather than calling + panic directly. + +The goal of this increased "panic rigor" is to ensure that any escaped +panic is reflects a fixable bug in Tendermint. + +### Removing Panics + +The process for removing panics involve a few steps, and will be part +of an ongoing process of code modernization: + +- converting existing explicit panics to errors in cases where it's + possible to return an error, the errors can and should be handled, and returning + an error would not lead to data corruption or cover up data + corruption. + +- increase rigor around operations that can cause runtime errors, like + type assertions, nil pointer errors, array bounds access issues, and + either avoid these situations or return errors where possible. + +- remove generic panic handlers which could cover and hide known + panics. diff --git a/docs/rfc/tendermint-core/rfc-009-consensus-parameter-upgrades.md b/docs/rfc/tendermint-core/rfc-009-consensus-parameter-upgrades.md new file mode 100644 index 0000000..7859e3a --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-009-consensus-parameter-upgrades.md @@ -0,0 +1,128 @@ +# RFC 009 : Consensus Parameter Upgrade Considerations + +## Changelog + +- 06-Jan-2011: Initial draft (@williambanfield). + +## Abstract + +This document discusses the challenges of adding additional consensus parameters +to Tendermint and proposes a few solutions that can enable addition of consensus +parameters in a backwards-compatible way. + +## Background + +This section provides an overview of the issues of adding consensus parameters +to Tendermint. + +### Hash Compatibility + +Tendermint produces a hash of a subset of the consensus parameters. The values +that are hashed currently are the `BlockMaxGas` and the `BlockMaxSize`. These +are currently in the [HashedParams struct][hashed-params]. This hash is included +in the block and validators use it to validate that their local view of the consensus +parameters matches what the rest of the network is configured with. + +Any new consensus parameters added to Tendermint should be included in this +hash. This presents a challenge for verification of historical blocks when consensus +parameters are added. If a network produced blocks with a version of Tendermint that +did not yet have the new consensus parameters, the parameter hash it produced will +not reference the new parameters. Any nodes joining the network with the newer +version of Tendermint will have the new consensus parameters. Tendermint will need +to handle this case so that new versions of Tendermint with new consensus parameters +can still validate old blocks correctly without having to do anything overly complex +or hacky. + +### Allowing Developer-Defined Values and the `EndBlock` Problem + +When new consensus parameters are added, application developers may wish to set +values for them so that the developer-defined values may be used as soon as the +software upgrades. We do not currently have a clean mechanism for handling this. + +Consensus parameter updates are communicated from the application to Tendermint +within `EndBlock` of some height `H` and take effect at the next height, `H+1`. +This means that for updates that add a consensus parameter, there is a single +height where the new parameters cannot take effect. The parameters did not exist +in the version of the software that emitted the `EndBlock` response for height `H-1`, +so they cannot take effect at height `H`. The first height that the updated params +can take effect is height `H+1`. As of now, height `H` must run with the defaults. + +## Discussion + +### Hash Compatibility + +This section discusses possible solutions to the problem of maintaining backwards-compatibility +of hashed parameters while adding new parameters. + +#### Never Hash Defaults + +One solution to the problem of backwards-compatibility is to never include parameters +in the hash if the are using the default value. This means that blocks produced +before the parameters existed will have implicitly been created with the defaults. +This works because any software with newer versions of Tendermint must be using the +defaults for new parameters when validating old blocks since the defaults can not +have been updated until a height at which the parameters existed. + +#### Only Update HashedParams on Hash-Breaking Releases + +An alternate solution to never hashing defaults is to not update the hashed +parameters on non-hash-breaking releases. This means that when new consensus +parameters are added to Tendermint, there may be a release that makes use of the +parameters but does not verify that they are the same across all validators by +referencing them in the hash. This seems reasonably safe given the fact that +only a very far subset of the consensus parameters are currently verified at all. + +#### Version The Consensus Parameter Hash Scheme + +The upcoming work on [soft upgrades](https://github.com/tendermint/spec/pull/222) +proposes applying different hashing rules depending on the active block version. +The consensus parameter hash could be versioned in the same way. When different +block versions are used, a different set of consensus parameters will be included +in the hash. + +### Developer Defined Values + +This section discusses possible solutions to the problem of allowing application +developers to define values for the new parameters during the upgrade that adds +the parameters. + +#### Using `InitChain` for New Values + +One solution to the problem of allowing application developers to define values +for new consensus parameters is to call the `InitChain` ABCI method on application +startup and fetch the value for any new consensus parameters. The [response object][init-chain-response] +contains a field for `ConsensusParameter` updates so this may serve as a natural place +to put this logic. + +This poses a few difficulties. Nodes replaying old blocks while running new +software do not ever call `InitChain` after the initial time. They will therefore +not have a way to determine that the parameters changed at some height by using a +call to `InitChain`. The `EndBlock` response is how parameter changes at a height +are currently communicated to Tendermint and conflating these cases seems risky. + +#### Force Defaults For Single Height + +An alternate option is to not use `InitChain` and instead require chains to use the +default values of the new parameters for a single height. + +As documented in the upcoming [ADR-74][adr-74], popular chains often simply use the default +values. Additionally, great care is being taken to ensure that logic governed by upcoming +consensus parameters is not liveness-breaking. This means that, at worst-case, +chains will experience a single slow height while waiting for the new values to +by applied. + +#### Add a new `UpgradeChain` method + +An additional method for allowing chains to update the consensus parameters that +do not yet exist is to add a new `UpgradeChain` method to `ABCI`. The upgrade chain +method would be called when the chain detects that the version of block that it +is about to produce does not match the previous block. This method would be called +after `EndBlock` and would return the set of consensus parameters to use at the +next height. It would therefore give an application the chance to set the new +consensus parameters before running a height with these new parameter. + +### References + +[hashed-params]: https://github.com/tendermint/tendermint/blob/0ae974e63911804d4a2007bd8a9b3ad81d6d2a90/types/params.go#L49 +[init-chain-response]: https://github.com/tendermint/tendermint/blob/0ae974e63911804d4a2007bd8a9b3ad81d6d2a90/abci/types/types.pb.go#L1616 +[adr-74]: https://github.com/tendermint/tendermint/pull/7503 diff --git a/docs/rfc/tendermint-core/rfc-010-p2p-light-client.rst b/docs/rfc/tendermint-core/rfc-010-p2p-light-client.rst new file mode 100644 index 0000000..2e0b8b8 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-010-p2p-light-client.rst @@ -0,0 +1,145 @@ +================================== +RFC 010: Peer to Peer Light Client +================================== + +Changelog +--------- + +- 2022-01-21: Initial draft (@tychoish) + +Abstract +-------- + +The dependency on access to the RPC system makes running or using the light +client more complicated than it should be, because in practice node operators +choose to restrict access to these end points (often correctly.) There is no +deep dependency for the light client on the RPC system, and there is a +persistent notion that "make a p2p light client" is a solution to this +operational limitation. This document explores the implications and +requirements of implementing a p2p-based light client, as well as the +possibilities afforded by this implementation. + +Background +---------- + +High Level Design +~~~~~~~~~~~~~~~~~ + +From a high level, the light client P2P implementation, is relatively straight +forward, but is orthogonal to the P2P-backed statesync implementation that +took place during the 0.35 cycle. The light client only really needs to be +able to request (and receive) a `LightBlock` at a given height. To support +this, a new Reactor would run on every full node and validator which would be +able to service these requests. The workload would be entirely +request-response, and the implementation of the reactor would likely be very +straight forward, and the implementation of the provider is similarly +relatively simple. + +The complexity of the project focuses around peer discovery, handling when +peers disconnect from the light clients, and how to change the current P2P +code to appropriately handle specialized nodes. + +I believe it's safe to assume that much of the current functionality of the +current ``light`` mode would *not* need to be maintained: there is no need to +proxy the RPC endpoints over the P2P layer and there may be no need to run a +node/process for the p2p light client (e.g. all use of this will be as a +client.) + +The ability to run light clients using the RPC system will continue to be +maintained. + +LibP2P +~~~~~~ + +While some aspects of the P2P light client implementation are orthogonal to +LibP2P project, it's useful to think about the ways that these efforts may +combine or interact. + +We expect to be able to leverage libp2p tools to provide some kind of service +discovery for tendermint-based networks. This means that it will be possible +for the p2p stack to easily identify specialized nodes, (e.g. light clients) +thus obviating many of the design challenges with providing this feature in +the context of the current stack. + +Similarly, libp2p makes it possible for a project to be able back their non-Go +light clients, without the major task of first implementing Tendermint's p2p +connection handling. We should identify if there exist users (e.g. the go IBC +relayer, it's maintainers, and operators) who would be able to take advantage +of p2p light client, before switching to libp2p. To our knowledge there are +limited implementations of this p2p protocol (a simple implementation without +secret connection support exists in rust but it has not been used in +production), and it seems unlikely that a team would implement this directly +ahead of its impending removal. + +User Cases +~~~~~~~~~~ + +This RFC makes a few assumptions about the use cases and users of light +clients in tendermint. + +The most active and delicate use cases for light clients is in the +implementation of the IBC relayer. Thus, we expect that providing P2P light +clients might increase the reliability of relayers and reduce the cost of +running a relayer, because relayer operators won't have to decide between rely +on public RPC endpoints (unreliable) or running their own full nodes +(expensive.) This also assumes that there are *no* other uses of the RPC in +the relayer, and unless the relayers have the option of dropping all RPC use, +it's unclear if a P2P light client will actually be able to successfully +remove the dependency on the RPC system. + +Given that the primary relayer implementation is Hermes (rust,) it might be +safe to deliver a version of Tendermint that adds a light client rector in +the full nodes, but that does not provide an implementation of a Go light +client. This either means that the rust implementation would need support for +the legacy P2P connection protocol or wait for the libp2p implementation. + +Client side light client (e.g. wallets, etc.) users may always want to use (a +subset) of the RPC rather than connect to the P2P network for an ephemeral +use. + +Discussion +---------- + +Implementation Questions +~~~~~~~~~~~~~~~~~~~~~~~~ + +Most of the complication in the is how to have a long lived light client node +that *only* runs the light client reactor, as this raises a few questions: + +- would users specify a single P2P node to connect to when creating a light + client or would they also need/want to discover peers? + + - **answer**: most light client use cases won't care much about selecting + peers (and those that do can either disable PEX and specify persistent + peers, *or* use the RPC light client.) + +- how do we prevent full nodes and validators from allowing their peer slots, + which are typically limited, from filling with light clients? If + light-clients aren't limited, how do we prevent light clients from consuming + resources on consensus nodes? + + - **answer**: I think we can institute an internal cap on number of light + client connections to accept and also elide light client nodes from PEX + (pre-libp2p, if we implement this.) I believe that libp2p should provide + us with the kind of service discovery semantics for network connectivity + that would obviate this issue. + +- when a light client disconnects from its peers will it need to reset its + internal state (cache)? does this change if it connects to the same peers? + + - **answer**: no, the internal state only needs to be reset if the light + client detects an invalid block or other divergence, and changing + witnesses--which will be more common with a p2p light client--need not + invalidate the cache. + +These issues are primarily present given that the current peer management later +does not have a particularly good service discovery mechanism nor does it have +a very sophisticated way of identifying nodes of different types or modes. + +Report Evidence +~~~~~~~~~~~~~~~ + +The current light client implementation currently has the ability to report +observed evidence. Either the notional light client reactor needs to be able +to handle these kinds of requests *or* all light client nodes need to also run +the evidence reactor. This could be configured at runtime. diff --git a/docs/rfc/tendermint-core/rfc-011-delete-gas.md b/docs/rfc/tendermint-core/rfc-011-delete-gas.md new file mode 100644 index 0000000..59aad4d --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-011-delete-gas.md @@ -0,0 +1,160 @@ +# RFC 011: Remove Gas From Tendermint + +## Changelog + +- 03-Feb-2022: Initial draft (@williambanfield). +- 10-Feb-2022: Update in response to feedback (@williambanfield). +- 11-Feb-2022: Add reflection on MaxGas during consensus (@williambanfield). + +## Abstract + +In the v0.25.0 release, Tendermint added a mechanism for tracking 'Gas' in the mempool. +At a high level, Gas allows applications to specify how much it will cost the network, +often in compute resources, to execute a given transaction. While such a mechanism is common +in blockchain applications, it is not generalizable enough to be a maintained as a part +of Tendermint. This RFC explores the possibility of removing the concept of Gas from +Tendermint while still allowing applications the power to control the contents of +blocks to achieve similar goals. + +## Background + +The notion of Gas was included in the original Ethereum whitepaper and exists as +an important feature of the Ethereum blockchain. + +The [whitepaper describes Gas][eth-whitepaper-messages] as an Anti-DoS mechanism. The Ethereum Virtual Machine +provides a Turing complete execution platform. Without any limitations, malicious +actors could waste computation resources by directing the EVM to perform large +or even infinite computations. Gas serves as a metering mechanism to prevent this. + +Gas appears to have been added to Tendermint multiple times, initially as part of +a now defunct `/vm` package, and in its most recent iteration [as part of v0.25.0][gas-add-pr] +as a mechanism to limit the transactions that will be included in the block by an additional +parameter. + +Gas has gained adoption within the Cosmos ecosystem [as part of the Cosmos SDK][cosmos-sdk-gas]. +The SDK provides facilities for tracking how much 'Gas' a transaction is expected to take +and a mechanism for tracking how much gas a transaction has already taken. + +Non-SDK applications also make use of the concept of Gas. Anoma appears to implement +[a gas system][anoma-gas] to meter the transactions it executes. + +While the notion of gas is present in projects that make use of Tendermint, it is +not a concern of Tendermint's. Tendermint's value and goal is producing blocks +via a distributed consensus algorithm. Tendermint relies on the application specific +code to decide how to handle the transactions Tendermint has produced (or if the +application wants to consider them at all). Gas is an application concern. + +Our implementation of Gas is not currently enforced by consensus. Our current validation check that +occurs during block propagation does not verify that the block is under the configured `MaxGas`. +Ensuring that the transactions in a proposed block do not exceed `MaxGas` would require +input from the application during propagation. The `ProcessProposal` method introduced +as part of ABCI++ would enable such input but would further entwine Tendermint and +the application. The issue of checking `MaxGas` during block propagation is important +because it demonstrates that the feature as it currently exists is not implemented +as fully as it perhaps should be. + +Our implementation of Gas is causing issues for node operators and relayers. At +the moment, transactions that overflow the configured 'MaxGas' can be silently rejected +from the mempool. Overflowing MaxGas is the _only_ way that a transaction can be considered +invalid that is not directly a result of failing the `CheckTx`. Operators, and the application, +do not know that a transaction was removed from the mempool for this reason. A stateless check +of this nature is exactly what `CheckTx` exists for and there is no reason for the mempool +to keep track of this data separately. A special [MempoolError][add-mempool-error] field +was added in v0.35 to communicate to clients that a transaction failed after `CheckTx`. +While this should alleviate the pain for operators wishing to understand if their +transaction was included in the mempool, it highlights that the abstraction of +what is included in the mempool is not currently well defined. + +Removing Gas from Tendermint and the mempool would allow for the mempool to be a better +abstraction: any transaction that arrived at `CheckTx` and passed the check will either be +a candidate for a later block or evicted after a TTL is reached or to make room for +other, higher priority transactions. All other transactions are completely invalid and can be discarded forever. + +Removing gas will not be completely straightforward. It will mean ensuring that +equivalent functionality can be implemented outside of the mempool using the mempool's API. + +## Discussion + +This section catalogs the functionality that will need to exist within the Tendermint +mempool to allow Gas to be removed and replaced by application-side bookkeeping. + +### Requirement: Provide Mempool Tx Sorting Mechanism + +Gas produces a market for inclusion in a block. On many networks, a [gas fee][cosmos-sdk-fees] is +included in pending transactions. This fee indicates how much a user is willing to +pay per unit of execution and the fees are distributed to validators. + +Validators wishing to extract higher gas fees are incentivized to include transactions +with the highest listed gas fees into each block. This produces a natural ordering +of the pending transactions. Applications wishing to implement a gas mechanism need +to be able to order the transactions in the mempool. This can trivially be accomplished +by sorting transactions using the `priority` field available to applications as part of +v0.35's `ResponseCheckTx` message. + +### Requirement: Allow Application-Defined Block Resizing + +When creating a block proposal, Tendermint pulls a set of possible transactions out of +the mempool to include in the next block. Tendermint uses MaxGas to limit the set of transactions +it pulls out of the mempool fetching a set of transactions whose sum is less than MaxGas. + +By removing gas tracking from Tendermint's mempool, Tendermint will need to provide a way for +applications to determine an acceptable set of transactions to include in the block. + +This is what the new ABCI++ `PrepareProposal` method is useful for. Applications +that wish to limit the contents of a block by an application-defined limit may +do so by removing transactions from the proposal it is passed during `PrepareProposal`. +Applications wishing to reach parity with the current Gas implementation may do +so by creating an application-side limit: filtering out transactions from +`PrepareProposal` the cause the proposal the exceed the maximum gas. Additionally, +applications can currently opt to have all transactions in the mempool delivered +during `PrepareProposal` by passing `-1` for `MaxGas` and `MaxBytes` into +[ReapMaxBytesMaxGas][reap-max-bytes-max-gas]. + +### Requirement: Handle Transaction Metadata + +Moving the gas mechanism into applications adds an additional piece of complexity +to applications. The application must now track how much gas it expects a transaction +to consume. The mempool currently handles this bookkeeping responsibility and uses the estimated +gas to determine the set of transactions to include in the block. In order to task +the application with keeping track of this metadata, we should make it easier for the +application to do so. In general, we'll want to keep only one copy of this type +of metadata in the program at a time, either in the application or in Tendermint. + +The following sections are possible solutions to the problem of storing transaction +metadata without duplication. + +#### Metadata Handling: EvictTx Callback + +A possible approach to handling transaction metadata is by adding a new `EvictTx` +ABCI method. Whenever the mempool is removing a transaction, either because it has +reached its TTL or because it failed `RecheckTx`, `EvictTx` would be called with +the transaction hash. This would indicate to the application that it could free any +metadata it was storing about the transaction such as the computed gas fee. + +Eviction callbacks are pretty common in caching systems, so this would be very +well-worn territory. + +#### Metadata Handling: Application-Specific Metadata Field(s) + +An alternative approach to handling transaction metadata would be would be the +addition of a new application-metadata field in the `ResponseCheckTx`. This field +would be a protocol buffer message whose contents were entirely opaque to Tendermint. +The application would be responsible for marshalling and unmarshalling whatever data +it stored in this field. During `PrepareProposal`, the application would be passed +this metadata along with the transaction, allowing the application to use it to perform +any necessary filtering. + +If either of these proposed metadata handling techniques are selected, it's likely +useful to enable applications to gossip metadata along with the transaction it is +gossiping. This could easily take the form of an opaque proto message that is +gossiped along with the transaction. + +## References + +[eth-whitepaper-messages]: https://ethereum.org/en/whitepaper/#messages-and-transactions +[gas-add-pr]: https://github.com/tendermint/tendermint/pull/2360 +[cosmos-sdk-gas]: https://github.com/cosmos/cosmos-sdk/blob/c00cedb1427240a730d6eb2be6f7cb01f43869d3/docs/basics/gas-fees.md +[cosmos-sdk-fees]: https://github.com/cosmos/cosmos-sdk/blob/c00cedb1427240a730d6eb2be6f7cb01f43869d3/docs/basics/tx-lifecycle.md#gas-and-fees +[anoma-gas]: https://github.com/anoma/anoma/blob/6974fe1532a59db3574fc02e7f7e65d1216c1eb2/docs/src/specs/ledger.md#transaction-execution +[reap-max-bytes-max-gas]: https://github.com/tendermint/tendermint/blob/1ac58469f32a98f1c0e2905ca1773d9eac7b7103/internal/mempool/types.go#L45 +[add-mempool-error]: https://github.com/tendermint/tendermint/blob/205bfca66f6da1b2dded381efb9ad3792f9404cf/rpc/coretypes/responses.go#L239 diff --git a/docs/rfc/tendermint-core/rfc-012-custom-indexing.md b/docs/rfc/tendermint-core/rfc-012-custom-indexing.md new file mode 100644 index 0000000..3297411 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-012-custom-indexing.md @@ -0,0 +1,351 @@ +# RFC 012: Event Indexing Revisited + +## Changelog + +- 11-Feb-2022: Add terminological notes. +- 10-Feb-2022: Updated from review feedback. +- 07-Feb-2022: Initial draft (@creachadair) + +## Abstract + +A Tendermint node allows ABCI events associated with block and transaction +processing to be "indexed" into persistent storage. The original Tendermint +implementation provided a fixed, built-in [proprietary indexer][kv-index] for +such events. + +In response to user requests to customize indexing, [ADR 065][adr065] +introduced an "event sink" interface that allows developers (at least in +theory) to plug in alternative index storage. + +Although ADR-065 was a good first step toward customization, its implementation +model does not satisfy all the user requirements. Moreover, this approach +leaves some existing technical issues with indexing unsolved. + +This RFC documents these concerns, and discusses some potential approaches to +solving them. This RFC does _not_ propose a specific technical decision. It is +meant to unify and focus some of the disparate discussions of the topic. + + +## Background + +We begin with some important terminological context. The term "event" in +Tendermint can be confusing, as the same word is used for multiple related but +distinct concepts: + +1. **ABCI Events** refer to the key-value metadata attached to blocks and + transactions by the application. These values are represented by the ABCI + `Event` protobuf message type. + +2. **Consensus Events** refer to the data published by the Tendermint node to + its pubsub bus in response to various consensus state transitions and other + important activities, such as round updates, votes, transaction delivery, + and block completion. + +This confusion is compounded because some "consensus event" values also have +"ABCI event" metadata attached to them. Notably, block and transaction items +typically have ABCI metadata assigned by the application. + +Indexers and RPC clients subscribed to the pubsub bus receive **consensus +events**, but they identify which ones to care about using query expressions +that match against the **ABCI events** associated with them. + +In the discussion that follows, we will use the term **event item** to refer to +a datum published to or received from the pubsub bus, and **ABCI event** or +**event metadata** to refer to the key/value annotations. + +**Indexing** in this context means recording the association between certain +ABCI metadata and the blocks or transactions they're attached to. The ABCI +metadata typically carry application-specific details like sender and recipient +addresses, catgory tags, and so forth, that are not part of consensus but are +used by UI tools to find and display transactions of interest. + +The consensus node records the blocks and transactions as part of its block +store, but does not persist the application metadata. Metadata persistence is +the task of the indexer, which can be (optionally) enabled by the node +operator. + +### History + +The [original indexer][kv-index] built in to Tendermint stored index data in an +embedded [`tm-db` database][tmdb] with a proprietary key layout. +In [ADR 065][adr065], we noted that this implementation has both performance +and scaling problems under load. Moreover, the only practical way to query the +index data is via the [query filter language][query] used for event +subscription. [Issue #1161][i1161] appears to be a motivational context for that ADR. + +To mitigate both of these concerns, we introduced the [`EventSink`][esink] +interface, combining the original transaction and block indexer interfaces +along with some service plumbing. Using this interface, a developer can plug +in an indexer that uses a more efficient storage engine, and provides a more +expressive query language. As a proof-of-concept, we built a [PostgreSQL event +sink][psql] that exports data to a [PostgreSQL database][postgres]. + +Although this approach addressed some of the immediate concerns, there are +several issues for custom indexing that have not been fully addressed. Here we +will discuss them in more detail. + +For further context, including links to user reports and related work, see also +the [Pluggable custom event indexing tracking issue][i7135] issue. + +### Issue 1: Tight Coupling + +The `EventSink` interface supports multiple implementations, but plugging in +implementations still requires tight integration with the node. In particular: + +- Any custom indexer must either be written in Go and compiled in to the + Tendermint binary, or the developer must write a Go shim to communicate with + the implementation and build that into the Tendermint binary. + +- This means to support a custom indexer, it either has to be integrated into + the Tendermint core repository, or every installation that uses that indexer + must fetch or build a patched version of Tendermint. + +The problem with integrating indexers into Tendermint Core is that every user +of Tendermint Core takes a dependency on all supported indexers, including +those they never use. Even if the unused code is disabled with build tags, +users have to remember to do this or potentially be exposed to security issues +that may arise in any of the custom indexers. This is a risk for Tendermint, +which is a trust-critical component of all applications built on it. + +The problem with _not_ integrating indexers into Tendermint Core is that any +developer who wants to use a particular indexer must now fetch or build a +patched version of the core code that includes the custom indexer. Besides +being inconvenient, this makes it harder for users to upgrade their node, since +they need to either re-apply their patches directly or wait for an intermediary +to do it for them. + +Even for developers who have written their applications in Go and link with the +consensus node directly (e.g., using the [Cosmos SDK][sdk]), these issues add a +potentially significant complication to the build process. + +### Issue 2: Legacy Compatibility + +The `EventSink` interface retains several limitations of the original +proprietary indexer. These include: + +- The indexer has no control over which event items are reported. Only the + exact block and transaction events that were reported to the original indexer + are reported to a custom indexer. + +- The interface requires the implementation to define methods for the legacy + search and query API. This requirement comes from the integation with the + [event subscription RPC API][event-rpc], but actually supporting these + methods is not trivial. + +At present, only the original KV indexer implements the query methods. Even the +proof-of-concept PostgreSQL implementation simply reports errors for all calls +to these methods. + +Even for a plugin written in Go, implementing these methods "correctly" would +require parsing and translating the custom query language over whatever storage +platform the indexer uses. + +For a plugin _not_ written in Go, even beyond the cost of integration the +developer would have to re-implement the entire query language. + +### Issue 3: Indexing Delays Consensus + +Within the node, indexing hooks in to the same internal pubsub dispatcher that +is used to export event items to the [event subscription RPC API][event-rpc]. +In contrast with RPC subscribers, however, indexing is a "privileged" +subscriber: If an RPC subscriber is "too slow", the node may terminate the +subscription and disconnect the client. That means that RPC subscribers may +lose (miss) event items. The indexer, however, is "unbuffered", and the +publisher will never drop or disconnect from it. If the indexer is slow, the +publisher will block until it returns, to ensure that no event items are lost. + +In practice, this means that the performance of the indexer has a direct effect +on the performance of the consensus node: If the indexer is slow or stalls, it +will slow or halt the progress of consensus. Users have already reported this +problem even with the built-in indexer (see, for example, [#7247][i7247]). +Extending this concern to arbitrary user-defined custom indexers gives that +risk a much larger surface area. + + +## Discussion + +It is not possible to simultaneously guarantee that publishing event items will +not delay consensus, and also that all event items of interest are always +completely indexed. + +Therefore, our choice is between eliminating delay (and minimizing loss) or +eliminating loss (and minimizing delay). Currently, we take the second +approach, which has led to user complaints about consensus delays due to +indexing and subscription overhead. + +- If we agree that consensus performance supersedes index completeness, our + design choices are to constrain the likelihood and frequency of missing event + items. + +- If we decide that consensus performance is more important than index + completeness, our option is to minimize overhead on the event delivery path + and document that indexer plugins constrain the rate of consensus. + +Since we have user reports requesting both properties, we have to choose one or +the other. Since the primary job of the consensus engine is to correctly, +robustly, reliablly, and efficiently replicate application state across the +network, I believe the correct choice is to favor consensus performance. + +An important consideration for this decision is that a node does not index +application metadata separately: If indexing is disabled, there is no built-in +mechanism to go back and replay or reconstruct the data that an indexer would +have stored. The node _does_ store the blockchain itself (i.e., the blocks and +their transactions), so potentially some use cases currently handled by the +indexer could be handled by the node. For example, allowing clients to ask +whether a given transaction ID has been committed to a block could in principle +be done without an indexer, since it does not depend on application metadata. + +Inevitably, a question will arise whether we could implement both strategies +and toggle between them with a flag. That would be a worst-case scenario, +requiring us to maintain the complexity of two very-different operational +concerns. If our goal is that Tendermint should be as simple, efficient, and +trustworthy as posible, there is not a strong case for making these options +configurable: We should pick a side and commit to it. + +### Design Principles + +Although there is no unique "best" solution to the issues described above, +there are some specific principles that a solution should include: + +1. **A custom indexer should not require integration into Tendermint core.** A + developer or node operator can create, build, deploy, and use a custom + indexer with a stock build of the Tendermint consensus node. + +2. **Custom indexers cannot stall consensus.** An indexer that is slow or + stalls cannot slow down or prevent core consensus from making progress. + + The plugin interface must give node operators control over the tolerances + for acceptable indexer performance, and the means to detect when indexers + are falling outside those tolerances, but indexer failures should "fail + safe" with respect to consensus (even if that means the indexer may miss + some data, in sufficiently-extreme circumstances). + +3. **Custom indexers control which event items they index.** A custom indexer + is not limited to only the current transaction and block events, but can + observe any event item published by the node. + +4. **Custom indexing is forward-compatible.** Adding new event item types or + metadata to the consensus node should not require existing custom indexers + to be rebuilt or modified, unless they want to take advantage of the new + data. + +5. **Indexers are responsible for answering queries.** An indexer plugin is not + required to support the legacy query filter language, nor to be compatible + with the legacy RPC endpoints for accessing them. Any APIs for clients to + query a custom index are the responsibility of the indexer, not the node. + +### Open Questions + +Given the constraints outlined above, there are important design questions we +must answer to guide any specific changes: + +1. **What is an acceptable probability that, given sufficiently extreme + operational issues, an indexer might miss some number of events?** + + There are two parts to this question: One is what constitutes an extreme + operational problem, the other is how likely we are to miss some number of + events items. + + - If the consensus is that no event item must ever be missed, no matter how + bad the operational circumstances, then we _must_ accept that indexing can + slow or halt consensus arbitrarily. It is impossible to guarantee complete + index coverage without potentially unbounded delays. + + - Otherwise, how much data can we afford to lose and how often? For example, + if we can ensure no event item will be lost unless the indexer halts for + at least five minutes, is that acceptable? What probabilities and time + ranges are reasonable for real production environments? + +2. **What level of operational overhead is acceptable to impose on node + operators to support indexing?** + + Are node operators willing to configure and run custom indexers as sidecar + type processes alongside a node? How much indexer setup above and beyond the + work of setting up the underlying node in isolation is tractable in + production networks? + + The answer to this question also informs the question of whether we should + keep an "in-process" indexing option, and to what extent that option needs + to satisfy the suggested design principles. + + Relatedly, to what extent do we need to be concerned about the cost of + encoding and sending event items to an external process (e.g., as JSON blobs + or protobuf wire messages)? Given that the node already encodes event items + as JSON for subscription purposes, the overhead would be negligible for the + node itself, but the indexer would have to decode to process the results. + +3. **What (if any) query APIs does the consensus node need to export, + independent of the indexer implementation?** + + One typical example is whether the node should be able to answer queries + like "is this transaction ID in a block?" Currently, a node cannot answer + this query _unless_ it runs the built-in KV indexer. Does the node need to + continue to support that query even for nodes that disable the KV indexer, + or which use a custom indexer? + +### Informal Design Intent + +The design principles described above implicate several components of the +Tendermint node, beyond just the indexer. In the context of [ADR 075][adr075], +we are re-working the RPC event subscription API to improve some of the UX +issues discussed above for RPC clients. It is our expectation that a solution +for pluggable custom indexing will take advantage of some of the same work. + +On that basis, the design approach I am considering for custom indexing looks +something like this (subject to refinement): + +1. A custom indexer runs as a separate process from the node. + +2. The indexer subscribes to event items via the ADR 075 events API. + + This means indexers would receive event payloads as JSON rather than + protobuf, but since we already have to support JSON encoding for the RPC + interface anyway, that should not increase complexity for the node. + +3. The existing PostgreSQL indexer gets reworked to have this form, and no + longer built as part of the Tendermint core binary. + + We can retain the code in the core repository as a proof-of-concept, or + perhaps create a separate repository with contributed indexers and move it + there. + +4. (Possibly) Deprecate and remove the legacy KV indexer, or disable it by + default. If we decide to remove it, we can also remove the legacy RPC + endpoints for querying the KV indexer. + + If we plan to do this, we should also investigate providing a way for + clients to query whether a given transaction ID has landed in a block. That + serves a common need, and currently _only_ works if the KV indexer is + enabled, but could be addressed more simply using the other data a node + already has stored, without having to answer more general queries. + + +## References + +- [ADR 065: Custom Event Indexing][adr065] +- [ADR 075: RPC Event Subscription Interface][adr075] +- [Cosmos SDK][sdk] +- [Event subscription RPC][event-rpc] +- [KV transaction indexer][kv-index] +- [Pluggable custom event indexing][i7135] (#7135) +- [PostgreSQL event sink][psql] + - [PostgreSQL database][postgres] +- [Query filter language][query] +- [Stream events to postgres for indexing][i1161] (#1161) +- [Unbuffered event subscription slow down the consensus][i7247] (#7247) +- [`EventSink` interface][esink] +- [`tm-db` library][tmdb] + +[adr065]: https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-065-custom-event-indexing.md +[adr075]: https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-075-rpc-subscription.md +[esink]: https://pkg.go.dev/github.com/tendermint/tendermint/internal/state/indexer#EventSink +[event-rpc]: https://docs.tendermint.com/v0.34/rpc/#/Websocket/subscribe +[i1161]: https://github.com/tendermint/tendermint/issues/1161 +[i7135]: https://github.com/tendermint/tendermint/issues/7135 +[i7247]: https://github.com/tendermint/tendermint/issues/7247 +[kv-index]: https://github.com/tendermint/tendermint/blob/main/state/indexer/block/kv +[postgres]: https://postgresql.org/ +[psql]: https://github.com/tendermint/tendermint/tree/main/state/indexer/sink/psql +[query]: https://pkg.go.dev/github.com/tendermint/tendermint/internal/pubsub/query/syntax +[sdk]: https://github.com/cosmos/cosmos-sdk +[tmdb]: https://pkg.go.dev/github.com/tendermint/tm-db#DB diff --git a/docs/rfc/tendermint-core/rfc-013-abci++.md b/docs/rfc/tendermint-core/rfc-013-abci++.md new file mode 100644 index 0000000..62da0e1 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-013-abci++.md @@ -0,0 +1,253 @@ +# RFC 013: ABCI++ + +## Changelog + +- 2020-01-11: initialized +- 2022-02-11: Migrate RFC to tendermint repo (Originally [RFC 004](https://github.com/tendermint/spec/pull/254)) + +## Author(s) + +- Dev (@valardragon) +- Sunny (@sunnya97) + +## Context + +ABCI is the interface between the consensus engine and the application. +It defines when the application can talk to consensus during the execution of a blockchain. +At the moment, the application can only act at one phase in consensus, immediately after a block has been finalized. + +This restriction on the application prohibits numerous features for the application, including many scalability improvements that are now better understood than when ABCI was first written. +For example, many of the scalability proposals can be boiled down to "Make the miner / block proposers / validators do work, so the network does not have to". +This includes optimizations such as tx-level signature aggregation, state transition proofs, etc. +Furthermore, many new security properties cannot be achieved in the current paradigm, as the application cannot enforce validators do more than just finalize txs. +This includes features such as threshold cryptography, and guaranteed IBC connection attempts. +We propose introducing three new phases to ABCI to enable these new features, and renaming the existing methods for block execution. + +#### Prepare Proposal phase + +This phase aims to allow the block proposer to perform more computation, to reduce load on all other full nodes, and light clients in the network. +It is intended to enable features such as batch optimizations on the transaction data (e.g. signature aggregation, zk rollup style validity proofs, etc.), enabling stateless blockchains with validator provided authentication paths, etc. + +This new phase will only be executed by the block proposer. The application will take in the block header and raw transaction data output by the consensus engine's mempool. It will then return block data that is prepared for gossip on the network, and additional fields to include into the block header. + +#### Process Proposal Phase + +This phase aims to allow applications to determine validity of a new block proposal, and execute computation on the block data, prior to the blocks finalization. +It is intended to enable applications to reject block proposals with invalid data, and to enable alternate pipelined execution models. (Such as Ethereum-style immediate execution) + +This phase will be executed by all full nodes upon receiving a block, though on the application side it can do more work in the even that the current node is a validator. + +#### Vote Extension Phase + +This phase aims to allow applications to require their validators do more than just validate blocks. +Example usecases of this include validator determined price oracles, validator guaranteed IBC connection attempts, and validator based threshold crypto. + +This adds an app-determined data field that every validator must include with their vote, and these will thus appear in the header. + +#### Rename {BeginBlock, [DeliverTx], EndBlock} to FinalizeBlock + +The prior phases gives the application more flexibility in their execution model for a block, and they obsolete the current methods for how the consensus engine relates the block data to the state machine. Thus we refactor the existing methods to better reflect what is happening in the new ABCI model. + +This rename doesn't on its own enable anything new, but instead improves naming to clarify the expectations from the application in this new communication model. The existing ABCI methods `BeginBlock, [DeliverTx], EndBlock` are renamed to a single method called `FinalizeBlock`. + +#### Summary + +We include a more detailed list of features / scaling improvements that are blocked, and which new phases resolve them at the end of this document. + + +On the top is the existing definition of ABCI, and on the bottom is the proposed ABCI++. + +## Proposal + +Below we suggest an API to add these three new phases. +In this document, sometimes the final round of voting is referred to as precommit for clarity in how it acts in the Tendermint case. + +### Prepare Proposal + +*Note, APIs in this section will change after Vote Extensions, we list the adjusted APIs further in the proposal.* + +The Prepare Proposal phase allows the block proposer to perform application-dependent work in a block, to lower the amount of work the rest of the network must do. This enables batch optimizations to a block, which has been empirically demonstrated to be a key component for scaling. This phase introduces the following ABCI method + +```rust +fn PrepareProposal(Block) -> BlockData +``` + +where `BlockData` is a type alias for however data is internally stored within the consensus engine. In Tendermint Core today, this is `[]Tx`. + +The application may read the entire block proposal, and mutate the block data fields. Mutated transactions will still get removed from the mempool later on, as the mempool rechecks all transactions after a block is executed. + +The `PrepareProposal` API will be modified in the vote extensions section, for allowing the application to modify the header. + +### Process Proposal + +The Process Proposal phase sends the block data to the state machine, prior to running the last round of votes on the state machine. This enables features such as allowing validators to reject a block according to whether state machine deems it valid, and changing block execution pipeline. + +We introduce three new methods, + +```rust +fn VerifyHeader(header: Header, isValidator: bool) -> ResponseVerifyHeader {...} +fn ProcessProposal(block: Block) -> ResponseProcessProposal {...} +fn RevertProposal(height: usize, round: usize) {...} +``` + +where + +```rust +struct ResponseVerifyHeader { + accept_header: bool, + evidence: Vec +} +struct ResponseProcessProposal { + accept_block: bool, + evidence: Vec +} +``` + +Upon receiving a block header, every validator runs `VerifyHeader(header, isValidator)`. The reason for why `VerifyHeader` is split from `ProcessProposal` is due to the later sections for Preprocess Proposal and Vote Extensions, where there may be application dependent data in the header that must be verified before accepting the header. +If the returned `ResponseVerifyHeader.accept_header` is false, then the validator must precommit nil on this block, and reject all other precommits on this block. `ResponseVerifyHeader.evidence` is appended to the validators local `EvidencePool`. + +Upon receiving an entire block proposal (in the current implementation, all "block parts"), every validator runs `ProcessProposal(block)`. If the returned `ResponseProcessProposal.accept_block` is false, then the validator must precommit nil on this block, and reject all other precommits on this block. `ResponseProcessProposal.evidence` is appended to the validators local `EvidencePool`. + +Once a validator knows that consensus has failed to be achieved for a given block, it must run `RevertProposal(block.height, block.round)`, in order to signal to the application to revert any potentially mutative state changes it may have made. In Tendermint, this occurs when incrementing rounds. + +**RFC**: How do we handle the scenario where honest node A finalized on round x, and honest node B finalized on round x + 1? (e.g. when 2f precommits are publicly known, and a validator precommits themself but doesn't broadcast, but they increment rounds) Is this a real concern? The state root derived could change if everyone finalizes on round x+1, not round x, as the state machine can depend non-uniformly on timestamp. + +The application is expected to cache the block data for later execution. + +The `isValidator` flag is set according to whether the current node is a validator or a full node. This is intended to allow for beginning validator-dependent computation that will be included later in vote extensions. (An example of this is threshold decryptions of ciphertexts.) + +### DeliverTx rename to FinalizeBlock + +After implementing `ProcessProposal`, txs no longer need to be delivered during the block execution phase. Instead, they are already in the state machine. Thus `BeginBlock, DeliverTx, EndBlock` can all be replaced with a single ABCI method for `ExecuteBlock`. Internally the application may still structure its method for executing the block as `BeginBlock, DeliverTx, EndBlock`. However, it is overly restrictive to enforce that the block be executed after it is finalized. There are multiple other, very reasonable pipelined execution models one can go for. So instead we suggest calling this succession of methods `FinalizeBlock`. We propose the following API + +Replace the `BeginBlock, DeliverTx, EndBlock` ABCI methods with the following method + +```rust +fn FinalizeBlock() -> ResponseFinalizeBlock +``` + +where `ResponseFinalizeBlock` has the following API, in terms of what already exists + +```rust +struct ResponseFinalizeBlock { + updates: ResponseEndBlock, + tx_results: Vec +} +``` + +`ResponseEndBlock` should then be renamed to `ConsensusUpdates` and `ResponseDeliverTx` should be renamed to `ResponseTx`. + +### Vote Extensions + +The Vote Extensions phase allow applications to force their validators to do more than just validate within consensus. This is done by allowing the application to add more data to their votes, in the final round of voting. (Namely the precommit) +This additional application data will then appear in the block header. + +First we discuss the API changes to the vote struct directly + +```rust +fn ExtendVote(height: u64, round: u64) -> (UnsignedAppVoteData, SelfAuthenticatingAppData) +fn VerifyVoteExtension(signed_app_vote_data: Vec, self_authenticating_app_vote_data: Vec) -> bool +``` + +There are two types of data that the application can enforce validators to include with their vote. +There is data that the app needs the validator to sign over in their vote, and there can be self-authenticating vote data. Self-authenticating here means that the application upon seeing these bytes, knows its valid, came from the validator and is non-malleable. We give an example of each type of vote data here, to make their roles clearer. + +- Unsigned app vote data: A use case of this is if you wanted validator backed oracles, where each validator independently signs some oracle data in their vote, and the median of these values is used on chain. Thus we leverage consensus' signing process for convenience, and use that same key to sign the oracle data. +- Self-authenticating vote data: A use case of this is in threshold random beacons. Every validator produces a threshold beacon share. This threshold beacon share can be verified by any node in the network, given the share and the validators public key (which is not the same as its consensus public key). However, this decryption share will not make it into the subsequent block's header. They will be aggregated by the subsequent block proposer to get a single random beacon value that will appear in the subsequent block's header. Everyone can then verify that this aggregated value came from the requisite threshold of the validator set, without increasing the bandwidth for full nodes or light clients. To achieve this goal, the self-authenticating vote data cannot be signed over by the consensus key along with the rest of the vote, as that would require all full nodes & light clients to know this data in order to verify the vote. + +The `CanonicalVote` struct will acommodate the `UnsignedAppVoteData` field by adding another string to its encoding, after the `chain-id`. This should not interfere with existing hardware signing integrations, as it does not affect the constant offset for the `height` and `round`, and the vote size does not have an explicit upper bound. (So adding this unsigned app vote data field is equivalent from the HSM's perspective as having a superlong chain-ID) + +**RFC**: Please comment if you think it will be fine to have elongate the message the HSM signs, or if we need to explore pre-hashing the app vote data. + +The flow of these methods is that when a validator has to precommit, Tendermint will first produce a precommit canonical vote without the application vote data. It will then pass it to the application, which will return unsigned application vote data, and self authenticating application vote data. It will bundle the `unsigned_application_vote_data` into the canonical vote, and pass it to the HSM to sign. Finally it will package the self-authenticating app vote data, and the `signed_vote_data` together, into one final Vote struct to be passed around the network. + +#### Changes to Prepare Proposal Phase + +There are many use cases where the additional data from vote extensions can be batch optimized. +This is mainly of interest when the votes include self-authenticating app vote data that be batched together, or the unsigned app vote data is the same across all votes. +To allow for this, we change the PrepareProposal API to the following + +```rust +fn PrepareProposal(Block, UnbatchedHeader) -> (BlockData, Header) +``` + +where `UnbatchedHeader` essentially contains a "RawCommit", the `Header` contains a batch-optimized `commit` and an additional "Application Data" field in its root. This will involve a number of changes to core data structures, which will be gone over in the ADR. +The `Unbatched` header and `rawcommit` will never be broadcasted, they will be completely internal to consensus. + +#### Inter-process communication (IPC) effects + +For brevity in exposition above, we did not discuss the trade-offs that may occur in interprocess communication delays that these changs will introduce. +These new ABCI methods add more locations where the application must communicate with the consensus engine. +In most configurations, we expect that the consensus engine and the application will be either statically or dynamically linked, so all communication is a matter of at most adjusting the memory model the data is layed out within. +This memory model conversion is typically considered negligible, as delay here is measured on the order of microseconds at most, whereas we face milisecond delays due to cryptography and network overheads. +Thus we ignore the overhead in the case of linked libraries. + +In the case where the consensus engine and the application are ran in separate processes, and thus communicate with a form of Inter-process communication (IPC), the delays can easily become on the order of miliseconds based upon the data sent. Thus its important to consider whats happening here. +We go through this phase by phase. + +##### Prepare proposal IPC overhead + +This requires a round of IPC communication, where both directions are quite large. Namely the proposer communicating an entire block to the application. +However, this can be mitigated by splitting up `PrepareProposal` into two distinct, async methods, one for the block IPC communication, and one for the Header IPC communication. + +Then for chains where the block data does not depend on the header data, the block data IPC communication can proceed in parallel to the prior block's voting phase. (As a node can know whether or not its the leader in the next round) + +Furthermore, this IPC communication is expected to be quite low relative to the amount of p2p gossip time it takes to send the block data around the network, so this is perhaps a premature concern until more sophisticated block gossip protocols are implemented. + +##### Process Proposal IPC overhead + +This phase changes the amount of time available for the consensus engine to deliver a block's data to the state machine. +Before, the block data for block N would be delivered to the state machine upon receiving a commit for block N and then be executed. +The state machine would respond after executing the txs and before prevoting. +The time for block delivery from the consensus engine to the state machine after this change is the time of receiving block proposal N to the to time precommit on proposal N. +It is expected that this difference is unimportant in practice, as this time is in parallel to one round of p2p communication for prevoting, which is expected to be significantly less than the time for the consensus engine to deliver a block to the state machine. + +##### Vote Extension IPC overhead + +This has a small amount of data, but does incur an IPC round trip delay. This IPC round trip delay is pretty negligible as compared the variance in vote gossip time. (the IPC delay is typically on the order of 10 microseconds) + +## Status + +Proposed + +## Consequences + +### Positive + +- Enables a large number of new features for applications +- Supports both immediate and delayed execution models +- Allows application specific data from each validator +- Allows for batch optimizations across txs, and votes + +### Negative + +- This is a breaking change to all existing ABCI clients, however the application should be able to have a thin wrapper to replicate existing ABCI behavior. + - PrepareProposal - can be a no-op + - Process Proposal - has to cache the block, but can otherwise be a no-op + - Vote Extensions - can be a no-op + - Finalize Block - Can black-box call BeginBlock, DeliverTx, EndBlock given the cached block data + +- Vote Extensions adds more complexity to core Tendermint Data Structures +- Allowing alternate alternate execution models will lead to a proliferation of new ways for applications to violate expected guarantees. + +### Neutral + +- IPC overhead considerations change, but mostly for the better + +## References + +Reference for IPC delay constants: + +### Short list of blocked features / scaling improvements with required ABCI++ Phases + +| Feature | PrepareProposal | ProcessProposal | Vote Extensions | +| :--- | :---: | :---: | :---: | +| Tx based signature aggregation | X | | | +| SNARK proof of valid state transition | X | | | +| Validator provided authentication paths in stateless blockchains | X | | | +| Immediate Execution | | X | | +| Simple soft forks | | X | | +| Validator guaranteed IBC connection attempts | | | X | +| Validator based price oracles | | | X | +| Immediate Execution with increased time for block execution | X | X | X | +| Threshold Encrypted txs | X | X | X | diff --git a/docs/rfc/tendermint-core/rfc-014-semantic-versioning.md b/docs/rfc/tendermint-core/rfc-014-semantic-versioning.md new file mode 100644 index 0000000..44dfcd5 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-014-semantic-versioning.md @@ -0,0 +1,94 @@ +# RFC 014: Semantic Versioning + +## Changelog + +- 2021-11-19: Initial Draft +- 2021-02-11: Migrate RFC to tendermint repo (Originally [RFC 006](https://github.com/tendermint/spec/pull/365)) + +## Author(s) + +- Callum Waters @cmwaters + +## Context + +We use versioning as an instrument to hold a set of promises to users and signal when such a set changes and how. In the conventional sense of a Go library, major versions signal that the public Go API’s have changed in a breaking way and thus require the users of such libraries to change their usage accordingly. Tendermint is a bit different in that there are multiple users: application developers (both in-process and out-of-process), node operators, and external clients. More importantly, both how these users interact with Tendermint and what's important to these users differs from how users interact and what they find important in a more conventional library. + +This document attempts to encapsulate the discussions around versioning in Tendermint and draws upon them to propose a guide to how Tendermint uses versioning to make promises to its users. + +For a versioning policy to make sense, we must also address the intended frequency of breaking changes. The strictest guarantees in the world will not help users if we plan to break them with every release. + +Finally I would like to remark that this RFC only addresses the "what", as in what are the rules for versioning. The "how" of Tendermint implementing the versioning rules we choose, will be addressed in a later RFC on Soft Upgrades. + +## Discussion + +We first begin with a round up of the various users and a set of assumptions on what these users expect from Tendermint in regards to versioning: + +1. **Application Developers**, those that use the ABCI to build applications on top of Tendermint, are chiefly concerned with that API. Breaking changes will force developers to modify large portions of their codebase to accommodate for the changes. Some ABCI changes such as introducing priority for the mempool don't require any effort and can be lazily adopted whilst changes like ABCI++ may force applications to redesign their entire execution system. It's also worth considering that the API's for go developers differ to developers of other languages. The former here can use the entire Tendermint library, most notably the local RPC methods, and so the team must be wary of all public Go API's. +2. **Node Operators**, those running node infrastructure, are predominantly concerned with downtime, complexity and frequency of upgrading, and avoiding data loss. They may be also concerned about changes that may break the scripts and tooling they use to supervise their nodes. +3. **External Clients** are those that perform any of the following: + - consume the RPC endpoints of nodes like `/block` + - subscribe to the event stream + - make queries to the indexer + + This set are concerned with chain upgrades which will impact their ability to query state and block data as well as broadcast transactions. Examples include wallets and block explorers. + +4. **IBC module and relayers**. The developers of IBC and consumers of their software are concerned about changes that may affect a chain's ability to send arbitrary messages to another chain. Specifically, these users are affected by any breaking changes to the light client verification algorithm. + +Although we present them here as having different concerns, in a broader sense these user groups share a concern for the end users of applications. A crucial principle guiding this RFC is that **the ability for chains to provide continual service is more important than the actual upgrade burden put on the developers of these chains**. This means some extra burden for application developers is tolerable if it minimizes or substantially reduces downtime for the end user. + +### Modes of Interprocess Communication + +Tendermint has two primary mechanisms to communicate with other processes: RPC and P2P. The division marks the boundary between the internal and external components of the network: + +- The P2P layer is used in all cases that nodes (of any type) need to communicate with one another. +- The RPC interface is for any outside process that wants to communicate with a node. + +The design principle here is that **communication via RPC is to a trusted source** and thus the RPC service prioritizes inspection rather than verification. The P2P interface is the primary medium for verification. + +As an example, an in-browser light client would verify headers (and perhaps application state) via the p2p layer, and then pass along information on to the client via RPC (or potentially directly via a separate API). + +The main exceptions to this are the IBC module and relayers, which are external to the node but also require verifiable data. Breaking changes to the light client verification path mean that all neighbouring chains that are connected will no longer be able to verify state transitions and thus pass messages back and forward. + +## Proposal + +Tendermint version labels will follow the syntax of [Semantic Versions 2.0.0](https://semver.org/) with a major, minor and patch version. The version components will be interpreted according to these rules: + +For the entire cycle of a **major version** in Tendermint: + +- All blocks and state data in a blockchain can be queried. All headers can be verified even across minor version changes. Nodes can both block sync and state sync from genesis to the head of the chain. +- Nodes in a network are able to communicate and perform BFT state machine replication so long as the agreed network version is the lowest of all nodes in a network. For example, nodes using version 1.5.x and 1.2.x can operate together so long as the network version is 1.2 or lower (but still within the 1.x range). This rule essentially captures the concept of network backwards compatibility. +- Node RPC endpoints will remain compatible with existing external clients: + - New endpoints may be added, but old endpoints may not be removed. + - Old endpoints may be extended to add new request and response fields, but requests not using those fields must function as before the change. +- Migrations should be automatic. Upgrading of one node can happen asynchronously with respect to other nodes (although agreement of a network-wide upgrade must still occur synchronously via consensus). + +For the entire cycle of a **minor version** in Tendermint: + +- Public Go API's, for example in `node` or `abci` packages will not change in a way that requires any consumer (not just application developers) to modify their code. +- No breaking changes to the block protocol. This means that all block related data structures should not change in a way that breaks any of the hashes, the consensus engine or light client verification. +- Upgrades between minor versions may not result in any downtime (i.e., no migrations are required), nor require any changes to the config files to continue with the existing behavior. A minor version upgrade will require only stopping the existing process, swapping the binary, and starting the new process. + +A new **patch version** of Tendermint will only contain bug fixes and updates that impact the security and stability of Tendermint. + +These guarantees will come into effect at release 1.0. + +## Status + +Proposed + +## Consequences + +### Positive + +- Clearer communication of what versioning means to us and the effect they have on our users. + +### Negative + +- Can potentially incur greater engineering effort to uphold and follow these guarantees. + +### Neutral + +## References + +- [SemVer](https://semver.org/) +- [Tendermint Tracking Issue](https://github.com/tendermint/tendermint/issues/5680) diff --git a/docs/rfc/tendermint-core/rfc-015-abci++-tx-mutation.md b/docs/rfc/tendermint-core/rfc-015-abci++-tx-mutation.md new file mode 100644 index 0000000..5302cd3 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-015-abci++-tx-mutation.md @@ -0,0 +1,259 @@ +# RFC 015: ABCI++ TX Mutation + +## Changelog + +- 23-Feb-2022: Initial draft (@williambanfield). +- 28-Feb-2022: Revised draft (@williambanfield). + +## Abstract + +A previous version of the ABCI++ specification detailed a mechanism for proposers to replace transactions +in the proposed block. This scheme required the proposer to construct new transactions +and mark these new transactions as replacing other removed transactions. The specification +was ambiguous as to how the replacement may be communicated to peer nodes. +This RFC discusses issues with this mechanism and possible solutions. + +## Background + +### What is the proposed change? + +A previous version of the ABCI++ specification proposed mechanisms for adding, removing, and replacing +transactions in a proposed block. To replace a transaction, the application running +`ProcessProposal` could mark a transaction as replaced by other application-supplied +transactions by returning a new transaction marked with the `ADDED` flag setting +the `new_hashes` field of the removed transaction to contain the list of transaction hashes +that replace it. In that previous specification for ABCI++, the full use of the +`new_hashes` field is left somewhat ambiguous. At present, these hashes are not +gossiped and are not eventually included in the block to signal replacement to +other nodes. The specification did indicate that the transactions specified in +the `new_hashes` field will be removed from the mempool but it's not clear how +peer nodes will learn about them. + +### What systems would be affected by adding transaction replacement? + +The 'transaction' is a central building block of a Tendermint blockchain, so adding +a mechanism for transaction replacement would require changes to many aspects of Tendermint. + +The following is a rough list of the functionality that this mechanism would affect: + +#### Transaction indexing + +Tendermint's indexer stores transactions and transaction results using the hash of the executed +transaction [as the key][tx-result-index] and the ABCI results and transaction bytes as the value. + +To allow transaction replacement, the replaced transactions would need to stored as well in the +indexer, likely as a mapping of original transaction to list of transaction hashes that replaced +the original transaction. + +#### Transaction inclusion proofs + +The result of a transaction query includes a Merkle proof of the existence of the +transaction in the block chain. This [proof is built][inclusion-proof] as a merkle tree +of the hashes of all of the transactions in the block where the queried transaction was executed. + +To allow transaction replacement, these proofs would need to be updated to prove +that a replaced transaction was included by replacement in the block. + +#### RPC-based transaction query parameters and results + +Tendermint's RPC allows clients to retrieve information about transactions via the +`/tx_search` and `/tx` RPC endpoints. + +RPC query results containing replaced transactions would need to be updated to include +information on replaced transactions, either by returning results for all of the replaced +transactions, or by including a response with just the hashes of the replaced transactions +which clients could proceed to query individually. + +#### Mempool transaction removal + +Additional logic would need to be added to the Tendermint mempool to clear out replaced +transactions after each block is executed. Tendermint currently removes executed transactions +from the mempool, so this would be a pretty straightforward change. + +## Discussion + +### What value may be added to Tendermint by introducing transaction replacement? + +Transaction replacement would would enable applications to aggregate or disaggregate transactions. + +For aggregation, a set of transactions that all related work, such as transferring +tokens between the same two accounts, could be replaced with a single transaction, +i.e. one that transfers a single sum from one account to the other. +Applications that make frequent use of aggregation may be able to achieve a higher throughput. +Aggregation would decrease the space occupied by a single client-submitted transaction in the block, allowing +more client-submitted transactions to be executed per block. + +For disaggregation, a very complex transaction could be split into multiple smaller transactions. +This may be useful if an application wishes to perform more fine-grained indexing on intermediate parts +of a multi-part transaction. + +### Drawbacks to transaction replacement + +Transaction replacement would require updating and shimming many of the places that +Tendermint records and exposes information about executed transactions. While +systems within Tendermint could be updated to account for transaction replacement, +such a system would leave new issues and rough edges. + +#### No way of guaranteeing correct replacement + +If a user issues a transaction to the network and the transaction is replaced, the +user has no guarantee that the replacement was correct. For example, suppose a set of users issue +transactions A, B, and C and they are all aggregated into a new transaction, D. +There is nothing guaranteeing that D was constructed correctly from the inputs. +The only way for users to ensure D is correct would be if D contained all of the +information of its constituent transactions, in which case, nothing is really gained by the replacement. + +#### Replacement transactions not signed by submitter + +Abstractly, Tendermint simply views transactions as a ball of bytes and therefore +should be fine with replacing one for another. However, many applications require +that transactions submitted to the chain be signed by some private key to authenticate +and authorize the transaction. Replaced transactions could not be signed by the +submitter, only by the application node. Therefore, any use of transaction replacement +could not contain authorization from the submitter and would either need to grant +application-submitted transactions power to perform application logic on behalf +of a user without their consent. + +Granting this power to application-submitted transactions would be very dangerous +and therefore might not be of much value to application developers. +Transaction replacement might only be really safe in the case of application-submitted +transactions or for transactions that require no authorization. For such transactions, +it's quite not quite clear what the utility of replacement is: the application can already +generate any transactions that it wants. The fact that such a transaction was a replacement +is not particularly relevant to participants in the chain since the application is +merely replacing its own transactions. + +#### New vector for censorship + +Depending on the implementation, transaction replacement may allow a node signal +to the rest of the chain that some transaction should no longer be considered for execution. +Honest nodes will use the replacement mechanism to signal that a transaction has been aggregated. +Malicious nodes will be granted a new vector for censoring transactions. +There is no guarantee that a replaced transactions is actually executed at all. +A malicious node could censor a transaction by simply listing it as replaced. +Honest nodes seeing the replacement would flush the transaction from their mempool +and not execute or propose it it in later blocks. + +### Transaction tracking implementations + +This section discusses possible ways to flesh out the implementation of transaction replacement. +Specifically, this section proposes a few alternative ways that Tendermint blockchains could +track and store transaction replacements. + +#### Include transaction replacements in the block + +One option to track transaction replacement is to include information on the +transaction replacement within the block. An additional structure may be added +the block of the following form: + +```proto +message Block { +... + repeated Replacement replacements = 5; +} + +message Replacement { + bytes included_tx_key = 1; + repeated bytes replaced_txs_keys = 2; +} +``` + +Applications executing `PrepareProposal` would return the list of replacements and +Tendermint would include an encoding of these replacements in the block that is gossiped +and committed. + +Tendermint's transaction indexing would include a new mapping for each replaced transaction +key to the committed transaction. +Transaction inclusion proofs would be updated to include these additional new transaction +keys in the Merkle tree and queries for transaction hashes that were replaced would return +information indicating that the transaction was replaced along with the hash of the +transaction that replaced it. + +Block validation of gossiped blocks would be updated to check that each of the +`included_txs_key` matches the hash of some transaction in the proposed block. + +Implementing the changes described in this section would allow Tendermint to gossip +and index transaction replacements as part of block propagation. These changes would +still require the application to certify that the replacements were valid. This +validation may be performed in one of two ways: + +1. **Applications optimistically trust that the proposer performed a legitimate replacement.** + +In this validation scheme, applications would not verify that the substitution +is valid during consensus and instead simply trust that the proposer is correct. +This would have the drawback of allowing a malicious proposer to remove transactions +it did not want executed. + +2. **Applications completely validate transaction replacement.** + +In this validation scheme, applications that allow replacement would check that +each listed replaced transaction was correctly reflected in the replacement transaction. +In order to perform such validation, the node would need to have the replaced transactions +locally. This could be accomplished one of a few ways: by querying the mempool, +by adding an additional p2p gossip channel for transaction replacements, or by including the replaced transactions +in the block. Replacement validation via mempool querying would require the node +to have received all of the replaced transactions in the mempool which is far from +guaranteed. Adding an additional gossip channel would make gossiping replaced transactions +a requirement for consensus to proceed, since all nodes would need to receive all replacement +messages before considering a block valid. Finally, including replaced transactions in +the block seems to obviate any benefit gained from performing a transaction replacement +since the replaced transaction and the original transactions would now both appear in the block. + +#### Application defined transaction replacement + +An additional option for allowing transaction replacement is to leave it entirely as a responsibility +of the application. The `PrepareProposal` ABCI++ call allows for applications to add +new transactions to a proposed block. Applications that wished to implement a transaction +replacement mechanism would be free to do so without the newly defined `new_hashes` field. +Applications wishing to implement transaction replacement would add the aggregated +transactions in the `PrepareProposal` response, and include one additional bookkeeping +transaction that listed all of the replacements, with a similar scheme to the `new_hashes` +field described in ABCI++. This new bookkeeping transaction could be used by the +application to determine which transactions to clear from the mempool in future calls +to `CheckTx`. + +The meaning of any transaction in the block is completely opaque to Tendermint, +so applications performing this style of replacement would not be able to have the replacement +reflected in any most of Tendermint's transaction tracking mechanisms, such as transaction indexing +and the `/tx` endpoint. + +#### Application defined Tx Keys + +Tendermint currently uses cryptographic hashes, SHA256, as a key for each transaction. +As noted in the section on systems that would require changing, this key is used +to identify the transaction in the mempool, in the indexer, and within the RPC system. + +An alternative approach to allowing `ProcessProposal` to specify a set of transaction +replacements would be instead to allow the application to specify an additional key or set +of keys for each transaction during `ProcessProposal`. This new `secondary_keys` set +would be included in the block and therefore gossiped during block propagation. +Additional RPC endpoints could be exposed to query by the application-defined keys. + +Applications wishing to implement replacement would leverage this new field by providing the +replaced transaction hashes as the `secondary_keys` and checking their validity during +`ProcessProposal`. During `RecheckTx` the application would then be responsible for +clearing out transactions that matched the `secondary_keys`. + +It is worth noting that something like this would be possible without `secondary_keys`. +An application wishing to implement a system like this one could define a replacement +transaction, as discussed in the section on application-defined transaction replacement, +and use a custom [ABCI event type][abci-event-type] to communicate that the replacement should +be indexed within Tendermint's ABCI event indexing. + +### Complexity to value-add tradeoff + +It is worth remarking that adding a system like this may introduce a decent amount +of new complexity into Tendermint. An approach that leaves much of the replacement +logic to Tendermint would require altering the core transaction indexing and querying +data. In many of the cases listed, a system for transaction replacement is possible +without explicitly defining it as part of `PrepareProposal`. Since applications +can now add transactions during `PrepareProposal` they can and should leverage this +functionality to include additional bookkeeping transactions in the block. It may +be worth encouraging applications to discover new and interesting ways to leverage this +power instead of immediately solving the problem for them. + +### References + +[inclusion-proof]: https://github.com/tendermint/tendermint/blob/0fcfaa4568cb700e27c954389c1fcd0b9e786332/types/tx.go#L67 +[tx-result-index]: https://github.com/tendermint/tendermint/blob/0fcfaa4568cb700e27c954389c1fcd0b9e786332/internal/state/indexer/tx/kv/kv.go#L90 +[abci-event-type]: https://github.com/tendermint/tendermint/blob/0fcfaa4568cb700e27c954389c1fcd0b9e786332/abci/types/types.pb.go#L3168 diff --git a/docs/rfc/tendermint-core/rfc-016-node-architecture.md b/docs/rfc/tendermint-core/rfc-016-node-architecture.md new file mode 100644 index 0000000..d801b97 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-016-node-architecture.md @@ -0,0 +1,83 @@ +# RFC 016: Node Architecture + +## Changelog + +- April 8, 2022: Initial draft (@cmwaters) +- April 15, 2022: Incorporation of feedback + +## Abstract + +The `node` package is the entry point into the Tendermint codebase, used both by the command line and programatically to create the nodes that make up a network. The package has suffered the most from the evolution of the codebase, becoming bloated as developers clipped on their bits of code here and there to get whatever feature they wanted working. + +The decisions made at the node level have the biggest impact to simplifying the protocols within them, unlocking better internal designs and making Tendermint more intuitive to use and easier to understand from the outside. Work, in minor increments, has already begun on this section of the codebase. This document exists to spark forth the necessary discourse in a few related areas that will help the team to converge on the long term makeup of the node. + +## Discussion + +The following is a list of points of discussion around the architecture of the node: + +### Dependency Tree + +The node object is currently stuffed with every component that possibly exists within Tendermint. In the constructor, all objects are built and interlaid with one another in some awkward dance. My guiding principle is that the node should only be made up of the components that it wants to have direct control of throughout its life. The node is a service which currently has the purpose of starting other services up in a particular order and stopping them all when commanded to do so. However, there are many services which are not direct dependents i.e. the mempool and evidence services should only be working when the consensus service is running. I propose to form more of a hierarchical structure of dependents which forces us to be clear about the relations that one component has to the other. More concretely, I propose the following dependency tree: + +![node dependency tree](./images/node-dependency-tree.svg) + +Many of the further discussion topics circle back to this representation of the node. + +It's also important to distinguish two dimensions which may require different characteristics of the architecture. There is the starting and stopping of services and their general lifecycle management. What is the correct order of operations to starting a node for example. Then there is the question of the needs of the service during actual operation. Then there is the question of what resources each service needs access to during its operation. Some need to publish events, others need access to data stores, and so forth. + +An alternative model and one that perhaps better suits the latter of these dimensions is the notion of an internal message passing system. Either the events bus or p2p layer could serve as a viable transport. This would essentially allow all services to communicate with any other service and could perhaps provide a solution to the coordination problem (presented below) without a centralized coordinator. The other main advantage is that such a system would be more robust to disruptions and changes to the code which may make a hierarchical structure quickly outdated and suboptimal. The addition of message routing is an added complexity to implement, will increase the degree of asynchronicity in the system and may make it harder to debug problems that are across multiple services. + +### Coordination of State Advancing Mechanisms + +Advancement of state in Tendermint is simply defined in heights: If the node is at height n, how does it get to height n + 1 and so on. Based on this definition we have three components that help a node to advance in height: consensus, statesync and blocksync. The way these components behave currently is very tightly coupled to one another with references passed back and forth. My guiding principle is that each of these should be able to operate completely independently of each other, e.g. a node should be able to run solely blocksync indefinitely. There have been several ideas suggested towards improving this flow. I've been leaning strongly towards a centralized system, whereby an orchestrator (in this case the node) decides what services to start and stop. +In a decentralized message passing system, individual services make their decision based upon a "global" shared state i.e. if my height is less that 10 below the average peer height, I as consensus, should stop (knowing that blocksync has the same condition for starting). As the example illustrates, each mechanism will still need to be aware of the presence of other mechanisms. + +Both centralized and decentralized systems rely on the communication of the nodes current height and a judgement on the height of the head of the chain. The latter, working out the head of the chain, is quite a difficult challenge as their is nothing preventing the node from acting maliciously and providing a different height. Currently both blocksync, consensus (and to a certain degree statesync), have parallel systems where peers communicate their height. This could be streamlined with the consensus (or even the p2p layer), broadcasting peer heights and either the node or the other state advancing mechanisms acting accordingly. + +Currently, when a node starts, it turns on every service that it is attached to. This means that while a node is syncing up by requesting blocks, it is also receiving transactions and votes, as well as snapshot and block requests. This is a needless use of bandwidth. An implementation of an orchestrator, regardless of whether the system is heirachical or not, should look to be able to open and close channels dynamically and effectively broadcast which services it is running. Integrating this with service discovery may also lead to a better serivce to peers. + +The orchestrator allows for some deal of variablity in how a node is constructed. Does it just run blocksync, shadowing the head of the chain and be highly available for querying. Does it rely on state sync at all? An important question that arises from this dynamicism is we ideally want to encourage nodes to provide as much of their resources as possible so that their is a healthy amount of providers to consumers. Do we make all services compulsory or allow for them to be disabled? Arguably it's possible that a user forks the codebase and rips out the blocksync code because they want to reduce bandwidth so this is more a question of how easy do we want to make this for users. + +### Block Executor + +The block executor is an important component that is currently used by both consensus and blocksync to execute transactions and update application state. Principally, I think it should be the only component that can write (and possibly even read) the block and state stores, and we should clean up other direct dependencies on the storage engine if we can. This would mean: + +- The reactors Consensus, BlockSync and StateSync should all import the executor for advancing state ie. `ApplyBlock` and `BootstrapState`. +- Pruning should also be a concern of the block executor as well as `FinalizeBlock` and `Commit`. This can simplify consensus to focus just on the consensus part. + +### The Interprocess communication systems: RPC, P2P, ABCI, and Events + +The schematic supplied above shows the relations between the different services, the node, the block executor, and the storage layer. Represented as colored dots are the components responsible for different roles of interprocess communication (IPC). These components permeate throughout the code base, seeping into most services. What can provide powerful functionality on one hand can also become a twisted vine, creating messy corner cases and convoluting the protocols themselves. A lot of the thinking around +how we want our IPC systens to function has been summarised in this [RFC](./rfc-002-ipc-ecosystem.md). In this section, I'd like to focus the reader on the relation between the IPC and the node structure. An issue that has frequently risen is that the RPC has control of the components where it strikes me as being more logical for the component to dictate the information that is emitted/available and the knobs it wishes to expose. The RPC is also inextricably tied to the node instance and has situations where it is passed pointers directly to the storage engine and other components. + +I am currently convinced of the approach that the p2p layer takes and would like to see other IPC components follow suit. This would mean that the RPC and events system would be constructed in the node yet would pass the adequate methods to register endpoints and topics to the sub components. For example, + +```go +// Methods from the RPC and event bus that would be passed into the constructor of components like "consensus" +// NOTE: This is a hypothetical construction to convey the idea. An actual implementation may differ. +func RegisterRoute(path string, handler func(http.ResponseWriter, *http.Request)) + +func RegisterTopic(name string) EventPublisher + +type EventPublisher func (context.Context, types.EventData, []abci.Event) +``` + +This would give the components control to the information they want to expose and keep all relevant logic within that package. It accomodates more to a dynamic system where services can switch on and off. Each component would also receive access to the logger and metrics system for introspection and debuggability. + +#### IPC Rubric + +I'd like to aim to reach a state where we as a team have either an implicit or explicit rubric which can determine, in the event of some new need to communicate information, what tool it should use for doing this. In the case of inter node communication, this is obviously the p2p stack (with perhaps the exception of the light client). Metrics and logging also have clear usage patterns. RPC and the events system are less clear. The RPC is used for debugging data and fine tuned operator control as it is for general public querying and transaction submission. The RPC is also known to have been plumbed back into the application for historical queries. The events system, similarly, is used for consuming transaction events as it is for the testing of consensus state transitions. + +Principally, I think we should look to change our language away from what the actual transport is and more towards what it's being used for and to whom. We call it a peer to peer layer and not the underlying tcp connection. In the same way, we should look to split RPC into an operator interface (RPC Internal), a public interface (RPC External) and a bidirectional ABCI. + +### Seperation of consumers and suppliers + +When a service such as blocksync is turned on, it automatically begins requesting blocks to verify and apply them as it also tries to serve them to other peers catching up. We should look to distinguish these two aspects: supplying of information and consuming of information in many of these components. More concretely, I'd suggest: + +- The blocksync and statesync service, i.e. supplying information for those trying to catch up should only start running once a node has caught up i.e. after running the blocksync and/or state sync *processes* +- The blocksync and state sync processes have defined termination clauses that inform the orchestrator when they are done and where they finished. + - One way of achieving this would be that every process both passes and returns the `State` object + - In some cases, a node may specify that it wants to run blocksync indefinitely. +- The mempool should also indicate whether it wants to receive transactions or to send them only (one-directional mempool) +- Similarly, the light client itself only requests information whereas the light client service (currently part of state sync) can do both. +- This distinction needs to be communicated in the p2p layer handshake itself but should also be changeable over the lifespan of the connection. diff --git a/docs/rfc/tendermint-core/rfc-017-abci++-vote-extension-propag.md b/docs/rfc/tendermint-core/rfc-017-abci++-vote-extension-propag.md new file mode 100644 index 0000000..6c00fa8 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-017-abci++-vote-extension-propag.md @@ -0,0 +1,571 @@ +# RFC 017: ABCI++ Vote Extension Propagation + +## Changelog + +- 11-Apr-2022: Initial draft (@sergio-mena). +- 15-Apr-2022: Addressed initial comments. First complete version (@sergio-mena). +- 09-May-2022: Addressed all outstanding comments. + +## Abstract + +According to the +[ABCI++ specification](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/abci%2B%2B/README.md) +(as of 11-Apr-2022), a validator MUST provide a signed vote extension for each non-`nil` precommit vote +of height *h* that it uses to propose a block in height *h+1*. When a validator is up to +date, this is easy to do, but when a validator needs to catch up this is far from trivial as this data +cannot be retrieved from the blockchain. + +This RFC presents and compares the different options to address this problem, which have been proposed +in several discussions by the Tendermint Core team. + +## Document Structure + +The RFC is structured as follows. In the [Background](#background) section, +subsections [Problem Description](#problem-description) and [Cases to Address](#cases-to-address) +explain the problem at hand from a high level perspective, i.e., abstracting away from the current +Tendermint implementation. In contrast, subsection +[Current Catch-up Mechanisms](#current-catch-up-mechanisms) delves into the details of the current +Tendermint code. + +In the [Discussion](#discussion) section, subsection [Solutions Proposed](#solutions-proposed) is also +worded abstracting away from implementation details, whilst subsections +[Feasibility of the Proposed Solutions](#feasibility-of-the-proposed-solutions) and +[Current Limitations and Possible Implementations](#current-limitations-and-possible-implementations) +analize the viability of one of the proposed solutions in the context of Tendermint's architecture +based on reactors. Finally, [Formalization Work](#formalization-work) briefly discusses the work +still needed demonstrate the correctness of the chosen solution. + +The high level subsections are aimed at readers who are familiar with consensus algorithms, in +particular with the one described in the Tendermint (white paper), but who are not necessarily +acquainted with the details of the Tendermint codebase. The other subsections, which go into +implementation details, are best understood by engineers with deep knowledge of the implementation of +Tendermint's blocksync and consensus reactors. + +## Background + +### Basic Definitions + +This document assumes that all validators have equal voting power for the sake of simplicity. This is done +without loss of generality. + +There are two types of votes in Tendermint: *prevotes* and *precommits*. Votes can be `nil` or refer to +a proposed block. This RFC focuses on precommits, +also known as *precommit votes*. In this document we sometimes call them simply *votes*. + +Validators send precommit votes to their peer nodes in *precommit messages*. According to the +[ABCI++ specification](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/abci%2B%2B/README.md), +a precommit message MUST also contain a *vote extension*. +This mandatory vote extension can be empty, but MUST be signed with the same key as the precommit +vote (i.e., the sending validator's). +Nevertheless, the vote extension is signed independently from the vote, so a vote can be separated from +its extension. +The reason for vote extensions to be mandatory in precommit messages is that, otherwise, a (malicious) +node can omit a vote extension while still providing/forwarding/sending the corresponding precommit vote. + +The validator set at height *h* is denoted *valseth*. A *commit* for height *h* consists of more +than *2nh/3* precommit votes voting for a block *b*, where *nh* denotes the size of +*valseth*. A commit does not contain `nil` precommit votes, and all votes in it refer to the +same block. An *extended commit* is a *commit* where every precommit vote has its respective vote extension +attached. + +### Problem Description + +In the version of [ABCI](https://github.com/tendermint/spec/blob/4fb99af/spec/abci/README.md) present up to +Tendermint v0.35, for any height *h*, a validator *v* MUST have the decided block *b* and a commit for +height *h* in order to decide at height *h*. Then, *v* just needs a commit for height *h* to propose at +height *h+1*, in the rounds of *h+1* where *v* is a proposer. + +In [ABCI++](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/abci%2B%2B/README.md), +the information that a validator *v* MUST have to be able to decide in *h* does not change with +respect to pre-existing ABCI: the decided block *b* and a commit for *h*. +In contrast, for proposing in *h+1*, a commit for *h* is not enough: *v* MUST now have an extended +commit. + +When a validator takes an active part in consensus at height *h*, it has all the data it needs in memory, +in its consensus state, to decide on *h* and propose in *h+1*. Things are not so easy in the cases when +*v* cannot take part in consensus because it is late (e.g., it falls behind, it crashes +and recovers, or it just starts after the others). If *v* does not take part, it cannot actively +gather precommit messages (which include vote extensions) in order to decide. +Before ABCI++, this was not a problem: full nodes are supposed to persist past blocks in the block store, +so other nodes would realise that *v* is late and send it the missing decided block at height *h* and +the corresponding commit (kept in block *h+1*) so that *v* can catch up. +However, we cannot apply this catch-up technique for ABCI++, as the vote extensions, which are part +of the needed *extended commit* are not part of the blockchain. + +### Cases to Address + +Before we tackle the description of the possible cases we need to address, let us describe the following +incremental improvement to the ABCI++ logic. Upon decision, a full node persists (e.g., in the block +store) the extended commit that allowed the node to decide. For the moment, let us assume the node only +needs to keep its *most recent* extended commit, and MAY remove any older extended commits from persistent +storage. +This improvement is so obvious that all solutions described in the [Discussion](#discussion) section use +it as a building block. Moreover, it completely addresses by itself some of the cases described in this +subsection. + +We now describe the cases (i.e. possible *runs* of the system) that have been raised in different +discussions and need to be addressed. They are (roughly) ordered from easiest to hardest to deal with. + +- **(a)** *Happy path: all validators advance together, no crash*. + + This case is included for completeness. All validators have taken part in height *h*. + Even if some of them did not manage to send a precommit message for the decided block, they all + receive enough precommit messages to be able to decide. As vote extensions are mandatory in + precommit messages, every validator *v* trivially has all the information, namely the decided block + and the extended commit, needed to propose in height *h+1* for the rounds in which *v* is the + proposer. + + No problem to solve here. + +- **(b)** *All validators advance together, then all crash at the same height*. + + This case has been raised in some discussions, the main concern being whether the vote extensions + for the previous height would be lost across the network. With the improvement described above, + namely persisting the latest extended commit at decision time, this case is solved. + When a crashed validator recovers, it recovers the last extended commit from persistent storage + and handshakes with the Application. + If need be, it also reconstructs messages for the unfinished height + (including all precommits received) from the WAL. + Then, the validator can resume where it was at the time of the crash. Thus, as extensions are + persisted, either in the WAL (in the form of received precommit messages), or in the latest + extended commit, the only way that vote extensions needed to start the next height could be lost + forever would be if all validators crashed and never recovered (e.g. disk corruption). + Since a *correct* node MUST eventually recover, this violates Tendermint's assumption of more than + *2nh/3* correct validators for every height *h*. + + No problem to solve here. + +- **(c)** *Lagging majority*. + + Let us assume the validator set does not change between *h* and *h+1*. + It is not possible by the nature of the Tendermint algorithm, which requires more + than *2nh/3* precommit votes for some round of height *h* in order to make progress. + So, only up to *nh/3* validators can lag behind. + + On the other hand, for the case where there are changes to the validator set between *h* and + *h+1* please see case (d) below, where the extreme case is discussed. + +- **(d)** *Validator set changes completely between* h *and* h+1. + + If sets *valseth* and *valseth+1* are disjoint, + more than *2nh/3* of validators in height *h* should + have actively participated in conensus in *h*. So, as of height *h*, only a minority of validators + in *h* can be lagging behind, although they could all lag behind from *h+1* on, as they are no + longer validators, only full nodes. This situation falls under the assumptions of case (h) below. + + As for validators in *valseth+1*, as they were not validators as of height *h*, they + could all be lagging behind by that time. However, by the time *h* finishes and *h+1* begins, the + chain will halt until more than *2nh+1/3* of them have caught up and started consensus + at height *h+1*. If set *valseth+1* does not change in *h+2* and subsequent + heights, only up to *nh+1/3* validators will be able to lag behind. Thus, we have + converted this case into case (h) below. + +- **(e)** *Enough validators crash to block the rest*. + + In this case, blockchain progress halts, i.e. surviving full nodes keep increasing rounds + indefinitely, until some of the crashed validators are able to recover. + Those validators that recover first will handshake with the Application and recover at the height + they crashed, which is still the same the nodes that did not crash are stuck in, so they don't need + to catch up. + Further, they had persisted the extended commit for the previous height. Nothing to solve. + + For those validators recovering later, we are in case (h) below. + +- **(f)** *Some validators crash, but not enough to block progress*. + + When the correct processes that crashed recover, they handshake with the Application and resume at + the height they were at when they crashed. As the blockchain did not stop making progress, the + recovered processes are likely to have fallen behind with respect to the progressing majority. + + At this point, the recovered processes are in case (h) below. + +- **(g)** *A new full node starts*. + + The reasoning here also applies to the case when more than one full node are starting. + When the full node starts from scratch, it has no state (its current height is 0). Ignoring + statesync for the time being, the node just needs to catch up by applying past blocks one by one + (after verifying them). + + Thus, the node is in case (h) below. + +- **(h)** *Advancing majority, lagging minority* + + In this case, some nodes are late. More precisely, at the present time, a set of full nodes, + denoted *Lhp*, are falling behind + (e.g., temporary disconnection or network partition, memory thrashing, crashes, new nodes) + an arbitrary + number of heights: + between *hs* and *hp*, where *hs < hp*, and + *hp* is the highest height + any correct full node has reached so far. + + The correct full nodes that reached *hp* were able to decide for *hp-1*. + Therefore, less than *nhp-1/3* validators of *hp-1* can be part + of *Lhp*, since enough up-to-date validators needed to actively participate + in consensus for *hp-1*. + + Since, at the present time, + no node in *Lhp* took part in any consensus between + *hs* and *hp-1*, + the reasoning above can be extended to validator set changes between *hs* and + *hp-1*. This results in the following restriction on the full nodes that can be part of *Lhp*. + + - ∀ *h*, where *hs ≤ h < hp*, + | *valseth* ∩ *Lhp* | *< nh/3* + + If this property does not hold for a particular height *h*, where + *hs ≤ h < hp*, Tendermint could not have progressed beyond *h* and + therefore no full node could have reached *hp* (a contradiction). + + These lagging nodes in *Lhp* need to catch up. They have to obtain the + information needed to make + progress from other nodes. For each height *h* between *hs* and *hp-2*, + this includes the decided block for *h*, and the + precommit votes also for *deciding h* (which can be extracted from the block at height *h+1*). + + At a given height *hc* (where possibly *hc << hp*), + a full node in *Lhp* will consider itself *caught up*, based on the + (maybe out of date) information it is getting from its peers. Then, the node needs to be ready to + propose at height *hc+1*, which requires having received the vote extensions for + *hc*. + As the vote extensions are *not* stored in the blocks, and it is difficult to have strong + guarantees on *when* a late node considers itself caught up, providing the late node with the right + vote extensions for the right height poses a problem. + +At this point, we have described and compared all cases raised in discussions leading up to this +RFC. The list above aims at being exhaustive. The analysis of each case included above makes all of +them converge into case (h). + +### Current Catch-up Mechanisms + +We now briefly describe the current catch-up mechanisms in the reactors concerned in Tendermint. + +#### Statesync + +Full nodes optionally run statesync just after starting, when they start from scratch. +If statesync succeeds, an Application snapshot is installed, and Tendermint jumps from height 0 directly +to the height the Application snapshop represents, without applying the block of any previous height. +Some light blocks are received and stored in the block store for running light-client verification of +all the skipped blocks. Light blocks are incomplete blocks, typically containing the header and the +canonical commit but, e.g., no transactions. They are stored in the block store as "signed headers". + +The statesync reactor is not really relevant for solving the problem discussed in this RFC. We will +nevertheless mention it when needed; in particular, to understand some corner cases. + +#### Blocksync + +The blocksync reactor kicks in after start up or recovery (and, optionally, after statesync is done) +and sends the following messages to its peers: + +- `StatusRequest` to query the height its peers are currently at, and +- `BlockRequest`, asking for blocks of heights the local node is missing. + +Using `BlockResponse` messages received from peers, the blocksync reactor validates each received +block using the block of the following height, saves the block in the block store, and sends the +block to the Application for execution. + +If blocksync has validated and applied the block for the height *previous* to the highest seen in +a `StatusResponse` message, or if no progress has been made after a timeout, the node considers +itself as caught up and switches to the consensus reactor. + +#### Consensus Reactor + +The consensus reactor runs the full Tendermint algorithm. For a validator this means it has to +propose blocks, and send/receive prevote/precommit messages, as mandated by Tendermint, before it can +decide and move on to the next height. + +If a full node that is running the consensus reactor falls behind at height *h*, when a peer node +realises this it will retrieve the canonical commit of *h+1* from the block store, and *convert* +it into a set of precommit votes and will send those to the late node. + +## Discussion + +### Solutions Proposed + +These are the solutions proposed in discussions leading up to this RFC. + +- **Solution 0.** *Vote extensions are made **best effort** in the specification*. + + This is the simplest solution, considered as a way to provide vote extensions in a simple enough + way so that it can be part of v0.36. + It consists in changing the specification so as to not *require* that precommit votes used upon + `PrepareProposal` contain their corresponding vote extensions. In other words, we render vote + extensions optional. + There are strong implications stemming from such a relaxation of the original specification. + + - As a vote extension is signed *separately* from the vote it is extending, an intermediate node + can now remove (i.e., censor) vote extensions from precommit messages at will. + - Further, there is no point anymore in the spec requiring the Application to accept a vote extension + passed via `VerifyVoteExtension` to consider a precommit message valid in its entirety. Remember + this behavior of `VerifyVoteExtension` is adding a constraint to Tendermint's conditions for + liveness. + In this situation, it is better and simpler to just drop the vote extension rejected by the + Application via `VerifyVoteExtension`, but still consider the precommit vote itself valid as long + as its signature verifies. + +- **Solution 1.** *Include vote extensions in the blockchain*. + + Another obvious solution, which has somehow been considered in the past, is to include the vote + extensions and their signatures in the blockchain. + The blockchain would thus include the extended commit, rather than a regular commit, as the structure + to be canonicalized in the next block. + With this solution, the current mechanisms implemented both in the blocksync and consensus reactors + would still be correct, as all the information a node needs to catch up, and to start proposing when + it considers itself as caught-up, can now be recovered from past blocks saved in the block store. + + This solution has two main drawbacks. + + - As the block format must change, upgrading a chain requires a hard fork. Furthermore, + all existing light client implementations will stop working until they are upgraded to deal with + the new format (e.g., how certain hashes calculated and/or how certain signatures are checked). + For instance, let us consider IBC, which relies on light clients. An IBC connection between + two chains will be broken if only one chain upgrades. + - The extra information (i.e., the vote extensions) that is now kept in the blockchain is not really + needed *at every height* for a late node to catch up. + - This information is only needed to be able to *propose* at the height the validator considers + itself as caught-up. If a validator is indeed late for height *h*, it is useless (although + correct) for it to call `PrepareProposal`, or `ExtendVote`, since the block is already decided. + - Moreover, some use cases require pretty sizeable vote extensions, which would result in an + important waste of space in the blockchain. + +- **Solution 2.** *Skip* propose *step in Tendermint algorithm*. + + This solution consists in modifying the Tendermint algorithm to skip the *send proposal* step in + heights where the node does not have the required vote extensions to populate the call to + `PrepareProposal`. The main idea behind this is that it should only happen when the validator is late + and, therefore, up-to-date validators have already proposed (and decided) for that height. + A small variation of this solution is, rather than skipping the *send proposal* step, the validator + sends a special *empty* or *bottom* (⊥) proposal to signal other nodes that it is not ready to propose + at (any round of) the current height. + + The appeal of this solution is its simplicity. A possible implementation does not need to extend + the data structures, or change the current catch-up mechanisms implemented in the blocksync or + in the consensus reactor. When we lack the needed information (vote extensions), we simply rely + on another correct validator to propose a valid block in other rounds of the current height. + + However, this solution can be attacked by a byzantine node in the network in the following way. + Let us consider the following scenario: + + - all validators in *valseth* send out precommit messages, with vote extensions, + for height *h*, round 0, roughly at the same time, + - all those precommit messages contain non-`nil` precommit votes, which vote for block *b* + - all those precommit messages sent in height *h*, round 0, and all messages sent in + height *h*, round *r > 0* get delayed indefinitely, so, + - all validators in *valseth* keep waiting for enough precommit + messages for height *h*, round 0, needed for deciding in height *h* + - an intermediate (malicious) full node *m* manages to receive block *b*, and gather more than + *2nh/3* precommit messages for height *h*, round 0, + - one way or another, the solution should have either (a) a mechanism for a full node to *tell* + another full node it is late, or (b) a mechanism for a full node to conclude it is late based + on other full nodes' messages; any of these mechanisms should, at the very least, + require the late node receiving the decided block and a commit (not necessarily an extended + commit) for *h*, + - node *m* uses the gathered precommit messages to build a commit for height *h*, round 0, + - in order to convince full nodes that they are late, node *m* either (a) *tells* them they + are late, or (b) shows them it (i.e. *m*) is ahead, by sending them block *b*, along with the + commit for height *h*, round 0, + - all full nodes conclude they are late from *m*'s behavior, and use block *b* and the commit for + height *h*, round 0, to decide on height *h*, and proceed to height *h+1*. + + At this point, *all* full nodes, including all validators in *valseth+1*, have advanced + to height *h+1* believing they are late, and so, expecting the *hypothetical* leading majority of + validators in *valseth+1* to propose for *h+1*. As a result, the blockhain + grinds to a halt. + A (rather complex) ad-hoc mechanism would need to be carried out by node operators to roll + back all validators to the precommit step of height *h*, round *r*, so that they can regenerate + vote extensions (remember vote extensions are non-deterministic) and continue execution. + +- **Solution 3.** *Require extended commits to be available at switching time*. + + This one is more involved than all previous solutions, and builds on an idea present in Solution 2: + vote extensions are actually not needed for Tendermint to make progress as long as the + validator is *certain* it is late. + + We define two modes. The first is denoted *catch-up mode*, and Tendermint only calls + `FinalizeBlock` for each height when in this mode. The second is denoted *consensus mode*, in + which the validator considers itself up to date and fully participates in consensus and calls + `PrepareProposal`/`ProcessProposal`, `ExtendVote`, and `VerifyVoteExtension`, before calling + `FinalizeBlock`. + + The catch-up mode does not need vote extension information to make progress, as all it needs is the + decided block at each height to call `FinalizeBlock` and keep the state-machine replication making + progress. The consensus mode, on the other hand, does need vote extension information when + starting every height. + + Validators are in consensus mode by default. When a validator in consensus mode falls behind + for whatever reason, e.g. cases (b), (d), (e), (f), (g), or (h) above, we introduce the following + key safety property: + + - for every height *hp*, a full node *f* in *hp* refuses to switch to catch-up + mode **until** there exists a height *h'* such that: + - *p* has received and (light-client) verified the blocks of + all heights *h*, where *hp ≤ h ≤ h'* + - it has received an extended commit for *h'* and has verified: + - the precommit vote signatures in the extended commit + - the vote extension signatures in the extended commit: each is signed with the same + key as the precommit vote it extends + + If the condition above holds for *hp*, namely receiving a valid sequence of blocks in + the *f*'s future, and an extended commit corresponding to the last block in the sequence, then + node *f*: + + - switches to catch-up mode, + - applies all blocks between *hp* and *h'* (calling `FinalizeBlock` only), and + - switches back to consensus mode using the extended commit for *h'* to propose in the rounds of + *h' + 1* where it is the proposer. + + This mechanism, together with the invariant it uses, ensures that the node cannot be attacked by + being fed a block without extensions to make it believe it is late, in a similar way as explained + for Solution 2. + +### Feasibility of the Proposed Solutions + +Solution 0, besides the drawbacks described in the previous section, provides guarantees that are +weaker than the rest. The Application does not have the assurance that more than *2nh/3* vote +extensions will *always* be available when calling `PrepareProposal` at height *h+1*. +This level of guarantees is probably not strong enough for vote extensions to be useful for some +important use cases that motivated them in the first place, e.g., encrypted mempool transactions. + +Solution 1, while being simple in that the changes needed in the current Tendermint codebase would +be rather small, is changing the block format, and would therefore require all blockchains using +Tendermint v0.35 or earlier to hard-fork when upgrading to v0.36. + +Since Solution 2 can be attacked, one might prefer Solution 3, even if it is more involved +to implement. Further, we must elaborate on how we can turn Solution 3, described in abstract +terms in the previous section, into a concrete implementation compatible with the current +Tendermint codebase. + +### Current Limitations and Possible Implementations + +The main limitations affecting the current version of Tendermint are the following. + +- The current version of the blocksync reactor does not use the full + [light client verification](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/light-client/README.md) + algorithm to validate blocks coming from other peers. +- The code being structured into the blocksync and consensus reactors, only switching from the + blocksync reactor to the consensus reactor is supported; switching in the opposite direction is + not supported. Alternatively, the consensus reactor could have a mechanism allowing a late node + to catch up by skipping calls to `PrepareProposal`/`ProcessProposal`, and + `ExtendVote`/`VerifyVoteExtension` and only calling `FinalizeBlock` for each height. + Such a mechanism does not exist at the time of writing this RFC. + +The blocksync reactor featuring light client verification is being actively worked on (tentatively +for v0.37). So it is best if this RFC does not try to delve into that problem, but just makes sure +its outcomes are compatible with that effort. + +In subsection [Cases to Address](#cases-to-address), we concluded that we can focus on +solving case (h) in theoretical terms. +However, as the current Tendermint version does not yet support switching back to blocksync once a +node has switched to consensus, we need to split case (h) into two cases. When a full node needs to +catch up... + +- **(h.1)** ... it has not switched yet from the blocksync reactor to the consensus reactor, or + +- **(h.2)** ... it has already switched to the consensus reactor. + +This is important in order to discuss the different possible implementations. + +#### Base Implementation: Persist and Propagate Extended Commit History + +In order to circumvent the fact that we cannot switch from the consensus reactor back to blocksync, +rather than just keeping the few most recent extended commits, nodes will need to keep +and gossip a backlog of extended commits so that the consensus reactor can still propose and decide +in out-of-date heights (even if those proposals will be useless). + +The base implementation - for which an experimental patch exists - consists in the conservative +approach of persisting in the block store *all* extended commits for which we have also stored +the full block. Currently, when statesync is run at startup, it saves light blocks. +This base implementation does not seek +to receive or persist extended commits for those light blocks as they would not be of any use. + +Then, we modify the blocksync reactor so that peers *always* send requested full blocks together +with the corresponding extended commit in the `BlockResponse` messages. This guarantees that the +block store being reconstructed by blocksync has the same information as that of peers that are +up to date (at least starting from the latest snapshot applied by statesync before starting blocksync). +Thus, blocksync has all the data it requires to switch to the consensus reactor, as long as one of +the following exit conditions are met: + +- The node is still at height 0 (where no commit or extended commit is needed) +- The node has processed at least 1 block in blocksync + +The second condition is needed in case the node has installed an Application snapshot during statesync. +If that is the case, at the time blocksync starts, the block store only has the data statesync has saved: +light blocks, and no extended commits. +Hence we need to blocksync at least one block from another node, which will be sent with its corresponding extended commit, before we can switch to consensus. + +As a side note, a chain might be started at a height *hi > 0*, all other heights +*h < hi* being non-existent. In this case, the chain is still considered to be at height 0 before +block *hi* is applied, so the first condition above allows the node to switch to consensus even +if blocksync has not processed any block (which is always the case if all nodes are starting from scratch). + +When a validator falls behind while having already switched to the consensus reactor, a peer node can +simply retrieve the extended commit for the required height from the block store and reconstruct a set of +precommit votes together with their extensions and send them in the form of precommit messages to the +validator falling behind, regardless of whether the peer node holds the extended commit because it +actually participated in that consensus and thus received the precommit messages, or it received the extended commit via a `BlockResponse` message while running blocksync. + +This solution requires a few changes to the consensus reactor: + +- upon saving the block for a given height in the block store at decision time, save the + corresponding extended commit as well +- in the catch-up mechanism, when a node realizes that another peer is more than 2 heights + behind, it uses the extended commit (rather than the canoncial commit as done previously) to + reconstruct the precommit votes with their corresponding extensions + +The changes to the blocksync reactor are more substantial: + +- the `BlockResponse` message is extended to include the extended commit of the same height as + the block included in the response (just as they are stored in the block store) +- structure `bpRequester` is likewise extended to hold the received extended commits coming in + `BlockResponse` messages +- method `PeekTwoBlocks` is modified to also return the extended commit corresponding to the first block +- when successfully verifying a received block, the reactor saves its corresponding extended commit in + the block store + +The two main drawbacks of this base implementation are: + +- the increased size taken by the block store, in particular with big extensions +- the increased bandwith taken by the new format of `BlockResponse` + +#### Possible Optimization: Pruning the Extended Commit History + +If we cannot switch from the consensus reactor back to the blocksync reactor we cannot prune the extended commit backlog in the block store without sacrificing the implementation's correctness. The asynchronous +nature of our distributed system model allows a process to fall behing an arbitrary number of +heights, and thus all extended commits need to be kept *just in case* a node that late had +previously switched to the consensus reactor. + +However, there is a possibility to optimize the base implementation. Every time we enter a new height, +we could prune from the block store all extended commits that are more than *d* heights in the past. +Then, we need to handle two new situations, roughly equivalent to cases (h.1) and (h.2) described above. + +- (h.1) A node starts from scratch or recovers after a crash. In thisy case, we need to modify the + blocksync reactor's base implementation. + - when receiving a `BlockResponse` message, it MUST accept that the extended commit set to `nil`, + - when sending a `BlockResponse` message, if the block store contains the extended commit for that + height, it MUST set it in the message, otherwise it sets it to `nil`, + - the exit conditions used for the base implementation are no longer valid; the only reliable exit + condition now consists in making sure that the last block processed by blocksync was received with + the corresponding commit, and not `nil`; this extended commit will allow the node to switch from + the blocksync reactor to the consensus reactor and immediately act as a proposer if required. +- (h.2) A node already running the consensus reactor falls behind beyond *d* heights. In principle, + the node will be stuck forever as no other node can provide the vote extensions it needs to make + progress (they all have pruned the corresponding extended commit). + However we can manually have the node crash and recover as a workaround. This effectively converts + this case into (h.1). + +### Formalization Work + +A formalization work to show or prove the correctness of the different use cases and solutions +presented here (and any other that may be found) needs to be carried out. +A question that needs a precise answer is how many extended commits (one?, two?) a node needs +to keep in persistent memory when implementing Solution 3 described above without Tendermint's +current limitations. +Another important invariant we need to prove formally is that the set of vote extensions +required to make progress will always be held somewhere in the network. + +## References + +- [ABCI++ specification](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/abci%2B%2B/README.md) +- [ABCI as of v0.35](https://github.com/tendermint/spec/blob/4fb99af/spec/abci/README.md) +- [Vote extensions issue](https://github.com/tendermint/tendermint/issues/8174) +- [Light client verification](https://github.com/tendermint/tendermint/blob/4743a7ad0/spec/light-client/README.md) diff --git a/docs/rfc/tendermint-core/rfc-018-bls-agg-exploration.md b/docs/rfc/tendermint-core/rfc-018-bls-agg-exploration.md new file mode 100644 index 0000000..0b1868a --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-018-bls-agg-exploration.md @@ -0,0 +1,551 @@ +# RFC 018: BLS Signature Aggregation Exploration + +## Changelog + +- 01-April-2022: Initial draft (@williambanfield). +- 15-April-2022: Draft complete (@williambanfield). + +## Abstract + +## Background + +### Glossary + +The terms that are attached to these types of cryptographic signing systems +become confusing quickly. Different sources appear to use slightly different +meanings of each term and this can certainly add to the confusion. Below is +a brief glossary that may be helpful in understanding the discussion that follows. + +- **Short Signature**: A signature that does not vary in length with the +number of signers. +- **Multi-Signature**: A signature generated over a single message +where, given the message and signature, a verifier is able to determine that +all parties signed the message. May be short or may vary with the number of signers. +- **Aggregated Signature**: A _short_ signature generated over messages with +possibly different content where, given the messages and signature, a verifier +should be able to determine that all the parties signed the designated messages. +- **Threshold Signature**: A _short_ signature generated from multiple signers +where, given a message and the signature, a verifier is able to determine that +a large enough share of the parties signed the message. The identities of the +parties that contributed to the signature are not revealed. +- **BLS Signature**: An elliptic-curve pairing-based signature system that +has some nice properties for short multi-signatures. May stand for +_Boneh-Lynn-Schacham_ or _Barreto-Lynn-Scott_ depending on the context. A +BLS signature is type of signature scheme that is distinct from other forms +of elliptic-curve signatures such as ECDSA and EdDSA. +- **Interactive**: Cryptographic scheme where parties need to perform one or +more request-response cycles to produce the cryptographic material. For +example, an interactive signature scheme may require the signer and the +verifier to cooperate to create and/or verify the signature, rather than a +signature being created ahead of time. +- **Non-interactive**: Cryptographic scheme where parties do not need to +perform any request-response cycles to produce the cryptographic material. + +### Brief notes on pairing-based elliptic-curve cryptography + +Pairing-based elliptic-curve cryptography is quite complex and relies on several +types of high-level math. Cryptography, in general, relies on being able to find +problems with an asymmetry between the difficulty of calculating the solution +and verifying that a given solution is correct. + +Pairing-based cryptography works by operating on mathematical functions that +satisfy the property of **bilinear mapping**. This property is satisfied for +functions `e` with values `P`, `Q`, `R` and `S` where `e(P, Q + R) = e(P, Q) * e(P, R)` +and `e(P + S, Q) = e(P, Q) * e(S, Q)`. The most familiar example of this is +exponentiation. Written in common notation, `g^P*(Q+R) = g^(P*Q) * g^(P*R)` for +some value `g`. + +Pairing-based elliptic-curve cryptography creates a bilinear mapping using +elliptic curves over a finite field. With some original curve, you can define two groups, +`G1` and `G2` which are points of the original curve _modulo_ different values. +Finally, you define a third group `Gt`, where points from `G1` and `G2` satisfy +the property of bilinearity with `Gt`. In this scheme, the function `e` takes +as inputs points in `G1` and `G2` and outputs values in `Gt`. Succintly, given +some point `P` in `G1` and some point `Q` in `G1`, `e(P, Q) = C` where `C` is in `Gt`. +You can efficiently compute the mapping of points in `G1` and `G2` into `Gt`, +but you cannot efficiently determine what points were summed and paired to +produce the value in `Gt`. + +Functions are then defined to map digital signatures, messages, and keys into +and out of points of `G1` or `G2` and signature verification is the process +of calculating if a set of values representing a message, public key, and digital +signature produce the same value in `Gt` through `e`. + +Signatures can be created as either points in `G1` with public keys being +created as points in `G2` or vice versa. For the case of BLS12-381, the popular +curve used, points in `G1` are represented with 48 bytes and points in `G2` are +represented with 96 bytes. It is up to the implementer of the cryptosystem to +decide which should be larger, the public keys or the signatures. + +BLS signatures rely on pairing-based elliptic-curve cryptography to produce +various types of signatures. For a more in-depth but still high level discussion +pairing-based elliptic-curve cryptography, see Vitalik Buterin's post on +[Exploring Elliptic Curve Pairings][vitalik-pairing-post]. For much more in +depth discussion, see the specific paper on BLS12-381, [Short signatures from + the Weil Pairing][bls-weil-pairing] and +[Compact Multi-Signatures for Smaller Blockchains][multi-signatures-smaller-blockchains]. + +### Adoption + +BLS signatures have already gained traction within several popular projects. + +- Algorand is working on an implementation. +- [Zcash][zcash-adoption] has adopted BLS12-381 into the protocol. +- [Ethereum 2.0][eth-2-adoption] has adopted BLS12-381 into the protocol. +- [Chia Network][chia-adoption] has adopted BLS for signing blocks. +- [Ostracon][line-ostracon-pr], a fork of Tendermint has adopted BLS for signing blocks. + +### What systems may be affected by adding aggregated signatures? + +#### Gossip + +Gossip could be updated to aggregate vote signatures during a consensus round. +This appears to be of frankly little utility. Creating an aggregated signature +incurs overhead, so frequently re-aggregating may incur a significant +overhead. How costly this is is still subject to further investigation and +performance testing. + +Even if vote signatures were aggregated before gossip, each validator would still +need to receive and verify vote extension data from each (individual) peer validator in +order for consensus to proceed. That displaces any advantage gained by aggregating signatures across the vote message in the presence of vote extensions. + +#### Block Creation + +When creating a block, the proposer may create a small set of short +multi-signatures and attach these to the block instead of including one +signature per validator. + +#### Block Verification + +Currently, we verify each validator signature using the public key associated +with that validator. With signature aggregation, verification of blocks would +not verify many signatures individually, but would instead check the (single) +multi-signature using the public keys stored by the validator. This would also +require a mechanism for indicating which validators are included in the +aggregated signature. + +#### IBC Relaying + +IBC would no longer need to transmit a large set of signatures when +updating state. These state updates do not happen for every IBC packet, only +when changing an IBC light client's view of the counterparty chain's state. +General [IBC packets][ibc-packet] only contain enough information to correctly +route the data to the counterparty chain. + +IBC does persist commit signatures to the chain in these `MsgUpdateClient` +message when updating state. This message would no longer need the full set +of unique signatures and would instead only need one signature for all of the +data in the header. + +Adding BLS signatures would create a new signature type that must be +understood by the IBC module and by the relayers. For some operations, such +as state updates, the set of data written into the chain and received by the +IBC module could be slightly smaller. + +## Discussion + +### What are the proposed benefits to aggregated signatures? + +#### Reduce Block Size + +At the moment, a commit contains a 64-byte (512-bit) signature for each validator +that voted for the block. For the Cosmos Hub, which has 175 validators in the +active set, this amounts to about 11 KiB per block. That gives an upper bound of +around 113 GiB over the lifetime of the chain's 10.12M blocks. (Note, the Hub has +increased the number of validators in the active set over time so the total +signature size over the history of the chain is likely somewhat less than that). + +Signature aggregation would only produce two signatures for the entire block. +One for the yeas and one for the nays. Each BLS aggregated signature is 48 +bytes, per the [IETF standard of BLS signatures][bls-ietf-ecdsa-compare]. +Over the lifetime of the same Cosmos Hub chain, that would amount to about 1 +GB, a savings of 112 GB. While that is a large factor of reduction it's worth +bearing in mind that, at [GCP's cost][gcp-storage-pricing] of $.026 USD per GB, +that is a total savings of around $2.50 per month. + +#### Reduce Signature Creation and Verification Time + +From the [IETF draft standard on BLS Signatures][bls-ietf], BLS signatures can be +created in 370 microseconds and verified in 2700 microseconds. Our current +[Ed25519 implementation][voi-ed25519-perf] was benchmarked locally to take +13.9 microseconds to produce a signature and 2.03 milliseconds to batch verify +128 signatures, which is slightly fewer than the 175 in the Hub. blst, a popular +implementation of BLS signature aggregation was benchmarked to perform verification +on 100 signatures in 1.5 milliseconds [when run locally][blst-verify-bench] +on an 8 thread machine and pre-aggregated public keys. It is worth noting that +the `ed25519` library verification time grew steadily with the number of signatures, +whereas the bls library verification time remains constant. This is because the +number of operations used to verify a signature does not grow at all with the +number of signatures included in the aggregate signature (as long as the signers +signed over the same message data as is the case in Tendermint). + +It is worth noting that this would also represent a _degredation_ in signature +verification time for chains with small validator sets. When batch verifying +only 32 signatures, our ed25519 library takes .57 milliseconds, whereas BLS +would still require the same 1.5 milliseconds. + +For massive validator sets, blst dominates, taking the same 1.5 milliseconds to +check an aggregated signature from 1024 validators versus our ed25519 library's +13.066 milliseconds to batch verify a set of that size. + +#### Reduce Light-Client Verification Time + +The light client aims to be a faster and lighter-weight way to verify that a +block was voted on by a Tendermint network. The light client fetches +Tendermint block headers and commit signatures, performing public key +verification to ensure that the associated validator set signed the block. +Reducing the size of the commit signature would allow the light client to fetch +block data more quickly. + +Additionally, the faster signature verification times of BLS signatures mean +that light client verification would proceed more quickly. + +However, verification of an aggregated signature is all-or-nothing. The verifier +cannot check that some singular signer had a signature included in the block. +Instead, the verifier must use all public keys to check if some signature +was included. This does mean that any light client implementation must always +be able to fetch all public keys for any height instead of potentially being +able to check if some singular validator's key signed the block. + +#### Reduce Gossip Bandwidth + +##### Vote Gossip + +It is possible to aggregate subsets of signatures during voting, so that the +network need not gossip all _n_ validator signatures to all _n_ validators. +Theoretically, subsets of the signatures could be aggregated during consensus +and vote messages could carry those aggregated signatures. Implementing this +would certainly increase the complexity of the gossip layer but could possibly +reduce the total number of signatures required to be verified by each validator. + +##### Block Gossip + +A reduction in the block size as a result of signature aggregation would +naturally lead to a reduction in the bandwidth required to gossip a block. +Each validator would only send and receive the smaller aggregated signatures +instead of the full list of multi-signatures as we have them now. + +### What are the drawbacks to aggregated signatures? + +#### Heterogeneous key types cannot be aggregated + +Aggregation requires a specific signature algorithm, and our legacy signing schemes +cannot be aggregated. In practice, this means that aggregated signatures could +be created for a subset of validators using BLS signatures, and validators +with other key types (such as Ed25519) would still have to be be separately +propagated in blocks and votes. + +#### Many HSMs do not support aggregated signatures + +**Hardware Signing Modules** (HSM) are a popular way to manage private keys. +They provide additional security for key management and should be used when +possible for storing highly sensitive private key material. + +Below is a list of popular HSMs along with their support for BLS signatures. + +- YubiKey + - [No support][yubi-key-bls-support] +- Amazon Cloud HSM + - [No support][cloud-hsm-support] +- Ledger + - [Lists support for the BLS12-381 curve][ledger-bls-announce] + +I cannot find support listed for Google Cloud, although perhaps it exists. + +## Feasibility of implementation + +This section outlines the various hurdles that would exist to implementing BLS +signature aggregation into Tendermint. It aims to demonstrate that we _could_ +implement BLS signatures but that it would incur risk and require breaking changes for a +reasonably unclear benefit. + +### Can aggregated signatures be added as soft-upgrades? + +In my estimation, yes. With the implementation of proposer-based timestamps, +all validators now produce signatures on only one of two messages: + +1. A [CanonicalVote][canonical-vote-proto] where the BlockID is the hash of the block or +2. A `CanonicalVote` where the `BlockID` is nil. + +The block structure can be updated to perform hashing and validation in a new +way as a soft upgrade. This would look like adding a new section to the [Block.Commit][commit-proto] structure +alongside the current `Commit.Signatures` field. This new field, tentatively named +`AggregatedSignature` would contain the following structure: + +```proto +message AggregatedSignature { + // yeas is a BitArray representing which validators in the active validator + // set issued a 'yea' vote for the block. + tendermint.libs.bits.BitArray yeas = 1; + + // absent is a BitArray representing which validators in the active + // validator set did not issue votes for the block. + tendermint.libs.bits.BitArray absent = 2; + + // yea_signature is an aggregated signature produced from all of the vote + // signatures for the block. + repeated bytes yea_signature = 3; + + // nay_signature is an aggregated signature produced from all of the vote + // signatures from votes for 'nil' for this block. + // nay_signature should be made from all of the validators that were both not + // in the 'yeas' BitArray and not in the 'absent' BitArray. + repeated bytes nay_signature = 4; +} +``` + +Adding this new field as a soft upgrade would mean hashing this data structure +into the blockID along with the old `Commit.Signatures` when both are present +as well as ensuring that the voting power represented in the new +`AggregatedSignature` and `Signatures` field was enough to commit the block +during block validation. One can certainly imagine other possible schemes for +implementing this but the above should serve as a simple enough proof of concept. + +### Implementing vote-time and commit-time signature aggregation separately + +Implementing aggregated BLS signatures as part of the block structure can easily be +achieved without implementing any 'vote-time' signature aggregation. +The block proposer would gather all of the votes, complete with signatures, +as it does now, and produce a set of aggregate signatures from all of the +individual vote signatures. + +Implementing 'vote-time' signature aggregation cannot be achieved without +also implementing commit-time signature aggregation. This is because such +signatures cannot be dis-aggregated into their constituent pieces. Therefore, +in order to implement 'vote-time' signature aggregation, we would need to +either first implement 'commit-time' signature aggregation, or implement both +'vote-time' signature aggregation while also updating the block creation and +verification protocols to allow for aggregated signatures. + +### Updating IBC clients + +In order for IBC clients to function, they must be able to perform light-client +verification of blocks on counterparty chains. Because BLS signatures are not +currently part of light-clients, chains that transmit messages over IBC +cannot update to using BLS signatures without their counterparties first +being upgraded to parse and verify BLS. If chains upgrade without their +counterparties first updating, they will lose the ability to interoperate with +non-updated chains. + +### New attack surfaces + +BLS signatures and signature aggregation comes with a new set of attack surfaces. +Additionally, it's not clear that all possible major attacks are currently known +on the BLS aggregation schemes since new ones have been discovered since the ietf +draft standard was written. The known attacks are manageable and are listed below. +Our implementation would need to prevent against these but this does not appear +to present a significant hurdle to implementation. + +#### Rogue key attack prevention + +Generating an aggregated signature requires guarding against what is called +a [rogue key attack][bls-ietf-terms]. A rogue key attack is one in which a +malicious actor can craft an _aggregate_ key that can produce signatures that +appear to include a signature from a private key that the malicious actor +does not actually know. In Tendermint terms, this would look like a Validator +producing a vote signed by both itself and some other validator where the other +validator did not actually produce the vote itself. + +The main mechanisms for preventing this require that each entity prove that it +can can sign data with just their private key. The options involve either +ensuring that each entity sign a _different_ message when producing every +signature _or_ producing a [proof of possession][bls-ietf-pop] (PoP) when announcing +their key to the network. + +A PoP is a message that demonstrates ownership of a private +key. A simple scheme for PoP is one where the entity announcing +its new public key to the network includes a digital signature over the bytes +of the public key generated using the associated private key. Everyone receiving +the public key and associated proof-of-possession can easily verify the +signature and be sure the entity owns the private key. + +This PoP scheme suits the Tendermint use case quite well since +validator keys change infrequently so the associated PoPs would not be onerous +to produce, verify, and store. Using this scheme allows signature verification +to proceed more quickly, since all signatures are over identical data and +can therefore be checked using an aggregated public key instead of one at a +time, public key by public key. + +#### Summing Zero Attacks + +[Summing zero attacks][summing-zero-paper] are attacks that rely on using the '0' point of an +elliptic curve. For BLS signatures, if the point 0 is chosen as the private +key, then the 0 point will also always be the public key and all signatures +produced by the key will also be the 0 point. This is easy enough to +detect when verifying each signature individually. + +However, because BLS signature aggregation creates an aggregated signature and +an aggregated public key, a set of colluding signers can create a pair or set +of signatures that are non-zero but which aggregate ("sum") to 0. The signatures that sum zero along with the +summed public key of the colluding signers will verify any message. This would +allow the colluding signers to sign any block or message with the same signature. +This would be reasonably easy to detect and create evidence for because, in +all other cases, the same signature should not verify more than message. It's +not exactly clear how such an attack would advantage the colluding validators +because the normal mechanisms of evidence gathering would still detect the +double signing, regardless of the signatures on both blocks being identical. + +### Backwards Compatibility + +Backwards compatibility is an important consideration for signature verification. +Specifically, it is important to consider whether chains using current versions +of IBC would be able to interact with chains adopting BLS. + +Because the `Block` shared by IBC and Tendermint is produced and parsed using +protobuf, new structures can be added to the Block without breaking the +ability of legacy users to parse the new structure. Breaking changes between +current users of IBC and new Tendermint blocks only occur if data that is +relied upon by the current users is no longer included in the current fields. + +For the case of BLS aggregated signatures, a new `AggregatedSignature` field +can therefore be added to the `Commit` field without breaking current users. +Current users will be broken when counterparty chains upgrade to the new version +and _begin using_ BLS signatures. Once counterparty chains begin using BLS +signatures, the BlockID hashes will include hashes of the `AggregatedSignature` +data structure that the legacy users will not be able to compute. Additionally, +the legacy software will not be able to parse and verify the signatures to +ensure that a supermajority of validators from the counterparty chain signed +the block. + +### Library Support + +Libraries for BLS signature creation are limited in number, although active +development appears to be ongoing. Cryptographic algorithms are difficult to +implement correctly and correctness issues are extremely serious and dangerous. +No further exploration of BLS should be undertaken without strong assurance of +a well-tested library with continuing support for creating and verifying BLS +signatures. + +At the moment, there is one candidate, `blst`, that appears to be the most +mature and well vetted. While this library is undergoing continuing auditing +and is supported by funds from the Ethereum foundation, adopting a new cryptographic +library presents some serious risks. Namely, if the support for the library were +to be discontinued, Tendermint may become saddled with the requirement of supporting +a very complex piece of software or force a massive ecosystem-wide migration away +from BLS signatures. + +This is one of the more serious reasons to avoid adopting BLS signatures at this +time. There is no gold standard library. Some projects look promising, but no +project has been formally verified with a long term promise of being supported +well into the future. + +#### Go Standard Library + +The Go Standard library has no implementation of BLS signatures. + +#### BLST + +[blst][blst], or 'blast' is an implementation of BLS signatures written in C +that provides bindings into Go as part of the repository. This library is +actively undergoing formal verification by Galois and previously received an +initial audit by NCC group, a firm I'd never heard of. + +`blst` is [targeted for use in prysm][prysm-blst], the golang implementation of Ethereum 2.0. + +#### Gnark-Crypto + +[Gnark-Crypto][gnark] is a Go-native implementation of elliptic-curve pairing-based +cryptography. It is not audited and is documented as 'as-is', although +development appears to be active so formal verification may be forthcoming. + +#### CIRCL + +[CIRCL][circl] is a go-native implementation of several cryptographic primitives, +bls12-381 among them. The library is written and maintained by Cloudflare and +appears to receive frequent contributions. However, it lists itself as experimental +and urges users to take caution before using it in production. + +### Added complexity to light client verification + +Implementing BLS signature aggregation in Tendermint would pose issues for the +light client. The light client currently validates a subset of the signatures +on a block when performing the verification algorithm. This is no longer possible +with an aggregated signature. Aggregated signature verification is all-or-nothing. +The light client could no longer check that a subset of validators from some +set of validators is represented in the signature. Instead, it would need to create +a new aggregated key with all the stated signers for each height it verified where +the validator set changed. + +This means that the speed advantages gained by using BLS cannot be fully realized +by the light client since the client needs to perform the expensive operation +of re-aggregating the public key. Aggregation is _not_ constant time in the +number of keys and instead grows linearly. When [benchmarked locally][blst-verify-bench-agg], +blst public key aggregation of 128 keys took 2.43 milliseconds. This, along with +the 1.5 milliseconds to verify a signature would raise light client signature +verification time to 3.9 milliseconds, a time above the previously mentioned +batch verification time using our ed25519 library of 2.0 milliseconds. + +Schemes to cache aggregated subsets of keys could certainly cut this time down at the +cost of adding complexity to the light client. + +### Added complexity to evidence handling + +Implementing BLS signature aggregation in Tendermint would add complexity to +the evidence handling within Tendermint. Currently, the light client can submit +evidence of a fork attempt to the chain. This evidence consists of the set of +validators that double-signed, including their public keys, with the conflicting +block. + +We can quickly check that the listed validators double signed by verifying +that each of their signatures are in the submitted conflicting block. A BLS +signature scheme would change this by requiring the light client to submit +the public keys of all of the validators that signed the conflicting block so +that the aggregated signature may be checked against the full signature set. +Again, aggregated signature verification is all-or-nothing, so without all of +the public keys, we cannot verify the signature at all. These keys would be +retrievable. Any party that wanted to create a fork would want to convince a +network that its fork is legitimate, so it would need to gossip the public keys. +This does not hamper the feasibility of implementing BLS signature aggregation +into Tendermint, but does represent yet another piece of added complexity to +the associated protocols. + +## Open Questions + +- _Q_: Can you aggregate Ed25519 signatures in Tendermint? + - There is a suggested scheme in github issue [7892][suggested-ed25519-agg], +but additional rigor would be required to fully verify its correctness. + +## Current Consideration + +Adopting a signature aggregation scheme presents some serious risks and costs +to the Tendermint project. It requires multiple backwards-incompatible changes +to the code, namely a change in the structure of the block and a new backwards-incompatible +signature and key type. It risks adding a new signature type for which new attack +types are still being discovered _and_ for which no industry standard, battle-tested +library yet exists. + +The gains boasted by this new signing scheme are modest: Verification time is +marginally faster and block sizes shrink by a few kilobytes. These are relatively +minor gains in exchange for the complexity of the change and the listed risks of the technology. +We should take a wait-and-see approach to BLS signature aggregation, monitoring +the up-and-coming projects and consider implementing it as the libraries and +standards develop. + +### References + +[line-ostracon-pr]: https://github.com/line/ostracon/pull/117 +[gcp-storage-pricing]: https://cloud.google.com/storage/pricing#north-america_2 +[yubi-key-bls-support]: https://github.com/Yubico/yubihsm-shell/issues/66 +[cloud-hsm-support]: https://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-key-types.html +[bls-ietf]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04 +[bls-ietf-terms]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-1.3 +[bls-ietf-pop]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-3.3 +[multi-signatures-smaller-blockchains]: https://eprint.iacr.org/2018/483.pdf +[zcash-adoption]: https://github.com/zcash/zcash/issues/2502 +[chia-adoption]: https://github.com/Chia-Network/chia-blockchain#chia-blockchain +[bls-ietf-ecdsa-compare]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-1.1 +[voi-ed25519-perf]: https://github.com/williambanfield/curve25519-voi/blob/benchmark/primitives/ed25519/PERFORMANCE.txt#L79 +[blst-verify-bench]: https://github.com/williambanfield/blst/blame/bench/bindings/go/PERFORMANCE.md#L9 +[blst-verify-bench-agg]: https://github.com/williambanfield/blst/blame/bench/bindings/go/PERFORMANCE.md#L23 +[vitalik-pairing-post]: https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627 +[ledger-bls-announce]: https://www.ledger.com/first-ever-firmware-update-coming-to-the-ledger-nano-x +[commit-proto]: https://github.com/tendermint/tendermint/blob/be7cb50bb3432ee652f88a443e8ee7b8ef7122bc/proto/tendermint/types/types.proto#L121 +[canonical-vote-proto]: https://github.com/tendermint/tendermint/blob/be7cb50bb3432ee652f88a443e8ee7b8ef7122bc/spec/core/encoding.md#L283 +[blst]: https://github.com/supranational/blst +[prysm-blst]: https://github.com/prysmaticlabs/prysm/blob/develop/go.mod#L75 +[gnark]: https://github.com/ConsenSys/gnark-crypto/ +[eth-2-adoption]: https://notes.ethereum.org/@GW1ZUbNKR5iRjjKYx6_dJQ/Skxf3tNcg_ +[bls-weil-pairing]: https://www.iacr.org/archive/asiacrypt2001/22480516.pdf +[summing-zero-paper]: https://eprint.iacr.org/2021/323.pdf +[circl]: https://github.com/cloudflare/circl +[suggested-ed25519-agg]: https://github.com/tendermint/tendermint/issues/7892 diff --git a/docs/rfc/tendermint-core/rfc-019-config-version.md b/docs/rfc/tendermint-core/rfc-019-config-version.md new file mode 100644 index 0000000..2cf55f6 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-019-config-version.md @@ -0,0 +1,401 @@ + +# RFC 019: Configuration File Versioning + +## Changelog + +- 19-Apr-2022: Initial draft (@creachadair) +- 20-Apr-2022: Updates from review feedback (@creachadair) + +## Abstract + +Updating configuration settings is an essential part of upgrading an existing +node to a new version of the Tendermint software. Unfortunately, it is also +currently a very manual process. This document discusses some of the history of +changes to the config format, actions we've taken to improve the tooling for +configuration upgrades, and additional steps we may want to consider. + +## Background + +A Tendermint node reads configuration settings at startup from a TOML formatted +text file, typically named `config.toml`. The contents of this file are defined +by the [`github.com/tendermint/tendermint/config`][config-pkg]. + +Although many settings in this file remain valid from one version of Tendermint +to the next, new versions of Tendermint often add, update, and remove settings. +These changes often require manual intervention by operators who are upgrading +their nodes. + +I propose we should provide better tools and documentation to help operators +make configuration changes correctly during version upgrades. Ideally, as much +as possible of any configuration file update should be automated, and where +that is not possible or practical, we should provide clear, explicit directions +for what steps need to be taken manually. Moreover, when the node discovers +incorrect or invalid configuration, we should improve the diagnostics it emits +so that the operator can quickly and easily find the relevant documentation, +without having to grep through source code. + +## Discussion + +By convention, we are supposed to document required changes to the config file +in the `UPGRADING.md` file for the release that introduces them. Although we +have mostly done this, the level of detail in the upgrading instructions is +often insufficient for an operator to correctly update their file. + +The updates vary widely in complexity: Operators may need to add new required +settings, update obsolete values for existing settings, move or rename existing +settings within the file, or remove obsolete settings (which are thus invalid). +Here are a few examples of each of these cases: + +- **New required settings:** Tendermint v0.35 added a new top-level `mode` + setting that determines whether a node runs as a validator, a full node, or a + seed node. The default value is `"full"`, which means the operator of a + validator must manually add `mode = "validator"` (or set the `--mode` flag on + the command line) for their node to come up in the correct mode. + +- **Updated obsolete values:** Tendermint v0.35 removed support for versions + `"v1"` and `"v2"` of the blocksync (formerly "fastsync") protocol, requiring + any node using either of those values to update to `"v0"`. + +- **Moved/renamed settings:** Version v0.34 moved the top-level `pprof_laddr` + setting under the `[rpc]` section. + + Version v0.35 renamed every setting in the file from `snake_case` to + `kebab-case`, moved the top-level `fast_sync` setting into the `[blocksync]` + section as (itself renamed from `[fastsync]`), and moved all the top-level + `priv-validator-*` settings under a new `[priv-validator]` section with their + prefix trimmed off. + +- **Removed obsolete settings:** Version v0.34 removed the `index_all_keys` and + `index_keys` settings from the `[tx_index]` section; version v0.35 removed + the `wal-dir` setting from the `[mempool]` section, and version v0.36 removed + the `[blocksync]` section entirely. + +While many of these changes are mentioned in the config section of the upgrade +instructions, some are not mentioned at all, or are hidden in other parts of +the doc. For instance, the v0.34 `pprof_laddr` change was documented only as an +RPC flag change. (A savvy reader might realize that the flag `--rpc.pprof_laddr` +implies a corresponding config section, but it omits the related detail that +there was a top-level setting that's been renamed). The lesson here is not +that the docs are bad, but to point out that prose is not the most efficient +format to convey detailed changes like this. The upgrading instructions are +still valuable for the human reader to understand what to expect. + +### Concrete Steps + +As part of the v0.36 development cycle, we spent some time reverse-engineering +the configuration changes since the v0.34 release and built an experimental +command-line tool called [`confix`][confix], whose job it is to automatically +update the settings in a `config.toml` file to the latest version. We also +backported a version of this tool into the v0.35.x branch at release v0.35.4. + +This tool should work fine for configuration files created by Tendermint v0.34 +and later, but does not (yet) know how to handle changes from prior versions of +Tendermint. Part of the difficulty for older versions is simply logistical: To +figure out which changes to apply, we need to understand something about the +version that made the file, as well as the version we're converting it to. + +> **Discussion point:** In the future we might want to consider incorporating +> this into the node CLI directly, but we're keeping it separate for now until +> we can get some feedback from operators. + +For the experiment, we handled this by carefully searching the history of +config format changes for shibboleths to bound the version: For example, the +`[fastsync]` section was added in Tendermint v0.32 and renamed `[blocksync]` in +Tendermint v0.35. So if we see a `[fastsync]` section, we have some confidence +that the file was created by v0.32, v0.33, or v0.34. + +But such signals are delicate: The `[blocksync]` section was removed in v0.36, +so if we do not find `[fastsync]`, we cannot conclude from that alone that the +file is from v0.31 or earlier -- we have to look for corroborating details. +While such "sniffing" tactics are fine for an experiment, they aren't as robust +as we might like. + +This is especially relevant for configuration files that may have already been +manually upgraded across several versions by the time we are asked to update +them again. Another related concern is that we'd like to make sure conversion +is idempotent, so that it would be safe to rerun the tool over an +already-converted file without breaking anything. + +### Config Versioning + +One obvious tactic we could use for future releases is add a version marker to +the config file. This would give tools like `confix` (and the node itself) a +way to calibrate their expectations. Rather than being a version for the file +itself, however, this version marker would indicate which version of Tendermint +is needed to read the file. + +Provisionally, this might look something like: + +```toml +# THe minimum version of Tendermint compatible with the contents of +# this configuration file. +config-version = 'v0.35' +``` + +When initializing a new node, Tendermint would populate this field with its own +version (e.g., `v0.36`). When conducting an upgrade, tools like `confix` can +then use this to decide which conversions are valid, and then update the value +accordingly. After converting a file marked `'v0.35'` to`'v0.37'`, the +conversion tool sets the file's `config-version` to reflect its compatibility. + +> **Discussion point:** This example presumes we would keep config files +> compatible within a given release cycle, e.g., all of v0.36.x. We could also +> use patch numbers here, if we think there's some reason to permit changes +> that would require config file edits at that granularity. I don't think we +> should, but that's a design question to consider. + +Upon seeing an up-to-date version marker, the conversion tool can simply exit +with a diagnostic like "this file is already up-to-date", rather than sniffing +the keyspace and potentially introducing errors. In addition, this would let a +tool detect config files that are _newer_ than the one it understands, and +issue a safe diagnostic rather than doing something wrong. Plus, besides +avoiding potentially unsafe conversions, this would also serve as +human-readable documentation that the file is up-to-date for a given version. + +Adding a config version would not address the problem of how to convert files +created by older versions of Tendermint, but it would at least help us build +more robust config tooling going forward. + +### Stability and Change + +In light of the discussion so far, it is natural to examine why we make so many +changes to the configuration file from one version to the next, and whether we +could reduce friction by being more conservative about what we make +configurable, what config changes we make over time, and how we roll them out. + +Some changes, like renaming everything from snake case to kebab case, are +entirely gratuitous. We could safely agree not to make those kinds of changes. +Apart from that obvious case, however, many other configuration settings +provide value to node operators in cases where there is no simple, universal +setting that matches every application. + +Taking a high-level view, there are several broad reasons why we might want to +make changes to configuration settings: + +- **Lessons learned:** Configuration settings are a good way to try things out + in production, before making more invasive changes to the consensus protocol. + + For example, up until Tendermint v0.35, consensus timeouts were specified as + per-node configuration settings (e.g., `timeout-precommit` et al.). This + allowed operators to tune these values for the needs of their network, but + had the downside that individually-misconfigured nodes could stall consensus. + + Based on that experience, these timeouts have been deprecated in Tendermint + v0.36 and converted to consensus parameters, to be consistent across all + nodes in the network. + +- **Migration & experimentation:** Introducing new features and updating old + features can complicate migration for existing users of the software. + Temporary or "experimental" configuration settings can be a valuable way to + mitigate that friction. + + For example, Tendermint v0.36 introduces a new RPC event subscription + endpoint (see [ADR 075][adr075]) that will eventually replace the existing + webwocket-based interface. To give users time to migrate, v0.36 adds an + `experimental-disable-websocket` setting, defaulted to `false`, that allows + operators to selectively disable the websocket API for testing purposes + during the conversion. This setting is designed to be removed in v0.37, when + the old interface is no longer supported. + +- **Ongoing maintenance:** Sometimes configuration settings become obsolete, + and the cost of removing them trades off against the potential risks of + leaving a non-functional or deprecated knob hooked up indefinitely. + + For example, Tendermint v0.35 deprecated two alternate implementations of the + blocksync protocol, one of which was deleted entirely (`v1`) and one of which + was scheduled for removal (`v2`). The `blocksync.version` setting, which had + been added as a migration aid, became obsolete and needed to be updated. + + Despite our best intentions, sometimes engineering designs do not work out. + It's just as important to leave room to back out of changes we have since + reconsidered, as it is to support migrations forward onto new and improved + code. + +- **Clarity and legibility:** Besides configuring the software, another + important purpose of a config file is to document intent for the humans who + operate and maintain the software. Operators need adjust settings to keep the + node running, and developers need to know what options were in use when + something goes wrong so they can diagnose and fix bugs. The legibility of a + config file as a _human_ artifact is also thus important. + + For example, Tendermint v0.35 moved settings related to validator private + keys from the top-level section of the configuration file to their own + designated `[priv-validator]` section. Although this change did not make any + difference to the meaning of those settings, it made the organization of the + file easier to understand, and allowed the names of the individual settings + to be simplified (e.g., `priv-validator-key-file` became simply `key-file` in + the new section). + + Although such changes are "gratuitous" with respect to the software, there is + often value in making things more legible for the humans. While there is no + simple rule to define the line, the Potter Stewart principle can be used with + due care. + +Keeping these examples in mind, we can and should take reasonable steps to +avoid churn in the configuration file across versions where we can. However, we +must also accept that part of the reason for _having_ a config file is to allow +us flexibility elsewhere in the design. On that basis, we should not attempt +to be too dogmatic about config changes either. Unlike changes in the block +protocol, for example, which affect every user of every network that adopts +them, config changes are relatively self-contained. + +There are few guiding principles I think we can use to strike a sensible +balance: + +1. **No gratuitous changes.** Aesthetic changes that do not enhance legibility, + avert confusion, or clarity documentation, should be entirely avoided. + +2. **Prefer mechanical changes.** Whenever it is practical, change settings in + a way that can be updated by a tool without operator judgement. This implies + finding safe, universal defaults for new settings, and not changing the + default values of existing settings. + + Even if that means we have to make multiple changes (e.g., add a new setting + in the current version, deprecate the old one, and remove the old one in the + next version) it's preferable if we can mechanize each step. + +3. **Clearly signal intent.** When adding temporary or experimental settings, + they should be clearly named and documented as such. Use long names and + suggestive prefixes (e.g., `experimental-*`) so that they stand out when + read in the config file or printed in logs. + + Relatedly, using temporary or experimental settings should cause the + software to emit diagnostic logs at runtime. These log messages should be + easy to grep for, and should contain pointers to more complete documentation + (say, issue numbers or URLs) that the operator can read, as well as a hint + about when the setting is expected to become invalid. For example: + + ``` + WARNING: Websocket RPC access is deprecated and will be removed in + Tendermint v0.37. See https://tinyurl.com/adr075 for more information. + ``` + +4. **Consider both directions.** When adding a configuration setting, take some + time during the implementation process to think about how the setting could + be removed, as well as how it will be rolled out. This applies even for + settings we imagine should be permanent. Experience may cause is to rethink + our original design intent more broadly than we expected. + + This does not mean we have to spend a long time picking nits over the design + of every setting; merely that we should convince ourselves we _could_ undo + it without making too big a mess later. Even a little extra effort up front + can sometimes save a lot. + +## References + +- [Tendermint `config` package][config-pkg] +- [`confix` command-line tool][confix] +- [`condiff` command-line tool][condiff] +- [Configuration update plan][plan] +- [ADR 075: RPC Event Subscription Interface][adr075] + +[config-pkg]: https://godoc.org/github.com/tendermint/tendermint/config +[confix]: https://github.com/tendermint/tendermint/blob/main/scripts/confix +[condiff]: https://github.com/tendermint/tendermint/blob/main/scripts/confix/condiff +[plan]: https://github.com/tendermint/tendermint/blob/main/scripts/confix/plan.go +[testdata]: https://github.com/tendermint/tendermint/blob/main/scripts/confix/testdata +[adr075]: https://github.com/tendermint/tendermint/blob/main/docs/architecture/adr-075-rpc-subscription.md + +## Appendix: Research Notes + +Discovering when various configuration settings were added, updated, and +removed turns out to be surprisingly tedious. To solve this puzzle, we had to +answer the following questions: + +1. What changes were made between v0.x and v0.y? This is further complicated by + cases where we have backported config changes into the middle of an earlier + release cycle (e.g., `psql-conn` from v0.35.x into v0.34.13). + +2. When during the development cycle were those changes made? This allows us to + recognize features that were backported into a previous release. + +3. What were the default values of the changed settings, and did they change at + all during or across the release boundary? + +Each step of the [configuration update plan][plan] is commented with a link to +one or more PRs where that change was made. The sections below discuss how we +found these references. + +### Tracking Changes Across Releases + +To figure out what changed between two releases, we built a tool called +[`condiff`][condiff], which performs a "keyspace" diff of two TOML documents. +This diff respects the structure of the TOML file, but ignores comments, blank +lines, and configuration values, so that we can see what was added and removed. + +To use it, run: + +```shell +go run ./scripts/confix/condiff old.toml new.toml +``` + +This tool works on any TOML documents, but for our purposes we needed +Tendermint `config.toml` files. The easiest way to get these is to build the +node binary for your version of interest, run `tendermint init` on a clean home +directory, and copy the generated config file out. The [`testdata`][testdata] +directory for the `confix` tool has configs generated from the heads of each +release branch from v0.31 through v0.35. + +If you want to reproduce this yourself, it looks something like this: + +```shell +# Example for Tendermint v0.32. +git checkout --track origin/v0.32.x +go get golang.org/x/sys/unix +go mod tidy +make build +rm -fr -- tmhome +./build/tendermint --home=tmhome init +cp tmhome/config/config.toml config-v32.toml +``` + +Be advised that the further back you go, the more idiosyncrasies you will +encounter. For example, Tendermint v0.31 and earlier predate Go modules (v0.31 +used dep), and lack backport branches. And you may need to do some editing of +Makefile rules once you get back into the 20s. + +Note that when diffing config files across the v0.34/v0.35 gap, the swap from +`snake_case` to `kebab-case` makes it look like everything changed. The +`condiff` tool has a `-desnake` flag that normalizes all the keys to kebab case +in both inputs before comparison. + +### Locating Additions and Deletions + +To figure out when a configuration setting was added or removed, your tool of +choice is `git bisect`. The only tricky part is finding the endpoints for the +search. If the transition happened within a release, you can use that +release's backport branch as the endpoint (if it has one, e.g., `v0.35.x`). + +However, the start point can be more problematic. The backport branches are not +ancestors of `master` or of each other, which means you need to find some point +in history _prior_ to the change but still attached to the mainline. For recent +releases there is a dev root (e.g., `v0.35.0-dev`, `v0.34.0-dev1`, etc.). These +are not named consistently, but you can usually grep the output of `git tag` to +find them. + +In the worst case you could try starting from the root commit of the repo, but +that turns out not to work in all cases. We've done some branching shenanigans +over the years that mean the root is not a direct ancestor of all our release +branches. When you find this you will probably swear a lot. I did. + +Once you have a start and end point (say, `v0.35.0-dev` and `master`), you can +bisect in the usual way. I use `git grep` on the `config` directory to check +whether the case I am looking for is present. For example, to find when the +`[fastsync]` section was removed: + +```shell +# Setup: +git checkout master +git bisect start +git bisect bad # it's not present on tip of master. +git bisect good v0.34.0-dev1 # it was present at the start of v0.34. +``` + +```shell +# Now repeat this until it gives you a specific commit: +if git grep -q '\[fastsync\]' config ; then git bisect good ; else git bisect bad ; fi +``` + +The above example finds where a config was removed: To find where a setting was +added, do the same thing except reverse the sense of the test (`if ! git grep -q +...`). diff --git a/docs/rfc/tendermint-core/rfc-020-onboarding-projects.rst b/docs/rfc/tendermint-core/rfc-020-onboarding-projects.rst new file mode 100644 index 0000000..5122638 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-020-onboarding-projects.rst @@ -0,0 +1,240 @@ +======================================= +RFC 020: Tendermint Onboarding Projects +======================================= + +.. contents:: + :backlinks: none + +Changelog +--------- + +- 2022-03-30: Initial draft. (@tychoish) +- 2022-04-25: Imported document to tendermint repository. (@tychoish) + +Overview +-------- + +This document describes a collection of projects that might be good for new +engineers joining the Tendermint Core team. These projects mostly describe +features that we'd be very excited to see land in the code base, but that are +intentionally outside of the critical path of a release on the roadmap, and +have the following properties that we think make good on-boarding projects: + +- require relatively little context for the project or its history beyond a + more isolated area of the code. + +- provide exposure to different areas of the codebase, so new team members + will have reason to explore the code base, build relationships with people + on the team, and gain experience with more than one area of the system. + +- be of moderate size, striking a healthy balance between trivial or + mechanical changes (which provide little insight) and large intractable + changes that require deeper insight than is available during onboarding to + address well. A good size project should have natural touchpoints or + check-ins. + +Projects +-------- + +Before diving into one of these projects, have a conversation about the +project or aspects of Tendermint that you're excited to work on with your +onboarding buddy. This will help make sure that these issues are still +relevant, help you get any context, underatnding known pitfalls, and to +confirm a high level approach or design (if relevant.) On-boarding buddies +should be prepared to do some design work before someone joins the team. + +The descriptions that follow provide some basic background and attempt to +describe the user stories and the potential impact of these project. + +E2E Test Systems +~~~~~~~~~~~~~~~~ + +Tendermint's E2E framework makes it possible to run small test networks with +different Tendermint configurations, and make sure that the system works. The +tests run Tendermint in a separate binary, and the system provides some very +high level protection against making changes that could break Tendermint in +otherwise difficult to detect ways. + +Working on the E2E system is a good place to get introduced to the Tendermint +codebase, particularly for developers who are newer to Go, as the E2E +system (generator, runner, etc.) is distinct from the rest of Tendermint and +comparatively quite small, so it may be easier to begin making changes in this +area. At the same time, because the E2E system exercises *all* of Tendermint, +work in this area is a good way to get introduced to various components of the +system. + +Configurable E2E Workloads +++++++++++++++++++++++++++ + +All E2E tests use the same workload (e.g. generated transactions, submitted to +different nodes in the network,) which has been tuned empirically to provide a +gentle but consistent parallel load that all E2E tests can pass. Ideally, the +workload generator could be configurable to have different shapes of work +(bursty, different transaction sizes, weighted to different nodes, etc.) and +even perhaps further parameterized within a basic shape, which would make it +possible to use our existing test infrastructure to answer different questions +about the performance or capability of the system. + +The work would involve adding a new parameter to the E2E test manifest, and +creating an option (e.g. "legacy") for the current load generation model, +extract configurations options for the current load generation, and then +prototype implementations of alternate load generation, and also run some +preliminary using the tools. + +Byzantine E2E Workloads ++++++++++++++++++++++++ + +There are two main kinds of integration tests in Tendermint: the E2E test +framework, and then a collection of integration tests that masquerade as +unit-tests. While some of this expansion of test scope is (potentially) +inevitable, the masquerading unit tests (e.g ``consensus.byzantine_test.go``) +end up being difficult to understand, difficult to maintain, and unreliable. + +One solution to this, would be to modify the E2E ABCI application to allow it +to inject byzantine behavior, and then have this be a configurable aspect of +a test network to be able to provoke Byzantine behavior in a "real" system and +then observe that evidence is constructed. This would make it possible to +remove the legacy tests entirely once the new tests have proven themselves. + +Abstract Orchestration Framework +++++++++++++++++++++++++++++++++ + +The orchestration of e2e test processes is presently done using docker +compose, which works well, but has proven a bit limiting as all processes need +to run on a single machine, and the log aggregation functions are confusing at +best. + +This project would replace the current orchestration with something more +generic, potentially maintaining the current system, but also allowing the e2e +tests to manage processes using k8s. There are a few "local" k8s frameworks +(e.g. kind and k3s,) which might be able to be useful for our current testing +model, but hopefully, we could use this new implementation with other k8s +systems for more flexible distribute test orchestration. + +Improve Operationalize Experience of ``run-multiple.sh`` +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +The e2e test runner currently runs a single test, and in most cases we manage +the test cases using a shell script that ensure cleanup of entire test +suites. This is a bit difficult to maintain and makes reproduction of test +cases more awkward than it should be. The e2e ``runner`` itself should provide +equivalent functionality to ``run-multiple.sh``: ensure cleanup of test cases, +collect and process output, and be able to manage entire suites of cases. + +It might also be useful to implement an e2e test orchestrator that runs all +tendermint instances in a single process, using "real" networks for faster +feedback and iteration during development. + +In addition to being a bit easier to maintain, having a more capable runner +implementation would make it easier to collect data from test runs, improve +debugability and reporting. + +Fan-Out For CI E2E Tests +++++++++++++++++++++++++ + +While there are some parallelism in the execution of e2e tests, each e2e test +job must build a tendermint e2e image, which takes about 5 minutes of CPU time +per-task, which given the size of each of the runs. + +We'd like to be able to reduce the amount of overhead per-e2e tests while +keeping the cycle time for working with the tests very low, while also +maintaining a reasonable level of test coverage. This is an impossible +tradeoff, in some ways, and the percentage of overhead at the moment is large +enough that we can make some material progress with a moderate amount of time. + +Most of this work has to do with modifying github actions configuration and +e2e artifact (docker) building to reduce redundant work. Eventually, when we +can drop the requirement for CGo storage engines, it will be possible to move +(cross) compile tendermint locally, and then inject the binary into the docker +container, which would reduce a lot of the build-time complexity, although we +can move more in this direction or have runtime flags to disable CGo +dependencies for local development. + +Remove Panics +~~~~~~~~~~~~~ + +There are lots of places in the code base which can panic, and would not be +particularly well handled. While in some cases, panics are the right answer, +in many cases the panics were just added to simplify downstream error +checking, and could easily be converted to errors. + +The `Don't Panic RFC +<./rfc-008-do-not-panic.md>`_ +covers some of the background and approach. + +While the changes are in this project are relatively rote, this will provide +exposure to lots of different areas of the codebase as well as insight into +how different areas of the codebase interact with eachother, as well as +experience with the test suites and infrastructure. + +Implement more Expressive ABCI Applications +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tendermint maintains two very simple ABCI applications (a KV application used +for basic testing, and slightly more advanced test application used in the +end-to-end tests). Writing an application would provide a new engineer with +useful experiences using Tendermint that mirrors the expierence of downstream +users. + +This is more of an exploratory project, but could include providing common +interfaces on top of Tendermint consensus for other well known protocols or +tools (e.g. ``etcd``) or a DNS server or some other tool. + +Self-Regulating Reactors +~~~~~~~~~~~~~~~~~~~~~~~~ + +Currently reactors (the internal processes that are responsible for the higher +level behavior of Tendermint) can be started and stopped, but have no +provision for being paused. These additional semantics may allow Tendermint to +pause reactors (and avoid processing their messhages, etc.) and allow better +coordination in the future. + +While this is a big project, it's possible to break this apart into many +smaller projects: make p2p channels pauseable, add pause/UN-pause hooks to the +service implementation and machinery, and finally to modify the reactor +implementations to take advantage of these additional semantics + +This project would give an engineer some exposure to the p2p layer of the +code, as well as to various aspects of the reactor implementations. + +Metrics +~~~~~~~ + +Tendermint has a metrics system that is relatively underutilized, and figuring +out ways to capture and organize the metrics to provide value to users might +provide an interesting set of projects for new engineers on Tendermint. + +Convert Logs to Metrics ++++++++++++++++++++++++ + +Because the tendermint logs tend to be quite verbose and not particularly +actionable, most users largely ignore the logging or run at very low +verbosity. While the log statements in the code do describe useful events, +taken as a whole the system is not particularly tractable, and particularly at +the Debug level, not useful. One solution to this problem is to identify log +messages that might be (e.g. increment a counter for certian kinds of errors) + +One approach might be to look at various logging statements, particularly +debug statements or errors that are logged but not returned, and see if +they're convertable to counters or other metrics. + +Expose Metrics to Tests ++++++++++++++++++++++++ + +The existing Tendermint test suites replace the metrics infrastructure with +no-op implementations, which means that tests can neither verify that metrics +are ever recorded, nor can tests use metrics to observe events in the +system. Writing an implementation, for testing, that makes it possible to +record metrics and provides an API for introspecting this data, as well as +potentially writing tests that take advantage of this type, could be useful. + +Logging Metrics ++++++++++++++++ + +In some systems, the logging system itself can provide some interesting +insights for operators: having metrics that track the number of messages at +different levels as well as the total number of messages, can act as a canary +for the system as a whole. + +This should be achievable by adding an interceptor layer within the logging +package itself that can add metrics to the existing system. diff --git a/docs/rfc/tendermint-core/rfc-021-socket-protocol.md b/docs/rfc/tendermint-core/rfc-021-socket-protocol.md new file mode 100644 index 0000000..c041894 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-021-socket-protocol.md @@ -0,0 +1,266 @@ +# RFC 021: The Future of the Socket Protocol + +## Changelog + +- 19-May-2022: Initial draft (@creachadair) +- 19-Jul-2022: Converted from ADR to RFC (@creachadair) + +## Abstract + +This RFC captures some technical discussion about the ABCI socket protocol that +was originally documented to solicit an architectural decision. This topic was +not high-enough priority as of this writing to justify making a final decision. + +For that reason, the text of this RFC has the general structure of an ADR, but +should be viewed primarily as a record of the issue for future reference. + +## Background + +The [Application Blockchain Interface (ABCI)][abci] is a client-server protocol +used by the Tendermint consensus engine to communicate with the application on +whose behalf it performs state replication. There are currently three transport +options available for ABCI applications: + +1. **In-process**: Applications written in Go can be linked directly into the + same binary as the consensus node. Such applications use a "local" ABCI + connection, which exposes application methods to the node as direct function + calls. + +2. **Socket protocol**: Out-of-process applications may export the ABCI service + via a custom socket protocol that sends requests and responses over a + Unix-domain or TCP socket connection as length-prefixed protocol buffers. + In Tendermint, this is handled by the [socket client][socket-client]. + +3. **gRPC**: Out-of-process applications may export the ABCI service via gRPC. + In Tendermint, this is handled by the [gRPC client][grpc-client]. + +Both the out-of-process options (2) and (3) have a long history in Tendermint. +The beginnings of the gRPC client were added in [May 2016][abci-start] when +ABCI was still hosted in a separate repository, and the socket client (formerly +called the "remote client") was part of ABCI from its inception in November +2015. + +At that time when ABCI was first being developed, the gRPC project was very new +(it launched Q4 2015) and it was not an obvious choice for use in Tendermint. +It took a while before the language coverage and quality of gRPC reached a +point where it could be a viable solution for out-of-process applications. For +that reason, it made sense for the initial design of ABCI to focus on a custom +protocol for out-of-process applications. + +## Problem Statement + +For practical reasons, ABCI needs an interprocess communication option to +support applications not written in Go. The two practical options are RPC and +FFI, and for operational reasons an RPC mechanism makes more sense. + +The socket protocol has not changed all that substantially since its original +design, and has the advantage of being simple to implement in almost any +reasonable language. However, its simplicity includes some limitations that +have had a negative impact on the stability and performance of out-of-process +applications using it. In particular: + +- The protocol lacks request identifiers, so the client and server must return + responses in strict FIFO order. Even if the client issues requests that have + no dependency on each other, the protocol has no way except order of issue to + map responses to requests. + + This reduces (in some cases substantially) the concurrency an application can + exploit, since the parallelism of requests in flight is gated by the slowest + active request at any moment. There have been complaints from some network + operators on that basis. + +- The protocol lacks method identifiers, so the only way for the client and + server to understand which operation is requested is to dispatch on the type + of the request and response payloads. For responses, this means that [any + error condition is terminal not only to the request, but to the entire ABCI + client](https://github.com/tendermint/tendermint/blob/main/abci/client/socket_client.go#L149). + + The historical intent of terminating for any error seems to have been that + all ABCI errors are unrecoverable and hence protocol fatal + (see [Note 1](#note1)). In practice, however, this greatly complicates + debugging a faulty node, since the only way to respond to errors is to panic + the node which loses valuable context that could have been logged. + +- There are subtle concurrency management dependencies between the client and + the server that are not clearly documented anywhere, and it is very easy for + small changes in both the client and the server to lead to tricky deadlocks, + panics, race conditions, and slowdowns. As a recent example of this, see + . + +These limitations are fixable, but one important question is whether it is +worthwhile to fix them. We can add request and method identifiers, for +example, but doing so would be a breaking change to the protocol requiring +every application using it to update. If applications have to migrate anyway, +the stability and language coverage of gRPC have improved a lot, and today it +is probably simpler to set up and maintain an application using gRPC transport +than to reimplement the Tendermint socket protocol. + +Moreover, gRPC addresses all the above issues out-of-the-box, and requires +(much) less custom code for both the server (i.e., the application) and the +client. The project is well-funded and widely-used, which makes it a safe bet +for a dependency. + +## Decision + +There is a set of related alternatives to consider: + +- Question 1: Designate a single IPC standard for out-of-process applications? + + Claim: We should converge on one (and only one) IPC option for out-of-process + applications. We should choose an option that, after a suitable period of + deprecation for alternatives, will address most or all the highest-impact + uses of Tendermint. Maintaining multiple options increases the surface area + for bugs and vulnerabilities, and we should not have multiple options for + basic interfaces without a clear and well-documented reason. + +- Question 2a: Choose gRPC and deprecate/remove the socket protocol? + + Claim: Maintaining and improving a custom RPC protocol is a substantial + project and not directly relevant to the requirements of consensus. We would + be better served by depending on a well-maintained open-source library like + gRPC. + +- Question 2b: Improve the socket protocol and deprecate/remove gRPC? + + Claim: If we find meaningful advantages to maintaining our own custom RPC + protocol in Tendermint, we should treat it as a first-class project within + the core and invest in making it good enough that we do not require other + options. + +**One important consideration** when discussing these questions is that _any +outcome which includes keeping the socket protocol will have eventual migration +impacts for out-of-process applications_ regardless. To fix the limitations of +the socket protocol as it is currently designed will require making _breaking +changes_ to the protocol. So, while we may put off a migration cost for +out-of-process applications by retaining the socket protocol in the short term, +we will eventually have to pay those costs to fix the problems in its current +design. + +## Detailed Design + +1. If we choose to standardize on gRPC, the main work in Tendermint core will + be removing and cleaning up the code for the socket client and server. + + Besides the code cleanup, we will also need to clearly document a + deprecation schedule, and invest time in making the migration easier for + applications currently using the socket protocol. + + > **Point for discussion:** Migrating from the socket protocol to gRPC + > should mostly be a plumbing change, as long as we do it during a release + > in which we are not making other breaking changes to ABCI. However, the + > effort may be more or less depending on how gRPC integration works in the + > application's implementation language, and would have to be sure networks + > have plenty of time not only to make the change but to verify that it + > preserves the function of the network. + > + > What questions should we be asking node operators and application + > developers to understand the migration costs better? + +2. If we choose to keep only the socket protocol, we will need to follow up + with a more detailed design for extending and upgrading the protocol to fix + the existing performance and operational issues with the protocol. + + Moreover, since the gRPC interface has been around for a long time we will + also need a deprecation plan for it. + +3. If we choose to keep both options, we will still need to do all the work of + (2), but the gRPC implementation should not require any immediate changes. + + +## Alternatives Considered + +- **FFI**. Another approach we could take is to use a C-based FFI interface so + that applications written in other languages are linked directly with the + consensus node, an option currently only available for Go applications. + + An FFI interface is possible for a lot of languages, but FFI support varies + widely in coverage and quality across languages and the points of friction + can be tricky to work around. Moreover, it's much harder to add FFI support + to a language where it's missing after-the-fact for an application developer. + + Although a basic FFI interface is not too difficult on the Go side, the C + shims for an FFI can get complicated if there's a lot of variability in the + runtime environment on the other end. + + If we want to have one answer for non-Go applications, we are better off + picking an IPC-based solution (whether that's gRPC or an extension of our + custom socket protocol or something else). + +## Consequences + +- **Standardize on gRPC** + + - ✅ Addresses existing performance and operational issues. + - ✅ Replaces custom code with a well-maintained widely-used library. + - ✅ Aligns with Cosmos SDK, which already uses gRPC extensively. + - ✅ Aligns with priv validator interface, for which the socket protocol is already deprecated for gRPC. + - ❓ Applications will be hard to implement in a language without gRPC support. + - ⛔ All users of the socket protocol have to migrate to gRPC, and we believe most current out-of-process applications use the socket protocol. + +- **Standardize on socket protocol** + + - ✅ Less immediate impact for existing users (but see below). + - ✅ Simplifies ABCI API surface by removing gRPC. + - ❓ Users of the socket protocol will have a (smaller) migration. + - ❓ Potentially easier to implement for languages that do not have support. + - ⛔ Need to do all the work to fix the socket protocol (which will require existing users to update anyway later). + - ⛔ Ongoing maintenance burden for per-language server implementations. + +- **Keep both options** + + - ✅ Less immediate impact for existing users (but see below). + - ❓ Users of the socket protocol will have a (smaller) migration. + - ⛔ Still need to do all the work to fix the socket protocol (which will require existing users to update anyway later). + - ⛔ Requires ongoing maintenance and support of both gRPC and socket protocol integrations. + + +## References + +- [Application Blockchain Interface (ABCI)][abci] +- [Tendermint ABCI socket client][socket-client] +- [Tendermint ABCI gRPC client][grpc-client] +- [Initial commit of gRPC client][abci-start] + +[abci]: https://github.com/tendermint/tendermint/tree/main/spec/abci +[socket-client]: https://github.com/tendermint/tendermint/blob/main/abci/client/socket_client.go +[socket-server]: https://github.com/tendermint/tendermint/blob/main/abci/server/socket_server.go +[grpc-client]: https://github.com/tendermint/tendermint/blob/main/abci/client/grpc_client.go +[abci-start]: https://github.com/tendermint/abci/commit/1ab3c747182aaa38418258679c667090c2bb1e0d + +## Notes + +- **Note 1**: The choice to make all ABCI errors protocol-fatal + was intended to avoid the risk that recovering an application error could + cause application state to diverge. Divergence can break consensus, so it's + essential to avoid it. + + This is a sound principle, but conflates protocol errors with "mechanical" + errors such as timeouts, resoures exhaustion, failed connections, and so on. + Because the protocol has no way to distinguish these conditions, the only way + for an application to report an error is to panic or crash. + + Whether a node is running in the same process as the application or as a + separate process, application errors should not be suppressed or hidden. + However, it's important to ensure that errors are handled at a consistent and + well-defined point in the protocol: Having the application panic or crash + rather than reporting an error means the node sees different results + depending on whether the application runs in-process or out-of-process, even + if the application logic is otherwise identical. + +## Appendix: Known Implementations of ABCI Socket Protocol + +This is a list of known implementations of the Tendermint custom socket +protocol. Note that in most cases I have not checked how complete or correct +these implementations are; these are based on search results and a cursory +visual inspection. + +- Tendermint Core (Go): [client][socket-client], [server][socket-server] +- Informal Systems [tendermint-rs](https://github.com/informalsystems/tendermint-rs) (Rust): [client](https://github.com/informalsystems/tendermint-rs/blob/master/abci/src/client.rs), [server](https://github.com/informalsystems/tendermint-rs/blob/master/abci/src/server.rs) +- Tendermint [js-abci](https://github.com/tendermint/js-abci) (JS): [server](https://github.com/tendermint/js-abci/blob/master/src/server.js) +- [Hotmoka](https://github.com/Hotmoka/hotmoka) ABCI (Java): [server](https://github.com/Hotmoka/hotmoka/blob/master/io-hotmoka-tendermint-abci/src/main/java/io/hotmoka/tendermint_abci/Server.java) +- [Tower ABCI](https://github.com/penumbra-zone/tower-abci) (Rust): [server](https://github.com/penumbra-zone/tower-abci/blob/main/src/server.rs) +- [abci-host](https://github.com/datopia/abci-host) (Clojure): [server](https://github.com/datopia/abci-host/blob/master/src/abci/host.clj) +- [abci_server](https://github.com/KrzysiekJ/abci_server) (Erlang): [server](https://github.com/KrzysiekJ/abci_server/blob/master/src/abci_server.erl) +- [py-abci](https://github.com/davebryson/py-abci) (Python): [server](https://github.com/davebryson/py-abci/blob/master/src/abci/server.py) +- [scala-tendermint-server](https://github.com/intechsa/scala-tendermint-server) (Scala): [server](https://github.com/InTechSA/scala-tendermint-server/blob/master/src/main/scala/lu/intech/tendermint/Server.scala) +- [kepler](https://github.com/f-o-a-m/kepler) (Rust): [server](https://github.com/f-o-a-m/kepler/blob/master/hs-abci-server/src/Network/ABCI/Server.hs) diff --git a/docs/rfc/tendermint-core/rfc-023-semi-permanent-testnet.md b/docs/rfc/tendermint-core/rfc-023-semi-permanent-testnet.md new file mode 100644 index 0000000..c572a53 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-023-semi-permanent-testnet.md @@ -0,0 +1,265 @@ +# RFC 023: Semi-permanent Testnet + +## Changelog + +- 2022-07-28: Initial draft (@mark-rushakoff) +- 2022-07-29: Renumber to 023, minor clarifications (@mark-rushakoff) + +## Abstract + +This RFC discusses a long-lived testnet, owned and operated by the Tendermint engineers. +By owning and operating a production-like testnet, +the team who develops Tendermint becomes more capable of discovering bugs that +only arise in production-like environments. +They also build expertise in operating Tendermint; +this will help guide the development of Tendermint towards operator-friendly design. + +The RFC details a rough roadmap towards a semi-permanent testnet, some of the considered tradeoffs, +and the expected outcomes from following this roadmap. + +## Background + +The author's understanding -- which is limited as a new contributor to the Tendermint project -- +is that Tendermint development has been largely treated as a library for other projects to consume. +Of course effort has been spent on unit tests, end-to-end tests, and integration tests. +But whether developing a library or an application, +there is no substitute for putting the software under a production-like load. + +First, there are classes of bugs that are unrealistic to discover in environments +that do not resemble production. +But perhaps more importantly, there are "operational features" that are best designed +by the authors of a given piece of software. +For instance, does the software have sufficient observability built-in? +Are the reported metrics useful? +Are the log messages clear and sufficiently detailed, without being too noisy? + +Furthermore, if the library authors are not only building -- +but also maintaining and operating -- an application built on top of their library, +the authors will have a greatly increased confidence that their library's API +is appropriate for other application authors. + +Once the decision has been made to run and operate a service, +one of the next strategic questions is that of deploying said service. +The author strongly holds the opinion that, when possible, +a continuous delivery model offers the most compelling set of advantages: + +- The code on a particular branch (likely `main` or `master`) is exactly what is, + or what will very soon be, running in production +- There are no manual steps involved in deploying -- other than merging your pull request, + which you had to do anyway +- A bug discovered in production can be rapidly confirmed as fixed in production + +In summary, if the tendermint authors build, maintain, and continuously deliver an application +intended to serve as a long-lived testnet, they will be able to state with confidence: + +- We operate the software in a production-like environment and we have observed it to be + stable and performant to our requirements +- We have discovered issues in production before any external parties have consumed our software, + and we have addressed said issues +- We have successfully used the observability tooling built into our software + (perhaps in conjunction with other off-the-shelf tooling) + to diagnose and debug issues in production + +## Discussion + +The Discussion Section proposes a variety of aspects of maintaining a testnet for Tendermint. + +### Number of testnets + +There should probably be one testnet per maintained branch of Tendermint, +i.e. one for the `main` branch +and one per `v0.N.x` branch that the authors maintain. + +There may also exist testnets for long-lived feature branches. + +We may eventually discover that there is good reason to run more than one testnet for a branch, +perhaps due to a significant configuration variation. + +### Testnet lifecycle + +The document has used the terms "long-lived" and "semi-permanent" somewhat interchangeably. +The intent of the testnet being discussed in this RFC is to exist indefinitely; +but there is a practical understanding that there will be testnet instances +which will be retired due to a variety of reasons. +For instance, once a release branch is no longer supported, +its corresponding testnet should be torn down. + +In general, new commits to branches with corresponding testnets +should result in an in-place upgrade of all nodes in the testnet +without any data loss and without requiring new configuration. +The mechanism for achieving this is outside the scope of this RFC. + +However, it is also expected that there will be +breaking changes during the development of the `main` branch. +For instance, suppose there is an unreleased feature involving storage on disk, +and the developers need to change the storage format. +It should be at the developers' discretion whether it is feasible and worthwhile +to introduce an intermediate commit that translates the old format to the new format, +or if it would be preferable to just destroy the testnet and start from scratch +without any data in the old format. + +Similarly, if a developer inadvertently pushed a breaking change to an unreleased feature, +they are free to make a judgement call between reverting the change, +adding a commit to allow a forward migration, +or simply forcing the testnet to recreate. + +### Testnet maintenance investment + +While there is certainly engineering effort required to build the tooling and infrastructure +to get the testnets up and running, +the intent is that a running testnet requires no manual upkeep under normal conditions. + +It is expected that a subset of the Tendermint engineers are familiar with and engaged in +writing the software to maintain and build the testnet infrastructure, +but the rest of the team should not need any involvement in authoring that code. + +The testnets should be configured to send notifications for events requiring triage, +such as a chain halt or a node OOMing. +The time investment necessary to address the underlying issues for those kind of events +is unpredictable. + +Aside from triaging exceptional events, an engineer may choose to spend some time +collecting metrics or profiles from testnet nodes to check performance details +before and after a particular change; +or they may inspect logs associated with an expected behavior change. +But during day-to-day work, engineers are not expected to spend any considerable time +directly interacting with the testnets. + +If we discover that there are any routine actions engineers must take against the testnet +that take any substantial focused time, +those actions should be automated to a one-line command as much as is reasonable. + +### Testnet MVP + +The minimum viable testnet meets this set of features: + +- The testnet self-updates following a new commit pushed to Tendermint's `main` branch on GitHub + (there are some omitted steps here, such as CI building appropriate binaries and + somehow notifying the testnet that a new build is available) +- The testnet runs the Tendermint KV store for MVP +- The testnet operators are notified if: + - Any node's process exits for any reason other than a restart for a new binary + - Any node stops updating blocks, and by extension if a chain halt occurs + - No other observability will be considered for MVP +- The testnet has a minimum of 1 full node and 3 validators +- The testnet has a reasonably low, constant throughput of transactions -- say 30 tx/min -- + and the testnet operators are notified if that throughput drops below 75% of target + sustained over 5 minutes +- The testnet only needs to run in a single datacenter/cloud-region for MVP, + i.e. running in multiple datacenters is out of scope for MVP +- The testnet is running directly on VMs or compute instances; + while Kubernetes or other orchestration frameworks may offer many significant advantages, + the Tendermint engineers should not be required to learn those tools in order to + perform basic debugging + +### Testnet medium-term goals + +The medium-term goals are intended to be achievable within the 6-12 month time range +following the launch of MVP. +These goals could realistically be roadmapped following the launch of the MVP testnet. + +- The `main` testnet has more than 20 nodes (completely arbitrary -- 5x more than 1+3 at MVP) +- In addition to the `main` testnet, + there is at least one testnet associated with one release branch +- The testnet no longer is simply running the Tendermint KV store; + now it is built on a more complex, custom application + that deliberately exercises a greater portion of the Tendermint stack +- Each testnet is spread across at least two cloud providers, + in order to communicate over a network more closely resembling use of Tendermint in "real" chains +- The node updates have some "jitter", + with some nodes updating immediately when a new build is available, + and others delaying up to perhaps 30-60 minutes +- The team has published some form of dashboards that have served well for debugging, + which external parties can copy/modify to their needs + - The dashboards must include metrics published by Tendermint nodes; + there should be both OS- or runtime-level metrics such as memory in use, + and application-level metrics related to the underlying blockchain + - "Published" in this context is more in the spirit of "shared with the community", + not "produced a supported open source tool" -- + this could be published to GitHub with a warning that no support is offered, + or it could simply be a blog post detailing what has worked for the Tendermint developers + - The dashboards will likely be implemented on free and open source tooling, + but that is not a hard requirement if paid software is more appropriate +- The team has produced a reference model of a log aggregation stack that external parties can use + - Similar to the "published" dashboards, this only needs to be "shared" rather than "supported" +- Chaos engineering has begun being integrated into the testnets + (this could be periodic CPU limiting or deliberate network interference, etc. + but it probably would not be filesystem corruption) +- Each testnet has at least one node running a build with the Go race detector enabled +- The testnet contains some kind of generalized notification system built in: + - Tendermint code grows "watchdog" systems built in to validate things like + subsystems have not deadlocked; e.g. if the watchdog can't acquire and immediately release + a particular mutex once in every 5-minute period, it is near certain that the target + subsystem has deadlocked, and an alert must be sent to the engineering team. + (Outside of the testnet, the watchdogs could be disabled, or they could panic on failure.) + - The notification system does some deduplication to minimize spam on system failure + +### Testnet long-term vision + +The long-term vision includes goals that are not necessary for short- or medium-term success, +but which would support building an increasingly stable and performant product. +These goals would generally be beyond the one-year plan, +and therefore they would not be part of initial planning. + +- There is a centralized dashboard to get a quick overview of all testnets, + or at least one centralized dashboard per testnet, + showing TBD basic information +- Testnets include cloud spot instances which periodically and abruptly join and leave the network +- The testnets are a heterogeneous mixture of straight VMs and Docker containers, + thereby more closely representing production blockchains +- Testnets have some manner of continuous profiling, + so that we can produce an apples-to-apples comparison of CPU/memory cost of particular operations + +### Testnet non-goals + +There are some things we are explicitly not trying to achieve with long-lived testnets: + +- The Tendermint engineers will NOT be responsible for the testnets' availability + outside of working hours; there will not be any kind of on-call schedule +- As a result of the 8x5 support noted in the previous point, + there will be NO guarantee of uptime or availability for any testnet +- The testnets will NOT be used to gate pull requests; + that responsibility belongs to unit tests, end-to-end tests, and integration tests +- Similarly, the testnet will NOT be used to automate any changes back into Tendermint source code; + we will not automatically create a revert commit due to a failed rollout, for instance +- The testnets are NOT intended to have participation from machines outside of the + Tendermint engineering team's control, as the Tendermint engineers are expected + to have full access to any instance where they may need to debug an issue +- While there will certainly be individuals within the Tendermint engineering team + who will continue to build out their individual "devops" skills to produce + the infrastructure for the testnet, it is NOT a goal that every Tendermint engineer + is even _familiar_ with the tech stack involved, whether it is Ansible, Terraform, + Kubernetes, etc. + As a rule of thumb, all engineers should be able to get shell access on any given instance + and should have access to the instance's logs. + Little if any further operational skills will be expected. +- The testnets are not intended to be _created_ for one-off experiments. + While there is nothing wrong with an engineer directly interacting with a testnet + to try something out, + a testnet comes with a considerable amount of "baggage", so end-to-end or integration tests + are closer to the intent for "trying something to see what happens". + Direct interaction should be limited to standard blockchain operations, + _not_ modifying configuration of nodes. +- Likewise, the purpose of the testnet is not to run specific "tests" per se, + but rather to demonstrate that Tendermint blockchains as a whole are stable + under a production load. + Of course we will inject faults periodically, but the intent is to observe and prove that + the testnet is resilient to those faults. + It would be the responsibility of a lower-level test to demonstrate e.g. + that the network continues when a single validator disappears without warning. +- The testnet descriptions in this document are scoped only to building directly on Tendermint; + integrating with the Cosmos SDK, or any other third-party library, is out of scope + +### Team outcomes as a result of maintaining and operating a testnet + +Finally, this section reiterates what team growth we expect by running semi-permanent testnets. + +- Confidence that Tendermint is stable under a particular production-like load +- Familiarity with typical production behavior of Tendermint, e.g. what the logs look like, + what the memory footprint looks like, and what kind of throughput is reasonable + for a network of a particular size +- Comfort and familiarity in manually inspecting a misbehaving or failing node +- Confidence that Tendermint ships sufficient tooling for external users + to operate their nodes +- Confidence that Tendermint exposes useful metrics, and comfort interpreting those metrics +- Produce useful reference documentation that gives operators confidence to run Tendermint nodes diff --git a/docs/rfc/tendermint-core/rfc-024-block-structure-consolidation.md b/docs/rfc/tendermint-core/rfc-024-block-structure-consolidation.md new file mode 100644 index 0000000..7d982aa --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-024-block-structure-consolidation.md @@ -0,0 +1,362 @@ +# RFC 024: Block Structure Consolidation + +## Changelog + +- 19-Apr-2022: Initial draft started (@williambanfield). +- 3-May-2022: Initial draft complete (@williambanfield). + +## Abstract + +The `Block` data structure is a very central structure within Tendermint. Because +of its centrality, it has gained several fields over the years through accretion. +Not all of these fields may be necessary any more. This document examines which +of these fields may no longer be necessary for inclusion in the block and makes +recommendations about how to proceed with each of them. + +## Background + +The current block structure contains multiple fields that are not required for +validation or execution of a Tendermint block. Some of these fields had vestigial +purposes that they no longer serve and some of these fields exist as a result of +internal Tendermint domain objects leaking out into the external data structure. + +In so far as is possible, we should consolidate and prune these superfluous +fields before releasing a 1.0 version of Tendermint. All pruning of these +fields should be done with the aim of simplifying the structures to what +is needed while preserving information that aids with debugging and that also +allow external protocols to function more efficiently than if they were removed. + +### Current Block Structure + +The current block structures are included here to aid discussion. + +```proto +message Block { + Header header = 1; + Data data = 2; + tendermint.types.EvidenceList evidence = 3; + Commit last_commit = 4; +} +``` + +```proto +message Header { + tendermint.version.Consensus version = 1; + string chain_id = 2; + int64 height = 3; + google.protobuf.Timestamp time = 4; + BlockID last_block_id = 5; + bytes last_commit_hash = 6; + bytes data_hash = 7; + bytes validators_hash = 8; + bytes next_validators_hash = 9; + bytes consensus_hash = 10; + bytes app_hash = 11; + bytes last_results_hash = 12; + bytes evidence_hash = 13; + bytes proposer_address = 14; +} + +``` + +```proto +message Data { + repeated bytes txs = 1; +} +``` + +```proto +message EvidenceList { + repeated Evidence evidence = 1; +} +``` + +```proto +message Commit { + int64 height = 1; + int32 round = 2; + BlockID block_id = 3; + repeated CommitSig signatures = 4; +} +``` + +```proto +message CommitSig { + BlockIDFlag block_id_flag = 1; + bytes validator_address = 2; + google.protobuf.Timestamp timestamp = 3; + bytes signature = 4; +} +``` + +```proto +message BlockID { + bytes hash = 1; + PartSetHeader part_set_header = 2; +} +``` + +### On Tendermint Blocks + +#### What is a Tendermint 'Block'? + +A block is the structure produced as the result of an instance of the Tendermint +consensus algorithm. At its simplest, the 'block' can be represented as a Merkle +root hash of all of the data used to construct and produce the hash. Our current +block proto structure includes _far_ from all of the data used to produce the +hashes included in the block. + +It does not contain the full `AppState`, it does not contain the `ConsensusParams`, +nor the `LastResults`, nor the `ValidatorSet`. Additionally, the layout of +the block structure is not inherently tied to this Merkle root hash. Different +layouts of the same set of data could trivially be used to construct the +exact same hash. The thing we currently call the 'Block' is really just a view +into a subset of the data used to construct the root hash. Sections of the +structure can be modified as long as alternative methods exist to query and +retrieve the constituent values. + +#### Why this digression? + +This digression is aimed at informing what it means to consolidate 'fields' in the +'block'. The discussion of what should be included in the block can be teased +apart into a few different lines of inquiry. + +1. What values need to be included as part of the Merkle tree so that the +consensus algorithm can use proof-of-stake consensus to validate all of the +properties of the chain that we would like? +2. How can we create views of the data that can be easily retrieved, stored, and +verified by the relevant protocols? + +These two concerns are intertwined at the moment as a result of how we store +and propagate our data but they don't necessarily need to be. This document +focuses primarily on the first concern by suggesting fields that can be +completely removed without any loss in the function of our consensus algorithm. + +This document also suggests ways that we may update our storage and propagation +mechanisms to better take advantage of Merkle tree nature of our data although +these are not its primary concern. + +## Discussion + +### Data to consider removing + +This section proposes a list of data that could be completely removed from the +Merkle tree with no loss to the functionality of our consensus algorithm. + +Where the change is possible but would hamper external protocols or make +debugging more difficult, that is noted in discussion. + +#### CommitSig.Timestamp + +This field contains the timestamp included in the precommit message that was +issued for the block. The field was once used to produce the timestamp of the block. +With the introduction of Proposer-Based Timestamps, This field is no longer used +in any Tendermint algorithms and can be completely removed. + +#### CommitSig.ValidatorAddress + +The `ValidatorAddress` is included in each `CommitSig` structure. This field +is hashed along with all of the other fields of the `CommitSig`s in the block +to form the `LastCommitHash` field in the `Header`. The `ValidatorAddress` is +somewhat redundant in the hash. Each validator has a unique position in the +`CommitSig` and the hash is built preserving this order. Therefore, the +information of which signature corresponds to which validator is included in +the root hash, even if the address is absent. + +It's worth noting that the validator address could still be included in the +_hash_ even if it is absent from the `CommitSig` structure in the block by +simply hashing it locally at each validator but not including it in the block. +The reverse is also true. It would be perfectly possible to not include the +`ValidatorAddress` data in the `LastCommitHash` but still include the field in +the block. + +#### BlockID.PartSetHeader + +The [BlockID][block-id] field comprises the [PartSetHeader][part-set-header] and the hash of the block. +The `PartSetHeader` is used by nodes to gossip the block by dividing it into +parts. Nodes receive the `PartSetHeader` from their peers, informing them of +what pieces of the block to gather. There is no strong reason to include this +value in the block. Validators will still be able to gossip and validate the +blocks that they received from their peers using this mechanism even if it is +not written into the block. The `BlockID` can therefore be consolidated into +just the hash of the block. This is by far the most uncontroversial change +and there appears to be no good reason _not_ to do it. Further evidence that +the field is not meaningful can be found in the fact that the field is not +actually validated to ensure it is correct during block validation. Validation +only checks that the [field is well formed][psh-check]. + +#### ChainID + +The `ChainID` is a string selected by the chain operators, usually a +human-readable name for the network. This value is immutable for the lifetime +of the chain and is defined in the genesis file. It is therefore hashed into the +original block and therefore transitively included as in the Merkle root hash of +every block. The redundant field is a candidate for removal from the root hash +of each block. However, aesthetically, it's somewhat nice to include in each +block, as if the block was 'stamped' with the ID. Additionally, re-validating +the value from genesis would be painful and require reconstituting potentially +large chains. I'm therefore mildly in favor of maintaining this redundant +piece of information. We pay almost no storage cost for maintaining this +identical data, so the only cost is in the time required to hash it into the +structure. + +#### LastResultsHash + +`LastResultsHash` is a hash covering the result of executing the transactions +from the previous block. It covers the response `Code`, `Data`, `GasWanted`, +and `GasUsed` with the aim of ensuring that execution of all of the transactions +was performed identically on each node. The data covered by this field _should_ +be also reflected in the `AppHash`. The `AppHash` is provided by the application +and should be deterministically calculated by each node. This field could +therefore be removed on the grounds that its data is already reflected elsewhere. + +I would advocate for keeping this field. This field provides an additional check +for determinism across nodes. Logic to update the application hash is more +complicated for developers to implement because it relies either on building a +complete view of the state of the application data. The `Results` returned by +the application contain simple response codes and deterministic data bytes. +Leaving the field will allow for transaction execution issues that are not +correctly reflected in the `AppHash` to be more completely diagnosed. + +Take the case of mismatch of `LastResultsHash` between two nodes, A and B, where both +nodes report divergent values. If `A` and `B` both report +the same `AppHash`, then some non-deterministic behavior occurred that was not +accurately reflected in the `AppHash`. The issue caused by this +non-determinism may not show itself for several blocks, but catching the divergent +state earlier will improve the chances that a chain is able to recover. + +#### ValidatorsHash + +Both `ValidatorsHash` and `NextValidatorsHash` are included in the block +header. `Validatorshash` contains the hash of the [public key and voting power][val-hash] +of each validator in the active set for the current block and `NextValidatorsHash` +contains the same data but for the next height. + +This data is effectively redundant. Having both values present in the block +structure is helpful for light client verification. The light client is able to +easily determine if two sequential blocks used the same validator set by querying +only one header. + +`ValidatorsHash` is also important to the light client algorithm for performing block +validation. The light client uses this field to ensure that the validator set +it fetched from a full node is correct. It can be sure of the correctness of +the retrieved structure by hashing it and checking the hash against the `ValidatorsHash` +of the block it is verifying. Because a validator that the light client trusts +signed over the `ValidatorsHash`, it can be certain of the validity of the +structure. Without this check, phony validator sets could be handed to the light +client and the code tricked into believing a different validator set was present +at a height, opening up a major hole in the light client security model. + +This creates a recursive problem. To verify the validator set that signed the +block at height `H`, what information do we need? We could fetch the +`NextValidatorsHash` from height `H-1`, but how do we verify that that hash is correct? + +#### ProposerAddress + +The section below details a change to allow the `ProposerAddress` to be calculated +from a field added to the block. This would allow the `Address` to be dropped +from the block. Consumers of the chain could run the proposer selection [algorithm][proposer-selection] +to determine who proposed each block. + +I would advocate against this. Any consumer of the chain that wanted to +know which validator proposed a block would have to run the proposer selection +algorithm. This algorithm is not widely implemented, meaning that consumers +in other languages would need to implement the algorithm to determine a piece +of basic information about the chain. + +### Data to consider adding + +#### ProofOfLockRound + +The _proof of lock round_ is the round of consensus for a height in which the +Tendermint algorithm observed a super majority of voting power on the network for +a block. + +Including this value in the block will allow validation of currently +un-validated metadata. Specifically, including this value will allow Tendermint +to validate that the `ProposerAddress` in the block is correct. Without knowing +the locked round number, Tendermint cannot calculate which validator was supposed +to propose a height. Because of this, our [validation logic][proposer-check] does not check that +the `ProposerAddress` included in the block corresponds to the validator that +proposed the height. Instead, the validation logic simply checks that the value +is an address of one of the known validators. + +Currently, we maintain the _committed round_ in the `Commit` for height `H`, which is +written into the block at height `H+1`. This value corresponds to the round in +which the proposer of height `H+1` received the commit for height `H`. The proof +of lock round would not subsume this value. + +### Additional possible updates + +#### Updates to storage + +Currently we store the [every piece of each block][save-block] in the `BlockStore`. +I suspect that this has lead to some mistakes in reasoning around the merits of +consolidating fields in the block. We could update the storage scheme we use to +store only some pieces of each block and still achieve a space savings without having +to change the block structure at all. + +The main way to achieve this would be by _no longer saving data that does not change_. +At each height we save a set of data that is unlikely to have changed from the +previous height in the block structure, this includes the `ValidatorAddress`es, +the `ValidatorsHash`, the `ChainID`. These do not need to be saved along with +_each_ block. We could easily save the value and the height at which the value +was updated and construct each block using the data that existed at the time. + +This document does not make any specific recommendations around storage since +that is likely to change with upcoming improvements to to the database infrastructure. +However, it's important to note that removing fields from the block for the +purposes of 'saving space' may not be that meaningful. We should instead focus +our attention of removing fields from the block that are no longer needed +for correct functioning of the protocol. + +#### Updates to propagation + +Block propagation suffers from the same issue that plagues block storage, we +propagate all of the contents of each block proto _even when these contents are redundant +or unchanged from previous blocks_. For example, we propagate the `ValidatorAddress`es +for each block in the `CommitSig` structure even when it never changed from a +previous height. We could achieve a speed-up in many cases by communicating the +hashes _first_ and letting peers request additional information when they do not +recognize the communicated hash. + +For example, in the case of the `ValidatorAddress`es, the node would first +communicate the `ValidatorsHash` of the block to its peers. The peers would +check their storage for a validator set matching the provided hash. If the peer +has a matching set, it would populate its local block structure with the +appropriate values from its store. If peer did not have a matching set, it would +issue a request to its peers, either via P2P or RPC for the data it did not have. + +Conceptually, this is very similar to how content addressing works in protocols +such as git where pushing a commit does not require pushing the entire contents +of the tree referenced by the commit. + +### Impact on light clients + +As outlined in the section [On Tendermint Blocks](#on-tendermint-blocks), there +is a distinction between what data is referenced in the Merkle root hash and the +contents of the proto structure we currently call the `Block`. + +Any changes to the Merkle root hash will necessarily be breaking for legacy light clients. +Either a soft-upgrades scheme will need to be implemented or a hard fork will +be required for chains and light clients to function with the new hashes. +This means that all of the additions and deletions from the Merkle root hash +proposed by this document will be light client breaking. + +Changes to the block structure alone are not necessarily light client breaking if the +data being hashed are identical and legacy views into the data are provided +for old light clients during transitions. For example, a newer version of the +block structure could move the `ValidatorAddress` field to a different field +in the block while still including it in the hashed data of the `LastCommitHash`. +As long as old light clients could still fetch the old data structure, then +this would not be light client breaking. + +## References + +[part-set-header]: https://github.com/tendermint/tendermint/blob/208a15dadf01e4e493c187d8c04a55a61758c3cc/types/part_set.go#L94 +[block-id]: https://github.com/tendermint/tendermint/blob/208a15dadf01e4e493c187d8c04a55a61758c3cc/types/block.go#L1090 +[psh-check]: https://github.com/tendermint/tendermint/blob/208a15dadf01e4e493c187d8c04a55a61758c3cc/types/part_set.go#L116 +[proposer-selection]: https://github.com/tendermint/tendermint/blob/208a15dadf01e4e493c187d8c04a55a61758c3cc/spec/consensus/proposer-selection.md +[val-hash]: https://github.com/tendermint/tendermint/blob/29e5fbcc648510e4763bd0af0b461aed92c21f30/types/validator.go#L160 +[proposer-check]: https://github.com/tendermint/tendermint/blob/29e5fbcc648510e4763bd0af0b461aed92c21f30/internal/state/validation.go#L102 +[save-block]: https://github.com/tendermint/tendermint/blob/59f0236b845c83009bffa62ed44053b04370b8a9/internal/store/store.go#L490 diff --git a/docs/rfc/tendermint-core/rfc-025-support-app-side-mempool.md b/docs/rfc/tendermint-core/rfc-025-support-app-side-mempool.md new file mode 100644 index 0000000..1bcfec4 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-025-support-app-side-mempool.md @@ -0,0 +1,300 @@ +# RFC 25: Support Application Defined Transaction Storage (app-side mempools) + +## Changelog + +- Aug 17, 2022: initial draft (@williambanfield) +- Aug 19, 2022: updated draft (@williambanfield) + +## Abstract + +With the release of ABCI++, specifically the `PrepareProposal` call, the utility +of the Tendermint mempool becomes much less clear. This RFC discusses possible +changes that should be considered to Tendermint to better support applications +that intend to use `PrepareProposal` to implement much more powerful transaction +ordering and filtering functionality than Tendermint can provide. It proposes +scoping down the responsibilities of Tendermint to suit this new use case. + +## Background + +Tendermint currently ships with a data structure it calls the +[mempool][mempool-link]. The mempool's primary function is to store pending +valid transactions. Tendermint uses the contents of the mempool in two main +ways: 1) to gossip these pending transactions to other nodes on a Tendermint +network and 2) to select transactions to be included in a proposed block. Before +ABCI++, when proposing a block Tendermint selects the next set of transactions +from the mempool that fit within block and proposes them. + +There are a few issues with this data structure. These include issues of how +transaction validity is defined, how transactions should be ordered and selected +for inclusion in the next block, and when a transaction should start or stop +being gossiped. The creation of `PrepareProposal` in ABCI++ adds the additional +issue of unclear ownership over which entity, Tendermint or the ABCI +application, is responsible for selecting the transactions to be included in +a proposed block. + +None of these issues of validity, ordering, and gossiping having simple, +one-size fits all solutions. Different applications will have different +preferences and needs for each of them. The current Tendermint mempool attempts +to strike a balance but is quite prescriptive about these questions. We can +better support a varied range of applications by simplifying the current mempool +and by reducing and clarifying its scope of responsibilities. + +## Discussion + +### The mempool is a leaky abstraction and handles too many concerns + +The current mempool is a leaky abstraction. Presently, Tendermint's mempool keeps +track of a multitude of details that primarily service concerns of the application. + +#### Gas + +The mempool keeps track of Gas, a proxy for how computationally expensive it +will be to execute a transaction. As discussed in [RFC-011](https://github.com/tendermint/tendermint/blob/2313f358003d0c4d9d0e7705b4632d819dfb0d92/docs/rfc/rfc-011-delete-gas.md), this metadata is +not a concern of Tendermint's. Tendermint does not execute transactions. This +data is stored within Tendermint's mempool along with the maximum gas the application +will permit to be used in a block so that Tendermint's mempool can enforce +transaction validity using it: transactions that exceed the configured maximum +are rejected from the mempool. How much 'Gas' a transaction consumes and if that +precludes it from execution by the application is a validity condition imposed +by the application, not Tendermint. It is an application abstraction that leaks +into the Tendermint mempool. + +#### Sender + +The Tendermint mempool stores a `sender` string metadata for each transaction +it receives. The mempool only stores one transaction per sender at any time. +The `sender` metadata is populated by the application during `CheckTx`. +`Sender` uniqueness is enforced separately on each node's mempool. Nothing +prevents multiple transactions with the same `sender` from existing in separate +mempools on the network. + +While multiple transactions from the same sender on a network is a shortcoming +of the `sender` abstraction, the issue posed by sender to the mempool is that +`sender` uniqueness is a condition of transaction validity that is otherwise +meaningless to Tendermint. The `sender` field allows the application to +influence which transactions Tendermint will include next in a block. However, +with the advent of `PrepareProposal`, the application can select directly and +this `sender` field is of marginal benefit. Additionally, applications require +much more expressive validity conditions than just `sender` uniqueness. + +#### Adding additional semantics to the mempool + +The Tendermint mempool is relied upon by every ABCI application. Changing its +code to incorporate new features or update its behavior affects all of +Tendermint's downstream consumers. New applications frequently need ways of +sorting pending transactions and imposing transaction validity conditions. This +data structure cannot change quickly to meet the shifting needs of new +consumers while also maintaining a stable API for the applications that are +already successfully running on top of Tendermint. New strategies for sorting +and validating pending transactions would be best implemented outside of +Tendermint, where creating new semantics does not risk disrupting the existing +users. + +### Tendermint's scope of responsibility + +#### What should Tendermint be responsible for? + +Tendermint's responsibilities should be as narrowly scoped as possible to allow +the code base to be useful for many developers and maintainable by the core +team. + +The Tendermint node maintains a P2P network over which pending transactions, +proposed blocks, votes and other messages are sent. Tendermint, using these +messages, comes to consensus on the proposed blocks and delivers their contents +to the application in an orderly fashion. + +In this description of Tendermint, its only responsibility, in terms of pending +transactions, is to _gossip_ them over its P2P network. Any additional logic +surrounding validity, ordering etc. requires an understanding of the meaning of +the transaction that Tendermint does not and _should not_ have. + +#### What should the application be responsible for? + +Transaction contents have semantic meaning to the ABCI application. Pending +transactions are valid and have execution priority in relationship to the +current state of application. While Tendermint is clearly responsible for the +action of gossiping the transaction, it cannot decide when to start or stop +gossiping any given transaction. While only valid transactions should be +gossiped, as stated, it cannot appropriately make decisions about transaction +validity beyond simple heuristics. The application therefore should be +responsible for defining pending transaction validity, determining when to start +or stop gossiping a transaction, and for selecting which transaction should be +contained within a block. + +### How can Tendermint best be designed for this responsibility? + +With the understanding that Tendermint's responsibility is to gossip the set of +transactions that the application currently considers valid and high priority, +we can update its API and data structures accordingly. With the creation of +`PrepareProposal`, the mempool may be able to drop its responsibility to select +transactions for a block; It can be primarily responsible for gossiping and +nothing else. + +#### Goodbye mempool, hello GossipList + +The mempool contains many structures to retain, order, and select the set of +transactions to gossip and to propose. These mempool structures could be +completely replaced with a single list that allows Tendermint to fulfill the +previously stated responsibility. This proposed list, the `GossipList`, would +simply contain the set of transactions that Tendermint is responsible for +gossiping at the moment. This `GossipList` would be updated by the application +at a set of defined junctures and Tendermint would never add to it or remove +from it without input from the application. Tendermint would impose _no_ +validity constraints on the contents of this list and would not attempt to +remove items unless instructed to. + +### Mock API of the GossipList + +Outlined below is a proposed API for this data structure. These calls would be +added to the ABCI API and would come to replace the current `CheckTx` call. + +#### `OfferPendingTransaction` + +`OfferPendingTransaction` replaces the `CheckTx` call that is invoked when +Tendermint receives a submitted or gossiped transaction. The `GossipList` will +invoke `OfferPendingTransaction` on _every_ transaction sent to Tendermint that +does not match one of the transactions already in the `GossipList`. The mempool +currently drops gossiped transactions before `CheckTx` is called if the +transaction is considered invalid for a Tendermint-defined reason such as +inclusion in the mempool 'cache' or it overflows the max transaction size. + +The application can indicate if the transaction should be added to the +`GossipList` via `ResponseOfferPendingTransaction`'s `GossipStatus` field. If +the `GossipList` is full, the application must list a transaction to remove from +`GossipList`, otherwise the transaction will not be added. In this way, +a transaction will _never_ leave the list unless the application removes it from +the list explicitly. + +```proto +message RequestOfferPendingTransaction { + bytes tx = 1; + int64 gossip_list_max_size = 2; + int64 gossip_list_current_size = 3; +} + +message ResponseOfferPendingTransaction { + GossipStatus gossip_status = 1; + enum GossipStatus { + UNKNOWN = 0; + GOSSIP = 1; + NO_GOSSIP = 2; + } + repeated bytes removals =2 +} +``` + +#### `UpdateTransactionGossipList` + +`UpdateTransactionGossipList` would be a simple method that allows the +application to exactly set the contents of the `GossipList`. Tendermint would +call `UpdateTransactionGossipList` on the application, which would respond with +the list of all transactions to gossip. The contents of the `GossipList` would +be completely replaced with the contents provided by the application in +`UpdateTransactionGossipList`. + +```proto +message UpdateTransactionGossipListRequest { + int64 max_size = 1; // application cannot provide more than `max_size` transactions. +} + +message UpdateTransactionGossipListResponse { + repeated bytes = 1; +} +``` + +This new `ABCI` method would serve multiple functions. First, it would replace +the re-`CheckTx` calls made by Tendermint after each block is committed. After +each block is committed, Tendermint currently passes the entire contents of the +mempool to the application one-by-one via `CheckTx` calls with `CheckTxType` set +to `RECHECK`. The application, in this way, can then inspect the entire mempool +and remove any transactions that became invalid as a result of the most recent +block being committed. + +`UpdateTransactionGossipList` would completely replace this set of re-`CheckTx` +calls. After each block is committed, Tendermint would call +`UpdateTransactionGossipList` and the application would be responsible for +exactly providing the set of transactions for Tendermint to maintain. The IPC +overhead here would be roughly equivalent to the re-`CheckTx` overhead, as the +entire contents of the gossip structure is communicated, but, in the +`UpdateTransactionGossipList` call, the application sends transactions instead +of Tendermint. + +This new method would _also_ replace the mempool's `Update` API. The `Update` +method on the mempool receives the list of transactions that were just executed +as part of the most recent height and removes them from the mempool. The +`GossipList` would have no such method and instead, the application would become +responsible for setting the contents after each block via +`UpdateTransactionGossipList`. This gives the application more control over when +to start and stop gossiping transactions than it has at the moment. In this +call, the application can completely replace the `GossipList`. + +This also complements the `PrepareProposal` call nicely, because a transaction +introduced via `PrepareProposal` may be semantically equivalent to a transaction +present in Tendermint's mempool in a way that Tendermint cannot detect. The +mempool `Update` call only compares transaction hashes, +`UpdateTransactionGossipList` allows the application to easily compare on +transaction contents as well. + +As a nice benefit, it also allows the application to easily continue gossiping +of a transaction that was just executed in the block. Applications may wish to +execute the same transaction multiple times, which the mempool `Update` call +makes very cumbersome by clearing transactions that have the same contents of +those that were just executed. + +### Tendermint startup + +On Tendermint startup, the `GossipList` would be completely empty. It does not +persist transactions and is an in-memory only data structure. To populate the +`GossipList` on startup, Tendermint will issue an `UpdateTransactionGossipList` +call to the application to request the application provide it with a list of +transactions to fill the gossip list. + +### Additional benefits of this API + +#### No more confusing mempool cache + +The current Tendermint mempool stores a [cache][cache-when-clear] of transaction +hashes that should not be accepted into the mempool. When a transaction is sent +to the mempool but is present in the cache the transaction is dropped without +ever being sent to the application via `CheckTx`. This cache is intended to help +the application guard against receiving the same invalid transaction over and +over. However, this means that presence or absence from the mempool cache +becomes a condition of validity for pending transactions. + +Being placed in this cache has serious consequences for a proposed transaction, +but the rules for when a transaction should be placed in this cache are unclear. +So unclear in fact, that conditions for when to include a transaction in this +cache have been completely reversed by different commits +([1][update-remove-from-cache],[2][update-keep-in-cache]) on the Tendermint +project. Additional github issues have noted that it's very ambiguous as to +[when the cache should be cleared][cache-when-clear] and whether or not the +cache should allow [previously invalid transactions][later-valid] to later +become valid. There is no one-size-fits all solution to these problems. +Different applications need very different behavior, so this should ultimately +not be the responsibility of Tendermint. Implementing the `GossipList` clears +Tendermint of this responsibility. + +#### Improved guarantees about the set of transactions being gossiped + +As discussed in the [Mock API](#mock-api-of-the-gossiplist) section, the +`GossipList` only adds and removes or replaces transactions in the `GossipList` +when the application says to. Under this design, the contents of this list are +never ambiguous. The list contains exactly what the application most recently +told Tendermint to gossip, nothing more nothing less. + +### Additional considerations + +This document leaves a few aspects unconsidered that should be understood before +future designs are made in this area: + +1. Impact of duplicating transactions in both the `GossipList` and within the + application. +2. Transition plan and feasibility of migrating applications to the new API. + +## References + +[cache-when-clear]:https://github.com/tendermint/tendermint/issues/7723 +[update-remove-from-cache]:https://github.com/tendermint/tendermint/pull/233 +[update-keep-in-cache]:https://github.com/tendermint/tendermint/issues/2855 +[later-valid]:https://github.com/tendermint/tendermint/issues/458 +[mempool-link]:https://github.com/tendermint/tendermint/blob/c8302c5fcb7f1ffafdefc5014a26047df1d27c99/mempool/mempool.go#L30 diff --git a/docs/rfc/tendermint-core/rfc-027-p2p-message-bandwidth-report.md b/docs/rfc/tendermint-core/rfc-027-p2p-message-bandwidth-report.md new file mode 100644 index 0000000..b0d5066 --- /dev/null +++ b/docs/rfc/tendermint-core/rfc-027-p2p-message-bandwidth-report.md @@ -0,0 +1,287 @@ +# RFC 27: P2P Message Bandwidth Report + +## Changelog + +- Nov 7, 2022: initial draft (@williambanfield) +- Nov 15, 2022: draft completed (@williambanfield) + +## Abstract + +Node operators and application developers complain that Tendermint nodes consume +larges amounts of network bandwidth. This RFC catalogues the major sources of bandwidth +consumption within Tendermint and suggests modifications to Tendermint that may reduce +bandwidth consumption for nodes. + +## Background +Multiple teams running validators in production report that the validator +consumes a lot of bandwidth. They report that operators running on a network +with hundreds of validators consumes multiple terabytes of bandwidth per day. +Prometheus data collected from a validator node running on the Osmosis chain +shows that Tendermint sends and receives large amounts of data to peers. In the +nearly three hours of observation, Tendermint sent nearly 42 gigabytes and +received about 26 gigabytes, for an estimated 366 gigabytes sent daily and 208 +gigabytes received daily. While this is shy of the reported terabytes number, +operators running multiple nodes for a 'sentry' pattern could easily send and +receive a terabyte of data. + +Sending and receiving large amounts of data has a cost for node operators. Most +cloud platforms charge for network traffic egress. Google Cloud charges between +[$.05 to $.12 per gigabyte of egress traffic][gcloud-pricing], and ingress is +free. Hetzner [charges 1€ per TB used over the 10-20TB base bandwidth per +month][hetzner-pricing], which will be easily hit if multiple terabytes are +sent and received per day. Using the values collected from the validator on +Osmosis, a single node on Google cloud may cost $18 to $44 a day running on +Google cloud. On Hetzner, the estimated 18TB a month of both sending and +receiving may cost between 0 and 10 Euro a month per node. + +## Discussion + +### Overview of Major Bandwidth Usage + +To determine which components of Tendermint were consuming the most bandwidth, +I gathered prometheus metrics from the [Blockpane][blockpane] validator running +on the Osmosis network for several hours. The data reveal that three message +types account for 98% of the total bandwidth consumed. These message types are +as follows: + + +1. [consensus.BlockPart][block-part-message] +2. [mempool.Txs][mempool-txs-message] +3. [consensus.Vote][vote-message] + + +The image below of p2p data collected from the Blockpane validator illustrate +the total bandwidth consumption of these three message types. + + +#### Send: + +##### Top 3 Percent: + +![](./images/top-3-percent-send.png) + +##### Rate For All Messages: + +![](./images/send-rate-all.png) + +#### Receive: + +##### Top 3 Percent: + +![](./images/top-3-percent-receive.png) + +##### Rate For All Messages: + +![](./images/receive-rate-all.png) + +### Investigation of Message Usage + +This section discusses the usage of each of the three highest consumption messages. +#### BlockPart Transmission + +Sending `BlockPart` messages consumes the most bandwidth out of all p2p +messages types as observed in the Blockpane Osmosis validator. In the almost 3 +hour observation, the validator sent about 20 gigabytes of `BlockPart` +messages. + +A block is proposed each round of Tendermint consensus. The paper does not +define a specific way that the block is to be transmitted, just that all +participants will receive it via a gossip network. + +The Go implementation of Tendermint transmits the block in 'parts'. It +serializes the block to wire-format proto and splits this byte representation +into a set of 4 kilobyte arrays and sends these arrays to its peers, each in a +separate message. + +The logic for sending `BlockPart` messages resides in the code for the +[consensus.Reactor][gossip-data-routine]. The consensus reactor starts a new +`gossipDataRoutine` for each peer it connects to. This routine repeatedly picks +a part of the block that Tendermint believes the peer does not know about yet +and gossips it to the peer. The set of `BlockParts` that Tendermint considers +its peer as having is only updated in one of four ways: + + + 1. Our peer tells us they have entered a new round [via a `NewRoundStep` +message][new-round-step-message-send]. This message is only sent when a node +moves to a new round or height and only resets the data we collect about a +peer's blockpart state. + 1. [We receive a block part from the peer][block-part-receive]. + 1. [We send][block-part-send-1] [the peer a block part][block-part-send-2]. + 1. Our peer tells us about the parts they have block [via `NewValidBlock` +messages][new-valid-block-message-send]. This message is only sent when the +peer has a quorum of prevotes or precommits for a block. + +Each node receives block parts from all of its peers. The particular block part +to send at any given time is randomly selected from the set of parts that the +peer node is not yet known to have. Given that these are the only times that +Tendermint learns of its peers' block parts, it's very likely that a node has +an incomplete understanding of its peers' block parts and is transmitting block +parts to a peer that the peer has received from some other node. + +Multiple potential mechanisms exist to reduce the number of duplicate block +parts a node receives. One set of mechanisms relies on more frequently +communicating the set of block parts a node needs to its peers. Another +potential mechanism requires a larger overhaul to the way blocks are gossiped +in the network. + +#### Mempool Tx Transmission + +The Tendermint mempool stages transactions that are yet to be committed to the +blockchain and communicates these transactions to its peers. Each message +contains one transaction. Data collected from the Blockpane node running on +Osmosis indicates that the validator sent about 12 gigabytes of `Txs` messages +during the nearly 3 hour observation period. + +The Tendermint mempool starts a new [broadcastTxRoutine][broadcast-tx-routine] +for each peer that it is informed of. The routine sends all transactions that +the mempool is aware of to all peers with few exceptions. The only exception is +if the mempool received a transaction from a peer, then it marks it as such and +won't resend to that peer. Otherwise, it retains no information about which +transactions it already sent to a peer. In some cases it may therefore resend +transactions the peer already has. This can occur if the mempool removes a +transaction from the `CList` data structure used to store the list of +transactions while it is about to be sent and if the transaction was the tail +of the `CList` during removal. This will be more likely to occur if a large +number of transactions from the end of the list are removed during `RecheckTx`, +since multiple transactions will become the tail and then be deleted. It is +unclear at the moment how frequently this occurs on production chains. + +Beyond ensuring that transactions are rebroadcast to peers less frequently, +there is not a simple scheme to communicate fewer transactions to peers. Peers +cannot communicate what transactions they need since they do not know which +transactions exist on the network. + +#### Vote Transmission + +Tendermint votes, both prevotes and precommits, are central to Tendermint +consensus and are gossiped by all nodes to all peers during each consensus +round. Data collected from the Blockpane node running on Osmosis indicates that +about 9 gigabytes of `Vote` messages were sent during the nearly 3 hour period +of observation. Examination of the [Vote message][vote-msg] indicates that it +contains 184 bytes of data, with the proto encoding adding a few additional +bytes when transmitting. + +The Tendermint consensus reactor starts a new +[gossipVotesRoutine][gossip-votes-routine] for each peer that it connects to. +The reactor sends all votes to all peers unless it knows that the peer already +has the vote or the reactor learns that the peer is in a different round and +that thus the vote no longer applies. Tendermint learns that a peer has a vote +in one of 4 ways: + + 1. Tendermint sent the peer the vote. + 1. Tendermint received the vote from the peer. + 1. The peer [sent a `HasVote` message][apply-has-vote]. This message is broadcast +to all peers [each time validator receives a vote it hasn't seen before +corresponding to its current height and round][publish-event-vote]. + 1. The peer [sent a `VoteSetBits` message][apply-vote-set-bits]. This message is +[sent as a response to a peer that sends a `VoteSetMaj23`][vote-set-bits-send]. + +Given that Tendermint informs all peers of _each_ vote message it receives, all +nodes should be well informed of which votes their peers have. Given that the +vote messages were the third largest consumer of bandwidth in the observation +on Osmosis, it's possible that this system is not currently working correctly. +Further analysis should examine where votes may be being retransmitted. + +### Suggested Improvements to Lower Message Transmission Bandwidth + +#### Gossip Known BlockPart Data + +The `BlockPart` messages, by far, account for the majority of the data sent to +each peer. At the moment, peers do not inform the node of which block parts +they already have. This means that each block part is _very likely_ to be +transmitted many times to each node. This frivolous consumption is even worse +in networks with large blocks. + +The very simple solution to this issue is to copy the technique used in +consensus for informing peers when the node receives a vote. The consensus +reactor can be augmented with a `HasBlockPart` message that is broadcast to +each peer every time the node receives a block part. By informing each peer +every time the node receives a block part, we can drastically reduce the amount +of duplicate data sent to each node. There would be no algorithmic way of +enforcing that a peer accurately reports its block parts, so providing this +message would be a somewhat altruistic action on the part of the node. Such a +system [has been proposed in the past][i627] as well, so this is certainly not +totally new ground. + +Measuring the size of duplicately received blockparts before and after this +change would help validate this approach. + +#### Compress Transmitted Data + +Tendermint's data is sent uncompressed on the wire. The messages are not +compressed before sending and the transport performs no compression either. +Some of the information communicated by Tendermint is a poor candidate for +compression: Data such as digital signatures and hashes have high entropy and +therefore do not compress well. However, transactions may contain lots of +information that has less entropy. Compression within Tendermint may be added +at several levels. Compression may be performed at the [Tendermint 'packet' +level][must-wrap-packet] or at the [Tendermint message send +level][message-send]. + +#### Transmit Less Data During Block Gossip + +Block, vote, and mempool gossiping transmit much of same data. The mempool +reactor gossips candidate transactions to each peer. The consensus reactor, +when gossiping the votes, sends vote metadata and the digital signature of that +signs over that metadata. Finally, when a block is proposed, the proposing node +amalgamates the received votes, a set of transaction, and adds a header to +produce the block. This block is then serialized and gossiped as a list of +bytes. However, the data that the block contains, namely the votes and the +transactions were most likely _already transmitted to the nodes on the network_ +via mempool transaction gossip and consensus vote gossip. + +Therefore, block gossip can be updated to transmit a representation of the data +contained in the block that assumes the peers will already have most of this +data. Namely, the block gossip can be updated to only send 1) a list of +transaction hashes and 2) a bit array of votes selected for the block along +with the header and other required block metadata. + +This new proposed method for gossiping block data could accompany a slight +update to the mempool transaction gossip and consensus vote gossip. Since all +of the contents of each block will not be gossiped together, it's possible that +some nodes are missing a proposed transaction or the vote of a validator +indicated in the new block gossip format during block gossip. The mempool and +consensus reactors may therefore be updated to provide a `NeedTxs` and +`NeedVotes` message. Each of these messages would allow a node to request a set +of data from their peers. When a node receives one of these, it will then +transmit the Tx/Votes indicate in the associated message regardless of whether +it believes it has transmitted them to the peer before. The gossip layer will +ensure that each peer eventually receives all of the data in the block. +However, if a transaction is needed immediately by a peer so that it can verify +and execute a block during consensus, a mechanism such as the `NeedTxs` and +`NeedVotes` messages should be added to ensure it receives the messages +quickly. + +The same logic may applied for evidence transmission as well, since all nodes +should receive evidence and therefore do not need to re-transmit it in a block +part. + +A similar idea has been proposed in the past as [Compact Block +Propagation][compact-block-propagation]. + + +## References + +[blockpane]: https://www.mintscan.io/osmosis/validators/osmovaloper1z0sh4s80u99l6y9d3vfy582p8jejeeu6tcucs2 +[block-part-message]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/proto/tendermint/consensus/types.proto#L44 +[mempool-txs-message]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/proto/tendermint/mempool/types.proto#L6 +[vote-message]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/proto/tendermint/consensus/types.proto#L51 +[gossip-data-routine]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L537 +[block-part-receive]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L324 +[block-part-send-1]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L566 +[block-part-send-2]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L684. +[new-valid-block-message-send]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L268 +[new-round-step-message-send]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L266 +[broadcast-tx-routine]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/mempool/v0/reactor.go#L197 +[gossip-votes-routine]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L694 +[apply-has-vote]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L1429 +[apply-vote-set-bits]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L1445 +[publish-event-vote]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/state.go#L2083 +[vote-set-bits-send]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/consensus/reactor.go#L306 +[must-wrap-packet]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/p2p/conn/connection.go#L889-L918 +[message-send]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/p2p/peer.go#L285 +[gcloud-pricing]: https://cloud.google.com/vpc/network-pricing#vpc-pricing +[hetzner-pricing]: https://docs.hetzner.com/robot/general/traffic +[vote-msg]: https://github.com/tendermint/tendermint/blob/ff0f98892f24aac11e46aeff2b6d2c0ad816701a/proto/tendermint/types/types.pb.go#L468 +[i627]: https://github.com/tendermint/tendermint/issues/627 +[compact-block-propagation]: https://github.com/tendermint/tendermint/issues/7932 diff --git a/docs/tools/README.md b/docs/tools/README.md new file mode 100644 index 0000000..52dbf78 --- /dev/null +++ b/docs/tools/README.md @@ -0,0 +1,20 @@ +--- +order: 1 +parent: + title: Tools + order: 5 +--- + +# Overview + +CometBFT has some tools that are associated with it for: + +- [Debugging](./debugging.md) +- [Benchmarking](#benchmarking) + +## Benchmarking + +- + +`tm-load-test` is a distributed load testing tool (and framework) for load +testing CometBFT networks. diff --git a/docs/tools/debugging.md b/docs/tools/debugging.md new file mode 100644 index 0000000..eee7e2b --- /dev/null +++ b/docs/tools/debugging.md @@ -0,0 +1,105 @@ +--- +order: 1 +--- + +# Debugging + +## CometBFT debug kill + +CometBFT comes with a `debug` sub-command that allows you to kill a live +CometBFT process while collecting useful information in a compressed archive. +The information includes the configuration used, consensus state, network +state, the node' status, the WAL, and even the stack trace of the process +before exit. These files can be useful to examine when debugging a faulty +CometBFT process. + +```bash +cometbft debug kill --home= +``` + +will write debug info into a compressed archive. The archive will contain the +following: + +```sh +├── config.toml +├── consensus_state.json +├── net_info.json +├── stacktrace.out +├── status.json +└── wal +``` + +Under the hood, `debug kill` fetches info from `/status`, `/net_info`, and +`/dump_consensus_state` HTTP endpoints, and kills the process with `-6`, which +catches the go-routine dump. + +## CometBFT debug dump + +Also, the `debug dump` sub-command allows you to dump debugging data into +compressed archives at a regular interval. These archives contain the goroutine +and heap profiles in addition to the consensus state, network info, node +status, and even the WAL. + +```bash +cometbft debug dump --home= +``` + +will perform similarly to `kill` except it only polls the node and +dumps debugging data every frequency seconds to a compressed archive under a +given destination directory. Each archive will contain: + +```sh +├── consensus_state.json +├── goroutine.out +├── heap.out +├── net_info.json +├── status.json +└── wal +``` + +Note: goroutine.out and heap.out will only be written if a profile address is +provided and is operational. This command is blocking and will log any error. + +## CometBFT Inspect + +CometBFT includes an `inspect` command for querying CometBFT's state store and block +store over CometBFT RPC. + +When the CometBFT consensus engine detects inconsistent state, it will crash the +entire CometBFT process. +While in this inconsistent state, a node running CometBFT will not start up. +The `inspect` command runs only a subset of CometBFT's RPC endpoints for querying the block store +and state store. +`inspect` allows operators to query a read-only view of the stage. +`inspect` does not run the consensus engine at all and can therefore be used to debug +processes that have crashed due to inconsistent state. + +### Running inspect + +Start up the `inspect` tool on the machine where CometBFT crashed using: +```bash +cometbft inspect --home= +``` + +`inspect` will use the data directory specified in your CometBFT configuration file. +`inspect` will also run the RPC server at the address specified in your CometBFT configuration file. + +### Using inspect + +With the `inspect` server running, you can access RPC endpoints that are critically important +for debugging. +Calling the `/status`, `/consensus_state` and `/dump_consensus_state` RPC endpoint +will return useful information about the CometBFT consensus state. + +To start the `inspect` process, run +```bash +cometbft inspect +``` + +### RPC endpoints + +The list of available RPC endpoints can be found by making a request to the RPC port. +For an `inspect` process running on `127.0.0.1:26657`, navigate your browser to +`http://127.0.0.1:26657/` to retrieve the list of enabled RPC endpoints. + +Additional information on the CometBFT RPC endpoints can be found in the [rpc documentation](https://docs.cometbft.com/v0.38/rpc). diff --git a/dredd.yml b/dredd.yml new file mode 100644 index 0000000..142fdce --- /dev/null +++ b/dredd.yml @@ -0,0 +1,33 @@ +color: true +dry-run: null +hookfiles: build/contract_tests +language: go +require: null +server: make localnet-start +server-wait: 30 +init: false +custom: {} +names: false +only: [] +reporter: [] +output: [] +header: [] +sorted: false +user: null +inline-errors: false +details: false +method: [GET] +loglevel: warning +path: [] +hooks-worker-timeout: 5000 +hooks-worker-connect-timeout: 1500 +hooks-worker-connect-retry: 500 +hooks-worker-after-connect-wait: 100 +hooks-worker-term-timeout: 5000 +hooks-worker-term-retry: 500 +hooks-worker-handler-host: 127.0.0.1 +hooks-worker-handler-port: 61321 +config: ./dredd.yml +# This path accepts no variables +blueprint: ./rpc/openapi/openapi.yaml +endpoint: "http://127.0.0.1:26657/" diff --git a/evidence/doc.go b/evidence/doc.go new file mode 100644 index 0000000..1ef9fea --- /dev/null +++ b/evidence/doc.go @@ -0,0 +1,52 @@ +/* +Package evidence handles all evidence storage and gossiping from detection to block proposal. +For the different types of evidence refer to the `evidence.go` file in the types package +or https://github.com/cometbft/cometbft/blob/v0.38.x/spec/consensus/light-client/accountability.md. + +# Gossiping + +The core functionality begins with the evidence reactor (see reactor. +go) which operates both the sending and receiving of evidence. + +The `Receive` function takes a list of evidence and does the following: + +1. Checks that it does not already have the evidence stored + +2. Verifies the evidence against the node's state (see state/validation.go#VerifyEvidence) + +3. Stores the evidence to a db and a concurrent list + +The gossiping of evidence is initiated when a peer is added which starts a go routine to broadcast currently +uncommitted evidence at intervals of 60 seconds (set by the by broadcastEvidenceIntervalS). +It uses a concurrent list to store the evidence and before sending verifies that each evidence is still valid in the +sense that it has not exceeded the max evidence age and height (see types/params.go#EvidenceParams). + +There are two buckets that evidence can be stored in: Pending & Committed. + +1. Pending is awaiting to be committed (evidence is usually broadcasted then) + +2. Committed is for those already on the block and is to ensure that evidence isn't submitted twice + +All evidence is proto encoded to disk. + +# Proposing + +When a new block is being proposed (in state/execution.go#CreateProposalBlock), +`PendingEvidence(maxBytes)` is called to send up to the maxBytes of uncommitted evidence, from the evidence store, +prioritized in order of age. All evidence is checked for expiration. + +When a node receives evidence in a block it will use the evidence module as a cache first to see if it has +already verified the evidence before trying to verify it again. + +Once the proposed evidence is submitted, +the evidence is marked as committed and is moved from the broadcasted set to the committed set. +As a result it is also removed from the concurrent list so that it is no longer gossiped. + +# Minor Functionality + +As all evidence (including POLC's) are bounded by an expiration date, those that exceed this are no longer needed +and hence pruned. Currently, only committed evidence in which a marker to the height that the evidence was committed +and hence very small is saved. All updates are made from the `Update(block, state)` function which should be called +when a new block is committed. +*/ +package evidence diff --git a/evidence/mocks/block_store.go b/evidence/mocks/block_store.go new file mode 100644 index 0000000..bcbc19c --- /dev/null +++ b/evidence/mocks/block_store.go @@ -0,0 +1,85 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + types "github.com/cometbft/cometbft/types" + mock "github.com/stretchr/testify/mock" +) + +// BlockStore is an autogenerated mock type for the BlockStore type +type BlockStore struct { + mock.Mock +} + +// Height provides a mock function with no fields +func (_m *BlockStore) Height() int64 { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Height") + } + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// LoadBlockCommit provides a mock function with given fields: height +func (_m *BlockStore) LoadBlockCommit(height int64) *types.Commit { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockCommit") + } + + var r0 *types.Commit + if rf, ok := ret.Get(0).(func(int64) *types.Commit); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Commit) + } + } + + return r0 +} + +// LoadBlockMeta provides a mock function with given fields: height +func (_m *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockMeta") + } + + var r0 *types.BlockMeta + if rf, ok := ret.Get(0).(func(int64) *types.BlockMeta); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockMeta) + } + } + + return r0 +} + +// NewBlockStore creates a new instance of BlockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockStore(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockStore { + mock := &BlockStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/evidence/pool.go b/evidence/pool.go new file mode 100644 index 0000000..c90d915 --- /dev/null +++ b/evidence/pool.go @@ -0,0 +1,573 @@ +package evidence + +import ( + "bytes" + "errors" + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/cosmos/gogoproto/proto" + gogotypes "github.com/cosmos/gogoproto/types" + + dbm "github.com/cometbft/cometbft-db" + + clist "github.com/cometbft/cometbft/libs/clist" + "github.com/cometbft/cometbft/libs/log" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +const ( + baseKeyCommitted = byte(0x00) + baseKeyPending = byte(0x01) +) + +// Pool maintains a pool of valid evidence to be broadcasted and committed +type Pool struct { + logger log.Logger + + evidenceStore dbm.DB + evidenceList *clist.CList // concurrent linked-list of evidence + evidenceSize uint32 // amount of pending evidence + + // needed to load validators to verify evidence + stateDB sm.Store + // needed to load headers and commits to verify evidence + blockStore BlockStore + + mtx sync.Mutex + // latest state + state sm.State + // evidence from consensus is buffered to this slice, awaiting until the next height + // before being flushed to the pool. This prevents broadcasting and proposing of + // evidence before the height with which the evidence happened is finished. + consensusBuffer []duplicateVoteSet + + pruningHeight int64 + pruningTime time.Time +} + +// NewPool creates an evidence pool. If using an existing evidence store, +// it will add all pending evidence to the concurrent list. +func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) { + state, err := stateDB.Load() + if err != nil { + return nil, fmt.Errorf("cannot load state: %w", err) + } + + pool := &Pool{ + stateDB: stateDB, + blockStore: blockStore, + state: state, + logger: log.NewNopLogger(), + evidenceStore: evidenceDB, + evidenceList: clist.New(), + consensusBuffer: make([]duplicateVoteSet, 0), + } + + // if pending evidence already in db, in event of prior failure, then check for expiration, + // update the size and load it back to the evidenceList + pool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence() + evList, _, err := pool.listEvidence(baseKeyPending, -1) + if err != nil { + return nil, err + } + atomic.StoreUint32(&pool.evidenceSize, uint32(len(evList))) + for _, ev := range evList { + pool.evidenceList.PushBack(ev) + } + + return pool, nil +} + +// PendingEvidence is used primarily as part of block proposal and returns up to maxNum of uncommitted evidence. +func (evpool *Pool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) { + if evpool.Size() == 0 { + return []types.Evidence{}, 0 + } + evidence, size, err := evpool.listEvidence(baseKeyPending, maxBytes) + if err != nil { + evpool.logger.Error("Unable to retrieve pending evidence", "err", err) + } + return evidence, size +} + +// Update takes both the new state and the evidence committed at that height and performs +// the following operations: +// 1. Take any conflicting votes from consensus and use the state's LastBlockTime to form +// DuplicateVoteEvidence and add it to the pool. +// 2. Update the pool's state which contains evidence params relating to expiry. +// 3. Moves pending evidence that has now been committed into the committed pool. +// 4. Removes any expired evidence based on both height and time. +func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) { + // sanity check + if state.LastBlockHeight <= evpool.state.LastBlockHeight { + panic(fmt.Sprintf( + "failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d", + state.LastBlockHeight, + evpool.state.LastBlockHeight, + )) + } + evpool.logger.Debug("Updating evidence pool", "last_block_height", state.LastBlockHeight, + "last_block_time", state.LastBlockTime) + + // flush conflicting vote pairs from the buffer, producing DuplicateVoteEvidence and + // adding it to the pool + evpool.processConsensusBuffer(state) + // update state + evpool.updateState(state) + + // move committed evidence out from the pending pool and into the committed pool + evpool.markEvidenceAsCommitted(ev) + + // prune pending evidence when it has expired. This also updates when the next evidence will expire + if evpool.Size() > 0 && state.LastBlockHeight > evpool.pruningHeight && + state.LastBlockTime.After(evpool.pruningTime) { + evpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence() + } +} + +// AddEvidence checks the evidence is valid and adds it to the pool. +func (evpool *Pool) AddEvidence(ev types.Evidence) error { + evpool.logger.Info("Attempting to add evidence", "ev", ev) + + // We have already verified this piece of evidence - no need to do it again + if evpool.isPending(ev) { + evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev) + return nil + } + + // check that the evidence isn't already committed + if evpool.isCommitted(ev) { + // this can happen if the peer that sent us the evidence is behind so we shouldn't + // punish the peer. + evpool.logger.Info("Evidence was already committed, ignoring this one", "ev", ev) + return nil + } + + // 1) Verify against state. + err := evpool.verify(ev) + if err != nil { + return types.NewErrInvalidEvidence(ev, err) + } + + // 2) Save to store. + if err := evpool.addPendingEvidence(ev); err != nil { + return fmt.Errorf("can't add evidence to pending list: %w", err) + } + + // 3) Add evidence to clist. + evpool.evidenceList.PushBack(ev) + + evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev) + + return nil +} + +// ReportConflictingVotes takes two conflicting votes and forms duplicate vote evidence, +// adding it eventually to the evidence pool. +// +// Duplicate vote attacks happen before the block is committed and the timestamp is +// finalized, thus the evidence pool holds these votes in a buffer, forming the +// evidence from them once consensus at that height has been reached and `Update()` with +// the new state called. +// +// Votes are not verified. +func (evpool *Pool) ReportConflictingVotes(voteA, voteB *types.Vote) { + evpool.mtx.Lock() + defer evpool.mtx.Unlock() + evpool.consensusBuffer = append(evpool.consensusBuffer, duplicateVoteSet{ + VoteA: voteA, + VoteB: voteB, + }) +} + +// CheckEvidence takes an array of evidence from a block and verifies all the evidence there. +// If it has already verified the evidence then it jumps to the next one. It ensures that no +// evidence has already been committed or is being proposed twice. It also adds any +// evidence that it doesn't currently have so that it can quickly form ABCI Evidence later. +func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error { + hashes := make([][]byte, len(evList)) + for idx, ev := range evList { + + _, isLightEv := ev.(*types.LightClientAttackEvidence) + + // We must verify light client attack evidence regardless because there could be a + // different conflicting block with the same hash. + if isLightEv || !evpool.isPending(ev) { + // check that the evidence isn't already committed + if evpool.isCommitted(ev) { + return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")} + } + + err := evpool.verify(ev) + if err != nil { + return err + } + + if err := evpool.addPendingEvidence(ev); err != nil { + // Something went wrong with adding the evidence but we already know it is valid + // hence we log an error and continue + evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev) + } + + evpool.logger.Info("Check evidence: verified evidence of byzantine behavior", "evidence", ev) + } + + // check for duplicate evidence. We cache hashes so we don't have to work them out again. + hashes[idx] = ev.Hash() + for i := idx - 1; i >= 0; i-- { + if bytes.Equal(hashes[i], hashes[idx]) { + return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")} + } + } + } + + return nil +} + +// EvidenceFront goes to the first evidence in the clist +func (evpool *Pool) EvidenceFront() *clist.CElement { + return evpool.evidenceList.Front() +} + +// EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil +func (evpool *Pool) EvidenceWaitChan() <-chan struct{} { + return evpool.evidenceList.WaitChan() +} + +// SetLogger sets the Logger. +func (evpool *Pool) SetLogger(l log.Logger) { + evpool.logger = l +} + +// Size returns the number of evidence in the pool. +func (evpool *Pool) Size() uint32 { + return atomic.LoadUint32(&evpool.evidenceSize) +} + +// State returns the current state of the evpool. +func (evpool *Pool) State() sm.State { + evpool.mtx.Lock() + defer evpool.mtx.Unlock() + return evpool.state +} + +func (evpool *Pool) Close() error { + return evpool.evidenceStore.Close() +} + +// IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older +// than set by the evidence consensus parameters +func (evpool *Pool) isExpired(height int64, time time.Time) bool { + var ( + params = evpool.State().ConsensusParams.Evidence + ageDuration = evpool.State().LastBlockTime.Sub(time) + ageNumBlocks = evpool.State().LastBlockHeight - height + ) + return ageNumBlocks > params.MaxAgeNumBlocks && + ageDuration > params.MaxAgeDuration +} + +// IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed. +func (evpool *Pool) isCommitted(evidence types.Evidence) bool { + key := keyCommitted(evidence) + ok, err := evpool.evidenceStore.Has(key) + if err != nil { + evpool.logger.Error("Unable to find committed evidence", "err", err) + } + return ok +} + +// IsPending checks whether the evidence is already pending. DB errors are passed to the logger. +func (evpool *Pool) isPending(evidence types.Evidence) bool { + key := keyPending(evidence) + ok, err := evpool.evidenceStore.Has(key) + if err != nil { + evpool.logger.Error("Unable to find pending evidence", "err", err) + } + return ok +} + +func (evpool *Pool) addPendingEvidence(ev types.Evidence) error { + evpb, err := types.EvidenceToProto(ev) + if err != nil { + return fmt.Errorf("unable to convert to proto, err: %w", err) + } + + evBytes, err := evpb.Marshal() + if err != nil { + return fmt.Errorf("unable to marshal evidence: %w", err) + } + + key := keyPending(ev) + + err = evpool.evidenceStore.Set(key, evBytes) + if err != nil { + return fmt.Errorf("can't persist evidence: %w", err) + } + atomic.AddUint32(&evpool.evidenceSize, 1) + return nil +} + +func (evpool *Pool) removePendingEvidence(evidence types.Evidence) { + key := keyPending(evidence) + if err := evpool.evidenceStore.Delete(key); err != nil { + evpool.logger.Error("Unable to delete pending evidence", "err", err) + } else { + atomic.AddUint32(&evpool.evidenceSize, ^uint32(0)) + evpool.logger.Debug("Deleted pending evidence", "evidence", evidence) + } +} + +// markEvidenceAsCommitted processes all the evidence in the block, marking it as +// committed and removing it from the pending database. +func (evpool *Pool) markEvidenceAsCommitted(evidence types.EvidenceList) { + blockEvidenceMap := make(map[string]struct{}, len(evidence)) + for _, ev := range evidence { + if evpool.isPending(ev) { + evpool.removePendingEvidence(ev) + blockEvidenceMap[evMapKey(ev)] = struct{}{} + } + + // Add evidence to the committed list. As the evidence is stored in the block store + // we only need to record the height that it was saved at. + key := keyCommitted(ev) + + h := gogotypes.Int64Value{Value: ev.Height()} + evBytes, err := proto.Marshal(&h) + if err != nil { + evpool.logger.Error("failed to marshal committed evidence", "err", err, "key(height/hash)", key) + continue + } + + if err := evpool.evidenceStore.Set(key, evBytes); err != nil { + evpool.logger.Error("Unable to save committed evidence", "err", err, "key(height/hash)", key) + } + } + + // remove committed evidence from the clist + if len(blockEvidenceMap) != 0 { + evpool.removeEvidenceFromList(blockEvidenceMap) + } +} + +// listEvidence retrieves lists evidence from oldest to newest within maxBytes. +// If maxBytes is -1, there's no cap on the size of returned evidence. +func (evpool *Pool) listEvidence(prefixKey byte, maxBytes int64) ([]types.Evidence, int64, error) { + var ( + evSize int64 + totalSize int64 + evidence []types.Evidence + evList cmtproto.EvidenceList // used for calculating the bytes size + ) + + iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey}) + if err != nil { + return nil, totalSize, fmt.Errorf("database error: %v", err) + } + defer iter.Close() + for ; iter.Valid(); iter.Next() { + var evpb cmtproto.Evidence + err := evpb.Unmarshal(iter.Value()) + if err != nil { + return evidence, totalSize, err + } + evList.Evidence = append(evList.Evidence, evpb) + evSize = int64(evList.Size()) + if maxBytes != -1 && evSize > maxBytes { + if err := iter.Error(); err != nil { + return evidence, totalSize, err + } + return evidence, totalSize, nil + } + + ev, err := types.EvidenceFromProto(&evpb) + if err != nil { + return nil, totalSize, err + } + + totalSize = evSize + evidence = append(evidence, ev) + } + + if err := iter.Error(); err != nil { + return evidence, totalSize, err + } + return evidence, totalSize, nil +} + +func (evpool *Pool) removeExpiredPendingEvidence() (int64, time.Time) { + iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending}) + if err != nil { + evpool.logger.Error("Unable to iterate over pending evidence", "err", err) + return evpool.State().LastBlockHeight, evpool.State().LastBlockTime + } + defer iter.Close() + blockEvidenceMap := make(map[string]struct{}) + for ; iter.Valid(); iter.Next() { + ev, err := bytesToEv(iter.Value()) + if err != nil { + evpool.logger.Error("Error in transition evidence from protobuf", "err", err) + continue + } + if !evpool.isExpired(ev.Height(), ev.Time()) { + if len(blockEvidenceMap) != 0 { + evpool.removeEvidenceFromList(blockEvidenceMap) + } + + // return the height and time with which this evidence will have expired so we know when to prune next + return ev.Height() + evpool.State().ConsensusParams.Evidence.MaxAgeNumBlocks + 1, + ev.Time().Add(evpool.State().ConsensusParams.Evidence.MaxAgeDuration).Add(time.Second) + } + evpool.removePendingEvidence(ev) + blockEvidenceMap[evMapKey(ev)] = struct{}{} + } + // We either have no pending evidence or all evidence has expired + if len(blockEvidenceMap) != 0 { + evpool.removeEvidenceFromList(blockEvidenceMap) + } + return evpool.State().LastBlockHeight, evpool.State().LastBlockTime +} + +func (evpool *Pool) removeEvidenceFromList( + blockEvidenceMap map[string]struct{}, +) { + for e := evpool.evidenceList.Front(); e != nil; e = e.Next() { + // Remove from clist + ev := e.Value.(types.Evidence) + if _, ok := blockEvidenceMap[evMapKey(ev)]; ok { + evpool.evidenceList.Remove(e) + e.DetachPrev() + } + } +} + +func (evpool *Pool) updateState(state sm.State) { + evpool.mtx.Lock() + defer evpool.mtx.Unlock() + evpool.state = state +} + +// processConsensusBuffer converts all the duplicate votes witnessed from consensus +// into DuplicateVoteEvidence. It sets the evidence timestamp to the block height +// from the most recently committed block. +// Evidence is then added to the pool so as to be ready to be broadcasted and proposed. +func (evpool *Pool) processConsensusBuffer(state sm.State) { + evpool.mtx.Lock() + defer evpool.mtx.Unlock() + for _, voteSet := range evpool.consensusBuffer { + + // Check the height of the conflicting votes and fetch the corresponding time and validator set + // to produce the valid evidence + var ( + dve *types.DuplicateVoteEvidence + err error + ) + switch { + case voteSet.VoteA.Height == state.LastBlockHeight: + dve, err = types.NewDuplicateVoteEvidence( + voteSet.VoteA, + voteSet.VoteB, + state.LastBlockTime, + state.LastValidators, + ) + + case voteSet.VoteA.Height < state.LastBlockHeight: + var valSet *types.ValidatorSet + valSet, err = evpool.stateDB.LoadValidators(voteSet.VoteA.Height) + if err != nil { + evpool.logger.Error("failed to load validator set for conflicting votes", "height", + voteSet.VoteA.Height, "err", err, + ) + continue + } + blockMeta := evpool.blockStore.LoadBlockMeta(voteSet.VoteA.Height) + if blockMeta == nil { + evpool.logger.Error("failed to load block time for conflicting votes", "height", voteSet.VoteA.Height) + continue + } + dve, err = types.NewDuplicateVoteEvidence( + voteSet.VoteA, + voteSet.VoteB, + blockMeta.Header.Time, + valSet, + ) + + default: + // evidence pool shouldn't expect to get votes from consensus of a height that is above the current + // state. If this error is seen then perhaps consider keeping the votes in the buffer and retry + // in following heights + evpool.logger.Error("inbound duplicate votes from consensus are of a greater height than current state", + "duplicate vote height", voteSet.VoteA.Height, + "state.LastBlockHeight", state.LastBlockHeight) + continue + } + if err != nil { + evpool.logger.Error("error in generating evidence from votes", "err", err) + continue + } + + // check if we already have this evidence + if evpool.isPending(dve) { + evpool.logger.Info("evidence already pending; ignoring", "evidence", dve) + continue + } + + // check that the evidence is not already committed on chain + if evpool.isCommitted(dve) { + evpool.logger.Info("evidence already committed; ignoring", "evidence", dve) + continue + } + + if err := evpool.addPendingEvidence(dve); err != nil { + evpool.logger.Error("failed to flush evidence from consensus buffer to pending list: %w", err) + continue + } + + evpool.evidenceList.PushBack(dve) + + evpool.logger.Info("verified new evidence of byzantine behavior", "evidence", dve) + } + // reset consensus buffer + evpool.consensusBuffer = make([]duplicateVoteSet, 0) +} + +type duplicateVoteSet struct { + VoteA *types.Vote + VoteB *types.Vote +} + +func bytesToEv(evBytes []byte) (types.Evidence, error) { + var evpb cmtproto.Evidence + err := evpb.Unmarshal(evBytes) + if err != nil { + return &types.DuplicateVoteEvidence{}, err + } + + return types.EvidenceFromProto(&evpb) +} + +func evMapKey(ev types.Evidence) string { + return string(ev.Hash()) +} + +// big endian padded hex +func bE(h int64) string { + return fmt.Sprintf("%0.16X", h) +} + +func keyCommitted(evidence types.Evidence) []byte { + return append([]byte{baseKeyCommitted}, keySuffix(evidence)...) +} + +func keyPending(evidence types.Evidence) []byte { + return append([]byte{baseKeyPending}, keySuffix(evidence)...) +} + +func keySuffix(evidence types.Evidence) []byte { + return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash())) +} diff --git a/evidence/pool_test.go b/evidence/pool_test.go new file mode 100644 index 0000000..29ccbac --- /dev/null +++ b/evidence/pool_test.go @@ -0,0 +1,474 @@ +package evidence_test + +import ( + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/evidence/mocks" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + sm "github.com/cometbft/cometbft/state" + smmocks "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +func TestMain(m *testing.M) { + code := m.Run() + os.Exit(code) +} + +const evidenceChainID = "test_chain" + +var ( + defaultEvidenceTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + defaultEvidenceMaxBytes int64 = 1000 +) + +func TestEvidencePoolBasic(t *testing.T) { + var ( + height = int64(1) + stateStore = &smmocks.Store{} + evidenceDB = dbm.NewMemDB() + blockStore = &mocks.BlockStore{} + ) + + valSet, privVals := types.RandValidatorSet(1, 10) + + blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return( + &types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}}, + ) + stateStore.On("LoadValidators", mock.AnythingOfType("int64")).Return(valSet, nil) + stateStore.On("Load").Return(createState(height+1, valSet), nil) + + pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + + // evidence not seen yet: + evs, size := pool.PendingEvidence(defaultEvidenceMaxBytes) + assert.Equal(t, 0, len(evs)) + assert.Zero(t, size) + + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, privVals[0], evidenceChainID) + require.NoError(t, err) + + // good evidence + evAdded := make(chan struct{}) + go func() { + <-pool.EvidenceWaitChan() + close(evAdded) + }() + + // evidence seen but not yet committed: + assert.NoError(t, pool.AddEvidence(ev)) + + select { + case <-evAdded: + case <-time.After(5 * time.Second): + t.Fatal("evidence was not added to list after 5s") + } + + next := pool.EvidenceFront() + assert.Equal(t, ev, next.Value.(types.Evidence)) + + const evidenceBytes int64 = 372 + evs, size = pool.PendingEvidence(evidenceBytes) + assert.Equal(t, 1, len(evs)) + assert.Equal(t, evidenceBytes, size) // check that the size of the single evidence in bytes is correct + + // shouldn't be able to add evidence twice + assert.NoError(t, pool.AddEvidence(ev)) + evs, _ = pool.PendingEvidence(defaultEvidenceMaxBytes) + assert.Equal(t, 1, len(evs)) +} + +// Tests inbound evidence for the right time and height +func TestAddExpiredEvidence(t *testing.T) { + var ( + val = types.NewMockPV() + height = int64(30) + stateStore = initializeValidatorState(val, height) + evidenceDB = dbm.NewMemDB() + blockStore = &mocks.BlockStore{} + expiredEvidenceTime = time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC) + expiredHeight = int64(2) + ) + + blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(func(h int64) *types.BlockMeta { + if h == height || h == expiredHeight { + return &types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}} + } + return &types.BlockMeta{Header: types.Header{Time: expiredEvidenceTime}} + }) + + pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + + testCases := []struct { + evHeight int64 + evTime time.Time + expErr bool + evDescription string + }{ + {height, defaultEvidenceTime, false, "valid evidence"}, + {expiredHeight, defaultEvidenceTime, false, "valid evidence (despite old height)"}, + {height - 1, expiredEvidenceTime, false, "valid evidence (despite old time)"}, + { + expiredHeight - 1, expiredEvidenceTime, true, + "evidence from height 1 (created at: 2019-01-01 00:00:00 +0000 UTC) is too old", + }, + {height, defaultEvidenceTime.Add(1 * time.Minute), true, "evidence time and block time is different"}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.evDescription, func(t *testing.T) { + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(tc.evHeight, tc.evTime, val, evidenceChainID) + require.NoError(t, err) + err = pool.AddEvidence(ev) + if tc.expErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestReportConflictingVotes(t *testing.T) { + var height int64 = 10 + + pool, pv := defaultTestPool(t, height) + val := types.NewValidator(pv.PrivKey.PubKey(), 10) + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height+1, defaultEvidenceTime, pv, evidenceChainID) + require.NoError(t, err) + + pool.ReportConflictingVotes(ev.VoteA, ev.VoteB) + + // shouldn't be able to submit the same evidence twice + pool.ReportConflictingVotes(ev.VoteA, ev.VoteB) + + // evidence from consensus should not be added immediately but reside in the consensus buffer + evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes) + require.Empty(t, evList) + require.Zero(t, evSize) + + next := pool.EvidenceFront() + require.Nil(t, next) + + // move to next height and update state and evidence pool + state := pool.State() + state.LastBlockHeight++ + state.LastBlockTime = ev.Time() + state.LastValidators = types.NewValidatorSet([]*types.Validator{val}) + pool.Update(state, []types.Evidence{}) + + // should be able to retrieve evidence from pool + evList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes) + require.Equal(t, []types.Evidence{ev}, evList) + + next = pool.EvidenceFront() + require.NotNil(t, next) +} + +func TestEvidencePoolUpdate(t *testing.T) { + height := int64(21) + pool, val := defaultTestPool(t, height) + state := pool.State() + + // create new block (no need to save it to blockStore) + prunedEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultEvidenceTime.Add(1*time.Minute), + val, evidenceChainID) + require.NoError(t, err) + err = pool.AddEvidence(prunedEv) + require.NoError(t, err) + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(21*time.Minute), + val, evidenceChainID) + require.NoError(t, err) + lastExtCommit := makeExtCommit(height, val.PrivKey.PubKey().Address()) + block := types.MakeBlock(height+1, []types.Tx{}, lastExtCommit.ToCommit(), []types.Evidence{ev}) + // update state (partially) + state.LastBlockHeight = height + 1 + state.LastBlockTime = defaultEvidenceTime.Add(22 * time.Minute) + err = pool.CheckEvidence(types.EvidenceList{ev}) + require.NoError(t, err) + + pool.Update(state, block.Evidence.Evidence) + // a) Update marks evidence as committed so pending evidence should be empty + evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes) + assert.Empty(t, evList) + assert.Zero(t, evSize) + + // b) If we try to check this evidence again it should fail because it has already been committed + err = pool.CheckEvidence(types.EvidenceList{ev}) + if assert.Error(t, err) { + assert.Equal(t, "evidence was already committed", err.(*types.ErrInvalidEvidence).Reason.Error()) + } +} + +func TestVerifyPendingEvidencePasses(t *testing.T) { + var height int64 = 1 + pool, val := defaultTestPool(t, height) + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(1*time.Minute), + val, evidenceChainID) + require.NoError(t, err) + err = pool.AddEvidence(ev) + require.NoError(t, err) + + err = pool.CheckEvidence(types.EvidenceList{ev}) + assert.NoError(t, err) +} + +func TestVerifyDuplicatedEvidenceFails(t *testing.T) { + var height int64 = 1 + pool, val := defaultTestPool(t, height) + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(1*time.Minute), + val, evidenceChainID) + require.NoError(t, err) + err = pool.CheckEvidence(types.EvidenceList{ev, ev}) + if assert.Error(t, err) { + assert.Equal(t, "duplicate evidence", err.(*types.ErrInvalidEvidence).Reason.Error()) + } +} + +// check that valid light client evidence is correctly validated and stored in +// evidence pool +func TestLightClientAttackEvidenceLifecycle(t *testing.T) { + var ( + height int64 = 100 + commonHeight int64 = 90 + ) + + ev, trusted, common := makeLunaticEvidence(t, height, commonHeight, + 10, 5, 5, defaultEvidenceTime, defaultEvidenceTime.Add(1*time.Hour)) + + state := sm.State{ + LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour), + LastBlockHeight: 110, + ConsensusParams: *types.DefaultConsensusParams(), + } + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", height).Return(trusted.ValidatorSet, nil) + stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trusted.Header}) + blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header}) + blockStore.On("LoadBlockCommit", height).Return(trusted.Commit) + blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit) + + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + + err = pool.AddEvidence(ev) + assert.NoError(t, err) + + hash := ev.Hash() + + require.NoError(t, pool.AddEvidence(ev)) + require.NoError(t, pool.AddEvidence(ev)) + + pendingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + require.Equal(t, 1, len(pendingEv)) + require.Equal(t, ev, pendingEv[0]) + + require.NoError(t, pool.CheckEvidence(pendingEv)) + require.Equal(t, ev, pendingEv[0]) + + state.LastBlockHeight++ + state.LastBlockTime = state.LastBlockTime.Add(1 * time.Minute) + pool.Update(state, pendingEv) + require.Equal(t, hash, pendingEv[0].Hash()) + + remaindingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + require.Empty(t, remaindingEv) + + // evidence is already committed so it shouldn't pass + require.Error(t, pool.CheckEvidence(types.EvidenceList{ev})) + require.NoError(t, pool.AddEvidence(ev)) + + remaindingEv, _ = pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + require.Empty(t, remaindingEv) +} + +// Tests that restarting the evidence pool after a potential failure will recover the +// pending evidence and continue to gossip it +func TestRecoverPendingEvidence(t *testing.T) { + height := int64(10) + val := types.NewMockPV() + valAddress := val.PrivKey.PubKey().Address() + evidenceDB := dbm.NewMemDB() + stateStore := initializeValidatorState(val, height) + state, err := stateStore.Load() + require.NoError(t, err) + blockStore, err := initializeBlockStore(dbm.NewMemDB(), state, valAddress) + require.NoError(t, err) + // create previous pool and populate it + pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + goodEvidence, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, + defaultEvidenceTime.Add(10*time.Minute), val, evidenceChainID) + require.NoError(t, err) + expiredEvidence, err := types.NewMockDuplicateVoteEvidenceWithValidator(int64(1), + defaultEvidenceTime.Add(1*time.Minute), val, evidenceChainID) + require.NoError(t, err) + err = pool.AddEvidence(goodEvidence) + require.NoError(t, err) + err = pool.AddEvidence(expiredEvidence) + require.NoError(t, err) + + // now recover from the previous pool at a different time + newStateStore := &smmocks.Store{} + newStateStore.On("Load").Return(sm.State{ + LastBlockTime: defaultEvidenceTime.Add(25 * time.Minute), + LastBlockHeight: height + 15, + ConsensusParams: types.ConsensusParams{ + Block: types.BlockParams{ + MaxBytes: 22020096, + MaxGas: -1, + }, + Evidence: types.EvidenceParams{ + MaxAgeNumBlocks: 20, + MaxAgeDuration: 20 * time.Minute, + MaxBytes: defaultEvidenceMaxBytes, + }, + }, + }, nil) + newPool, err := evidence.NewPool(evidenceDB, newStateStore, blockStore) + assert.NoError(t, err) + evList, _ := newPool.PendingEvidence(defaultEvidenceMaxBytes) + assert.Equal(t, 1, len(evList)) + next := newPool.EvidenceFront() + assert.Equal(t, goodEvidence, next.Value.(types.Evidence)) +} + +func initializeStateFromValidatorSet(valSet *types.ValidatorSet, height int64) sm.Store { + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state := sm.State{ + ChainID: evidenceChainID, + InitialHeight: 1, + LastBlockHeight: height, + LastBlockTime: defaultEvidenceTime, + Validators: valSet, + NextValidators: valSet.CopyIncrementProposerPriority(1), + LastValidators: valSet, + LastHeightValidatorsChanged: 1, + ConsensusParams: types.ConsensusParams{ + Block: types.BlockParams{ + MaxBytes: 22020096, + MaxGas: -1, + }, + Evidence: types.EvidenceParams{ + MaxAgeNumBlocks: 20, + MaxAgeDuration: 20 * time.Minute, + MaxBytes: 1000, + }, + }, + } + + // save all states up to height + for i := int64(0); i <= height; i++ { + state.LastBlockHeight = i + if err := stateStore.Save(state); err != nil { + panic(err) + } + } + + return stateStore +} + +func initializeValidatorState(privVal types.PrivValidator, height int64) sm.Store { + pubKey, _ := privVal.GetPubKey() + validator := &types.Validator{Address: pubKey.Address(), VotingPower: 10, PubKey: pubKey} + + // create validator set and state + valSet := &types.ValidatorSet{ + Validators: []*types.Validator{validator}, + Proposer: validator, + } + + return initializeStateFromValidatorSet(valSet, height) +} + +// initializeBlockStore creates a block storage and populates it w/ a dummy +// block at +height+. +func initializeBlockStore(db dbm.DB, state sm.State, valAddr []byte) (*store.BlockStore, error) { + blockStore := store.NewBlockStore(db) + + for i := int64(1); i <= state.LastBlockHeight; i++ { + lastCommit := makeExtCommit(i-1, valAddr) + block, err := state.MakeBlock(i, test.MakeNTxs(i, 1), lastCommit.ToCommit(), nil, state.Validators.Proposer.Address) + if err != nil { + return nil, err + } + block.Time = defaultEvidenceTime.Add(time.Duration(i) * time.Minute) + block.Version = cmtversion.Consensus{Block: version.BlockProtocol, App: 1} + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + if err != nil { + return nil, err + } + + seenCommit := makeExtCommit(i, valAddr) + blockStore.SaveBlockWithExtendedCommit(block, partSet, seenCommit) + } + + return blockStore, nil +} + +func makeExtCommit(height int64, valAddr []byte) *types.ExtendedCommit { + return &types.ExtendedCommit{ + Height: height, + ExtendedSignatures: []types.ExtendedCommitSig{{ + CommitSig: types.CommitSig{ + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: valAddr, + Timestamp: defaultEvidenceTime, + Signature: []byte("Signature"), + }, + ExtensionSignature: []byte("Extended Signature"), + }}, + } +} + +func defaultTestPool(t *testing.T, height int64) (*evidence.Pool, types.MockPV) { + t.Helper() + val := types.NewMockPV() + valAddress := val.PrivKey.PubKey().Address() + evidenceDB := dbm.NewMemDB() + stateStore := initializeValidatorState(val, height) + state, _ := stateStore.Load() + blockStore, err := initializeBlockStore(dbm.NewMemDB(), state, valAddress) + require.NoError(t, err) + pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + if err != nil { + panic("test evidence pool could not be created") + } + pool.SetLogger(log.TestingLogger()) + return pool, val +} + +func createState(height int64, valSet *types.ValidatorSet) sm.State { + return sm.State{ + ChainID: evidenceChainID, + LastBlockHeight: height, + LastBlockTime: defaultEvidenceTime, + Validators: valSet, + ConsensusParams: *types.DefaultConsensusParams(), + } +} diff --git a/evidence/reactor.go b/evidence/reactor.go new file mode 100644 index 0000000..661187d --- /dev/null +++ b/evidence/reactor.go @@ -0,0 +1,254 @@ +package evidence + +import ( + "fmt" + "time" + + "github.com/cosmos/gogoproto/proto" + + clist "github.com/cometbft/cometbft/libs/clist" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +const ( + EvidenceChannel = byte(0x38) + + maxMsgSize = 1048576 // 1MB TODO make it configurable + + // broadcast all uncommitted evidence this often. This sets when the reactor + // goes back to the start of the list and begins sending the evidence again. + // Most evidence should be committed in the very next block that is why we wait + // just over the block production rate before sending evidence again. + broadcastEvidenceIntervalS = 10 + // If a message fails wait this much before sending it again + peerRetryMessageIntervalMS = 100 +) + +// Reactor handles evpool evidence broadcasting amongst peers. +type Reactor struct { + p2p.BaseReactor + evpool *Pool + eventBus *types.EventBus +} + +// NewReactor returns a new Reactor with the given config and evpool. +func NewReactor(evpool *Pool) *Reactor { + evR := &Reactor{ + evpool: evpool, + } + evR.BaseReactor = *p2p.NewBaseReactor("Evidence", evR) + return evR +} + +// SetLogger sets the Logger on the reactor and the underlying Evidence. +func (evR *Reactor) SetLogger(l log.Logger) { + evR.Logger = l + evR.evpool.SetLogger(l) +} + +// GetChannels implements Reactor. +// It returns the list of channels for this reactor. +func (evR *Reactor) GetChannels() []*p2p.ChannelDescriptor { + return []*p2p.ChannelDescriptor{ + { + ID: EvidenceChannel, + Priority: 6, + RecvMessageCapacity: maxMsgSize, + MessageType: &cmtproto.EvidenceList{}, + }, + } +} + +// AddPeer implements Reactor. +func (evR *Reactor) AddPeer(peer p2p.Peer) { + go evR.broadcastEvidenceRoutine(peer) +} + +// Receive implements Reactor. +// It adds any received evidence to the evpool. +func (evR *Reactor) Receive(e p2p.Envelope) { + evis, err := evidenceListFromProto(e.Message) + if err != nil { + evR.Logger.Error("Error decoding message", "src", e.Src, "chId", e.ChannelID, "err", err) + evR.Switch.StopPeerForError(e.Src, err) + return + } + + for _, ev := range evis { + err := evR.evpool.AddEvidence(ev) + switch err.(type) { + case *types.ErrInvalidEvidence: + evR.Logger.Error(err.Error()) + // punish peer + evR.Switch.StopPeerForError(e.Src, err) + return + case nil: + default: + // continue to the next piece of evidence + evR.Logger.Error("Evidence has not been added", "evidence", evis, "err", err) + } + } +} + +// SetEventBus implements events.Eventable. +func (evR *Reactor) SetEventBus(b *types.EventBus) { + evR.eventBus = b +} + +// Modeled after the mempool routine. +// - Evidence accumulates in a clist. +// - Each peer has a routine that iterates through the clist, +// sending available evidence to the peer. +// - If we're waiting for new evidence and the list is not empty, +// start iterating from the beginning again. +func (evR *Reactor) broadcastEvidenceRoutine(peer p2p.Peer) { + var next *clist.CElement + for { + // This happens because the CElement we were looking at got garbage + // collected (removed). That is, .NextWait() returned nil. Go ahead and + // start from the beginning. + if next == nil { + select { + case <-evR.evpool.EvidenceWaitChan(): // Wait until evidence is available + if next = evR.evpool.EvidenceFront(); next == nil { + continue + } + case <-peer.Quit(): + return + case <-evR.Quit(): + return + } + } else if !peer.IsRunning() || !evR.IsRunning() { + return + } + + ev := next.Value.(types.Evidence) + evis := evR.prepareEvidenceMessage(peer, ev) + if len(evis) > 0 { + evR.Logger.Debug("Gossiping evidence to peer", "ev", ev, "peer", peer) + evp, err := evidenceListToProto(evis) + if err != nil { + panic(err) + } + + success := peer.Send(p2p.Envelope{ + ChannelID: EvidenceChannel, + Message: evp, + }) + if !success { + time.Sleep(peerRetryMessageIntervalMS * time.Millisecond) + continue + } + } + + afterCh := time.After(time.Second * broadcastEvidenceIntervalS) + select { + case <-afterCh: + // start from the beginning every tick. + // TODO: only do this if we're at the end of the list! + next = nil + case <-next.NextWaitChan(): + // see the start of the for loop for nil check + next = next.Next() + case <-peer.Quit(): + return + case <-evR.Quit(): + return + } + } +} + +// Returns the message to send to the peer, or nil if the evidence is invalid for the peer. +// If message is nil, we should sleep and try again. +func (evR Reactor) prepareEvidenceMessage( + peer p2p.Peer, + ev types.Evidence, +) (evis []types.Evidence) { + + // make sure the peer is up to date + evHeight := ev.Height() + peerState, ok := peer.Get(types.PeerStateKey).(PeerState) + if !ok { + // Peer does not have a state yet. We set it in the consensus reactor, but + // when we add peer in Switch, the order we call reactors#AddPeer is + // different every time due to us using a map. Sometimes other reactors + // will be initialized before the consensus reactor. We should wait a few + // milliseconds and retry. + return nil + } + + // NOTE: We only send evidence to peers where + // peerHeight - maxAge < evidenceHeight < peerHeight + var ( + peerHeight = peerState.GetHeight() + params = evR.evpool.State().ConsensusParams.Evidence + ageNumBlocks = peerHeight - evHeight + ) + + if peerHeight <= evHeight { // peer is behind. sleep while he catches up + return nil + } else if ageNumBlocks > params.MaxAgeNumBlocks { // evidence is too old relative to the peer, skip + + // NOTE: if evidence is too old for an honest peer, then we're behind and + // either it already got committed or it never will! + evR.Logger.Info("Not sending peer old evidence", + "peerHeight", peerHeight, + "evHeight", evHeight, + "maxAgeNumBlocks", params.MaxAgeNumBlocks, + "lastBlockTime", evR.evpool.State().LastBlockTime, + "maxAgeDuration", params.MaxAgeDuration, + "peer", peer, + ) + + return nil + } + + // send evidence + return []types.Evidence{ev} +} + +// PeerState describes the state of a peer. +type PeerState interface { + GetHeight() int64 +} + +// encodemsg takes a array of evidence +// returns the byte encoding of the List Message +func evidenceListToProto(evis []types.Evidence) (*cmtproto.EvidenceList, error) { + evi := make([]cmtproto.Evidence, len(evis)) + for i := 0; i < len(evis); i++ { + ev, err := types.EvidenceToProto(evis[i]) + if err != nil { + return nil, err + } + evi[i] = *ev + } + epl := cmtproto.EvidenceList{ + Evidence: evi, + } + return &epl, nil +} + +func evidenceListFromProto(m proto.Message) ([]types.Evidence, error) { + lm := m.(*cmtproto.EvidenceList) + + evis := make([]types.Evidence, len(lm.Evidence)) + for i := 0; i < len(lm.Evidence); i++ { + ev, err := types.EvidenceFromProto(&lm.Evidence[i]) + if err != nil { + return nil, err + } + evis[i] = ev + } + + for i, ev := range evis { + if err := ev.ValidateBasic(); err != nil { + return nil, fmt.Errorf("invalid evidence (#%d): %v", i, err) + } + } + + return evis, nil +} diff --git a/evidence/reactor_test.go b/evidence/reactor_test.go new file mode 100644 index 0000000..f5c8f92 --- /dev/null +++ b/evidence/reactor_test.go @@ -0,0 +1,420 @@ +package evidence_test + +import ( + "encoding/hex" + "fmt" + "sync" + "testing" + "time" + + "github.com/fortytw2/leaktest" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/evidence/mocks" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + p2pmocks "github.com/cometbft/cometbft/p2p/mocks" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +var ( + numEvidence = 10 + timeout = 120 * time.Second // ridiculously high because CircleCI is slow +) + +// We have N evidence reactors connected to one another. The first reactor +// receives a number of evidence at varying heights. We test that all +// other reactors receive the evidence and add it to their own respective +// evidence pools. +func TestReactorBroadcastEvidence(t *testing.T) { + config := cfg.TestConfig() + N := 7 + + // create statedb for everyone + stateDBs := make([]sm.Store, N) + val := types.NewMockPV() + // we need validators saved for heights at least as high as we have evidence for + height := int64(numEvidence) + 10 + for i := 0; i < N; i++ { + stateDBs[i] = initializeValidatorState(val, height) + } + + // make reactors from statedb + reactors, pools := makeAndConnectReactorsAndPools(config, stateDBs) + + // set the peer height on each reactor + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + ps := peerState{height} + peer.Set(types.PeerStateKey, ps) + } + } + + // send a bunch of valid evidence to the first reactor's evpool + // and wait for them all to be received in the others + evList := sendEvidence(t, pools[0], val, numEvidence) + waitForEvidence(t, evList, pools) +} + +// We have two evidence reactors connected to one another but are at different heights. +// Reactor 1 which is ahead receives a number of evidence. It should only send the evidence +// that is below the height of the peer to that peer. +func TestReactorSelectiveBroadcast(t *testing.T) { + config := cfg.TestConfig() + + val := types.NewMockPV() + height1 := int64(numEvidence) + 10 + height2 := int64(numEvidence) / 2 + + // DB1 is ahead of DB2 + stateDB1 := initializeValidatorState(val, height1) + stateDB2 := initializeValidatorState(val, height2) + + // make reactors from statedb + reactors, pools := makeAndConnectReactorsAndPools(config, []sm.Store{stateDB1, stateDB2}) + + // set the peer height on each reactor + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + ps := peerState{height1} + peer.Set(types.PeerStateKey, ps) + } + } + + // update the first reactor peer's height to be very small + peer := reactors[0].Switch.Peers().List()[0] + ps := peerState{height2} + peer.Set(types.PeerStateKey, ps) + + // send a bunch of valid evidence to the first reactor's evpool + evList := sendEvidence(t, pools[0], val, numEvidence) + + // only ones less than the peers height should make it through + waitForEvidence(t, evList[:numEvidence/2-1], []*evidence.Pool{pools[1]}) + + // peers should still be connected + peers := reactors[1].Switch.Peers().List() + assert.Equal(t, 1, len(peers)) +} + +// This tests aims to ensure that reactors don't send evidence that they have committed or that ar +// not ready for the peer through three scenarios. +// First, committed evidence to a newly connected peer +// Second, evidence to a peer that is behind +// Third, evidence that was pending and became committed just before the peer caught up +func TestReactorsGossipNoCommittedEvidence(t *testing.T) { + config := cfg.TestConfig() + + val := types.NewMockPV() + var height int64 = 10 + + // DB1 is ahead of DB2 + stateDB1 := initializeValidatorState(val, height-1) + stateDB2 := initializeValidatorState(val, height-2) + state, err := stateDB1.Load() + require.NoError(t, err) + state.LastBlockHeight++ + + // make reactors from statedb + reactors, pools := makeAndConnectReactorsAndPools(config, []sm.Store{stateDB1, stateDB2}) + + evList := sendEvidence(t, pools[0], val, 2) + pools[0].Update(state, evList) + require.EqualValues(t, uint32(0), pools[0].Size()) + + time.Sleep(100 * time.Millisecond) + + peer := reactors[0].Switch.Peers().List()[0] + ps := peerState{height - 2} + peer.Set(types.PeerStateKey, ps) + + peer = reactors[1].Switch.Peers().List()[0] + ps = peerState{height} + peer.Set(types.PeerStateKey, ps) + + // wait to see that no evidence comes through + time.Sleep(300 * time.Millisecond) + + // the second pool should not have received any evidence because it has already been committed + assert.Equal(t, uint32(0), pools[1].Size(), "second reactor should not have received evidence") + + // the first reactor receives three more evidence + evList = make([]types.Evidence, 3) + for i := 0; i < 3; i++ { + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height-3+int64(i), + time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), val, state.ChainID) + require.NoError(t, err) + err = pools[0].AddEvidence(ev) + require.NoError(t, err) + evList[i] = ev + } + + // wait to see that only one evidence is sent + time.Sleep(300 * time.Millisecond) + + // the second pool should only have received the first evidence because it is behind + peerEv, _ := pools[1].PendingEvidence(10000) + assert.EqualValues(t, []types.Evidence{evList[0]}, peerEv) + + // the last evidence is committed and the second reactor catches up in state to the first + // reactor. We therefore expect that the second reactor only receives one more evidence, the + // one that is still pending and not the evidence that has already been committed. + state.LastBlockHeight++ + pools[0].Update(state, []types.Evidence{evList[2]}) + // the first reactor should have the two remaining pending evidence + require.EqualValues(t, uint32(2), pools[0].Size()) + + // now update the state of the second reactor + pools[1].Update(state, types.EvidenceList{}) + peer = reactors[0].Switch.Peers().List()[0] + ps = peerState{height} + peer.Set(types.PeerStateKey, ps) + + // wait to see that only two evidence is sent + time.Sleep(300 * time.Millisecond) + + peerEv, _ = pools[1].PendingEvidence(1000) + assert.EqualValues(t, []types.Evidence{evList[0], evList[1]}, peerEv) +} + +func TestReactorBroadcastEvidenceMemoryLeak(t *testing.T) { + evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + evidenceDB := dbm.NewMemDB() + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return( + &types.BlockMeta{Header: types.Header{Time: evidenceTime}}, + ) + val := types.NewMockPV() + stateStore := initializeValidatorState(val, 1) + pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + + p := &p2pmocks.Peer{} + + p.On("IsRunning").Once().Return(true) + p.On("IsRunning").Return(false) + // check that we are not leaking any go-routines + // i.e. broadcastEvidenceRoutine finishes when peer is stopped + defer leaktest.CheckTimeout(t, 10*time.Second)() + + p.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + return ok && e.ChannelID == evidence.EvidenceChannel + })).Return(false) + quitChan := make(<-chan struct{}) + p.On("Quit").Return(quitChan) + ps := peerState{2} + p.On("Get", types.PeerStateKey).Return(ps) + p.On("ID").Return("ABC") + p.On("String").Return("mock") + + r := evidence.NewReactor(pool) + r.SetLogger(log.TestingLogger()) + r.AddPeer(p) + + _ = sendEvidence(t, pool, val, 2) +} + +// evidenceLogger is a TestingLogger which uses a different +// color for each validator ("validator" key must exist). +func evidenceLogger() log.Logger { + return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor { + for i := 0; i < len(keyvals)-1; i += 2 { + if keyvals[i] == "validator" { + return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))} + } + } + return term.FgBgColor{} + }) +} + +// connect N evidence reactors through N switches +func makeAndConnectReactorsAndPools(config *cfg.Config, stateStores []sm.Store) ([]*evidence.Reactor, + []*evidence.Pool, +) { + N := len(stateStores) + + reactors := make([]*evidence.Reactor, N) + pools := make([]*evidence.Pool, N) + logger := evidenceLogger() + evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + + for i := 0; i < N; i++ { + evidenceDB := dbm.NewMemDB() + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return( + &types.BlockMeta{Header: types.Header{Time: evidenceTime}}, + ) + pool, err := evidence.NewPool(evidenceDB, stateStores[i], blockStore) + if err != nil { + panic(err) + } + pools[i] = pool + reactors[i] = evidence.NewReactor(pool) + reactors[i].SetLogger(logger.With("validator", i)) + } + + p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("EVIDENCE", reactors[i]) + return s + }, p2p.Connect2Switches) + + return reactors, pools +} + +// wait for all evidence on all reactors +func waitForEvidence(t *testing.T, evs types.EvidenceList, pools []*evidence.Pool) { + // wait for the evidence in all evpools + wg := new(sync.WaitGroup) + for i := 0; i < len(pools); i++ { + wg.Add(1) + go _waitForEvidence(t, wg, evs, i, pools) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + timer := time.After(timeout) + select { + case <-timer: + t.Fatal("Timed out waiting for evidence") + case <-done: + } +} + +// wait for all evidence on a single evpool +func _waitForEvidence( + t *testing.T, + wg *sync.WaitGroup, + evs types.EvidenceList, + poolIdx int, + pools []*evidence.Pool, +) { + evpool := pools[poolIdx] + var evList []types.Evidence + currentPoolSize := 0 + for currentPoolSize != len(evs) { + evList, _ = evpool.PendingEvidence(int64(len(evs) * 500)) // each evidence should not be more than 500 bytes + currentPoolSize = len(evList) + time.Sleep(time.Millisecond * 100) + } + + // put the reaped evidence in a map so we can quickly check we got everything + evMap := make(map[string]types.Evidence) + for _, e := range evList { + evMap[string(e.Hash())] = e + } + for i, expectedEv := range evs { + gotEv := evMap[string(expectedEv.Hash())] + assert.Equal(t, expectedEv, gotEv, + fmt.Sprintf("evidence at index %d on pool %d don't match: %v vs %v", + i, poolIdx, expectedEv, gotEv)) + } + + wg.Done() +} + +func sendEvidence(t *testing.T, evpool *evidence.Pool, val types.PrivValidator, n int) types.EvidenceList { + evList := make([]types.Evidence, n) + for i := 0; i < n; i++ { + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(int64(i+1), + time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), val, evidenceChainID) + require.NoError(t, err) + err = evpool.AddEvidence(ev) + require.NoError(t, err) + evList[i] = ev + } + return evList +} + +type peerState struct { + height int64 +} + +func (ps peerState) GetHeight() int64 { + return ps.height +} + +func exampleVote(t byte) *types.Vote { + stamp, err := time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z") + if err != nil { + panic(err) + } + + return &types.Vote{ + Type: cmtproto.SignedMsgType(t), + Height: 3, + Round: 2, + Timestamp: stamp, + BlockID: types.BlockID{ + Hash: tmhash.Sum([]byte("blockID_hash")), + PartSetHeader: types.PartSetHeader{ + Total: 1000000, + Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")), + }, + }, + ValidatorAddress: crypto.AddressHash([]byte("validator_address")), + ValidatorIndex: 56789, + } +} + +//nolint:lll //ignore line length for tests +func TestEvidenceVectors(t *testing.T) { + val := &types.Validator{ + Address: crypto.AddressHash([]byte("validator_address")), + VotingPower: 10, + } + + valSet := types.NewValidatorSet([]*types.Validator{val}) + + dupl, err := types.NewDuplicateVoteEvidence( + exampleVote(1), + exampleVote(2), + defaultEvidenceTime, + valSet, + ) + require.NoError(t, err) + + testCases := []struct { + testName string + evidenceList []types.Evidence + expBytes string + }{ + {"DuplicateVoteEvidence", []types.Evidence{dupl}, "0a85020a82020a79080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb031279080110031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb03180a200a2a060880dbaae105"}, + } + + for _, tc := range testCases { + tc := tc + + evi := make([]cmtproto.Evidence, len(tc.evidenceList)) + for i := 0; i < len(tc.evidenceList); i++ { + ev, err := types.EvidenceToProto(tc.evidenceList[i]) + require.NoError(t, err, tc.testName) + evi[i] = *ev + } + + epl := cmtproto.EvidenceList{ + Evidence: evi, + } + + bz, err := epl.Marshal() + require.NoError(t, err, tc.testName) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + + } +} diff --git a/evidence/services.go b/evidence/services.go new file mode 100644 index 0000000..59c4e84 --- /dev/null +++ b/evidence/services.go @@ -0,0 +1,13 @@ +package evidence + +import ( + "github.com/cometbft/cometbft/types" +) + +//go:generate ../scripts/mockery_generate.sh BlockStore + +type BlockStore interface { + LoadBlockMeta(height int64) *types.BlockMeta + LoadBlockCommit(height int64) *types.Commit + Height() int64 +} diff --git a/evidence/verify.go b/evidence/verify.go new file mode 100644 index 0000000..2e7aec0 --- /dev/null +++ b/evidence/verify.go @@ -0,0 +1,303 @@ +package evidence + +import ( + "bytes" + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/types" +) + +// verify verifies the evidence fully by checking: +// - It has not already been committed +// - it is sufficiently recent (MaxAge) +// - it is from a key who was a validator at the given height +// - it is internally consistent with state +// - it was properly signed by the alleged equivocator and meets the individual evidence verification requirements +func (evpool *Pool) verify(evidence types.Evidence) error { + var ( + state = evpool.State() + height = state.LastBlockHeight + evidenceParams = state.ConsensusParams.Evidence + ) + + // verify the time of the evidence + blockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height()) + if blockMeta == nil { + return fmt.Errorf("don't have header #%d", evidence.Height()) + } + evTime := blockMeta.Header.Time + if evidence.Time() != evTime { + return fmt.Errorf("evidence has a different time to the block it is associated with (%v != %v)", + evidence.Time(), evTime) + } + + // checking if evidence is expired calculated using the block evidence time and height + if IsEvidenceExpired(height, state.LastBlockTime, evidence.Height(), evTime, evidenceParams) { + return fmt.Errorf( + "evidence from height %d (created at: %v) is too old; min height is %d and evidence can not be older than %v", + evidence.Height(), + evTime, + height-evidenceParams.MaxAgeNumBlocks, + state.LastBlockTime.Add(evidenceParams.MaxAgeDuration), + ) + } + + // apply the evidence-specific verification logic + switch ev := evidence.(type) { + case *types.DuplicateVoteEvidence: + valSet, err := evpool.stateDB.LoadValidators(evidence.Height()) + if err != nil { + return err + } + return VerifyDuplicateVote(ev, state.ChainID, valSet) + + case *types.LightClientAttackEvidence: + commonHeader, err := getSignedHeader(evpool.blockStore, evidence.Height()) + if err != nil { + return err + } + commonVals, err := evpool.stateDB.LoadValidators(evidence.Height()) + if err != nil { + return err + } + trustedHeader := commonHeader + // in the case of lunatic the trusted header is different to the common header + if evidence.Height() != ev.ConflictingBlock.Height { + trustedHeader, err = getSignedHeader(evpool.blockStore, ev.ConflictingBlock.Height) + if err != nil { + // FIXME: This multi step process is a bit unergonomic. We may want to consider a more efficient process + // that doesn't require as much io and is atomic. + + // If the node doesn't have a block at the height of the conflicting block, then this could be + // a forward lunatic attack. Thus the node must get the latest height it has + latestHeight := evpool.blockStore.Height() + trustedHeader, err = getSignedHeader(evpool.blockStore, latestHeight) + if err != nil { + return err + } + if trustedHeader.Time.Before(ev.ConflictingBlock.Time) { + return fmt.Errorf("latest block time (%v) is before conflicting block time (%v)", + trustedHeader.Time, ev.ConflictingBlock.Time, + ) + } + } + } + + err = VerifyLightClientAttack(ev, commonHeader, trustedHeader, commonVals, state.LastBlockTime, + state.ConsensusParams.Evidence.MaxAgeDuration) + if err != nil { + return err + } + return nil + default: + return fmt.Errorf("unrecognized evidence type: %T", evidence) + } +} + +// VerifyLightClientAttack verifies LightClientAttackEvidence against the state of the full node. This involves +// the following checks: +// - the common header from the full node has at least 1/3 voting power which is also present in +// the conflicting header's commit +// - 2/3+ of the conflicting validator set correctly signed the conflicting block +// - the nodes trusted header at the same height as the conflicting header has a different hash +// - all signatures must be checked as this will be used as evidence +// +// CONTRACT: must run ValidateBasic() on the evidence before verifying +// +// must check that the evidence has not expired (i.e. is outside the maximum age threshold) +func VerifyLightClientAttack( + e *types.LightClientAttackEvidence, + commonHeader, trustedHeader *types.SignedHeader, + commonVals *types.ValidatorSet, + now time.Time, //nolint:revive + trustPeriod time.Duration, //nolint:revive +) error { + // TODO: Should the current time and trust period be used in this method? + // If not, why were the parameters present? + + // In the case of lunatic attack there will be a different commonHeader height. Therefore the node perform a single + // verification jump between the common header and the conflicting one + if commonHeader.Height != e.ConflictingBlock.Height { + err := commonVals.VerifyCommitLightTrustingAllSignatures(trustedHeader.ChainID, e.ConflictingBlock.Commit, light.DefaultTrustLevel) + if err != nil { + return fmt.Errorf("skipping verification of conflicting block failed: %w", err) + } + + // In the case of equivocation and amnesia we expect all header hashes to be correctly derived + } else if e.ConflictingHeaderIsInvalid(trustedHeader.Header) { + return errors.New("common height is the same as conflicting block height so expected the conflicting" + + " block to be correctly derived yet it wasn't") + } + + // Verify that the 2/3+ commits from the conflicting validator set were for the conflicting header + if err := e.ConflictingBlock.ValidatorSet.VerifyCommitLightAllSignatures(trustedHeader.ChainID, e.ConflictingBlock.Commit.BlockID, + e.ConflictingBlock.Height, e.ConflictingBlock.Commit); err != nil { + return fmt.Errorf("invalid commit from conflicting block: %w", err) + } + + // Assert the correct amount of voting power of the validator set + if evTotal, valsTotal := e.TotalVotingPower, commonVals.TotalVotingPower(); evTotal != valsTotal { + return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)", + evTotal, valsTotal) + } + + // check in the case of a forward lunatic attack that monotonically increasing time has been violated + if e.ConflictingBlock.Height > trustedHeader.Height && e.ConflictingBlock.Time.After(trustedHeader.Time) { + return fmt.Errorf("conflicting block doesn't violate monotonically increasing time (%v is after %v)", + e.ConflictingBlock.Time, trustedHeader.Time, + ) + + // In all other cases check that the hashes of the conflicting header and the trusted header are different + } else if bytes.Equal(trustedHeader.Hash(), e.ConflictingBlock.Hash()) { + return fmt.Errorf("trusted header hash matches the evidence's conflicting header hash: %X", + trustedHeader.Hash()) + } + + return validateABCIEvidence(e, commonVals, trustedHeader) +} + +// VerifyDuplicateVote verifies DuplicateVoteEvidence against the state of full node. This involves the +// following checks: +// - the validator is in the validator set at the height of the evidence +// - the height, round, type and validator address of the votes must be the same +// - the block ID's must be different +// - The signatures must both be valid +func VerifyDuplicateVote(e *types.DuplicateVoteEvidence, chainID string, valSet *types.ValidatorSet) error { + _, val := valSet.GetByAddress(e.VoteA.ValidatorAddress) + if val == nil { + return fmt.Errorf("address %X was not a validator at height %d", e.VoteA.ValidatorAddress, e.Height()) + } + pubKey := val.PubKey + + // H/R/S must be the same + if e.VoteA.Height != e.VoteB.Height || + e.VoteA.Round != e.VoteB.Round || + e.VoteA.Type != e.VoteB.Type { + return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v", + e.VoteA.Height, e.VoteA.Round, e.VoteA.Type, + e.VoteB.Height, e.VoteB.Round, e.VoteB.Type) + } + + // Address must be the same + if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) { + return fmt.Errorf("validator addresses do not match: %X vs %X", + e.VoteA.ValidatorAddress, + e.VoteB.ValidatorAddress, + ) + } + + // BlockIDs must be different + if e.VoteA.BlockID.Equals(e.VoteB.BlockID) { + return fmt.Errorf( + "block IDs are the same (%v) - not a real duplicate vote", + e.VoteA.BlockID, + ) + } + + // pubkey must match address (this should already be true, sanity check) + addr := e.VoteA.ValidatorAddress + if !bytes.Equal(pubKey.Address(), addr) { + return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)", + addr, pubKey, pubKey.Address()) + } + + // validator voting power and total voting power must match + if val.VotingPower != e.ValidatorPower { + return fmt.Errorf("validator power from evidence and our validator set does not match (%d != %d)", + e.ValidatorPower, val.VotingPower) + } + if valSet.TotalVotingPower() != e.TotalVotingPower { + return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)", + e.TotalVotingPower, valSet.TotalVotingPower()) + } + + va := e.VoteA.ToProto() + vb := e.VoteB.ToProto() + // Signatures must be valid + if !pubKey.VerifySignature(types.VoteSignBytes(chainID, va), e.VoteA.Signature) { + return fmt.Errorf("verifying VoteA: %w", types.ErrVoteInvalidSignature) + } + if !pubKey.VerifySignature(types.VoteSignBytes(chainID, vb), e.VoteB.Signature) { + return fmt.Errorf("verifying VoteB: %w", types.ErrVoteInvalidSignature) + } + + return nil +} + +// validateABCIEvidence validates the ABCI component of the light client attack +// evidence i.e voting power and byzantine validators +func validateABCIEvidence( + ev *types.LightClientAttackEvidence, + commonVals *types.ValidatorSet, + trustedHeader *types.SignedHeader, +) error { + if evTotal, valsTotal := ev.TotalVotingPower, commonVals.TotalVotingPower(); evTotal != valsTotal { + return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)", + evTotal, valsTotal) + } + + // Find out what type of attack this was and thus extract the malicious + // validators. Note, in the case of an Amnesia attack we don't have any + // malicious validators. + validators := ev.GetByzantineValidators(commonVals, trustedHeader) + + // Ensure this matches the validators that are listed in the evidence. They + // should be ordered based on power. + if validators == nil && ev.ByzantineValidators != nil { + return fmt.Errorf( + "expected nil validators from an amnesia light client attack but got %d", + len(ev.ByzantineValidators), + ) + } + + if exp, got := len(validators), len(ev.ByzantineValidators); exp != got { + return fmt.Errorf("expected %d byzantine validators from evidence but got %d", exp, got) + } + + for idx, val := range validators { + if !bytes.Equal(ev.ByzantineValidators[idx].Address, val.Address) { + return fmt.Errorf( + "evidence contained an unexpected byzantine validator address; expected: %v, got: %v", + val.Address, ev.ByzantineValidators[idx].Address, + ) + } + + if ev.ByzantineValidators[idx].VotingPower != val.VotingPower { + return fmt.Errorf( + "evidence contained unexpected byzantine validator power; expected %d, got %d", + val.VotingPower, ev.ByzantineValidators[idx].VotingPower, + ) + } + } + + return nil +} + +func getSignedHeader(blockStore BlockStore, height int64) (*types.SignedHeader, error) { + blockMeta := blockStore.LoadBlockMeta(height) + if blockMeta == nil { + return nil, fmt.Errorf("don't have header at height #%d", height) + } + commit := blockStore.LoadBlockCommit(height) + if commit == nil { + return nil, fmt.Errorf("don't have commit at height #%d", height) + } + return &types.SignedHeader{ + Header: &blockMeta.Header, + Commit: commit, + }, nil +} + +// check that the evidence hasn't expired +func IsEvidenceExpired(heightNow int64, timeNow time.Time, heightEv int64, timeEv time.Time, evidenceParams types.EvidenceParams) bool { + ageDuration := timeNow.Sub(timeEv) + ageNumBlocks := heightNow - heightEv + + if ageDuration > evidenceParams.MaxAgeDuration && ageNumBlocks > evidenceParams.MaxAgeNumBlocks { + return true + } + return false +} diff --git a/evidence/verify_test.go b/evidence/verify_test.go new file mode 100644 index 0000000..d068259 --- /dev/null +++ b/evidence/verify_test.go @@ -0,0 +1,586 @@ +package evidence_test + +import ( + "bytes" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/evidence/mocks" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + sm "github.com/cometbft/cometbft/state" + smmocks "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +const ( + defaultVotingPower = 10 +) + +func TestVerifyLightClientAttack_Lunatic(t *testing.T) { + const ( + height int64 = 10 + commonHeight int64 = 4 + totalVals = 10 + byzVals = 4 + ) + attackTime := defaultEvidenceTime.Add(1 * time.Hour) + // create valid lunatic evidence + ev, trusted, common := makeLunaticEvidence( + t, height, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime) + require.NoError(t, ev.ValidateBasic()) + + // good pass -> no error + err := evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet, + defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour) + assert.NoError(t, err) + + // trusted and conflicting hashes are the same -> an error should be returned + err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, ev.ConflictingBlock.SignedHeader, common.ValidatorSet, + defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour) + assert.Error(t, err) + + // evidence with different total validator power should fail + ev.TotalVotingPower = 1 * defaultVotingPower + err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet, + defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour) + assert.Error(t, err) + + // evidence without enough malicious votes should fail + ev, trusted, common = makeLunaticEvidence( + t, height, commonHeight, totalVals, byzVals-1, totalVals-byzVals, defaultEvidenceTime, attackTime) + err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet, + defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour) + assert.Error(t, err) +} + +func TestVerify_LunaticAttackAgainstState(t *testing.T) { + const ( + height int64 = 10 + commonHeight int64 = 4 + totalVals = 10 + byzVals = 4 + ) + attackTime := defaultEvidenceTime.Add(1 * time.Hour) + // create valid lunatic evidence + ev, trusted, common := makeLunaticEvidence( + t, height, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime) + + // now we try to test verification against state + state := sm.State{ + LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour), + LastBlockHeight: height + 1, + ConsensusParams: *types.DefaultConsensusParams(), + } + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header}) + blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trusted.Header}) + blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit) + blockStore.On("LoadBlockCommit", height).Return(trusted.Commit) + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + + evList := types.EvidenceList{ev} + // check that the evidence pool correctly verifies the evidence + assert.NoError(t, pool.CheckEvidence(evList)) + + // as it was not originally in the pending bucket, it should now have been added + pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + assert.Equal(t, 1, len(pendingEvs)) + assert.Equal(t, ev, pendingEvs[0]) + + // if we submit evidence only against a single byzantine validator when we see there are more validators then this + // should return an error + ev.ByzantineValidators = ev.ByzantineValidators[:1] + t.Log(evList) + assert.Error(t, pool.CheckEvidence(evList)) + // restore original byz vals + ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader) + + // duplicate evidence should be rejected + evList = types.EvidenceList{ev, ev} + pool, err = evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + assert.Error(t, pool.CheckEvidence(evList)) + + // If evidence is submitted with an altered timestamp it should return an error + ev.Timestamp = defaultEvidenceTime.Add(1 * time.Minute) + pool, err = evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + assert.Error(t, pool.AddEvidence(ev)) + ev.Timestamp = defaultEvidenceTime + + // Evidence submitted with a different validator power should fail + ev.TotalVotingPower = 1 + pool, err = evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + assert.Error(t, pool.AddEvidence(ev)) + ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower() +} + +func TestVerify_ForwardLunaticAttack(t *testing.T) { + const ( + nodeHeight int64 = 8 + attackHeight int64 = 10 + commonHeight int64 = 4 + totalVals = 10 + byzVals = 5 + ) + attackTime := defaultEvidenceTime.Add(1 * time.Hour) + + // create a forward lunatic attack + ev, trusted, common := makeLunaticEvidence( + t, attackHeight, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime) + + // now we try to test verification against state + state := sm.State{ + LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour), + LastBlockHeight: nodeHeight, + ConsensusParams: *types.DefaultConsensusParams(), + } + + // modify trusted light block so that it is of a height less than the conflicting one + trusted.Height = state.LastBlockHeight + trusted.Time = state.LastBlockTime + + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header}) + blockStore.On("LoadBlockMeta", nodeHeight).Return(&types.BlockMeta{Header: *trusted.Header}) + blockStore.On("LoadBlockMeta", attackHeight).Return(nil) + blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit) + blockStore.On("LoadBlockCommit", nodeHeight).Return(trusted.Commit) + blockStore.On("Height").Return(nodeHeight) + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + + // check that the evidence pool correctly verifies the evidence + assert.NoError(t, pool.CheckEvidence(types.EvidenceList{ev})) + + // now we use a time which isn't able to contradict the FLA - thus we can't verify the evidence + oldBlockStore := &mocks.BlockStore{} + oldHeader := trusted.Header + oldHeader.Time = defaultEvidenceTime + oldBlockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header}) + oldBlockStore.On("LoadBlockMeta", nodeHeight).Return(&types.BlockMeta{Header: *oldHeader}) + oldBlockStore.On("LoadBlockMeta", attackHeight).Return(nil) + oldBlockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit) + oldBlockStore.On("LoadBlockCommit", nodeHeight).Return(trusted.Commit) + oldBlockStore.On("Height").Return(nodeHeight) + require.Equal(t, defaultEvidenceTime, oldBlockStore.LoadBlockMeta(nodeHeight).Header.Time) + + pool, err = evidence.NewPool(dbm.NewMemDB(), stateStore, oldBlockStore) + require.NoError(t, err) + assert.Error(t, pool.CheckEvidence(types.EvidenceList{ev})) +} + +func TestVerifyLightClientAttack_Equivocation(t *testing.T) { + conflictingVals, conflictingPrivVals := types.RandValidatorSet(5, 10) + trustedHeader := makeHeaderRandom(10) + + conflictingHeader := makeHeaderRandom(10) + conflictingHeader.ValidatorsHash = conflictingVals.Hash() + + trustedHeader.ValidatorsHash = conflictingHeader.ValidatorsHash + trustedHeader.NextValidatorsHash = conflictingHeader.NextValidatorsHash + trustedHeader.ConsensusHash = conflictingHeader.ConsensusHash + trustedHeader.AppHash = conflictingHeader.AppHash + trustedHeader.LastResultsHash = conflictingHeader.LastResultsHash + + // we are simulating a duplicate vote attack where all the validators in the conflictingVals set + // except the last validator vote twice + blockID := makeBlockID(conflictingHeader.Hash(), 1000, []byte("partshash")) + voteSet := types.NewVoteSet(evidenceChainID, 10, 1, cmtproto.SignedMsgType(2), conflictingVals) + commit, err := test.MakeCommitFromVoteSet(blockID, voteSet, conflictingPrivVals[:4], defaultEvidenceTime) + require.NoError(t, err) + ev := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: conflictingHeader, + Commit: commit, + }, + ValidatorSet: conflictingVals, + }, + CommonHeight: 10, + ByzantineValidators: conflictingVals.Validators[:4], + TotalVotingPower: 50, + Timestamp: defaultEvidenceTime, + } + + trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash")) + trustedVoteSet := types.NewVoteSet(evidenceChainID, 10, 1, cmtproto.SignedMsgType(2), conflictingVals) + trustedCommit, err := test.MakeCommitFromVoteSet(trustedBlockID, trustedVoteSet, conflictingPrivVals, defaultEvidenceTime) + require.NoError(t, err) + trustedSignedHeader := &types.SignedHeader{ + Header: trustedHeader, + Commit: trustedCommit, + } + + // good pass -> no error + err = evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, conflictingVals, + defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour) + assert.NoError(t, err) + + // trusted and conflicting hashes are the same -> an error should be returned + err = evidence.VerifyLightClientAttack(ev, trustedSignedHeader, ev.ConflictingBlock.SignedHeader, conflictingVals, + defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour) + assert.Error(t, err) + + // conflicting header has different next validators hash which should have been correctly derived from + // the previous round + ev.ConflictingBlock.NextValidatorsHash = crypto.CRandBytes(tmhash.Size) + err = evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, nil, + defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour) + assert.Error(t, err) + // revert next validators hash + ev.ConflictingBlock.NextValidatorsHash = trustedHeader.NextValidatorsHash + + state := sm.State{ + LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute), + LastBlockHeight: 11, + ConsensusParams: *types.DefaultConsensusParams(), + } + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", int64(10)).Return(conflictingVals, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: *trustedHeader}) + blockStore.On("LoadBlockCommit", int64(10)).Return(trustedCommit) + + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + + evList := types.EvidenceList{ev} + err = pool.CheckEvidence(evList) + assert.NoError(t, err) + + pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + assert.Equal(t, 1, len(pendingEvs)) +} + +func TestVerifyLightClientAttack_Amnesia(t *testing.T) { + conflictingVals, conflictingPrivVals := types.RandValidatorSet(5, 10) + + conflictingHeader := makeHeaderRandom(10) + conflictingHeader.ValidatorsHash = conflictingVals.Hash() + trustedHeader := makeHeaderRandom(10) + trustedHeader.ValidatorsHash = conflictingHeader.ValidatorsHash + trustedHeader.NextValidatorsHash = conflictingHeader.NextValidatorsHash + trustedHeader.AppHash = conflictingHeader.AppHash + trustedHeader.ConsensusHash = conflictingHeader.ConsensusHash + trustedHeader.LastResultsHash = conflictingHeader.LastResultsHash + + // we are simulating an amnesia attack where all the validators in the conflictingVals set + // except the last validator vote twice. However this time the commits are of different rounds. + blockID := makeBlockID(conflictingHeader.Hash(), 1000, []byte("partshash")) + voteSet := types.NewVoteSet(evidenceChainID, 10, 0, cmtproto.SignedMsgType(2), conflictingVals) + commit, err := test.MakeCommitFromVoteSet(blockID, voteSet, conflictingPrivVals, defaultEvidenceTime) + require.NoError(t, err) + ev := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: conflictingHeader, + Commit: commit, + }, + ValidatorSet: conflictingVals, + }, + CommonHeight: 10, + ByzantineValidators: nil, // with amnesia evidence no validators are submitted as abci evidence + TotalVotingPower: 50, + Timestamp: defaultEvidenceTime, + } + + trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash")) + trustedVoteSet := types.NewVoteSet(evidenceChainID, 10, 1, cmtproto.SignedMsgType(2), conflictingVals) + trustedCommit, err := test.MakeCommitFromVoteSet(trustedBlockID, trustedVoteSet, conflictingPrivVals, defaultEvidenceTime) + require.NoError(t, err) + trustedSignedHeader := &types.SignedHeader{ + Header: trustedHeader, + Commit: trustedCommit, + } + + // good pass -> no error + err = evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, conflictingVals, + defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour) + assert.NoError(t, err) + + // trusted and conflicting hashes are the same -> an error should be returned + err = evidence.VerifyLightClientAttack(ev, trustedSignedHeader, ev.ConflictingBlock.SignedHeader, conflictingVals, + defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour) + assert.Error(t, err) + + state := sm.State{ + LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute), + LastBlockHeight: 11, + ConsensusParams: *types.DefaultConsensusParams(), + } + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", int64(10)).Return(conflictingVals, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: *trustedHeader}) + blockStore.On("LoadBlockCommit", int64(10)).Return(trustedCommit) + + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + pool.SetLogger(log.TestingLogger()) + + evList := types.EvidenceList{ev} + err = pool.CheckEvidence(evList) + assert.NoError(t, err) + + pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + assert.Equal(t, 1, len(pendingEvs)) +} + +type voteData struct { + vote1 *types.Vote + vote2 *types.Vote + valid bool +} + +func TestVerifyDuplicateVoteEvidence(t *testing.T) { + val := types.NewMockPV() + val2 := types.NewMockPV() + valSet := types.NewValidatorSet([]*types.Validator{val.ExtractIntoValidator(1)}) + + blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash")) + blockID2 := makeBlockID([]byte("blockhash2"), 1000, []byte("partshash")) + blockID3 := makeBlockID([]byte("blockhash"), 10000, []byte("partshash")) + blockID4 := makeBlockID([]byte("blockhash"), 10000, []byte("partshash2")) + + const chainID = "mychain" + + vote1 := types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime) + + v1 := vote1.ToProto() + err := val.SignVote(chainID, v1) + require.NoError(t, err) + badVote := types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime) + bv := badVote.ToProto() + err = val2.SignVote(chainID, bv) + require.NoError(t, err) + + vote1.Signature = v1.Signature + badVote.Signature = bv.Signature + + cases := []voteData{ + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID2, defaultEvidenceTime), true}, // different block ids + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID3, defaultEvidenceTime), true}, + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID4, defaultEvidenceTime), true}, + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime), false}, // wrong block id + {vote1, types.MakeVoteNoError(t, val, "mychain2", 0, 10, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong chain id + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 11, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong height + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 3, 1, blockID2, defaultEvidenceTime), false}, // wrong round + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 2, blockID2, defaultEvidenceTime), false}, // wrong step + {vote1, types.MakeVoteNoError(t, val2, chainID, 0, 10, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong validator + // a different vote time doesn't matter + {vote1, types.MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID2, time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)), true}, + {vote1, badVote, false}, // signed by wrong key + } + + require.NoError(t, err) + for _, c := range cases { + ev := &types.DuplicateVoteEvidence{ + VoteA: c.vote1, + VoteB: c.vote2, + ValidatorPower: 1, + TotalVotingPower: 1, + Timestamp: defaultEvidenceTime, + } + if c.valid { + assert.Nil(t, evidence.VerifyDuplicateVote(ev, chainID, valSet), "evidence should be valid") + } else { + assert.NotNil(t, evidence.VerifyDuplicateVote(ev, chainID, valSet), "evidence should be invalid") + } + } + + // create good evidence and correct validator power + goodEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(10, defaultEvidenceTime, val, chainID) + require.NoError(t, err) + goodEv.ValidatorPower = 1 + goodEv.TotalVotingPower = 1 + badEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(10, defaultEvidenceTime, val, chainID) + require.NoError(t, err) + badTimeEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(10, defaultEvidenceTime.Add(1*time.Minute), val, chainID) + require.NoError(t, err) + badTimeEv.ValidatorPower = 1 + badTimeEv.TotalVotingPower = 1 + state := sm.State{ + ChainID: chainID, + LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute), + LastBlockHeight: 11, + ConsensusParams: *types.DefaultConsensusParams(), + } + stateStore := &smmocks.Store{} + stateStore.On("LoadValidators", int64(10)).Return(valSet, nil) + stateStore.On("Load").Return(state, nil) + blockStore := &mocks.BlockStore{} + blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}}) + + pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore) + require.NoError(t, err) + + evList := types.EvidenceList{goodEv} + err = pool.CheckEvidence(evList) + assert.NoError(t, err) + + // evidence with a different validator power should fail + evList = types.EvidenceList{badEv} + err = pool.CheckEvidence(evList) + assert.Error(t, err) + + // evidence with a different timestamp should fail + evList = types.EvidenceList{badTimeEv} + err = pool.CheckEvidence(evList) + assert.Error(t, err) +} + +func makeLunaticEvidence( + t *testing.T, + height, commonHeight int64, + totalVals, byzVals, phantomVals int, + commonTime, attackTime time.Time, +) (ev *types.LightClientAttackEvidence, trusted *types.LightBlock, common *types.LightBlock) { + commonValSet, commonPrivVals := types.RandValidatorSet(totalVals, defaultVotingPower) + + require.Greater(t, totalVals, byzVals) + + // extract out the subset of byzantine validators in the common validator set + byzValSet, byzPrivVals := commonValSet.Validators[:byzVals], commonPrivVals[:byzVals] + + phantomValSet, phantomPrivVals := types.RandValidatorSet(phantomVals, defaultVotingPower) + + conflictingVals := phantomValSet.Copy() + require.NoError(t, conflictingVals.UpdateWithChangeSet(byzValSet)) + conflictingPrivVals := append(phantomPrivVals, byzPrivVals...) + + conflictingPrivVals = orderPrivValsByValSet(t, conflictingVals, conflictingPrivVals) + + commonHeader := makeHeaderRandom(commonHeight) + commonHeader.Time = commonTime + trustedHeader := makeHeaderRandom(height) + + conflictingHeader := makeHeaderRandom(height) + conflictingHeader.Time = attackTime + conflictingHeader.ValidatorsHash = conflictingVals.Hash() + + blockID := makeBlockID(conflictingHeader.Hash(), 1000, []byte("partshash")) + voteSet := types.NewVoteSet(evidenceChainID, height, 1, cmtproto.SignedMsgType(2), conflictingVals) + commit, err := test.MakeCommitFromVoteSet(blockID, voteSet, conflictingPrivVals, defaultEvidenceTime) + require.NoError(t, err) + ev = &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: conflictingHeader, + Commit: commit, + }, + ValidatorSet: conflictingVals, + }, + CommonHeight: commonHeight, + TotalVotingPower: commonValSet.TotalVotingPower(), + ByzantineValidators: byzValSet, + Timestamp: commonTime, + } + + common = &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: commonHeader, + // we can leave this empty because we shouldn't be checking this + Commit: &types.Commit{}, + }, + ValidatorSet: commonValSet, + } + trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash")) + trustedVals, privVals := types.RandValidatorSet(totalVals, defaultVotingPower) + trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, cmtproto.SignedMsgType(2), trustedVals) + trustedCommit, err := test.MakeCommitFromVoteSet(trustedBlockID, trustedVoteSet, privVals, defaultEvidenceTime) + require.NoError(t, err) + trusted = &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: trustedHeader, + Commit: trustedCommit, + }, + ValidatorSet: trustedVals, + } + return ev, trusted, common +} + +// func makeEquivocationEvidence() *types.LightClientAttackEvidence { + +// } + +// func makeAmnesiaEvidence() *types.LightClientAttackEvidence { + +// } + +func makeHeaderRandom(height int64) *types.Header { + return &types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: evidenceChainID, + Height: height, + Time: defaultEvidenceTime, + LastBlockID: makeBlockID([]byte("headerhash"), 1000, []byte("partshash")), + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: crypto.CRandBytes(tmhash.Size), + NextValidatorsHash: crypto.CRandBytes(tmhash.Size), + ConsensusHash: crypto.CRandBytes(tmhash.Size), + AppHash: crypto.CRandBytes(tmhash.Size), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + } +} + +func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID { + var ( + h = make([]byte, tmhash.Size) + psH = make([]byte, tmhash.Size) + ) + copy(h, hash) + copy(psH, partSetHash) + return types.BlockID{ + Hash: h, + PartSetHeader: types.PartSetHeader{ + Total: partSetSize, + Hash: psH, + }, + } +} + +func orderPrivValsByValSet( + t *testing.T, vals *types.ValidatorSet, privVals []types.PrivValidator, +) []types.PrivValidator { + output := make([]types.PrivValidator, len(privVals)) + for idx, v := range vals.Validators { + for _, p := range privVals { + pubKey, err := p.GetPubKey() + require.NoError(t, err) + if bytes.Equal(v.Address, pubKey.Address()) { + output[idx] = p + break + } + } + require.NotEmpty(t, output[idx]) + } + return output +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..58efb38 --- /dev/null +++ b/go.mod @@ -0,0 +1,147 @@ +module git.cw.tr/mukan-network/mukan-consensus + +go 1.22.11 + +require ( + github.com/BurntSushi/toml v1.4.0 + github.com/Masterminds/semver/v3 v3.3.1 + github.com/adlio/schema v1.3.6 + github.com/btcsuite/btcd/btcutil v1.1.6 + github.com/cenkalti/backoff v2.2.1+incompatible // indirect + github.com/cometbft/cometbft-db v0.14.1 + github.com/cosmos/gogoproto v1.7.0 + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 + github.com/fortytw2/leaktest v1.3.0 + github.com/go-git/go-git/v5 v5.13.2 + github.com/go-kit/kit v0.13.0 + github.com/go-kit/log v0.2.1 + github.com/go-logfmt/logfmt v0.6.0 + github.com/gofrs/uuid v4.4.0+incompatible + github.com/golang/protobuf v1.5.4 + github.com/google/orderedcode v0.0.1 + github.com/google/uuid v1.6.0 + github.com/gorilla/websocket v1.5.3 + github.com/hashicorp/golang-lru/v2 v2.0.7 + github.com/informalsystems/tm-load-test v1.3.0 + github.com/lib/pq v1.10.9 + github.com/minio/highwayhash v1.0.3 + github.com/oasisprotocol/curve25519-voi v0.0.0-20220708102147-0a8a51822cae + github.com/ory/dockertest v3.3.5+incompatible + github.com/pkg/errors v0.9.1 + github.com/prometheus/client_golang v1.21.0 + github.com/prometheus/client_model v0.6.1 + github.com/prometheus/common v0.62.0 + github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 + github.com/rs/cors v1.11.1 + github.com/sasha-s/go-deadlock v0.3.5 + github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa + github.com/spf13/cobra v1.9.1 + github.com/spf13/viper v1.19.0 + github.com/stretchr/testify v1.10.0 + github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 + golang.org/x/crypto v0.33.0 + golang.org/x/net v0.35.0 + golang.org/x/sync v0.11.0 + gonum.org/v1/gonum v0.15.1 + google.golang.org/grpc v1.70.0 + google.golang.org/protobuf v1.36.5 +) + +require ( + dario.cat/mergo v1.0.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect + github.com/DataDog/zstd v1.4.5 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect + github.com/ProtonMail/go-crypto v1.1.5 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cloudflare/circl v1.3.7 // indirect + github.com/cockroachdb/errors v1.11.3 // indirect + github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/cockroachdb/pebble v1.1.1 // indirect + github.com/cockroachdb/redact v1.1.5 // indirect + github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect + github.com/containerd/continuity v0.3.0 // indirect + github.com/cyphar/filepath-securejoin v0.3.6 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/dgraph-io/badger/v4 v4.2.0 // indirect + github.com/dgraph-io/ristretto v0.1.1 // indirect + github.com/docker/cli v24.0.7+incompatible // indirect + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/emirpasic/gods v1.18.1 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect + github.com/go-git/go-billy/v5 v5.6.2 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/glog v1.2.3 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/btree v1.1.3 // indirect + github.com/google/flatbuffers v1.12.1 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/gotestyourself/gotestyourself v2.2.0+incompatible // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect + github.com/jmhodges/levigo v1.0.0 // indirect + github.com/kevinburke/ssh_config v1.2.0 // indirect + github.com/klauspost/compress v1.17.11 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/linxGnu/grocksdb v1.8.14 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.0-rc2 // indirect + github.com/opencontainers/runc v1.1.12 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect + github.com/pjbgf/sha1cd v0.3.2 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/procfs v0.15.1 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/satori/go.uuid v1.2.0 // indirect + github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/skeema/knownhosts v1.3.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.6 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/xanzy/ssh-agent v0.3.3 // indirect + go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect + go.opencensus.io v0.24.0 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect + golang.org/x/mod v0.19.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect + golang.org/x/tools v0.23.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/warnings.v0 v0.1.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + gotest.tools v2.2.0+incompatible // indirect +) + +retract ( + // bumped go version in minor release + v0.38.14 + // a regression was introduced + v0.38.4 + // a breaking change was introduced + v0.38.3 + // superseeded by v0.38.3 because of ASA-2024-001 + [v0.38.0, v0.38.2] +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..123b1ed --- /dev/null +++ b/go.sum @@ -0,0 +1,534 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= +dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= +github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4= +github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= +github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= +github.com/ProtonMail/go-crypto v1.1.5 h1:eoAQfK2dwL+tFSFpr7TbOaPNUbPiJj4fLYwwGE1FQO4= +github.com/ProtonMail/go-crypto v1.1.5/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= +github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= +github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/adlio/schema v1.3.6 h1:k1/zc2jNfeiZBA5aFTRy37jlBIuCkXCm0XmvpzCKI9I= +github.com/adlio/schema v1.3.6/go.mod h1:qkxwLgPBd1FgLRHYVCmQT/rrBr3JH38J9LjmVzWNudg= +github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= +github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= +github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= +github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= +github.com/btcsuite/btcd v0.23.5-0.20231215221805-96c9fd8078fd/go.mod h1:nm3Bko6zh6bWP60UxwoT5LzdGJsQJaPo6HjduXq9p6A= +github.com/btcsuite/btcd v0.24.2/go.mod h1:5C8ChTkl5ejr3WHj8tkQSCmydiMEPB0ZhQhehpq7Dgg= +github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA= +github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE= +github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A= +github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE= +github.com/btcsuite/btcd/btcutil v1.1.5/go.mod h1:PSZZ4UitpLBWzxGd5VGOrLnmOjtPP/a6HaFo12zMs00= +github.com/btcsuite/btcd/btcutil v1.1.6 h1:zFL2+c3Lb9gEgqKNzowKUPQNb8jV7v5Oaodi/AYFd6c= +github.com/btcsuite/btcd/btcutil v1.1.6/go.mod h1:9dFymx8HpuLqBnsPELrImQeTQfKBQqzqGbbV3jK55aE= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= +github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= +github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= +github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= +github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= +github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= +github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= +github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= +github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= +github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= +github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v1.1.1 h1:XnKU22oiCLy2Xn8vp1re67cXg4SAasg/WDt1NtcRFaw= +github.com/cockroachdb/pebble v1.1.1/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= +github.com/cometbft/cometbft-db v0.14.1 h1:SxoamPghqICBAIcGpleHbmoPqy+crij/++eZz3DlerQ= +github.com/cometbft/cometbft-db v0.14.1/go.mod h1:KHP1YghilyGV/xjD5DP3+2hyigWx0WTp9X+0Gnx0RxQ= +github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= +github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= +github.com/cosmos/gogoproto v1.7.0 h1:79USr0oyXAbxg3rspGh/m4SWNyoz/GLaAh0QlCe2fro= +github.com/cosmos/gogoproto v1.7.0/go.mod h1:yWChEv5IUEYURQasfyBW5ffkMHR/90hiHgbNgrtp4j0= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cyphar/filepath-securejoin v0.3.6 h1:4d9N5ykBnSp5Xn2JkhocYDkOpURL/18CYMpo6xB9uWM= +github.com/cyphar/filepath-securejoin v0.3.6/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI= +github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8= +github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= +github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/denisenkom/go-mssqldb v0.12.0 h1:VtrkII767ttSPNRfFekePK3sctr+joXgO58stqQbtUA= +github.com/denisenkom/go-mssqldb v0.12.0/go.mod h1:iiK0YP1ZeepvmBQk/QpLEhhTNJgfzrpArPY/aFvc9yU= +github.com/dgraph-io/badger/v4 v4.2.0 h1:kJrlajbXXL9DFTNuhhu9yCx7JJa4qpYWxtE8BzuWsEs= +github.com/dgraph-io/badger/v4 v4.2.0/go.mod h1:qfCqhPoWDFJRx1gp5QwwyGo8xk1lbHUxvK9nK0OGAak= +github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= +github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/docker/cli v24.0.7+incompatible h1:wa/nIwYFW7BVTGa7SWPVyyXU9lgORqUb1xfI36MSkFg= +github.com/docker/cli v24.0.7+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0= +github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/elazarl/goproxy v1.4.0 h1:4GyuSbFa+s26+3rmYNSuUVsx+HgPrV1bk1jXI0l9wjM= +github.com/elazarl/goproxy v1.4.0/go.mod h1:X/5W/t+gzDyLfHW4DrMdpjqYjpXsURlBt9lpBDxZZZQ= +github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= +github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c= +github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= +github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= +github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM= +github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU= +github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4= +github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII= +github.com/go-git/go-git/v5 v5.13.2 h1:7O7xvsK7K+rZPKW6AQR1YyNhfywkv7B8/FsP3ki6Zv0= +github.com/go-git/go-git/v5 v5.13.2/go.mod h1:hWdW5P4YZRjmpGHwRH2v3zkWcNl6HeXaXQEMGb3NJ9A= +github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU= +github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg= +github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= +github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= +github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188 h1:+eHOFJl1BaXrQxKX+T06f78590z4qA2ZzBTqahsKSE4= +github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.2.3 h1:oDTdz9f5VGVVNGu/Q7UXKWYsD0873HXLHdJUNBsSEKM= +github.com/golang/glog v1.2.3/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/flatbuffers v1.12.1 h1:MVlul7pQNoDzWRLTw5imwYsl+usrS1TXG2H4jg6ImGw= +github.com/google/flatbuffers v1.12.1/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/orderedcode v0.0.1 h1:UzfcAexk9Vhv8+9pNOgRu41f16lHq725vPwnSeiG/Us= +github.com/google/orderedcode v0.0.1/go.mod h1:iVyU4/qPKHY5h/wSd6rZZCDcLJNxiWO6dvsYES2Sb20= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gotestyourself/gotestyourself v2.2.0+incompatible h1:AQwinXlbQR2HvPjQZOmDhRqsv5mZf+Jb1RnSLxcqZcI= +github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= +github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/informalsystems/tm-load-test v1.3.0 h1:FGjKy7vBw6mXNakt+wmNWKggQZRsKkEYpaFk/zR64VA= +github.com/informalsystems/tm-load-test v1.3.0/go.mod h1:OQ5AQ9TbT5hKWBNIwsMjn6Bf4O0U4b1kRc+0qZlQJKw= +github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= +github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= +github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= +github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= +github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= +github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/linxGnu/grocksdb v1.8.14 h1:HTgyYalNwBSG/1qCQUIott44wU5b2Y9Kr3z7SK5OfGQ= +github.com/linxGnu/grocksdb v1.8.14/go.mod h1:QYiYypR2d4v63Wj1adOOfzglnoII0gLj3PNh4fZkcFA= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/minio/highwayhash v1.0.3 h1:kbnuUMoHYyVl7szWjSxJnxw11k2U709jqFPPmIUyD6Q= +github.com/minio/highwayhash v1.0.3/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/oasisprotocol/curve25519-voi v0.0.0-20220708102147-0a8a51822cae h1:FatpGJD2jmJfhZiFDElaC0QhZUDQnxUeAwTGkfAHN3I= +github.com/oasisprotocol/curve25519-voi v0.0.0-20220708102147-0a8a51822cae/go.mod h1:hVoHR2EVESiICEMbg137etN/Lx+lSrHPTD39Z/uE+2s= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k= +github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0-rc2 h1:2zx/Stx4Wc5pIPDvIxHXvXtQFW/7XWJGmnM7r3wg034= +github.com/opencontainers/image-spec v1.1.0-rc2/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ= +github.com/opencontainers/runc v1.1.12 h1:BOIssBaW1La0/qbNZHXOOa71dZfZEQOzW7dqQf3phss= +github.com/opencontainers/runc v1.1.12/go.mod h1:S+lQwSfncpBha7XTy/5lBwWgm5+y5Ma/O44Ekby9FK8= +github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= +github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= +github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= +github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4= +github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.21.0 h1:DIsaGmiaBkSangBgMtWdNfxbMNdku5IK6iNhrEqWvdA= +github.com/prometheus/client_golang v1.21.0/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= +github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= +github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= +github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= +github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/skeema/knownhosts v1.3.0 h1:AM+y0rI04VksttfwjkSTNQorvGqmwATnvnAHpSgc0LY= +github.com/skeema/knownhosts v1.3.0/go.mod h1:sPINvnADmT/qYH1kfv+ePMmOBTH6Tbl7b5LvTDjFK7M= +github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa h1:YJfZp12Z3AFhSBeXOlv4BO55RMwPn2NoQeDsrdWnBtY= +github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= +github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= +github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= +github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 h1:qxen9oVGzDdIRP6ejyAJc760RwW4SnVDiTYTzwnXuxo= +go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5/go.mod h1:eW0HG9/oHQhvRCvb1/pIXW4cOvtDqeQK+XSi3TnwaXY= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= +go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= +go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= +go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= +go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= +go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= +go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= +go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= +go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= +go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= +golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= +golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= +golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.15.1 h1:FNy7N6OUZVUaWG9pTiD+jlhdQ3lMP+/LcTpJ6+a8sQ0= +gonum.org/v1/gonum v0.15.1/go.mod h1:eZTZuRFrzu5pcyjN5wJhcIhnUdNijYxX1T2IcrOGY0o= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a h1:hgh8P4EuoxpsuKMXX/To36nOFD7vixReXgn8lPGnt+o= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= +google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/inspect/doc.go b/inspect/doc.go new file mode 100644 index 0000000..cc9d8ed --- /dev/null +++ b/inspect/doc.go @@ -0,0 +1,36 @@ +/* +Package inspect provides a tool for investigating the state of a +failed CometBFT node. + +This package provides the Inspector type. The Inspector type runs a subset of the CometBFT +RPC endpoints that are useful for debugging issues with CometBFT's consensus. + +When a node running the CometBFT's consensus engine detects an inconsistent consensus state, +the entire node will crash. The CometBFT's consensus engine cannot run in this +inconsistent state so the node will not be able to start up again. + +The RPC endpoints provided by the Inspector type allow for a node operator to inspect +the block store and state store to better understand what may have caused the inconsistent state. + +The Inspector type's lifecycle is controlled by a context.Context + + ins := inspect.NewFromConfig(rpcConfig) + ctx, cancelFunc:= context.WithCancel(context.Background()) + + // Run blocks until the Inspector server is shut down. + go ins.Run(ctx) + ... + + // calling the cancel function will stop the running inspect server + cancelFunc() + +Inspector serves its RPC endpoints on the address configured in the RPC configuration + + rpcConfig.ListenAddress = "tcp://127.0.0.1:26657" + ins := inspect.NewFromConfig(rpcConfig) + go ins.Run(ctx) + +The list of available RPC endpoints can then be viewed by navigating to +http://127.0.0.1:26657/ in the web browser. +*/ +package inspect diff --git a/inspect/inspect.go b/inspect/inspect.go new file mode 100644 index 0000000..38dd4bd --- /dev/null +++ b/inspect/inspect.go @@ -0,0 +1,141 @@ +package inspect + +import ( + "context" + "errors" + "net" + "os" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/inspect/rpc" + "github.com/cometbft/cometbft/libs/log" + cmtstrings "github.com/cometbft/cometbft/libs/strings" + rpccore "github.com/cometbft/cometbft/rpc/core" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/indexer/block" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + + "golang.org/x/sync/errgroup" +) + +var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + +// Inspector manages an RPC service that exports methods to debug a failed node. +// After a node shuts down due to a consensus failure, it will no longer start +// up its state cannot easily be inspected. An Inspector value provides a similar interface +// to the node, using the underlying CometBFT data stores, without bringing up +// any other components. A caller can query the Inspector service to inspect the +// persisted state and debug the failure. +type Inspector struct { + routes rpccore.RoutesMap + + config *config.RPCConfig + + logger log.Logger + + // References to the state store and block store are maintained to enable + // the Inspector to safely close them on shutdown. + ss state.Store + bs state.BlockStore +} + +// New returns an Inspector that serves RPC on the specified BlockStore and StateStore. +// The Inspector type does not modify the state or block stores. +// The sinks are used to enable block and transaction querying via the RPC server. +// The caller is responsible for starting and stopping the Inspector service. +// +//nolint:lll +func New( + cfg *config.RPCConfig, + bs state.BlockStore, + ss state.Store, + txidx txindex.TxIndexer, + blkidx indexer.BlockIndexer, +) *Inspector { + routes := rpc.Routes(*cfg, ss, bs, txidx, blkidx, logger) + eb := types.NewEventBus() + eb.SetLogger(logger.With("module", "events")) + return &Inspector{ + routes: routes, + config: cfg, + logger: logger, + ss: ss, + bs: bs, + } +} + +// NewFromConfig constructs an Inspector using the values defined in the passed in config. +func NewFromConfig(cfg *config.Config) (*Inspector, error) { + bsDB, err := config.DefaultDBProvider(&config.DBContext{ID: "blockstore", Config: cfg}) + if err != nil { + return nil, err + } + bs := store.NewBlockStore(bsDB) + sDB, err := config.DefaultDBProvider(&config.DBContext{ID: "state", Config: cfg}) + if err != nil { + return nil, err + } + genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile()) + if err != nil { + return nil, err + } + txidx, blkidx, err := block.IndexerFromConfig(cfg, config.DefaultDBProvider, genDoc.ChainID) + if err != nil { + return nil, err + } + ss := state.NewStore(sDB, state.StoreOptions{}) + return New(cfg.RPC, bs, ss, txidx, blkidx), nil +} + +// Run starts the Inspector servers and blocks until the servers shut down. The passed +// in context is used to control the lifecycle of the servers. +func (ins *Inspector) Run(ctx context.Context) error { + defer ins.bs.Close() + defer ins.ss.Close() + + return startRPCServers(ctx, ins.config, ins.logger, ins.routes) +} + +func startRPCServers(ctx context.Context, cfg *config.RPCConfig, logger log.Logger, routes rpccore.RoutesMap) error { + g, tctx := errgroup.WithContext(ctx) + listenAddrs := cmtstrings.SplitAndTrimEmpty(cfg.ListenAddress, ",", " ") + rh := rpc.Handler(cfg, routes, logger) + for _, listenerAddr := range listenAddrs { + server := rpc.Server{ + Logger: logger, + Config: cfg, + Handler: rh, + Addr: listenerAddr, + } + if cfg.IsTLSEnabled() { + keyFile := cfg.KeyFile() + certFile := cfg.CertFile() + listenerAddr := listenerAddr + g.Go(func() error { + logger.Info("RPC HTTPS server starting", "address", listenerAddr, + "certfile", certFile, "keyfile", keyFile) + err := server.ListenAndServeTLS(tctx, certFile, keyFile) + if !errors.Is(err, net.ErrClosed) { + return err + } + logger.Info("RPC HTTPS server stopped", "address", listenerAddr) + return nil + }) + } else { + listenerAddr := listenerAddr + g.Go(func() error { + logger.Info("RPC HTTP server starting", "address", listenerAddr) + err := server.ListenAndServe(tctx) + if !errors.Is(err, net.ErrClosed) { + return err + } + logger.Info("RPC HTTP server stopped", "address", listenerAddr) + return nil + }) + } + } + return g.Wait() +} diff --git a/inspect/inspect_test.go b/inspect/inspect_test.go new file mode 100644 index 0000000..afbf843 --- /dev/null +++ b/inspect/inspect_test.go @@ -0,0 +1,591 @@ +package inspect_test + +import ( + "context" + "fmt" + "net" + "os" + "strings" + "sync" + "testing" + "time" + + abcitypes "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/inspect" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/pubsub/query" + httpclient "github.com/cometbft/cometbft/rpc/client/http" + indexermocks "github.com/cometbft/cometbft/state/indexer/mocks" + statemocks "github.com/cometbft/cometbft/state/mocks" + txindexmocks "github.com/cometbft/cometbft/state/txindex/mocks" + "github.com/cometbft/cometbft/types" + "github.com/fortytw2/leaktest" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestInspectConstructor(t *testing.T) { + cfg := test.ResetTestRoot("test") + t.Cleanup(leaktest.Check(t)) + defer func() { _ = os.RemoveAll(cfg.RootDir) }() + t.Run("from config", func(t *testing.T) { + d, err := inspect.NewFromConfig(cfg) + require.NoError(t, err) + require.NotNil(t, d) + }) +} + +func TestInspectRun(t *testing.T) { + cfg := test.ResetTestRoot("test") + t.Cleanup(leaktest.Check(t)) + defer func() { _ = os.RemoveAll(cfg.RootDir) }() + t.Run("from config", func(t *testing.T) { + d, err := inspect.NewFromConfig(cfg) + require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + stoppedWG := &sync.WaitGroup{} + stoppedWG.Add(1) + go func() { + require.NoError(t, d.Run(ctx)) + stoppedWG.Done() + }() + cancel() + stoppedWG.Wait() + }) +} + +func TestBlock(t *testing.T) { + testHeight := int64(1) + testBlock := new(types.Block) + testBlock.Height = testHeight + testBlock.LastCommitHash = []byte("test hash") + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Height").Return(testHeight) + blockStoreMock.On("Base").Return(int64(0)) + blockStoreMock.On("LoadBlockMeta", testHeight).Return(&types.BlockMeta{}) + blockStoreMock.On("LoadBlock", testHeight).Return(testBlock) + blockStoreMock.On("Close").Return(nil) + + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + resultBlock, err := cli.Block(context.Background(), &testHeight) + require.NoError(t, err) + require.Equal(t, testBlock.Height, resultBlock.Block.Height) + require.Equal(t, testBlock.LastCommitHash, resultBlock.Block.LastCommitHash) + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestTxSearch(t *testing.T) { + testHash := []byte("test") + testTx := []byte("tx") + testQuery := fmt.Sprintf("tx.hash='%s'", string(testHash)) + testTxResult := &abcitypes.TxResult{ + Height: 1, + Index: 100, + Tx: testTx, + } + + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + txIndexerMock.On("Search", mock.Anything, + mock.MatchedBy(func(q *query.Query) bool { + return testQuery == strings.ReplaceAll(q.String(), " ", "") + })). + Return([]*abcitypes.TxResult{testTxResult}, nil) + + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + + page := 1 + resultTxSearch, err := cli.TxSearch(context.Background(), testQuery, false, &page, &page, "") + require.NoError(t, err) + require.Len(t, resultTxSearch.Txs, 1) + require.Equal(t, types.Tx(testTx), resultTxSearch.Txs[0].Tx) + + cancel() + wg.Wait() + + txIndexerMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) + blockStoreMock.AssertExpectations(t) +} + +func TestTx(t *testing.T) { + testHash := []byte("test") + testTx := []byte("tx") + + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blkIdxMock := &indexermocks.BlockIndexer{} + txIndexerMock := &txindexmocks.TxIndexer{} + txIndexerMock.On("Get", testHash).Return(&abcitypes.TxResult{ + Tx: testTx, + }, nil) + + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + + res, err := cli.Tx(context.Background(), testHash, false) + require.NoError(t, err) + require.Equal(t, types.Tx(testTx), res.Tx) + + cancel() + wg.Wait() + + txIndexerMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) + blockStoreMock.AssertExpectations(t) +} + +func TestConsensusParams(t *testing.T) { + testHeight := int64(1) + testMaxGas := int64(55) + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("Height").Return(testHeight) + blockStoreMock.On("Base").Return(int64(0)) + stateStoreMock.On("LoadConsensusParams", testHeight).Return(types.ConsensusParams{ + Block: types.BlockParams{ + MaxGas: testMaxGas, + }, + }, nil) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + params, err := cli.ConsensusParams(context.Background(), &testHeight) + require.NoError(t, err) + require.Equal(t, params.ConsensusParams.Block.MaxGas, testMaxGas) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestBlockResults(t *testing.T) { + testHeight := int64(1) + testGasUsed := int64(100) + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + // cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + stateStoreMock.On("LoadFinalizeBlockResponse", testHeight).Return(&abcitypes.ResponseFinalizeBlock{ + TxResults: []*abcitypes.ExecTxResult{ + { + GasUsed: testGasUsed, + }, + }, + }, nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("Base").Return(int64(0)) + blockStoreMock.On("Height").Return(testHeight) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + res, err := cli.BlockResults(context.Background(), &testHeight) + require.NoError(t, err) + require.Equal(t, res.TxsResults[0].GasUsed, testGasUsed) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestCommit(t *testing.T) { + testHeight := int64(1) + testRound := int32(101) + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("Base").Return(int64(0)) + blockStoreMock.On("Height").Return(testHeight) + blockStoreMock.On("LoadBlockMeta", testHeight).Return(&types.BlockMeta{}, nil) + blockStoreMock.On("LoadSeenCommit", testHeight).Return(&types.Commit{ + Height: testHeight, + Round: testRound, + }, nil) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + res, err := cli.Commit(context.Background(), &testHeight) + require.NoError(t, err) + require.NotNil(t, res) + require.Equal(t, res.Commit.Round, testRound) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestBlockByHash(t *testing.T) { + testHeight := int64(1) + testHash := []byte("test hash") + testBlock := new(types.Block) + testBlock.Height = testHeight + testBlock.LastCommitHash = testHash + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("LoadBlockMeta", testHeight).Return(&types.BlockMeta{ + BlockID: types.BlockID{ + Hash: testHash, + }, + Header: types.Header{ + Height: testHeight, + }, + }, nil) + blockStoreMock.On("LoadBlockByHash", testHash).Return(testBlock, nil) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + res, err := cli.BlockByHash(context.Background(), testHash) + require.NoError(t, err) + require.NotNil(t, res) + require.Equal(t, []byte(res.BlockID.Hash), testHash) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestBlockchain(t *testing.T) { + testHeight := int64(1) + testBlock := new(types.Block) + testBlockHash := []byte("test hash") + testBlock.Height = testHeight + testBlock.LastCommitHash = testBlockHash + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("Height").Return(testHeight) + blockStoreMock.On("Base").Return(int64(0)) + blockStoreMock.On("LoadBlockMeta", testHeight).Return(&types.BlockMeta{ + BlockID: types.BlockID{ + Hash: testBlockHash, + }, + }) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + res, err := cli.BlockchainInfo(context.Background(), 0, 100) + require.NoError(t, err) + require.NotNil(t, res) + require.Equal(t, testBlockHash, []byte(res.BlockMetas[0].BlockID.Hash)) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestValidators(t *testing.T) { + testHeight := int64(1) + testVotingPower := int64(100) + testValidators := types.ValidatorSet{ + Validators: []*types.Validator{ + { + VotingPower: testVotingPower, + }, + }, + } + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + stateStoreMock.On("LoadValidators", testHeight).Return(&testValidators, nil) + + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + blockStoreMock.On("Height").Return(testHeight) + blockStoreMock.On("Base").Return(int64(0)) + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + + testPage := 1 + testPerPage := 100 + res, err := cli.Validators(context.Background(), &testHeight, &testPage, &testPerPage) + require.NoError(t, err) + require.NotNil(t, res) + require.Equal(t, testVotingPower, res.Validators[0].VotingPower) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func TestBlockSearch(t *testing.T) { + testHeight := int64(1) + testBlockHash := []byte("test hash") + testQuery := "block.height = 1" + stateStoreMock := &statemocks.Store{} + stateStoreMock.On("Close").Return(nil) + + blockStoreMock := &statemocks.BlockStore{} + blockStoreMock.On("Close").Return(nil) + + txIndexerMock := &txindexmocks.TxIndexer{} + blkIdxMock := &indexermocks.BlockIndexer{} + blockStoreMock.On("LoadBlock", testHeight).Return(&types.Block{ + Header: types.Header{ + Height: testHeight, + }, + }, nil) + blockStoreMock.On("LoadBlockMeta", testHeight).Return(&types.BlockMeta{ + BlockID: types.BlockID{ + Hash: testBlockHash, + }, + }) + blkIdxMock.On("Search", mock.Anything, + mock.MatchedBy(func(q *query.Query) bool { return testQuery == q.String() })). + Return([]int64{testHeight}, nil) + rpcConfig := config.TestRPCConfig() + d := inspect.New(rpcConfig, blockStoreMock, stateStoreMock, txIndexerMock, blkIdxMock) + + ctx, cancel := context.WithCancel(context.Background()) + wg := &sync.WaitGroup{} + wg.Add(1) + + startedWG := &sync.WaitGroup{} + startedWG.Add(1) + go func() { + startedWG.Done() + defer wg.Done() + require.NoError(t, d.Run(ctx)) + }() + // FIXME: used to induce context switch. + // Determine more deterministic method for prompting a context switch + startedWG.Wait() + requireConnect(t, rpcConfig.ListenAddress, 20) + cli, err := httpclient.New(rpcConfig.ListenAddress, "/websocket") + require.NoError(t, err) + + testPage := 1 + testPerPage := 100 + testOrderBy := "desc" + res, err := cli.BlockSearch(context.Background(), testQuery, &testPage, &testPerPage, testOrderBy) + require.NoError(t, err) + require.NotNil(t, res) + require.Equal(t, testBlockHash, []byte(res.Blocks[0].BlockID.Hash)) + + cancel() + wg.Wait() + + blockStoreMock.AssertExpectations(t) + stateStoreMock.AssertExpectations(t) +} + +func requireConnect(t testing.TB, addr string, retries int) { + parts := strings.SplitN(addr, "://", 2) + if len(parts) != 2 { + t.Fatalf("malformed address to dial: %s", addr) + } + var err error + for i := 0; i < retries; i++ { + var conn net.Conn + conn, err = net.Dial(parts[0], parts[1]) + if err == nil { + conn.Close() + return + } + // FIXME attempt to yield and let the other goroutine continue execution. + time.Sleep(time.Microsecond * 100) + } + t.Fatalf("unable to connect to server %s after %d tries: %s", addr, retries, err) +} diff --git a/inspect/rpc/rpc.go b/inspect/rpc/rpc.go new file mode 100644 index 0000000..6ef69a5 --- /dev/null +++ b/inspect/rpc/rpc.go @@ -0,0 +1,128 @@ +package rpc + +import ( + "context" + "net/http" + "time" + + "github.com/rs/cors" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/rpc/core" + "github.com/cometbft/cometbft/rpc/jsonrpc/server" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/txindex" +) + +// Server defines parameters for running an Inspector rpc server. +type Server struct { + Addr string // TCP address to listen on, ":http" if empty + Handler http.Handler + Logger log.Logger + Config *config.RPCConfig +} + +// Routes returns the set of routes used by the Inspector server. +func Routes(cfg config.RPCConfig, s state.Store, bs state.BlockStore, txidx txindex.TxIndexer, blkidx indexer.BlockIndexer, logger log.Logger) core.RoutesMap { //nolint: lll + env := &core.Environment{ + Config: cfg, + BlockIndexer: blkidx, + TxIndexer: txidx, + StateStore: s, + BlockStore: bs, + ConsensusReactor: waitSyncCheckerImpl{}, + Logger: logger, + } + return core.RoutesMap{ + "blockchain": server.NewRPCFunc(env.BlockchainInfo, "minHeight,maxHeight"), + "consensus_params": server.NewRPCFunc(env.ConsensusParams, "height"), + "block": server.NewRPCFunc(env.Block, "height"), + "block_by_hash": server.NewRPCFunc(env.BlockByHash, "hash"), + "block_results": server.NewRPCFunc(env.BlockResults, "height"), + "commit": server.NewRPCFunc(env.Commit, "height"), + "header": server.NewRPCFunc(env.Header, "height"), + "header_by_hash": server.NewRPCFunc(env.HeaderByHash, "hash"), + "validators": server.NewRPCFunc(env.Validators, "height,page,per_page"), + "tx": server.NewRPCFunc(env.Tx, "hash,prove"), + "tx_search": server.NewRPCFunc(env.TxSearch, "query,prove,page,per_page,order_by"), + "block_search": server.NewRPCFunc(env.BlockSearch, "query,page,per_page,order_by"), + } +} + +// Handler returns the http.Handler configured for use with an Inspector server. Handler +// registers the routes on the http.Handler and also registers the websocket handler +// and the CORS handler if specified by the configuration options. +func Handler(rpcConfig *config.RPCConfig, routes core.RoutesMap, logger log.Logger) http.Handler { + mux := http.NewServeMux() + wmLogger := logger.With("protocol", "websocket") + wm := server.NewWebsocketManager(routes, + server.ReadLimit(rpcConfig.MaxBodyBytes)) + wm.SetLogger(wmLogger) + mux.HandleFunc("/websocket", wm.WebsocketHandler) + + server.RegisterRPCFuncs(mux, routes, logger) + var rootHandler http.Handler = mux + if rpcConfig.IsCorsEnabled() { + rootHandler = addCORSHandler(rpcConfig, mux) + } + return rootHandler +} + +func addCORSHandler(rpcConfig *config.RPCConfig, h http.Handler) http.Handler { + corsMiddleware := cors.New(cors.Options{ + AllowedOrigins: rpcConfig.CORSAllowedOrigins, + AllowedMethods: rpcConfig.CORSAllowedMethods, + AllowedHeaders: rpcConfig.CORSAllowedHeaders, + }) + h = corsMiddleware.Handler(h) + return h +} + +type waitSyncCheckerImpl struct{} + +func (waitSyncCheckerImpl) WaitSync() bool { + return false +} + +// ListenAndServe listens on the address specified in srv.Addr and handles any +// incoming requests over HTTP using the Inspector rpc handler specified on the server. +func (srv *Server) ListenAndServe(ctx context.Context) error { + listener, err := server.Listen(srv.Addr, srv.Config.MaxOpenConnections) + if err != nil { + return err + } + go func() { + <-ctx.Done() + listener.Close() + }() + return server.Serve(listener, srv.Handler, srv.Logger, serverRPCConfig(srv.Config)) +} + +// ListenAndServeTLS listens on the address specified in srv.Addr. ListenAndServeTLS handles +// incoming requests over HTTPS using the Inspector rpc handler specified on the server. +func (srv *Server) ListenAndServeTLS(ctx context.Context, certFile, keyFile string) error { + listener, err := server.Listen(srv.Addr, srv.Config.MaxOpenConnections) + if err != nil { + return err + } + go func() { + <-ctx.Done() + listener.Close() + }() + return server.ServeTLS(listener, srv.Handler, certFile, keyFile, srv.Logger, serverRPCConfig(srv.Config)) +} + +func serverRPCConfig(r *config.RPCConfig) *server.Config { + cfg := server.DefaultConfig() + cfg.MaxBodyBytes = r.MaxBodyBytes + cfg.MaxHeaderBytes = r.MaxHeaderBytes + // If necessary adjust global WriteTimeout to ensure it's greater than + // TimeoutBroadcastTxCommit. + // See https://github.com/tendermint/tendermint/issues/3435 + if cfg.WriteTimeout <= r.TimeoutBroadcastTxCommit { + cfg.WriteTimeout = r.TimeoutBroadcastTxCommit + 1*time.Second + } + return cfg +} diff --git a/internal/indexer/indexer_utils.go b/internal/indexer/indexer_utils.go new file mode 100644 index 0000000..21848eb --- /dev/null +++ b/internal/indexer/indexer_utils.go @@ -0,0 +1,119 @@ +package indexer + +import ( + "fmt" + "math/big" + + "github.com/cometbft/cometbft/state/indexer" +) + +// If the actual event value is a float, we get the condition and parse it as a float +// to compare against +func compareFloat(op1 *big.Float, op2 interface{}) (int, bool, error) { + switch opVal := op2.(type) { + case *big.Int: + vF := new(big.Float) + vF.SetInt(opVal) + cmp := op1.Cmp(vF) + return cmp, false, nil + + case *big.Float: + return op1.Cmp(opVal), true, nil + default: + return -1, false, fmt.Errorf("unable to parse arguments, bad type: %T", op2) + } +} + +// If the event value we compare against the condition (op2) is an integer +// we convert the int to float with a precision equal to the number of bits +// needed to represent the integer to avoid rounding issues with floats +// where 100 would equal to 100.2 because 100.2 is rounded to 100, while 100.7 +// would be rounded to 101. +func compareInt(op1 *big.Int, op2 interface{}) (int, bool, error) { + + switch opVal := op2.(type) { + case *big.Int: + return op1.Cmp(opVal), false, nil + case *big.Float: + vF := new(big.Float) + vF.SetInt(op1) + return vF.Cmp(opVal), true, nil + default: + return -1, false, fmt.Errorf("unable to parse arguments, unexpected type: %T", op2) + } +} + +func CheckBounds(ranges indexer.QueryRange, v interface{}) (bool, error) { + // These functions fetch the lower and upper bounds of the query + // It is expected that for x > 5, the value of lowerBound is 6. + // This is achieved by adding one to the actual lower bound. + // For a query of x < 5, the value of upper bound is 4. + // This is achieved by subtracting one from the actual upper bound. + + // For integers this behavior will work. However, for floats, we cannot simply add/sub 1. + // Query :x < 5.5 ; x = 5 should match the query. If we subtracted one as for integers, + // the upperBound would be 4.5 and x would not match. Thus we do not subtract anything for + // floating point bounds. + + // We can rewrite these functions to not add/sub 1 but the function handles also time arguments. + // To be sure we are not breaking existing queries that compare time, and as we are planning to replace + // the indexer in the future, we adapt the code here to handle floats as a special case. + lowerBound := ranges.LowerBoundValue() + upperBound := ranges.UpperBoundValue() + + // *Explanation for the isFloat condition below.* + // In LowerBoundValue(), for floating points, we cannot simply add 1 due to the reasons explained in + // in the comment at the beginning. The same is true for subtracting one for UpperBoundValue(). + // That means that for integers, if the condition is >=, cmp will be either 0 or 1 + // ( cmp == -1 should always be false). + // But if the lowerBound is a float, we have not subtracted one, so returning a 0 + // is correct only if ranges.IncludeLowerBound is true. + // example int: x < 100; upperBound = 99; if x.Cmp(99) == 0 the condition holds + // example float: x < 100.0; upperBound = 100.0; if x.Cmp(100) ==0 then returning x + // would be wrong. + switch vVal := v.(type) { + case *big.Int: + if lowerBound != nil { + cmp, isFloat, err := compareInt(vVal, lowerBound) + if err != nil { + return false, err + } + if cmp == -1 || (isFloat && cmp == 0 && !ranges.IncludeLowerBound) { + return false, err + } + } + if upperBound != nil { + cmp, isFloat, err := compareInt(vVal, upperBound) + if err != nil { + return false, err + } + if cmp == 1 || (isFloat && cmp == 0 && !ranges.IncludeUpperBound) { + return false, err + } + } + + case *big.Float: + if lowerBound != nil { + cmp, isFloat, err := compareFloat(vVal, lowerBound) + if err != nil { + return false, err + } + if cmp == -1 || (cmp == 0 && isFloat && !ranges.IncludeLowerBound) { + return false, err + } + } + if upperBound != nil { + cmp, isFloat, err := compareFloat(vVal, upperBound) + if err != nil { + return false, err + } + if cmp == 1 || (cmp == 0 && isFloat && !ranges.IncludeUpperBound) { + return false, err + } + } + + default: + return false, fmt.Errorf("invalid argument type in query: %T", v) + } + return true, nil +} diff --git a/internal/test/block.go b/internal/test/block.go new file mode 100644 index 0000000..9137918 --- /dev/null +++ b/internal/test/block.go @@ -0,0 +1,92 @@ +package test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +const ( + DefaultTestChainID = "test-chain" +) + +var ( + DefaultTestTime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) +) + +func RandomAddress() []byte { + return crypto.CRandBytes(crypto.AddressSize) +} + +func RandomHash() []byte { + return crypto.CRandBytes(tmhash.Size) +} + +func MakeBlockID() types.BlockID { + return MakeBlockIDWithHash(RandomHash()) +} + +func MakeBlockIDWithHash(hash []byte) types.BlockID { + return types.BlockID{ + Hash: hash, + PartSetHeader: types.PartSetHeader{ + Total: 100, + Hash: RandomHash(), + }, + } +} + +// MakeHeader fills the rest of the contents of the header such that it passes +// validate basic +func MakeHeader(t *testing.T, h *types.Header) *types.Header { + t.Helper() + if h.Version.Block == 0 { + h.Version.Block = version.BlockProtocol + } + if h.Height == 0 { + h.Height = 1 + } + if h.LastBlockID.IsZero() { + h.LastBlockID = MakeBlockID() + } + if h.ChainID == "" { + h.ChainID = DefaultTestChainID + } + if len(h.LastCommitHash) == 0 { + h.LastCommitHash = RandomHash() + } + if len(h.DataHash) == 0 { + h.DataHash = RandomHash() + } + if len(h.ValidatorsHash) == 0 { + h.ValidatorsHash = RandomHash() + } + if len(h.NextValidatorsHash) == 0 { + h.NextValidatorsHash = RandomHash() + } + if len(h.ConsensusHash) == 0 { + h.ConsensusHash = RandomHash() + } + if len(h.AppHash) == 0 { + h.AppHash = RandomHash() + } + if len(h.LastResultsHash) == 0 { + h.LastResultsHash = RandomHash() + } + if len(h.EvidenceHash) == 0 { + h.EvidenceHash = RandomHash() + } + if len(h.ProposerAddress) == 0 { + h.ProposerAddress = RandomAddress() + } + + require.NoError(t, h.ValidateBasic()) + + return h +} diff --git a/internal/test/commit.go b/internal/test/commit.go new file mode 100644 index 0000000..fc7d6fc --- /dev/null +++ b/internal/test/commit.go @@ -0,0 +1,85 @@ +package test + +import ( + "fmt" + "time" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +func MakeCommitFromVoteSet(blockID types.BlockID, voteSet *types.VoteSet, validators []types.PrivValidator, now time.Time) (*types.Commit, error) { + // all sign + for i := 0; i < len(validators); i++ { + pubKey, err := validators[i].GetPubKey() + if err != nil { + return nil, err + } + vote := &types.Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: int32(i), + Height: voteSet.GetHeight(), + Round: voteSet.GetRound(), + Type: cmtproto.PrecommitType, + BlockID: blockID, + Timestamp: now, + } + + v := vote.ToProto() + + if err := validators[i].SignVote(voteSet.ChainID(), v); err != nil { + return nil, err + } + vote.Signature = v.Signature + if _, err := voteSet.AddVote(vote); err != nil { + return nil, err + } + } + + return voteSet.MakeExtendedCommit(types.ABCIParams{VoteExtensionsEnableHeight: 0}).ToCommit(), nil +} + +func MakeCommit(blockID types.BlockID, height int64, round int32, valSet *types.ValidatorSet, privVals []types.PrivValidator, chainID string, now time.Time) (*types.Commit, error) { + sigs := make([]types.CommitSig, len(valSet.Validators)) + for i := 0; i < len(valSet.Validators); i++ { + sigs[i] = types.NewCommitSigAbsent() + } + + for _, privVal := range privVals { + pk, err := privVal.GetPubKey() + if err != nil { + return nil, err + } + addr := pk.Address() + + idx, _ := valSet.GetByAddress(addr) + if idx < 0 { + return nil, fmt.Errorf("validator with address %s not in validator set", addr) + } + + vote := &types.Vote{ + ValidatorAddress: addr, + ValidatorIndex: idx, + Height: height, + Round: round, + Type: cmtproto.PrecommitType, + BlockID: blockID, + Timestamp: now, + } + + v := vote.ToProto() + + if err := privVal.SignVote(chainID, v); err != nil { + return nil, err + } + + sigs[idx] = types.CommitSig{ + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: addr, + Timestamp: now, + Signature: v.Signature, + } + } + + return &types.Commit{Height: height, Round: round, BlockID: blockID, Signatures: sigs}, nil +} diff --git a/internal/test/config.go b/internal/test/config.go new file mode 100644 index 0000000..8b4abb0 --- /dev/null +++ b/internal/test/config.go @@ -0,0 +1,99 @@ +package test + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/cometbft/cometbft/config" + cmtos "github.com/cometbft/cometbft/libs/os" +) + +func ResetTestRoot(testName string) *config.Config { + return ResetTestRootWithChainID(testName, "") +} + +func ResetTestRootWithChainID(testName string, chainID string) *config.Config { + // create a unique, concurrency-safe test directory under os.TempDir() + rootDir, err := os.MkdirTemp("", fmt.Sprintf("%s-%s_", chainID, testName)) + if err != nil { + panic(err) + } + + config.EnsureRoot(rootDir) + + baseConfig := config.DefaultBaseConfig() + genesisFilePath := filepath.Join(rootDir, baseConfig.Genesis) + privKeyFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorKey) + privStateFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorState) + + if !cmtos.FileExists(genesisFilePath) { + if chainID == "" { + chainID = DefaultTestChainID + } + testGenesis := fmt.Sprintf(testGenesisFmt, chainID) + cmtos.MustWriteFile(genesisFilePath, []byte(testGenesis), 0644) + } + // we always overwrite the priv val + cmtos.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0644) + cmtos.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0644) + + config := config.TestConfig().SetRoot(rootDir) + return config +} + +var testGenesisFmt = `{ + "genesis_time": "2018-10-10T08:20:13.695936996Z", + "chain_id": "%s", + "initial_height": "1", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "-1", + "time_iota_ms": "10" + }, + "evidence": { + "max_age_num_blocks": "100000", + "max_age_duration": "172800000000000", + "max_bytes": "1048576" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + }, + "abci": { + "vote_extensions_enable_height": "0" + }, + "version": {} + }, + "validators": [ + { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" + }, + "power": "10", + "name": "" + } + ], + "app_hash": "" +}` + +var testPrivValidatorKey = `{ + "address": "A3258DCBF45DCA0DF052981870F2D1441A36D145", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" + }, + "priv_key": { + "type": "tendermint/PrivKeyEd25519", + "value": "EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ==" + } +}` + +var testPrivValidatorState = `{ + "height": "0", + "round": 0, + "step": 0 +}` diff --git a/internal/test/doc.go b/internal/test/doc.go new file mode 100644 index 0000000..4fec0ff --- /dev/null +++ b/internal/test/doc.go @@ -0,0 +1,6 @@ +/* +Package factory provides generation code for common structs in CometBFT. +It is used primarily for the testing of internal components such as statesync, +consensus, blocksync etc.. +*/ +package test diff --git a/internal/test/factory_test.go b/internal/test/factory_test.go new file mode 100644 index 0000000..852c115 --- /dev/null +++ b/internal/test/factory_test.go @@ -0,0 +1,16 @@ +package test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/types" +) + +func TestMakeHeader(t *testing.T) { + header := MakeHeader(t, &types.Header{}) + require.NotNil(t, header) + + require.NoError(t, header.ValidateBasic()) +} diff --git a/internal/test/genesis.go b/internal/test/genesis.go new file mode 100644 index 0000000..5af1e01 --- /dev/null +++ b/internal/test/genesis.go @@ -0,0 +1,32 @@ +package test + +import ( + "time" + + "github.com/cometbft/cometbft/types" +) + +func GenesisDoc( + time time.Time, + validators []*types.Validator, + consensusParams *types.ConsensusParams, + chainID string, +) *types.GenesisDoc { + + genesisValidators := make([]types.GenesisValidator, len(validators)) + + for i := range validators { + genesisValidators[i] = types.GenesisValidator{ + Power: validators[i].VotingPower, + PubKey: validators[i].PubKey, + } + } + + return &types.GenesisDoc{ + GenesisTime: time, + InitialHeight: 1, + ChainID: chainID, + Validators: genesisValidators, + ConsensusParams: consensusParams, + } +} diff --git a/internal/test/params.go b/internal/test/params.go new file mode 100644 index 0000000..ebfdbc8 --- /dev/null +++ b/internal/test/params.go @@ -0,0 +1,14 @@ +package test + +import ( + "github.com/cometbft/cometbft/types" +) + +// ConsensusParams returns a default set of ConsensusParams that are suitable +// for use in testing +func ConsensusParams() *types.ConsensusParams { + c := types.DefaultConsensusParams() + // enable vote extensions + c.ABCI.VoteExtensionsEnableHeight = 1 + return c +} diff --git a/internal/test/tx.go b/internal/test/tx.go new file mode 100644 index 0000000..36b077f --- /dev/null +++ b/internal/test/tx.go @@ -0,0 +1,11 @@ +package test + +import "github.com/cometbft/cometbft/types" + +func MakeNTxs(height, n int64) types.Txs { + txs := make([]types.Tx, n) + for i := range txs { + txs[i] = types.Tx([]byte{byte(height), byte(i / 256), byte(i % 256)}) + } + return txs +} diff --git a/internal/test/validator.go b/internal/test/validator.go new file mode 100644 index 0000000..e9c46ef --- /dev/null +++ b/internal/test/validator.go @@ -0,0 +1,41 @@ +package test + +import ( + "context" + "sort" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/types" +) + +func Validator(_ context.Context, votingPower int64) (*types.Validator, types.PrivValidator, error) { + privVal := types.NewMockPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + return nil, nil, err + } + + val := types.NewValidator(pubKey, votingPower) + return val, privVal, nil +} + +func ValidatorSet(ctx context.Context, t *testing.T, numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) { + var ( + valz = make([]*types.Validator, numValidators) + privValidators = make([]types.PrivValidator, numValidators) + ) + t.Helper() + + for i := 0; i < numValidators; i++ { + val, privValidator, err := Validator(ctx, votingPower) + require.NoError(t, err) + valz[i] = val + privValidators[i] = privValidator + } + + sort.Sort(types.PrivValidatorsByAddress(privValidators)) + + return types.NewValidatorSet(valz), privValidators +} diff --git a/libs/async/async.go b/libs/async/async.go new file mode 100644 index 0000000..04418af --- /dev/null +++ b/libs/async/async.go @@ -0,0 +1,184 @@ +package async + +import ( + "fmt" + "runtime" + "sync/atomic" +) + +//---------------------------------------- +// Task + +// val: the value returned after task execution. +// err: the error returned during task completion. +// abort: tells Parallel to return, whether or not all tasks have completed. +type Task func(i int) (val interface{}, abort bool, err error) + +type TaskResult struct { + Value interface{} + Error error +} + +type TaskResultCh <-chan TaskResult + +type taskResultOK struct { + TaskResult + OK bool +} + +type TaskResultSet struct { + chz []TaskResultCh + results []taskResultOK +} + +func newTaskResultSet(chz []TaskResultCh) *TaskResultSet { + return &TaskResultSet{ + chz: chz, + results: make([]taskResultOK, len(chz)), + } +} + +func (trs *TaskResultSet) Channels() []TaskResultCh { + return trs.chz +} + +func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool) { + if len(trs.results) <= index { + return TaskResult{}, false + } + resultOK := trs.results[index] + return resultOK.TaskResult, resultOK.OK +} + +// NOTE: Not concurrency safe. +// Writes results to trs.results without waiting for all tasks to complete. +func (trs *TaskResultSet) Reap() *TaskResultSet { + for i := 0; i < len(trs.results); i++ { + var trch = trs.chz[i] + select { + case result, ok := <-trch: + if ok { + // Write result. + trs.results[i] = taskResultOK{ + TaskResult: result, + OK: true, + } + } + // else { + // We already wrote it. + // } + default: + // Do nothing. + } + } + return trs +} + +// NOTE: Not concurrency safe. +// Like Reap() but waits until all tasks have returned or panic'd. +func (trs *TaskResultSet) Wait() *TaskResultSet { + for i := 0; i < len(trs.results); i++ { + var trch = trs.chz[i] + result, ok := <-trch + if ok { + // Write result. + trs.results[i] = taskResultOK{ + TaskResult: result, + OK: true, + } + } + // else { + // We already wrote it. + // } + } + return trs +} + +// Returns the firstmost (by task index) error as +// discovered by all previous Reap() calls. +func (trs *TaskResultSet) FirstValue() interface{} { + for _, result := range trs.results { + if result.Value != nil { + return result.Value + } + } + return nil +} + +// Returns the firstmost (by task index) error as +// discovered by all previous Reap() calls. +func (trs *TaskResultSet) FirstError() error { + for _, result := range trs.results { + if result.Error != nil { + return result.Error + } + } + return nil +} + +//---------------------------------------- +// Parallel + +// Run tasks in parallel, with ability to abort early. +// Returns ok=false iff any of the tasks returned abort=true. +// NOTE: Do not implement quit features here. Instead, provide convenient +// concurrent quit-like primitives, passed implicitly via Task closures. (e.g. +// it's not Parallel's concern how you quit/abort your tasks). +func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { + var taskResultChz = make([]TaskResultCh, len(tasks)) // To return. + var taskDoneCh = make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received. + var numPanics = new(int32) // Keep track of panics to set ok=false later. + + // We will set it to false iff any tasks panic'd or returned abort. + ok = true + + // Start all tasks in parallel in separate goroutines. + // When the task is complete, it will appear in the + // respective taskResultCh (associated by task index). + for i, task := range tasks { + var taskResultCh = make(chan TaskResult, 1) // Capacity for 1 result. + taskResultChz[i] = taskResultCh + go func(i int, task Task, taskResultCh chan TaskResult) { + // Recovery + defer func() { + if pnk := recover(); pnk != nil { + atomic.AddInt32(numPanics, 1) + // Send panic to taskResultCh. + const size = 64 << 10 + buf := make([]byte, size) + buf = buf[:runtime.Stack(buf, false)] + taskResultCh <- TaskResult{nil, fmt.Errorf("panic in task %v : %s", pnk, buf)} + // Closing taskResultCh lets trs.Wait() work. + close(taskResultCh) + // Decrement waitgroup. + taskDoneCh <- false + } + }() + // Run the task. + var val, abort, err = task(i) + // Send val/err to taskResultCh. + // NOTE: Below this line, nothing must panic/ + taskResultCh <- TaskResult{val, err} + // Closing taskResultCh lets trs.Wait() work. + close(taskResultCh) + // Decrement waitgroup. + taskDoneCh <- abort + }(i, task, taskResultCh) + } + + // Wait until all tasks are done, or until abort. + // DONE_LOOP: + for i := 0; i < len(tasks); i++ { + abort := <-taskDoneCh + if abort { + ok = false + break + } + } + + // Ok is also false if there were any panics. + // We must do this check here (after DONE_LOOP). + ok = ok && (atomic.LoadInt32(numPanics) == 0) + + return newTaskResultSet(taskResultChz).Reap(), ok +} diff --git a/libs/async/async_test.go b/libs/async/async_test.go new file mode 100644 index 0000000..6187c50 --- /dev/null +++ b/libs/async/async_test.go @@ -0,0 +1,160 @@ +package async + +import ( + "errors" + "fmt" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestParallel(t *testing.T) { + + // Create tasks. + var counter = new(int32) + var tasks = make([]Task, 100*1000) + for i := 0; i < len(tasks); i++ { + tasks[i] = func(i int) (res interface{}, abort bool, err error) { + atomic.AddInt32(counter, 1) + return -1 * i, false, nil + } + } + + // Run in parallel. + var trs, ok = Parallel(tasks...) + assert.True(t, ok) + + // Verify. + assert.Equal(t, int(*counter), len(tasks), "Each task should have incremented the counter already") + var failedTasks int + for i := 0; i < len(tasks); i++ { + taskResult, ok := trs.LatestResult(i) + switch { + case !ok: + assert.Fail(t, "Task #%v did not complete.", i) + failedTasks++ + case taskResult.Error != nil: + assert.Fail(t, "Task should not have errored but got %v", taskResult.Error) + failedTasks++ + case !assert.Equal(t, -1*i, taskResult.Value.(int)): + assert.Fail(t, "Task should have returned %v but got %v", -1*i, taskResult.Value.(int)) + failedTasks++ + } + // else { + // Good! + // } + } + assert.Equal(t, failedTasks, 0, "No task should have failed") + assert.Nil(t, trs.FirstError(), "There should be no errors") + assert.Equal(t, 0, trs.FirstValue(), "First value should be 0") +} + +func TestParallelAbort(t *testing.T) { + + var flow1 = make(chan struct{}, 1) + var flow2 = make(chan struct{}, 1) + var flow3 = make(chan struct{}, 1) // Cap must be > 0 to prevent blocking. + var flow4 = make(chan struct{}, 1) + + // Create tasks. + var tasks = []Task{ + func(i int) (res interface{}, abort bool, err error) { + assert.Equal(t, i, 0) + flow1 <- struct{}{} + return 0, false, nil + }, + func(i int) (res interface{}, abort bool, err error) { + assert.Equal(t, i, 1) + flow2 <- <-flow1 + return 1, false, errors.New("some error") + }, + func(i int) (res interface{}, abort bool, err error) { + assert.Equal(t, i, 2) + flow3 <- <-flow2 + return 2, true, nil + }, + func(i int) (res interface{}, abort bool, err error) { + assert.Equal(t, i, 3) + <-flow4 + return 3, false, nil + }, + } + + // Run in parallel. + var taskResultSet, ok = Parallel(tasks...) + assert.False(t, ok, "ok should be false since we aborted task #2.") + + // Verify task #3. + // Initially taskResultSet.chz[3] sends nothing since flow4 didn't send. + waitTimeout(t, taskResultSet.chz[3], "Task #3") + + // Now let the last task (#3) complete after abort. + flow4 <- <-flow3 + + // Wait until all tasks have returned or panic'd. + taskResultSet.Wait() + + // Verify task #0, #1, #2. + checkResult(t, taskResultSet, 0, 0, nil, nil) + checkResult(t, taskResultSet, 1, 1, errors.New("some error"), nil) + checkResult(t, taskResultSet, 2, 2, nil, nil) + checkResult(t, taskResultSet, 3, 3, nil, nil) +} + +func TestParallelRecover(t *testing.T) { + + // Create tasks. + var tasks = []Task{ + func(i int) (res interface{}, abort bool, err error) { + return 0, false, nil + }, + func(i int) (res interface{}, abort bool, err error) { + return 1, false, errors.New("some error") + }, + func(i int) (res interface{}, abort bool, err error) { + panic(2) + }, + } + + // Run in parallel. + var taskResultSet, ok = Parallel(tasks...) + assert.False(t, ok, "ok should be false since we panic'd in task #2.") + + // Verify task #0, #1, #2. + checkResult(t, taskResultSet, 0, 0, nil, nil) + checkResult(t, taskResultSet, 1, 1, errors.New("some error"), nil) + checkResult(t, taskResultSet, 2, nil, nil, fmt.Errorf("panic in task %v", 2).Error()) +} + +// Wait for result +func checkResult(t *testing.T, taskResultSet *TaskResultSet, index int, + val interface{}, err error, pnk interface{}) { + taskResult, ok := taskResultSet.LatestResult(index) + taskName := fmt.Sprintf("Task #%v", index) + assert.True(t, ok, "TaskResultCh unexpectedly closed for %v", taskName) + assert.Equal(t, val, taskResult.Value, taskName) + switch { + case err != nil: + assert.Equal(t, err.Error(), taskResult.Error.Error(), taskName) + case pnk != nil: + assert.Contains(t, taskResult.Error.Error(), pnk, taskName) + default: + assert.Nil(t, taskResult.Error, taskName) + } +} + +// Wait for timeout (no result) +func waitTimeout(t *testing.T, taskResultCh TaskResultCh, taskName string) { + select { + case _, ok := <-taskResultCh: + if !ok { + assert.Fail(t, "TaskResultCh unexpectedly closed (%v)", taskName) + } else { + assert.Fail(t, "TaskResultCh unexpectedly returned for %v", taskName) + } + case <-time.After(1 * time.Second): // TODO use deterministic time? + // Good! + } +} diff --git a/libs/autofile/README.md b/libs/autofile/README.md new file mode 100644 index 0000000..a5bc8be --- /dev/null +++ b/libs/autofile/README.md @@ -0,0 +1 @@ +# go-autofile diff --git a/libs/autofile/autofile.go b/libs/autofile/autofile.go new file mode 100644 index 0000000..798d911 --- /dev/null +++ b/libs/autofile/autofile.go @@ -0,0 +1,194 @@ +package autofile + +import ( + "os" + "os/signal" + "path/filepath" + "sync" + "syscall" + "time" + + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +/* AutoFile usage + +// Create/Append to ./autofile_test +af, err := OpenAutoFile("autofile_test") +if err != nil { + panic(err) +} + +// Stream of writes. +// During this time, the file may be moved e.g. by logRotate. +for i := 0; i < 60; i++ { + af.Write([]byte(Fmt("LOOP(%v)", i))) + time.Sleep(time.Second) +} + +// Close the AutoFile +err = af.Close() +if err != nil { + panic(err) +} +*/ + +const ( + autoFileClosePeriod = 1000 * time.Millisecond + autoFilePerms = os.FileMode(0600) +) + +// AutoFile automatically closes and re-opens file for writing. The file is +// automatically setup to close itself every 1s and upon receiving SIGHUP. +// +// This is useful for using a log file with the logrotate tool. +type AutoFile struct { + ID string + Path string + + closeTicker *time.Ticker + closeTickerStopc chan struct{} // closed when closeTicker is stopped + hupc chan os.Signal + + mtx sync.Mutex + file *os.File +} + +// OpenAutoFile creates an AutoFile in the path (with random ID). If there is +// an error, it will be of type *PathError or *ErrPermissionsChanged (if file's +// permissions got changed (should be 0600)). +func OpenAutoFile(path string) (*AutoFile, error) { + var err error + path, err = filepath.Abs(path) + if err != nil { + return nil, err + } + af := &AutoFile{ + ID: cmtrand.Str(12) + ":" + path, + Path: path, + closeTicker: time.NewTicker(autoFileClosePeriod), + closeTickerStopc: make(chan struct{}), + } + if err := af.openFile(); err != nil { + af.Close() + return nil, err + } + + // Close file on SIGHUP. + af.hupc = make(chan os.Signal, 1) + signal.Notify(af.hupc, syscall.SIGHUP) + go func() { + for range af.hupc { + _ = af.closeFile() + } + }() + + go af.closeFileRoutine() + + return af, nil +} + +// Close shuts down the closing goroutine, SIGHUP handler and closes the +// AutoFile. +func (af *AutoFile) Close() error { + af.closeTicker.Stop() + close(af.closeTickerStopc) + if af.hupc != nil { + close(af.hupc) + } + return af.closeFile() +} + +func (af *AutoFile) closeFileRoutine() { + for { + select { + case <-af.closeTicker.C: + _ = af.closeFile() + case <-af.closeTickerStopc: + return + } + } +} + +func (af *AutoFile) closeFile() (err error) { + af.mtx.Lock() + defer af.mtx.Unlock() + + file := af.file + if file == nil { + return nil + } + + af.file = nil + return file.Close() +} + +// Write writes len(b) bytes to the AutoFile. It returns the number of bytes +// written and an error, if any. Write returns a non-nil error when n != +// len(b). +// Opens AutoFile if needed. +func (af *AutoFile) Write(b []byte) (n int, err error) { + af.mtx.Lock() + defer af.mtx.Unlock() + + if af.file == nil { + if err = af.openFile(); err != nil { + return + } + } + + n, err = af.file.Write(b) + return +} + +// Sync commits the current contents of the file to stable storage. Typically, +// this means flushing the file system's in-memory copy of recently written +// data to disk. +// Opens AutoFile if needed. +func (af *AutoFile) Sync() error { + af.mtx.Lock() + defer af.mtx.Unlock() + + if af.file == nil { + if err := af.openFile(); err != nil { + return err + } + } + return af.file.Sync() +} + +func (af *AutoFile) openFile() error { + file, err := os.OpenFile(af.Path, os.O_RDWR|os.O_CREATE|os.O_APPEND, autoFilePerms) + if err != nil { + return err + } + // fileInfo, err := file.Stat() + // if err != nil { + // return err + // } + // if fileInfo.Mode() != autoFilePerms { + // return errors.NewErrPermissionsChanged(file.Name(), fileInfo.Mode(), autoFilePerms) + // } + af.file = file + return nil +} + +// Size returns the size of the AutoFile. It returns -1 and an error if fails +// get stats or open file. +// Opens AutoFile if needed. +func (af *AutoFile) Size() (int64, error) { + af.mtx.Lock() + defer af.mtx.Unlock() + + if af.file == nil { + if err := af.openFile(); err != nil { + return -1, err + } + } + + stat, err := af.file.Stat() + if err != nil { + return -1, err + } + return stat.Size(), nil +} diff --git a/libs/autofile/autofile_test.go b/libs/autofile/autofile_test.go new file mode 100644 index 0000000..7588250 --- /dev/null +++ b/libs/autofile/autofile_test.go @@ -0,0 +1,148 @@ +package autofile + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtos "github.com/cometbft/cometbft/libs/os" +) + +func TestSIGHUP(t *testing.T) { + origDir, err := os.Getwd() + require.NoError(t, err) + t.Cleanup(func() { + if err := os.Chdir(origDir); err != nil { + t.Error(err) + } + }) + + // First, create a temporary directory and move into it + dir, err := os.MkdirTemp("", "sighup_test") + require.NoError(t, err) + t.Cleanup(func() { + os.RemoveAll(dir) + }) + err = os.Chdir(dir) + require.NoError(t, err) + + // Create an AutoFile in the temporary directory + name := "sighup_test" + af, err := OpenAutoFile(name) + require.NoError(t, err) + require.True(t, filepath.IsAbs(af.Path)) + + // Write to the file. + _, err = af.Write([]byte("Line 1\n")) + require.NoError(t, err) + _, err = af.Write([]byte("Line 2\n")) + require.NoError(t, err) + + // Move the file over + err = os.Rename(name, name+"_old") + require.NoError(t, err) + + // Move into a different temporary directory + otherDir, err := os.MkdirTemp("", "sighup_test_other") + require.NoError(t, err) + defer os.RemoveAll(otherDir) + err = os.Chdir(otherDir) + require.NoError(t, err) + + // Send SIGHUP to self. + err = syscall.Kill(syscall.Getpid(), syscall.SIGHUP) + require.NoError(t, err) + + // Wait a bit... signals are not handled synchronously. + time.Sleep(time.Millisecond * 10) + + // Write more to the file. + _, err = af.Write([]byte("Line 3\n")) + require.NoError(t, err) + _, err = af.Write([]byte("Line 4\n")) + require.NoError(t, err) + err = af.Close() + require.NoError(t, err) + + // Both files should exist + if body := cmtos.MustReadFile(filepath.Join(dir, name+"_old")); string(body) != "Line 1\nLine 2\n" { + t.Errorf("unexpected body %s", body) + } + if body := cmtos.MustReadFile(filepath.Join(dir, name)); string(body) != "Line 3\nLine 4\n" { + t.Errorf("unexpected body %s", body) + } + + // The current directory should be empty + files, err := os.ReadDir(".") + require.NoError(t, err) + assert.Empty(t, files) +} + +// // Manually modify file permissions, close, and reopen using autofile: +// // We expect the file permissions to be changed back to the intended perms. +// func TestOpenAutoFilePerms(t *testing.T) { +// file, err := os.CreateTemp("", "permission_test") +// require.NoError(t, err) +// err = file.Close() +// require.NoError(t, err) +// name := file.Name() + +// // open and change permissions +// af, err := OpenAutoFile(name) +// require.NoError(t, err) +// err = af.file.Chmod(0755) +// require.NoError(t, err) +// err = af.Close() +// require.NoError(t, err) + +// // reopen and expect an ErrPermissionsChanged as Cause +// af, err = OpenAutoFile(name) +// require.Error(t, err) +// if e, ok := err.(*errors.ErrPermissionsChanged); ok { +// t.Logf("%v", e) +// } else { +// t.Errorf("unexpected error %v", e) +// } +// } + +func TestAutoFileSize(t *testing.T) { + // First, create an AutoFile writing to a tempfile dir + f, err := os.CreateTemp("", "sighup_test") + require.NoError(t, err) + err = f.Close() + require.NoError(t, err) + + // Here is the actual AutoFile. + af, err := OpenAutoFile(f.Name()) + require.NoError(t, err) + + // 1. Empty file + size, err := af.Size() + require.Zero(t, size) + require.NoError(t, err) + + // 2. Not empty file + data := []byte("Maniac\n") + _, err = af.Write(data) + require.NoError(t, err) + size, err = af.Size() + require.EqualValues(t, len(data), size) + require.NoError(t, err) + + // 3. Not existing file + err = af.Close() + require.NoError(t, err) + err = os.Remove(f.Name()) + require.NoError(t, err) + size, err = af.Size() + require.EqualValues(t, 0, size, "Expected a new file to be empty") + require.NoError(t, err) + + // Cleanup + _ = os.Remove(f.Name()) +} diff --git a/libs/autofile/cmd/logjack.go b/libs/autofile/cmd/logjack.go new file mode 100644 index 0000000..e58e129 --- /dev/null +++ b/libs/autofile/cmd/logjack.go @@ -0,0 +1,126 @@ +package main + +import ( + "flag" + "fmt" + "io" + "os" + "strconv" + "strings" + + auto "github.com/cometbft/cometbft/libs/autofile" + cmtos "github.com/cometbft/cometbft/libs/os" +) + +const ( + Version = "0.0.1" + readBufferSize = 1024 // 1KB at a time +) + +// Parse command-line options +func parseFlags() (headPath string, chopSize int64, limitSize int64, version bool) { + flagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError) + var chopSizeStr, limitSizeStr string + flagSet.StringVar(&headPath, "head", "logjack.out", "Destination (head) file.") + flagSet.StringVar(&chopSizeStr, "chop", "100M", "Move file if greater than this") + flagSet.StringVar(&limitSizeStr, "limit", "10G", "Only keep this much (for each specified file). Remove old files.") + flagSet.BoolVar(&version, "version", false, "Version") + if err := flagSet.Parse(os.Args[1:]); err != nil { + fmt.Printf("err parsing flag: %v\n", err) + os.Exit(1) + } + chopSize = parseBytesize(chopSizeStr) + limitSize = parseBytesize(limitSizeStr) + return +} + +type fmtLogger struct{} + +func (fmtLogger) Info(msg string, keyvals ...interface{}) { + strs := make([]string, len(keyvals)) + for i, kv := range keyvals { + strs[i] = fmt.Sprintf("%v", kv) + } + fmt.Printf("%s %s\n", msg, strings.Join(strs, ",")) +} + +func main() { + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(fmtLogger{}, func() { + fmt.Println("logjack shutting down") + }) + + // Read options + headPath, chopSize, limitSize, version := parseFlags() + if version { + fmt.Printf("logjack version %v\n", Version) + return + } + + // Open Group + group, err := auto.OpenGroup(headPath, auto.GroupHeadSizeLimit(chopSize), auto.GroupTotalSizeLimit(limitSize)) + if err != nil { + fmt.Printf("logjack couldn't create output file %v\n", headPath) + os.Exit(1) + } + + if err = group.Start(); err != nil { + fmt.Printf("logjack couldn't start with file %v\n", headPath) + os.Exit(1) + } + + // Forever read from stdin and write to AutoFile. + buf := make([]byte, readBufferSize) + for { + n, err := os.Stdin.Read(buf) + if err != nil { + if err := group.Stop(); err != nil { + fmt.Fprintf(os.Stderr, "logjack stopped with error %v\n", headPath) + os.Exit(1) + } + if err == io.EOF { + os.Exit(0) + } + fmt.Println("logjack errored") + os.Exit(1) + } + _, err = group.Write(buf[:n]) + if err != nil { + fmt.Fprintf(os.Stderr, "logjack failed write with error %v\n", headPath) + os.Exit(1) + } + if err := group.FlushAndSync(); err != nil { + fmt.Fprintf(os.Stderr, "logjack flushsync fail with error %v\n", headPath) + os.Exit(1) + } + } +} + +func parseBytesize(chopSize string) int64 { + // Handle suffix multiplier + var multiplier int64 = 1 + if strings.HasSuffix(chopSize, "T") { + multiplier = 1042 * 1024 * 1024 * 1024 + chopSize = chopSize[:len(chopSize)-1] + } + if strings.HasSuffix(chopSize, "G") { + multiplier = 1042 * 1024 * 1024 + chopSize = chopSize[:len(chopSize)-1] + } + if strings.HasSuffix(chopSize, "M") { + multiplier = 1042 * 1024 + chopSize = chopSize[:len(chopSize)-1] + } + if strings.HasSuffix(chopSize, "K") { + multiplier = 1042 + chopSize = chopSize[:len(chopSize)-1] + } + + // Parse the numeric part + chopSizeInt, err := strconv.Atoi(chopSize) + if err != nil { + panic(err) + } + + return int64(chopSizeInt) * multiplier +} diff --git a/libs/autofile/group.go b/libs/autofile/group.go new file mode 100644 index 0000000..f1240a5 --- /dev/null +++ b/libs/autofile/group.go @@ -0,0 +1,540 @@ +package autofile + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/cometbft/cometbft/libs/service" +) + +const ( + defaultGroupCheckDuration = 5000 * time.Millisecond + defaultHeadSizeLimit = 10 * 1024 * 1024 // 10MB + defaultTotalSizeLimit = 1 * 1024 * 1024 * 1024 // 1GB + maxFilesToRemove = 4 // needs to be greater than 1 +) + +/* +You can open a Group to keep restrictions on an AutoFile, like +the maximum size of each chunk, and/or the total amount of bytes +stored in the group. + +The first file to be written in the Group.Dir is the head file. + + Dir/ + - + +Once the Head file reaches the size limit, it will be rotated. + + Dir/ + - .000 // First rolled file + - // New head path, starts empty. + // The implicit index is 001. + +As more files are written, the index numbers grow... + + Dir/ + - .000 // First rolled file + - .001 // Second rolled file + - ... + - // New head path + +The Group can also be used to binary-search for some line, +assuming that marker lines are written occasionally. +*/ +type Group struct { + service.BaseService + + ID string + Head *AutoFile // The head AutoFile to write to + headBuf *bufio.Writer + Dir string // Directory that contains .Head + ticker *time.Ticker + mtx sync.Mutex + headSizeLimit int64 + totalSizeLimit int64 + groupCheckDuration time.Duration + minIndex int // Includes head + maxIndex int // Includes head, where Head will move to + + // close this when the processTicks routine is done. + // this ensures we can cleanup the dir after calling Stop + // and the routine won't be trying to access it anymore + doneProcessTicks chan struct{} + + // TODO: When we start deleting files, we need to start tracking GroupReaders + // and their dependencies. +} + +// OpenGroup creates a new Group with head at headPath. It returns an error if +// it fails to open head file. +func OpenGroup(headPath string, groupOptions ...func(*Group)) (*Group, error) { + dir, err := filepath.Abs(filepath.Dir(headPath)) + if err != nil { + return nil, err + } + head, err := OpenAutoFile(headPath) + if err != nil { + return nil, err + } + + g := &Group{ + ID: "group:" + head.ID, + Head: head, + headBuf: bufio.NewWriterSize(head, 4096*10), + Dir: dir, + headSizeLimit: defaultHeadSizeLimit, + totalSizeLimit: defaultTotalSizeLimit, + groupCheckDuration: defaultGroupCheckDuration, + minIndex: 0, + maxIndex: 0, + doneProcessTicks: make(chan struct{}), + } + + for _, option := range groupOptions { + option(g) + } + + g.BaseService = *service.NewBaseService(nil, "Group", g) + + gInfo := g.readGroupInfo() + g.minIndex = gInfo.MinIndex + g.maxIndex = gInfo.MaxIndex + return g, nil +} + +// GroupCheckDuration allows you to overwrite default groupCheckDuration. +func GroupCheckDuration(duration time.Duration) func(*Group) { + return func(g *Group) { + g.groupCheckDuration = duration + } +} + +// GroupHeadSizeLimit allows you to overwrite default head size limit - 10MB. +func GroupHeadSizeLimit(limit int64) func(*Group) { + return func(g *Group) { + g.headSizeLimit = limit + } +} + +// GroupTotalSizeLimit allows you to overwrite default total size limit of the group - 1GB. +func GroupTotalSizeLimit(limit int64) func(*Group) { + return func(g *Group) { + g.totalSizeLimit = limit + } +} + +// OnStart implements service.Service by starting the goroutine that checks file +// and group limits. +func (g *Group) OnStart() error { + g.ticker = time.NewTicker(g.groupCheckDuration) + go g.processTicks() + return nil +} + +// OnStop implements service.Service by stopping the goroutine described above. +// NOTE: g.Head must be closed separately using Close. +func (g *Group) OnStop() { + g.ticker.Stop() + if err := g.FlushAndSync(); err != nil { + g.Logger.Error("Error flushin to disk", "err", err) + } +} + +// Wait blocks until all internal goroutines are finished. Supposed to be +// called after Stop. +func (g *Group) Wait() { + // wait for processTicks routine to finish + <-g.doneProcessTicks +} + +// Close closes the head file. The group must be stopped by this moment. +func (g *Group) Close() { + if err := g.FlushAndSync(); err != nil { + g.Logger.Error("Error flushin to disk", "err", err) + } + + g.mtx.Lock() + _ = g.Head.closeFile() + g.mtx.Unlock() +} + +// HeadSizeLimit returns the current head size limit. +func (g *Group) HeadSizeLimit() int64 { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.headSizeLimit +} + +// TotalSizeLimit returns total size limit of the group. +func (g *Group) TotalSizeLimit() int64 { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.totalSizeLimit +} + +// MaxIndex returns index of the last file in the group. +func (g *Group) MaxIndex() int { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.maxIndex +} + +// MinIndex returns index of the first file in the group. +func (g *Group) MinIndex() int { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.minIndex +} + +// Write writes the contents of p into the current head of the group. It +// returns the number of bytes written. If nn < len(p), it also returns an +// error explaining why the write is short. +// NOTE: Writes are buffered so they don't write synchronously +// TODO: Make it halt if space is unavailable +func (g *Group) Write(p []byte) (nn int, err error) { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.headBuf.Write(p) +} + +// WriteLine writes line into the current head of the group. It also appends "\n". +// NOTE: Writes are buffered so they don't write synchronously +// TODO: Make it halt if space is unavailable +func (g *Group) WriteLine(line string) error { + g.mtx.Lock() + defer g.mtx.Unlock() + _, err := g.headBuf.Write([]byte(line + "\n")) + return err +} + +// Buffered returns the size of the currently buffered data. +func (g *Group) Buffered() int { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.headBuf.Buffered() +} + +// FlushAndSync writes any buffered data to the underlying file and commits the +// current content of the file to stable storage (fsync). +func (g *Group) FlushAndSync() error { + g.mtx.Lock() + defer g.mtx.Unlock() + err := g.headBuf.Flush() + if err == nil { + err = g.Head.Sync() + } + return err +} + +func (g *Group) processTicks() { + defer close(g.doneProcessTicks) + for { + select { + case <-g.ticker.C: + g.checkHeadSizeLimit() + g.checkTotalSizeLimit() + case <-g.Quit(): + return + } + } +} + +// NOTE: this function is called manually in tests. +func (g *Group) checkHeadSizeLimit() { + limit := g.HeadSizeLimit() + if limit == 0 { + return + } + size, err := g.Head.Size() + if err != nil { + g.Logger.Error("Group's head may grow without bound", "head", g.Head.Path, "err", err) + return + } + if size >= limit { + g.RotateFile() + } +} + +func (g *Group) checkTotalSizeLimit() { + limit := g.TotalSizeLimit() + if limit == 0 { + return + } + + gInfo := g.readGroupInfo() + totalSize := gInfo.TotalSize + for i := 0; i < maxFilesToRemove; i++ { + index := gInfo.MinIndex + i + if totalSize < limit { + return + } + if index == gInfo.MaxIndex { + // Special degenerate case, just do nothing. + g.Logger.Error("Group's head may grow without bound", "head", g.Head.Path) + return + } + pathToRemove := filePathForIndex(g.Head.Path, index, gInfo.MaxIndex) + fInfo, err := os.Stat(pathToRemove) + if err != nil { + g.Logger.Error("Failed to fetch info for file", "file", pathToRemove) + continue + } + err = os.Remove(pathToRemove) + if err != nil { + g.Logger.Error("Failed to remove path", "path", pathToRemove) + return + } + totalSize -= fInfo.Size() + } +} + +// RotateFile causes group to close the current head and assign it some index. +// Note it does not create a new head. +func (g *Group) RotateFile() { + g.mtx.Lock() + defer g.mtx.Unlock() + + headPath := g.Head.Path + + if err := g.headBuf.Flush(); err != nil { + panic(err) + } + + if err := g.Head.Sync(); err != nil { + panic(err) + } + + if err := g.Head.closeFile(); err != nil { + panic(err) + } + + indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1) + if err := os.Rename(headPath, indexPath); err != nil { + panic(err) + } + + g.maxIndex++ +} + +// NewReader returns a new group reader. +// CONTRACT: Caller must close the returned GroupReader. +func (g *Group) NewReader(index int) (*GroupReader, error) { + r := newGroupReader(g) + err := r.SetIndex(index) + if err != nil { + return nil, err + } + return r, nil +} + +// GroupInfo holds information about the group. +type GroupInfo struct { + MinIndex int // index of the first file in the group, including head + MaxIndex int // index of the last file in the group, including head + TotalSize int64 // total size of the group + HeadSize int64 // size of the head +} + +// Returns info after scanning all files in g.Head's dir. +func (g *Group) ReadGroupInfo() GroupInfo { + g.mtx.Lock() + defer g.mtx.Unlock() + return g.readGroupInfo() +} + +// Index includes the head. +// CONTRACT: caller should have called g.mtx.Lock +func (g *Group) readGroupInfo() GroupInfo { + groupDir := filepath.Dir(g.Head.Path) + headBase := filepath.Base(g.Head.Path) + var minIndex, maxIndex = -1, -1 + var totalSize, headSize int64 = 0, 0 + + dir, err := os.Open(groupDir) + if err != nil { + panic(err) + } + defer dir.Close() + fiz, err := dir.Readdir(0) + if err != nil { + panic(err) + } + + // For each file in the directory, filter by pattern + for _, fileInfo := range fiz { + if fileInfo.Name() == headBase { + fileSize := fileInfo.Size() + totalSize += fileSize + headSize = fileSize + continue + } else if strings.HasPrefix(fileInfo.Name(), headBase) { + fileSize := fileInfo.Size() + totalSize += fileSize + indexedFilePattern := regexp.MustCompile(`^.+\.([0-9]{3,})$`) + submatch := indexedFilePattern.FindSubmatch([]byte(fileInfo.Name())) + if len(submatch) != 0 { + // Matches + fileIndex, err := strconv.Atoi(string(submatch[1])) + if err != nil { + panic(err) + } + if maxIndex < fileIndex { + maxIndex = fileIndex + } + if minIndex == -1 || fileIndex < minIndex { + minIndex = fileIndex + } + } + } + } + + // Now account for the head. + if minIndex == -1 { + // If there were no numbered files, + // then the head is index 0. + minIndex, maxIndex = 0, 0 + } else { + // Otherwise, the head file is 1 greater + maxIndex++ + } + return GroupInfo{minIndex, maxIndex, totalSize, headSize} +} + +func filePathForIndex(headPath string, index int, maxIndex int) string { + if index == maxIndex { + return headPath + } + return fmt.Sprintf("%v.%03d", headPath, index) +} + +//-------------------------------------------------------------------------------- + +// GroupReader provides an interface for reading from a Group. +type GroupReader struct { + *Group + mtx sync.Mutex + curIndex int + curFile *os.File + curReader *bufio.Reader + curLine []byte +} + +func newGroupReader(g *Group) *GroupReader { + return &GroupReader{ + Group: g, + curIndex: 0, + curFile: nil, + curReader: nil, + curLine: nil, + } +} + +// Close closes the GroupReader by closing the cursor file. +func (gr *GroupReader) Close() error { + gr.mtx.Lock() + defer gr.mtx.Unlock() + + if gr.curReader != nil { + err := gr.curFile.Close() + gr.curIndex = 0 + gr.curReader = nil + gr.curFile = nil + gr.curLine = nil + return err + } + return nil +} + +// Read implements io.Reader, reading bytes from the current Reader +// incrementing index until enough bytes are read. +func (gr *GroupReader) Read(p []byte) (n int, err error) { + lenP := len(p) + if lenP == 0 { + return 0, errors.New("given empty slice") + } + + gr.mtx.Lock() + defer gr.mtx.Unlock() + + // Open file if not open yet + if gr.curReader == nil { + if err = gr.openFile(gr.curIndex); err != nil { + return 0, err + } + } + + // Iterate over files until enough bytes are read + var nn int + for { + nn, err = gr.curReader.Read(p[n:]) + n += nn + switch { + case err == io.EOF: + if n >= lenP { + return n, nil + } + // Open the next file + if err1 := gr.openFile(gr.curIndex + 1); err1 != nil { + return n, err1 + } + case err != nil: + return n, err + case nn == 0: // empty file + return n, err + } + } +} + +// IF index > gr.Group.maxIndex, returns io.EOF +// CONTRACT: caller should hold gr.mtx +func (gr *GroupReader) openFile(index int) error { + // Lock on Group to ensure that head doesn't move in the meanwhile. + gr.Group.mtx.Lock() + defer gr.Group.mtx.Unlock() + + if index > gr.maxIndex { + return io.EOF + } + + curFilePath := filePathForIndex(gr.Head.Path, index, gr.maxIndex) + curFile, err := os.OpenFile(curFilePath, os.O_RDONLY|os.O_CREATE, autoFilePerms) + if err != nil { + return err + } + curReader := bufio.NewReader(curFile) + + // Update gr.cur* + if gr.curFile != nil { + gr.curFile.Close() // TODO return error? + } + gr.curIndex = index + gr.curFile = curFile + gr.curReader = curReader + gr.curLine = nil + return nil +} + +// CurIndex returns cursor's file index. +func (gr *GroupReader) CurIndex() int { + gr.mtx.Lock() + defer gr.mtx.Unlock() + return gr.curIndex +} + +// SetIndex sets the cursor's file index to index by opening a file at this +// position. +func (gr *GroupReader) SetIndex(index int) error { + gr.mtx.Lock() + defer gr.mtx.Unlock() + return gr.openFile(index) +} diff --git a/libs/autofile/group_test.go b/libs/autofile/group_test.go new file mode 100644 index 0000000..1d72f02 --- /dev/null +++ b/libs/autofile/group_test.go @@ -0,0 +1,290 @@ +package autofile + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtos "github.com/cometbft/cometbft/libs/os" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func createTestGroupWithHeadSizeLimit(t *testing.T, headSizeLimit int64) *Group { + testID := cmtrand.Str(12) + testDir := "_test_" + testID + err := cmtos.EnsureDir(testDir, 0700) + require.NoError(t, err, "Error creating dir") + + headPath := testDir + "/myfile" + g, err := OpenGroup(headPath, GroupHeadSizeLimit(headSizeLimit)) + require.NoError(t, err, "Error opening Group") + require.NotEqual(t, nil, g, "Failed to create Group") + + return g +} + +func destroyTestGroup(t *testing.T, g *Group) { + g.Close() + + err := os.RemoveAll(g.Dir) + require.NoError(t, err, "Error removing test Group directory") +} + +func assertGroupInfo(t *testing.T, gInfo GroupInfo, minIndex, maxIndex int, totalSize, headSize int64) { + assert.Equal(t, minIndex, gInfo.MinIndex) + assert.Equal(t, maxIndex, gInfo.MaxIndex) + assert.Equal(t, totalSize, gInfo.TotalSize) + assert.Equal(t, headSize, gInfo.HeadSize) +} + +func TestCheckHeadSizeLimit(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 1000*1000) + + // At first, there are no files. + assertGroupInfo(t, g.ReadGroupInfo(), 0, 0, 0, 0) + + // Write 1000 bytes 999 times. + for i := 0; i < 999; i++ { + err := g.WriteLine(cmtrand.Str(999)) + require.NoError(t, err, "Error appending to head") + } + err := g.FlushAndSync() + require.NoError(t, err) + assertGroupInfo(t, g.ReadGroupInfo(), 0, 0, 999000, 999000) + + // Even calling checkHeadSizeLimit manually won't rotate it. + g.checkHeadSizeLimit() + assertGroupInfo(t, g.ReadGroupInfo(), 0, 0, 999000, 999000) + + // Write 1000 more bytes. + err = g.WriteLine(cmtrand.Str(999)) + require.NoError(t, err, "Error appending to head") + err = g.FlushAndSync() + require.NoError(t, err) + + // Calling checkHeadSizeLimit this time rolls it. + g.checkHeadSizeLimit() + assertGroupInfo(t, g.ReadGroupInfo(), 0, 1, 1000000, 0) + + // Write 1000 more bytes. + err = g.WriteLine(cmtrand.Str(999)) + require.NoError(t, err, "Error appending to head") + err = g.FlushAndSync() + require.NoError(t, err) + + // Calling checkHeadSizeLimit does nothing. + g.checkHeadSizeLimit() + assertGroupInfo(t, g.ReadGroupInfo(), 0, 1, 1001000, 1000) + + // Write 1000 bytes 999 times. + for i := 0; i < 999; i++ { + err = g.WriteLine(cmtrand.Str(999)) + require.NoError(t, err, "Error appending to head") + } + err = g.FlushAndSync() + require.NoError(t, err) + assertGroupInfo(t, g.ReadGroupInfo(), 0, 1, 2000000, 1000000) + + // Calling checkHeadSizeLimit rolls it again. + g.checkHeadSizeLimit() + assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2000000, 0) + + // Write 1000 more bytes. + _, err = g.Head.Write([]byte(cmtrand.Str(999) + "\n")) + require.NoError(t, err, "Error appending to head") + err = g.FlushAndSync() + require.NoError(t, err) + assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2001000, 1000) + + // Calling checkHeadSizeLimit does nothing. + g.checkHeadSizeLimit() + assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2001000, 1000) + + // Cleanup + destroyTestGroup(t, g) +} + +func TestRotateFile(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + // Create a different temporary directory and move into it, to make sure + // relative paths are resolved at Group creation + origDir, err := os.Getwd() + require.NoError(t, err) + defer func() { + if err := os.Chdir(origDir); err != nil { + t.Error(err) + } + }() + + dir, err := os.MkdirTemp("", "rotate_test") + require.NoError(t, err) + defer os.RemoveAll(dir) + err = os.Chdir(dir) + require.NoError(t, err) + + require.True(t, filepath.IsAbs(g.Head.Path)) + require.True(t, filepath.IsAbs(g.Dir)) + + // Create and rotate files + err = g.WriteLine("Line 1") + require.NoError(t, err) + err = g.WriteLine("Line 2") + require.NoError(t, err) + err = g.WriteLine("Line 3") + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + g.RotateFile() + err = g.WriteLine("Line 4") + require.NoError(t, err) + err = g.WriteLine("Line 5") + require.NoError(t, err) + err = g.WriteLine("Line 6") + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + + // Read g.Head.Path+"000" + body1, err := os.ReadFile(g.Head.Path + ".000") + assert.NoError(t, err, "Failed to read first rolled file") + if string(body1) != "Line 1\nLine 2\nLine 3\n" { + t.Errorf("got unexpected contents: [%v]", string(body1)) + } + + // Read g.Head.Path + body2, err := os.ReadFile(g.Head.Path) + assert.NoError(t, err, "Failed to read first rolled file") + if string(body2) != "Line 4\nLine 5\nLine 6\n" { + t.Errorf("got unexpected contents: [%v]", string(body2)) + } + + // Make sure there are no files in the current, temporary directory + files, err := os.ReadDir(".") + require.NoError(t, err) + assert.Empty(t, files) + + // Cleanup + destroyTestGroup(t, g) +} + +func TestWrite(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + written := []byte("Medusa") + _, err := g.Write(written) + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + + read := make([]byte, len(written)) + gr, err := g.NewReader(0) + require.NoError(t, err, "failed to create reader") + + _, err = gr.Read(read) + assert.NoError(t, err, "failed to read data") + assert.Equal(t, written, read) + + // Cleanup + destroyTestGroup(t, g) +} + +// test that Read reads the required amount of bytes from all the files in the +// group and returns no error if n == size of the given slice. +func TestGroupReaderRead(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + professor := []byte("Professor Monster") + _, err := g.Write(professor) + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + g.RotateFile() + frankenstein := []byte("Frankenstein's Monster") + _, err = g.Write(frankenstein) + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + + totalWrittenLength := len(professor) + len(frankenstein) + read := make([]byte, totalWrittenLength) + gr, err := g.NewReader(0) + require.NoError(t, err, "failed to create reader") + + n, err := gr.Read(read) + assert.NoError(t, err, "failed to read data") + assert.Equal(t, totalWrittenLength, n, "not enough bytes read") + professorPlusFrankenstein := professor + professorPlusFrankenstein = append(professorPlusFrankenstein, frankenstein...) + assert.Equal(t, professorPlusFrankenstein, read) + + // Cleanup + destroyTestGroup(t, g) +} + +// test that Read returns an error if number of bytes read < size of +// the given slice. Subsequent call should return 0, io.EOF. +func TestGroupReaderRead2(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + professor := []byte("Professor Monster") + _, err := g.Write(professor) + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + g.RotateFile() + frankenstein := []byte("Frankenstein's Monster") + frankensteinPart := []byte("Frankenstein") + _, err = g.Write(frankensteinPart) // note writing only a part + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + + totalLength := len(professor) + len(frankenstein) + read := make([]byte, totalLength) + gr, err := g.NewReader(0) + require.NoError(t, err, "failed to create reader") + + // 1) n < (size of the given slice), io.EOF + n, err := gr.Read(read) + assert.Equal(t, io.EOF, err) + assert.Equal(t, len(professor)+len(frankensteinPart), n, "Read more/less bytes than it is in the group") + + // 2) 0, io.EOF + n, err = gr.Read([]byte("0")) + assert.Equal(t, io.EOF, err) + assert.Equal(t, 0, n) + + // Cleanup + destroyTestGroup(t, g) +} + +func TestMinIndex(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + assert.Zero(t, g.MinIndex(), "MinIndex should be zero at the beginning") + + // Cleanup + destroyTestGroup(t, g) +} + +func TestMaxIndex(t *testing.T) { + g := createTestGroupWithHeadSizeLimit(t, 0) + + assert.Zero(t, g.MaxIndex(), "MaxIndex should be zero at the beginning") + + err := g.WriteLine("Line 1") + require.NoError(t, err) + err = g.FlushAndSync() + require.NoError(t, err) + g.RotateFile() + + assert.Equal(t, 1, g.MaxIndex(), "MaxIndex should point to the last file") + + // Cleanup + destroyTestGroup(t, g) +} diff --git a/libs/bits/bit_array.go b/libs/bits/bit_array.go new file mode 100644 index 0000000..a9f6169 --- /dev/null +++ b/libs/bits/bit_array.go @@ -0,0 +1,521 @@ +package bits + +import ( + "encoding/binary" + "fmt" + "math/bits" + "regexp" + "strings" + "sync" + + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtprotobits "github.com/cometbft/cometbft/proto/tendermint/libs/bits" +) + +// BitArray is a thread-safe implementation of a bit array. +type BitArray struct { + mtx sync.Mutex + Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported + Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported +} + +// NewBitArray returns a new bit array. +// It returns nil if the number of bits is zero. +func NewBitArray(bits int) *BitArray { + if bits <= 0 { + return nil + } + return &BitArray{ + Bits: bits, + Elems: make([]uint64, numElements(bits)), + } +} + +// NewBitArrayFromFn returns a new bit array. +// It returns nil if the number of bits is zero. +// It initializes the `i`th bit to the value of `fn(i)`. +func NewBitArrayFromFn(bits int, fn func(int) bool) *BitArray { + if bits <= 0 { + return nil + } + bA := &BitArray{ + Bits: bits, + Elems: make([]uint64, numElements(bits)), + } + for i := 0; i < bits; i++ { + v := fn(i) + if v { + bA.Elems[i/64] |= (uint64(1) << uint(i%64)) + } + } + return bA +} + +// Size returns the number of bits in the bitarray. +func (bA *BitArray) Size() int { + if bA == nil { + return 0 + } + return bA.Bits +} + +// GetIndex returns the bit at index i within the bit array. +// The behavior is undefined if i >= bA.Bits +func (bA *BitArray) GetIndex(i int) bool { + if bA == nil { + return false + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + return bA.getIndex(i) +} + +func (bA *BitArray) getIndex(i int) bool { + if i >= bA.Bits { + return false + } + return bA.Elems[i/64]&(uint64(1)< 0 +} + +// SetIndex sets the bit at index i within the bit array. +// The behavior is undefined if i >= bA.Bits +func (bA *BitArray) SetIndex(i int, v bool) bool { + if bA == nil { + return false + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + return bA.setIndex(i, v) +} + +func (bA *BitArray) setIndex(i int, v bool) bool { + if i >= bA.Bits || i/64 >= len(bA.Elems) { + return false + } + if v { + bA.Elems[i/64] |= (uint64(1) << uint(i%64)) + } else { + bA.Elems[i/64] &= ^(uint64(1) << uint(i%64)) + } + return true +} + +// Copy returns a copy of the provided bit array. +func (bA *BitArray) Copy() *BitArray { + if bA == nil { + return nil + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + return bA.copy() +} + +func (bA *BitArray) copy() *BitArray { + c := make([]uint64, len(bA.Elems)) + copy(c, bA.Elems) + return &BitArray{ + Bits: bA.Bits, + Elems: c, + } +} + +func (bA *BitArray) copyBits(bits int) *BitArray { + c := make([]uint64, numElements(bits)) + copy(c, bA.Elems) + return &BitArray{ + Bits: bits, + Elems: c, + } +} + +// Or returns a bit array resulting from a bitwise OR of the two bit arrays. +// If the two bit-arrys have different lengths, Or right-pads the smaller of the two bit-arrays with zeroes. +// Thus the size of the return value is the maximum of the two provided bit arrays. +func (bA *BitArray) Or(o *BitArray) *BitArray { + if bA == nil && o == nil { + return nil + } + if bA == nil && o != nil { + return o.Copy() + } + if o == nil { + return bA.Copy() + } + bA.mtx.Lock() + o.mtx.Lock() + c := bA.copyBits(cmtmath.MaxInt(bA.Bits, o.Bits)) + smaller := cmtmath.MinInt(len(bA.Elems), len(o.Elems)) + for i := 0; i < smaller; i++ { + c.Elems[i] |= o.Elems[i] + } + bA.mtx.Unlock() + o.mtx.Unlock() + return c +} + +// And returns a bit array resulting from a bitwise AND of the two bit arrays. +// If the two bit-arrys have different lengths, this truncates the larger of the two bit-arrays from the right. +// Thus the size of the return value is the minimum of the two provided bit arrays. +func (bA *BitArray) And(o *BitArray) *BitArray { + if bA == nil || o == nil { + return nil + } + bA.mtx.Lock() + o.mtx.Lock() + defer func() { + bA.mtx.Unlock() + o.mtx.Unlock() + }() + return bA.and(o) +} + +func (bA *BitArray) and(o *BitArray) *BitArray { + c := bA.copyBits(cmtmath.MinInt(bA.Bits, o.Bits)) + for i := 0; i < len(c.Elems); i++ { + c.Elems[i] &= o.Elems[i] + } + return c +} + +// Not returns a bit array resulting from a bitwise Not of the provided bit array. +func (bA *BitArray) Not() *BitArray { + if bA == nil { + return nil // Degenerate + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + return bA.not() +} + +func (bA *BitArray) not() *BitArray { + c := bA.copy() + for i := 0; i < len(c.Elems); i++ { + c.Elems[i] = ^c.Elems[i] + } + return c +} + +// Sub subtracts the two bit-arrays bitwise, without carrying the bits. +// Note that carryless subtraction of a - b is (a and not b). +// The output is the same as bA, regardless of o's size. +// If bA is longer than o, o is right padded with zeroes +func (bA *BitArray) Sub(o *BitArray) *BitArray { + if bA == nil || o == nil { + // TODO: Decide if we should do 1's complement here? + return nil + } + bA.mtx.Lock() + o.mtx.Lock() + // output is the same size as bA + c := bA.copyBits(bA.Bits) + // Only iterate to the minimum size between the two. + // If o is longer, those bits are ignored. + // If bA is longer, then skipping those iterations is equivalent + // to right padding with 0's + smaller := cmtmath.MinInt(len(bA.Elems), len(o.Elems)) + for i := 0; i < smaller; i++ { + // &^ is and not in golang + c.Elems[i] &^= o.Elems[i] + } + bA.mtx.Unlock() + o.mtx.Unlock() + return c +} + +// IsEmpty returns true iff all bits in the bit array are 0 +func (bA *BitArray) IsEmpty() bool { + if bA == nil { + return true // should this be opposite? + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + for _, e := range bA.Elems { + if e > 0 { + return false + } + } + return true +} + +// IsFull returns true iff all bits in the bit array are 1. +func (bA *BitArray) IsFull() bool { + if bA == nil { + return true + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + + // Check all elements except the last + for _, elem := range bA.Elems[:len(bA.Elems)-1] { + if (^elem) != 0 { + return false + } + } + + // Check that the last element has (lastElemBits) 1's + lastElemBits := (bA.Bits+63)%64 + 1 + lastElem := bA.Elems[len(bA.Elems)-1] + return (lastElem+1)&((uint64(1)< 0 { + count++ + } + } + return count +} + +// getNthTrueIndex returns the index of the nth true bit in the bit array. +// n is 0 indexed. (e.g. for bitarray x__x, getNthTrueIndex(0) returns 0). +// If there is no such value, it returns -1. +func (bA *BitArray) getNthTrueIndex(n int) int { + numElems := len(bA.Elems) + count := 0 + + // Iterate over each element + for i := 0; i < numElems; i++ { + // Count set bits in the current element + setBits := bits.OnesCount64(bA.Elems[i]) + + // If the count of set bits in this element plus the count so far + // is greater than or equal to n, then the nth bit must be in this element + if count+setBits >= n { + // Find the index of the nth set bit within this element + for j := 0; j < 64; j++ { + if bA.Elems[i]&(1<}, +// where is a sequence of 'x' (1) and '_' (0). +// The includes spaces and newlines to help people. +// For a simple sequence of 'x' and '_' characters with no spaces or newlines, +// see the MarshalJSON() method. +// Example: "BA{_x_}" or "nil-BitArray" for nil. +func (bA *BitArray) String() string { + return bA.StringIndented("") +} + +// StringIndented returns the same thing as String(), but applies the indent +// at every 10th bit, and twice at every 50th bit. +func (bA *BitArray) StringIndented(indent string) string { + if bA == nil { + return "nil-BitArray" + } + bA.mtx.Lock() + defer bA.mtx.Unlock() + return bA.stringIndented(indent) +} + +func (bA *BitArray) stringIndented(indent string) string { + lines := []string{} + bits := "" + for i := 0; i < bA.Bits; i++ { + if bA.getIndex(i) { + bits += "x" + } else { + bits += "_" + } + if i%100 == 99 { + lines = append(lines, bits) + bits = "" + } + if i%10 == 9 { + bits += indent + } + if i%50 == 49 { + bits += indent + } + } + if len(bits) > 0 { + lines = append(lines, bits) + } + return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent)) +} + +// Bytes returns the byte representation of the bits within the bitarray. +func (bA *BitArray) Bytes() []byte { + bA.mtx.Lock() + defer bA.mtx.Unlock() + + numBytes := (bA.Bits + 7) / 8 + bytes := make([]byte, numBytes) + for i := 0; i < len(bA.Elems); i++ { + elemBytes := [8]byte{} + binary.LittleEndian.PutUint64(elemBytes[:], bA.Elems[i]) + copy(bytes[i*8:], elemBytes[:]) + } + return bytes +} + +// Update sets the bA's bits to be that of the other bit array. +// The copying begins from the begin of both bit arrays. +func (bA *BitArray) Update(o *BitArray) { + if bA == nil || o == nil { + return + } + + bA.mtx.Lock() + o.mtx.Lock() + copy(bA.Elems, o.Elems) + o.mtx.Unlock() + bA.mtx.Unlock() +} + +// MarshalJSON implements json.Marshaler interface by marshaling bit array +// using a custom format: a string of '-' or 'x' where 'x' denotes the 1 bit. +func (bA *BitArray) MarshalJSON() ([]byte, error) { + if bA == nil { + return []byte("null"), nil + } + + bA.mtx.Lock() + defer bA.mtx.Unlock() + + bits := `"` + for i := 0; i < bA.Bits; i++ { + if bA.getIndex(i) { + bits += `x` + } else { + bits += `_` + } + } + bits += `"` + return []byte(bits), nil +} + +var bitArrayJSONRegexp = regexp.MustCompile(`\A"([_x]*)"\z`) + +// UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom +// JSON description. +func (bA *BitArray) UnmarshalJSON(bz []byte) error { + b := string(bz) + if b == "null" { + // This is required e.g. for encoding/json when decoding + // into a pointer with pre-allocated BitArray. + bA.Bits = 0 + bA.Elems = nil + return nil + } + + // Validate 'b'. + match := bitArrayJSONRegexp.FindStringSubmatch(b) + if match == nil { + return fmt.Errorf("bitArray in JSON should be a string of format %q but got %s", bitArrayJSONRegexp.String(), b) + } + bits := match[1] + + // Construct new BitArray and copy over. + numBits := len(bits) + bA2 := NewBitArray(numBits) + if bA2 == nil { + // Treat it as if we encountered the case: b == "null" + bA.Bits = 0 + bA.Elems = nil + return nil + } + + for i := 0; i < numBits; i++ { + if bits[i] == 'x' { + bA2.SetIndex(i, true) + } + } + *bA = *bA2 //nolint:govet + return nil +} + +// ToProto converts BitArray to protobuf +func (bA *BitArray) ToProto() *cmtprotobits.BitArray { + if bA == nil || len(bA.Elems) == 0 { + return nil + } + + return &cmtprotobits.BitArray{ + Bits: int64(bA.Bits), + Elems: bA.Elems, + } +} + +// FromProto sets a protobuf BitArray to the given pointer. +func (bA *BitArray) FromProto(protoBitArray *cmtprotobits.BitArray) { + if protoBitArray == nil { + bA = nil + return + } + + bA.Bits = int(protoBitArray.Bits) + if len(protoBitArray.Elems) > 0 { + bA.Elems = protoBitArray.Elems + } +} + +// ValidateBasic validates a BitArray. Note that a nil BitArray and BitArray of +// size 0 bits is valid. However the number of Bits and Elems be valid based on +// each other. +func (bA *BitArray) ValidateBasic() error { + if bA == nil { + return nil + } + + expectedElems := numElements(bA.Size()) + if expectedElems != len(bA.Elems) { + return fmt.Errorf("mismatch between specified number of bits %d, and number of elements %d, expected %d elements", bA.Size(), len(bA.Elems), expectedElems) + } + return nil +} + +func numElements(bits int) int { + return (bits + 63) / 64 +} diff --git a/libs/bits/bit_array_test.go b/libs/bits/bit_array_test.go new file mode 100644 index 0000000..97a1712 --- /dev/null +++ b/libs/bits/bit_array_test.go @@ -0,0 +1,447 @@ +package bits + +import ( + "bytes" + "encoding/json" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +var ( + empty16Bits = "________________" + empty64Bits = empty16Bits + empty16Bits + empty16Bits + empty16Bits + full16bits = "xxxxxxxxxxxxxxxx" + full64bits = full16bits + full16bits + full16bits + full16bits +) + +func randBitArray(bits int) *BitArray { + src := cmtrand.Bytes((bits + 7) / 8) + srcIndexToBit := func(i int) bool { + return src[i/8]&(1< 0 + } + return NewBitArrayFromFn(bits, srcIndexToBit) +} + +func TestAnd(t *testing.T) { + bA1 := randBitArray(51) + bA2 := randBitArray(31) + bA3 := bA1.And(bA2) + + var bNil *BitArray + require.Equal(t, bNil.And(bA1), (*BitArray)(nil)) + require.Equal(t, bA1.And(nil), (*BitArray)(nil)) + require.Equal(t, bNil.And(nil), (*BitArray)(nil)) + + if bA3.Bits != 31 { + t.Error("Expected min bits", bA3.Bits) + } + if len(bA3.Elems) != len(bA2.Elems) { + t.Error("Expected min elems length") + } + for i := 0; i < bA3.Bits; i++ { + expected := bA1.GetIndex(i) && bA2.GetIndex(i) + if bA3.GetIndex(i) != expected { + t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) + } + } +} + +func TestOr(t *testing.T) { + bA1 := randBitArray(57) + bA2 := randBitArray(31) + bA3 := bA1.Or(bA2) + + bNil := (*BitArray)(nil) + require.Equal(t, bNil.Or(bA1), bA1) + require.Equal(t, bA1.Or(nil), bA1) + require.Equal(t, bNil.Or(nil), (*BitArray)(nil)) + + if bA3.Bits != 57 { + t.Error("Expected max bits") + } + if len(bA3.Elems) != len(bA1.Elems) { + t.Error("Expected max elems length") + } + for i := 0; i < bA3.Bits; i++ { + expected := bA1.GetIndex(i) || bA2.GetIndex(i) + if bA3.GetIndex(i) != expected { + t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) + } + } + if bA3.getNumTrueIndices() == 0 { + t.Error("Expected at least one true bit. " + + "This has a false positive rate that is less than 1 in 2^80 (cryptographically improbable).") + } +} + +func TestSub(t *testing.T) { + testCases := []struct { + initBA string + subtractingBA string + expectedBA string + }{ + {`null`, `null`, `null`}, + {`"x"`, `null`, `null`}, + {`null`, `"x"`, `null`}, + {`"x"`, `"x"`, `"_"`}, + {`"xxxxxx"`, `"x_x_x_"`, `"_x_x_x"`}, + {`"x_x_x_"`, `"xxxxxx"`, `"______"`}, + {`"xxxxxx"`, `"x_x_x_xxxx"`, `"_x_x_x"`}, + {`"x_x_x_xxxx"`, `"xxxxxx"`, `"______xxxx"`}, + {`"xxxxxxxxxx"`, `"x_x_x_"`, `"_x_x_xxxxx"`}, + {`"x_x_x_"`, `"xxxxxxxxxx"`, `"______"`}, + } + for _, tc := range testCases { + var bA *BitArray + err := json.Unmarshal([]byte(tc.initBA), &bA) + require.Nil(t, err) + + var o *BitArray + err = json.Unmarshal([]byte(tc.subtractingBA), &o) + require.Nil(t, err) + + got, _ := json.Marshal(bA.Sub(o)) + require.Equal( + t, + tc.expectedBA, + string(got), + "%s minus %s doesn't equal %s", + tc.initBA, + tc.subtractingBA, + tc.expectedBA, + ) + } +} + +func TestPickRandom(t *testing.T) { + testCases := []struct { + bA string + ok bool + }{ + {`null`, false}, + {`"x"`, true}, + {`"` + empty16Bits + `"`, false}, + {`"x` + empty16Bits + `"`, true}, + {`"` + empty16Bits + `x"`, true}, + {`"x` + empty16Bits + `x"`, true}, + {`"` + empty64Bits + `"`, false}, + {`"x` + empty64Bits + `"`, true}, + {`"` + empty64Bits + `x"`, true}, + {`"x` + empty64Bits + `x"`, true}, + {`"` + empty64Bits + `___x"`, true}, + } + for _, tc := range testCases { + var bitArr *BitArray + err := json.Unmarshal([]byte(tc.bA), &bitArr) + require.NoError(t, err) + _, ok := bitArr.PickRandom() + require.Equal(t, tc.ok, ok, "PickRandom got an unexpected result on input %s", tc.bA) + } +} + +func TestGetNumTrueIndices(t *testing.T) { + type testcase struct { + Input string + ExpectedResult int + } + testCases := []testcase{ + {"x_x_x_", 3}, + {"______", 0}, + {"xxxxxx", 6}, + {"x_x_x_x_x_x_x_x_x_", 9}, + } + numOriginalTestCases := len(testCases) + for i := 0; i < numOriginalTestCases; i++ { + testCases = append(testCases, testcase{testCases[i].Input + "x", testCases[i].ExpectedResult + 1}) + testCases = append(testCases, testcase{full64bits + testCases[i].Input, testCases[i].ExpectedResult + 64}) + testCases = append(testCases, testcase{empty64Bits + testCases[i].Input, testCases[i].ExpectedResult}) + } + + for _, tc := range testCases { + var bitArr *BitArray + err := json.Unmarshal([]byte(`"`+tc.Input+`"`), &bitArr) + require.NoError(t, err) + result := bitArr.getNumTrueIndices() + require.Equal(t, tc.ExpectedResult, result, "for input %s, expected %d, got %d", tc.Input, tc.ExpectedResult, result) + result = bitArr.Not().getNumTrueIndices() + require.Equal(t, bitArr.Bits-result, bitArr.getNumTrueIndices()) + } +} + +func TestGetNumTrueIndicesInvalidStates(t *testing.T) { + testCases := []struct { + name string + bA1 *BitArray + exp int + }{ + {"empty", &BitArray{}, 0}, + {"explicit 0 bits nil elements", &BitArray{Bits: 0, Elems: nil}, 0}, + {"explicit 0 bits 0 len elements", &BitArray{Bits: 0, Elems: make([]uint64, 0)}, 0}, + {"nil", nil, 0}, + {"with elements", NewBitArray(10), 0}, + {"more elements than bits specifies", &BitArray{Bits: 0, Elems: make([]uint64, 5)}, 0}, + {"less elements than bits specifies", &BitArray{Bits: 200, Elems: make([]uint64, 1)}, 0}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + n := tc.bA1.getNumTrueIndices() + require.Equal(t, n, tc.exp) + }) + } +} + +func TestGetNthTrueIndex(t *testing.T) { + type testcase struct { + Input string + N int + ExpectedResult int + } + testCases := []testcase{ + // Basic cases + {"x_x_x_", 0, 0}, + {"x_x_x_", 1, 2}, + {"x_x_x_", 2, 4}, + {"______", 1, -1}, // No true indices + {"xxxxxx", 5, 5}, // Last true index + {"x_x_x_x_x_x_x_", 9, -1}, // Out-of-range + + // Edge cases + {"xxxxxx", 7, -1}, // Out-of-range + {"______", 0, -1}, // No true indices + {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 49, 49}, // Last true index + {"____________________________________________", 1, -1}, // No true indices + {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 63, 63}, // last index of first word + {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 64, 64}, // first index of second word + {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 100, -1}, // Out-of-range + + // Input beyond 64 bits + {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 99, 99}, // Last true index + + // Input less than 64 bits + {"x_x_x_", 3, -1}, // Out-of-range + } + + numOriginalTestCases := len(testCases) + // Add 64 underscores to each test case + for i := 0; i < numOriginalTestCases; i++ { + expectedResult := testCases[i].ExpectedResult + if expectedResult != -1 { + expectedResult += 64 + } + testCases = append(testCases, testcase{empty64Bits + testCases[i].Input, testCases[i].N, expectedResult}) + } + + for _, tc := range testCases { + var bitArr *BitArray + err := json.Unmarshal([]byte(`"`+tc.Input+`"`), &bitArr) + require.NoError(t, err) + + // Get the nth true index + result := bitArr.getNthTrueIndex(tc.N) + + require.Equal(t, tc.ExpectedResult, result, "for bit array %s, input %d, expected %d, got %d", tc.Input, tc.N, tc.ExpectedResult, result) + } +} + +func TestBytes(t *testing.T) { + bA := NewBitArray(4) + bA.SetIndex(0, true) + check := func(bA *BitArray, bz []byte) { + if !bytes.Equal(bA.Bytes(), bz) { + panic(fmt.Sprintf("Expected %X but got %X", bz, bA.Bytes())) + } + } + check(bA, []byte{0x01}) + bA.SetIndex(3, true) + check(bA, []byte{0x09}) + + bA = NewBitArray(9) + check(bA, []byte{0x00, 0x00}) + bA.SetIndex(7, true) + check(bA, []byte{0x80, 0x00}) + bA.SetIndex(8, true) + check(bA, []byte{0x80, 0x01}) + + bA = NewBitArray(16) + check(bA, []byte{0x00, 0x00}) + bA.SetIndex(7, true) + check(bA, []byte{0x80, 0x00}) + bA.SetIndex(8, true) + check(bA, []byte{0x80, 0x01}) + bA.SetIndex(9, true) + check(bA, []byte{0x80, 0x03}) + + bA = NewBitArray(4) + bA.Elems = nil + require.False(t, bA.SetIndex(1, true)) +} + +func TestEmptyFull(t *testing.T) { + ns := []int{47, 123} + for _, n := range ns { + bA := NewBitArray(n) + if !bA.IsEmpty() { + t.Fatal("Expected bit array to be empty") + } + for i := 0; i < n; i++ { + bA.SetIndex(i, true) + } + if !bA.IsFull() { + t.Fatal("Expected bit array to be full") + } + } +} + +func TestUpdateNeverPanics(_ *testing.T) { + newRandBitArray := func(n int) *BitArray { + ba := randBitArray(n) + return ba + } + pairs := []struct { + a, b *BitArray + }{ + {nil, nil}, + {newRandBitArray(10), newRandBitArray(12)}, + {newRandBitArray(23), newRandBitArray(23)}, + {newRandBitArray(37), nil}, + {nil, NewBitArray(10)}, + } + + for _, pair := range pairs { + a, b := pair.a, pair.b + a.Update(b) + b.Update(a) + } +} + +func TestNewBitArrayNeverCrashesOnNegatives(_ *testing.T) { + bitList := []int{-127, -128, -1 << 31} + for _, bits := range bitList { + _ = NewBitArray(bits) + } +} + +func TestJSONMarshalUnmarshal(t *testing.T) { + bA1 := NewBitArray(0) + + bA2 := NewBitArray(1) + + bA3 := NewBitArray(1) + bA3.SetIndex(0, true) + + bA4 := NewBitArray(5) + bA4.SetIndex(0, true) + bA4.SetIndex(1, true) + + testCases := []struct { + bA *BitArray + marshalledBA string + }{ + {nil, `null`}, + {bA1, `null`}, + {bA2, `"_"`}, + {bA3, `"x"`}, + {bA4, `"xx___"`}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.bA.String(), func(t *testing.T) { + bz, err := json.Marshal(tc.bA) + require.NoError(t, err) + + assert.Equal(t, tc.marshalledBA, string(bz)) + + var unmarshalledBA *BitArray + err = json.Unmarshal(bz, &unmarshalledBA) + require.NoError(t, err) + + if tc.bA == nil { + require.Nil(t, unmarshalledBA) + } else { + require.NotNil(t, unmarshalledBA) + assert.EqualValues(t, tc.bA.Bits, unmarshalledBA.Bits) + if assert.EqualValues(t, tc.bA.String(), unmarshalledBA.String()) { + assert.EqualValues(t, tc.bA.Elems, unmarshalledBA.Elems) + } + } + }) + } +} + +func TestBitArrayProtoBuf(t *testing.T) { + testCases := []struct { + msg string + bA1 *BitArray + expPass bool + }{ + {"success empty", &BitArray{}, true}, + {"success", NewBitArray(1), true}, + {"success", NewBitArray(2), true}, + {"negative", NewBitArray(-1), false}, + } + for _, tc := range testCases { + protoBA := tc.bA1.ToProto() + ba := new(BitArray) + ba.FromProto(protoBA) + if tc.expPass { + require.Equal(t, tc.bA1, ba, tc.msg) + } else { + require.NotEqual(t, tc.bA1, ba, tc.msg) + } + } +} + +func TestBitArrayValidateBasic(t *testing.T) { + testCases := []struct { + name string + bA1 *BitArray + expPass bool + }{ + {"valid empty", &BitArray{}, true}, + {"valid explicit 0 bits nil elements", &BitArray{Bits: 0, Elems: nil}, true}, + {"valid explicit 0 bits 0 len elements", &BitArray{Bits: 0, Elems: make([]uint64, 0)}, true}, + {"valid nil", nil, true}, + {"valid with elements", NewBitArray(10), true}, + {"more elements than bits specifies", &BitArray{Bits: 0, Elems: make([]uint64, 5)}, false}, + {"less elements than bits specifies", &BitArray{Bits: 200, Elems: make([]uint64, 1)}, false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := tc.bA1.ValidateBasic() + require.Equal(t, err == nil, tc.expPass) + }) + } +} + +// Tests that UnmarshalJSON doesn't crash when no bits are passed into the JSON. +// See issue https://github.com/cometbft/cometbft/issues/2658 +func TestUnmarshalJSONDoesntCrashOnZeroBits(t *testing.T) { + type indexCorpus struct { + BitArray *BitArray `json:"ba"` + Index int `json:"i"` + } + + ic := new(indexCorpus) + blob := []byte(`{"BA":""}`) + err := json.Unmarshal(blob, ic) + require.NoError(t, err) + require.Equal(t, ic.BitArray, &BitArray{Bits: 0, Elems: nil}) +} + +func BenchmarkPickRandomBitArray(b *testing.B) { + // A random 150 bit string to use as the benchmark bit array + benchmarkBitArrayStr := "_______xx__xxx_xx__x_xx_x_x_x__x_x_x_xx__xx__xxx__xx_x_xxx_x__xx____x____xx__xx____x_x__x_____xx_xx_xxxxxxx__xx_x_xxxx_x___x_xxxxx_xx__xxxx_xx_x___x_x" + var bitArr *BitArray + err := json.Unmarshal([]byte(`"`+benchmarkBitArrayStr+`"`), &bitArr) + require.NoError(b, err) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, _ = bitArr.PickRandom() + } +} diff --git a/libs/bytes/bytes.go b/libs/bytes/bytes.go new file mode 100644 index 0000000..ca478cd --- /dev/null +++ b/libs/bytes/bytes.go @@ -0,0 +1,65 @@ +package bytes + +import ( + "encoding/hex" + "fmt" + "strings" +) + +// HexBytes enables HEX-encoding for json/encoding. +type HexBytes []byte + +// Marshal needed for protobuf compatibility +func (bz HexBytes) Marshal() ([]byte, error) { + return bz, nil +} + +// Unmarshal needed for protobuf compatibility +func (bz *HexBytes) Unmarshal(data []byte) error { + *bz = data + return nil +} + +// This is the point of Bytes. +func (bz HexBytes) MarshalJSON() ([]byte, error) { + s := strings.ToUpper(hex.EncodeToString(bz)) + jbz := make([]byte, len(s)+2) + jbz[0] = '"' + copy(jbz[1:], s) + jbz[len(jbz)-1] = '"' + return jbz, nil +} + +// This is the point of Bytes. +func (bz *HexBytes) UnmarshalJSON(data []byte) error { + if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { + return fmt.Errorf("invalid hex string: %s", data) + } + bz2, err := hex.DecodeString(string(data[1 : len(data)-1])) + if err != nil { + return err + } + *bz = bz2 + return nil +} + +// Bytes fulfills various interfaces in light-client, etc... +func (bz HexBytes) Bytes() []byte { + return bz +} + +func (bz HexBytes) String() string { + return strings.ToUpper(hex.EncodeToString(bz)) +} + +// Format writes either address of 0th element in a slice in base 16 notation, +// with leading 0x (%p), or casts HexBytes to bytes and writes as hexadecimal +// string to s. +func (bz HexBytes) Format(s fmt.State, verb rune) { + switch verb { + case 'p': + fmt.Fprintf(s, "%p", bz) + default: + fmt.Fprintf(s, "%X", []byte(bz)) + } +} diff --git a/libs/bytes/bytes_test.go b/libs/bytes/bytes_test.go new file mode 100644 index 0000000..39d1d20 --- /dev/null +++ b/libs/bytes/bytes_test.go @@ -0,0 +1,73 @@ +package bytes + +import ( + "encoding/json" + "fmt" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +// This is a trivial test for protobuf compatibility. +func TestMarshal(t *testing.T) { + bz := []byte("hello world") + dataB := HexBytes(bz) + bz2, err := dataB.Marshal() + assert.Nil(t, err) + assert.Equal(t, bz, bz2) + + var dataB2 HexBytes + err = (&dataB2).Unmarshal(bz) + assert.Nil(t, err) + assert.Equal(t, dataB, dataB2) +} + +// Test that the hex encoding works. +func TestJSONMarshal(t *testing.T) { + type TestStruct struct { + B1 []byte + B2 HexBytes + } + + cases := []struct { + input []byte + expected string + }{ + {[]byte(``), `{"B1":"","B2":""}`}, + {[]byte(`a`), `{"B1":"YQ==","B2":"61"}`}, + {[]byte(`abc`), `{"B1":"YWJj","B2":"616263"}`}, + } + + for i, tc := range cases { + tc := tc + t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) { + ts := TestStruct{B1: tc.input, B2: tc.input} + + // Test that it marshals correctly to JSON. + jsonBytes, err := json.Marshal(ts) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, string(jsonBytes), tc.expected) + + // TODO do fuzz testing to ensure that unmarshal fails + + // Test that unmarshaling works correctly. + ts2 := TestStruct{} + err = json.Unmarshal(jsonBytes, &ts2) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, ts2.B1, tc.input) + assert.Equal(t, ts2.B2, HexBytes(tc.input)) + }) + } +} + +func TestHexBytes_String(t *testing.T) { + hs := HexBytes([]byte("test me")) + if _, err := strconv.ParseInt(hs.String(), 16, 64); err != nil { + t.Fatal(err) + } +} diff --git a/libs/bytes/byteslice.go b/libs/bytes/byteslice.go new file mode 100644 index 0000000..bdb7ed9 --- /dev/null +++ b/libs/bytes/byteslice.go @@ -0,0 +1,10 @@ +package bytes + +// Fingerprint returns the first 6 bytes of a byte slice. +// If the slice is less than 6 bytes, the fingerprint +// contains trailing zeroes. +func Fingerprint(slice []byte) []byte { + fingerprint := make([]byte, 6) + copy(fingerprint, slice) + return fingerprint +} diff --git a/libs/cli/flags/log_level.go b/libs/cli/flags/log_level.go new file mode 100644 index 0000000..b31eb7d --- /dev/null +++ b/libs/cli/flags/log_level.go @@ -0,0 +1,90 @@ +package flags + +import ( + "errors" + "fmt" + "strings" + + "github.com/cometbft/cometbft/libs/log" +) + +const ( + defaultLogLevelKey = "*" +) + +// ParseLogLevel parses complex log level - comma-separated +// list of module:level pairs with an optional *:level pair (* means +// all other modules). +// +// Example: +// +// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info") +func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) (log.Logger, error) { + if lvl == "" { + return nil, errors.New("empty log level") + } + + l := lvl + + // prefix simple one word levels (e.g. "info") with "*" + if !strings.Contains(l, ":") { + l = defaultLogLevelKey + ":" + l + } + + options := make([]log.Option, 0) + + isDefaultLogLevelSet := false + var option log.Option + var err error + + list := strings.Split(l, ",") + for _, item := range list { + moduleAndLevel := strings.Split(item, ":") + + if len(moduleAndLevel) != 2 { + return nil, fmt.Errorf("expected list in a form of \"module:level\" pairs, given pair %s, list %s", item, list) + } + + module := moduleAndLevel[0] + level := moduleAndLevel[1] + + if module == defaultLogLevelKey { + option, err = log.AllowLevel(level) + if err != nil { + return nil, fmt.Errorf("failed to parse default log level (pair %s, list %s): %w", item, l, err) + } + options = append(options, option) + isDefaultLogLevelSet = true + } else { + switch level { + case "debug": + option = log.AllowDebugWith("module", module) + case "info": + option = log.AllowInfoWith("module", module) + case "error": + option = log.AllowErrorWith("module", module) + case "none": + option = log.AllowNoneWith("module", module) + default: + return nil, + fmt.Errorf("expected either \"info\", \"debug\", \"error\" or \"none\" log level, given %s (pair %s, list %s)", + level, + item, + list) + } + options = append(options, option) + + } + } + + // if "*" is not provided, set default global level + if !isDefaultLogLevelSet { + option, err = log.AllowLevel(defaultLogLevelValue) + if err != nil { + return nil, err + } + options = append(options, option) + } + + return log.NewFilter(logger, options...), nil +} diff --git a/libs/cli/flags/log_level_test.go b/libs/cli/flags/log_level_test.go new file mode 100644 index 0000000..620e3e8 --- /dev/null +++ b/libs/cli/flags/log_level_test.go @@ -0,0 +1,94 @@ +package flags_test + +import ( + "bytes" + "strings" + "testing" + + cmtflags "github.com/cometbft/cometbft/libs/cli/flags" + "github.com/cometbft/cometbft/libs/log" +) + +const ( + defaultLogLevelValue = "info" +) + +func TestParseLogLevel(t *testing.T) { + var buf bytes.Buffer + jsonLogger := log.NewTMJSONLoggerNoTS(&buf) + + correctLogLevels := []struct { + lvl string + expectedLogLines []string + }{ + {"mempool:error", []string{ + ``, // if no default is given, assume info + ``, + `{"_msg":"Mesmero","level":"error","module":"mempool"}`, + `{"_msg":"Mind","level":"info","module":"state"}`, // if no default is given, assume info + ``}}, + + {"mempool:error,*:debug", []string{ + `{"_msg":"Kingpin","level":"debug","module":"wire"}`, + ``, + `{"_msg":"Mesmero","level":"error","module":"mempool"}`, + `{"_msg":"Mind","level":"info","module":"state"}`, + `{"_msg":"Gideon","level":"debug"}`}}, + + {"*:debug,wire:none", []string{ + ``, + `{"_msg":"Kitty Pryde","level":"info","module":"mempool"}`, + `{"_msg":"Mesmero","level":"error","module":"mempool"}`, + `{"_msg":"Mind","level":"info","module":"state"}`, + `{"_msg":"Gideon","level":"debug"}`}}, + } + + for _, c := range correctLogLevels { + logger, err := cmtflags.ParseLogLevel(c.lvl, jsonLogger, defaultLogLevelValue) + if err != nil { + t.Fatal(err) + } + + buf.Reset() + + logger.With("module", "mempool").With("module", "wire").Debug("Kingpin") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[0] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[0], have, c.lvl) + } + + buf.Reset() + + logger.With("module", "mempool").Info("Kitty Pryde") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[1] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[1], have, c.lvl) + } + + buf.Reset() + + logger.With("module", "mempool").Error("Mesmero") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[2] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[2], have, c.lvl) + } + + buf.Reset() + + logger.With("module", "state").Info("Mind") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[3] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[3], have, c.lvl) + } + + buf.Reset() + + logger.Debug("Gideon") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[4] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[4], have, c.lvl) + } + } + + incorrectLogLevel := []string{"some", "mempool:some", "*:some,mempool:error"} + for _, lvl := range incorrectLogLevel { + if _, err := cmtflags.ParseLogLevel(lvl, jsonLogger, defaultLogLevelValue); err == nil { + t.Fatalf("Expected %s to produce error", lvl) + } + } +} diff --git a/libs/cli/helper.go b/libs/cli/helper.go new file mode 100644 index 0000000..2cacdce --- /dev/null +++ b/libs/cli/helper.go @@ -0,0 +1,127 @@ +package cli + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/spf13/cobra" +) + +// WriteConfigVals writes a toml file with the given values. +// It returns an error if writing was impossible. +func WriteConfigVals(dir string, vals map[string]string) error { + data := "" + for k, v := range vals { + data += fmt.Sprintf("%s = \"%s\"\n", k, v) + } + cfile := filepath.Join(dir, "config.toml") + return os.WriteFile(cfile, []byte(data), 0600) +} + +// RunWithArgs executes the given command with the specified command line args +// and environmental variables set. It returns any error returned from cmd.Execute() +func RunWithArgs(cmd Executable, args []string, env map[string]string) error { + oargs := os.Args + oenv := map[string]string{} + // defer returns the environment back to normal + defer func() { + os.Args = oargs + for k, v := range oenv { + os.Setenv(k, v) + } + }() + + // set the args and env how we want them + os.Args = args + for k, v := range env { + // backup old value if there, to restore at end + oenv[k] = os.Getenv(k) + err := os.Setenv(k, v) + if err != nil { + return err + } + } + + // and finally run the command + return cmd.Execute() +} + +// RunCaptureWithArgs executes the given command with the specified command +// line args and environmental variables set. It returns string fields +// representing output written to stdout and stderr, additionally any error +// from cmd.Execute() is also returned +func RunCaptureWithArgs(cmd Executable, args []string, env map[string]string) (stdout, stderr string, err error) { + oldout, olderr := os.Stdout, os.Stderr // keep backup of the real stdout + rOut, wOut, _ := os.Pipe() + rErr, wErr, _ := os.Pipe() + os.Stdout, os.Stderr = wOut, wErr + defer func() { + os.Stdout, os.Stderr = oldout, olderr // restoring the real stdout + }() + + // copy the output in a separate goroutine so printing can't block indefinitely + copyStd := func(reader *os.File) *(chan string) { + stdC := make(chan string) + go func() { + var buf bytes.Buffer + // io.Copy will end when we call reader.Close() below + io.Copy(&buf, reader) //nolint:errcheck //ignore error + stdC <- buf.String() + }() + return &stdC + } + outC := copyStd(rOut) + errC := copyStd(rErr) + + // now run the command + err = RunWithArgs(cmd, args, env) + + // and grab the stdout to return + wOut.Close() + wErr.Close() + stdout = <-*outC + stderr = <-*errC + return stdout, stderr, err +} + +// NewCompletionCmd returns a cobra.Command that generates bash and zsh +// completion scripts for the given root command. If hidden is true, the +// command will not show up in the root command's list of available commands. +func NewCompletionCmd(rootCmd *cobra.Command, hidden bool) *cobra.Command { + flagZsh := "zsh" + cmd := &cobra.Command{ + Use: "completion", + Short: "Generate shell completion scripts", + Long: fmt.Sprintf(`Generate Bash and Zsh completion scripts and print them to STDOUT. + +Once saved to file, a completion script can be loaded in the shell's +current session as shown: + + $ . <(%s completion) + +To configure your bash shell to load completions for each session add to +your $HOME/.bashrc or $HOME/.profile the following instruction: + + . <(%s completion) +`, rootCmd.Use, rootCmd.Use), + RunE: func(cmd *cobra.Command, _ []string) error { + zsh, err := cmd.Flags().GetBool(flagZsh) + if err != nil { + return err + } + if zsh { + return rootCmd.GenZshCompletion(cmd.OutOrStdout()) + } + return rootCmd.GenBashCompletion(cmd.OutOrStdout()) + }, + Hidden: hidden, + Args: cobra.NoArgs, + } + + cmd.Flags().Bool(flagZsh, false, "Generate Zsh completion script") + + return cmd +} diff --git a/libs/cli/setup.go b/libs/cli/setup.go new file mode 100644 index 0000000..37f77b4 --- /dev/null +++ b/libs/cli/setup.go @@ -0,0 +1,158 @@ +package cli + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + HomeFlag = "home" + TraceFlag = "trace" + OutputFlag = "output" + EncodingFlag = "encoding" +) + +// Executable is the minimal interface to *corba.Command, so we can +// wrap if desired before the test +type Executable interface { + Execute() error +} + +// PrepareBaseCmd is meant for CometBFT and other servers +func PrepareBaseCmd(cmd *cobra.Command, envPrefix, defaultHome string) Executor { + cobra.OnInitialize(func() { initEnv(envPrefix) }) + cmd.PersistentFlags().StringP(HomeFlag, "", defaultHome, "directory for config and data") + cmd.PersistentFlags().Bool(TraceFlag, false, "print out full stack trace on errors") + cmd.PersistentPreRunE = concatCobraCmdFuncs(bindFlagsLoadViper, cmd.PersistentPreRunE) + return Executor{cmd, os.Exit} +} + +// PrepareMainCmd is meant for client side libs that want some more flags +// +// This adds --encoding (hex, btc, base64) and --output (text, json) to +// the command. These only really make sense in interactive commands. +func PrepareMainCmd(cmd *cobra.Command, envPrefix, defaultHome string) Executor { + cmd.PersistentFlags().StringP(EncodingFlag, "e", "hex", "Binary encoding (hex|b64|btc)") + cmd.PersistentFlags().StringP(OutputFlag, "o", "text", "Output format (text|json)") + cmd.PersistentPreRunE = concatCobraCmdFuncs(validateOutput, cmd.PersistentPreRunE) + return PrepareBaseCmd(cmd, envPrefix, defaultHome) +} + +// initEnv sets to use ENV variables if set. +func initEnv(prefix string) { + copyEnvVars(prefix) + + // env variables with TM prefix (eg. TM_ROOT) + viper.SetEnvPrefix(prefix) + viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) + viper.AutomaticEnv() +} + +// This copies all variables like TMROOT to TM_ROOT, +// so we can support both formats for the user +func copyEnvVars(prefix string) { + prefix = strings.ToUpper(prefix) + ps := prefix + "_" + for _, e := range os.Environ() { + kv := strings.SplitN(e, "=", 2) + if len(kv) == 2 { + k, v := kv[0], kv[1] + if strings.HasPrefix(k, prefix) && !strings.HasPrefix(k, ps) { + k2 := strings.Replace(k, prefix, ps, 1) + os.Setenv(k2, v) + } + } + } +} + +// Executor wraps the cobra Command with a nicer Execute method +type Executor struct { + *cobra.Command + Exit func(int) // this is os.Exit by default, override in tests +} + +type ExitCoder interface { + ExitCode() int +} + +// execute adds all child commands to the root command sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func (e Executor) Execute() error { + e.SilenceUsage = true + e.SilenceErrors = true + err := e.Command.Execute() + if err != nil { + if viper.GetBool(TraceFlag) { + const size = 64 << 10 + buf := make([]byte, size) + buf = buf[:runtime.Stack(buf, false)] + fmt.Fprintf(os.Stderr, "ERROR: %v\n%s\n", err, buf) + } else { + fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) + } + + // return error code 1 by default, can override it with a special error type + exitCode := 1 + if ec, ok := err.(ExitCoder); ok { + exitCode = ec.ExitCode() + } + e.Exit(exitCode) + } + return err +} + +type cobraCmdFunc func(cmd *cobra.Command, args []string) error + +// Returns a single function that calls each argument function in sequence +// RunE, PreRunE, PersistentPreRunE, etc. all have this same signature +func concatCobraCmdFuncs(fs ...cobraCmdFunc) cobraCmdFunc { + return func(cmd *cobra.Command, args []string) error { + for _, f := range fs { + if f != nil { + if err := f(cmd, args); err != nil { + return err + } + } + } + return nil + } +} + +// Bind all flags and read the config into viper +func bindFlagsLoadViper(cmd *cobra.Command, _ []string) error { + // cmd.Flags() includes flags from this command and all persistent flags from the parent + if err := viper.BindPFlags(cmd.Flags()); err != nil { + return err + } + + homeDir := viper.GetString(HomeFlag) + viper.Set(HomeFlag, homeDir) + viper.SetConfigName("config") // name of config file (without extension) + viper.AddConfigPath(homeDir) // search root directory + viper.AddConfigPath(filepath.Join(homeDir, "config")) // search root directory /config + + // If a config file is found, read it in. + err := viper.ReadInConfig() + if _, ok := err.(viper.ConfigFileNotFoundError); !ok { + // ignore not found error, return other errors + return err + } + return nil +} + +func validateOutput(_ *cobra.Command, _ []string) error { + // validate output format + output := viper.GetString(OutputFlag) + switch output { + case "text", "json": + default: + return fmt.Errorf("unsupported output format: %s", output) + } + return nil +} diff --git a/libs/cli/setup_test.go b/libs/cli/setup_test.go new file mode 100644 index 0000000..15d6e9d --- /dev/null +++ b/libs/cli/setup_test.go @@ -0,0 +1,237 @@ +package cli + +import ( + "fmt" + "os" + "strconv" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSetupEnv(t *testing.T) { + cases := []struct { + args []string + env map[string]string + expected string + }{ + {nil, nil, ""}, + {[]string{"--foobar", "bang!"}, nil, "bang!"}, + // make sure reset is good + {nil, nil, ""}, + // test both variants of the prefix + {nil, map[string]string{"DEMO_FOOBAR": "good"}, "good"}, + {nil, map[string]string{"DEMOFOOBAR": "silly"}, "silly"}, + // and that cli overrides env... + {[]string{"--foobar", "important"}, + map[string]string{"DEMO_FOOBAR": "ignored"}, "important"}, + } + + for idx, tc := range cases { + i := strconv.Itoa(idx) + // test command that store value of foobar in local variable + var foo string + demo := &cobra.Command{ + Use: "demo", + RunE: func(cmd *cobra.Command, args []string) error { + foo = viper.GetString("foobar") + return nil + }, + } + demo.Flags().String("foobar", "", "Some test value from config") + cmd := PrepareBaseCmd(demo, "DEMO", "/qwerty/asdfgh") // some missing dir.. + cmd.Exit = func(int) {} + + viper.Reset() + args := append([]string{cmd.Use}, tc.args...) + err := RunWithArgs(cmd, args, tc.env) + require.Nil(t, err, i) + assert.Equal(t, tc.expected, foo, i) + } +} + +func tempDir() string { + cdir, err := os.MkdirTemp("", "test-cli") + if err != nil { + panic(err) + } + return cdir +} + +func TestSetupConfig(t *testing.T) { + // we pre-create two config files we can refer to in the rest of + // the test cases. + cval1 := "fubble" + conf1 := tempDir() + err := WriteConfigVals(conf1, map[string]string{"boo": cval1}) + require.Nil(t, err) + + cases := []struct { + args []string + env map[string]string + expected string + expectedTwo string + }{ + {nil, nil, "", ""}, + // setting on the command line + {[]string{"--boo", "haha"}, nil, "haha", ""}, + {[]string{"--two-words", "rocks"}, nil, "", "rocks"}, + {[]string{"--home", conf1}, nil, cval1, ""}, + // test both variants of the prefix + {nil, map[string]string{"RD_BOO": "bang"}, "bang", ""}, + {nil, map[string]string{"RD_TWO_WORDS": "fly"}, "", "fly"}, + {nil, map[string]string{"RDTWO_WORDS": "fly"}, "", "fly"}, + {nil, map[string]string{"RD_HOME": conf1}, cval1, ""}, + {nil, map[string]string{"RDHOME": conf1}, cval1, ""}, + } + + for idx, tc := range cases { + i := strconv.Itoa(idx) + // test command that store value of foobar in local variable + var foo, two string + boo := &cobra.Command{ + Use: "reader", + RunE: func(cmd *cobra.Command, args []string) error { + foo = viper.GetString("boo") + two = viper.GetString("two-words") + return nil + }, + } + boo.Flags().String("boo", "", "Some test value from config") + boo.Flags().String("two-words", "", "Check out env handling -") + cmd := PrepareBaseCmd(boo, "RD", "/qwerty/asdfgh") // some missing dir... + cmd.Exit = func(int) {} + + viper.Reset() + args := append([]string{cmd.Use}, tc.args...) + err := RunWithArgs(cmd, args, tc.env) + require.Nil(t, err, i) + assert.Equal(t, tc.expected, foo, i) + assert.Equal(t, tc.expectedTwo, two, i) + } +} + +type DemoConfig struct { + Name string `mapstructure:"name"` + Age int `mapstructure:"age"` + Unused int `mapstructure:"unused"` +} + +func TestSetupUnmarshal(t *testing.T) { + // we pre-create two config files we can refer to in the rest of + // the test cases. + cval1, cval2 := "someone", "else" + conf1 := tempDir() + err := WriteConfigVals(conf1, map[string]string{"name": cval1}) + require.Nil(t, err) + // even with some ignored fields, should be no problem + conf2 := tempDir() + err = WriteConfigVals(conf2, map[string]string{"name": cval2, "foo": "bar"}) + require.Nil(t, err) + + // unused is not declared on a flag and remains from base + base := DemoConfig{ + Name: "default", + Age: 42, + Unused: -7, + } + c := func(name string, age int) DemoConfig { + r := base + // anything set on the flags as a default is used over + // the default config object + r.Name = "from-flag" + if name != "" { + r.Name = name + } + if age != 0 { + r.Age = age + } + return r + } + + cases := []struct { + args []string + env map[string]string + expected DemoConfig + }{ + {nil, nil, c("", 0)}, + // setting on the command line + {[]string{"--name", "haha"}, nil, c("haha", 0)}, + {[]string{"--home", conf1}, nil, c(cval1, 0)}, + // test both variants of the prefix + {nil, map[string]string{"MR_AGE": "56"}, c("", 56)}, + {nil, map[string]string{"MR_HOME": conf1}, c(cval1, 0)}, + {[]string{"--age", "17"}, map[string]string{"MRHOME": conf2}, c(cval2, 17)}, + } + + for idx, tc := range cases { + i := strconv.Itoa(idx) + // test command that store value of foobar in local variable + cfg := base + marsh := &cobra.Command{ + Use: "marsh", + RunE: func(cmd *cobra.Command, args []string) error { + return viper.Unmarshal(&cfg) + }, + } + marsh.Flags().String("name", "from-flag", "Some test value from config") + // if we want a flag to use the proper default, then copy it + // from the default config here + marsh.Flags().Int("age", base.Age, "Some test value from config") + cmd := PrepareBaseCmd(marsh, "MR", "/qwerty/asdfgh") // some missing dir... + cmd.Exit = func(int) {} + + viper.Reset() + args := append([]string{cmd.Use}, tc.args...) + err := RunWithArgs(cmd, args, tc.env) + require.Nil(t, err, i) + assert.Equal(t, tc.expected, cfg, i) + } +} + +func TestSetupTrace(t *testing.T) { + cases := []struct { + args []string + env map[string]string + long bool + expected string + }{ + {nil, nil, false, "trace flag = false"}, + {[]string{"--trace"}, nil, true, "trace flag = true"}, + {[]string{"--no-such-flag"}, nil, false, "unknown flag: --no-such-flag"}, + {nil, map[string]string{"DBG_TRACE": "true"}, true, "trace flag = true"}, + } + + for idx, tc := range cases { + i := strconv.Itoa(idx) + // test command that store value of foobar in local variable + trace := &cobra.Command{ + Use: "trace", + RunE: func(cmd *cobra.Command, args []string) error { + return fmt.Errorf("trace flag = %t", viper.GetBool(TraceFlag)) + }, + } + cmd := PrepareBaseCmd(trace, "DBG", "/qwerty/asdfgh") // some missing dir.. + cmd.Exit = func(int) {} + + viper.Reset() + args := append([]string{cmd.Use}, tc.args...) + stdout, stderr, err := RunCaptureWithArgs(cmd, args, tc.env) + require.NotNil(t, err, i) + require.Equal(t, "", stdout, i) + require.NotEqual(t, "", stderr, i) + msg := strings.Split(stderr, "\n") + desired := fmt.Sprintf("ERROR: %s", tc.expected) + assert.Equal(t, desired, msg[0], i) + t.Log(msg) + if tc.long && assert.True(t, len(msg) > 2, i) { + // the next line starts the stack trace... + assert.Contains(t, stderr, "TestSetupTrace", i) + assert.Contains(t, stderr, "setup_test.go", i) + } + } +} diff --git a/libs/clist/bench_test.go b/libs/clist/bench_test.go new file mode 100644 index 0000000..eacbb66 --- /dev/null +++ b/libs/clist/bench_test.go @@ -0,0 +1,46 @@ +package clist + +import "testing" + +func BenchmarkDetaching(b *testing.B) { + lst := New() + for i := 0; i < b.N+1; i++ { + lst.PushBack(i) + } + start := lst.Front() + nxt := start.Next() + b.ResetTimer() + for i := 0; i < b.N; i++ { + start.removed = true + start.DetachNext() + start.DetachPrev() + tmp := nxt + nxt = nxt.Next() + start = tmp + } +} + +// This is used to benchmark the time of RMutex. +func BenchmarkRemoved(b *testing.B) { + lst := New() + for i := 0; i < b.N+1; i++ { + lst.PushBack(i) + } + start := lst.Front() + nxt := start.Next() + b.ResetTimer() + for i := 0; i < b.N; i++ { + start.Removed() + tmp := nxt + nxt = nxt.Next() + start = tmp + } +} + +func BenchmarkPushBack(b *testing.B) { + lst := New() + b.ResetTimer() + for i := 0; i < b.N; i++ { + lst.PushBack(i) + } +} diff --git a/libs/clist/clist.go b/libs/clist/clist.go new file mode 100644 index 0000000..b2e1d78 --- /dev/null +++ b/libs/clist/clist.go @@ -0,0 +1,407 @@ +package clist + +/* + +The purpose of CList is to provide a goroutine-safe linked-list. +This list can be traversed concurrently by any number of goroutines. +However, removed CElements cannot be added back. +NOTE: Not all methods of container/list are (yet) implemented. +NOTE: Removed elements need to DetachPrev or DetachNext consistently +to ensure garbage collection of removed elements. + +*/ + +import ( + "fmt" + "sync" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// MaxLength is the max allowed number of elements a linked list is +// allowed to contain. +// If more elements are pushed to the list it will panic. +const MaxLength = int(^uint(0) >> 1) + +/* +CElement is an element of a linked-list +Traversal from a CElement is goroutine-safe. + +We can't avoid using WaitGroups or for-loops given the documentation +spec without re-implementing the primitives that already exist in +golang/sync. Notice that WaitGroup allows many go-routines to be +simultaneously released, which is what we want. Mutex doesn't do +this. RWMutex does this, but it's clumsy to use in the way that a +WaitGroup would be used -- and we'd end up having two RWMutex's for +prev/next each, which is doubly confusing. + +sync.Cond would be sort-of useful, but we don't need a write-lock in +the for-loop. Use sync.Cond when you need serial access to the +"condition". In our case our condition is if `next != nil || removed`, +and there's no reason to serialize that condition for goroutines +waiting on NextWait() (since it's just a read operation). +*/ +type CElement struct { + mtx cmtsync.RWMutex + prev *CElement + prevWg *sync.WaitGroup + prevWaitCh chan struct{} + next *CElement + nextWg *sync.WaitGroup + nextWaitCh chan struct{} + removed bool + + Value interface{} // immutable +} + +// Blocking implementation of Next(). +// May return nil iff CElement was tail and got removed. +func (e *CElement) NextWait() *CElement { + for { + e.mtx.RLock() + next := e.next + nextWg := e.nextWg + removed := e.removed + e.mtx.RUnlock() + + if next != nil || removed { + return next + } + + nextWg.Wait() + // e.next doesn't necessarily exist here. + // That's why we need to continue a for-loop. + } +} + +// Blocking implementation of Prev(). +// May return nil iff CElement was head and got removed. +func (e *CElement) PrevWait() *CElement { + for { + e.mtx.RLock() + prev := e.prev + prevWg := e.prevWg + removed := e.removed + e.mtx.RUnlock() + + if prev != nil || removed { + return prev + } + + prevWg.Wait() + } +} + +// PrevWaitChan can be used to wait until Prev becomes not nil. Once it does, +// channel will be closed. +func (e *CElement) PrevWaitChan() <-chan struct{} { + e.mtx.RLock() + defer e.mtx.RUnlock() + + return e.prevWaitCh +} + +// NextWaitChan can be used to wait until Next becomes not nil. Once it does, +// channel will be closed. +func (e *CElement) NextWaitChan() <-chan struct{} { + e.mtx.RLock() + defer e.mtx.RUnlock() + + return e.nextWaitCh +} + +// Nonblocking, may return nil if at the end. +func (e *CElement) Next() *CElement { + e.mtx.RLock() + val := e.next + e.mtx.RUnlock() + return val +} + +// Nonblocking, may return nil if at the end. +func (e *CElement) Prev() *CElement { + e.mtx.RLock() + prev := e.prev + e.mtx.RUnlock() + return prev +} + +func (e *CElement) Removed() bool { + e.mtx.RLock() + isRemoved := e.removed + e.mtx.RUnlock() + return isRemoved +} + +func (e *CElement) DetachNext() { + e.mtx.Lock() + if !e.removed { + e.mtx.Unlock() + panic("DetachNext() must be called after Remove(e)") + } + e.next = nil + e.mtx.Unlock() +} + +func (e *CElement) DetachPrev() { + e.mtx.Lock() + if !e.removed { + e.mtx.Unlock() + panic("DetachPrev() must be called after Remove(e)") + } + e.prev = nil + e.mtx.Unlock() +} + +// NOTE: This function needs to be safe for +// concurrent goroutines waiting on nextWg. +func (e *CElement) SetNext(newNext *CElement) { + e.mtx.Lock() + + oldNext := e.next + e.next = newNext + if oldNext != nil && newNext == nil { + // See https://golang.org/pkg/sync/: + // + // If a WaitGroup is reused to wait for several independent sets of + // events, new Add calls must happen after all previous Wait calls have + // returned. + e.nextWg = waitGroup1() // WaitGroups are difficult to re-use. + e.nextWaitCh = make(chan struct{}) + } + if oldNext == nil && newNext != nil { + e.nextWg.Done() + close(e.nextWaitCh) + } + e.mtx.Unlock() +} + +// NOTE: This function needs to be safe for +// concurrent goroutines waiting on prevWg +func (e *CElement) SetPrev(newPrev *CElement) { + e.mtx.Lock() + + oldPrev := e.prev + e.prev = newPrev + if oldPrev != nil && newPrev == nil { + e.prevWg = waitGroup1() // WaitGroups are difficult to re-use. + e.prevWaitCh = make(chan struct{}) + } + if oldPrev == nil && newPrev != nil { + e.prevWg.Done() + close(e.prevWaitCh) + } + e.mtx.Unlock() +} + +func (e *CElement) SetRemoved() { + e.mtx.Lock() + + e.removed = true + + // This wakes up anyone waiting in either direction. + if e.prev == nil { + e.prevWg.Done() + close(e.prevWaitCh) + } + if e.next == nil { + e.nextWg.Done() + close(e.nextWaitCh) + } + e.mtx.Unlock() +} + +//-------------------------------------------------------------------------------- + +// CList represents a linked list. +// The zero value for CList is an empty list ready to use. +// Operations are goroutine-safe. +// Panics if length grows beyond the max. +type CList struct { + mtx cmtsync.RWMutex + wg *sync.WaitGroup + waitCh chan struct{} + head *CElement // first element + tail *CElement // last element + curLen int // list length + maxLen int // max list length +} + +func (l *CList) Init() *CList { + l.mtx.Lock() + + l.wg = waitGroup1() + l.waitCh = make(chan struct{}) + l.head = nil + l.tail = nil + l.curLen = 0 + l.mtx.Unlock() + return l +} + +// Return CList with MaxLength. CList will panic if it goes beyond MaxLength. +func New() *CList { return newWithMax(MaxLength) } + +// Return CList with given maxLength. +// Will panic if list exceeds given maxLength. +func newWithMax(maxLength int) *CList { + l := new(CList) + l.maxLen = maxLength + return l.Init() +} + +func (l *CList) Len() int { + l.mtx.RLock() + curLen := l.curLen + l.mtx.RUnlock() + return curLen +} + +func (l *CList) Front() *CElement { + l.mtx.RLock() + head := l.head + l.mtx.RUnlock() + return head +} + +func (l *CList) FrontWait() *CElement { + // Loop until the head is non-nil else wait and try again + for { + l.mtx.RLock() + head := l.head + wg := l.wg + l.mtx.RUnlock() + + if head != nil { + return head + } + wg.Wait() + // NOTE: If you think l.head exists here, think harder. + } +} + +func (l *CList) Back() *CElement { + l.mtx.RLock() + back := l.tail + l.mtx.RUnlock() + return back +} + +func (l *CList) BackWait() *CElement { + for { + l.mtx.RLock() + tail := l.tail + wg := l.wg + l.mtx.RUnlock() + + if tail != nil { + return tail + } + wg.Wait() + // l.tail doesn't necessarily exist here. + // That's why we need to continue a for-loop. + } +} + +// WaitChan can be used to wait until Front or Back becomes not nil. Once it +// does, channel will be closed. +func (l *CList) WaitChan() <-chan struct{} { + l.mtx.Lock() + defer l.mtx.Unlock() + + return l.waitCh +} + +// Panics if list grows beyond its max length. +func (l *CList) PushBack(v interface{}) *CElement { + l.mtx.Lock() + + // Construct a new element + e := &CElement{ + prev: nil, + prevWg: waitGroup1(), + prevWaitCh: make(chan struct{}), + next: nil, + nextWg: waitGroup1(), + nextWaitCh: make(chan struct{}), + removed: false, + Value: v, + } + + // Release waiters on FrontWait/BackWait maybe + if l.curLen == 0 { + l.wg.Done() + close(l.waitCh) + } + if l.curLen >= l.maxLen { + panic(fmt.Sprintf("clist: maximum length list reached %d", l.maxLen)) + } + l.curLen++ + + // Modify the tail + if l.tail == nil { + l.head = e + l.tail = e + } else { + e.SetPrev(l.tail) // We must init e first. + l.tail.SetNext(e) // This will make e accessible. + l.tail = e // Update the list. + } + l.mtx.Unlock() + return e +} + +// CONTRACT: Caller must call e.DetachPrev() and/or e.DetachNext() to avoid memory leaks. +// NOTE: As per the contract of CList, removed elements cannot be added back. +func (l *CList) Remove(e *CElement) interface{} { + l.mtx.Lock() + + prev := e.Prev() + next := e.Next() + + if l.head == nil || l.tail == nil { + l.mtx.Unlock() + panic("Remove(e) on empty CList") + } + if prev == nil && l.head != e { + l.mtx.Unlock() + panic("Remove(e) with false head") + } + if next == nil && l.tail != e { + l.mtx.Unlock() + panic("Remove(e) with false tail") + } + + // If we're removing the only item, make CList FrontWait/BackWait wait. + if l.curLen == 1 { + l.wg = waitGroup1() // WaitGroups are difficult to re-use. + l.waitCh = make(chan struct{}) + } + + // Update l.len + l.curLen-- + + // Connect next/prev and set head/tail + if prev == nil { + l.head = next + } else { + prev.SetNext(next) + } + if next == nil { + l.tail = prev + } else { + next.SetPrev(prev) + } + + // Set .Done() on e, otherwise waiters will wait forever. + e.SetRemoved() + + l.mtx.Unlock() + return e.Value +} + +func waitGroup1() (wg *sync.WaitGroup) { + wg = &sync.WaitGroup{} + wg.Add(1) + return +} diff --git a/libs/clist/clist_test.go b/libs/clist/clist_test.go new file mode 100644 index 0000000..a5cd42f --- /dev/null +++ b/libs/clist/clist_test.go @@ -0,0 +1,314 @@ +package clist + +import ( + "fmt" + "runtime" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func TestPanicOnMaxLength(t *testing.T) { + maxLength := 1000 + + l := newWithMax(maxLength) + for i := 0; i < maxLength; i++ { + l.PushBack(1) + } + assert.Panics(t, func() { + l.PushBack(1) + }) +} + +func TestSmall(t *testing.T) { + l := New() + el1 := l.PushBack(1) + el2 := l.PushBack(2) + el3 := l.PushBack(3) + if l.Len() != 3 { + t.Error("Expected len 3, got ", l.Len()) + } + + // fmt.Printf("%p %v\n", el1, el1) + // fmt.Printf("%p %v\n", el2, el2) + // fmt.Printf("%p %v\n", el3, el3) + + r1 := l.Remove(el1) + + // fmt.Printf("%p %v\n", el1, el1) + // fmt.Printf("%p %v\n", el2, el2) + // fmt.Printf("%p %v\n", el3, el3) + + r2 := l.Remove(el2) + + // fmt.Printf("%p %v\n", el1, el1) + // fmt.Printf("%p %v\n", el2, el2) + // fmt.Printf("%p %v\n", el3, el3) + + r3 := l.Remove(el3) + + if r1 != 1 { + t.Error("Expected 1, got ", r1) + } + if r2 != 2 { + t.Error("Expected 2, got ", r2) + } + if r3 != 3 { + t.Error("Expected 3, got ", r3) + } + if l.Len() != 0 { + t.Error("Expected len 0, got ", l.Len()) + } + +} + +// This test is quite hacky because it relies on SetFinalizer +// which isn't guaranteed to run at all. +// +//nolint:unused,deadcode +func _TestGCFifo(t *testing.T) { + if runtime.GOARCH != "amd64" { + t.Skipf("Skipping on non-amd64 machine") + } + + const numElements = 1000000 + l := New() + gcCount := new(uint64) + + // SetFinalizer doesn't work well with circular structures, + // so we construct a trivial non-circular structure to + // track. + type value struct { + Int int + } + done := make(chan struct{}) + + for i := 0; i < numElements; i++ { + v := new(value) + v.Int = i + l.PushBack(v) + runtime.SetFinalizer(v, func(v *value) { + atomic.AddUint64(gcCount, 1) + }) + } + + for el := l.Front(); el != nil; { + l.Remove(el) + // oldEl := el + el = el.Next() + // oldEl.DetachPrev() + // oldEl.DetachNext() + } + + runtime.GC() + time.Sleep(time.Second * 3) + runtime.GC() + time.Sleep(time.Second * 3) + _ = done + + if *gcCount != numElements { + t.Errorf("expected gcCount to be %v, got %v", numElements, + *gcCount) + } +} + +// This test is quite hacky because it relies on SetFinalizer +// which isn't guaranteed to run at all. +// +//nolint:unused,deadcode +func _TestGCRandom(t *testing.T) { + if runtime.GOARCH != "amd64" { + t.Skipf("Skipping on non-amd64 machine") + } + + const numElements = 1000000 + l := New() + gcCount := 0 + + // SetFinalizer doesn't work well with circular structures, + // so we construct a trivial non-circular structure to + // track. + type value struct { + Int int + } + + for i := 0; i < numElements; i++ { + v := new(value) + v.Int = i + l.PushBack(v) + runtime.SetFinalizer(v, func(v *value) { + gcCount++ + }) + } + + els := make([]*CElement, 0, numElements) + for el := l.Front(); el != nil; el = el.Next() { + els = append(els, el) + } + + for _, i := range cmtrand.Perm(numElements) { + el := els[i] + l.Remove(el) + _ = el.Next() + } + + runtime.GC() + time.Sleep(time.Second * 3) + + if gcCount != numElements { + t.Errorf("expected gcCount to be %v, got %v", numElements, + gcCount) + } +} + +func TestScanRightDeleteRandom(t *testing.T) { + + const numElements = 1000 + const numTimes = 100 + const numScanners = 10 + + l := New() + stop := make(chan struct{}) + + els := make([]*CElement, numElements) + for i := 0; i < numElements; i++ { + el := l.PushBack(i) + els[i] = el + } + + // Launch scanner routines that will rapidly iterate over elements. + for i := 0; i < numScanners; i++ { + go func(scannerID int) { + var el *CElement + restartCounter := 0 + counter := 0 + FOR_LOOP: + for { + select { + case <-stop: + fmt.Println("stopped") + break FOR_LOOP + default: + } + if el == nil { + el = l.FrontWait() + restartCounter++ + } + el = el.Next() + counter++ + } + fmt.Printf("Scanner %v restartCounter: %v counter: %v\n", scannerID, restartCounter, counter) + }(i) + } + + // Remove an element, push back an element. + for i := 0; i < numTimes; i++ { + // Pick an element to remove + rmElIdx := cmtrand.Intn(len(els)) + rmEl := els[rmElIdx] + + // Remove it + l.Remove(rmEl) + // fmt.Print(".") + + // Insert a new element + newEl := l.PushBack(-1*i - 1) + els[rmElIdx] = newEl + + if i%100000 == 0 { + fmt.Printf("Pushed %vK elements so far...\n", i/1000) + } + + } + + // Stop scanners + close(stop) + // time.Sleep(time.Second * 1) + + // And remove all the elements. + for el := l.Front(); el != nil; el = el.Next() { + l.Remove(el) + } + if l.Len() != 0 { + t.Fatal("Failed to remove all elements from CList") + } +} + +func TestWaitChan(t *testing.T) { + l := New() + ch := l.WaitChan() + + // 1) add one element to an empty list + go l.PushBack(1) + <-ch + + // 2) and remove it + el := l.Front() + v := l.Remove(el) + if v != 1 { + t.Fatal("where is 1 coming from?") + } + + // 3) test iterating forward and waiting for Next (NextWaitChan and Next) + el = l.PushBack(0) + + done := make(chan struct{}) + pushed := 0 + go func() { + for i := 1; i < 100; i++ { + l.PushBack(i) + pushed++ + time.Sleep(time.Duration(cmtrand.Intn(25)) * time.Millisecond) + } + // apply a deterministic pause so the counter has time to catch up + time.Sleep(25 * time.Millisecond) + close(done) + }() + + next := el + seen := 0 +FOR_LOOP: + for { + select { + case <-next.NextWaitChan(): + next = next.Next() + seen++ + if next == nil { + t.Fatal("Next should not be nil when waiting on NextWaitChan") + } + case <-done: + break FOR_LOOP + case <-time.After(10 * time.Second): + t.Fatal("max execution time") + } + } + + if pushed != seen { + t.Fatalf("number of pushed items (%d) not equal to number of seen items (%d)", pushed, seen) + } + + // 4) test iterating backwards (PrevWaitChan and Prev) + prev := next + seen = 0 +FOR_LOOP2: + for { + select { + case <-prev.PrevWaitChan(): + prev = prev.Prev() + seen++ + if prev == nil { + t.Fatal("expected PrevWaitChan to block forever on nil when reached first elem") + } + case <-time.After(3 * time.Second): + break FOR_LOOP2 + } + } + + if pushed != seen { + t.Fatalf("number of pushed items (%d) not equal to number of seen items (%d)", pushed, seen) + } +} diff --git a/libs/cmap/cmap.go b/libs/cmap/cmap.go new file mode 100644 index 0000000..69e6b8e --- /dev/null +++ b/libs/cmap/cmap.go @@ -0,0 +1,77 @@ +package cmap + +import ( + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// CMap is a goroutine-safe map +type CMap struct { + m map[string]interface{} + l cmtsync.Mutex +} + +func NewCMap() *CMap { + return &CMap{ + m: make(map[string]interface{}), + } +} + +func (cm *CMap) Set(key string, value interface{}) { + cm.l.Lock() + cm.m[key] = value + cm.l.Unlock() +} + +func (cm *CMap) Get(key string) interface{} { + cm.l.Lock() + val := cm.m[key] + cm.l.Unlock() + return val +} + +func (cm *CMap) Has(key string) bool { + cm.l.Lock() + _, ok := cm.m[key] + cm.l.Unlock() + return ok +} + +func (cm *CMap) Delete(key string) { + cm.l.Lock() + delete(cm.m, key) + cm.l.Unlock() +} + +func (cm *CMap) Size() int { + cm.l.Lock() + size := len(cm.m) + cm.l.Unlock() + return size +} + +func (cm *CMap) Clear() { + cm.l.Lock() + cm.m = make(map[string]interface{}) + cm.l.Unlock() +} + +func (cm *CMap) Keys() []string { + cm.l.Lock() + + keys := make([]string, 0, len(cm.m)) + for k := range cm.m { + keys = append(keys, k) + } + cm.l.Unlock() + return keys +} + +func (cm *CMap) Values() []interface{} { + cm.l.Lock() + items := make([]interface{}, 0, len(cm.m)) + for _, v := range cm.m { + items = append(items, v) + } + cm.l.Unlock() + return items +} diff --git a/libs/cmap/cmap_test.go b/libs/cmap/cmap_test.go new file mode 100644 index 0000000..69fffc5 --- /dev/null +++ b/libs/cmap/cmap_test.go @@ -0,0 +1,69 @@ +package cmap + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIterateKeysWithValues(t *testing.T) { + cmap := NewCMap() + + for i := 1; i <= 10; i++ { + cmap.Set(fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i)) + } + + // Testing size + assert.Equal(t, 10, cmap.Size()) + assert.Equal(t, 10, len(cmap.Keys())) + assert.Equal(t, 10, len(cmap.Values())) + + // Iterating Keys, checking for matching Value + for _, key := range cmap.Keys() { + val := strings.ReplaceAll(key, "key", "value") + assert.Equal(t, val, cmap.Get(key)) + } + + // Test if all keys are within []Keys() + keys := cmap.Keys() + for i := 1; i <= 10; i++ { + assert.Contains(t, keys, fmt.Sprintf("key%d", i), "cmap.Keys() should contain key") + } + + // Delete 1 Key + cmap.Delete("key1") + + assert.NotEqual( + t, + len(keys), + len(cmap.Keys()), + "[]keys and []Keys() should not be equal, they are copies, one item was removed", + ) +} + +func TestContains(t *testing.T) { + cmap := NewCMap() + + cmap.Set("key1", "value1") + + // Test for known values + assert.True(t, cmap.Has("key1")) + assert.Equal(t, "value1", cmap.Get("key1")) + + // Test for unknown values + assert.False(t, cmap.Has("key2")) + assert.Nil(t, cmap.Get("key2")) +} + +func BenchmarkCMapHas(b *testing.B) { + m := NewCMap() + for i := 0; i < 1000; i++ { + m.Set(string(rune(i)), i) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.Has(string(rune(i))) + } +} diff --git a/libs/events/Makefile b/libs/events/Makefile new file mode 100644 index 0000000..3331708 --- /dev/null +++ b/libs/events/Makefile @@ -0,0 +1,9 @@ +.PHONY: docs +REPO:=github.com/cometbft/cometbft/libs/events + +docs: + @go get github.com/davecheney/godoc2md + godoc2md $(REPO) > README.md + +test: + go test -v ./... diff --git a/libs/events/README.md b/libs/events/README.md new file mode 100644 index 0000000..c9df4be --- /dev/null +++ b/libs/events/README.md @@ -0,0 +1,186 @@ + + +# events + +`import "github.com/cometbft/cometbft/libs/events"` + +## Overview + +Pub-Sub in go with event caching + +## Index + +* [type EventCache](#type-eventcache) + * [func NewEventCache(evsw Fireable) *EventCache](#func-neweventcache) + * [func (evc *EventCache) FireEvent(event string, data EventData)](#func-eventcache-fireevent) + * [func (evc *EventCache) Flush()](#func-eventcache-flush) +* [type EventCallback](#type-eventcallback) +* [type EventData](#type-eventdata) +* [type EventSwitch](#type-eventswitch) + * [func NewEventSwitch() EventSwitch](#func-neweventswitch) +* [type Eventable](#type-eventable) +* [type Fireable](#type-fireable) + + +### Package files + +[event_cache.go](./event_cache.go) [events.go](./events.go) + + +## Type [EventCache](./event_cache.go?s=116:179#L5) + +``` go +type EventCache struct { + // contains filtered or unexported fields +} +``` + +An EventCache buffers events for a Fireable +All events are cached. Filtering happens on Flush + + + + + + + +### func [NewEventCache](./event_cache.go?s=239:284#L11) + +``` go +func NewEventCache(evsw Fireable) *EventCache +``` + +Create a new EventCache with an EventSwitch as backend + + + + + +### func (\*EventCache) [FireEvent](./event_cache.go?s=449:511#L24) + +``` go +func (evc *EventCache) FireEvent(event string, data EventData) +``` + +Cache an event to be fired upon finality. + + + + +### func (\*EventCache) [Flush](./event_cache.go?s=735:765#L31) + +``` go +func (evc *EventCache) Flush() +``` + +Fire events by running evsw.FireEvent on all cached events. Blocks. +Clears cached events + + + + +## Type [EventCallback](./events.go?s=4201:4240#L185) + +``` go +type EventCallback func(data EventData) +``` + + + + + + + + + +## Type [EventData](./events.go?s=243:294#L14) + +``` go +type EventData interface { +} +``` + +Generic event data can be typed and registered with [tendermint/go-amino](https://github.com/tendermint/go-amino) +via concrete implementation of this interface + + + + + + + + + + +## Type [EventSwitch](./events.go?s=560:771#L29) + +``` go +type EventSwitch interface { + service.Service + Fireable + + AddListenerForEvent(listenerID, event string, cb EventCallback) + RemoveListenerForEvent(event string, listenerID string) + RemoveListener(listenerID string) +} +``` + + + + + + +### func [NewEventSwitch](./events.go?s=917:950#L46) + +``` go +func NewEventSwitch() EventSwitch +``` + + + + +## Type [Eventable](./events.go?s=378:440#L20) + +``` go +type Eventable interface { + SetEventSwitch(evsw EventSwitch) +} +``` + +reactors and other modules should export +this interface to become eventable + + + + + + + + + + +## Type [Fireable](./events.go?s=490:558#L25) + +``` go +type Fireable interface { + FireEvent(event string, data EventData) +} +``` + +an event switch or cache implements fireable + + + + + + + + + + + + + + +- - - +Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) diff --git a/libs/events/event_cache.go b/libs/events/event_cache.go new file mode 100644 index 0000000..e74bc5b --- /dev/null +++ b/libs/events/event_cache.go @@ -0,0 +1,37 @@ +package events + +// An EventCache buffers events for a Fireable +// All events are cached. Filtering happens on Flush +type EventCache struct { + evsw Fireable + events []eventInfo +} + +// Create a new EventCache with an EventSwitch as backend +func NewEventCache(evsw Fireable) *EventCache { + return &EventCache{ + evsw: evsw, + } +} + +// a cached event +type eventInfo struct { + event string + data EventData +} + +// Cache an event to be fired upon finality. +func (evc *EventCache) FireEvent(event string, data EventData) { + // append to list (go will grow our backing array exponentially) + evc.events = append(evc.events, eventInfo{event, data}) +} + +// Fire events by running evsw.FireEvent on all cached events. Blocks. +// Clears cached events +func (evc *EventCache) Flush() { + for _, ei := range evc.events { + evc.evsw.FireEvent(ei.event, ei.data) + } + // Clear the buffer, since we only add to it with append it's safe to just set it to nil and maybe safe an allocation + evc.events = nil +} diff --git a/libs/events/event_cache_test.go b/libs/events/event_cache_test.go new file mode 100644 index 0000000..3843fea --- /dev/null +++ b/libs/events/event_cache_test.go @@ -0,0 +1,42 @@ +package events + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEventCache_Flush(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + + err = evsw.AddListenerForEvent("nothingness", "", func(data EventData) { + // Check we are not initializing an empty buffer full + // of zeroed eventInfos in the EventCache + require.FailNow(t, "We should never receive a message on this switch since none are fired") + }) + require.NoError(t, err) + + evc := NewEventCache(evsw) + evc.Flush() + // Check after reset + evc.Flush() + fail := true + pass := false + err = evsw.AddListenerForEvent("somethingness", "something", func(data EventData) { + if fail { + require.FailNow(t, "Shouldn't see a message until flushed") + } + pass = true + }) + require.NoError(t, err) + + evc.FireEvent("something", struct{ int }{1}) + evc.FireEvent("something", struct{ int }{2}) + evc.FireEvent("something", struct{ int }{3}) + fail = false + evc.Flush() + assert.True(t, pass) +} diff --git a/libs/events/events.go b/libs/events/events.go new file mode 100644 index 0000000..d4e41c7 --- /dev/null +++ b/libs/events/events.go @@ -0,0 +1,247 @@ +// Package events - Pub-Sub in go with event caching +package events + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// ErrListenerWasRemoved is returned by AddEvent if the listener was removed. +type ErrListenerWasRemoved struct { + listenerID string +} + +// Error implements the error interface. +func (e ErrListenerWasRemoved) Error() string { + return fmt.Sprintf("listener #%s was removed", e.listenerID) +} + +// EventData is a generic event data can be typed and registered with +// tendermint/go-amino via concrete implementation of this interface. +type EventData interface{} + +// Eventable is the interface reactors and other modules must export to become +// eventable. +type Eventable interface { + SetEventSwitch(evsw EventSwitch) +} + +// Fireable is the interface that wraps the FireEvent method. +// +// FireEvent fires an event with the given name and data. +type Fireable interface { + FireEvent(event string, data EventData) +} + +// EventSwitch is the interface for synchronous pubsub, where listeners +// subscribe to certain events and, when an event is fired (see Fireable), +// notified via a callback function. +// +// Listeners are added by calling AddListenerForEvent function. +// They can be removed by calling either RemoveListenerForEvent or +// RemoveListener (for all events). +type EventSwitch interface { + service.Service + Fireable + + AddListenerForEvent(listenerID, event string, cb EventCallback) error + RemoveListenerForEvent(event string, listenerID string) + RemoveListener(listenerID string) +} + +type eventSwitch struct { + service.BaseService + + mtx cmtsync.RWMutex + eventCells map[string]*eventCell + listeners map[string]*eventListener +} + +func NewEventSwitch() EventSwitch { + evsw := &eventSwitch{ + eventCells: make(map[string]*eventCell), + listeners: make(map[string]*eventListener), + } + evsw.BaseService = *service.NewBaseService(nil, "EventSwitch", evsw) + return evsw +} + +func (evsw *eventSwitch) OnStart() error { + return nil +} + +func (evsw *eventSwitch) OnStop() {} + +func (evsw *eventSwitch) AddListenerForEvent(listenerID, event string, cb EventCallback) error { + // Get/Create eventCell and listener. + evsw.mtx.Lock() + eventCell := evsw.eventCells[event] + if eventCell == nil { + eventCell = newEventCell() + evsw.eventCells[event] = eventCell + } + listener := evsw.listeners[listenerID] + if listener == nil { + listener = newEventListener(listenerID) + evsw.listeners[listenerID] = listener + } + evsw.mtx.Unlock() + + // Add event and listener. + if err := listener.AddEvent(event); err != nil { + return err + } + eventCell.AddListener(listenerID, cb) + + return nil +} + +func (evsw *eventSwitch) RemoveListener(listenerID string) { + // Get and remove listener. + evsw.mtx.RLock() + listener := evsw.listeners[listenerID] + evsw.mtx.RUnlock() + if listener == nil { + return + } + + evsw.mtx.Lock() + delete(evsw.listeners, listenerID) + evsw.mtx.Unlock() + + // Remove callback for each event. + listener.SetRemoved() + for _, event := range listener.GetEvents() { + evsw.RemoveListenerForEvent(event, listenerID) + } +} + +func (evsw *eventSwitch) RemoveListenerForEvent(event string, listenerID string) { + // Get eventCell + evsw.mtx.Lock() + eventCell := evsw.eventCells[event] + evsw.mtx.Unlock() + + if eventCell == nil { + return + } + + // Remove listenerID from eventCell + numListeners := eventCell.RemoveListener(listenerID) + + // Maybe garbage collect eventCell. + if numListeners == 0 { + // Lock again and double check. + evsw.mtx.Lock() // OUTER LOCK + eventCell.mtx.Lock() // INNER LOCK + if len(eventCell.listeners) == 0 { + delete(evsw.eventCells, event) + } + eventCell.mtx.Unlock() // INNER LOCK + evsw.mtx.Unlock() // OUTER LOCK + } +} + +func (evsw *eventSwitch) FireEvent(event string, data EventData) { + // Get the eventCell + evsw.mtx.RLock() + eventCell := evsw.eventCells[event] + evsw.mtx.RUnlock() + + if eventCell == nil { + return + } + + // Fire event for all listeners in eventCell + eventCell.FireEvent(data) +} + +//----------------------------------------------------------------------------- + +// eventCell handles keeping track of listener callbacks for a given event. +type eventCell struct { + mtx cmtsync.RWMutex + listeners map[string]EventCallback +} + +func newEventCell() *eventCell { + return &eventCell{ + listeners: make(map[string]EventCallback), + } +} + +func (cell *eventCell) AddListener(listenerID string, cb EventCallback) { + cell.mtx.Lock() + cell.listeners[listenerID] = cb + cell.mtx.Unlock() +} + +func (cell *eventCell) RemoveListener(listenerID string) int { + cell.mtx.Lock() + delete(cell.listeners, listenerID) + numListeners := len(cell.listeners) + cell.mtx.Unlock() + return numListeners +} + +func (cell *eventCell) FireEvent(data EventData) { + cell.mtx.RLock() + eventCallbacks := make([]EventCallback, 0, len(cell.listeners)) + for _, cb := range cell.listeners { + eventCallbacks = append(eventCallbacks, cb) + } + cell.mtx.RUnlock() + + for _, cb := range eventCallbacks { + cb(data) + } +} + +//----------------------------------------------------------------------------- + +type EventCallback func(data EventData) + +type eventListener struct { + id string + + mtx cmtsync.RWMutex + removed bool + events []string +} + +func newEventListener(id string) *eventListener { + return &eventListener{ + id: id, + removed: false, + events: nil, + } +} + +func (evl *eventListener) AddEvent(event string) error { + evl.mtx.Lock() + + if evl.removed { + evl.mtx.Unlock() + return ErrListenerWasRemoved{listenerID: evl.id} + } + + evl.events = append(evl.events, event) + evl.mtx.Unlock() + return nil +} + +func (evl *eventListener) GetEvents() []string { + evl.mtx.RLock() + events := make([]string, len(evl.events)) + copy(events, evl.events) + evl.mtx.RUnlock() + return events +} + +func (evl *eventListener) SetRemoved() { + evl.mtx.Lock() + evl.removed = true + evl.mtx.Unlock() +} diff --git a/libs/events/events_test.go b/libs/events/events_test.go new file mode 100644 index 0000000..c54eb5d --- /dev/null +++ b/libs/events/events_test.go @@ -0,0 +1,487 @@ +package events + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/rand" +) + +// TestAddListenerForEventFireOnce sets up an EventSwitch, subscribes a single +// listener to an event, and sends a string "data". +func TestAddListenerForEventFireOnce(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + messages := make(chan EventData) + err = evsw.AddListenerForEvent("listener", "event", + func(data EventData) { + // test there's no deadlock if we remove the listener inside a callback + evsw.RemoveListener("listener") + messages <- data + }) + require.NoError(t, err) + go evsw.FireEvent("event", "data") + received := <-messages + if received != "data" { + t.Errorf("message received does not match: %v", received) + } +} + +// TestAddListenerForEventFireMany sets up an EventSwitch, subscribes a single +// listener to an event, and sends a thousand integers. +func TestAddListenerForEventFireMany(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + doneSum := make(chan uint64) + doneSending := make(chan uint64) + numbers := make(chan uint64, 4) + // subscribe one listener for one event + err = evsw.AddListenerForEvent("listener", "event", + func(data EventData) { + numbers <- data.(uint64) + }) + require.NoError(t, err) + // collect received events + go sumReceivedNumbers(numbers, doneSum) + // go fire events + go fireEvents(evsw, "event", doneSending, uint64(1)) + checkSum := <-doneSending + close(numbers) + eventSum := <-doneSum + if checkSum != eventSum { + t.Errorf("not all messages sent were received.\n") + } +} + +// TestAddListenerForDifferentEvents sets up an EventSwitch, subscribes a single +// listener to three different events and sends a thousand integers for each +// of the three events. +func TestAddListenerForDifferentEvents(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + doneSum := make(chan uint64) + doneSending1 := make(chan uint64) + doneSending2 := make(chan uint64) + doneSending3 := make(chan uint64) + numbers := make(chan uint64, 4) + // subscribe one listener to three events + err = evsw.AddListenerForEvent("listener", "event1", + func(data EventData) { + numbers <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener", "event2", + func(data EventData) { + numbers <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener", "event3", + func(data EventData) { + numbers <- data.(uint64) + }) + require.NoError(t, err) + // collect received events + go sumReceivedNumbers(numbers, doneSum) + // go fire events + go fireEvents(evsw, "event1", doneSending1, uint64(1)) + go fireEvents(evsw, "event2", doneSending2, uint64(1)) + go fireEvents(evsw, "event3", doneSending3, uint64(1)) + var checkSum uint64 + checkSum += <-doneSending1 + checkSum += <-doneSending2 + checkSum += <-doneSending3 + close(numbers) + eventSum := <-doneSum + if checkSum != eventSum { + t.Errorf("not all messages sent were received.\n") + } +} + +// TestAddDifferentListenerForDifferentEvents sets up an EventSwitch, +// subscribes a first listener to three events, and subscribes a second +// listener to two of those three events, and then sends a thousand integers +// for each of the three events. +func TestAddDifferentListenerForDifferentEvents(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + doneSum1 := make(chan uint64) + doneSum2 := make(chan uint64) + doneSending1 := make(chan uint64) + doneSending2 := make(chan uint64) + doneSending3 := make(chan uint64) + numbers1 := make(chan uint64, 4) + numbers2 := make(chan uint64, 4) + // subscribe two listener to three events + err = evsw.AddListenerForEvent("listener1", "event1", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener1", "event2", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener1", "event3", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener2", "event2", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener2", "event3", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + // collect received events for listener1 + go sumReceivedNumbers(numbers1, doneSum1) + // collect received events for listener2 + go sumReceivedNumbers(numbers2, doneSum2) + // go fire events + go fireEvents(evsw, "event1", doneSending1, uint64(1)) + go fireEvents(evsw, "event2", doneSending2, uint64(1001)) + go fireEvents(evsw, "event3", doneSending3, uint64(2001)) + checkSumEvent1 := <-doneSending1 + checkSumEvent2 := <-doneSending2 + checkSumEvent3 := <-doneSending3 + checkSum1 := checkSumEvent1 + checkSumEvent2 + checkSumEvent3 + checkSum2 := checkSumEvent2 + checkSumEvent3 + close(numbers1) + close(numbers2) + eventSum1 := <-doneSum1 + eventSum2 := <-doneSum2 + if checkSum1 != eventSum1 || + checkSum2 != eventSum2 { + t.Errorf("not all messages sent were received for different listeners to different events.\n") + } +} + +func TestAddAndRemoveListenerConcurrency(t *testing.T) { + var ( + stopInputEvent = false + roundCount = 2000 + ) + + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + done1 := make(chan struct{}) + done2 := make(chan struct{}) + + // Must be executed concurrently to uncover the data race. + // 1. RemoveListener + go func() { + defer close(done1) + for i := 0; i < roundCount; i++ { + evsw.RemoveListener("listener") + } + }() + + // 2. AddListenerForEvent + go func() { + defer close(done2) + for i := 0; i < roundCount; i++ { + index := i + // we explicitly ignore errors here, since the listener will sometimes be removed + // (that's what we're testing) + _ = evsw.AddListenerForEvent("listener", fmt.Sprintf("event%d", index), + func(data EventData) { + t.Errorf("should not run callback for %d.\n", index) + stopInputEvent = true + }) + } + }() + + <-done1 + <-done2 + + evsw.RemoveListener("listener") // remove the last listener + + for i := 0; i < roundCount && !stopInputEvent; i++ { + evsw.FireEvent(fmt.Sprintf("event%d", i), uint64(1001)) + } +} + +// TestAddAndRemoveListener sets up an EventSwitch, subscribes a listener to +// two events, fires a thousand integers for the first event, then unsubscribes +// the listener and fires a thousand integers for the second event. +func TestAddAndRemoveListener(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + doneSum1 := make(chan uint64) + doneSum2 := make(chan uint64) + doneSending1 := make(chan uint64) + doneSending2 := make(chan uint64) + numbers1 := make(chan uint64, 4) + numbers2 := make(chan uint64, 4) + // subscribe two listener to three events + err = evsw.AddListenerForEvent("listener", "event1", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener", "event2", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + // collect received events for event1 + go sumReceivedNumbers(numbers1, doneSum1) + // collect received events for event2 + go sumReceivedNumbers(numbers2, doneSum2) + // go fire events + go fireEvents(evsw, "event1", doneSending1, uint64(1)) + checkSumEvent1 := <-doneSending1 + // after sending all event1, unsubscribe for all events + evsw.RemoveListener("listener") + go fireEvents(evsw, "event2", doneSending2, uint64(1001)) + checkSumEvent2 := <-doneSending2 + close(numbers1) + close(numbers2) + eventSum1 := <-doneSum1 + eventSum2 := <-doneSum2 + if checkSumEvent1 != eventSum1 || + // correct value asserted by preceding tests, suffices to be non-zero + checkSumEvent2 == uint64(0) || + eventSum2 != uint64(0) { + t.Errorf("not all messages sent were received or unsubscription did not register.\n") + } +} + +// TestRemoveListener does basic tests on adding and removing +func TestRemoveListener(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + count := 10 + sum1, sum2 := 0, 0 + // add some listeners and make sure they work + err = evsw.AddListenerForEvent("listener", "event1", + func(data EventData) { + sum1++ + }) + require.NoError(t, err) + + err = evsw.AddListenerForEvent("listener", "event2", + func(data EventData) { + sum2++ + }) + require.NoError(t, err) + + for i := 0; i < count; i++ { + evsw.FireEvent("event1", true) + evsw.FireEvent("event2", true) + } + assert.Equal(t, count, sum1) + assert.Equal(t, count, sum2) + + // remove one by event and make sure it is gone + evsw.RemoveListenerForEvent("event2", "listener") + for i := 0; i < count; i++ { + evsw.FireEvent("event1", true) + evsw.FireEvent("event2", true) + } + assert.Equal(t, count*2, sum1) + assert.Equal(t, count, sum2) + + // remove the listener entirely and make sure both gone + evsw.RemoveListener("listener") + for i := 0; i < count; i++ { + evsw.FireEvent("event1", true) + evsw.FireEvent("event2", true) + } + assert.Equal(t, count*2, sum1) + assert.Equal(t, count, sum2) +} + +// TestAddAndRemoveListenersAsync sets up an EventSwitch, subscribes two +// listeners to three events, and fires a thousand integers for each event. +// These two listeners serve as the baseline validation while other listeners +// are randomly subscribed and unsubscribed. +// More precisely it randomly subscribes new listeners (different from the first +// two listeners) to one of these three events. At the same time it starts +// randomly unsubscribing these additional listeners from all events they are +// at that point subscribed to. +// NOTE: it is important to run this test with race conditions tracking on, +// `go test -race`, to examine for possible race conditions. +func TestRemoveListenersAsync(t *testing.T) { + evsw := NewEventSwitch() + err := evsw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := evsw.Stop(); err != nil { + t.Error(err) + } + }) + + doneSum1 := make(chan uint64) + doneSum2 := make(chan uint64) + doneSending1 := make(chan uint64) + doneSending2 := make(chan uint64) + doneSending3 := make(chan uint64) + numbers1 := make(chan uint64, 4) + numbers2 := make(chan uint64, 4) + // subscribe two listener to three events + err = evsw.AddListenerForEvent("listener1", "event1", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener1", "event2", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener1", "event3", + func(data EventData) { + numbers1 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener2", "event1", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener2", "event2", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + err = evsw.AddListenerForEvent("listener2", "event3", + func(data EventData) { + numbers2 <- data.(uint64) + }) + require.NoError(t, err) + // collect received events for event1 + go sumReceivedNumbers(numbers1, doneSum1) + // collect received events for event2 + go sumReceivedNumbers(numbers2, doneSum2) + addListenersStress := func() { + r1 := rand.NewRand() + r1.Seed(time.Now().UnixNano()) + for k := uint16(0); k < 400; k++ { + listenerNumber := r1.Intn(100) + 3 + eventNumber := r1.Intn(3) + 1 + go evsw.AddListenerForEvent(fmt.Sprintf("listener%v", listenerNumber), //nolint:errcheck // ignore for tests + fmt.Sprintf("event%v", eventNumber), + func(_ EventData) {}) + } + } + removeListenersStress := func() { + r2 := rand.NewRand() + r2.Seed(time.Now().UnixNano()) + for k := uint16(0); k < 80; k++ { + listenerNumber := r2.Intn(100) + 3 + go evsw.RemoveListener(fmt.Sprintf("listener%v", listenerNumber)) + } + } + addListenersStress() + // go fire events + go fireEvents(evsw, "event1", doneSending1, uint64(1)) + removeListenersStress() + go fireEvents(evsw, "event2", doneSending2, uint64(1001)) + go fireEvents(evsw, "event3", doneSending3, uint64(2001)) + checkSumEvent1 := <-doneSending1 + checkSumEvent2 := <-doneSending2 + checkSumEvent3 := <-doneSending3 + checkSum := checkSumEvent1 + checkSumEvent2 + checkSumEvent3 + close(numbers1) + close(numbers2) + eventSum1 := <-doneSum1 + eventSum2 := <-doneSum2 + if checkSum != eventSum1 || + checkSum != eventSum2 { + t.Errorf("not all messages sent were received.\n") + } +} + +//------------------------------------------------------------------------------ +// Helper functions + +// sumReceivedNumbers takes two channels and adds all numbers received +// until the receiving channel `numbers` is closed; it then sends the sum +// on `doneSum` and closes that channel. Expected to be run in a go-routine. +func sumReceivedNumbers(numbers, doneSum chan uint64) { + var sum uint64 + for { + j, more := <-numbers + sum += j + if !more { + doneSum <- sum + close(doneSum) + return + } + } +} + +// fireEvents takes an EventSwitch and fires a thousand integers under +// a given `event` with the integers mootonically increasing from `offset` +// to `offset` + 999. It additionally returns the addition of all integers +// sent on `doneChan` for assertion that all events have been sent, and enabling +// the test to assert all events have also been received. +func fireEvents(evsw Fireable, event string, doneChan chan uint64, + offset uint64) { + var sentSum uint64 + for i := offset; i <= offset+uint64(999); i++ { + sentSum += i + evsw.FireEvent(event, i) + } + doneChan <- sentSum + close(doneChan) +} diff --git a/libs/fail/fail.go b/libs/fail/fail.go new file mode 100644 index 0000000..6b3a33d --- /dev/null +++ b/libs/fail/fail.go @@ -0,0 +1,47 @@ +package fail + +import ( + "fmt" + "os" + "strconv" +) + +func envSet() int { + callIndexToFailS := os.Getenv("FAIL_TEST_INDEX") + + if callIndexToFailS == "" { + return -1 + } + + var err error + callIndexToFail, err := strconv.Atoi(callIndexToFailS) + if err != nil { + return -1 + } + + return callIndexToFail +} + +// Fail when FAIL_TEST_INDEX == callIndex +var callIndex int // indexes Fail calls + +func Fail() { + callIndexToFail := envSet() + if callIndexToFail < 0 { + return + } + + if callIndex == callIndexToFail { + Exit() + } + + callIndex++ +} + +func Exit() { + fmt.Printf("*** fail-test %d ***\n", callIndex) + os.Exit(1) + // proc, _ := os.FindProcess(os.Getpid()) + // proc.Signal(os.Interrupt) + // panic(fmt.Sprintf("*** fail-test %d ***", callIndex)) +} diff --git a/libs/flowrate/README.md b/libs/flowrate/README.md new file mode 100644 index 0000000..5f41945 --- /dev/null +++ b/libs/flowrate/README.md @@ -0,0 +1,10 @@ +Data Flow Rate Control +====================== + +To download and install this package run: + +go get github.com/mxk/go-flowrate/flowrate + +The documentation is available at: + + diff --git a/libs/flowrate/flowrate.go b/libs/flowrate/flowrate.go new file mode 100644 index 0000000..47e1948 --- /dev/null +++ b/libs/flowrate/flowrate.go @@ -0,0 +1,276 @@ +// +// Written by Maxim Khitrov (November 2012) +// + +// Package flowrate provides the tools for monitoring and limiting the flow rate +// of an arbitrary data stream. +package flowrate + +import ( + "math" + "time" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// Monitor monitors and limits the transfer rate of a data stream. +type Monitor struct { + mu cmtsync.Mutex // Mutex guarding access to all internal fields + active bool // Flag indicating an active transfer + start time.Duration // Transfer start time (clock() value) + bytes int64 // Total number of bytes transferred + samples int64 // Total number of samples taken + + rSample float64 // Most recent transfer rate sample (bytes per second) + rEMA float64 // Exponential moving average of rSample + rPeak float64 // Peak transfer rate (max of all rSamples) + rWindow float64 // rEMA window (seconds) + + sBytes int64 // Number of bytes transferred since sLast + sLast time.Duration // Most recent sample time (stop time when inactive) + sRate time.Duration // Sampling rate + + tBytes int64 // Number of bytes expected in the current transfer + tLast time.Duration // Time of the most recent transfer of at least 1 byte +} + +// New creates a new flow control monitor. Instantaneous transfer rate is +// measured and updated for each sampleRate interval. windowSize determines the +// weight of each sample in the exponential moving average (EMA) calculation. +// The exact formulas are: +// +// sampleTime = currentTime - prevSampleTime +// sampleRate = byteCount / sampleTime +// weight = 1 - exp(-sampleTime/windowSize) +// newRate = weight*sampleRate + (1-weight)*oldRate +// +// The default values for sampleRate and windowSize (if <= 0) are 100ms and 1s, +// respectively. +func New(sampleRate, windowSize time.Duration) *Monitor { + if sampleRate = clockRound(sampleRate); sampleRate <= 0 { + sampleRate = 5 * clockRate + } + if windowSize <= 0 { + windowSize = 1 * time.Second + } + now := clock() + return &Monitor{ + active: true, + start: now, + rWindow: windowSize.Seconds(), + sLast: now, + sRate: sampleRate, + tLast: now, + } +} + +// Update records the transfer of n bytes and returns n. It should be called +// after each Read/Write operation, even if n is 0. +func (m *Monitor) Update(n int) int { + m.mu.Lock() + m.update(n) + m.mu.Unlock() + return n +} + +// Hack to set the current rEMA. +func (m *Monitor) SetREMA(rEMA float64) { + m.mu.Lock() + m.rEMA = rEMA + m.samples++ + m.mu.Unlock() +} + +// IO is a convenience method intended to wrap io.Reader and io.Writer method +// execution. It calls m.Update(n) and then returns (n, err) unmodified. +func (m *Monitor) IO(n int, err error) (int, error) { + return m.Update(n), err +} + +// Done marks the transfer as finished and prevents any further updates or +// limiting. Instantaneous and current transfer rates drop to 0. Update, IO, and +// Limit methods become NOOPs. It returns the total number of bytes transferred. +func (m *Monitor) Done() int64 { + m.mu.Lock() + if now := m.update(0); m.sBytes > 0 { + m.reset(now) + } + m.active = false + m.tLast = 0 + n := m.bytes + m.mu.Unlock() + return n +} + +// timeRemLimit is the maximum Status.TimeRem value. +const timeRemLimit = 999*time.Hour + 59*time.Minute + 59*time.Second + +// Status represents the current Monitor status. All transfer rates are in bytes +// per second rounded to the nearest byte. +type Status struct { + Start time.Time // Transfer start time + Bytes int64 // Total number of bytes transferred + Samples int64 // Total number of samples taken + InstRate int64 // Instantaneous transfer rate + CurRate int64 // Current transfer rate (EMA of InstRate) + AvgRate int64 // Average transfer rate (Bytes / Duration) + PeakRate int64 // Maximum instantaneous transfer rate + BytesRem int64 // Number of bytes remaining in the transfer + Duration time.Duration // Time period covered by the statistics + Idle time.Duration // Time since the last transfer of at least 1 byte + TimeRem time.Duration // Estimated time to completion + Progress Percent // Overall transfer progress + Active bool // Flag indicating an active transfer +} + +// Status returns current transfer status information. The returned value +// becomes static after a call to Done. +func (m *Monitor) Status() Status { + m.mu.Lock() + now := m.update(0) + s := Status{ + Active: m.active, + Start: clockToTime(m.start), + Duration: m.sLast - m.start, + Idle: now - m.tLast, + Bytes: m.bytes, + Samples: m.samples, + PeakRate: round(m.rPeak), + BytesRem: m.tBytes - m.bytes, + Progress: percentOf(float64(m.bytes), float64(m.tBytes)), + } + if s.BytesRem < 0 { + s.BytesRem = 0 + } + if s.Duration > 0 { + rAvg := float64(s.Bytes) / s.Duration.Seconds() + s.AvgRate = round(rAvg) + if s.Active { + s.InstRate = round(m.rSample) + s.CurRate = round(m.rEMA) + if s.BytesRem > 0 { + if tRate := 0.8*m.rEMA + 0.2*rAvg; tRate > 0 { + ns := float64(s.BytesRem) / tRate * 1e9 + if ns > float64(timeRemLimit) { + ns = float64(timeRemLimit) + } + s.TimeRem = clockRound(time.Duration(ns)) + } + } + } + } + m.mu.Unlock() + return s +} + +// Limit restricts the instantaneous (per-sample) data flow to rate bytes per +// second. It returns the maximum number of bytes (0 <= n <= want) that may be +// transferred immediately without exceeding the limit. If block == true, the +// call blocks until n > 0. want is returned unmodified if want < 1, rate < 1, +// or the transfer is inactive (after a call to Done). +// +// At least one byte is always allowed to be transferred in any given sampling +// period. Thus, if the sampling rate is 100ms, the lowest achievable flow rate +// is 10 bytes per second. +// +// For usage examples, see the implementation of Reader and Writer in io.go. +func (m *Monitor) Limit(want int, rate int64, block bool) (n int) { + if want < 1 || rate < 1 { + return want + } + m.mu.Lock() + + // Determine the maximum number of bytes that can be sent in one sample + limit := round(float64(rate) * m.sRate.Seconds()) + if limit <= 0 { + limit = 1 + } + + // If block == true, wait until m.sBytes < limit + if now := m.update(0); block { + for m.sBytes >= limit && m.active { + now = m.waitNextSample(now) + } + } + + // Make limit <= want (unlimited if the transfer is no longer active) + if limit -= m.sBytes; limit > int64(want) || !m.active { + limit = int64(want) + } + m.mu.Unlock() + + if limit < 0 { + limit = 0 + } + return int(limit) +} + +// SetTransferSize specifies the total size of the data transfer, which allows +// the Monitor to calculate the overall progress and time to completion. +func (m *Monitor) SetTransferSize(bytes int64) { + if bytes < 0 { + bytes = 0 + } + m.mu.Lock() + m.tBytes = bytes + m.mu.Unlock() +} + +// update accumulates the transferred byte count for the current sample until +// clock() - m.sLast >= m.sRate. The monitor status is updated once the current +// sample is done. +func (m *Monitor) update(n int) (now time.Duration) { + if !m.active { + return + } + if now = clock(); n > 0 { + m.tLast = now + } + m.sBytes += int64(n) + if sTime := now - m.sLast; sTime >= m.sRate { + t := sTime.Seconds() + if m.rSample = float64(m.sBytes) / t; m.rSample > m.rPeak { + m.rPeak = m.rSample + } + + // Exponential moving average using a method similar to *nix load + // average calculation. Longer sampling periods carry greater weight. + if m.samples > 0 { + w := math.Exp(-t / m.rWindow) + m.rEMA = m.rSample + w*(m.rEMA-m.rSample) + } else { + m.rEMA = m.rSample + } + m.reset(now) + } + return +} + +// reset clears the current sample state in preparation for the next sample. +func (m *Monitor) reset(sampleTime time.Duration) { + m.bytes += m.sBytes + m.samples++ + m.sBytes = 0 + m.sLast = sampleTime +} + +// waitNextSample sleeps for the remainder of the current sample. The lock is +// released and reacquired during the actual sleep period, so it's possible for +// the transfer to be inactive when this method returns. +func (m *Monitor) waitNextSample(now time.Duration) time.Duration { + const minWait = 5 * time.Millisecond + current := m.sLast + + // sleep until the last sample time changes (ideally, just one iteration) + for m.sLast == current && m.active { + d := current + m.sRate - now + m.mu.Unlock() + if d < minWait { + d = minWait + } + time.Sleep(d) + m.mu.Lock() + now = m.update(0) + } + return now +} diff --git a/libs/flowrate/io.go b/libs/flowrate/io.go new file mode 100644 index 0000000..1c479da --- /dev/null +++ b/libs/flowrate/io.go @@ -0,0 +1,133 @@ +// +// Written by Maxim Khitrov (November 2012) +// + +package flowrate + +import ( + "errors" + "io" +) + +// ErrLimit is returned by the Writer when a non-blocking write is short due to +// the transfer rate limit. +var ErrLimit = errors.New("flowrate: flow rate limit exceeded") + +// Limiter is implemented by the Reader and Writer to provide a consistent +// interface for monitoring and controlling data transfer. +type Limiter interface { + Done() int64 + Status() Status + SetTransferSize(bytes int64) + SetLimit(new int64) (old int64) + SetBlocking(new bool) (old bool) +} + +// Reader implements io.ReadCloser with a restriction on the rate of data +// transfer. +type Reader struct { + io.Reader // Data source + *Monitor // Flow control monitor + + limit int64 // Rate limit in bytes per second (unlimited when <= 0) + block bool // What to do when no new bytes can be read due to the limit +} + +// NewReader restricts all Read operations on r to limit bytes per second. +func NewReader(r io.Reader, limit int64) *Reader { + return &Reader{r, New(0, 0), limit, true} +} + +// Read reads up to len(p) bytes into p without exceeding the current transfer +// rate limit. It returns (0, nil) immediately if r is non-blocking and no new +// bytes can be read at this time. +func (r *Reader) Read(p []byte) (n int, err error) { + p = p[:r.Limit(len(p), r.limit, r.block)] + if len(p) > 0 { + n, err = r.IO(r.Reader.Read(p)) + } + return +} + +// SetLimit changes the transfer rate limit to new bytes per second and returns +// the previous setting. +func (r *Reader) SetLimit(new int64) (old int64) { + old, r.limit = r.limit, new + return +} + +// SetBlocking changes the blocking behavior and returns the previous setting. A +// Read call on a non-blocking reader returns immediately if no additional bytes +// may be read at this time due to the rate limit. +func (r *Reader) SetBlocking(new bool) (old bool) { + old, r.block = r.block, new + return +} + +// Close closes the underlying reader if it implements the io.Closer interface. +func (r *Reader) Close() error { + defer r.Done() + if c, ok := r.Reader.(io.Closer); ok { + return c.Close() + } + return nil +} + +// Writer implements io.WriteCloser with a restriction on the rate of data +// transfer. +type Writer struct { + io.Writer // Data destination + *Monitor // Flow control monitor + + limit int64 // Rate limit in bytes per second (unlimited when <= 0) + block bool // What to do when no new bytes can be written due to the limit +} + +// NewWriter restricts all Write operations on w to limit bytes per second. The +// transfer rate and the default blocking behavior (true) can be changed +// directly on the returned *Writer. +func NewWriter(w io.Writer, limit int64) *Writer { + return &Writer{w, New(0, 0), limit, true} +} + +// Write writes len(p) bytes from p to the underlying data stream without +// exceeding the current transfer rate limit. It returns (n, ErrLimit) if w is +// non-blocking and no additional bytes can be written at this time. +func (w *Writer) Write(p []byte) (n int, err error) { + var c int + for len(p) > 0 && err == nil { + s := p[:w.Limit(len(p), w.limit, w.block)] + if len(s) > 0 { + c, err = w.IO(w.Writer.Write(s)) + } else { + return n, ErrLimit + } + p = p[c:] + n += c + } + return +} + +// SetLimit changes the transfer rate limit to new bytes per second and returns +// the previous setting. +func (w *Writer) SetLimit(new int64) (old int64) { + old, w.limit = w.limit, new + return +} + +// SetBlocking changes the blocking behavior and returns the previous setting. A +// Write call on a non-blocking writer returns as soon as no additional bytes +// may be written at this time due to the rate limit. +func (w *Writer) SetBlocking(new bool) (old bool) { + old, w.block = w.block, new + return +} + +// Close closes the underlying writer if it implements the io.Closer interface. +func (w *Writer) Close() error { + defer w.Done() + if c, ok := w.Writer.(io.Closer); ok { + return c.Close() + } + return nil +} diff --git a/libs/flowrate/io_test.go b/libs/flowrate/io_test.go new file mode 100644 index 0000000..99fd744 --- /dev/null +++ b/libs/flowrate/io_test.go @@ -0,0 +1,197 @@ +// +// Written by Maxim Khitrov (November 2012) +// + +package flowrate + +import ( + "bytes" + "testing" + "time" +) + +const ( + _50ms = 50 * time.Millisecond + _100ms = 100 * time.Millisecond + _200ms = 200 * time.Millisecond + _300ms = 300 * time.Millisecond + _400ms = 400 * time.Millisecond + _500ms = 500 * time.Millisecond +) + +func nextStatus(m *Monitor) Status { + samples := m.samples + for i := 0; i < 30; i++ { + if s := m.Status(); s.Samples != samples { + return s + } + time.Sleep(5 * time.Millisecond) + } + return m.Status() +} + +func TestReader(t *testing.T) { + in := make([]byte, 100) + for i := range in { + in[i] = byte(i) + } + b := make([]byte, 100) + r := NewReader(bytes.NewReader(in), 100) + start := time.Now() + + // Make sure r implements Limiter + _ = Limiter(r) + + // 1st read of 10 bytes is performed immediately + if n, err := r.Read(b); n != 10 || err != nil { + t.Fatalf("r.Read(b) expected 10 (); got %v (%v)", n, err) + } else if rt := time.Since(start); rt > _50ms { + t.Fatalf("r.Read(b) took too long (%v)", rt) + } + + // No new Reads allowed in the current sample + r.SetBlocking(false) + if n, err := r.Read(b); n != 0 || err != nil { + t.Fatalf("r.Read(b) expected 0 (); got %v (%v)", n, err) + } else if rt := time.Since(start); rt > _50ms { + t.Fatalf("r.Read(b) took too long (%v)", rt) + } + + status := [6]Status{0: r.Status()} // No samples in the first status + + // 2nd read of 10 bytes blocks until the next sample + r.SetBlocking(true) + if n, err := r.Read(b[10:]); n != 10 || err != nil { + t.Fatalf("r.Read(b[10:]) expected 10 (); got %v (%v)", n, err) + } else if rt := time.Since(start); rt < _100ms { + t.Fatalf("r.Read(b[10:]) returned ahead of time (%v)", rt) + } + + status[1] = r.Status() // 1st sample + status[2] = nextStatus(r.Monitor) // 2nd sample + status[3] = nextStatus(r.Monitor) // No activity for the 3rd sample + + if n := r.Done(); n != 20 { + t.Fatalf("r.Done() expected 20; got %v", n) + } + + status[4] = r.Status() + status[5] = nextStatus(r.Monitor) // Timeout + start = status[0].Start + + // Active, Bytes, Samples, InstRate, CurRate, AvgRate, PeakRate, BytesRem, Start, Duration, Idle, TimeRem, Progress + want := []Status{ + {start, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, true}, + {start, 10, 1, 100, 100, 100, 100, 0, _100ms, 0, 0, 0, true}, + {start, 20, 2, 100, 100, 100, 100, 0, _200ms, _100ms, 0, 0, true}, + {start, 20, 3, 0, 90, 67, 100, 0, _300ms, _200ms, 0, 0, true}, + {start, 20, 3, 0, 0, 67, 100, 0, _300ms, 0, 0, 0, false}, + {start, 20, 3, 0, 0, 67, 100, 0, _300ms, 0, 0, 0, false}, + } + for i, s := range status { + s := s + if !statusesAreEqual(&s, &want[i]) { + t.Errorf("r.Status(%v)\nexpected: %v\ngot : %v", i, want[i], s) + } + } + if !bytes.Equal(b[:20], in[:20]) { + t.Errorf("r.Read() input doesn't match output") + } +} + +func TestWriter(t *testing.T) { + b := make([]byte, 100) + for i := range b { + b[i] = byte(i) + } + w := NewWriter(&bytes.Buffer{}, 200) + start := time.Now() + + // Make sure w implements Limiter + _ = Limiter(w) + + // Non-blocking 20-byte write for the first sample returns ErrLimit + w.SetBlocking(false) + if n, err := w.Write(b); n != 20 || err != ErrLimit { + t.Fatalf("w.Write(b) expected 20 (ErrLimit); got %v (%v)", n, err) + } else if rt := time.Since(start); rt > _50ms { + t.Fatalf("w.Write(b) took too long (%v)", rt) + } + + // Blocking 80-byte write + w.SetBlocking(true) + if n, err := w.Write(b[20:]); n != 80 || err != nil { + t.Fatalf("w.Write(b[20:]) expected 80 (); got %v (%v)", n, err) + } else if rt := time.Since(start); rt < _300ms { + // Explanation for `rt < _300ms` (as opposed to `< _400ms`) + // + // |<-- start | | + // epochs: -----0ms|---100ms|---200ms|---300ms|---400ms + // sends: 20|20 |20 |20 |20# + // + // NOTE: The '#' symbol can thus happen before 400ms is up. + // Thus, we can only panic if rt < _300ms. + t.Fatalf("w.Write(b[20:]) returned ahead of time (%v)", rt) + } + + w.SetTransferSize(100) + status := []Status{w.Status(), nextStatus(w.Monitor)} + start = status[0].Start + + // Active, Bytes, Samples, InstRate, CurRate, AvgRate, PeakRate, BytesRem, Start, Duration, Idle, TimeRem, Progress + want := []Status{ + {start, 80, 4, 200, 200, 200, 200, 20, _400ms, 0, _100ms, 80000, true}, + {start, 100, 5, 200, 200, 200, 200, 0, _500ms, _100ms, 0, 100000, true}, + } + + for i, s := range status { + s := s + if !statusesAreEqual(&s, &want[i]) { + t.Errorf("w.Status(%v)\nexpected: %v\ngot : %v\n", i, want[i], s) + } + } + if !bytes.Equal(b, w.Writer.(*bytes.Buffer).Bytes()) { + t.Errorf("w.Write() input doesn't match output") + } +} + +const maxDeviationForDuration = 50 * time.Millisecond +const maxDeviationForRate int64 = 50 + +// statusesAreEqual returns true if s1 is equal to s2. Equality here means +// general equality of fields except for the duration and rates, which can +// drift due to unpredictable delays (e.g. thread wakes up 25ms after +// `time.Sleep` has ended). +func statusesAreEqual(s1 *Status, s2 *Status) bool { + if s1.Active == s2.Active && + s1.Start.Equal(s2.Start) && + durationsAreEqual(s1.Duration, s2.Duration, maxDeviationForDuration) && + s1.Idle == s2.Idle && + s1.Bytes == s2.Bytes && + s1.Samples == s2.Samples && + ratesAreEqual(s1.InstRate, s2.InstRate, maxDeviationForRate) && + ratesAreEqual(s1.CurRate, s2.CurRate, maxDeviationForRate) && + ratesAreEqual(s1.AvgRate, s2.AvgRate, maxDeviationForRate) && + ratesAreEqual(s1.PeakRate, s2.PeakRate, maxDeviationForRate) && + s1.BytesRem == s2.BytesRem && + durationsAreEqual(s1.TimeRem, s2.TimeRem, maxDeviationForDuration) && + s1.Progress == s2.Progress { + return true + } + return false +} + +func durationsAreEqual(d1 time.Duration, d2 time.Duration, maxDeviation time.Duration) bool { + return d2-d1 <= maxDeviation +} + +func ratesAreEqual(r1 int64, r2 int64, maxDeviation int64) bool { + sub := r1 - r2 + if sub < 0 { + sub = -sub + } + if sub <= maxDeviation { + return true + } + return false +} diff --git a/libs/flowrate/util.go b/libs/flowrate/util.go new file mode 100644 index 0000000..417b37e --- /dev/null +++ b/libs/flowrate/util.go @@ -0,0 +1,67 @@ +// +// Written by Maxim Khitrov (November 2012) +// + +package flowrate + +import ( + "math" + "strconv" + "time" +) + +// clockRate is the resolution and precision of clock(). +const clockRate = 20 * time.Millisecond + +// czero is the process start time rounded down to the nearest clockRate +// increment. +var czero = time.Now().Round(clockRate) + +// clock returns a low resolution timestamp relative to the process start time. +func clock() time.Duration { + return time.Now().Round(clockRate).Sub(czero) +} + +// clockToTime converts a clock() timestamp to an absolute time.Time value. +func clockToTime(c time.Duration) time.Time { + return czero.Add(c) +} + +// clockRound returns d rounded to the nearest clockRate increment. +func clockRound(d time.Duration) time.Duration { + return (d + clockRate>>1) / clockRate * clockRate +} + +// round returns x rounded to the nearest int64 (non-negative values only). +func round(x float64) int64 { + if _, frac := math.Modf(x); frac >= 0.5 { + return int64(math.Ceil(x)) + } + return int64(math.Floor(x)) +} + +// Percent represents a percentage in increments of 1/1000th of a percent. +type Percent uint32 + +// percentOf calculates what percent of the total is x. +func percentOf(x, total float64) Percent { + if x < 0 || total <= 0 { + return 0 + } else if p := round(x / total * 1e5); p <= math.MaxUint32 { + return Percent(p) + } + return Percent(math.MaxUint32) +} + +func (p Percent) Float() float64 { + return float64(p) * 1e-3 +} + +func (p Percent) String() string { + var buf [12]byte + b := strconv.AppendUint(buf[:0], uint64(p)/1000, 10) + n := len(b) + b = strconv.AppendUint(b, 1000+uint64(p)%1000, 10) + b[n] = '.' + return string(append(b, '%')) +} diff --git a/libs/json/decoder.go b/libs/json/decoder.go new file mode 100644 index 0000000..d3510b0 --- /dev/null +++ b/libs/json/decoder.go @@ -0,0 +1,278 @@ +package json + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "reflect" +) + +// Unmarshal unmarshals JSON into the given value, using Amino-compatible JSON encoding (strings +// for 64-bit numbers, and type wrappers for registered types). +func Unmarshal(bz []byte, v interface{}) error { + return decode(bz, v) +} + +func decode(bz []byte, v interface{}) error { + if len(bz) == 0 { + return errors.New("cannot decode empty bytes") + } + + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Ptr { + return errors.New("must decode into a pointer") + } + rv = rv.Elem() + + // If this is a registered type, defer to interface decoder regardless of whether the input is + // an interface or a bare value. This retains Amino's behavior, but is inconsistent with + // behavior in structs where an interface field will get the type wrapper while a bare value + // field will not. + if typeRegistry.name(rv.Type()) != "" { + return decodeReflectInterface(bz, rv) + } + + return decodeReflect(bz, rv) +} + +func decodeReflect(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() { + return errors.New("value is not addressable") + } + + // Handle null for slices, interfaces, and pointers + if bytes.Equal(bz, []byte("null")) { + rv.Set(reflect.Zero(rv.Type())) + return nil + } + + // Dereference-and-construct pointers, to handle nested pointers. + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) + } + rv = rv.Elem() + } + + // Times must be UTC and end with Z + if rv.Type() == timeType { + switch { + case len(bz) < 2 || bz[0] != '"' || bz[len(bz)-1] != '"': + return fmt.Errorf("JSON time must be an RFC3339 string, but got %q", bz) + case bz[len(bz)-2] != 'Z': + return fmt.Errorf("JSON time must be UTC and end with 'Z', but got %q", bz) + } + } + + // If value implements json.Umarshaler, call it. + if rv.Addr().Type().Implements(jsonUnmarshalerType) { + return rv.Addr().Interface().(json.Unmarshaler).UnmarshalJSON(bz) + } + + switch rv.Type().Kind() { + // Decode complex types recursively. + case reflect.Slice, reflect.Array: + return decodeReflectList(bz, rv) + + case reflect.Map: + return decodeReflectMap(bz, rv) + + case reflect.Struct: + return decodeReflectStruct(bz, rv) + + case reflect.Interface: + return decodeReflectInterface(bz, rv) + + // For 64-bit integers, unwrap expected string and defer to stdlib for integer decoding. + case reflect.Int64, reflect.Int, reflect.Uint64, reflect.Uint: + if bz[0] != '"' || bz[len(bz)-1] != '"' { + return fmt.Errorf("invalid 64-bit integer encoding %q, expected string", string(bz)) + } + bz = bz[1 : len(bz)-1] + fallthrough + + // Anything else we defer to the stdlib. + default: + return decodeStdlib(bz, rv) + } +} + +func decodeReflectList(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() { + return errors.New("list value is not addressable") + } + + switch rv.Type().Elem().Kind() { + // Decode base64-encoded bytes using stdlib decoder, via byte slice for arrays. + case reflect.Uint8: + if rv.Type().Kind() == reflect.Array { + var buf []byte + if err := json.Unmarshal(bz, &buf); err != nil { + return err + } + if len(buf) != rv.Len() { + return fmt.Errorf("got %v bytes, expected %v", len(buf), rv.Len()) + } + reflect.Copy(rv, reflect.ValueOf(buf)) + + } else if err := decodeStdlib(bz, rv); err != nil { + return err + } + + // Decode anything else into a raw JSON slice, and decode values recursively. + default: + var rawSlice []json.RawMessage + if err := json.Unmarshal(bz, &rawSlice); err != nil { + return err + } + if rv.Type().Kind() == reflect.Slice { + rv.Set(reflect.MakeSlice(reflect.SliceOf(rv.Type().Elem()), len(rawSlice), len(rawSlice))) + } + if rv.Len() != len(rawSlice) { // arrays of wrong size + return fmt.Errorf("got list of %v elements, expected %v", len(rawSlice), rv.Len()) + } + for i, bz := range rawSlice { + if err := decodeReflect(bz, rv.Index(i)); err != nil { + return err + } + } + } + + // Replace empty slices with nil slices, for Amino compatibility + if rv.Type().Kind() == reflect.Slice && rv.Len() == 0 { + rv.Set(reflect.Zero(rv.Type())) + } + + return nil +} + +func decodeReflectMap(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() { + return errors.New("map value is not addressable") + } + + // Decode into a raw JSON map, using string keys. + rawMap := make(map[string]json.RawMessage) + if err := json.Unmarshal(bz, &rawMap); err != nil { + return err + } + if rv.Type().Key().Kind() != reflect.String { + return fmt.Errorf("map keys must be strings, got %v", rv.Type().Key().String()) + } + + // Recursively decode values. + rv.Set(reflect.MakeMapWithSize(rv.Type(), len(rawMap))) + for key, bz := range rawMap { + value := reflect.New(rv.Type().Elem()).Elem() + if err := decodeReflect(bz, value); err != nil { + return err + } + rv.SetMapIndex(reflect.ValueOf(key), value) + } + return nil +} + +func decodeReflectStruct(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() { + return errors.New("struct value is not addressable") + } + sInfo := makeStructInfo(rv.Type()) + + // Decode raw JSON values into a string-keyed map. + rawMap := make(map[string]json.RawMessage) + if err := json.Unmarshal(bz, &rawMap); err != nil { + return err + } + for i, fInfo := range sInfo.fields { + if !fInfo.hidden { + frv := rv.Field(i) + bz := rawMap[fInfo.jsonName] + if len(bz) > 0 { + if err := decodeReflect(bz, frv); err != nil { + return err + } + } else if !fInfo.omitEmpty { + frv.Set(reflect.Zero(frv.Type())) + } + } + } + + return nil +} + +func decodeReflectInterface(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() { + return errors.New("interface value not addressable") + } + + // Decode the interface wrapper. + wrapper := interfaceWrapper{} + if err := json.Unmarshal(bz, &wrapper); err != nil { + return err + } + if wrapper.Type == "" { + return errors.New("interface type cannot be empty") + } + if len(wrapper.Value) == 0 { + return errors.New("interface value cannot be empty") + } + + // Dereference-and-construct pointers, to handle nested pointers. + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) + } + rv = rv.Elem() + } + + // Look up the interface type, and construct a concrete value. + rt, returnPtr := typeRegistry.lookup(wrapper.Type) + if rt == nil { + return fmt.Errorf("unknown type %q", wrapper.Type) + } + + cptr := reflect.New(rt) + crv := cptr.Elem() + if err := decodeReflect(wrapper.Value, crv); err != nil { + return err + } + + // This makes sure interface implementations with pointer receivers (e.g. func (c *Car)) are + // constructed as pointers behind the interface. The types must be registered as pointers with + // RegisterType(). + if rv.Type().Kind() == reflect.Interface && returnPtr { + if !cptr.Type().AssignableTo(rv.Type()) { + return fmt.Errorf("invalid type %q for this value", wrapper.Type) + } + rv.Set(cptr) + } else { + if !crv.Type().AssignableTo(rv.Type()) { + return fmt.Errorf("invalid type %q for this value", wrapper.Type) + } + rv.Set(crv) + } + return nil +} + +func decodeStdlib(bz []byte, rv reflect.Value) error { + if !rv.CanAddr() && rv.Kind() != reflect.Ptr { + return errors.New("value must be addressable or pointer") + } + + // Make sure we are unmarshaling into a pointer. + target := rv + if rv.Kind() != reflect.Ptr { + target = reflect.New(rv.Type()) + } + if err := json.Unmarshal(bz, target.Interface()); err != nil { + return err + } + rv.Set(target.Elem()) + return nil +} + +type interfaceWrapper struct { + Type string `json:"type"` + Value json.RawMessage `json:"value"` +} diff --git a/libs/json/decoder_test.go b/libs/json/decoder_test.go new file mode 100644 index 0000000..6b799de --- /dev/null +++ b/libs/json/decoder_test.go @@ -0,0 +1,151 @@ +package json_test + +import ( + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/json" +) + +func TestUnmarshal(t *testing.T) { + i64Nil := (*int64)(nil) + str := "string" + strPtr := &str + structNil := (*Struct)(nil) + i32 := int32(32) + i64 := int64(64) + + testcases := map[string]struct { + json string + value interface{} + err bool + }{ + "bool true": {"true", true, false}, + "bool false": {"false", false, false}, + "float32": {"3.14", float32(3.14), false}, + "float64": {"3.14", float64(3.14), false}, + "int32": {`32`, int32(32), false}, + "int32 string": {`"32"`, int32(32), true}, + "int32 ptr": {`32`, &i32, false}, + "int64": {`"64"`, int64(64), false}, + "int64 noend": {`"64`, int64(64), true}, + "int64 number": {`64`, int64(64), true}, + "int64 ptr": {`"64"`, &i64, false}, + "int64 ptr nil": {`null`, i64Nil, false}, + "string": {`"foo"`, "foo", false}, + "string noend": {`"foo`, "foo", true}, + "string ptr": {`"string"`, &str, false}, + "slice byte": {`"AQID"`, []byte{1, 2, 3}, false}, + "slice bytes": {`["AQID"]`, [][]byte{{1, 2, 3}}, false}, + "slice int32": {`[1,2,3]`, []int32{1, 2, 3}, false}, + "slice int64": {`["1","2","3"]`, []int64{1, 2, 3}, false}, + "slice int64 number": {`[1,2,3]`, []int64{1, 2, 3}, true}, + "slice int64 ptr": {`["64"]`, []*int64{&i64}, false}, + "slice int64 empty": {`[]`, []int64(nil), false}, + "slice int64 null": {`null`, []int64(nil), false}, + "array byte": {`"AQID"`, [3]byte{1, 2, 3}, false}, + "array byte large": {`"AQID"`, [4]byte{1, 2, 3, 4}, true}, + "array byte small": {`"AQID"`, [2]byte{1, 2}, true}, + "array int32": {`[1,2,3]`, [3]int32{1, 2, 3}, false}, + "array int64": {`["1","2","3"]`, [3]int64{1, 2, 3}, false}, + "array int64 number": {`[1,2,3]`, [3]int64{1, 2, 3}, true}, + "array int64 large": {`["1","2","3"]`, [4]int64{1, 2, 3, 4}, true}, + "array int64 small": {`["1","2","3"]`, [2]int64{1, 2}, true}, + "map bytes": {`{"b":"AQID"}`, map[string][]byte{"b": {1, 2, 3}}, false}, + "map int32": {`{"a":1,"b":2}`, map[string]int32{"a": 1, "b": 2}, false}, + "map int64": {`{"a":"1","b":"2"}`, map[string]int64{"a": 1, "b": 2}, false}, + "map int64 empty": {`{}`, map[string]int64{}, false}, + "map int64 null": {`null`, map[string]int64(nil), false}, + "map int key": {`{}`, map[int]int{}, true}, + "time": {`"2020-06-03T17:35:30Z"`, time.Date(2020, 6, 3, 17, 35, 30, 0, time.UTC), false}, + "time non-utc": {`"2020-06-03T17:35:30+02:00"`, time.Time{}, true}, + "time nozone": {`"2020-06-03T17:35:30"`, time.Time{}, true}, + "car": {`{"type":"vehicle/car","value":{"Wheels":4}}`, Car{Wheels: 4}, false}, + "car ptr": {`{"type":"vehicle/car","value":{"Wheels":4}}`, &Car{Wheels: 4}, false}, + "car iface": {`{"type":"vehicle/car","value":{"Wheels":4}}`, Vehicle(&Car{Wheels: 4}), false}, + "boat": {`{"type":"vehicle/boat","value":{"Sail":true}}`, Boat{Sail: true}, false}, + "boat ptr": {`{"type":"vehicle/boat","value":{"Sail":true}}`, &Boat{Sail: true}, false}, + "boat iface": {`{"type":"vehicle/boat","value":{"Sail":true}}`, Vehicle(Boat{Sail: true}), false}, + "boat into car": {`{"type":"vehicle/boat","value":{"Sail":true}}`, Car{}, true}, + "boat into car iface": {`{"type":"vehicle/boat","value":{"Sail":true}}`, Vehicle(&Car{}), true}, + "shoes": {`{"type":"vehicle/shoes","value":{"Soles":"rubber"}}`, Car{}, true}, + "shoes ptr": {`{"type":"vehicle/shoes","value":{"Soles":"rubber"}}`, &Car{}, true}, + "shoes iface": {`{"type":"vehicle/shoes","value":{"Soles":"rubbes"}}`, Vehicle(&Car{}), true}, + "key public": {`{"type":"key/public","value":"AQIDBAUGBwg="}`, PublicKey{1, 2, 3, 4, 5, 6, 7, 8}, false}, + "key wrong": {`{"type":"key/public","value":"AQIDBAUGBwg="}`, PrivateKey{1, 2, 3, 4, 5, 6, 7, 8}, true}, + "key into car": {`{"type":"key/public","value":"AQIDBAUGBwg="}`, Vehicle(&Car{}), true}, + "tags": { + `{"name":"name","OmitEmpty":"foo","Hidden":"bar","tags":{"name":"child"}}`, + Tags{JSONName: "name", OmitEmpty: "foo", Tags: &Tags{JSONName: "child"}}, + false, + }, + "tags ptr": { + `{"name":"name","OmitEmpty":"foo","tags":null}`, + &Tags{JSONName: "name", OmitEmpty: "foo"}, + false, + }, + "tags real name": {`{"JSONName":"name"}`, Tags{}, false}, + "struct": { + `{ + "Bool":true, "Float64":3.14, "Int32":32, "Int64":"64", "Int64Ptr":"64", + "String":"foo", "StringPtrPtr": "string", "Bytes":"AQID", + "Time":"2020-06-02T16:05:13.004346374Z", + "Car":{"Wheels":4}, + "Boat":{"Sail":true}, + "Vehicles":[ + {"type":"vehicle/car","value":{"Wheels":4}}, + {"type":"vehicle/boat","value":{"Sail":true}} + ], + "Child":{ + "Bool":false, "Float64":0, "Int32":0, "Int64":"0", "Int64Ptr":null, + "String":"child", "StringPtrPtr":null, "Bytes":null, + "Time":"0001-01-01T00:00:00Z", + "Car":null, "Boat":{"Sail":false}, "Vehicles":null, "Child":null + }, + "private": "foo", "unknown": "bar" + }`, + Struct{ + Bool: true, Float64: 3.14, Int32: 32, Int64: 64, Int64Ptr: &i64, + String: "foo", StringPtrPtr: &strPtr, Bytes: []byte{1, 2, 3}, + Time: time.Date(2020, 6, 2, 16, 5, 13, 4346374, time.UTC), + Car: &Car{Wheels: 4}, Boat: Boat{Sail: true}, Vehicles: []Vehicle{ + Vehicle(&Car{Wheels: 4}), + Vehicle(Boat{Sail: true}), + }, + Child: &Struct{Bool: false, String: "child"}, + }, + false, + }, + "struct key into vehicle": {`{"Vehicles":[ + {"type":"vehicle/car","value":{"Wheels":4}}, + {"type":"key/public","value":"MTIzNDU2Nzg="} + ]}`, Struct{}, true}, + "struct ptr null": {`null`, structNil, false}, + "custom value": {`{"Value":"foo"}`, CustomValue{}, false}, + "custom ptr": {`"foo"`, &CustomPtr{Value: "custom"}, false}, + "custom ptr value": {`"foo"`, CustomPtr{Value: "custom"}, false}, + "invalid type": {`"foo"`, Struct{}, true}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + // Create a target variable as a pointer to the zero value of the tc.value type, + // and wrap it in an empty interface. Decode into that interface. + target := reflect.New(reflect.TypeOf(tc.value)).Interface() + err := json.Unmarshal([]byte(tc.json), target) + if tc.err { + require.Error(t, err) + return + } + require.NoError(t, err) + + // Unwrap the target pointer and get the value behind the interface. + actual := reflect.ValueOf(target).Elem().Interface() + assert.Equal(t, tc.value, actual) + }) + } +} diff --git a/libs/json/doc.go b/libs/json/doc.go new file mode 100644 index 0000000..c87fa23 --- /dev/null +++ b/libs/json/doc.go @@ -0,0 +1,98 @@ +// Package json provides functions for marshaling and unmarshaling JSON in a format that is +// backwards-compatible with Amino JSON encoding. This mostly differs from encoding/json in +// encoding of integers (64-bit integers are encoded as strings, not numbers), and handling +// of interfaces (wrapped in an interface object with type/value keys). +// +// JSON tags (e.g. `json:"name,omitempty"`) are supported in the same way as encoding/json, as is +// custom marshaling overrides via the json.Marshaler and json.Unmarshaler interfaces. +// +// Note that not all JSON emitted by CometBFT is generated by this library; some is generated by +// encoding/json instead, and kept like that for backwards compatibility. +// +// Encoding of numbers uses strings for 64-bit integers (including unspecified ints), to improve +// compatibility with e.g. Javascript (which uses 64-bit floats for numbers, having 53-bit +// precision): +// +// int32(32) // Output: 32 +// uint32(32) // Output: 32 +// int64(64) // Output: "64" +// uint64(64) // Output: "64" +// int(64) // Output: "64" +// uint(64) // Output: "64" +// +// Encoding of other scalars follows encoding/json: +// +// nil // Output: null +// true // Output: true +// "foo" // Output: "foo" +// "" // Output: "" +// +// Slices and arrays are encoded as encoding/json, including base64-encoding of byte slices +// with additional base64-encoding of byte arrays as well: +// +// []int64(nil) // Output: null +// []int64{} // Output: [] +// []int64{1, 2, 3} // Output: ["1", "2", "3"] +// []int32{1, 2, 3} // Output: [1, 2, 3] +// []byte{1, 2, 3} // Output: "AQID" +// [3]int64{1, 2, 3} // Output: ["1", "2", "3"] +// [3]byte{1, 2, 3} // Output: "AQID" +// +// Maps are encoded as encoding/json, but only strings are allowed as map keys (nil maps are not +// emitted as null, to retain Amino backwards-compatibility): +// +// map[string]int64(nil) // Output: {} +// map[string]int64{} // Output: {} +// map[string]int64{"a":1,"b":2} // Output: {"a":"1","b":"2"} +// map[string]int32{"a":1,"b":2} // Output: {"a":1,"b":2} +// map[bool]int{true:1} // Errors +// +// Times are encoded as encoding/json, in RFC3339Nano format, but requiring UTC time zone (with zero +// times emitted as "0001-01-01T00:00:00Z" as with encoding/json): +// +// time.Date(2020, 6, 8, 16, 21, 28, 123, time.FixedZone("UTC+2", 2*60*60)) +// // Output: "2020-06-08T14:21:28.000000123Z" +// time.Time{} // Output: "0001-01-01T00:00:00Z" +// (*time.Time)(nil) // Output: null +// +// Structs are encoded as encoding/json, supporting JSON tags and ignoring private fields: +// +// type Struct struct{ +// Name string +// Value int32 `json:"value,omitempty"` +// private bool +// } +// +// Struct{Name: "foo", Value: 7, private: true} // Output: {"Name":"foo","value":7} +// Struct{} // Output: {"Name":""} +// +// Registered types are encoded with type wrapper, regardless of whether they are given as interface +// or bare struct, but inside structs they are only emitted with type wrapper for interface fields +// (this follows Amino behavior): +// +// type Vehicle interface { +// Drive() error +// } +// +// type Car struct { +// Wheels int8 +// } +// +// func (c *Car) Drive() error { return nil } +// +// RegisterType(&Car{}, "vehicle/car") +// +// Car{Wheels: 4} // Output: {"type":"vehicle/car","value":{"Wheels":4}} +// &Car{Wheels: 4} // Output: {"type":"vehicle/car","value":{"Wheels":4}} +// (*Car)(nil) // Output: null +// Vehicle(Car{Wheels: 4}) // Output: {"type":"vehicle/car","value":{"Wheels":4}} +// Vehicle(nil) // Output: null +// +// type Struct struct { +// Car *Car +// Vehicle Vehicle +// } +// +// Struct{Car: &Car{Wheels: 4}, Vehicle: &Car{Wheels: 4}} +// // Output: {"Car": {"Wheels: 4"}, "Vehicle": {"type":"vehicle/car","value":{"Wheels":4}}} +package json diff --git a/libs/json/encoder.go b/libs/json/encoder.go new file mode 100644 index 0000000..88c5d8d --- /dev/null +++ b/libs/json/encoder.go @@ -0,0 +1,257 @@ +package json + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "strconv" + "time" +) + +var ( + timeType = reflect.TypeOf(time.Time{}) + jsonMarshalerType = reflect.TypeOf(new(json.Marshaler)).Elem() + jsonUnmarshalerType = reflect.TypeOf(new(json.Unmarshaler)).Elem() +) + +// Marshal marshals the value as JSON, using Amino-compatible JSON encoding (strings for +// 64-bit numbers, and type wrappers for registered types). +func Marshal(v interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + err := encode(buf, v) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// MarshalIndent marshals the value as JSON, using the given prefix and indentation. +func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + bz, err := Marshal(v) + if err != nil { + return nil, err + } + buf := new(bytes.Buffer) + err = json.Indent(buf, bz, prefix, indent) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func encode(w *bytes.Buffer, v any) error { + // Bare nil values can't be reflected, so we must handle them here. + if v == nil { + return writeStr(w, "null") + } + rv := reflect.ValueOf(v) + + // If this is a registered type, defer to interface encoder regardless of whether the input is + // an interface or a bare value. This retains Amino's behavior, but is inconsistent with + // behavior in structs where an interface field will get the type wrapper while a bare value + // field will not. + if typeRegistry.name(rv.Type()) != "" { + return encodeReflectInterface(w, rv) + } + + return encodeReflect(w, rv) +} + +func encodeReflect(w *bytes.Buffer, rv reflect.Value) error { + if !rv.IsValid() { + return errors.New("invalid reflect value") + } + + // Recursively dereference if pointer. + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + return writeStr(w, "null") + } + rv = rv.Elem() + } + + // Convert times to UTC. + if rv.Type() == timeType { + rv = reflect.ValueOf(rv.Interface().(time.Time).Round(0).UTC()) + } + + // If the value implements json.Marshaler, defer to stdlib directly. Since we've already + // dereferenced, we try implementations with both value receiver and pointer receiver. We must + // do this after the time normalization above, and thus after dereferencing. + if rv.Type().Implements(jsonMarshalerType) { + return encodeStdlib(w, rv.Interface()) + } else if rv.CanAddr() && rv.Addr().Type().Implements(jsonMarshalerType) { + return encodeStdlib(w, rv.Addr().Interface()) + } + + switch rv.Type().Kind() { + // Complex types must be recursively encoded. + case reflect.Interface: + return encodeReflectInterface(w, rv) + + case reflect.Array, reflect.Slice: + return encodeReflectList(w, rv) + + case reflect.Map: + return encodeReflectMap(w, rv) + + case reflect.Struct: + return encodeReflectStruct(w, rv) + + // 64-bit integers are emitted as strings, to avoid precision problems with e.g. + // Javascript which uses 64-bit floats (having 53-bit precision). + case reflect.Int64, reflect.Int: + return writeStr(w, `"`+strconv.FormatInt(rv.Int(), 10)+`"`) + + case reflect.Uint64, reflect.Uint: + return writeStr(w, `"`+strconv.FormatUint(rv.Uint(), 10)+`"`) + + // For everything else, defer to the stdlib encoding/json encoder + default: + return encodeStdlib(w, rv.Interface()) + } +} + +func encodeReflectList(w *bytes.Buffer, rv reflect.Value) error { + // Emit nil slices as null. + if rv.Kind() == reflect.Slice && rv.IsNil() { + return writeStr(w, "null") + } + + // Encode byte slices as base64 with the stdlib encoder. + if rv.Type().Elem().Kind() == reflect.Uint8 { + // Stdlib does not base64-encode byte arrays, only slices, so we copy to slice. + if rv.Type().Kind() == reflect.Array { + slice := reflect.MakeSlice(reflect.SliceOf(rv.Type().Elem()), rv.Len(), rv.Len()) + reflect.Copy(slice, rv) + rv = slice + } + return encodeStdlib(w, rv.Interface()) + } + + // Anything else we recursively encode ourselves. + length := rv.Len() + if err := writeStr(w, "["); err != nil { + return err + } + for i := 0; i < length; i++ { + if err := encodeReflect(w, rv.Index(i)); err != nil { + return err + } + if i < length-1 { + if err := writeStr(w, ","); err != nil { + return err + } + } + } + return writeStr(w, "]") +} + +func encodeReflectMap(w *bytes.Buffer, rv reflect.Value) error { + if rv.Type().Key().Kind() != reflect.String { + return errors.New("map key must be string") + } + + // nil maps are not emitted as nil, to retain Amino compatibility. + + if err := writeStr(w, "{"); err != nil { + return err + } + writeComma := false + for _, keyrv := range rv.MapKeys() { + if writeComma { + if err := writeStr(w, ","); err != nil { + return err + } + } + if err := encodeStdlib(w, keyrv.Interface()); err != nil { + return err + } + if err := writeStr(w, ":"); err != nil { + return err + } + if err := encodeReflect(w, rv.MapIndex(keyrv)); err != nil { + return err + } + writeComma = true + } + return writeStr(w, "}") +} + +func encodeReflectStruct(w *bytes.Buffer, rv reflect.Value) error { + sInfo := makeStructInfo(rv.Type()) + if err := writeStr(w, "{"); err != nil { + return err + } + writeComma := false + for i, fInfo := range sInfo.fields { + frv := rv.Field(i) + if fInfo.hidden || (fInfo.omitEmpty && frv.IsZero()) { + continue + } + + if writeComma { + if err := writeStr(w, ","); err != nil { + return err + } + } + if err := encodeStdlib(w, fInfo.jsonName); err != nil { + return err + } + if err := writeStr(w, ":"); err != nil { + return err + } + if err := encodeReflect(w, frv); err != nil { + return err + } + writeComma = true + } + return writeStr(w, "}") +} + +func encodeReflectInterface(w *bytes.Buffer, rv reflect.Value) error { + // Get concrete value and dereference pointers. + for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface { + if rv.IsNil() { + return writeStr(w, "null") + } + rv = rv.Elem() + } + + // Look up the name of the concrete type + name := typeRegistry.name(rv.Type()) + if name == "" { + return fmt.Errorf("cannot encode unregistered type %v", rv.Type()) + } + + // Write value wrapped in interface envelope + if err := writeStr(w, fmt.Sprintf(`{"type":%q,"value":`, name)); err != nil { + return err + } + if err := encodeReflect(w, rv); err != nil { + return err + } + return writeStr(w, "}") +} + +func encodeStdlib(w *bytes.Buffer, v any) error { + // Stream the output of the JSON marshaling directly into the buffer. + // The stdlib encoder will write a newline, so we must truncate it, + // which is why we pass in a bytes.Buffer throughout, not io.Writer. + enc := json.NewEncoder(w) + err := enc.Encode(v) + if err != nil { + return err + } + // Remove the last byte from the buffer + w.Truncate(w.Len() - 1) + return err +} + +func writeStr(w io.Writer, s string) error { + _, err := w.Write([]byte(s)) + return err +} diff --git a/libs/json/encoder_test.go b/libs/json/encoder_test.go new file mode 100644 index 0000000..7eeb896 --- /dev/null +++ b/libs/json/encoder_test.go @@ -0,0 +1,121 @@ +package json_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/json" +) + +func TestMarshal(t *testing.T) { + s := "string" + sPtr := &s + i64 := int64(64) + ti := time.Date(2020, 6, 2, 18, 5, 13, 4346374, time.FixedZone("UTC+2", 2*60*60)) + car := &Car{Wheels: 4} + boat := Boat{Sail: true} + + testcases := map[string]struct { + value interface{} + output string + }{ + "nil": {nil, `null`}, + "string": {"foo", `"foo"`}, + "float32": {float32(3.14), `3.14`}, + "float32 neg": {float32(-3.14), `-3.14`}, + "float64": {float64(3.14), `3.14`}, + "float64 neg": {float64(-3.14), `-3.14`}, + "int32": {int32(32), `32`}, + "int64": {int64(64), `"64"`}, + "int64 neg": {int64(-64), `"-64"`}, + "int64 ptr": {&i64, `"64"`}, + "uint64": {uint64(64), `"64"`}, + "time": {ti, `"2020-06-02T16:05:13.004346374Z"`}, + "time empty": {time.Time{}, `"0001-01-01T00:00:00Z"`}, + "time ptr": {&ti, `"2020-06-02T16:05:13.004346374Z"`}, + "customptr": {CustomPtr{Value: "x"}, `{"Value":"x"}`}, // same as encoding/json + "customptr ptr": {&CustomPtr{Value: "x"}, `"custom"`}, + "customvalue": {CustomValue{Value: "x"}, `"custom"`}, + "customvalue ptr": {&CustomValue{Value: "x"}, `"custom"`}, + "slice nil": {[]int(nil), `null`}, + "slice empty": {[]int{}, `[]`}, + "slice bytes": {[]byte{1, 2, 3}, `"AQID"`}, + "slice int64": {[]int64{1, 2, 3}, `["1","2","3"]`}, + "slice int64 ptr": {[]*int64{&i64, nil}, `["64",null]`}, + "array bytes": {[3]byte{1, 2, 3}, `"AQID"`}, + "array int64": {[3]int64{1, 2, 3}, `["1","2","3"]`}, + "map nil": {map[string]int64(nil), `{}`}, // retain Amino compatibility + "map empty": {map[string]int64{}, `{}`}, + "map int64": {map[string]int64{"a": 1, "b": 2, "c": 3}, `{"a":"1","b":"2","c":"3"}`}, + "car": {car, `{"type":"vehicle/car","value":{"Wheels":4}}`}, + "car value": {*car, `{"type":"vehicle/car","value":{"Wheels":4}}`}, + "car iface": {Vehicle(car), `{"type":"vehicle/car","value":{"Wheels":4}}`}, + "car nil": {(*Car)(nil), `null`}, + "boat": {boat, `{"type":"vehicle/boat","value":{"Sail":true}}`}, + "boat ptr": {&boat, `{"type":"vehicle/boat","value":{"Sail":true}}`}, + "boat iface": {Vehicle(boat), `{"type":"vehicle/boat","value":{"Sail":true}}`}, + "key public": {PublicKey{1, 2, 3, 4, 5, 6, 7, 8}, `{"type":"key/public","value":"AQIDBAUGBwg="}`}, + "tags": { + Tags{JSONName: "name", OmitEmpty: "foo", Hidden: "bar", Tags: &Tags{JSONName: "child"}}, + `{"name":"name","OmitEmpty":"foo","tags":{"name":"child"}}`, + }, + "tags empty": {Tags{}, `{"name":""}`}, + // The encoding of the Car and Boat fields do not have type wrappers, even though they get + // type wrappers when encoded directly (see "car" and "boat" tests). This is to retain the + // same behavior as Amino. If the field was a Vehicle interface instead, it would get + // type wrappers, as seen in the Vehicles field. + "struct": { + Struct{ + Bool: true, Float64: 3.14, Int32: 32, Int64: 64, Int64Ptr: &i64, + String: "foo", StringPtrPtr: &sPtr, Bytes: []byte{1, 2, 3}, + Time: ti, Car: car, Boat: boat, Vehicles: []Vehicle{car, boat}, + Child: &Struct{Bool: false, String: "child"}, private: "private", + }, + `{ + "Bool":true, "Float64":3.14, "Int32":32, "Int64":"64", "Int64Ptr":"64", + "String":"foo", "StringPtrPtr": "string", "Bytes":"AQID", + "Time":"2020-06-02T16:05:13.004346374Z", + "Car":{"Wheels":4}, + "Boat":{"Sail":true}, + "Vehicles":[ + {"type":"vehicle/car","value":{"Wheels":4}}, + {"type":"vehicle/boat","value":{"Sail":true}} + ], + "Child":{ + "Bool":false, "Float64":0, "Int32":0, "Int64":"0", "Int64Ptr":null, + "String":"child", "StringPtrPtr":null, "Bytes":null, + "Time":"0001-01-01T00:00:00Z", + "Car":null, "Boat":{"Sail":false}, "Vehicles":null, "Child":null + } + }`, + }, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + bz, err := json.Marshal(tc.value) + require.NoError(t, err) + assert.JSONEq(t, tc.output, string(bz)) + }) + } +} + +func BenchmarkJsonMarshalStruct(b *testing.B) { + s := "string" + sPtr := &s + i64 := int64(64) + ti := time.Date(2020, 6, 2, 18, 5, 13, 4346374, time.FixedZone("UTC+2", 2*60*60)) + car := &Car{Wheels: 4} + boat := Boat{Sail: true} + for i := 0; i < b.N; i++ { + _, _ = json.Marshal(Struct{ + Bool: true, Float64: 3.14, Int32: 32, Int64: 64, Int64Ptr: &i64, + String: "foo", StringPtrPtr: &sPtr, Bytes: []byte{1, 2, 3}, + Time: ti, Car: car, Boat: boat, Vehicles: []Vehicle{car, boat}, + Child: &Struct{Bool: false, String: "child"}, private: "private", + }) + } +} diff --git a/libs/json/helpers_test.go b/libs/json/helpers_test.go new file mode 100644 index 0000000..4d5b648 --- /dev/null +++ b/libs/json/helpers_test.go @@ -0,0 +1,93 @@ +package json_test + +import ( + "time" + + "github.com/cometbft/cometbft/libs/json" +) + +// Register Car, an instance of the Vehicle interface. +func init() { + json.RegisterType(&Car{}, "vehicle/car") + json.RegisterType(Boat{}, "vehicle/boat") + json.RegisterType(PublicKey{}, "key/public") + json.RegisterType(PrivateKey{}, "key/private") +} + +type Vehicle interface { + Drive() error +} + +// Car is a pointer implementation of Vehicle. +type Car struct { + Wheels int32 +} + +func (c *Car) Drive() error { return nil } + +// Boat is a value implementation of Vehicle. +type Boat struct { + Sail bool +} + +func (b Boat) Drive() error { return nil } + +// These are public and private encryption keys. +type ( + PublicKey [8]byte + PrivateKey [8]byte +) + +// Custom has custom marshalers and unmarshalers, taking pointer receivers. +type CustomPtr struct { + Value string +} + +func (c *CustomPtr) MarshalJSON() ([]byte, error) { + return []byte("\"custom\""), nil +} + +func (c *CustomPtr) UnmarshalJSON(_ []byte) error { + c.Value = "custom" + return nil +} + +// CustomValue has custom marshalers and unmarshalers, taking value receivers (which usually doesn't +// make much sense since the unmarshaler can't change anything). +type CustomValue struct { + Value string +} + +func (c CustomValue) MarshalJSON() ([]byte, error) { + return []byte("\"custom\""), nil +} + +func (c CustomValue) UnmarshalJSON(_ []byte) error { + return nil +} + +// Tags tests JSON tags. +type Tags struct { + JSONName string `json:"name"` + OmitEmpty string `json:",omitempty"` + Hidden string `json:"-"` + Tags *Tags `json:"tags,omitempty"` +} + +// Struct tests structs with lots of contents. +type Struct struct { + Bool bool + Float64 float64 + Int32 int32 + Int64 int64 + Int64Ptr *int64 + String string + StringPtrPtr **string + Bytes []byte + Time time.Time + Car *Car + Boat Boat + Vehicles []Vehicle + Child *Struct + private string +} diff --git a/libs/json/structs.go b/libs/json/structs.go new file mode 100644 index 0000000..ba6720f --- /dev/null +++ b/libs/json/structs.go @@ -0,0 +1,88 @@ +package json + +import ( + "fmt" + "reflect" + "strings" + "unicode" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +var ( + // cache caches struct info. + cache = newStructInfoCache() +) + +// structCache is a cache of struct info. +type structInfoCache struct { + cmtsync.RWMutex + structInfos map[reflect.Type]*structInfo +} + +func newStructInfoCache() *structInfoCache { + return &structInfoCache{ + structInfos: make(map[reflect.Type]*structInfo), + } +} + +func (c *structInfoCache) get(rt reflect.Type) *structInfo { + c.RLock() + defer c.RUnlock() + return c.structInfos[rt] +} + +func (c *structInfoCache) set(rt reflect.Type, sInfo *structInfo) { + c.Lock() + defer c.Unlock() + c.structInfos[rt] = sInfo +} + +// structInfo contains JSON info for a struct. +type structInfo struct { + fields []*fieldInfo +} + +// fieldInfo contains JSON info for a struct field. +type fieldInfo struct { + jsonName string + omitEmpty bool + hidden bool +} + +// makeStructInfo generates structInfo for a struct as a reflect.Value. +func makeStructInfo(rt reflect.Type) *structInfo { + if rt.Kind() != reflect.Struct { + panic(fmt.Sprintf("can't make struct info for non-struct value %v", rt)) + } + if sInfo := cache.get(rt); sInfo != nil { + return sInfo + } + fields := make([]*fieldInfo, 0, rt.NumField()) + for i := 0; i < cap(fields); i++ { + frt := rt.Field(i) + fInfo := &fieldInfo{ + jsonName: frt.Name, + omitEmpty: false, + hidden: frt.Name == "" || !unicode.IsUpper(rune(frt.Name[0])), + } + o := frt.Tag.Get("json") + if o == "-" { + fInfo.hidden = true + } else if o != "" { + opts := strings.Split(o, ",") + if opts[0] != "" { + fInfo.jsonName = opts[0] + } + for _, o := range opts[1:] { + if o == "omitempty" { + fInfo.omitEmpty = true + } + } + } + fields = append(fields, fInfo) + } + sInfo := &structInfo{fields: fields} + cache.set(rt, sInfo) + return sInfo +} diff --git a/libs/json/types.go b/libs/json/types.go new file mode 100644 index 0000000..74212b0 --- /dev/null +++ b/libs/json/types.go @@ -0,0 +1,109 @@ +package json + +import ( + "errors" + "fmt" + "reflect" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +var ( + // typeRegistry contains globally registered types for JSON encoding/decoding. + typeRegistry = newTypes() +) + +// RegisterType registers a type for Amino-compatible interface encoding in the global type +// registry. These types will be encoded with a type wrapper `{"type":"","value":}` +// regardless of which interface they are wrapped in (if any). If the type is a pointer, it will +// still be valid both for value and pointer types, but decoding into an interface will generate +// the a value or pointer based on the registered type. +// +// Should only be called in init() functions, as it panics on error. +func RegisterType(_type interface{}, name string) { + if _type == nil { + panic("cannot register nil type") + } + err := typeRegistry.register(name, reflect.ValueOf(_type).Type()) + if err != nil { + panic(err) + } +} + +// typeInfo contains type information. +type typeInfo struct { + name string + rt reflect.Type + returnPtr bool +} + +// types is a type registry. It is safe for concurrent use. +type types struct { + cmtsync.RWMutex + byType map[reflect.Type]*typeInfo + byName map[string]*typeInfo +} + +// newTypes creates a new type registry. +func newTypes() types { + return types{ + byType: map[reflect.Type]*typeInfo{}, + byName: map[string]*typeInfo{}, + } +} + +// registers the given type with the given name. The name and type must not be registered already. +func (t *types) register(name string, rt reflect.Type) error { + if name == "" { + return errors.New("name cannot be empty") + } + // If this is a pointer type, we recursively resolve until we get a bare type, but register that + // we should return pointers. + returnPtr := false + for rt.Kind() == reflect.Ptr { + returnPtr = true + rt = rt.Elem() + } + tInfo := &typeInfo{ + name: name, + rt: rt, + returnPtr: returnPtr, + } + + t.Lock() + defer t.Unlock() + if _, ok := t.byName[tInfo.name]; ok { + return fmt.Errorf("a type with name %q is already registered", name) + } + if _, ok := t.byType[tInfo.rt]; ok { + return fmt.Errorf("the type %v is already registered", rt) + } + t.byName[name] = tInfo + t.byType[rt] = tInfo + return nil +} + +// lookup looks up a type from a name, or nil if not registered. +func (t *types) lookup(name string) (reflect.Type, bool) { + t.RLock() + defer t.RUnlock() + tInfo := t.byName[name] + if tInfo == nil { + return nil, false + } + return tInfo.rt, tInfo.returnPtr +} + +// name looks up the name of a type, or empty if not registered. Unwraps pointers as necessary. +func (t *types) name(rt reflect.Type) string { + for rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + t.RLock() + defer t.RUnlock() + tInfo := t.byType[rt] + if tInfo == nil { + return "" + } + return tInfo.name +} diff --git a/libs/log/filter.go b/libs/log/filter.go new file mode 100644 index 0000000..7a60f6d --- /dev/null +++ b/libs/log/filter.go @@ -0,0 +1,196 @@ +package log + +import "fmt" + +type level byte + +const ( + levelDebug level = 1 << iota + levelInfo + levelError +) + +type filter struct { + next Logger + allowed level // XOR'd levels for default case + initiallyAllowed level // XOR'd levels for initial case + allowedKeyvals map[keyval]level // When key-value match, use this level +} + +type keyval struct { + key interface{} + value interface{} +} + +// NewFilter wraps next and implements filtering. See the commentary on the +// Option functions for a detailed description of how to configure levels. If +// no options are provided, all leveled log events created with Debug, Info or +// Error helper methods are squelched. +func NewFilter(next Logger, options ...Option) Logger { + l := &filter{ + next: next, + allowedKeyvals: make(map[keyval]level), + } + for _, option := range options { + option(l) + } + l.initiallyAllowed = l.allowed + return l +} + +func (l *filter) Info(msg string, keyvals ...interface{}) { + levelAllowed := l.allowed&levelInfo != 0 + if !levelAllowed { + return + } + l.next.Info(msg, keyvals...) +} + +func (l *filter) Debug(msg string, keyvals ...interface{}) { + levelAllowed := l.allowed&levelDebug != 0 + if !levelAllowed { + return + } + l.next.Debug(msg, keyvals...) +} + +func (l *filter) Error(msg string, keyvals ...interface{}) { + levelAllowed := l.allowed&levelError != 0 + if !levelAllowed { + return + } + l.next.Error(msg, keyvals...) +} + +// With implements Logger by constructing a new filter with a keyvals appended +// to the logger. +// +// If custom level was set for a keyval pair using one of the +// Allow*With methods, it is used as the logger's level. +// +// Examples: +// +// logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto")) +// logger.With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto" +// +// logger = log.NewFilter(logger, log.AllowError(), +// log.AllowInfoWith("module", "crypto"), +// log.AllowNoneWith("user", "Sam")) +// logger.With("module", "crypto", "user", "Sam").Info("Hello") # returns nil +// +// logger = log.NewFilter(logger, +// log.AllowError(), +// log.AllowInfoWith("module", "crypto"), log.AllowNoneWith("user", "Sam")) +// logger.With("user", "Sam").With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto user=Sam" +func (l *filter) With(keyvals ...interface{}) Logger { + keyInAllowedKeyvals := false + + for i := len(keyvals) - 2; i >= 0; i -= 2 { + for kv, allowed := range l.allowedKeyvals { + if keyvals[i] == kv.key { + keyInAllowedKeyvals = true + // Example: + // logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto")) + // logger.With("module", "crypto") + if keyvals[i+1] == kv.value { + return &filter{ + next: l.next.With(keyvals...), + allowed: allowed, // set the desired level + allowedKeyvals: l.allowedKeyvals, + initiallyAllowed: l.initiallyAllowed, + } + } + } + } + } + + // Example: + // logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto")) + // logger.With("module", "main") + if keyInAllowedKeyvals { + return &filter{ + next: l.next.With(keyvals...), + allowed: l.initiallyAllowed, // return back to initially allowed + allowedKeyvals: l.allowedKeyvals, + initiallyAllowed: l.initiallyAllowed, + } + } + + return &filter{ + next: l.next.With(keyvals...), + allowed: l.allowed, // simply continue with the current level + allowedKeyvals: l.allowedKeyvals, + initiallyAllowed: l.initiallyAllowed, + } +} + +//-------------------------------------------------------------------------------- + +// Option sets a parameter for the filter. +type Option func(*filter) + +// AllowLevel returns an option for the given level or error if no option exist +// for such level. +func AllowLevel(lvl string) (Option, error) { + switch lvl { + case "debug": + return AllowDebug(), nil + case "info": + return AllowInfo(), nil + case "error": + return AllowError(), nil + case "none": + return AllowNone(), nil + default: + return nil, fmt.Errorf("expected either \"info\", \"debug\", \"error\" or \"none\" level, given %s", lvl) + } +} + +// AllowAll is an alias for AllowDebug. +func AllowAll() Option { + return AllowDebug() +} + +// AllowDebug allows error, info and debug level log events to pass. +func AllowDebug() Option { + return allowed(levelError | levelInfo | levelDebug) +} + +// AllowInfo allows error and info level log events to pass. +func AllowInfo() Option { + return allowed(levelError | levelInfo) +} + +// AllowError allows only error level log events to pass. +func AllowError() Option { + return allowed(levelError) +} + +// AllowNone allows no leveled log events to pass. +func AllowNone() Option { + return allowed(0) +} + +func allowed(allowed level) Option { + return func(l *filter) { l.allowed = allowed } +} + +// AllowDebugWith allows error, info and debug level log events to pass for a specific key value pair. +func AllowDebugWith(key interface{}, value interface{}) Option { + return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError | levelInfo | levelDebug } +} + +// AllowInfoWith allows error and info level log events to pass for a specific key value pair. +func AllowInfoWith(key interface{}, value interface{}) Option { + return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError | levelInfo } +} + +// AllowErrorWith allows only error level log events to pass for a specific key value pair. +func AllowErrorWith(key interface{}, value interface{}) Option { + return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError } +} + +// AllowNoneWith allows no leveled log events to pass for a specific key value pair. +func AllowNoneWith(key interface{}, value interface{}) Option { + return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = 0 } +} diff --git a/libs/log/filter_test.go b/libs/log/filter_test.go new file mode 100644 index 0000000..f8e8144 --- /dev/null +++ b/libs/log/filter_test.go @@ -0,0 +1,140 @@ +package log_test + +import ( + "bytes" + "strings" + "testing" + + "github.com/cometbft/cometbft/libs/log" +) + +func TestVariousLevels(t *testing.T) { + testCases := []struct { + name string + allowed log.Option + want string + }{ + { + "AllowAll", + log.AllowAll(), + strings.Join([]string{ + `{"_msg":"here","level":"debug","this is":"debug log"}`, + `{"_msg":"here","level":"info","this is":"info log"}`, + `{"_msg":"here","level":"error","this is":"error log"}`, + }, "\n"), + }, + { + "AllowDebug", + log.AllowDebug(), + strings.Join([]string{ + `{"_msg":"here","level":"debug","this is":"debug log"}`, + `{"_msg":"here","level":"info","this is":"info log"}`, + `{"_msg":"here","level":"error","this is":"error log"}`, + }, "\n"), + }, + { + "AllowInfo", + log.AllowInfo(), + strings.Join([]string{ + `{"_msg":"here","level":"info","this is":"info log"}`, + `{"_msg":"here","level":"error","this is":"error log"}`, + }, "\n"), + }, + { + "AllowError", + log.AllowError(), + strings.Join([]string{ + `{"_msg":"here","level":"error","this is":"error log"}`, + }, "\n"), + }, + { + "AllowNone", + log.AllowNone(), + ``, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + logger := log.NewFilter(log.NewTMJSONLoggerNoTS(&buf), tc.allowed) + + logger.Debug("here", "this is", "debug log") + logger.Info("here", "this is", "info log") + logger.Error("here", "this is", "error log") + + if want, have := tc.want, strings.TrimSpace(buf.String()); want != have { + t.Errorf("\nwant:\n%s\nhave:\n%s", want, have) + } + }) + } +} + +func TestLevelContext(t *testing.T) { + var buf bytes.Buffer + + logger := log.NewTMJSONLoggerNoTS(&buf) + logger = log.NewFilter(logger, log.AllowError()) + logger = logger.With("context", "value") + + logger.Error("foo", "bar", "baz") + + want := `{"_msg":"foo","bar":"baz","context":"value","level":"error"}` + have := strings.TrimSpace(buf.String()) + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } + + buf.Reset() + logger.Info("foo", "bar", "baz") + if want, have := ``, strings.TrimSpace(buf.String()); want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } +} + +func TestVariousAllowWith(t *testing.T) { + var buf bytes.Buffer + + logger := log.NewTMJSONLoggerNoTS(&buf) + + logger1 := log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("context", "value")) + logger1.With("context", "value").Info("foo", "bar", "baz") + + want := `{"_msg":"foo","bar":"baz","context":"value","level":"info"}` + have := strings.TrimSpace(buf.String()) + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } + + buf.Reset() + + logger2 := log.NewFilter( + logger, + log.AllowError(), + log.AllowInfoWith("context", "value"), + log.AllowNoneWith("user", "Sam"), + ) + + logger2.With("context", "value", "user", "Sam").Info("foo", "bar", "baz") + if want, have := ``, strings.TrimSpace(buf.String()); want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } + + buf.Reset() + + logger3 := log.NewFilter( + logger, + log.AllowError(), + log.AllowInfoWith("context", "value"), + log.AllowNoneWith("user", "Sam"), + ) + + logger3.With("user", "Sam").With("context", "value").Info("foo", "bar", "baz") + + want = `{"_msg":"foo","bar":"baz","context":"value","level":"info","user":"Sam"}` + have = strings.TrimSpace(buf.String()) + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } +} diff --git a/libs/log/lazy.go b/libs/log/lazy.go new file mode 100644 index 0000000..ddf170e --- /dev/null +++ b/libs/log/lazy.go @@ -0,0 +1,42 @@ +package log + +import ( + "fmt" + + cmtbytes "github.com/cometbft/cometbft/libs/bytes" +) + +type LazySprintf struct { + format string + args []interface{} +} + +// NewLazySprintf defers fmt.Sprintf until the Stringer interface is invoked. +// This is particularly useful for avoiding calling Sprintf when debugging is not +// active. +func NewLazySprintf(format string, args ...interface{}) *LazySprintf { + return &LazySprintf{format, args} +} + +func (l *LazySprintf) String() string { + return fmt.Sprintf(l.format, l.args...) +} + +type LazyBlockHash struct { + block hashable +} + +type hashable interface { + Hash() cmtbytes.HexBytes +} + +// NewLazyBlockHash defers block Hash until the Stringer interface is invoked. +// This is particularly useful for avoiding calling Sprintf when debugging is not +// active. +func NewLazyBlockHash(block hashable) *LazyBlockHash { + return &LazyBlockHash{block} +} + +func (l *LazyBlockHash) String() string { + return l.block.Hash().String() +} diff --git a/libs/log/logger.go b/libs/log/logger.go new file mode 100644 index 0000000..6ee3050 --- /dev/null +++ b/libs/log/logger.go @@ -0,0 +1,30 @@ +package log + +import ( + "io" + + kitlog "github.com/go-kit/log" +) + +// Logger is what any CometBFT library should take. +type Logger interface { + Debug(msg string, keyvals ...interface{}) + Info(msg string, keyvals ...interface{}) + Error(msg string, keyvals ...interface{}) + + With(keyvals ...interface{}) Logger +} + +// NewSyncWriter returns a new writer that is safe for concurrent use by +// multiple goroutines. Writes to the returned writer are passed on to w. If +// another write is already in progress, the calling goroutine blocks until +// the writer is available. +// +// If w implements the following interface, so does the returned writer. +// +// interface { +// Fd() uintptr +// } +func NewSyncWriter(w io.Writer) io.Writer { + return kitlog.NewSyncWriter(w) +} diff --git a/libs/log/nop_logger.go b/libs/log/nop_logger.go new file mode 100644 index 0000000..73dba5c --- /dev/null +++ b/libs/log/nop_logger.go @@ -0,0 +1,17 @@ +package log + +type nopLogger struct{} + +// Interface assertions +var _ Logger = (*nopLogger)(nil) + +// NewNopLogger returns a logger that doesn't do anything. +func NewNopLogger() Logger { return &nopLogger{} } + +func (nopLogger) Info(string, ...interface{}) {} +func (nopLogger) Debug(string, ...interface{}) {} +func (nopLogger) Error(string, ...interface{}) {} + +func (l *nopLogger) With(...interface{}) Logger { + return l +} diff --git a/libs/log/testing_logger.go b/libs/log/testing_logger.go new file mode 100644 index 0000000..30469e1 --- /dev/null +++ b/libs/log/testing_logger.go @@ -0,0 +1,60 @@ +package log + +import ( + "io" + "os" + "testing" + + "github.com/go-kit/log/term" +) + +var ( + // reuse the same logger across all tests + _testingLogger Logger +) + +// TestingLogger returns a TMLogger which writes to STDOUT if testing being run +// with the verbose (-v) flag, NopLogger otherwise. +// +// Note that the call to TestingLogger() must be made +// inside a test (not in the init func) because +// verbose flag only set at the time of testing. +func TestingLogger() Logger { + return TestingLoggerWithOutput(os.Stdout) +} + +// TestingLoggerWOutput returns a TMLogger which writes to (w io.Writer) if testing being run +// with the verbose (-v) flag, NopLogger otherwise. +// +// Note that the call to TestingLoggerWithOutput(w io.Writer) must be made +// inside a test (not in the init func) because +// verbose flag only set at the time of testing. +func TestingLoggerWithOutput(w io.Writer) Logger { + if _testingLogger != nil { + return _testingLogger + } + + if testing.Verbose() { + _testingLogger = NewTMLogger(NewSyncWriter(w)) + } else { + _testingLogger = NewNopLogger() + } + + return _testingLogger +} + +// TestingLoggerWithColorFn allow you to provide your own color function. See +// TestingLogger for documentation. +func TestingLoggerWithColorFn(colorFn func(keyvals ...interface{}) term.FgBgColor) Logger { + if _testingLogger != nil { + return _testingLogger + } + + if testing.Verbose() { + _testingLogger = NewTMLoggerWithColorFn(NewSyncWriter(os.Stdout), colorFn) + } else { + _testingLogger = NewNopLogger() + } + + return _testingLogger +} diff --git a/libs/log/tm_json_logger.go b/libs/log/tm_json_logger.go new file mode 100644 index 0000000..da0b273 --- /dev/null +++ b/libs/log/tm_json_logger.go @@ -0,0 +1,24 @@ +package log + +import ( + "io" + + kitlog "github.com/go-kit/log" +) + +// NewTMJSONLogger returns a Logger that encodes keyvals to the Writer as a +// single JSON object. Each log event produces no more than one call to +// w.Write. The passed Writer must be safe for concurrent use by multiple +// goroutines if the returned Logger will be used concurrently. +func NewTMJSONLogger(w io.Writer) Logger { + logger := kitlog.NewJSONLogger(w) + logger = kitlog.With(logger, "ts", kitlog.DefaultTimestampUTC) + return &tmLogger{logger} +} + +// NewTMJSONLoggerNoTS is the same as NewTMJSONLogger, but without the +// timestamp. +func NewTMJSONLoggerNoTS(w io.Writer) Logger { + logger := kitlog.NewJSONLogger(w) + return &tmLogger{logger} +} diff --git a/libs/log/tm_logger.go b/libs/log/tm_logger.go new file mode 100644 index 0000000..1b49475 --- /dev/null +++ b/libs/log/tm_logger.go @@ -0,0 +1,86 @@ +package log + +import ( + "fmt" + "io" + + kitlog "github.com/go-kit/log" + kitlevel "github.com/go-kit/log/level" + "github.com/go-kit/log/term" +) + +const ( + msgKey = "_msg" // "_" prefixed to avoid collisions + moduleKey = "module" +) + +type tmLogger struct { + srcLogger kitlog.Logger +} + +// Interface assertions +var _ Logger = (*tmLogger)(nil) + +// NewTMLogger returns a logger that encodes msg and keyvals to the Writer +// using go-kit's log as an underlying logger and our custom formatter. Note +// that underlying logger could be swapped with something else. +func NewTMLogger(w io.Writer) Logger { + // Color by level value + colorFn := func(keyvals ...interface{}) term.FgBgColor { + if keyvals[0] != kitlevel.Key() { + panic(fmt.Sprintf("expected level key to be first, got %v", keyvals[0])) + } + switch keyvals[1].(kitlevel.Value).String() { + case "debug": + return term.FgBgColor{Fg: term.DarkGray} + case "error": + return term.FgBgColor{Fg: term.Red} + default: + return term.FgBgColor{} + } + } + + return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)} +} + +// NewTMLoggerWithColorFn allows you to provide your own color function. See +// NewTMLogger for documentation. +func NewTMLoggerWithColorFn(w io.Writer, colorFn func(keyvals ...interface{}) term.FgBgColor) Logger { + return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)} +} + +// Info logs a message at level Info. +func (l *tmLogger) Info(msg string, keyvals ...interface{}) { + lWithLevel := kitlevel.Info(l.srcLogger) + + if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil { + errLogger := kitlevel.Error(l.srcLogger) + kitlog.With(errLogger, msgKey, msg).Log("err", err) //nolint:errcheck // no need to check error again + } +} + +// Debug logs a message at level Debug. +func (l *tmLogger) Debug(msg string, keyvals ...interface{}) { + lWithLevel := kitlevel.Debug(l.srcLogger) + + if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil { + errLogger := kitlevel.Error(l.srcLogger) + kitlog.With(errLogger, msgKey, msg).Log("err", err) //nolint:errcheck // no need to check error again + } +} + +// Error logs a message at level Error. +func (l *tmLogger) Error(msg string, keyvals ...interface{}) { + lWithLevel := kitlevel.Error(l.srcLogger) + + lWithMsg := kitlog.With(lWithLevel, msgKey, msg) + if err := lWithMsg.Log(keyvals...); err != nil { + lWithMsg.Log("err", err) //nolint:errcheck // no need to check error again + } +} + +// With returns a new contextual logger with keyvals prepended to those passed +// to calls to Info, Debug or Error. +func (l *tmLogger) With(keyvals ...interface{}) Logger { + return &tmLogger{kitlog.With(l.srcLogger, keyvals...)} +} diff --git a/libs/log/tm_logger_test.go b/libs/log/tm_logger_test.go new file mode 100644 index 0000000..43635c3 --- /dev/null +++ b/libs/log/tm_logger_test.go @@ -0,0 +1,112 @@ +package log_test + +import ( + "bytes" + "io" + "strings" + "testing" + + "github.com/cometbft/cometbft/libs/log" +) + +func TestLoggerLogsItsErrors(t *testing.T) { + var buf bytes.Buffer + + logger := log.NewTMLogger(&buf) + logger.Info("foo", "baz baz", "bar") + msg := strings.TrimSpace(buf.String()) + if !strings.Contains(msg, "foo") { + t.Errorf("expected logger msg to contain ErrInvalidKey, got %s", msg) + } +} + +func TestInfo(t *testing.T) { + var bufInfo bytes.Buffer + + l := log.NewTMLogger(&bufInfo) + l.Info("Client initialized with old header (trusted is more recent)", + "old", 42, + "trustedHeight", "forty two", + "trustedHash", []byte("test me")) + + msg := strings.TrimSpace(bufInfo.String()) + + // Remove the timestamp information to allow + // us to test against the expected message. + receivedmsg := strings.Split(msg, "] ")[1] + + const expectedmsg = `Client initialized with old header + (trusted is more recent) old=42 trustedHeight="forty two" + trustedHash=74657374206D65` + if strings.EqualFold(receivedmsg, expectedmsg) { + t.Fatalf("received %s, expected %s", receivedmsg, expectedmsg) + } +} + +func TestDebug(t *testing.T) { + var bufDebug bytes.Buffer + + ld := log.NewTMLogger(&bufDebug) + ld.Debug("Client initialized with old header (trusted is more recent)", + "old", 42, + "trustedHeight", "forty two", + "trustedHash", []byte("test me")) + + msg := strings.TrimSpace(bufDebug.String()) + + // Remove the timestamp information to allow + // us to test against the expected message. + receivedmsg := strings.Split(msg, "] ")[1] + + const expectedmsg = `Client initialized with old header + (trusted is more recent) old=42 trustedHeight="forty two" + trustedHash=74657374206D65` + if strings.EqualFold(receivedmsg, expectedmsg) { + t.Fatalf("received %s, expected %s", receivedmsg, expectedmsg) + } +} + +func TestError(t *testing.T) { + var bufErr bytes.Buffer + + le := log.NewTMLogger(&bufErr) + le.Error("Client initialized with old header (trusted is more recent)", + "old", 42, + "trustedHeight", "forty two", + "trustedHash", []byte("test me")) + + msg := strings.TrimSpace(bufErr.String()) + + // Remove the timestamp information to allow + // us to test against the expected message. + receivedmsg := strings.Split(msg, "] ")[1] + + const expectedmsg = `Client initialized with old header + (trusted is more recent) old=42 trustedHeight="forty two" + trustedHash=74657374206D65` + if strings.EqualFold(receivedmsg, expectedmsg) { + t.Fatalf("received %s, expected %s", receivedmsg, expectedmsg) + } +} + +func BenchmarkTMLoggerSimple(b *testing.B) { + benchmarkRunner(b, log.NewTMLogger(io.Discard), baseInfoMessage) +} + +func BenchmarkTMLoggerContextual(b *testing.B) { + benchmarkRunner(b, log.NewTMLogger(io.Discard), withInfoMessage) +} + +func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) { + lc := logger.With("common_key", "common_value") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + f(lc) + } +} + +var ( + baseInfoMessage = func(logger log.Logger) { logger.Info("foo_message", "foo_key", "foo_value") } + withInfoMessage = func(logger log.Logger) { logger.With("a", "b").Info("c", "d", "f") } +) diff --git a/libs/log/tmfmt_logger.go b/libs/log/tmfmt_logger.go new file mode 100644 index 0000000..222c5bd --- /dev/null +++ b/libs/log/tmfmt_logger.go @@ -0,0 +1,141 @@ +package log + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "strings" + "sync" + "time" + + kitlog "github.com/go-kit/log" + kitlevel "github.com/go-kit/log/level" + "github.com/go-logfmt/logfmt" +) + +type tmfmtEncoder struct { + *logfmt.Encoder + buf bytes.Buffer +} + +func (l *tmfmtEncoder) Reset() { + l.Encoder.Reset() + l.buf.Reset() +} + +var tmfmtEncoderPool = sync.Pool{ + New: func() interface{} { + var enc tmfmtEncoder + enc.Encoder = logfmt.NewEncoder(&enc.buf) + return &enc + }, +} + +type tmfmtLogger struct { + w io.Writer +} + +// NewTMFmtLogger returns a logger that encodes keyvals to the Writer in +// CometBFT custom format. Note complex types (structs, maps, slices) +// formatted as "%+v". +// +// Each log event produces no more than one call to w.Write. +// The passed Writer must be safe for concurrent use by multiple goroutines if +// the returned Logger will be used concurrently. +func NewTMFmtLogger(w io.Writer) kitlog.Logger { + return &tmfmtLogger{w} +} + +func (l tmfmtLogger) Log(keyvals ...interface{}) error { + enc := tmfmtEncoderPool.Get().(*tmfmtEncoder) + enc.Reset() + defer tmfmtEncoderPool.Put(enc) + + const unknown = "unknown" + lvl := "none" + msg := unknown + module := unknown + + // indexes of keys to skip while encoding later + excludeIndexes := make([]int, 0) + + for i := 0; i < len(keyvals)-1; i += 2 { + // Extract level + switch keyvals[i] { + case kitlevel.Key(): + excludeIndexes = append(excludeIndexes, i) + switch keyvals[i+1].(type) { //nolint:gocritic + case string: + lvl = keyvals[i+1].(string) + case kitlevel.Value: + lvl = keyvals[i+1].(kitlevel.Value).String() + default: + panic(fmt.Sprintf("level value of unknown type %T", keyvals[i+1])) + } + // and message + case msgKey: + excludeIndexes = append(excludeIndexes, i) + msg = keyvals[i+1].(string) + // and module (could be multiple keyvals; if such case last keyvalue wins) + case moduleKey: + excludeIndexes = append(excludeIndexes, i) + module = keyvals[i+1].(string) + } + + // Print []byte as a hexadecimal string (uppercased) + if b, ok := keyvals[i+1].([]byte); ok { + keyvals[i+1] = strings.ToUpper(hex.EncodeToString(b)) + } + + // Realize stringers + if s, ok := keyvals[i+1].(fmt.Stringer); ok { + keyvals[i+1] = s.String() + } + + } + + // Form a custom CometBFT line + // + // Example: + // D[2016-05-02|11:06:44.322] Stopping AddrBook (ignoring: already stopped) + // + // Description: + // D - first character of the level, uppercase (ASCII only) + // [2016-05-02|11:06:44.322] - our time format (see https://golang.org/src/time/format.go) + // Stopping ... - message + enc.buf.WriteString(fmt.Sprintf("%c[%s] %-44s ", lvl[0]-32, time.Now().Format("2006-01-02|15:04:05.000"), msg)) + + if module != unknown { + enc.buf.WriteString("module=" + module + " ") + } + +KeyvalueLoop: + for i := 0; i < len(keyvals)-1; i += 2 { + for _, j := range excludeIndexes { + if i == j { + continue KeyvalueLoop + } + } + + err := enc.EncodeKeyval(keyvals[i], keyvals[i+1]) + if err == logfmt.ErrUnsupportedValueType { + enc.EncodeKeyval(keyvals[i], fmt.Sprintf("%+v", keyvals[i+1])) //nolint:errcheck // no need to check error again + } else if err != nil { + return err + } + } + + // Add newline to the end of the buffer + if err := enc.EndRecord(); err != nil { + return err + } + + // The Logger interface requires implementations to be safe for concurrent + // use by multiple goroutines. For this implementation that means making + // only one call to l.w.Write() for each call to Log. + if _, err := l.w.Write(enc.buf.Bytes()); err != nil { + return err + } + return nil +} diff --git a/libs/log/tmfmt_logger_test.go b/libs/log/tmfmt_logger_test.go new file mode 100644 index 0000000..118c895 --- /dev/null +++ b/libs/log/tmfmt_logger_test.go @@ -0,0 +1,125 @@ +package log_test + +import ( + "bytes" + "errors" + "io" + "math" + "regexp" + "testing" + + kitlog "github.com/go-kit/log" + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/libs/log" +) + +func TestTMFmtLogger(t *testing.T) { + t.Parallel() + buf := &bytes.Buffer{} + logger := log.NewTMFmtLogger(buf) + + if err := logger.Log("hello", "world"); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] unknown \s+ hello=world\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("a", 1, "err", errors.New("error")); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] unknown \s+ a=1 err=error\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] unknown \s+ std_map=map\[1:2\] my_map=special_behavior\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("level", "error"); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`E\[.+\] unknown \s+\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("_msg", "Hello"); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] Hello \s+\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("module", "main", "module", "crypto", "module", "wire"); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] unknown \s+module=wire\s+\n$`), buf.String()) + + buf.Reset() + if err := logger.Log("hash", []byte("test me")); err != nil { + t.Fatal(err) + } + assert.Regexp(t, regexp.MustCompile(`N\[.+\] unknown \s+ hash=74657374206D65\n$`), buf.String()) +} + +func BenchmarkTMFmtLoggerSimple(b *testing.B) { + benchmarkRunnerKitlog(b, log.NewTMFmtLogger(io.Discard), baseMessage) +} + +func BenchmarkTMFmtLoggerContextual(b *testing.B) { + benchmarkRunnerKitlog(b, log.NewTMFmtLogger(io.Discard), withMessage) +} + +func TestTMFmtLoggerConcurrency(t *testing.T) { + t.Parallel() + testConcurrency(t, log.NewTMFmtLogger(io.Discard), 10000) +} + +func benchmarkRunnerKitlog(b *testing.B, logger kitlog.Logger, f func(kitlog.Logger)) { + lc := kitlog.With(logger, "common_key", "common_value") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + f(lc) + } +} + +var ( + baseMessage = func(logger kitlog.Logger) { logger.Log("foo_key", "foo_value") } //nolint:errcheck + withMessage = func(logger kitlog.Logger) { kitlog.With(logger, "a", "b").Log("d", "f") } //nolint:errcheck +) + +// These test are designed to be run with the race detector. + +func testConcurrency(t *testing.T, logger kitlog.Logger, total int) { + n := int(math.Sqrt(float64(total))) + share := total / n + + errC := make(chan error, n) + + for i := 0; i < n; i++ { + go func() { + errC <- spam(logger, share) + }() + } + + for i := 0; i < n; i++ { + err := <-errC + if err != nil { + t.Fatalf("concurrent logging error: %v", err) + } + } +} + +func spam(logger kitlog.Logger, count int) error { + for i := 0; i < count; i++ { + err := logger.Log("key", i) + if err != nil { + return err + } + } + return nil +} + +type mymap map[int]int + +func (m mymap) String() string { return "special_behavior" } diff --git a/libs/log/tracing_logger.go b/libs/log/tracing_logger.go new file mode 100644 index 0000000..f2d6a7e --- /dev/null +++ b/libs/log/tracing_logger.go @@ -0,0 +1,76 @@ +package log + +import ( + "fmt" + + "github.com/pkg/errors" +) + +// NewTracingLogger enables tracing by wrapping all errors (if they +// implement stackTracer interface) in tracedError. +// +// All errors returned by https://github.com/pkg/errors implement stackTracer +// interface. +// +// For debugging purposes only as it doubles the amount of allocations. +func NewTracingLogger(next Logger) Logger { + return &tracingLogger{ + next: next, + } +} + +type stackTracer interface { + error + StackTrace() errors.StackTrace +} + +type tracingLogger struct { + next Logger +} + +func (l *tracingLogger) Info(msg string, keyvals ...interface{}) { + l.next.Info(msg, formatErrors(keyvals)...) +} + +func (l *tracingLogger) Debug(msg string, keyvals ...interface{}) { + l.next.Debug(msg, formatErrors(keyvals)...) +} + +func (l *tracingLogger) Error(msg string, keyvals ...interface{}) { + l.next.Error(msg, formatErrors(keyvals)...) +} + +func (l *tracingLogger) With(keyvals ...interface{}) Logger { + return &tracingLogger{next: l.next.With(formatErrors(keyvals)...)} +} + +func formatErrors(keyvals []interface{}) []interface{} { + newKeyvals := make([]interface{}, len(keyvals)) + copy(newKeyvals, keyvals) + for i := 0; i < len(newKeyvals)-1; i += 2 { + if err, ok := newKeyvals[i+1].(stackTracer); ok { + newKeyvals[i+1] = tracedError{err} + } + } + return newKeyvals +} + +// tracedError wraps a stackTracer and just makes the Error() result +// always return a full stack trace. +type tracedError struct { + wrapped stackTracer +} + +var _ stackTracer = tracedError{} + +func (t tracedError) StackTrace() errors.StackTrace { + return t.wrapped.StackTrace() +} + +func (t tracedError) Cause() error { + return t.wrapped +} + +func (t tracedError) Error() string { + return fmt.Sprintf("%+v", t.wrapped) +} diff --git a/libs/log/tracing_logger_test.go b/libs/log/tracing_logger_test.go new file mode 100644 index 0000000..61c88e5 --- /dev/null +++ b/libs/log/tracing_logger_test.go @@ -0,0 +1,65 @@ +package log_test + +import ( + "bytes" + stderr "errors" + "fmt" + "strings" + "testing" + + "github.com/pkg/errors" + + "github.com/cometbft/cometbft/libs/log" +) + +func TestTracingLogger(t *testing.T) { + var buf bytes.Buffer + + logger := log.NewTMJSONLoggerNoTS(&buf) + + logger1 := log.NewTracingLogger(logger) + err1 := errors.New("courage is grace under pressure") + err2 := errors.New("it does not matter how slowly you go, so long as you do not stop") + logger1.With("err1", err1).Info("foo", "err2", err2) + + want := strings.ReplaceAll( + strings.ReplaceAll( + `{"_msg":"foo","err1":"`+ + fmt.Sprintf("%+v", err1)+ + `","err2":"`+ + fmt.Sprintf("%+v", err2)+ + `","level":"info"}`, + "\t", "", + ), "\n", "") + have := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(buf.String()), "\\n", ""), "\\t", "") + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } + + buf.Reset() + + logger.With( + "err1", stderr.New("opportunities don't happen. You create them"), + ).Info( + "foo", "err2", stderr.New("once you choose hope, anything's possible"), + ) + + want = `{"_msg":"foo",` + + `"err1":"opportunities don't happen. You create them",` + + `"err2":"once you choose hope, anything's possible",` + + `"level":"info"}` + have = strings.TrimSpace(buf.String()) + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } + + buf.Reset() + + logger.With("user", "Sam").With("context", "value").Info("foo", "bar", "baz") + + want = `{"_msg":"foo","bar":"baz","context":"value","level":"info","user":"Sam"}` + have = strings.TrimSpace(buf.String()) + if want != have { + t.Errorf("\nwant '%s'\nhave '%s'", want, have) + } +} diff --git a/libs/math/fraction.go b/libs/math/fraction.go new file mode 100644 index 0000000..e17de19 --- /dev/null +++ b/libs/math/fraction.go @@ -0,0 +1,48 @@ +package math + +import ( + "errors" + "fmt" + "math" + "strconv" + "strings" +) + +// Fraction defined in terms of a numerator divided by a denominator in uint64 +// format. Fraction must be positive. +type Fraction struct { + // The portion of the denominator in the faction, e.g. 2 in 2/3. + Numerator uint64 `json:"numerator"` + // The value by which the numerator is divided, e.g. 3 in 2/3. + Denominator uint64 `json:"denominator"` +} + +func (fr Fraction) String() string { + return fmt.Sprintf("%d/%d", fr.Numerator, fr.Denominator) +} + +// ParseFractions takes the string of a fraction as input i.e "2/3" and converts this +// to the equivalent fraction else returns an error. The format of the string must be +// one number followed by a slash (/) and then the other number. +func ParseFraction(f string) (Fraction, error) { + o := strings.Split(f, "/") + if len(o) != 2 { + return Fraction{}, errors.New("incorrect formating: should have a single slash i.e. \"1/3\"") + } + numerator, err := strconv.ParseUint(o[0], 10, 64) + if err != nil { + return Fraction{}, fmt.Errorf("incorrect formatting, err: %w", err) + } + + denominator, err := strconv.ParseUint(o[1], 10, 64) + if err != nil { + return Fraction{}, fmt.Errorf("incorrect formatting, err: %w", err) + } + if denominator == 0 { + return Fraction{}, errors.New("denominator can't be 0") + } + if numerator > math.MaxInt64 || denominator > math.MaxInt64 { + return Fraction{}, fmt.Errorf("value overflow, numerator and denominator must be less than %d", int64(math.MaxInt64)) + } + return Fraction{Numerator: numerator, Denominator: denominator}, nil +} diff --git a/libs/math/fraction_test.go b/libs/math/fraction_test.go new file mode 100644 index 0000000..b4afd08 --- /dev/null +++ b/libs/math/fraction_test.go @@ -0,0 +1,86 @@ +package math + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseFraction(t *testing.T) { + + testCases := []struct { + f string + exp Fraction + err bool + }{ + { + f: "2/3", + exp: Fraction{2, 3}, + err: false, + }, + { + f: "15/5", + exp: Fraction{15, 5}, + err: false, + }, + // test divide by zero error + { + f: "2/0", + exp: Fraction{}, + err: true, + }, + // test negative + { + f: "-1/2", + exp: Fraction{}, + err: true, + }, + { + f: "1/-2", + exp: Fraction{}, + err: true, + }, + // test overflow + { + f: "9223372036854775808/2", + exp: Fraction{}, + err: true, + }, + { + f: "2/9223372036854775808", + exp: Fraction{}, + err: true, + }, + { + f: "2/3/4", + exp: Fraction{}, + err: true, + }, + { + f: "123", + exp: Fraction{}, + err: true, + }, + { + f: "1a2/4", + exp: Fraction{}, + err: true, + }, + { + f: "1/3bc4", + exp: Fraction{}, + err: true, + }, + } + + for idx, tc := range testCases { + output, err := ParseFraction(tc.f) + if tc.err { + assert.Error(t, err, idx) + } else { + assert.NoError(t, err, idx) + } + assert.Equal(t, tc.exp, output, idx) + } + +} diff --git a/libs/math/math.go b/libs/math/math.go new file mode 100644 index 0000000..9ee3f71 --- /dev/null +++ b/libs/math/math.go @@ -0,0 +1,31 @@ +package math + +func MaxInt64(a, b int64) int64 { + if a > b { + return a + } + return b +} + +func MaxInt(a, b int) int { + if a > b { + return a + } + return b +} + +//----------------------------------------------------------------------------- + +func MinInt64(a, b int64) int64 { + if a < b { + return a + } + return b +} + +func MinInt(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/libs/math/safemath.go b/libs/math/safemath.go new file mode 100644 index 0000000..1157791 --- /dev/null +++ b/libs/math/safemath.go @@ -0,0 +1,65 @@ +package math + +import ( + "errors" + "math" +) + +var ErrOverflowInt32 = errors.New("int32 overflow") +var ErrOverflowUint8 = errors.New("uint8 overflow") +var ErrOverflowInt8 = errors.New("int8 overflow") + +// SafeAddInt32 adds two int32 integers +// If there is an overflow this will panic +func SafeAddInt32(a, b int32) int32 { + if b > 0 && (a > math.MaxInt32-b) { + panic(ErrOverflowInt32) + } else if b < 0 && (a < math.MinInt32-b) { + panic(ErrOverflowInt32) + } + return a + b +} + +// SafeSubInt32 subtracts two int32 integers +// If there is an overflow this will panic +func SafeSubInt32(a, b int32) int32 { + if b > 0 && (a < math.MinInt32+b) { + panic(ErrOverflowInt32) + } else if b < 0 && (a > math.MaxInt32+b) { + panic(ErrOverflowInt32) + } + return a - b +} + +// SafeConvertInt32 takes a int and checks if it overflows +// If there is an overflow this will panic +func SafeConvertInt32(a int64) int32 { + if a > math.MaxInt32 { + panic(ErrOverflowInt32) + } else if a < math.MinInt32 { + panic(ErrOverflowInt32) + } + return int32(a) +} + +// SafeConvertUint8 takes an int64 and checks if it overflows +// If there is an overflow it returns an error +func SafeConvertUint8(a int64) (uint8, error) { + if a > math.MaxUint8 { + return 0, ErrOverflowUint8 + } else if a < 0 { + return 0, ErrOverflowUint8 + } + return uint8(a), nil +} + +// SafeConvertInt8 takes an int64 and checks if it overflows +// If there is an overflow it returns an error +func SafeConvertInt8(a int64) (int8, error) { + if a > math.MaxInt8 { + return 0, ErrOverflowInt8 + } else if a < math.MinInt8 { + return 0, ErrOverflowInt8 + } + return int8(a), nil +} diff --git a/libs/net/net.go b/libs/net/net.go new file mode 100644 index 0000000..91b4605 --- /dev/null +++ b/libs/net/net.go @@ -0,0 +1,43 @@ +package net + +import ( + "net" + "strings" +) + +// Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol, +// eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock" +func Connect(protoAddr string) (net.Conn, error) { + proto, address := ProtocolAndAddress(protoAddr) + conn, err := net.Dial(proto, address) + return conn, err +} + +// ProtocolAndAddress splits an address into the protocol and address components. +// For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080". +// If the address has no protocol prefix, the default is "tcp". +func ProtocolAndAddress(listenAddr string) (string, string) { + protocol, address := "tcp", listenAddr + parts := strings.SplitN(address, "://", 2) + if len(parts) == 2 { + protocol, address = parts[0], parts[1] + } + return protocol, address +} + +// GetFreePort gets a free port from the operating system. +// Ripped from https://github.com/phayes/freeport. +// BSD-licensed. +func GetFreePort() (int, error) { + addr, err := net.ResolveTCPAddr("tcp", "localhost:0") + if err != nil { + return 0, err + } + + l, err := net.ListenTCP("tcp", addr) + if err != nil { + return 0, err + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port, nil +} diff --git a/libs/net/net_test.go b/libs/net/net_test.go new file mode 100644 index 0000000..04b9051 --- /dev/null +++ b/libs/net/net_test.go @@ -0,0 +1,38 @@ +package net + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestProtocolAndAddress(t *testing.T) { + + cases := []struct { + fullAddr string + proto string + addr string + }{ + { + "tcp://mydomain:80", + "tcp", + "mydomain:80", + }, + { + "mydomain:80", + "tcp", + "mydomain:80", + }, + { + "unix://mydomain:80", + "unix", + "mydomain:80", + }, + } + + for _, c := range cases { + proto, addr := ProtocolAndAddress(c.fullAddr) + assert.Equal(t, proto, c.proto) + assert.Equal(t, addr, c.addr) + } +} diff --git a/libs/os/os.go b/libs/os/os.go new file mode 100644 index 0000000..cf88589 --- /dev/null +++ b/libs/os/os.go @@ -0,0 +1,112 @@ +package os + +import ( + "errors" + "fmt" + "io" + "os" + "os/signal" + "syscall" + + "github.com/cometbft/cometbft/libs/log" +) + +type logger interface { + Info(msg string, keyvals ...interface{}) +} + +// TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits +// with code 0. +func TrapSignal(logger logger, cb func()) { + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + go func() { + for sig := range c { + logger.Info("signal trapped", "msg", log.NewLazySprintf("captured %v, exiting...", sig)) + if cb != nil { + cb() + } + os.Exit(0) + } + }() +} + +// Kill the running process by sending itself SIGTERM. +func Kill() error { + p, err := os.FindProcess(os.Getpid()) + if err != nil { + return err + } + return p.Signal(syscall.SIGTERM) +} + +func Exit(s string) { + fmt.Println(s) + os.Exit(1) +} + +// EnsureDir ensures the given directory exists, creating it if necessary. +// Errors if the path already exists as a non-directory. +func EnsureDir(dir string, mode os.FileMode) error { + err := os.MkdirAll(dir, mode) + if err != nil { + return fmt.Errorf("could not create directory %q: %w", dir, err) + } + return nil +} + +func FileExists(filePath string) bool { + _, err := os.Stat(filePath) + return !os.IsNotExist(err) +} + +func ReadFile(filePath string) ([]byte, error) { + return os.ReadFile(filePath) +} + +func MustReadFile(filePath string) []byte { + fileBytes, err := os.ReadFile(filePath) + if err != nil { + Exit(fmt.Sprintf("MustReadFile failed: %v", err)) + return nil + } + return fileBytes +} + +func WriteFile(filePath string, contents []byte, mode os.FileMode) error { + return os.WriteFile(filePath, contents, mode) +} + +func MustWriteFile(filePath string, contents []byte, mode os.FileMode) { + err := WriteFile(filePath, contents, mode) + if err != nil { + Exit(fmt.Sprintf("MustWriteFile failed: %v", err)) + } +} + +// CopyFile copies a file. It truncates the destination file if it exists. +func CopyFile(src, dst string) error { + srcfile, err := os.Open(src) + if err != nil { + return err + } + defer srcfile.Close() + + info, err := srcfile.Stat() + if err != nil { + return err + } + if info.IsDir() { + return errors.New("cannot read from directories") + } + + // create new file, truncate if exists and apply same permissions as the original one + dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm()) + if err != nil { + return err + } + defer dstfile.Close() + + _, err = io.Copy(dstfile, srcfile) + return err +} diff --git a/libs/os/os_test.go b/libs/os/os_test.go new file mode 100644 index 0000000..2106880 --- /dev/null +++ b/libs/os/os_test.go @@ -0,0 +1,113 @@ +package os + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCopyFile(t *testing.T) { + tmpfile, err := os.CreateTemp("", "example") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpfile.Name()) + content := []byte("hello world") + if _, err := tmpfile.Write(content); err != nil { + t.Fatal(err) + } + + copyfile := fmt.Sprintf("%s.copy", tmpfile.Name()) + if err := CopyFile(tmpfile.Name(), copyfile); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(copyfile); os.IsNotExist(err) { + t.Fatal("copy should exist") + } + data, err := os.ReadFile(copyfile) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(data, content) { + t.Fatalf("copy file content differs: expected %v, got %v", content, data) + } + os.Remove(copyfile) +} + +func TestEnsureDir(t *testing.T) { + tmp, err := os.MkdirTemp("", "ensure-dir") + require.NoError(t, err) + defer os.RemoveAll(tmp) + + // Should be possible to create a new directory. + err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + require.NoError(t, err) + require.DirExists(t, filepath.Join(tmp, "dir")) + + // Should succeed on existing directory. + err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + require.NoError(t, err) + + // Should fail on file. + err = os.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644) + require.NoError(t, err) + err = EnsureDir(filepath.Join(tmp, "file"), 0755) + require.Error(t, err) + + // Should allow symlink to dir. + err = os.Symlink(filepath.Join(tmp, "dir"), filepath.Join(tmp, "linkdir")) + require.NoError(t, err) + err = EnsureDir(filepath.Join(tmp, "linkdir"), 0755) + require.NoError(t, err) + + // Should error on symlink to file. + err = os.Symlink(filepath.Join(tmp, "file"), filepath.Join(tmp, "linkfile")) + require.NoError(t, err) + err = EnsureDir(filepath.Join(tmp, "linkfile"), 0755) + require.Error(t, err) +} + +// Ensure that using CopyFile does not truncate the destination file before +// the origin is positively a non-directory and that it is ready for copying. +// See https://github.com/tendermint/tendermint/issues/6427 +func TestTrickedTruncation(t *testing.T) { + tmpDir, err := os.MkdirTemp(os.TempDir(), "pwn_truncate") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpDir) + + originalWALPath := filepath.Join(tmpDir, "wal") + originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!") + if err := os.WriteFile(originalWALPath, originalWALContent, 0755); err != nil { + t.Fatal(err) + } + + // 1. Sanity check. + readWAL, err := os.ReadFile(originalWALPath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(readWAL, originalWALContent) { + t.Fatalf("Cannot proceed as the content does not match\nGot: %q\nWant: %q", readWAL, originalWALContent) + } + + // 2. Now cause the truncation of the original file. + // It is absolutely legal to invoke os.Open on a directory. + if err := CopyFile(tmpDir, originalWALPath); err == nil { + t.Fatal("Expected an error") + } + + // 3. Check the WAL's content + reReadWAL, err := os.ReadFile(originalWALPath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(reReadWAL, originalWALContent) { + t.Fatalf("Oops, the WAL's content was changed :(\nGot: %q\nWant: %q", reReadWAL, originalWALContent) + } +} diff --git a/libs/progressbar/progressbar.go b/libs/progressbar/progressbar.go new file mode 100644 index 0000000..7f31e84 --- /dev/null +++ b/libs/progressbar/progressbar.go @@ -0,0 +1,41 @@ +package progressbar + +import "fmt" + +// the progressbar indicates the current status and progress would be desired. +// ref: https://www.pixelstech.net/article/1596946473-A-simple-example-on-implementing-progress-bar-in-GoLang + +type Bar struct { + percent int64 // progress percentage + cur int64 // current progress + start int64 // the init starting value for progress + total int64 // total value for progress + rate string // the actual progress bar to be printed + graph string // the fill value for progress bar +} + +func (bar *Bar) NewOption(start, total int64) { + bar.cur = start + bar.start = start + bar.total = total + bar.graph = "█" + bar.percent = bar.getPercent() +} + +func (bar *Bar) getPercent() int64 { + return int64(float32(bar.cur-bar.start) / float32(bar.total-bar.start) * 100) +} + +func (bar *Bar) Play(cur int64) { + bar.cur = cur + last := bar.percent + bar.percent = bar.getPercent() + if bar.percent != last && bar.percent%2 == 0 { + bar.rate += bar.graph + } + fmt.Printf("\r[%-50s]%3d%% %8d/%d", bar.rate, bar.percent, bar.cur, bar.total) +} + +func (bar *Bar) Finish() { + fmt.Println() +} diff --git a/libs/progressbar/progressbar_test.go b/libs/progressbar/progressbar_test.go new file mode 100644 index 0000000..a548629 --- /dev/null +++ b/libs/progressbar/progressbar_test.go @@ -0,0 +1,41 @@ +package progressbar + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestProgressBar(t *testing.T) { + zero := int64(0) + hundred := int64(100) + + var bar Bar + bar.NewOption(zero, hundred) + + require.Equal(t, zero, bar.start) + require.Equal(t, zero, bar.cur) + require.Equal(t, hundred, bar.total) + require.Equal(t, zero, bar.percent) + require.Equal(t, "█", bar.graph) + require.Equal(t, "", bar.rate) + + defer bar.Finish() + for i := zero; i <= hundred; i++ { + time.Sleep(1 * time.Millisecond) + bar.Play(i) + } + + require.Equal(t, zero, bar.start) + require.Equal(t, hundred, bar.cur) + require.Equal(t, hundred, bar.total) + require.Equal(t, hundred, bar.percent) + + var rate string + for i := zero; i < hundred/2; i++ { + rate += "█" + } + + require.Equal(t, rate, bar.rate) +} diff --git a/libs/protoio/io.go b/libs/protoio/io.go new file mode 100644 index 0000000..8bc7fca --- /dev/null +++ b/libs/protoio/io.go @@ -0,0 +1,102 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Modified to return number of bytes written by Writer.WriteMsg(), and added byteReader. + +package protoio + +import ( + "io" + + "github.com/cosmos/gogoproto/proto" +) + +type Writer interface { + WriteMsg(proto.Message) (int, error) +} + +type WriteCloser interface { + Writer + io.Closer +} + +type Reader interface { + ReadMsg(msg proto.Message) (int, error) +} + +type ReadCloser interface { + Reader + io.Closer +} + +type marshaler interface { + MarshalTo(data []byte) (n int, err error) +} + +func getSize(v interface{}) (int, bool) { + if sz, ok := v.(interface { + Size() (n int) + }); ok { + return sz.Size(), true + } else if sz, ok := v.(interface { + ProtoSize() (n int) + }); ok { + return sz.ProtoSize(), true + } + return 0, false +} + +// byteReader wraps an io.Reader and implements io.ByteReader, required by +// binary.ReadUvarint(). Reading one byte at a time is extremely slow, but this +// is what Amino did previously anyway, and the caller can wrap the underlying +// reader in a bufio.Reader if appropriate. +type byteReader struct { + reader io.Reader + buf []byte + bytesRead int // keeps track of bytes read via ReadByte() +} + +func newByteReader(r io.Reader) *byteReader { + return &byteReader{ + reader: r, + buf: make([]byte, 1), + } +} + +func (r *byteReader) ReadByte() (byte, error) { + n, err := r.reader.Read(r.buf) + r.bytesRead += n + if err != nil { + return 0x00, err + } + return r.buf[0], nil +} + +func (r *byteReader) resetBytesRead() { + r.bytesRead = 0 +} diff --git a/libs/protoio/io_test.go b/libs/protoio/io_test.go new file mode 100644 index 0000000..0413bc0 --- /dev/null +++ b/libs/protoio/io_test.go @@ -0,0 +1,181 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package protoio_test + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + "math/rand" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/cosmos/gogoproto/test" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/protoio" +) + +func iotest(writer protoio.WriteCloser, reader protoio.ReadCloser) error { + varint := make([]byte, binary.MaxVarintLen64) + size := 1000 + msgs := make([]*test.NinOptNative, size) + lens := make([]int, size) + r := rand.New(rand.NewSource(time.Now().UnixNano())) + for i := range msgs { + msgs[i] = test.NewPopulatedNinOptNative(r, true) + // issue 31 + if i == 5 { + msgs[i] = &test.NinOptNative{} + } + // issue 31 + if i == 999 { + msgs[i] = &test.NinOptNative{} + } + // FIXME Check size + bz, err := proto.Marshal(msgs[i]) + if err != nil { + return err + } + visize := binary.PutUvarint(varint, uint64(len(bz))) + n, err := writer.WriteMsg(msgs[i]) + if err != nil { + return err + } + if n != len(bz)+visize { + return fmt.Errorf("WriteMsg() wrote %v bytes, expected %v", n, len(bz)+visize) + } + lens[i] = n + } + if err := writer.Close(); err != nil { + return err + } + i := 0 + for { + msg := &test.NinOptNative{} + if n, err := reader.ReadMsg(msg); err != nil { + if err == io.EOF { + break + } + return err + } else if n != lens[i] { + return fmt.Errorf("read %v bytes, expected %v", n, lens[i]) + } + if err := msg.VerboseEqual(msgs[i]); err != nil { + return err + } + i++ + } + if i != size { + panic("not enough messages read") + } + return reader.Close() +} + +type buffer struct { + *bytes.Buffer + closed bool +} + +func (b *buffer) Close() error { + b.closed = true + return nil +} + +func newBuffer() *buffer { + return &buffer{bytes.NewBuffer(nil), false} +} + +func TestVarintNormal(t *testing.T) { + buf := newBuffer() + writer := protoio.NewDelimitedWriter(buf) + reader := protoio.NewDelimitedReader(buf, 1024*1024) + err := iotest(writer, reader) + require.NoError(t, err) + require.True(t, buf.closed, "did not close buffer") +} + +func TestVarintNoClose(t *testing.T) { + buf := bytes.NewBuffer(nil) + writer := protoio.NewDelimitedWriter(buf) + reader := protoio.NewDelimitedReader(buf, 1024*1024) + err := iotest(writer, reader) + require.NoError(t, err) +} + +// issue 32 +func TestVarintMaxSize(t *testing.T) { + buf := newBuffer() + writer := protoio.NewDelimitedWriter(buf) + reader := protoio.NewDelimitedReader(buf, 20) + err := iotest(writer, reader) + require.Error(t, err) +} + +func TestVarintError(t *testing.T) { + buf := newBuffer() + buf.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}) + reader := protoio.NewDelimitedReader(buf, 1024*1024) + msg := &test.NinOptNative{} + n, err := reader.ReadMsg(msg) + require.Error(t, err) + require.Equal(t, 10, n) +} + +func TestVarintTruncated(t *testing.T) { + buf := newBuffer() + buf.Write([]byte{0xff, 0xff}) + reader := protoio.NewDelimitedReader(buf, 1024*1024) + msg := &test.NinOptNative{} + n, err := reader.ReadMsg(msg) + require.Error(t, err) + require.Equal(t, 2, n) +} + +func TestShort(t *testing.T) { + buf := newBuffer() + + varintBuf := make([]byte, binary.MaxVarintLen64) + varintLen := binary.PutUvarint(varintBuf, 100) + _, err := buf.Write(varintBuf[:varintLen]) + require.NoError(t, err) + + bz, err := proto.Marshal(&test.NinOptNative{Field15: []byte{0x01, 0x02, 0x03}}) + require.NoError(t, err) + buf.Write(bz) + + reader := protoio.NewDelimitedReader(buf, 1024*1024) + require.NoError(t, err) + msg := &test.NinOptNative{} + n, err := reader.ReadMsg(msg) + require.Error(t, err) + require.Equal(t, varintLen+len(bz), n) +} diff --git a/libs/protoio/reader.go b/libs/protoio/reader.go new file mode 100644 index 0000000..4228176 --- /dev/null +++ b/libs/protoio/reader.go @@ -0,0 +1,107 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Modified from original GoGo Protobuf to not buffer the reader. + +package protoio + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + + "github.com/cosmos/gogoproto/proto" +) + +// NewDelimitedReader reads varint-delimited Protobuf messages from a reader. +// Unlike the gogoproto NewDelimitedReader, this does not buffer the reader, +// which may cause poor performance but is necessary when only reading single +// messages (e.g. in the p2p package). It also returns the number of bytes +// read, which is necessary for the p2p package. +func NewDelimitedReader(r io.Reader, maxSize int) ReadCloser { + var closer io.Closer + if c, ok := r.(io.Closer); ok { + closer = c + } + return &varintReader{r, newByteReader(r), nil, maxSize, closer} +} + +type varintReader struct { + r io.Reader + // ReadUvarint needs an io.ByteReader, and we also need to keep track of the + // number of bytes read, so we use our own byteReader. This can't be + // buffered, so the caller should pass a buffered io.Reader to avoid poor + // performance. + byteReader *byteReader + buf []byte + maxSize int + closer io.Closer +} + +func (r *varintReader) ReadMsg(msg proto.Message) (int, error) { + r.byteReader.resetBytesRead() + l, err := binary.ReadUvarint(r.byteReader) + n := r.byteReader.bytesRead + if err != nil { + return n, err + } + + // Make sure length doesn't overflow the native int size (e.g. 32-bit), + // and that the returned sum of n+length doesn't overflow either. + length := int(l) + if l >= uint64(^uint(0)>>1) || length < 0 || n+length < 0 { + return n, fmt.Errorf("invalid out-of-range message length %v", l) + } + if length > r.maxSize { + return n, fmt.Errorf("message exceeds max size (%v > %v)", length, r.maxSize) + } + + if len(r.buf) < length { + r.buf = make([]byte, length) + } + buf := r.buf[:length] + nr, err := io.ReadFull(r.r, buf) + n += nr + if err != nil { + return n, err + } + return n, proto.Unmarshal(buf, msg) +} + +func (r *varintReader) Close() error { + if r.closer != nil { + return r.closer.Close() + } + return nil +} + +func UnmarshalDelimited(data []byte, msg proto.Message) error { + _, err := NewDelimitedReader(bytes.NewReader(data), len(data)).ReadMsg(msg) + return err +} diff --git a/libs/protoio/writer.go b/libs/protoio/writer.go new file mode 100644 index 0000000..4e77ec1 --- /dev/null +++ b/libs/protoio/writer.go @@ -0,0 +1,103 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Modified from original GoGo Protobuf to return number of bytes written. + +package protoio + +import ( + "bytes" + "encoding/binary" + "io" + + "github.com/cosmos/gogoproto/proto" +) + +// NewDelimitedWriter writes a varint-delimited Protobuf message to a writer. It is +// equivalent to the gogoproto NewDelimitedWriter, except WriteMsg() also returns the +// number of bytes written, which is necessary in the p2p package. +func NewDelimitedWriter(w io.Writer) WriteCloser { + return &varintWriter{w, nil, nil} +} + +type varintWriter struct { + w io.Writer + lenBuf []byte + buffer []byte +} + +func (w *varintWriter) WriteMsg(msg proto.Message) (int, error) { + if m, ok := msg.(marshaler); ok { + n, ok := getSize(m) + if ok { + if n+binary.MaxVarintLen64 >= len(w.buffer) { + w.buffer = make([]byte, n+binary.MaxVarintLen64) + } + lenOff := binary.PutUvarint(w.buffer, uint64(n)) + _, err := m.MarshalTo(w.buffer[lenOff:]) + if err != nil { + return 0, err + } + _, err = w.w.Write(w.buffer[:lenOff+n]) + return lenOff + n, err + } + } + + // fallback + if w.lenBuf == nil { + w.lenBuf = make([]byte, binary.MaxVarintLen64) + } + data, err := proto.Marshal(msg) + if err != nil { + return 0, err + } + length := uint64(len(data)) + n := binary.PutUvarint(w.lenBuf, length) + _, err = w.w.Write(w.lenBuf[:n]) + if err != nil { + return 0, err + } + _, err = w.w.Write(data) + return len(data) + n, err +} + +func (w *varintWriter) Close() error { + if closer, ok := w.w.(io.Closer); ok { + return closer.Close() + } + return nil +} + +func MarshalDelimited(msg proto.Message) ([]byte, error) { + var buf bytes.Buffer + _, err := NewDelimitedWriter(&buf).WriteMsg(msg) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/libs/pubsub/example_test.go b/libs/pubsub/example_test.go new file mode 100644 index 0000000..0c380bc --- /dev/null +++ b/libs/pubsub/example_test.go @@ -0,0 +1,32 @@ +package pubsub_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + + "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/pubsub/query" +) + +func TestExample(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription, err := s.Subscribe(ctx, "example-client", query.MustCompile("abci.account.name='John'")) + require.NoError(t, err) + err = s.PublishWithEvents(ctx, "Tombstone", map[string][]string{"abci.account.name": {"John"}}) + require.NoError(t, err) + assertReceive(t, "Tombstone", subscription.Out()) +} diff --git a/libs/pubsub/pubsub.go b/libs/pubsub/pubsub.go new file mode 100644 index 0000000..2750107 --- /dev/null +++ b/libs/pubsub/pubsub.go @@ -0,0 +1,433 @@ +// Package pubsub implements a pub-sub model with a single publisher (Server) +// and multiple subscribers (clients). +// +// Though you can have multiple publishers by sharing a pointer to a server or +// by giving the same channel to each publisher and publishing messages from +// that channel (fan-in). +// +// Clients subscribe for messages, which could be of any type, using a query. +// When some message is published, we match it with all queries. If there is a +// match, this message will be pushed to all clients, subscribed to that query. +// See query subpackage for our implementation. +// +// Example: +// +// q, err := query.New("account.name='John'") +// if err != nil { +// return err +// } +// ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second) +// defer cancel() +// subscription, err := pubsub.Subscribe(ctx, "johns-transactions", q) +// if err != nil { +// return err +// } +// +// for { +// select { +// case msg <- subscription.Out(): +// // handle msg.Data() and msg.Events() +// case <-subscription.Canceled(): +// return subscription.Err() +// } +// } +package pubsub + +import ( + "context" + "errors" + "fmt" + + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +type operation int + +const ( + sub operation = iota + pub + unsub + shutdown +) + +var ( + // ErrSubscriptionNotFound is returned when a client tries to unsubscribe + // from not existing subscription. + ErrSubscriptionNotFound = errors.New("subscription not found") + + // ErrAlreadySubscribed is returned when a client tries to subscribe twice or + // more using the same query. + ErrAlreadySubscribed = errors.New("already subscribed") +) + +// Query defines an interface for a query to be used for subscribing. A query +// matches against a map of events. Each key in this map is a composite of the +// even type and an attribute key (e.g. "{eventType}.{eventAttrKey}") and the +// values are the event values that are contained under that relationship. This +// allows event types to repeat themselves with the same set of keys and +// different values. +type Query interface { + Matches(events map[string][]string) (bool, error) + String() string +} + +type cmd struct { + op operation + + // subscribe, unsubscribe + query Query + subscription *Subscription + clientID string + + // publish + msg interface{} + events map[string][]string +} + +// Server allows clients to subscribe/unsubscribe for messages, publishing +// messages with or without events, and manages internal state. +type Server struct { + service.BaseService + + cmds chan cmd + cmdsCap int + + // check if we have subscription before + // subscribing or unsubscribing + mtx cmtsync.RWMutex + subscriptions map[string]map[string]struct{} // subscriber -> query (string) -> empty struct +} + +// Option sets a parameter for the server. +type Option func(*Server) + +// NewServer returns a new server. See the commentary on the Option functions +// for a detailed description of how to configure buffering. If no options are +// provided, the resulting server's queue is unbuffered. +func NewServer(options ...Option) *Server { + s := &Server{ + subscriptions: make(map[string]map[string]struct{}), + } + s.BaseService = *service.NewBaseService(nil, "PubSub", s) + + for _, option := range options { + option(s) + } + + // if BufferCapacity option was not set, the channel is unbuffered + s.cmds = make(chan cmd, s.cmdsCap) + + return s +} + +// BufferCapacity allows you to specify capacity for the internal server's +// queue. Since the server, given Y subscribers, could only process X messages, +// this option could be used to survive spikes (e.g. high amount of +// transactions during peak hours). +func BufferCapacity(cap int) Option { + return func(s *Server) { + if cap > 0 { + s.cmdsCap = cap + } + } +} + +// BufferCapacity returns capacity of the internal server's queue. +func (s *Server) BufferCapacity() int { + return s.cmdsCap +} + +// Subscribe creates a subscription for the given client. +// +// An error will be returned to the caller if the context is canceled or if +// subscription already exist for pair clientID and query. +// +// outCapacity can be used to set a capacity for Subscription#Out channel (1 by +// default). Panics if outCapacity is less than or equal to zero. If you want +// an unbuffered channel, use SubscribeUnbuffered. +func (s *Server) Subscribe( + ctx context.Context, + clientID string, + query Query, + outCapacity ...int) (*Subscription, error) { + outCap := 1 + if len(outCapacity) > 0 { + if outCapacity[0] <= 0 { + panic("Negative or zero capacity. Use SubscribeUnbuffered if you want an unbuffered channel") + } + outCap = outCapacity[0] + } + + return s.subscribe(ctx, clientID, query, outCap) +} + +// SubscribeUnbuffered does the same as Subscribe, except it returns a +// subscription with unbuffered channel. Use with caution as it can freeze the +// server. +func (s *Server) SubscribeUnbuffered(ctx context.Context, clientID string, query Query) (*Subscription, error) { + return s.subscribe(ctx, clientID, query, 0) +} + +func (s *Server) subscribe(ctx context.Context, clientID string, query Query, outCapacity int) (*Subscription, error) { + s.mtx.RLock() + clientSubscriptions, ok := s.subscriptions[clientID] + if ok { + _, ok = clientSubscriptions[query.String()] + } + s.mtx.RUnlock() + if ok { + return nil, ErrAlreadySubscribed + } + + subscription := NewSubscription(outCapacity) + select { + case s.cmds <- cmd{op: sub, clientID: clientID, query: query, subscription: subscription}: + s.mtx.Lock() + if _, ok = s.subscriptions[clientID]; !ok { + s.subscriptions[clientID] = make(map[string]struct{}) + } + s.subscriptions[clientID][query.String()] = struct{}{} + s.mtx.Unlock() + return subscription, nil + case <-ctx.Done(): + return nil, ctx.Err() + case <-s.Quit(): + return nil, errors.New("service is shutting down") + } +} + +// Unsubscribe removes the subscription on the given query. An error will be +// returned to the caller if the context is canceled or if subscription does +// not exist. +func (s *Server) Unsubscribe(ctx context.Context, clientID string, query Query) error { + s.mtx.RLock() + clientSubscriptions, ok := s.subscriptions[clientID] + if ok { + _, ok = clientSubscriptions[query.String()] + } + s.mtx.RUnlock() + if !ok { + return ErrSubscriptionNotFound + } + + select { + case s.cmds <- cmd{op: unsub, clientID: clientID, query: query}: + s.mtx.Lock() + delete(clientSubscriptions, query.String()) + if len(clientSubscriptions) == 0 { + delete(s.subscriptions, clientID) + } + s.mtx.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + case <-s.Quit(): + return nil + } +} + +// UnsubscribeAll removes all client subscriptions. An error will be returned +// to the caller if the context is canceled or if subscription does not exist. +func (s *Server) UnsubscribeAll(ctx context.Context, clientID string) error { + s.mtx.RLock() + _, ok := s.subscriptions[clientID] + s.mtx.RUnlock() + if !ok { + return ErrSubscriptionNotFound + } + + select { + case s.cmds <- cmd{op: unsub, clientID: clientID}: + s.mtx.Lock() + delete(s.subscriptions, clientID) + s.mtx.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + case <-s.Quit(): + return nil + } +} + +// NumClients returns the number of clients. +func (s *Server) NumClients() int { + s.mtx.RLock() + defer s.mtx.RUnlock() + return len(s.subscriptions) +} + +// NumClientSubscriptions returns the number of subscriptions the client has. +func (s *Server) NumClientSubscriptions(clientID string) int { + s.mtx.RLock() + defer s.mtx.RUnlock() + return len(s.subscriptions[clientID]) +} + +// Publish publishes the given message. An error will be returned to the caller +// if the context is canceled. +func (s *Server) Publish(ctx context.Context, msg interface{}) error { + return s.PublishWithEvents(ctx, msg, make(map[string][]string)) +} + +// PublishWithEvents publishes the given message with the set of events. The set +// is matched with clients queries. If there is a match, the message is sent to +// the client. +func (s *Server) PublishWithEvents(ctx context.Context, msg interface{}, events map[string][]string) error { + select { + case s.cmds <- cmd{op: pub, msg: msg, events: events}: + return nil + case <-ctx.Done(): + return ctx.Err() + case <-s.Quit(): + return nil + } +} + +// OnStop implements Service.OnStop by shutting down the server. +func (s *Server) OnStop() { + s.cmds <- cmd{op: shutdown} +} + +// NOTE: not goroutine safe +type state struct { + // query string -> client -> subscription + subscriptions map[string]map[string]*Subscription + // query string -> queryPlusRefCount + queries map[string]*queryPlusRefCount +} + +// queryPlusRefCount holds a pointer to a query and reference counter. When +// refCount is zero, query will be removed. +type queryPlusRefCount struct { + q Query + refCount int +} + +// OnStart implements Service.OnStart by starting the server. +func (s *Server) OnStart() error { + go s.loop(state{ + subscriptions: make(map[string]map[string]*Subscription), + queries: make(map[string]*queryPlusRefCount), + }) + return nil +} + +// OnReset implements Service.OnReset +func (s *Server) OnReset() error { + return nil +} + +func (s *Server) loop(state state) { +loop: + for cmd := range s.cmds { + switch cmd.op { + case unsub: + if cmd.query != nil { + state.remove(cmd.clientID, cmd.query.String(), ErrUnsubscribed) + } else { + state.removeClient(cmd.clientID, ErrUnsubscribed) + } + case shutdown: + state.removeAll(nil) + break loop + case sub: + state.add(cmd.clientID, cmd.query, cmd.subscription) + case pub: + if err := state.send(cmd.msg, cmd.events); err != nil { + s.Logger.Error("Error querying for events", "err", err) + } + } + } +} + +func (state *state) add(clientID string, q Query, subscription *Subscription) { + qStr := q.String() + + // initialize subscription for this client per query if needed + if _, ok := state.subscriptions[qStr]; !ok { + state.subscriptions[qStr] = make(map[string]*Subscription) + } + // create subscription + state.subscriptions[qStr][clientID] = subscription + + // initialize query if needed + if _, ok := state.queries[qStr]; !ok { + state.queries[qStr] = &queryPlusRefCount{q: q, refCount: 0} + } + // increment reference counter + state.queries[qStr].refCount++ +} + +func (state *state) remove(clientID string, qStr string, reason error) { + clientSubscriptions, ok := state.subscriptions[qStr] + if !ok { + return + } + + subscription, ok := clientSubscriptions[clientID] + if !ok { + return + } + + subscription.cancel(reason) + + // remove client from query map. + // if query has no other clients subscribed, remove it. + delete(state.subscriptions[qStr], clientID) + if len(state.subscriptions[qStr]) == 0 { + delete(state.subscriptions, qStr) + } + + // decrease ref counter in queries + state.queries[qStr].refCount-- + // remove the query if nobody else is using it + if state.queries[qStr].refCount == 0 { + delete(state.queries, qStr) + } +} + +func (state *state) removeClient(clientID string, reason error) { + for qStr, clientSubscriptions := range state.subscriptions { + if _, ok := clientSubscriptions[clientID]; ok { + state.remove(clientID, qStr, reason) + } + } +} + +func (state *state) removeAll(reason error) { + for qStr, clientSubscriptions := range state.subscriptions { + for clientID := range clientSubscriptions { + state.remove(clientID, qStr, reason) + } + } +} + +func (state *state) send(msg interface{}, events map[string][]string) error { + for qStr, clientSubscriptions := range state.subscriptions { + q := state.queries[qStr].q + + match, err := q.Matches(events) + if err != nil { + return fmt.Errorf("failed to match against query %s: %w", q.String(), err) + } + + if match { + for clientID, subscription := range clientSubscriptions { + if cap(subscription.out) == 0 { + // block on unbuffered channel + subscription.out <- NewMessage(msg, events) + } else { + // don't block on buffered channels + select { + case subscription.out <- NewMessage(msg, events): + default: + state.remove(clientID, qStr, ErrOutOfCapacity) + } + } + } + } + } + + return nil +} diff --git a/libs/pubsub/pubsub_test.go b/libs/pubsub/pubsub_test.go new file mode 100644 index 0000000..3a30ab2 --- /dev/null +++ b/libs/pubsub/pubsub_test.go @@ -0,0 +1,507 @@ +package pubsub_test + +import ( + "context" + "fmt" + "runtime/debug" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + + "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/pubsub/query" +) + +const ( + clientID = "test-client" +) + +func TestSubscribe(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription, err := s.Subscribe(ctx, clientID, query.All) + require.NoError(t, err) + + assert.Equal(t, 1, s.NumClients()) + assert.Equal(t, 1, s.NumClientSubscriptions(clientID)) + + err = s.Publish(ctx, "Ka-Zar") + require.NoError(t, err) + assertReceive(t, "Ka-Zar", subscription.Out()) + + published := make(chan struct{}) + go func() { + defer close(published) + + err := s.Publish(ctx, "Quicksilver") + assert.NoError(t, err) + + err = s.Publish(ctx, "Asylum") + assert.NoError(t, err) + + err = s.Publish(ctx, "Ivan") + assert.NoError(t, err) + }() + + select { + case <-published: + assertReceive(t, "Quicksilver", subscription.Out()) + assertCancelled(t, subscription, pubsub.ErrOutOfCapacity) + case <-time.After(3 * time.Second): + t.Fatal("Expected Publish(Asylum) not to block") + } +} + +func TestSubscribeWithCapacity(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + assert.Panics(t, func() { + _, err = s.Subscribe(ctx, clientID, query.All, -1) + require.NoError(t, err) + }) + assert.Panics(t, func() { + _, err = s.Subscribe(ctx, clientID, query.All, 0) + require.NoError(t, err) + }) + subscription, err := s.Subscribe(ctx, clientID, query.All, 1) + require.NoError(t, err) + err = s.Publish(ctx, "Aggamon") + require.NoError(t, err) + assertReceive(t, "Aggamon", subscription.Out()) +} + +func TestSubscribeUnbuffered(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription, err := s.SubscribeUnbuffered(ctx, clientID, query.All) + require.NoError(t, err) + + published := make(chan struct{}) + go func() { + defer close(published) + + err := s.Publish(ctx, "Ultron") + assert.NoError(t, err) + + err = s.Publish(ctx, "Darkhawk") + assert.NoError(t, err) + }() + + select { + case <-published: + t.Fatal("Expected Publish(Darkhawk) to block") + case <-time.After(3 * time.Second): + assertReceive(t, "Ultron", subscription.Out()) + assertReceive(t, "Darkhawk", subscription.Out()) + } +} + +func TestSlowClientIsRemovedWithErrOutOfCapacity(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription, err := s.Subscribe(ctx, clientID, query.All) + require.NoError(t, err) + err = s.Publish(ctx, "Fat Cobra") + require.NoError(t, err) + err = s.Publish(ctx, "Viper") + require.NoError(t, err) + + assertCancelled(t, subscription, pubsub.ErrOutOfCapacity) +} + +func TestDifferentClients(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription1, err := s.Subscribe(ctx, "client-1", query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + err = s.PublishWithEvents(ctx, "Iceman", map[string][]string{"tm.events.type": {"NewBlock"}}) + require.NoError(t, err) + assertReceive(t, "Iceman", subscription1.Out()) + + subscription2, err := s.Subscribe( + ctx, + "client-2", + query.MustCompile("tm.events.type='NewBlock' AND abci.account.name='Igor'"), + ) + require.NoError(t, err) + err = s.PublishWithEvents( + ctx, + "Ultimo", + map[string][]string{"tm.events.type": {"NewBlock"}, "abci.account.name": {"Igor"}}, + ) + require.NoError(t, err) + assertReceive(t, "Ultimo", subscription1.Out()) + assertReceive(t, "Ultimo", subscription2.Out()) + + subscription3, err := s.Subscribe( + ctx, + "client-3", + query.MustCompile("tm.events.type='NewRoundStep' AND abci.account.name='Igor' AND abci.invoice.number = 10"), + ) + require.NoError(t, err) + err = s.PublishWithEvents(ctx, "Valeria Richards", map[string][]string{"tm.events.type": {"NewRoundStep"}}) + require.NoError(t, err) + assert.Zero(t, len(subscription3.Out())) +} + +func TestSubscribeDuplicateKeys(t *testing.T) { + ctx := context.Background() + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + require.NoError(t, s.Start()) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + testCases := []struct { + query string + expected interface{} + }{ + { + "withdraw.rewards='17'", + "Iceman", + }, + { + "withdraw.rewards='22'", + "Iceman", + }, + { + "withdraw.rewards='1' AND withdraw.rewards='22'", + "Iceman", + }, + { + "withdraw.rewards='100'", + nil, + }, + } + + for i, tc := range testCases { + sub, err := s.Subscribe(ctx, fmt.Sprintf("client-%d", i), query.MustCompile(tc.query)) + require.NoError(t, err) + + err = s.PublishWithEvents( + ctx, + "Iceman", + map[string][]string{ + "transfer.sender": {"foo", "bar", "baz"}, + "withdraw.rewards": {"1", "17", "22"}, + }, + ) + require.NoError(t, err) + + if tc.expected != nil { + assertReceive(t, tc.expected, sub.Out()) + } else { + require.Zero(t, len(sub.Out())) + } + } +} + +func TestClientSubscribesTwice(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + q := query.MustCompile("tm.events.type='NewBlock'") + + subscription1, err := s.Subscribe(ctx, clientID, q) + require.NoError(t, err) + err = s.PublishWithEvents(ctx, "Goblin Queen", map[string][]string{"tm.events.type": {"NewBlock"}}) + require.NoError(t, err) + assertReceive(t, "Goblin Queen", subscription1.Out()) + + subscription2, err := s.Subscribe(ctx, clientID, q) + require.Error(t, err) + require.Nil(t, subscription2) + + err = s.PublishWithEvents(ctx, "Spider-Man", map[string][]string{"tm.events.type": {"NewBlock"}}) + require.NoError(t, err) + assertReceive(t, "Spider-Man", subscription1.Out()) +} + +func TestUnsubscribe(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription, err := s.Subscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + err = s.Unsubscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + + err = s.Publish(ctx, "Nick Fury") + require.NoError(t, err) + assert.Zero(t, len(subscription.Out()), "Should not receive anything after Unsubscribe") + + assertCancelled(t, subscription, pubsub.ErrUnsubscribed) +} + +func TestClientUnsubscribesTwice(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + _, err = s.Subscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + err = s.Unsubscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + + err = s.Unsubscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + assert.Equal(t, pubsub.ErrSubscriptionNotFound, err) + err = s.UnsubscribeAll(ctx, clientID) + assert.Equal(t, pubsub.ErrSubscriptionNotFound, err) +} + +func TestResubscribe(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + _, err = s.Subscribe(ctx, clientID, query.All) + require.NoError(t, err) + err = s.Unsubscribe(ctx, clientID, query.All) + require.NoError(t, err) + subscription, err := s.Subscribe(ctx, clientID, query.All) + require.NoError(t, err) + + err = s.Publish(ctx, "Cable") + require.NoError(t, err) + assertReceive(t, "Cable", subscription.Out()) +} + +func TestUnsubscribeAll(t *testing.T) { + s := pubsub.NewServer() + s.SetLogger(log.TestingLogger()) + err := s.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + ctx := context.Background() + subscription1, err := s.Subscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlock'")) + require.NoError(t, err) + subscription2, err := s.Subscribe(ctx, clientID, query.MustCompile("tm.events.type='NewBlockHeader'")) + require.NoError(t, err) + + err = s.UnsubscribeAll(ctx, clientID) + require.NoError(t, err) + + err = s.Publish(ctx, "Nick Fury") + require.NoError(t, err) + assert.Zero(t, len(subscription1.Out()), "Should not receive anything after UnsubscribeAll") + assert.Zero(t, len(subscription2.Out()), "Should not receive anything after UnsubscribeAll") + + assertCancelled(t, subscription1, pubsub.ErrUnsubscribed) + assertCancelled(t, subscription2, pubsub.ErrUnsubscribed) +} + +func TestBufferCapacity(t *testing.T) { + s := pubsub.NewServer(pubsub.BufferCapacity(2)) + s.SetLogger(log.TestingLogger()) + + assert.Equal(t, 2, s.BufferCapacity()) + + ctx := context.Background() + err := s.Publish(ctx, "Nighthawk") + require.NoError(t, err) + err = s.Publish(ctx, "Sage") + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond) + defer cancel() + err = s.Publish(ctx, "Ironclad") + if assert.Error(t, err) { + assert.Equal(t, context.DeadlineExceeded, err) + } +} + +func Benchmark10Clients(b *testing.B) { benchmarkNClients(10, b) } +func Benchmark100Clients(b *testing.B) { benchmarkNClients(100, b) } +func Benchmark1000Clients(b *testing.B) { benchmarkNClients(1000, b) } + +func Benchmark10ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(10, b) } +func Benchmark100ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(100, b) } +func Benchmark1000ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(1000, b) } + +func benchmarkNClients(n int, b *testing.B) { + s := pubsub.NewServer() + err := s.Start() + require.NoError(b, err) + + b.Cleanup(func() { + if err := s.Stop(); err != nil { + b.Error(err) + } + }) + + ctx := context.Background() + for i := 0; i < n; i++ { + subscription, err := s.Subscribe( + ctx, + clientID, + query.MustCompile(fmt.Sprintf("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = %d", i)), + ) + if err != nil { + b.Fatal(err) + } + go func() { + for { + select { + case <-subscription.Out(): + continue + case <-subscription.Canceled(): + return + } + } + }() + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + err = s.PublishWithEvents( + ctx, + "Gamora", + map[string][]string{"abci.Account.Owner": {"Ivan"}, "abci.Invoices.Number": {string(rune(i))}}, + ) + require.NoError(b, err) + } +} + +func benchmarkNClientsOneQuery(n int, b *testing.B) { + s := pubsub.NewServer() + err := s.Start() + require.NoError(b, err) + b.Cleanup(func() { + if err := s.Stop(); err != nil { + b.Error(err) + } + }) + + ctx := context.Background() + q := query.MustCompile("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = 1") + for i := 0; i < n; i++ { + subscription, err := s.Subscribe(ctx, clientID, q) + if err != nil { + b.Fatal(err) + } + go func() { + for { + select { + case <-subscription.Out(): + continue + case <-subscription.Canceled(): + return + } + } + }() + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + err = s.PublishWithEvents(ctx, "Gamora", map[string][]string{"abci.Account.Owner": {"Ivan"}, + "abci.Invoices.Number": {"1"}}) + require.NoError(b, err) + } +} + +// HELPERS + +func assertReceive(t *testing.T, expected interface{}, ch <-chan pubsub.Message, msgAndArgs ...interface{}) { + select { + case actual := <-ch: + assert.Equal(t, expected, actual.Data(), msgAndArgs...) + case <-time.After(1 * time.Second): + t.Errorf("expected to receive %v from the channel, got nothing after 1s", expected) + debug.PrintStack() + } +} + +func assertCancelled(t *testing.T, subscription *pubsub.Subscription, err error) { + _, ok := <-subscription.Canceled() + assert.False(t, ok) + assert.Equal(t, err, subscription.Err()) +} diff --git a/libs/pubsub/query/.gitignore b/libs/pubsub/query/.gitignore new file mode 100644 index 0000000..f3c3c0c --- /dev/null +++ b/libs/pubsub/query/.gitignore @@ -0,0 +1,7 @@ +# This is a temporary directory to hold the peg binary, +# to work around https://github.com/pointlander/peg/issues/129. +# Note that once we have a new version of peg fixing #129, +# we may still want to keep this .gitignore to prevent anyone +# from accidentally running "git add ." and including their built +# peg binary in a commit. +.bin/ diff --git a/libs/pubsub/query/bench_test.go b/libs/pubsub/query/bench_test.go new file mode 100644 index 0000000..cc0554a --- /dev/null +++ b/libs/pubsub/query/bench_test.go @@ -0,0 +1,46 @@ +package query_test + +import ( + "testing" + + "github.com/cometbft/cometbft/libs/pubsub/query" +) + +const testQuery = `tm.events.type='NewBlock' AND abci.account.name='Igor'` + +var testEvents = map[string][]string{ + "tm.events.index": { + "25", + }, + "tm.events.type": { + "NewBlock", + }, + "abci.account.name": { + "Anya", "Igor", + }, +} + +func BenchmarkParseCustom(b *testing.B) { + for i := 0; i < b.N; i++ { + _, err := query.New(testQuery) + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkMatchCustom(b *testing.B) { + q, err := query.New(testQuery) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + ok, err := q.Matches(testEvents) + if err != nil { + b.Fatal(err) + } else if !ok { + b.Error("no match") + } + } +} diff --git a/libs/pubsub/query/query.go b/libs/pubsub/query/query.go new file mode 100644 index 0000000..a6a1aeb --- /dev/null +++ b/libs/pubsub/query/query.go @@ -0,0 +1,357 @@ +// Package query implements the custom query format used to filter event +// subscriptions in CometBFT. +// +// abci.invoice.number=22 AND abci.invoice.owner=Ivan +// +// Query expressions can handle attribute values encoding numbers, strings, +// dates, and timestamps. The complete query grammar is described in the +// query/syntax package. +package query + +import ( + "fmt" + "math/big" + "regexp" + "strings" + "time" + + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" +) + +// All is a query that matches all events. +var All *Query + +// A Query is the compiled form of a query. +type Query struct { + ast syntax.Query + conds []condition +} + +// New parses and compiles the query expression into an executable query. +func New(query string) (*Query, error) { + ast, err := syntax.Parse(query) + if err != nil { + return nil, err + } + return Compile(ast) +} + +// MustCompile compiles the query expression into an executable query. +// In case of error, MustCompile will panic. +// +// This is intended for use in program initialization; use query.New if you +// need to check errors. +func MustCompile(query string) *Query { + q, err := New(query) + if err != nil { + panic(err) + } + return q +} + +// Compile compiles the given query AST so it can be used to match events. +func Compile(ast syntax.Query) (*Query, error) { + conds := make([]condition, len(ast)) + for i, q := range ast { + cond, err := compileCondition(q) + if err != nil { + return nil, fmt.Errorf("compile %s: %w", q, err) + } + conds[i] = cond + } + return &Query{ast: ast, conds: conds}, nil +} + +func ExpandEvents(flattenedEvents map[string][]string) []types.Event { + events := make([]types.Event, 0) + + for composite, values := range flattenedEvents { + tokens := strings.Split(composite, ".") + + attrs := make([]types.EventAttribute, len(values)) + for i, v := range values { + attrs[i] = types.EventAttribute{ + Key: tokens[len(tokens)-1], + Value: v, + } + } + + events = append(events, types.Event{ + Type: strings.Join(tokens[:len(tokens)-1], "."), + Attributes: attrs, + }) + } + + return events +} + +// Matches satisfies part of the pubsub.Query interface. This implementation +// never reports an error. A nil *Query matches all events. +func (q *Query) Matches(events map[string][]string) (bool, error) { + if q == nil { + return true, nil + } + return q.matchesEvents(ExpandEvents(events)), nil +} + +// String matches part of the pubsub.Query interface. +func (q *Query) String() string { + if q == nil { + return "" + } + return q.ast.String() +} + +// Syntax returns the syntax tree representation of q. +func (q *Query) Syntax() syntax.Query { + if q == nil { + return nil + } + return q.ast +} + +// matchesEvents reports whether all the conditions match the given events. +func (q *Query) matchesEvents(events []types.Event) bool { + for _, cond := range q.conds { + if !cond.matchesAny(events) { + return false + } + } + return len(events) != 0 +} + +// A condition is a compiled match condition. A condition matches an event if +// the event has the designated type, contains an attribute with the given +// name, and the match function returns true for the attribute value. +type condition struct { + tag string // e.g., "tx.hash" + match func(s string) bool +} + +// findAttr returns a slice of attribute values from event matching the +// condition tag, and reports whether the event type strictly equals the +// condition tag. +func (c condition) findAttr(event types.Event) ([]string, bool) { + if !strings.HasPrefix(c.tag, event.Type) { + return nil, false // type does not match tag + } else if len(c.tag) == len(event.Type) { + return nil, true // type == tag + } + var vals []string + for _, attr := range event.Attributes { + fullName := event.Type + "." + attr.Key + if fullName == c.tag { + vals = append(vals, attr.Value) + } + } + return vals, false +} + +// matchesAny reports whether c matches at least one of the given events. +func (c condition) matchesAny(events []types.Event) bool { + for _, event := range events { + if c.matchesEvent(event) { + return true + } + } + return false +} + +// matchesEvent reports whether c matches the given event. +func (c condition) matchesEvent(event types.Event) bool { + vs, tagEqualsType := c.findAttr(event) + if len(vs) == 0 { + // As a special case, a condition tag that exactly matches the event type + // is matched against an empty string. This allows existence checks to + // work for type-only queries. + if tagEqualsType { + return c.match("") + } + return false + } + + // At this point, we have candidate values. + for _, v := range vs { + if c.match(v) { + return true + } + } + return false +} + +func compileCondition(cond syntax.Condition) (condition, error) { + out := condition{tag: cond.Tag} + + // Handle existence checks separately to simplify the logic below for + // comparisons that take arguments. + if cond.Op == syntax.TExists { + out.match = func(string) bool { return true } + return out, nil + } + + // All the other operators require an argument. + if cond.Arg == nil { + return condition{}, fmt.Errorf("missing argument for %v", cond.Op) + } + + // Precompile the argument value matcher. + argType := cond.Arg.Type + var argValue interface{} + + switch argType { + case syntax.TString: + argValue = cond.Arg.Value() + case syntax.TNumber: + argValue = cond.Arg.Number() + case syntax.TTime, syntax.TDate: + argValue = cond.Arg.Time() + default: + return condition{}, fmt.Errorf("unknown argument type %v", argType) + } + + mcons := opTypeMap[cond.Op][argType] + if mcons == nil { + return condition{}, fmt.Errorf("invalid op/arg combination (%v, %v)", cond.Op, argType) + } + out.match = mcons(argValue) + return out, nil +} + +// We use this regex to support queries of the form "8atom", "6.5stake", +// which are actively used in production. +// The regex takes care of removing the non-number suffix. +var extractNum = regexp.MustCompile(`^\d+(\.\d+)?`) + +func parseNumber(s string) (*big.Float, error) { + intVal := new(big.Int) + if _, ok := intVal.SetString(s, 10); !ok { + f, _, err := big.ParseFloat(extractNum.FindString(s), 10, 125, big.ToNearestEven) + if err != nil { + return nil, err + } + return f, err + } + f, _, err := big.ParseFloat(extractNum.FindString(s), 10, uint(intVal.BitLen()), big.ToNearestEven) + return f, err + +} + +// A map of operator ⇒ argtype ⇒ match-constructor. +// An entry does not exist if the combination is not valid. +// +// Disable the dupl lint for this map. The result isn't even correct. +// +//nolint:dupl +var opTypeMap = map[syntax.Token]map[syntax.Token]func(interface{}) func(string) bool{ + syntax.TContains: { + syntax.TString: func(v interface{}) func(string) bool { + return func(s string) bool { + return strings.Contains(s, v.(string)) + } + }, + }, + syntax.TEq: { + syntax.TString: func(v interface{}) func(string) bool { + return func(s string) bool { return s == v.(string) } + }, + syntax.TNumber: func(v interface{}) func(string) bool { + return func(s string) bool { + w, err := parseNumber(s) + return err == nil && w.Cmp(v.(*big.Float)) == 0 + } + }, + syntax.TDate: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseDate(s) + return err == nil && ts.Equal(v.(time.Time)) + } + }, + syntax.TTime: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseTime(s) + return err == nil && ts.Equal(v.(time.Time)) + } + }, + }, + syntax.TLt: { + syntax.TNumber: func(v interface{}) func(string) bool { + return func(s string) bool { + w, err := parseNumber(s) + return err == nil && w.Cmp(v.(*big.Float)) < 0 + } + }, + syntax.TDate: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseDate(s) + return err == nil && ts.Before(v.(time.Time)) + } + }, + syntax.TTime: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseTime(s) + return err == nil && ts.Before(v.(time.Time)) + } + }, + }, + syntax.TLeq: { + syntax.TNumber: func(v interface{}) func(string) bool { + return func(s string) bool { + w, err := parseNumber(s) + return err == nil && w.Cmp(v.(*big.Float)) <= 0 + } + }, + syntax.TDate: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseDate(s) + return err == nil && !ts.After(v.(time.Time)) + } + }, + syntax.TTime: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseTime(s) + return err == nil && !ts.After(v.(time.Time)) + } + }, + }, + syntax.TGt: { + syntax.TNumber: func(v interface{}) func(string) bool { + return func(s string) bool { + w, err := parseNumber(s) + return err == nil && w.Cmp(v.(*big.Float)) > 0 + } + }, + syntax.TDate: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseDate(s) + return err == nil && ts.After(v.(time.Time)) + } + }, + syntax.TTime: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseTime(s) + return err == nil && ts.After(v.(time.Time)) + } + }, + }, + syntax.TGeq: { + syntax.TNumber: func(v interface{}) func(string) bool { + return func(s string) bool { + w, err := parseNumber(s) + return err == nil && w.Cmp(v.(*big.Float)) >= 0 + } + }, + syntax.TDate: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseDate(s) + return err == nil && !ts.Before(v.(time.Time)) + } + }, + syntax.TTime: func(v interface{}) func(string) bool { + return func(s string) bool { + ts, err := syntax.ParseTime(s) + return err == nil && !ts.Before(v.(time.Time)) + } + }, + }, +} diff --git a/libs/pubsub/query/query_test.go b/libs/pubsub/query/query_test.go new file mode 100644 index 0000000..afe650e --- /dev/null +++ b/libs/pubsub/query/query_test.go @@ -0,0 +1,486 @@ +package query_test + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" +) + +var _ pubsub.Query = (*query.Query)(nil) + +// Example events from the OpenAPI documentation: +// +// https://github.com/cometbft/cometbft/blob/master/rpc/openapi/openapi.yaml +// +// Redactions: +// +// - Add an explicit "tm" event for the built-in attributes. +// - Remove Index fields (not relevant to tests). +// - Add explicit balance values (to use in tests). +var apiEvents = map[string][]string{ + "tm.event": { + "Tx", + }, + "tm.hash": { + "XYZ", + }, + "tm.height": { + "5", + }, + "rewards.withdraw.address": { + "AddrA", + "AddrB", + }, + "rewards.withdraw.source": { + "SrcX", + "SrcY", + }, + "rewards.withdraw.amount": { + "100", + "45", + }, + "rewards.withdraw.balance": { + "1500", + "999", + }, + "transfer.sender": { + "AddrC", + }, + "transfer.recipient": { + "AddrD", + }, + "transfer.amount": { + "160", + }, +} + +var apiTypeEvents = []types.Event{ + { + Type: "tm", + Attributes: []types.EventAttribute{ + { + Key: "event", + Value: "Tx", + }, + }, + }, + { + Type: "tm", + Attributes: []types.EventAttribute{ + { + Key: "hash", + Value: "XYZ", + }, + }, + }, + { + Type: "tm", + Attributes: []types.EventAttribute{ + { + Key: "height", + Value: "5", + }, + }, + }, + { + Type: "rewards.withdraw", + Attributes: []types.EventAttribute{ + { + Key: "address", + Value: "AddrA", + }, + { + Key: "address", + Value: "AddrB", + }, + }, + }, + { + Type: "rewards.withdraw", + Attributes: []types.EventAttribute{ + { + Key: "source", + Value: "SrcX", + }, + { + Key: "source", + Value: "SrcY", + }, + }, + }, + { + Type: "rewards.withdraw", + Attributes: []types.EventAttribute{ + { + Key: "amount", + Value: "100", + }, + { + Key: "amount", + Value: "45", + }, + }, + }, + { + Type: "rewards.withdraw", + Attributes: []types.EventAttribute{ + { + Key: "balance", + Value: "1500", + }, + { + Key: "balance", + Value: "999", + }, + }, + }, + { + Type: "transfer", + Attributes: []types.EventAttribute{ + { + Key: "sender", + Value: "AddrC", + }, + }, + }, + { + Type: "transfer", + Attributes: []types.EventAttribute{ + { + Key: "recipient", + Value: "AddrD", + }, + }, + }, + { + Type: "transfer", + Attributes: []types.EventAttribute{ + { + Key: "amount", + Value: "160", + }, + }, + }, +} + +func TestBigNumbers(t *testing.T) { + + apiBigNumTest := map[string][]string{ + "big.value": { + "99999999999999999999", + }, + "big2.value": { + "18446744073709551615", // max(uint64) == 18446744073709551615 + }, + "big.floatvalue": { + "99999999999999999999.10", + }, + "big2.floatvalue": { + "18446744073709551615.6", // max(uint64) == 18446744073709551615 + }, + } + + testCases := []struct { + s string + events map[string][]string + matches bool + }{ + + // Test cases for values that exceed the capacity if int64/float64. + {`big.value >= 99999999999999999999`, + apiBigNumTest, + true}, + {`big.value > 99999999999999999998`, + apiBigNumTest, + true}, + {`big2.value <= 18446744073709551615`, + apiBigNumTest, true}, + {`big.floatvalue >= 99999999999999999999`, + apiBigNumTest, + true}, + {`big.floatvalue > 99999999999999999998.10`, + apiBigNumTest, + true}, + {`big.floatvalue > 99999999999999999998`, + apiBigNumTest, + true}, + {`big2.floatvalue <= 18446744073709551615.6`, + apiBigNumTest, + true}, + {`big2.floatvalue <= 18446744073709551615.6`, + apiBigNumTest, + true}, + {`big2.floatvalue >= 18446744073709551615`, + apiBigNumTest, + true}, + {`big2.floatvalue >= 12.5`, + apiBigNumTest, + true}, + {`big.value >= 10`, + apiBigNumTest, + true}, + } + + for i, tc := range testCases { + t.Run(fmt.Sprintf("%02d", i+1), func(t *testing.T) { + c, err := query.New(tc.s) + if err != nil { + t.Fatalf("NewCompiled %#q: unexpected error: %v", tc.s, err) + } + + got, err := c.Matches(tc.events) + if err != nil { + t.Errorf("Query: %#q\nInput: %+v\nMatches: got error %v", + tc.s, tc.events, err) + } + if got != tc.matches { + t.Errorf("Query: %#q\nInput: %+v\nMatches: got %v, want %v", + tc.s, tc.events, got, tc.matches) + } + }) + } +} + +func TestCompiledMatches(t *testing.T) { + var ( + txDate = "2017-01-01" + txTime = "2018-05-03T14:45:00Z" + ) + + //nolint:lll + testCases := []struct { + s string + events map[string][]string + matches bool + }{ + {`tm.events.type='NewBlock'`, + newTestEvents(`tm|events.type=NewBlock`), + true}, + {`tx.gas > 7`, + newTestEvents(`tx|gas=8`), + true}, + {`transfer.amount > 7`, + newTestEvents(`transfer|amount=8stake`), + true}, + {`transfer.amount > 7`, + newTestEvents(`transfer|amount=8.045`), + true}, + {`transfer.amount > 7.043`, + newTestEvents(`transfer|amount=8.045stake`), + true}, + {`transfer.amount > 8.045`, + newTestEvents(`transfer|amount=8.045stake`), + false}, + {`tx.gas > 7 AND tx.gas < 9`, + newTestEvents(`tx|gas=8`), + true}, + {`body.weight >= 3.5`, + newTestEvents(`body|weight=3.5`), + true}, + {`account.balance < 1000.0`, + newTestEvents(`account|balance=900`), + true}, + {`apples.kg <= 4`, + newTestEvents(`apples|kg=4.0`), + true}, + {`body.weight >= 4.5`, + newTestEvents(`body|weight=4.5`), + true}, + {`oranges.kg < 4 AND watermellons.kg > 10`, + newTestEvents(`oranges|kg=3`, `watermellons|kg=12`), + true}, + {`peaches.kg < 4`, + newTestEvents(`peaches|kg=5`), + false}, + {`tx.date > DATE 2017-01-01`, + newTestEvents(`tx|date=` + time.Now().Format(syntax.DateFormat)), + true}, + {`tx.date = DATE 2017-01-01`, + newTestEvents(`tx|date=` + txDate), + true}, + {`tx.date = DATE 2018-01-01`, + newTestEvents(`tx|date=` + txDate), + false}, + {`tx.time >= TIME 2013-05-03T14:45:00Z`, + newTestEvents(`tx|time=` + time.Now().Format(syntax.TimeFormat)), + true}, + {`tx.time = TIME 2013-05-03T14:45:00Z`, + newTestEvents(`tx|time=` + txTime), + false}, + {`abci.owner.name CONTAINS 'Igor'`, + newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`), + true}, + {`abci.owner.name CONTAINS 'Igor'`, + newTestEvents(`abci|owner.name=Pavel|owner.name=Ivan`), + false}, + {`abci.owner.name = 'Igor'`, + newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`), + true}, + {`abci.owner.name = 'Ivan'`, + newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`), + true}, + {`abci.owner.name = 'Ivan' AND abci.owner.name = 'Igor'`, + newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`), + true}, + {`abci.owner.name = 'Ivan' AND abci.owner.name = 'John'`, + newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`), + false}, + {`tm.events.type='NewBlock'`, + newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`), + true}, + {`app.name = 'fuzzed'`, + newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`), + true}, + {`tm.events.type='NewBlock' AND app.name = 'fuzzed'`, + newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`), + true}, + {`tm.events.type='NewHeader' AND app.name = 'fuzzed'`, + newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`), + false}, + {`slash EXISTS`, + newTestEvents(`slash|reason=missing_signature|power=6000`), + true}, + {`slash EXISTS`, + newTestEvents(`transfer|recipient=cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz|sender=cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5`), + false}, + {`slash.reason EXISTS AND slash.power > 1000`, + newTestEvents(`slash|reason=missing_signature|power=6000`), + true}, + {`slash.reason EXISTS AND slash.power > 1000`, + newTestEvents(`slash|reason=missing_signature|power=500`), + false}, + {`slash.reason EXISTS`, + newTestEvents(`transfer|recipient=cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz|sender=cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5`), + false}, + + // Test cases based on the OpenAPI examples. + {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA'`, + apiEvents, true}, + {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA' AND rewards.withdraw.source = 'SrcY'`, + apiEvents, true}, + {`tm.event = 'Tx' AND transfer.sender = 'AddrA'`, + apiEvents, false}, + {`tm.event = 'Tx' AND transfer.sender = 'AddrC'`, + apiEvents, true}, + {`tm.event = 'Tx' AND transfer.sender = 'AddrZ'`, + apiEvents, false}, + {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrZ'`, + apiEvents, false}, + {`tm.event = 'Tx' AND rewards.withdraw.source = 'W'`, + apiEvents, false}, + } + + // NOTE: The original implementation allowed arbitrary prefix matches on + // attribute tags, e.g., "sl" would match "slash". + // + // That is weird and probably wrong: "foo.ba" should not match "foo.bar", + // or there is no way to distinguish the case where there were two values + // for "foo.bar" or one value each for "foo.ba" and "foo.bar". + // + // Apart from a single test case, I could not find any attested usage of + // this implementation detail. It isn't documented in the OpenAPI docs and + // is not shown in any of the example inputs. + // + // On that basis, I removed that test case. This implementation still does + // correctly handle variable type/attribute splits ("x", "y.z" / "x.y", "z") + // since that was required by the original "flattened" event representation. + + for i, tc := range testCases { + t.Run(fmt.Sprintf("%02d", i+1), func(t *testing.T) { + c, err := query.New(tc.s) + if err != nil { + t.Fatalf("NewCompiled %#q: unexpected error: %v", tc.s, err) + } + + got, err := c.Matches(tc.events) + if err != nil { + t.Errorf("Query: %#q\nInput: %+v\nMatches: got error %v", + tc.s, tc.events, err) + } + if got != tc.matches { + t.Errorf("Query: %#q\nInput: %+v\nMatches: got %v, want %v", + tc.s, tc.events, got, tc.matches) + } + }) + } +} + +func sortEvents(events []types.Event) []types.Event { + sort.Slice(events, func(i, j int) bool { + if events[i].Type == events[j].Type { + return events[i].Attributes[0].Key < events[j].Attributes[0].Key + } + return events[i].Type < events[j].Type + }) + return events +} + +func TestExpandEvents(t *testing.T) { + expanded := query.ExpandEvents(apiEvents) + bz, err := json.Marshal(sortEvents(expanded)) + require.NoError(t, err) + bz2, err := json.Marshal(sortEvents(apiTypeEvents)) + require.NoError(t, err) + if string(bz) != string(bz2) { + t.Errorf("got %s, want %v", string(bz), string(bz2)) + } +} + +func TestAllMatchesAll(t *testing.T) { + events := newTestEvents( + ``, + `Asher|Roth=`, + `Route|66=`, + `Rilly|Blue=`, + ) + keys := make([]string, 0) + for k := range events { + keys = append(keys, k) + } + for _, key := range keys { + delete(events, key) + match, err := query.All.Matches(events) + if err != nil { + t.Errorf("Matches failed: %v", err) + } else if !match { + t.Errorf("Did not match on %+v ", events) + } + } +} + +// newTestEvent constructs an Event message from a template string. +// The format is "type|attr1=val1|attr2=val2|...". +func addNewTestEvent(events map[string][]string, s string) { + parts := strings.Split(s, "|") + key := parts[0] + for _, kv := range parts[1:] { + k, v := splitKV(kv) + k = key + "." + k + events[k] = append(events[k], v) + } +} + +// newTestEvents constructs a slice of Event messages by applying newTestEvent +// to each element of ss. +func newTestEvents(ss ...string) map[string][]string { + events := make(map[string][]string) + for _, s := range ss { + addNewTestEvent(events, s) + } + return events +} + +func splitKV(s string) (key, value string) { + kv := strings.SplitN(s, "=", 2) + return kv[0], kv[1] +} diff --git a/libs/pubsub/query/syntax/doc.go b/libs/pubsub/query/syntax/doc.go new file mode 100644 index 0000000..db01497 --- /dev/null +++ b/libs/pubsub/query/syntax/doc.go @@ -0,0 +1,33 @@ +// Package syntax defines a scanner and parser for the CometBFT event filter +// query language. A query selects events by their types and attribute values. +// +// # Grammar +// +// The grammar of the query language is defined by the following EBNF: +// +// query = conditions EOF +// conditions = condition {"AND" condition} +// condition = tag comparison +// comparison = equal / order / contains / "EXISTS" +// equal = "=" (date / number / time / value) +// order = cmp (date / number / time) +// contains = "CONTAINS" value +// cmp = "<" / "<=" / ">" / ">=" +// +// The lexical terms are defined here using RE2 regular expression notation: +// +// // The name of an event attribute (type.value) +// tag = #`^[\w]+[\.-\w]?$` +// +// // A datestamp (YYYY-MM-DD) +// date = #'DATE \d{4}-\d{2}-\d{2}' +// +// // A number with optional fractional parts (0, 10, 3.25) +// number = #'\d+(\.\d+)?' +// +// // An RFC3339 timestamp (2021-11-23T22:04:19-09:00) +// time = #'TIME \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}([-+]\d{2}:\d{2}|Z)' +// +// // A quoted literal string value ('a b c') +// value = #'\'[^\']*\'' +package syntax diff --git a/libs/pubsub/query/syntax/parser.go b/libs/pubsub/query/syntax/parser.go new file mode 100644 index 0000000..bcb29d9 --- /dev/null +++ b/libs/pubsub/query/syntax/parser.go @@ -0,0 +1,230 @@ +package syntax + +import ( + "fmt" + "io" + "math/big" + "strings" + "time" +) + +// Parse parses the specified query string. It is shorthand for constructing a +// parser for s and calling its Parse method. +func Parse(s string) (Query, error) { + return NewParser(strings.NewReader(s)).Parse() +} + +// Query is the root of the parse tree for a query. A query is the conjunction +// of one or more conditions. +type Query []Condition + +func (q Query) String() string { + ss := make([]string, len(q)) + for i, cond := range q { + ss[i] = cond.String() + } + return strings.Join(ss, " AND ") +} + +// A Condition is a single conditional expression, consisting of a tag, a +// comparison operator, and an optional argument. The type of the argument +// depends on the operator. +type Condition struct { + Tag string + Op Token + Arg *Arg + + opText string +} + +func (c Condition) String() string { + s := c.Tag + " " + c.opText + if c.Arg != nil { + return s + " " + c.Arg.String() + } + return s +} + +// An Arg is the argument of a comparison operator. +type Arg struct { + Type Token + text string +} + +func (a *Arg) String() string { + if a == nil { + return "" + } + switch a.Type { + case TString: + return "'" + a.text + "'" + case TTime: + return "TIME " + a.text + case TDate: + return "DATE " + a.text + default: + return a.text + } +} + +// Number returns the value of the argument text as a number, or nil if the +// text does not encode a valid number value. +func (a *Arg) Number() *big.Float { + if a == nil { + return nil + } + intVal := new(big.Int) + if _, ok := intVal.SetString(a.text, 10); !ok { + f, _, err := big.ParseFloat(a.text, 10, 125, big.ToNearestEven) + if err != nil { + return nil + } + return f + } + // If it is indeed a big integer, we make sure to convert it to a float with enough precision + // to represent all the bits + bitLen := uint(intVal.BitLen()) + var f *big.Float + var err error + if bitLen <= 64 { + f, _, err = big.ParseFloat(a.text, 10, 0, big.ToNearestEven) + } else { + f, _, err = big.ParseFloat(a.text, 10, bitLen, big.ToNearestEven) + } + if err != nil { + return nil + } + return f + +} + +// Time returns the value of the argument text as a time, or the zero value if +// the text does not encode a timestamp or datestamp. +func (a *Arg) Time() time.Time { + var ts time.Time + if a == nil { + return ts + } + var err error + switch a.Type { + case TDate: + ts, err = ParseDate(a.text) + case TTime: + ts, err = ParseTime(a.text) + } + if err == nil { + return ts + } + return time.Time{} +} + +// Value returns the value of the argument text as a string, or "". +func (a *Arg) Value() string { + if a == nil { + return "" + } + return a.text +} + +// Parser is a query expression parser. The grammar for query expressions is +// defined in the syntax package documentation. +type Parser struct { + scanner *Scanner +} + +// NewParser constructs a new parser that reads the input from r. +func NewParser(r io.Reader) *Parser { + return &Parser{scanner: NewScanner(r)} +} + +// Parse parses the complete input and returns the resulting query. +func (p *Parser) Parse() (Query, error) { + cond, err := p.parseCond() + if err != nil { + return nil, err + } + conds := []Condition{cond} + for p.scanner.Next() != io.EOF { + if tok := p.scanner.Token(); tok != TAnd { + return nil, fmt.Errorf("offset %d: got %v, want %v", p.scanner.Pos(), tok, TAnd) + } + cond, err := p.parseCond() + if err != nil { + return nil, err + } + conds = append(conds, cond) + } + return conds, nil +} + +// parseCond parses a conditional expression: tag OP value. +func (p *Parser) parseCond() (Condition, error) { + var cond Condition + if err := p.require(TTag); err != nil { + return cond, err + } + cond.Tag = p.scanner.Text() + if err := p.require(TLeq, TGeq, TLt, TGt, TEq, TContains, TExists); err != nil { + return cond, err + } + cond.Op = p.scanner.Token() + cond.opText = p.scanner.Text() + + var err error + switch cond.Op { + case TLeq, TGeq, TLt, TGt: + err = p.require(TNumber, TTime, TDate) + case TEq: + err = p.require(TNumber, TTime, TDate, TString) + case TContains: + err = p.require(TString) + case TExists: + // no argument + return cond, nil + default: + return cond, fmt.Errorf("offset %d: unexpected operator %v", p.scanner.Pos(), cond.Op) + } + if err != nil { + return cond, err + } + cond.Arg = &Arg{Type: p.scanner.Token(), text: p.scanner.Text()} + return cond, nil +} + +// require advances the scanner and requires that the resulting token is one of +// the specified token types. +func (p *Parser) require(tokens ...Token) error { + if err := p.scanner.Next(); err != nil { + return fmt.Errorf("offset %d: %w", p.scanner.Pos(), err) + } + got := p.scanner.Token() + for _, tok := range tokens { + if tok == got { + return nil + } + } + return fmt.Errorf("offset %d: got %v, wanted %s", p.scanner.Pos(), got, tokLabel(tokens)) +} + +// tokLabel makes a human-readable summary string for the given token types. +func tokLabel(tokens []Token) string { + if len(tokens) == 1 { + return tokens[0].String() + } + last := len(tokens) - 1 + ss := make([]string, len(tokens)-1) + for i, tok := range tokens[:last] { + ss[i] = tok.String() + } + return strings.Join(ss, ", ") + " or " + tokens[last].String() +} + +// ParseDate parses s as a date string in the format used by DATE values. +func ParseDate(s string) (time.Time, error) { + return time.Parse("2006-01-02", s) +} + +// ParseTime parses s as a timestamp in the format used by TIME values. +func ParseTime(s string) (time.Time, error) { + return time.Parse(time.RFC3339, s) +} diff --git a/libs/pubsub/query/syntax/scanner.go b/libs/pubsub/query/syntax/scanner.go new file mode 100644 index 0000000..64aadbe --- /dev/null +++ b/libs/pubsub/query/syntax/scanner.go @@ -0,0 +1,316 @@ +package syntax + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strings" + "time" + "unicode" +) + +// Token is the type of a lexical token in the query grammar. +type Token byte + +const ( + TInvalid = iota // invalid or unknown token + TTag // field tag: x.y + TString // string value: 'foo bar' + TNumber // number: 0, 15.5, 100 + TTime // timestamp: TIME yyyy-mm-ddThh:mm:ss([-+]hh:mm|Z) + TDate // datestamp: DATE yyyy-mm-dd + TAnd // operator: AND + TContains // operator: CONTAINS + TExists // operator: EXISTS + TEq // operator: = + TLt // operator: < + TLeq // operator: <= + TGt // operator: > + TGeq // operator: >= + + // Do not reorder these values without updating the scanner code. +) + +var tString = [...]string{ + TInvalid: "invalid token", + TTag: "tag", + TString: "string", + TNumber: "number", + TTime: "timestamp", + TDate: "datestamp", + TAnd: "AND operator", + TContains: "CONTAINS operator", + TExists: "EXISTS operator", + TEq: "= operator", + TLt: "< operator", + TLeq: "<= operator", + TGt: "> operator", + TGeq: ">= operator", +} + +func (t Token) String() string { + v := int(t) + if v > len(tString) { + return "unknown token type" + } + return tString[v] +} + +const ( + // TimeFormat is the format string used for timestamp values. + TimeFormat = time.RFC3339 + + // DateFormat is the format string used for datestamp values. + DateFormat = "2006-01-02" +) + +// Scanner reads lexical tokens of the query language from an input stream. +// Each call to Next advances the scanner to the next token, or reports an +// error. +type Scanner struct { + r *bufio.Reader + buf bytes.Buffer + tok Token + err error + + pos, last, end int +} + +// NewScanner constructs a new scanner that reads from r. +func NewScanner(r io.Reader) *Scanner { return &Scanner{r: bufio.NewReader(r)} } + +// Next advances s to the next token in the input, or reports an error. At the +// end of input, Next returns io.EOF. +func (s *Scanner) Next() error { + s.buf.Reset() + s.pos = s.end + s.tok = TInvalid + s.err = nil + + for { + ch, err := s.rune() + if err != nil { + return s.fail(err) + } + if unicode.IsSpace(ch) { + s.pos = s.end + continue // skip whitespace + } + if '0' <= ch && ch <= '9' { + return s.scanNumber(ch) + } else if isFirstTagRune(ch) { + return s.scanTagLike(ch) + } + switch ch { + case '\'': + return s.scanString(ch) + case '<', '>', '=': + return s.scanCompare(ch) + default: + return s.invalid(ch) + } + } +} + +// Token returns the type of the current input token. +func (s *Scanner) Token() Token { return s.tok } + +// Text returns the text of the current input token. +func (s *Scanner) Text() string { return s.buf.String() } + +// Pos returns the start offset of the current token in the input. +func (s *Scanner) Pos() int { return s.pos } + +// Err returns the last error reported by Next, if any. +func (s *Scanner) Err() error { return s.err } + +// scanNumber scans for numbers with optional fractional parts. +// Examples: 0, 1, 3.14 +func (s *Scanner) scanNumber(first rune) error { + s.buf.WriteRune(first) + if err := s.scanWhile(isDigit); err != nil { + return err + } + + ch, err := s.rune() + if err != nil && err != io.EOF { + return err + } + if ch == '.' { + s.buf.WriteRune(ch) + if err := s.scanWhile(isDigit); err != nil { + return err + } + } else { + s.unrune() + } + s.tok = TNumber + return nil +} + +func (s *Scanner) scanString(first rune) error { + // discard opening quote + for { + ch, err := s.rune() + if err != nil { + return s.fail(err) + } else if ch == first { + // discard closing quote + s.tok = TString + return nil + } + s.buf.WriteRune(ch) + } +} + +func (s *Scanner) scanCompare(first rune) error { + s.buf.WriteRune(first) + switch first { + case '=': + s.tok = TEq + return nil + case '<': + s.tok = TLt + case '>': + s.tok = TGt + default: + return s.invalid(first) + } + + ch, err := s.rune() + if err == io.EOF { + return nil // the assigned token is correct + } else if err != nil { + return s.fail(err) + } + if ch == '=' { + s.buf.WriteRune(ch) + s.tok++ // depends on token order + return nil + } + s.unrune() + return nil +} + +func (s *Scanner) scanTagLike(first rune) error { + s.buf.WriteRune(first) + var hasSpace bool + for { + ch, err := s.rune() + if err == io.EOF { + break + } else if err != nil { + return s.fail(err) + } + if !isTagRune(ch) { + hasSpace = ch == ' ' // to check for TIME, DATE + break + } + s.buf.WriteRune(ch) + } + + text := s.buf.String() + switch text { + case "TIME": + if hasSpace { + return s.scanTimestamp() + } + s.tok = TTag + case "DATE": + if hasSpace { + return s.scanDatestamp() + } + s.tok = TTag + case "AND": + s.tok = TAnd + case "EXISTS": + s.tok = TExists + case "CONTAINS": + s.tok = TContains + default: + s.tok = TTag + } + s.unrune() + return nil +} + +func (s *Scanner) scanTimestamp() error { + s.buf.Reset() // discard "TIME" label + if err := s.scanWhile(isTimeRune); err != nil { + return err + } + if ts, err := time.Parse(TimeFormat, s.buf.String()); err != nil { + return s.fail(fmt.Errorf("invalid TIME value: %w", err)) + } else if y := ts.Year(); y < 1900 || y > 2999 { + return s.fail(fmt.Errorf("timestamp year %d out of range", ts.Year())) + } + s.tok = TTime + return nil +} + +func (s *Scanner) scanDatestamp() error { + s.buf.Reset() // discard "DATE" label + if err := s.scanWhile(isDateRune); err != nil { + return err + } + if ts, err := time.Parse(DateFormat, s.buf.String()); err != nil { + return s.fail(fmt.Errorf("invalid DATE value: %w", err)) + } else if y := ts.Year(); y < 1900 || y > 2999 { + return s.fail(fmt.Errorf("datestamp year %d out of range", ts.Year())) + } + s.tok = TDate + return nil +} + +func (s *Scanner) scanWhile(ok func(rune) bool) error { + for { + ch, err := s.rune() + if err == io.EOF { + return nil + } else if err != nil { + return s.fail(err) + } else if !ok(ch) { + s.unrune() + return nil + } + s.buf.WriteRune(ch) + } +} + +func (s *Scanner) rune() (rune, error) { + ch, nb, err := s.r.ReadRune() + s.last = nb + s.end += nb + return ch, err +} + +func (s *Scanner) unrune() { + _ = s.r.UnreadRune() + s.end -= s.last +} + +func (s *Scanner) fail(err error) error { + s.err = err + return err +} + +func (s *Scanner) invalid(ch rune) error { + return s.fail(fmt.Errorf("invalid input %c at offset %d", ch, s.end)) +} + +func isDigit(r rune) bool { return '0' <= r && r <= '9' } + +func isTagRune(r rune) bool { + return r == '.' || r == '_' || r == '-' || unicode.IsLetter(r) || unicode.IsDigit(r) +} + +func isFirstTagRune(r rune) bool { + return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) +} + +func isTimeRune(r rune) bool { + return strings.ContainsRune("-T:+Z", r) || isDigit(r) +} + +func isDateRune(r rune) bool { return isDigit(r) || r == '-' } diff --git a/libs/pubsub/query/syntax/syntax_test.go b/libs/pubsub/query/syntax/syntax_test.go new file mode 100644 index 0000000..a0cd098 --- /dev/null +++ b/libs/pubsub/query/syntax/syntax_test.go @@ -0,0 +1,194 @@ +package syntax_test + +import ( + "io" + "reflect" + "strings" + "testing" + + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" +) + +func TestScanner(t *testing.T) { + tests := []struct { + input string + want []syntax.Token + }{ + // Empty inputs + {"", nil}, + {" ", nil}, + {"\t\n ", nil}, + + // Numbers + {`0 123`, []syntax.Token{syntax.TNumber, syntax.TNumber}}, + {`0.32 3.14`, []syntax.Token{syntax.TNumber, syntax.TNumber}}, + + // Tags + {`foo foo.bar`, []syntax.Token{syntax.TTag, syntax.TTag}}, + {`foo foo-foo.bar`, []syntax.Token{syntax.TTag, syntax.TTag}}, + {`foo foo._bar_bar`, []syntax.Token{syntax.TTag, syntax.TTag}}, + + // Strings (values) + {` '' x 'x' 'x y'`, []syntax.Token{syntax.TString, syntax.TTag, syntax.TString, syntax.TString}}, + {` 'you are not your job' `, []syntax.Token{syntax.TString}}, + + // Comparison operators + {`< <= = > >=`, []syntax.Token{ + syntax.TLt, syntax.TLeq, syntax.TEq, syntax.TGt, syntax.TGeq, + }}, + + // Mixed values of various kinds. + {`x AND y`, []syntax.Token{syntax.TTag, syntax.TAnd, syntax.TTag}}, + {`x.y CONTAINS 'z'`, []syntax.Token{syntax.TTag, syntax.TContains, syntax.TString}}, + {`foo EXISTS`, []syntax.Token{syntax.TTag, syntax.TExists}}, + {`and AND`, []syntax.Token{syntax.TTag, syntax.TAnd}}, + + // Timestamp + {`TIME 2021-11-23T15:16:17Z`, []syntax.Token{syntax.TTime}}, + + // Datestamp + {`DATE 2021-11-23`, []syntax.Token{syntax.TDate}}, + } + + for _, test := range tests { + s := syntax.NewScanner(strings.NewReader(test.input)) + var got []syntax.Token + for s.Next() == nil { + got = append(got, s.Token()) + } + if err := s.Err(); err != io.EOF { + t.Errorf("Next: unexpected error: %v", err) + } + + if !reflect.DeepEqual(got, test.want) { + t.Logf("Scanner input: %q", test.input) + t.Errorf("Wrong tokens:\ngot: %+v\nwant: %+v", got, test.want) + } + } +} + +func TestScannerErrors(t *testing.T) { + tests := []struct { + input string + }{ + {`'incomplete string`}, + {`-23`}, + {`&`}, + {`DATE xyz-pdq`}, + {`DATE xyzp-dq-zv`}, + {`DATE 0000-00-00`}, + {`DATE 0000-00-000`}, + {`DATE 2021-01-99`}, + {`TIME 2021-01-01T34:56:78Z`}, + {`TIME 2021-01-99T14:56:08Z`}, + {`TIME 2021-01-99T34:56:08`}, + {`TIME 2021-01-99T34:56:11+3`}, + } + for _, test := range tests { + s := syntax.NewScanner(strings.NewReader(test.input)) + if err := s.Next(); err == nil { + t.Errorf("Next: got %v (%#q), want error", s.Token(), s.Text()) + } + } +} + +// These parser tests were copied from the original implementation of the query +// parser, and are preserved here as a compatibility check. +func TestParseValid(t *testing.T) { + tests := []struct { + input string + valid bool + }{ + {"tm.events.type='NewBlock'", true}, + {"tm.events.type = 'NewBlock'", true}, + {"tm.events.name = ''", true}, + {"tm.events.type='TIME'", true}, + {"tm.events.type='DATE'", true}, + {"tm.events.type='='", true}, + {"tm.events.type='TIME", false}, + {"tm.events.type=TIME'", false}, + {"tm.events.type==", false}, + {"tm.events.type=NewBlock", false}, + {">==", false}, + {"tm.events.type 'NewBlock' =", false}, + {"tm.events.type>'NewBlock'", false}, + {"", false}, + {"=", false}, + {"='NewBlock'", false}, + {"tm.events.type=", false}, + + {"tm.events.typeNewBlock", false}, + {"tm.events.type'NewBlock'", false}, + {"'NewBlock'", false}, + {"NewBlock", false}, + {"", false}, + + {"tm.events.type='NewBlock' AND abci.account.name='Igor'", true}, + {"tm.events.type='NewBlock' AND", false}, + {"tm.events.type='NewBlock' AN", false}, + {"tm.events.type='NewBlock' AN tm.events.type='NewBlockHeader'", false}, + {"AND tm.events.type='NewBlock' ", false}, + + {"abci.account.name CONTAINS 'Igor'", true}, + + {"tx.date > DATE 2013-05-03", true}, + {"tx.date < DATE 2013-05-03", true}, + {"tx.date <= DATE 2013-05-03", true}, + {"tx.date >= DATE 2013-05-03", true}, + {"tx.date >= DAT 2013-05-03", false}, + {"tx.date <= DATE2013-05-03", false}, + {"tx.date <= DATE -05-03", false}, + {"tx.date >= DATE 20130503", false}, + {"tx.date >= DATE 2013+01-03", false}, + // incorrect year, month, day + {"tx.date >= DATE 0013-01-03", false}, + {"tx.date >= DATE 2013-31-03", false}, + {"tx.date >= DATE 2013-01-83", false}, + + {"tx.date > TIME 2013-05-03T14:45:00+07:00", true}, + {"tx.date < TIME 2013-05-03T14:45:00-02:00", true}, + {"tx.date <= TIME 2013-05-03T14:45:00Z", true}, + {"tx.date >= TIME 2013-05-03T14:45:00Z", true}, + {"tx.date >= TIME2013-05-03T14:45:00Z", false}, + {"tx.date = IME 2013-05-03T14:45:00Z", false}, + {"tx.date = TIME 2013-05-:45:00Z", false}, + {"tx.date >= TIME 2013-05-03T14:45:00", false}, + {"tx.date >= TIME 0013-00-00T14:45:00Z", false}, + {"tx.date >= TIME 2013+05=03T14:45:00Z", false}, + + {"account.balance=100", true}, + {"account.balance >= 200", true}, + {"account.balance >= -300", false}, + {"account.balance >>= 400", false}, + {"account.balance=33.22.1", false}, + + {"slashing.amount EXISTS", true}, + {"slashing.amount EXISTS AND account.balance=100", true}, + {"account.balance=100 AND slashing.amount EXISTS", true}, + {"slashing EXISTS", true}, + + {"hash='136E18F7E4C348B780CF873A0BF43922E5BAFA63'", true}, + {"hash=136E18F7E4C348B780CF873A0BF43922E5BAFA63", false}, + + {"cosm-wasm.transfer_amount=100", true}, + } + + for _, test := range tests { + q, err := syntax.Parse(test.input) + if test.valid != (err == nil) { + t.Errorf("Parse %#q: valid %v got err=%v", test.input, test.valid, err) + } + + // For valid queries, check that the query round-trips. + if test.valid { + qstr := q.String() + r, err := syntax.Parse(qstr) + if err != nil { + t.Errorf("Reparse %#q failed: %v", qstr, err) + } + if rstr := r.String(); rstr != qstr { + t.Errorf("Reparse diff\nold: %#q\nnew: %#q", qstr, rstr) + } + } + } +} diff --git a/libs/pubsub/subscription.go b/libs/pubsub/subscription.go new file mode 100644 index 0000000..c0b604b --- /dev/null +++ b/libs/pubsub/subscription.go @@ -0,0 +1,91 @@ +package pubsub + +import ( + "errors" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +var ( + // ErrUnsubscribed is returned by Err when a client unsubscribes. + ErrUnsubscribed = errors.New("client unsubscribed") + + // ErrOutOfCapacity is returned by Err when a client is not pulling messages + // fast enough. Note the client's subscription will be terminated. + ErrOutOfCapacity = errors.New("internal subscription event buffer is out of capacity") +) + +// A Subscription represents a client subscription for a particular query and +// consists of three things: +// 1) channel onto which messages and events are published +// 2) channel which is closed if a client is too slow or choose to unsubscribe +// 3) err indicating the reason for (2) +type Subscription struct { + out chan Message + + canceled chan struct{} + mtx cmtsync.RWMutex + err error +} + +// NewSubscription returns a new subscription with the given outCapacity. +func NewSubscription(outCapacity int) *Subscription { + return &Subscription{ + out: make(chan Message, outCapacity), + canceled: make(chan struct{}), + } +} + +// Out returns a channel onto which messages and events are published. +// Unsubscribe/UnsubscribeAll does not close the channel to avoid clients from +// receiving a nil message. +func (s *Subscription) Out() <-chan Message { + return s.out +} + +// Canceled returns a channel that's closed when the subscription is +// terminated and supposed to be used in a select statement. +func (s *Subscription) Canceled() <-chan struct{} { + return s.canceled +} + +// Err returns nil if the channel returned is not yet closed. +// If the channel is closed, Err returns a non-nil error explaining why: +// - ErrUnsubscribed if the subscriber choose to unsubscribe, +// - ErrOutOfCapacity if the subscriber is not pulling messages fast enough +// and the channel returned by Out became full, +// +// After Err returns a non-nil error, successive calls to Err return the same +// error. +func (s *Subscription) Err() error { + s.mtx.RLock() + defer s.mtx.RUnlock() + return s.err +} + +func (s *Subscription) cancel(err error) { + s.mtx.Lock() + s.err = err + s.mtx.Unlock() + close(s.canceled) +} + +// Message glues data and events together. +type Message struct { + data interface{} + events map[string][]string +} + +func NewMessage(data interface{}, events map[string][]string) Message { + return Message{data, events} +} + +// Data returns an original data published. +func (msg Message) Data() interface{} { + return msg.data +} + +// Events returns events, which matched the client's query. +func (msg Message) Events() map[string][]string { + return msg.events +} diff --git a/libs/rand/random.go b/libs/rand/random.go new file mode 100644 index 0000000..a764d0e --- /dev/null +++ b/libs/rand/random.go @@ -0,0 +1,312 @@ +package rand + +import ( + crand "crypto/rand" + mrand "math/rand" + "time" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +const ( + strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters +) + +// Rand is a prng, that is seeded with OS randomness. +// The OS randomness is obtained from crypto/rand, however none of the provided +// methods are suitable for cryptographic usage. +// They all utilize math/rand's prng internally. +// +// All of the methods here are suitable for concurrent use. +// This is achieved by using a mutex lock on all of the provided methods. +type Rand struct { + cmtsync.Mutex + rand *mrand.Rand +} + +var grand *Rand + +func init() { + grand = NewRand() + grand.init() +} + +func NewRand() *Rand { + rand := &Rand{} + rand.init() + return rand +} + +func (r *Rand) init() { + bz := cRandBytes(8) + var seed uint64 + for i := 0; i < 8; i++ { + seed |= uint64(bz[i]) + seed <<= 8 + } + r.reset(int64(seed)) +} + +func (r *Rand) reset(seed int64) { + // G404: Use of weak random number generator (math/rand instead of crypto/rand) + //nolint:gosec + r.rand = mrand.New(mrand.NewSource(seed)) +} + +//---------------------------------------- +// Global functions + +func Seed(seed int64) { + grand.Seed(seed) +} + +func Str(length int) string { + return grand.Str(length) +} + +func Uint16() uint16 { + return grand.Uint16() +} + +func Uint32() uint32 { + return grand.Uint32() +} + +func Uint64() uint64 { + return grand.Uint64() +} + +func Uint() uint { + return grand.Uint() +} + +func Int16() int16 { + return grand.Int16() +} + +func Int32() int32 { + return grand.Int32() +} + +func Int64() int64 { + return grand.Int64() +} + +func Int() int { + return grand.Int() +} + +func Int31() int32 { + return grand.Int31() +} + +func Int31n(n int32) int32 { + return grand.Int31n(n) +} + +func Int63() int64 { + return grand.Int63() +} + +func Int63n(n int64) int64 { + return grand.Int63n(n) +} + +func Bool() bool { + return grand.Bool() +} + +func Float32() float32 { + return grand.Float32() +} + +func Float64() float64 { + return grand.Float64() +} + +func Time() time.Time { + return grand.Time() +} + +func Bytes(n int) []byte { + return grand.Bytes(n) +} + +func Intn(n int) int { + return grand.Intn(n) +} + +func Perm(n int) []int { + return grand.Perm(n) +} + +//---------------------------------------- +// Rand methods + +func (r *Rand) Seed(seed int64) { + r.Lock() + r.reset(seed) + r.Unlock() +} + +// Str constructs a random alphanumeric string of given length. +func (r *Rand) Str(length int) string { + if length <= 0 { + return "" + } + + chars := []byte{} +MAIN_LOOP: + for { + val := r.Int63() + for i := 0; i < 10; i++ { + v := int(val & 0x3f) // rightmost 6 bits + if v >= 62 { // only 62 characters in strChars + val >>= 6 + continue + } + chars = append(chars, strChars[v]) + if len(chars) == length { + break MAIN_LOOP + } + val >>= 6 + } + } + + return string(chars) +} + +func (r *Rand) Uint16() uint16 { + return uint16(r.Uint32() & (1<<16 - 1)) +} + +func (r *Rand) Uint32() uint32 { + r.Lock() + u32 := r.rand.Uint32() + r.Unlock() + return u32 +} + +func (r *Rand) Uint64() uint64 { + return uint64(r.Uint32())<<32 + uint64(r.Uint32()) +} + +func (r *Rand) Uint() uint { + r.Lock() + i := r.rand.Int() + r.Unlock() + return uint(i) +} + +func (r *Rand) Int16() int16 { + return int16(r.Uint32() & (1<<16 - 1)) +} + +func (r *Rand) Int32() int32 { + return int32(r.Uint32()) +} + +func (r *Rand) Int64() int64 { + return int64(r.Uint64()) +} + +func (r *Rand) Int() int { + r.Lock() + i := r.rand.Int() + r.Unlock() + return i +} + +func (r *Rand) Int31() int32 { + r.Lock() + i31 := r.rand.Int31() + r.Unlock() + return i31 +} + +func (r *Rand) Int31n(n int32) int32 { + r.Lock() + i31n := r.rand.Int31n(n) + r.Unlock() + return i31n +} + +func (r *Rand) Int63() int64 { + r.Lock() + i63 := r.rand.Int63() + r.Unlock() + return i63 +} + +func (r *Rand) Int63n(n int64) int64 { + r.Lock() + i63n := r.rand.Int63n(n) + r.Unlock() + return i63n +} + +func (r *Rand) Float32() float32 { + r.Lock() + f32 := r.rand.Float32() + r.Unlock() + return f32 +} + +func (r *Rand) Float64() float64 { + r.Lock() + f64 := r.rand.Float64() + r.Unlock() + return f64 +} + +func (r *Rand) Time() time.Time { + return time.Unix(int64(r.Uint64()), 0) +} + +// Bytes returns n random bytes generated from the internal +// prng. +func (r *Rand) Bytes(n int) []byte { + // cRandBytes isn't guaranteed to be fast so instead + // use random bytes generated from the internal PRNG + bs := make([]byte, n) + for i := 0; i < len(bs); i++ { + bs[i] = byte(r.Int() & 0xFF) + } + return bs +} + +// Intn returns, as an int, a uniform pseudo-random number in the range [0, n). +// It panics if n <= 0. +func (r *Rand) Intn(n int) int { + r.Lock() + i := r.rand.Intn(n) + r.Unlock() + return i +} + +// Bool returns a uniformly random boolean +func (r *Rand) Bool() bool { + // See https://github.com/golang/go/issues/23804#issuecomment-365370418 + // for reasoning behind computing like this + return r.Int63()%2 == 0 +} + +// Perm returns a pseudo-random permutation of n integers in [0, n). +func (r *Rand) Perm(n int) []int { + r.Lock() + perm := r.rand.Perm(n) + r.Unlock() + return perm +} + +// NOTE: This relies on the os's random number generator. +// For real security, we should salt that with some seed. +// See github.com/cometbft/cometbft/crypto for a more secure reader. +func cRandBytes(numBytes int) []byte { + b := make([]byte, numBytes) + _, err := crand.Read(b) + if err != nil { + panic(err) + } + return b +} diff --git a/libs/rand/random_test.go b/libs/rand/random_test.go new file mode 100644 index 0000000..ea96fc5 --- /dev/null +++ b/libs/rand/random_test.go @@ -0,0 +1,115 @@ +package rand + +import ( + "bytes" + "encoding/json" + "fmt" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestRandStr(t *testing.T) { + l := 243 + s := Str(l) + assert.Equal(t, l, len(s)) +} + +func TestRandBytes(t *testing.T) { + l := 243 + b := Bytes(l) + assert.Equal(t, l, len(b)) +} + +func TestRandIntn(t *testing.T) { + n := 243 + for i := 0; i < 100; i++ { + x := Intn(n) + assert.True(t, x < n) + } +} + +// Test to make sure that we never call math.rand(). +// We do this by ensuring that outputs are deterministic. +func TestDeterminism(t *testing.T) { + var firstOutput string + + for i := 0; i < 100; i++ { + output := testThemAll() + if i == 0 { + firstOutput = output + } else if firstOutput != output { + t.Errorf("run #%d's output was different from first run.\nfirst: %v\nlast: %v", + i, firstOutput, output) + } + } +} + +func testThemAll() string { + // Such determinism. + grand.reset(1) + + // Use it. + out := new(bytes.Buffer) + perm := Perm(10) + blob, _ := json.Marshal(perm) + fmt.Fprintf(out, "perm: %s\n", blob) + fmt.Fprintf(out, "randInt: %d\n", Int()) + fmt.Fprintf(out, "randUint: %d\n", Uint()) + fmt.Fprintf(out, "randIntn: %d\n", Intn(97)) + fmt.Fprintf(out, "randInt31: %d\n", Int31()) + fmt.Fprintf(out, "randInt32: %d\n", Int32()) + fmt.Fprintf(out, "randInt63: %d\n", Int63()) + fmt.Fprintf(out, "randInt64: %d\n", Int64()) + fmt.Fprintf(out, "randUint32: %d\n", Uint32()) + fmt.Fprintf(out, "randUint64: %d\n", Uint64()) + return out.String() +} + +func TestRngConcurrencySafety(_ *testing.T) { + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + + _ = Uint64() + <-time.After(time.Millisecond * time.Duration(Intn(100))) + _ = Perm(3) + }() + } + wg.Wait() +} + +func BenchmarkRandBytes10B(b *testing.B) { + benchmarkRandBytes(b, 10) +} + +func BenchmarkRandBytes100B(b *testing.B) { + benchmarkRandBytes(b, 100) +} + +func BenchmarkRandBytes1KiB(b *testing.B) { + benchmarkRandBytes(b, 1024) +} + +func BenchmarkRandBytes10KiB(b *testing.B) { + benchmarkRandBytes(b, 10*1024) +} + +func BenchmarkRandBytes100KiB(b *testing.B) { + benchmarkRandBytes(b, 100*1024) +} + +func BenchmarkRandBytes1MiB(b *testing.B) { + benchmarkRandBytes(b, 1024*1024) +} + +func benchmarkRandBytes(b *testing.B, n int) { + for i := 0; i < b.N; i++ { + _ = Bytes(n) + } + b.ReportAllocs() +} diff --git a/libs/service/service.go b/libs/service/service.go new file mode 100644 index 0000000..9db6f2f --- /dev/null +++ b/libs/service/service.go @@ -0,0 +1,241 @@ +package service + +import ( + "errors" + "fmt" + "sync/atomic" + + "github.com/cometbft/cometbft/libs/log" +) + +var ( + // ErrAlreadyStarted is returned when somebody tries to start an already + // running service. + ErrAlreadyStarted = errors.New("already started") + // ErrAlreadyStopped is returned when somebody tries to stop an already + // stopped service (without resetting it). + ErrAlreadyStopped = errors.New("already stopped") + // ErrNotStarted is returned when somebody tries to stop a not running + // service. + ErrNotStarted = errors.New("not started") +) + +// Service defines a service that can be started, stopped, and reset. +type Service interface { + // Start the service. + // If it's already started or stopped, will return an error. + // If OnStart() returns an error, it's returned by Start() + Start() error + OnStart() error + + // Stop the service. + // If it's already stopped, will return an error. + // OnStop must never error. + Stop() error + OnStop() + + // Reset the service. + // Panics by default - must be overwritten to enable reset. + Reset() error + OnReset() error + + // Return true if the service is running + IsRunning() bool + + // Quit returns a channel, which is closed once service is stopped. + Quit() <-chan struct{} + + // String representation of the service + String() string + + // SetLogger sets a logger. + SetLogger(log.Logger) +} + +/* +Classical-inheritance-style service declarations. Services can be started, then +stopped, then optionally restarted. + +Users can override the OnStart/OnStop methods. In the absence of errors, these +methods are guaranteed to be called at most once. If OnStart returns an error, +service won't be marked as started, so the user can call Start again. + +A call to Reset will panic, unless OnReset is overwritten, allowing +OnStart/OnStop to be called again. + +The caller must ensure that Start and Stop are not called concurrently. + +It is ok to call Stop without calling Start first. + +Typical usage: + + type FooService struct { + BaseService + // private fields + } + + func NewFooService() *FooService { + fs := &FooService{ + // init + } + fs.BaseService = *NewBaseService(log, "FooService", fs) + return fs + } + + func (fs *FooService) OnStart() error { + fs.BaseService.OnStart() // Always call the overridden method. + // initialize private fields + // start subroutines, etc. + } + + func (fs *FooService) OnStop() error { + fs.BaseService.OnStop() // Always call the overridden method. + // close/destroy private fields + // stop subroutines, etc. + } +*/ +type BaseService struct { + Logger log.Logger + name string + started uint32 // atomic + stopped uint32 // atomic + quit chan struct{} + + // The "subclass" of BaseService + impl Service +} + +// NewBaseService creates a new BaseService. +func NewBaseService(logger log.Logger, name string, impl Service) *BaseService { + if logger == nil { + logger = log.NewNopLogger() + } + + return &BaseService{ + Logger: logger, + name: name, + quit: make(chan struct{}), + impl: impl, + } +} + +// SetLogger implements Service by setting a logger. +func (bs *BaseService) SetLogger(l log.Logger) { + bs.Logger = l +} + +// Start implements Service by calling OnStart (if defined). An error will be +// returned if the service is already running or stopped. Not to start the +// stopped service, you need to call Reset. +func (bs *BaseService) Start() error { + if atomic.CompareAndSwapUint32(&bs.started, 0, 1) { + if atomic.LoadUint32(&bs.stopped) == 1 { + bs.Logger.Error(fmt.Sprintf("Not starting %v service -- already stopped", bs.name), + "impl", bs.impl) + // revert flag + atomic.StoreUint32(&bs.started, 0) + return ErrAlreadyStopped + } + bs.Logger.Info("service start", + "msg", + log.NewLazySprintf("Starting %v service", bs.name), + "impl", + bs.impl.String()) + err := bs.impl.OnStart() + if err != nil { + // revert flag + atomic.StoreUint32(&bs.started, 0) + return err + } + return nil + } + bs.Logger.Debug("service start", + "msg", + log.NewLazySprintf("Not starting %v service -- already started", bs.name), + "impl", + bs.impl) + return ErrAlreadyStarted +} + +// OnStart implements Service by doing nothing. +// NOTE: Do not put anything in here, +// that way users don't need to call BaseService.OnStart() +func (bs *BaseService) OnStart() error { return nil } + +// Stop implements Service by calling OnStop (if defined) and closing quit +// channel. An error will be returned if the service is already stopped. +func (bs *BaseService) Stop() error { + if atomic.CompareAndSwapUint32(&bs.stopped, 0, 1) { + if atomic.LoadUint32(&bs.started) == 0 { + bs.Logger.Error(fmt.Sprintf("Not stopping %v service -- has not been started yet", bs.name), + "impl", bs.impl) + // revert flag + atomic.StoreUint32(&bs.stopped, 0) + return ErrNotStarted + } + bs.Logger.Info("service stop", + "msg", + log.NewLazySprintf("Stopping %v service", bs.name), + "impl", + bs.impl) + bs.impl.OnStop() + close(bs.quit) + return nil + } + bs.Logger.Debug("service stop", + "msg", + log.NewLazySprintf("Stopping %v service (already stopped)", bs.name), + "impl", + bs.impl) + return ErrAlreadyStopped +} + +// OnStop implements Service by doing nothing. +// NOTE: Do not put anything in here, +// that way users don't need to call BaseService.OnStop() +func (bs *BaseService) OnStop() {} + +// Reset implements Service by calling OnReset callback (if defined). An error +// will be returned if the service is running. +func (bs *BaseService) Reset() error { + if !atomic.CompareAndSwapUint32(&bs.stopped, 1, 0) { + bs.Logger.Debug("service reset", + "msg", + log.NewLazySprintf("Can't reset %v service. Not stopped", bs.name), + "impl", + bs.impl) + return fmt.Errorf("can't reset running %s", bs.name) + } + + // whether or not we've started, we can reset + atomic.CompareAndSwapUint32(&bs.started, 1, 0) + + bs.quit = make(chan struct{}) + return bs.impl.OnReset() +} + +// OnReset implements Service by panicking. +func (bs *BaseService) OnReset() error { + panic("The service cannot be reset") +} + +// IsRunning implements Service by returning true or false depending on the +// service's state. +func (bs *BaseService) IsRunning() bool { + return atomic.LoadUint32(&bs.started) == 1 && atomic.LoadUint32(&bs.stopped) == 0 +} + +// Wait blocks until the service is stopped. +func (bs *BaseService) Wait() { + <-bs.quit +} + +// String implements Service by returning a string representation of the service. +func (bs *BaseService) String() string { + return bs.name +} + +// Quit Implements Service by returning a quit channel. +func (bs *BaseService) Quit() <-chan struct{} { + return bs.quit +} diff --git a/libs/service/service_test.go b/libs/service/service_test.go new file mode 100644 index 0000000..504a81a --- /dev/null +++ b/libs/service/service_test.go @@ -0,0 +1,57 @@ +package service + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type testService struct { + BaseService +} + +func (testService) OnReset() error { + return nil +} + +func TestBaseServiceWait(t *testing.T) { + ts := &testService{} + ts.BaseService = *NewBaseService(nil, "TestService", ts) + err := ts.Start() + require.NoError(t, err) + + waitFinished := make(chan struct{}) + go func() { + ts.Wait() + waitFinished <- struct{}{} + }() + + go ts.Stop() //nolint:errcheck // ignore for tests + + select { + case <-waitFinished: + // all good + case <-time.After(100 * time.Millisecond): + t.Fatal("expected Wait() to finish within 100 ms.") + } +} + +func TestBaseServiceReset(t *testing.T) { + ts := &testService{} + ts.BaseService = *NewBaseService(nil, "TestService", ts) + err := ts.Start() + require.NoError(t, err) + + err = ts.Reset() + require.Error(t, err, "expected cant reset service error") + + err = ts.Stop() + require.NoError(t, err) + + err = ts.Reset() + require.NoError(t, err) + + err = ts.Start() + require.NoError(t, err) +} diff --git a/libs/strings/string.go b/libs/strings/string.go new file mode 100644 index 0000000..c875b5c --- /dev/null +++ b/libs/strings/string.go @@ -0,0 +1,96 @@ +package strings + +import ( + "fmt" + "strings" +) + +// StringInSlice returns true if a is found the list. +func StringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} + +// SplitAndTrim slices s into all subslices separated by sep and returns a +// slice of the string s with all leading and trailing Unicode code points +// contained in cutset removed. If sep is empty, SplitAndTrim splits after each +// UTF-8 sequence. First part is equivalent to strings.SplitN with a count of +// -1. +func SplitAndTrim(s, sep, cutset string) []string { + if s == "" { + return []string{} + } + + spl := strings.Split(s, sep) + for i := 0; i < len(spl); i++ { + spl[i] = strings.Trim(spl[i], cutset) + } + return spl +} + +// SplitAndTrimEmpty slices s into all subslices separated by sep and returns a +// slice of the string s with all leading and trailing Unicode code points +// contained in cutset removed. If sep is empty, SplitAndTrim splits after each +// UTF-8 sequence. First part is equivalent to strings.SplitN with a count of +// -1. also filter out empty strings, only return non-empty strings. +func SplitAndTrimEmpty(s, sep, cutset string) []string { + if s == "" { + return []string{} + } + + spl := strings.Split(s, sep) + nonEmptyStrings := make([]string, 0, len(spl)) + for i := 0; i < len(spl); i++ { + element := strings.Trim(spl[i], cutset) + if element != "" { + nonEmptyStrings = append(nonEmptyStrings, element) + } + } + return nonEmptyStrings +} + +// Returns true if s is a non-empty printable non-tab ascii character. +func IsASCIIText(s string) bool { + if len(s) == 0 { + return false + } + for _, b := range []byte(s) { + if b < 32 || b > 126 { + return false + } + } + return true +} + +// NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics. +func ASCIITrim(s string) string { + r := make([]byte, 0, len(s)) + for _, b := range []byte(s) { + switch { + case b == 32: + continue // skip space + case 32 < b && b <= 126: + r = append(r, b) + default: + panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b)) + } + } + return string(r) +} + +// StringSliceEqual checks if string slices a and b are equal +func StringSliceEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := 0; i < len(a); i++ { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/libs/strings/string_test.go b/libs/strings/string_test.go new file mode 100644 index 0000000..f0e57b1 --- /dev/null +++ b/libs/strings/string_test.go @@ -0,0 +1,58 @@ +package strings + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/stretchr/testify/assert" +) + +func TestStringInSlice(t *testing.T) { + assert.True(t, StringInSlice("a", []string{"a", "b", "c"})) + assert.False(t, StringInSlice("d", []string{"a", "b", "c"})) + assert.True(t, StringInSlice("", []string{""})) + assert.False(t, StringInSlice("", []string{})) +} + +func TestIsASCIIText(t *testing.T) { + notASCIIText := []string{ + "", "\xC2", "\xC2\xA2", "\xFF", "\x80", "\xF0", "\n", "\t", + } + for _, v := range notASCIIText { + assert.False(t, IsASCIIText(v), "%q is not ascii-text", v) + } + asciiText := []string{ + " ", ".", "x", "$", "_", "abcdefg;", "-", "0x00", "0", "123", + } + for _, v := range asciiText { + assert.True(t, IsASCIIText(v), "%q is ascii-text", v) + } +} + +func TestASCIITrim(t *testing.T) { + assert.Equal(t, ASCIITrim(" "), "") + assert.Equal(t, ASCIITrim(" a"), "a") + assert.Equal(t, ASCIITrim("a "), "a") + assert.Equal(t, ASCIITrim(" a "), "a") + assert.Panics(t, func() { ASCIITrim("\xC2\xA2") }) +} + +func TestStringSliceEqual(t *testing.T) { + tests := []struct { + a []string + b []string + want bool + }{ + {[]string{"hello", "world"}, []string{"hello", "world"}, true}, + {[]string{"test"}, []string{"test"}, true}, + {[]string{"test1"}, []string{"test2"}, false}, + {[]string{"hello", "world."}, []string{"hello", "world!"}, false}, + {[]string{"only 1 word"}, []string{"two", "words!"}, false}, + {[]string{"two", "words!"}, []string{"only 1 word"}, false}, + } + for i, tt := range tests { + require.Equal(t, tt.want, StringSliceEqual(tt.a, tt.b), + "StringSliceEqual failed on test %d", i) + } +} diff --git a/libs/sync/deadlock.go b/libs/sync/deadlock.go new file mode 100644 index 0000000..89c7e17 --- /dev/null +++ b/libs/sync/deadlock.go @@ -0,0 +1,18 @@ +//go:build deadlock +// +build deadlock + +package sync + +import ( + deadlock "github.com/sasha-s/go-deadlock" +) + +// A Mutex is a mutual exclusion lock. +type Mutex struct { + deadlock.Mutex +} + +// An RWMutex is a reader/writer mutual exclusion lock. +type RWMutex struct { + deadlock.RWMutex +} diff --git a/libs/sync/sync.go b/libs/sync/sync.go new file mode 100644 index 0000000..9c4e689 --- /dev/null +++ b/libs/sync/sync.go @@ -0,0 +1,16 @@ +//go:build !deadlock +// +build !deadlock + +package sync + +import "sync" + +// A Mutex is a mutual exclusion lock. +type Mutex struct { + sync.Mutex +} + +// An RWMutex is a reader/writer mutual exclusion lock. +type RWMutex struct { + sync.RWMutex +} diff --git a/libs/tempfile/tempfile.go b/libs/tempfile/tempfile.go new file mode 100644 index 0000000..1d61c7a --- /dev/null +++ b/libs/tempfile/tempfile.go @@ -0,0 +1,129 @@ +package tempfile + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +const ( + atomicWriteFilePrefix = "write-file-atomic-" + // Maximum number of atomic write file conflicts before we start reseeding + // (reduced from golang's default 10 due to using an increased randomness space) + atomicWriteFileMaxNumConflicts = 5 + // Maximum number of attempts to make at writing the write file before giving up + // (reduced from golang's default 10000 due to using an increased randomness space) + atomicWriteFileMaxNumWriteAttempts = 1000 + // LCG constants from Donald Knuth MMIX + // This LCG's has a period equal to 2**64 + lcgA = 6364136223846793005 + lcgC = 1442695040888963407 + // Create in case it doesn't exist and force kernel + // flush, which still leaves the potential of lingering disk cache. + // Never overwrites files + atomicWriteFileFlag = os.O_WRONLY | os.O_CREATE | os.O_SYNC | os.O_TRUNC | os.O_EXCL +) + +var ( + atomicWriteFileRand uint64 + atomicWriteFileRandMu cmtsync.Mutex +) + +func writeFileRandReseed() uint64 { + // Scale the PID, to minimize the chance that two processes seeded at similar times + // don't get the same seed. Note that PID typically ranges in [0, 2**15), but can be + // up to 2**22 under certain configurations. We left bit-shift the PID by 20, so that + // a PID difference of one corresponds to a time difference of 2048 seconds. + // The important thing here is that now for a seed conflict, they would both have to be on + // the correct nanosecond offset, and second-based offset, which is much less likely than + // just a conflict with the correct nanosecond offset. + return uint64(time.Now().UnixNano() + int64(os.Getpid()<<20)) +} + +// Use a fast thread safe LCG for atomic write file names. +// Returns a string corresponding to a 64 bit int. +// If it was a negative int, the leading number is a 0. +func randWriteFileSuffix() string { + atomicWriteFileRandMu.Lock() + r := atomicWriteFileRand + if r == 0 { + r = writeFileRandReseed() + } + + // Update randomness according to lcg + r = r*lcgA + lcgC + + atomicWriteFileRand = r + atomicWriteFileRandMu.Unlock() + // Can have a negative name, replace this in the following + suffix := strconv.Itoa(int(r)) + if string(suffix[0]) == "-" { + // Replace first "-" with "0". This is purely for UI clarity, + // as otherwhise there would be two `-` in a row. + suffix = strings.Replace(suffix, "-", "0", 1) + } + return suffix +} + +// WriteFileAtomic creates a temporary file with data and provided perm and +// swaps it atomically with filename if successful. +func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error) { + // This implementation is inspired by the golang stdlibs method of creating + // tempfiles. Notable differences are that we use different flags, a 64 bit LCG + // and handle negatives differently. + // The core reason we can't use golang's TempFile is that we must write + // to the file synchronously, as we need this to persist to disk. + // We also open it in write-only mode, to avoid concerns that arise with read. + var ( + dir = filepath.Dir(filename) + f *os.File + ) + + nconflict := 0 + // Limit the number of attempts to create a file. Something is seriously + // wrong if it didn't get created after 1000 attempts, and we don't want + // an infinite loop + i := 0 + for ; i < atomicWriteFileMaxNumWriteAttempts; i++ { + name := filepath.Join(dir, atomicWriteFilePrefix+randWriteFileSuffix()) + f, err = os.OpenFile(name, atomicWriteFileFlag, perm) + // If the file already exists, try a new file + if os.IsExist(err) { + // If the files exists too many times, start reseeding as we've + // likely hit another instances seed. + if nconflict++; nconflict > atomicWriteFileMaxNumConflicts { + atomicWriteFileRandMu.Lock() + atomicWriteFileRand = writeFileRandReseed() + atomicWriteFileRandMu.Unlock() + } + continue + } else if err != nil { + return err + } + break + } + if i == atomicWriteFileMaxNumWriteAttempts { + return fmt.Errorf("could not create atomic write file after %d attempts", i) + } + + // Clean up in any case. Defer stacking order is last-in-first-out. + defer os.Remove(f.Name()) + defer f.Close() + + if n, err := f.Write(data); err != nil { + return err + } else if n < len(data) { + return io.ErrShortWrite + } + // Close the file before renaming it, otherwise it will cause "The process + // cannot access the file because it is being used by another process." on windows. + f.Close() + + return os.Rename(f.Name(), filename) +} diff --git a/libs/tempfile/tempfile_test.go b/libs/tempfile/tempfile_test.go new file mode 100644 index 0000000..87124bd --- /dev/null +++ b/libs/tempfile/tempfile_test.go @@ -0,0 +1,143 @@ +package tempfile + +// Need access to internal variables, so can't use _test package + +import ( + "bytes" + "fmt" + "os" + testing "testing" + + "github.com/stretchr/testify/require" + + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func TestWriteFileAtomic(t *testing.T) { + var ( + data = []byte(cmtrand.Str(cmtrand.Intn(2048))) + old = cmtrand.Bytes(cmtrand.Intn(2048)) + perm os.FileMode = 0600 + ) + + f, err := os.CreateTemp("/tmp", "write-atomic-test-") + if err != nil { + t.Fatal(err) + } + defer os.Remove(f.Name()) + + if err = os.WriteFile(f.Name(), old, 0600); err != nil { + t.Fatal(err) + } + + if err = WriteFileAtomic(f.Name(), data, perm); err != nil { + t.Fatal(err) + } + + rData, err := os.ReadFile(f.Name()) + if err != nil { + t.Fatal(err) + } + + if !bytes.Equal(data, rData) { + t.Fatalf("data mismatch: %v != %v", data, rData) + } + + stat, err := os.Stat(f.Name()) + if err != nil { + t.Fatal(err) + } + + if have, want := stat.Mode().Perm(), perm; have != want { + t.Errorf("have %v, want %v", have, want) + } +} + +// This tests atomic write file when there is a single duplicate file. +// Expected behavior is for a new file to be created, and the original write file to be unaltered. +func TestWriteFileAtomicDuplicateFile(t *testing.T) { + var ( + defaultSeed uint64 = 1 + testString = "This is a glorious test string" + expectedString = "Did the test file's string appear here?" + + fileToWrite = "/tmp/TestWriteFileAtomicDuplicateFile-test.txt" + ) + // Create a file at the seed, and reset the seed. + atomicWriteFileRand = defaultSeed + firstFileRand := randWriteFileSuffix() + atomicWriteFileRand = defaultSeed + fname := "/tmp/" + atomicWriteFilePrefix + firstFileRand + f, err := os.OpenFile(fname, atomicWriteFileFlag, 0777) + defer os.Remove(fname) + // Defer here, in case there is a panic in WriteFileAtomic. + defer os.Remove(fileToWrite) + + require.NoError(t, err) + _, err = f.WriteString(testString) + require.NoError(t, err) + err = WriteFileAtomic(fileToWrite, []byte(expectedString), 0777) + require.NoError(t, err) + // Check that the first atomic file was untouched + firstAtomicFileBytes, err := os.ReadFile(fname) + require.NoError(t, err, "Error reading first atomic file") + require.Equal(t, []byte(testString), firstAtomicFileBytes, "First atomic file was overwritten") + // Check that the resultant file is correct + resultantFileBytes, err := os.ReadFile(fileToWrite) + require.NoError(t, err, "Error reading resultant file") + require.Equal(t, []byte(expectedString), resultantFileBytes, "Written file had incorrect bytes") + + // Check that the intermediate write file was deleted + // Get the second write files' randomness + atomicWriteFileRand = defaultSeed + _ = randWriteFileSuffix() + secondFileRand := randWriteFileSuffix() + _, err = os.Stat("/tmp/" + atomicWriteFilePrefix + secondFileRand) + require.True(t, os.IsNotExist(err), "Intermittent atomic write file not deleted") +} + +// This tests atomic write file when there are many duplicate files. +// Expected behavior is for a new file to be created under a completely new seed, +// and the original write files to be unaltered. +func TestWriteFileAtomicManyDuplicates(t *testing.T) { + var ( + defaultSeed uint64 = 2 + testString = "This is a glorious test string, from file %d" + expectedString = "Did any of the test file's string appear here?" + + fileToWrite = "/tmp/TestWriteFileAtomicDuplicateFile-test.txt" + ) + // Initialize all of the atomic write files + atomicWriteFileRand = defaultSeed + for i := 0; i < atomicWriteFileMaxNumConflicts+2; i++ { + fileRand := randWriteFileSuffix() + fname := "/tmp/" + atomicWriteFilePrefix + fileRand + f, err := os.OpenFile(fname, atomicWriteFileFlag, 0777) + require.Nil(t, err) + _, err = fmt.Fprintf(f, testString, i) + require.NoError(t, err) + defer os.Remove(fname) + } + + atomicWriteFileRand = defaultSeed + // Defer here, in case there is a panic in WriteFileAtomic. + defer os.Remove(fileToWrite) + + err := WriteFileAtomic(fileToWrite, []byte(expectedString), 0777) + require.NoError(t, err) + // Check that all intermittent atomic file were untouched + atomicWriteFileRand = defaultSeed + for i := 0; i < atomicWriteFileMaxNumConflicts+2; i++ { + fileRand := randWriteFileSuffix() + fname := "/tmp/" + atomicWriteFilePrefix + fileRand + firstAtomicFileBytes, err := os.ReadFile(fname) + require.Nil(t, err, "Error reading first atomic file") + require.Equal(t, []byte(fmt.Sprintf(testString, i)), firstAtomicFileBytes, + "atomic write file %d was overwritten", i) + } + + // Check that the resultant file is correct + resultantFileBytes, err := os.ReadFile(fileToWrite) + require.Nil(t, err, "Error reading resultant file") + require.Equal(t, []byte(expectedString), resultantFileBytes, "Written file had incorrect bytes") +} diff --git a/libs/test/mutate.go b/libs/test/mutate.go new file mode 100644 index 0000000..d36ce04 --- /dev/null +++ b/libs/test/mutate.go @@ -0,0 +1,28 @@ +package test + +import ( + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +// Contract: !bytes.Equal(input, output) && len(input) >= len(output) +func MutateByteSlice(bytez []byte) []byte { + // If bytez is empty, panic + if len(bytez) == 0 { + panic("Cannot mutate an empty bytez") + } + + // Copy bytez + mBytez := make([]byte, len(bytez)) + copy(mBytez, bytez) + bytez = mBytez + + // Try a random mutation + switch cmtrand.Int() % 2 { + case 0: // Mutate a single byte + bytez[cmtrand.Int()%len(bytez)] += byte(cmtrand.Int()%255 + 1) + case 1: // Remove an arbitrary byte + pos := cmtrand.Int() % len(bytez) + bytez = append(bytez[:pos], bytez[pos+1:]...) + } + return bytez +} diff --git a/libs/timer/throttle_timer.go b/libs/timer/throttle_timer.go new file mode 100644 index 0000000..60672c5 --- /dev/null +++ b/libs/timer/throttle_timer.go @@ -0,0 +1,76 @@ +package timer + +import ( + "time" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +/* +ThrottleTimer fires an event at most "dur" after each .Set() call. +If a short burst of .Set() calls happens, ThrottleTimer fires once. +If a long continuous burst of .Set() calls happens, ThrottleTimer fires +at most once every "dur". +*/ +type ThrottleTimer struct { + Name string + Ch chan struct{} + quit chan struct{} + dur time.Duration + + mtx cmtsync.Mutex + timer *time.Timer + isSet bool +} + +func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer { + var ch = make(chan struct{}) + var quit = make(chan struct{}) + var t = &ThrottleTimer{Name: name, Ch: ch, dur: dur, quit: quit} + t.mtx.Lock() + t.timer = time.AfterFunc(dur, t.fireRoutine) + t.mtx.Unlock() + t.timer.Stop() + return t +} + +func (t *ThrottleTimer) fireRoutine() { + t.mtx.Lock() + defer t.mtx.Unlock() + select { + case t.Ch <- struct{}{}: + t.isSet = false + case <-t.quit: + // do nothing + default: + t.timer.Reset(t.dur) + } +} + +func (t *ThrottleTimer) Set() { + t.mtx.Lock() + defer t.mtx.Unlock() + if !t.isSet { + t.isSet = true + t.timer.Reset(t.dur) + } +} + +func (t *ThrottleTimer) Unset() { + t.mtx.Lock() + defer t.mtx.Unlock() + t.isSet = false + t.timer.Stop() +} + +// For ease of .Stop()'ing services before .Start()'ing them, +// we ignore .Stop()'s on nil ThrottleTimers +func (t *ThrottleTimer) Stop() bool { + if t == nil { + return false + } + close(t.quit) + t.mtx.Lock() + defer t.mtx.Unlock() + return t.timer.Stop() +} diff --git a/libs/timer/throttle_timer_test.go b/libs/timer/throttle_timer_test.go new file mode 100644 index 0000000..f2c9338 --- /dev/null +++ b/libs/timer/throttle_timer_test.go @@ -0,0 +1,82 @@ +package timer + +import ( + "testing" + "time" + + // make govet noshadow happy... + + asrt "github.com/stretchr/testify/assert" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +type thCounter struct { + input chan struct{} + mtx cmtsync.Mutex + count int +} + +func (c *thCounter) Increment() { + c.mtx.Lock() + c.count++ + c.mtx.Unlock() +} + +func (c *thCounter) Count() int { + c.mtx.Lock() + val := c.count + c.mtx.Unlock() + return val +} + +// Read should run in a go-routine and +// updates count by one every time a packet comes in +func (c *thCounter) Read() { + for range c.input { + c.Increment() + } +} + +func TestThrottle(test *testing.T) { + assert := asrt.New(test) + + ms := 50 + delay := time.Duration(ms) * time.Millisecond + longwait := time.Duration(2) * delay + t := NewThrottleTimer("foo", delay) + + // start at 0 + c := &thCounter{input: t.Ch} + assert.Equal(0, c.Count()) + go c.Read() + + // waiting does nothing + time.Sleep(longwait) + assert.Equal(0, c.Count()) + + // send one event adds one + t.Set() + time.Sleep(longwait) + assert.Equal(1, c.Count()) + + // send a burst adds one + for i := 0; i < 5; i++ { + t.Set() + } + time.Sleep(longwait) + assert.Equal(2, c.Count()) + + // send 12, over 2 delay sections, adds 3 or more. It + // is possible for more to be added if the overhead + // in executing the loop is large + short := time.Duration(ms/5) * time.Millisecond + for i := 0; i < 13; i++ { + t.Set() + time.Sleep(short) + } + time.Sleep(longwait) + assert.LessOrEqual(5, c.Count()) + + close(t.Ch) +} diff --git a/light/client.go b/light/client.go new file mode 100644 index 0000000..11e179f --- /dev/null +++ b/light/client.go @@ -0,0 +1,1190 @@ +package light + +import ( + "bytes" + "context" + "errors" + "fmt" + "sort" + "sync" + "time" + + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/light/provider" + "github.com/cometbft/cometbft/light/store" + "github.com/cometbft/cometbft/types" +) + +type mode byte + +const ( + sequential mode = iota + 1 + skipping + + defaultPruningSize = 1000 + defaultMaxRetryAttempts = 10 + // For verifySkipping, when using the cache of headers from the previous batch, + // they will always be at a height greater than 1/2 (normal verifySkipping) so to + // find something in between the range, 9/16 is used. + verifySkippingNumerator = 9 + verifySkippingDenominator = 16 + + // 10s should cover most of the clients. + // References: + // - http://vancouver-webpages.com/time/web.html + // - https://blog.codinghorror.com/keeping-time-on-the-pc/ + defaultMaxClockDrift = 10 * time.Second + + // 10s is sufficient for most networks. + defaultMaxBlockLag = 10 * time.Second +) + +// Option sets a parameter for the light client. +type Option func(*Client) + +// SequentialVerification option configures the light client to sequentially +// check the blocks (every block, in ascending height order). Note this is +// much slower than SkippingVerification, albeit more secure. +func SequentialVerification() Option { + return func(c *Client) { + c.verificationMode = sequential + } +} + +// SkippingVerification option configures the light client to skip blocks as +// long as {trustLevel} of the old validator set signed the new header. The +// verifySkipping algorithm from the specification is used for finding the minimal +// "trust path". +// +// trustLevel - fraction of the old validator set (in terms of voting power), +// which must sign the new header in order for us to trust it. NOTE this only +// applies to non-adjacent headers. For adjacent headers, sequential +// verification is used. +func SkippingVerification(trustLevel cmtmath.Fraction) Option { + return func(c *Client) { + c.verificationMode = skipping + c.trustLevel = trustLevel + } +} + +// PruningSize option sets the maximum amount of light blocks that the light +// client stores. When Prune() is run, all light blocks that are earlier than +// the h amount of light blocks will be removed from the store. +// Default: 1000. A pruning size of 0 will not prune the light client at all. +func PruningSize(h uint16) Option { + return func(c *Client) { + c.pruningSize = h + } +} + +// ConfirmationFunction option can be used to prompt to confirm an action. For +// example, remove newer headers if the light client is being reset with an +// older header. No confirmation is required by default! +func ConfirmationFunction(fn func(action string) bool) Option { + return func(c *Client) { + c.confirmationFn = fn + } +} + +// Logger option can be used to set a logger for the client. +func Logger(l log.Logger) Option { + return func(c *Client) { + c.logger = l + } +} + +// MaxRetryAttempts option can be used to set max attempts before replacing +// primary with a witness. +func MaxRetryAttempts(max uint16) Option { + return func(c *Client) { + c.maxRetryAttempts = max + } +} + +// MaxClockDrift defines how much new header's time can drift into +// the future relative to the light clients local time. Default: 10s. +func MaxClockDrift(d time.Duration) Option { + return func(c *Client) { + c.maxClockDrift = d + } +} + +// MaxBlockLag represents the maximum time difference between the realtime +// that a block is received and the timestamp of that block. +// One can approximate it to the maximum block production time +// +// As an example, say the light client received block B at a time +// 12:05 (this is the real time) and the time on the block +// was 12:00. Then the lag here is 5 minutes. +// Default: 10s +func MaxBlockLag(d time.Duration) Option { + return func(c *Client) { + c.maxBlockLag = d + } +} + +// Client represents a light client, connected to a single chain, which gets +// light blocks from a primary provider, verifies them either sequentially or by +// skipping some and stores them in a trusted store (usually, a local FS). +// +// Default verification: SkippingVerification(DefaultTrustLevel) +type Client struct { + chainID string + trustingPeriod time.Duration // see TrustOptions.Period + verificationMode mode + trustLevel cmtmath.Fraction + maxRetryAttempts uint16 // see MaxRetryAttempts option + maxClockDrift time.Duration + maxBlockLag time.Duration + + // Mutex for locking during changes of the light clients providers + providerMutex cmtsync.Mutex + // Primary provider of new headers. + primary provider.Provider + // Providers used to "witness" new headers. + witnesses []provider.Provider + + // Where trusted light blocks are stored. + trustedStore store.Store + // Highest trusted light block from the store (height=H). + latestTrustedBlock *types.LightBlock + + // See RemoveNoLongerTrustedHeadersPeriod option + pruningSize uint16 + // See ConfirmationFunction option + confirmationFn func(action string) bool + + quit chan struct{} + + logger log.Logger +} + +// NewClient returns a new light client. It returns an error if it fails to +// obtain the light block from the primary or they are invalid (e.g. trust +// hash does not match with the one from the headers). +// +// Witnesses are providers, which will be used for cross-checking the primary +// provider. At least one witness must be given when skipping verification is +// used (default). A witness can become a primary iff the current primary is +// unavailable. +// +// See all Option(s) for the additional configuration. +func NewClient( + ctx context.Context, + chainID string, + trustOptions TrustOptions, + primary provider.Provider, + witnesses []provider.Provider, + trustedStore store.Store, + options ...Option, +) (*Client, error) { + if err := trustOptions.ValidateBasic(); err != nil { + return nil, fmt.Errorf("invalid TrustOptions: %w", err) + } + + c, err := NewClientFromTrustedStore(chainID, trustOptions.Period, primary, witnesses, trustedStore, options...) + if err != nil { + return nil, err + } + + if c.latestTrustedBlock != nil { + c.logger.Info("Checking trusted light block using options") + if err := c.checkTrustedHeaderUsingOptions(ctx, trustOptions); err != nil { + return nil, err + } + } + + if c.latestTrustedBlock == nil || c.latestTrustedBlock.Height < trustOptions.Height { + c.logger.Info("Downloading trusted light block using options") + if err := c.initializeWithTrustOptions(ctx, trustOptions); err != nil { + return nil, err + } + } + + return c, err +} + +// NewClientFromTrustedStore initializes existing client from the trusted store. +// +// See NewClient +func NewClientFromTrustedStore( + chainID string, + trustingPeriod time.Duration, + primary provider.Provider, + witnesses []provider.Provider, + trustedStore store.Store, + options ...Option, +) (*Client, error) { + c := &Client{ + chainID: chainID, + trustingPeriod: trustingPeriod, + verificationMode: skipping, + trustLevel: DefaultTrustLevel, + maxRetryAttempts: defaultMaxRetryAttempts, + maxClockDrift: defaultMaxClockDrift, + maxBlockLag: defaultMaxBlockLag, + primary: primary, + witnesses: witnesses, + trustedStore: trustedStore, + pruningSize: defaultPruningSize, + confirmationFn: func(action string) bool { return true }, + quit: make(chan struct{}), + logger: log.NewNopLogger(), + } + + for _, o := range options { + o(c) + } + + // Validate the number of witnesses. + if len(c.witnesses) == 0 { + return nil, ErrNoWitnesses + } + + // Verify witnesses are all on the same chain. + for i, w := range witnesses { + if w.ChainID() != chainID { + return nil, fmt.Errorf("witness #%d: %v is on another chain %s, expected %s", + i, w, w.ChainID(), chainID) + } + } + + // Validate trust level. + if err := ValidateTrustLevel(c.trustLevel); err != nil { + return nil, err + } + + if err := c.restoreTrustedLightBlock(); err != nil { + return nil, err + } + + return c, nil +} + +// restoreTrustedLightBlock loads the latest trusted light block from the store +func (c *Client) restoreTrustedLightBlock() error { + lastHeight, err := c.trustedStore.LastLightBlockHeight() + if err != nil { + return fmt.Errorf("can't get last trusted light block height: %w", err) + } + + if lastHeight > 0 { + trustedBlock, err := c.trustedStore.LightBlock(lastHeight) + if err != nil { + return fmt.Errorf("can't get last trusted light block: %w", err) + } + c.latestTrustedBlock = trustedBlock + c.logger.Info("Restored trusted light block", "height", lastHeight) + } + + return nil +} + +// if options.Height: +// +// 1. ahead of trustedLightBlock.Height => fetch light blocks (same height as +// trustedLightBlock) from primary provider and check it's hash matches the +// trustedLightBlock's hash (if not, remove trustedLightBlock and all the light blocks +// before) +// +// 2. equals trustedLightBlock.Height => check options.Hash matches the +// trustedLightBlock's hash (if not, remove trustedLightBlock and all the light blocks +// before) +// +// 3. behind trustedLightBlock.Height => remove all the light blocks between +// options.Height and trustedLightBlock.Height, update trustedLightBlock, then +// check options.Hash matches the trustedLightBlock's hash (if not, remove +// trustedLightBlock and all the light blocks before) +// +// The intuition here is the user is always right. I.e. if she decides to reset +// the light client with an older header, there must be a reason for it. +func (c *Client) checkTrustedHeaderUsingOptions(ctx context.Context, options TrustOptions) error { + var primaryHash []byte + switch { + case options.Height > c.latestTrustedBlock.Height: + h, err := c.lightBlockFromPrimary(ctx, c.latestTrustedBlock.Height) + if err != nil { + return err + } + primaryHash = h.Hash() + case options.Height == c.latestTrustedBlock.Height: + primaryHash = options.Hash + case options.Height < c.latestTrustedBlock.Height: + c.logger.Info("Client initialized with old header (trusted is more recent)", + "old", options.Height, + "trustedHeight", c.latestTrustedBlock.Height, + "trustedHash", c.latestTrustedBlock.Hash()) + + action := fmt.Sprintf( + "Rollback to %d (%X)? Note this will remove newer light blocks up to %d (%X)", + options.Height, options.Hash, + c.latestTrustedBlock.Height, c.latestTrustedBlock.Hash()) + if c.confirmationFn(action) { + // remove all the headers (options.Height, trustedHeader.Height] + err := c.cleanupAfter(options.Height) + if err != nil { + return fmt.Errorf("cleanupAfter(%d): %w", options.Height, err) + } + + c.logger.Info("Rolled back to older header (newer headers were removed)", + "old", options.Height) + } else { + return nil + } + + primaryHash = options.Hash + } + + if !bytes.Equal(primaryHash, c.latestTrustedBlock.Hash()) { + c.logger.Info("Prev. trusted header's hash (h1) doesn't match hash from primary provider (h2)", + "h1", c.latestTrustedBlock.Hash(), "h2", primaryHash) + + action := fmt.Sprintf( + "Prev. trusted header's hash %X doesn't match hash %X from primary provider. Remove all the stored light blocks?", + c.latestTrustedBlock.Hash(), primaryHash) + if c.confirmationFn(action) { + err := c.Cleanup() + if err != nil { + return fmt.Errorf("failed to cleanup: %w", err) + } + } else { + return errors.New("refused to remove the stored light blocks despite hashes mismatch") + } + } + + return nil +} + +// initializeWithTrustOptions fetches the weakly-trusted light block from +// primary provider. +func (c *Client) initializeWithTrustOptions(ctx context.Context, options TrustOptions) error { + // 1) Fetch and verify the light block. + l, err := c.lightBlockFromPrimary(ctx, options.Height) + if err != nil { + return err + } + + // NOTE: - Verify func will check if it's expired or not. + // - h.Time is not being checked against time.Now() because we don't + // want to add yet another argument to NewClient* functions. + if err := l.ValidateBasic(c.chainID); err != nil { + return err + } + + if !bytes.Equal(l.Hash(), options.Hash) { + return fmt.Errorf("expected header's hash %X, but got %X", options.Hash, l.Hash()) + } + + // 2) Ensure that +2/3 of validators signed correctly. + err = l.ValidatorSet.VerifyCommitLight(c.chainID, l.Commit.BlockID, l.Height, l.Commit) + if err != nil { + return fmt.Errorf("invalid commit: %w", err) + } + + // 3) Cross-verify with witnesses to ensure everybody has the same state. + if err := c.compareFirstLightBlockWithWitnesses(ctx, l); err != nil { + return err + } + + // 4) Persist both of them and continue. + return c.updateTrustedLightBlock(l) +} + +// TrustedLightBlock returns a trusted light block at the given height (0 - the latest). +// +// It returns an error if: +// - there are some issues with the trusted store, although that should not +// happen normally; +// - negative height is passed; +// - header has not been verified yet and is therefore not in the store +// +// Safe for concurrent use by multiple goroutines. +func (c *Client) TrustedLightBlock(height int64) (*types.LightBlock, error) { + height, err := c.compareWithLatestHeight(height) + if err != nil { + return nil, err + } + return c.trustedStore.LightBlock(height) +} + +func (c *Client) compareWithLatestHeight(height int64) (int64, error) { + latestHeight, err := c.LastTrustedHeight() + if err != nil { + return 0, fmt.Errorf("can't get last trusted height: %w", err) + } + if latestHeight == -1 { + return 0, errors.New("no headers exist") + } + + switch { + case height > latestHeight: + return 0, fmt.Errorf("unverified header/valset requested (latest: %d)", latestHeight) + case height == 0: + return latestHeight, nil + case height < 0: + return 0, errors.New("negative height") + } + + return height, nil +} + +// Update attempts to advance the state by downloading the latest light +// block and verifying it. It returns a new light block on a successful +// update. Otherwise, it returns nil (plus an error, if any). +func (c *Client) Update(ctx context.Context, now time.Time) (*types.LightBlock, error) { + lastTrustedHeight, err := c.LastTrustedHeight() + if err != nil { + return nil, fmt.Errorf("can't get last trusted height: %w", err) + } + + if lastTrustedHeight == -1 { + // no light blocks yet => wait + return nil, nil + } + + latestBlock, err := c.lightBlockFromPrimary(ctx, 0) + if err != nil { + return nil, err + } + + if latestBlock.Height > lastTrustedHeight { + err = c.verifyLightBlock(ctx, latestBlock, now) + if err != nil { + return nil, err + } + c.logger.Info("Advanced to new state", "height", latestBlock.Height, "hash", latestBlock.Hash()) + return latestBlock, nil + } + + return nil, nil +} + +// VerifyLightBlockAtHeight fetches the light block at the given height +// and verifies it. It returns the block immediately if it exists in +// the trustedStore (no verification is needed). +// +// height must be > 0. +// +// It returns provider.ErrlightBlockNotFound if light block is not found by +// primary. +// +// It will replace the primary provider if an error from a request to the provider occurs +func (c *Client) VerifyLightBlockAtHeight(ctx context.Context, height int64, now time.Time) (*types.LightBlock, error) { + if height <= 0 { + return nil, errors.New("negative or zero height") + } + + // Check if the light block already verified. + h, err := c.TrustedLightBlock(height) + if err == nil { + c.logger.Info("Header has already been verified", "height", height, "hash", h.Hash()) + // Return already trusted light block + return h, nil + } + + // Request the light block from primary + l, err := c.lightBlockFromPrimary(ctx, height) + if err != nil { + return nil, err + } + + return l, c.verifyLightBlock(ctx, l, now) +} + +// VerifyHeader verifies a new header against the trusted state. It returns +// immediately if newHeader exists in trustedStore (no verification is +// needed). Else it performs one of the two types of verification: +// +// SequentialVerification: verifies that 2/3 of the trusted validator set has +// signed the new header. If the headers are not adjacent, **all** intermediate +// headers will be requested. Intermediate headers are not saved to database. +// +// SkippingVerification(trustLevel): verifies that {trustLevel} of the trusted +// validator set has signed the new header. If it's not the case and the +// headers are not adjacent, verifySkipping is performed and necessary (not all) +// intermediate headers will be requested. See the specification for details. +// Intermediate headers are not saved to database. +// https://github.com/cometbft/cometbft/blob/v0.38.x/spec/consensus/light-client.md +// +// If the header, which is older than the currently trusted header, is +// requested and the light client does not have it, VerifyHeader will perform: +// +// a) verifySkipping verification if nearest trusted header is found & not expired +// b) backwards verification in all other cases +// +// It returns ErrOldHeaderExpired if the latest trusted header expired. +// +// If the primary provides an invalid header (ErrInvalidHeader), it is rejected +// and replaced by another provider until all are exhausted. +// +// If, at any moment, a LightBlock is not found by the primary provider as part of +// verification then the provider will be replaced by another and the process will +// restart. +func (c *Client) VerifyHeader(ctx context.Context, newHeader *types.Header, now time.Time) error { + if newHeader == nil { + return errors.New("nil header") + } + if newHeader.Height <= 0 { + return errors.New("negative or zero height") + } + + // Check if newHeader already verified. + l, err := c.TrustedLightBlock(newHeader.Height) + if err == nil { + // Make sure it's the same header. + if !bytes.Equal(l.Hash(), newHeader.Hash()) { + return fmt.Errorf("existing trusted header %X does not match newHeader %X", l.Hash(), newHeader.Hash()) + } + c.logger.Info("Header has already been verified", + "height", newHeader.Height, "hash", newHeader.Hash()) + return nil + } + + // Request the header and the vals. + l, err = c.lightBlockFromPrimary(ctx, newHeader.Height) + if err != nil { + return fmt.Errorf("failed to retrieve light block from primary to verify against: %w", err) + } + + if !bytes.Equal(l.Hash(), newHeader.Hash()) { + return fmt.Errorf("light block header %X does not match newHeader %X", l.Hash(), newHeader.Hash()) + } + + return c.verifyLightBlock(ctx, l, now) +} + +func (c *Client) verifyLightBlock(ctx context.Context, newLightBlock *types.LightBlock, now time.Time) error { + c.logger.Info("VerifyHeader", "height", newLightBlock.Height, "hash", newLightBlock.Hash()) + + var ( + verifyFunc func(ctx context.Context, trusted *types.LightBlock, new *types.LightBlock, now time.Time) error + err error + ) + + switch c.verificationMode { + case sequential: + verifyFunc = c.verifySequential + case skipping: + verifyFunc = c.verifySkippingAgainstPrimary + default: + panic(fmt.Sprintf("Unknown verification mode: %b", c.verificationMode)) + } + + firstBlockHeight, err := c.FirstTrustedHeight() + if err != nil { + return fmt.Errorf("can't get first light block height: %w", err) + } + + switch { + // Verifying forwards + case newLightBlock.Height >= c.latestTrustedBlock.Height: + err = verifyFunc(ctx, c.latestTrustedBlock, newLightBlock, now) + + // Verifying backwards + case newLightBlock.Height < firstBlockHeight: + var firstBlock *types.LightBlock + firstBlock, err = c.trustedStore.LightBlock(firstBlockHeight) + if err != nil { + return fmt.Errorf("can't get first light block: %w", err) + } + err = c.backwards(ctx, firstBlock.Header, newLightBlock.Header) + + // Verifying between first and last trusted light block + default: + var closestBlock *types.LightBlock + closestBlock, err = c.trustedStore.LightBlockBefore(newLightBlock.Height) + if err != nil { + return fmt.Errorf("can't get signed header before height %d: %w", newLightBlock.Height, err) + } + err = verifyFunc(ctx, closestBlock, newLightBlock, now) + } + if err != nil { + c.logger.Error("Can't verify", "err", err) + return err + } + + // Once verified, save and return + return c.updateTrustedLightBlock(newLightBlock) +} + +// see VerifyHeader +func (c *Client) verifySequential( + ctx context.Context, + trustedBlock *types.LightBlock, + newLightBlock *types.LightBlock, + now time.Time, +) error { + var ( + verifiedBlock = trustedBlock + interimBlock *types.LightBlock + err error + trace = []*types.LightBlock{trustedBlock} + ) + + for height := trustedBlock.Height + 1; height <= newLightBlock.Height; height++ { + // 1) Fetch interim light block if needed. + if height == newLightBlock.Height { // last light block + interimBlock = newLightBlock + } else { // intermediate light blocks + interimBlock, err = c.lightBlockFromPrimary(ctx, height) + if err != nil { + return ErrVerificationFailed{From: verifiedBlock.Height, To: height, Reason: err} + } + } + + // 2) Verify them + c.logger.Debug("Verify adjacent newLightBlock against verifiedBlock", + "trustedHeight", verifiedBlock.Height, + "trustedHash", verifiedBlock.Hash(), + "newHeight", interimBlock.Height, + "newHash", interimBlock.Hash()) + + err = VerifyAdjacent(verifiedBlock.SignedHeader, interimBlock.SignedHeader, interimBlock.ValidatorSet, + c.trustingPeriod, now, c.maxClockDrift) + if err != nil { + err := ErrVerificationFailed{From: verifiedBlock.Height, To: interimBlock.Height, Reason: err} + + switch errors.Unwrap(err).(type) { + case ErrInvalidHeader: + // If the target header is invalid, return immediately. + if err.To == newLightBlock.Height { + c.logger.Debug("Target header is invalid", "err", err) + return err + } + + // If some intermediate header is invalid, replace the primary and try + // again. + c.logger.Error("primary sent invalid header -> replacing", "err", err) + + replacementBlock, removeErr := c.findNewPrimary(ctx, newLightBlock.Height, true) + if removeErr != nil { + c.logger.Debug("failed to replace primary. Returning original error", "err", removeErr) + return err + } + + if !bytes.Equal(replacementBlock.Hash(), newLightBlock.Hash()) { + c.logger.Error("Replacement provider has a different light block", + "newHash", newLightBlock.Hash(), + "replHash", replacementBlock.Hash()) + // return original error + return err + } + + // attempt to verify header again + height-- + + continue + default: + return err + } + } + + // 3) Update verifiedBlock + verifiedBlock = interimBlock + + // 4) Add verifiedBlock to trace + trace = append(trace, verifiedBlock) + } + + // Compare header with the witnesses to ensure it's not a fork. + // More witnesses we have, more chance to notice one. + // + // CORRECTNESS ASSUMPTION: there's at least 1 correct full node + // (primary or one of the witnesses). + return c.detectDivergence(ctx, trace, now) +} + +// see VerifyHeader +// +// verifySkipping finds the middle light block between a trusted and new light block, +// reiterating the action until it verifies a light block. A cache of light blocks +// requested from source is kept such that when a verification is made, and the +// light client tries again to verify the new light block in the middle, the light +// client does not need to ask for all the same light blocks again. +func (c *Client) verifySkipping( + ctx context.Context, + source provider.Provider, + trustedBlock *types.LightBlock, + newLightBlock *types.LightBlock, + now time.Time, +) ([]*types.LightBlock, error) { + var ( + blockCache = []*types.LightBlock{newLightBlock} + depth = 0 + + verifiedBlock = trustedBlock + trace = []*types.LightBlock{trustedBlock} + ) + + for { + c.logger.Debug("Verify non-adjacent newHeader against verifiedBlock", + "trustedHeight", verifiedBlock.Height, + "trustedHash", verifiedBlock.Hash(), + "newHeight", blockCache[depth].Height, + "newHash", blockCache[depth].Hash()) + + err := Verify(verifiedBlock.SignedHeader, verifiedBlock.ValidatorSet, blockCache[depth].SignedHeader, + blockCache[depth].ValidatorSet, c.trustingPeriod, now, c.maxClockDrift, c.trustLevel) + switch err.(type) { + case nil: + // Have we verified the last header + if depth == 0 { + trace = append(trace, newLightBlock) + return trace, nil + } + // If not, update the lower bound to the previous upper bound + verifiedBlock = blockCache[depth] + // Remove the light block at the lower bound in the header cache - it will no longer be needed + blockCache = blockCache[:depth] + // Reset the cache depth so that we start from the upper bound again + depth = 0 + // add verifiedBlock to the trace + trace = append(trace, verifiedBlock) + + case ErrNewValSetCantBeTrusted: + // do add another header to the end of the cache + if depth == len(blockCache)-1 { + pivotHeight := verifiedBlock.Height + (blockCache[depth].Height-verifiedBlock. + Height)*verifySkippingNumerator/verifySkippingDenominator + interimBlock, providerErr := source.LightBlock(ctx, pivotHeight) + switch providerErr { + case nil: + blockCache = append(blockCache, interimBlock) + + // if the error is benign, the client does not need to replace the primary + case provider.ErrLightBlockNotFound, provider.ErrNoResponse, provider.ErrHeightTooHigh: + return nil, err + + // all other errors such as ErrBadLightBlock or ErrUnreliableProvider are seen as malevolent and the + // provider is removed + default: + return nil, ErrVerificationFailed{From: verifiedBlock.Height, To: pivotHeight, Reason: providerErr} + } + blockCache = append(blockCache, interimBlock) + } + depth++ + + default: + return nil, ErrVerificationFailed{From: verifiedBlock.Height, To: blockCache[depth].Height, Reason: err} + } + } +} + +// verifySkippingAgainstPrimary does verifySkipping plus it compares new header with +// witnesses and replaces primary if it sends the light client an invalid header +func (c *Client) verifySkippingAgainstPrimary( + ctx context.Context, + trustedBlock *types.LightBlock, + newLightBlock *types.LightBlock, + now time.Time, +) error { + trace, err := c.verifySkipping(ctx, c.primary, trustedBlock, newLightBlock, now) + + switch errors.Unwrap(err).(type) { + case ErrInvalidHeader: + // If the target header is invalid, return immediately. + invalidHeaderHeight := err.(ErrVerificationFailed).To + if invalidHeaderHeight == newLightBlock.Height { + c.logger.Debug("Target header is invalid", "err", err) + return err + } + + // If some intermediate header is invalid, replace the primary and try + // again. + c.logger.Error("primary sent invalid header -> replacing", "err", err) + + replacementBlock, removeErr := c.findNewPrimary(ctx, newLightBlock.Height, true) + if removeErr != nil { + c.logger.Error("failed to replace primary. Returning original error", "err", removeErr) + return err + } + + if !bytes.Equal(replacementBlock.Hash(), newLightBlock.Hash()) { + c.logger.Error("Replacement provider has a different light block", + "newHash", newLightBlock.Hash(), + "replHash", replacementBlock.Hash()) + // return original error + return err + } + + // attempt to verify the header again + return c.verifySkippingAgainstPrimary(ctx, trustedBlock, replacementBlock, now) + case nil: + // Compare header with the witnesses to ensure it's not a fork. + // More witnesses we have, more chance to notice one. + // + // CORRECTNESS ASSUMPTION: there's at least 1 correct full node + // (primary or one of the witnesses). + if cmpErr := c.detectDivergence(ctx, trace, now); cmpErr != nil { + return cmpErr + } + default: + return err + } + + return nil +} + +// LastTrustedHeight returns a last trusted height. -1 and nil are returned if +// there are no trusted headers. +// +// Safe for concurrent use by multiple goroutines. +func (c *Client) LastTrustedHeight() (int64, error) { + return c.trustedStore.LastLightBlockHeight() +} + +// FirstTrustedHeight returns a first trusted height. -1 and nil are returned if +// there are no trusted headers. +// +// Safe for concurrent use by multiple goroutines. +func (c *Client) FirstTrustedHeight() (int64, error) { + return c.trustedStore.FirstLightBlockHeight() +} + +// ChainID returns the chain ID the light client was configured with. +// +// Safe for concurrent use by multiple goroutines. +func (c *Client) ChainID() string { + return c.chainID +} + +// Primary returns the primary provider. +// +// NOTE: provider may be not safe for concurrent access. +func (c *Client) Primary() provider.Provider { + c.providerMutex.Lock() + defer c.providerMutex.Unlock() + return c.primary +} + +// Witnesses returns the witness providers. +// +// NOTE: providers may be not safe for concurrent access. +func (c *Client) Witnesses() []provider.Provider { + c.providerMutex.Lock() + defer c.providerMutex.Unlock() + return c.witnesses +} + +// Cleanup removes all the data (headers and validator sets) stored. Note: the +// client must be stopped at this point. +func (c *Client) Cleanup() error { + c.logger.Info("Removing all the data") + c.latestTrustedBlock = nil + return c.trustedStore.Prune(0) +} + +// cleanupAfter deletes all headers & validator sets after +height+. It also +// resets latestTrustedBlock to the latest header. +func (c *Client) cleanupAfter(height int64) error { + prevHeight := c.latestTrustedBlock.Height + + for { + h, err := c.trustedStore.LightBlockBefore(prevHeight) + if err == store.ErrLightBlockNotFound || (h != nil && h.Height <= height) { + break + } else if err != nil { + return fmt.Errorf("failed to get header before %d: %w", prevHeight, err) + } + + err = c.trustedStore.DeleteLightBlock(h.Height) + if err != nil { + c.logger.Error("can't remove a trusted header & validator set", "err", err, + "height", h.Height) + } + + prevHeight = h.Height + } + + c.latestTrustedBlock = nil + err := c.restoreTrustedLightBlock() + if err != nil { + return err + } + + return nil +} + +func (c *Client) updateTrustedLightBlock(l *types.LightBlock) error { + c.logger.Debug("updating trusted light block", "light_block", l) + + if err := c.trustedStore.SaveLightBlock(l); err != nil { + return fmt.Errorf("failed to save trusted header: %w", err) + } + + if c.pruningSize > 0 { + if err := c.trustedStore.Prune(c.pruningSize); err != nil { + return fmt.Errorf("prune: %w", err) + } + } + + if c.latestTrustedBlock == nil || l.Height > c.latestTrustedBlock.Height { + c.latestTrustedBlock = l + } + + return nil +} + +// backwards verification (see VerifyHeaderBackwards func in the spec) verifies +// headers before a trusted header. If a sent header is invalid the primary is +// replaced with another provider and the operation is repeated. +func (c *Client) backwards( + ctx context.Context, + trustedHeader *types.Header, + newHeader *types.Header, +) error { + var ( + verifiedHeader = trustedHeader + interimHeader *types.Header + ) + + for verifiedHeader.Height > newHeader.Height { + interimBlock, err := c.lightBlockFromPrimary(ctx, verifiedHeader.Height-1) + if err != nil { + return fmt.Errorf("failed to obtain the header at height #%d: %w", verifiedHeader.Height-1, err) + } + interimHeader = interimBlock.Header + c.logger.Debug("Verify newHeader against verifiedHeader", + "trustedHeight", verifiedHeader.Height, + "trustedHash", verifiedHeader.Hash(), + "newHeight", interimHeader.Height, + "newHash", interimHeader.Hash()) + if err := VerifyBackwards(interimHeader, verifiedHeader); err != nil { + // verification has failed + c.logger.Error("backwards verification failed, replacing primary...", "err", err, "primary", c.primary) + + // the client tries to see if it can get a witness to continue with the request + newPrimarysBlock, replaceErr := c.findNewPrimary(ctx, newHeader.Height, true) + if replaceErr != nil { + c.logger.Debug("failed to replace primary. Returning original error", "err", replaceErr) + return err + } + + // before continuing we must check that they have the same target header to validate + if !bytes.Equal(newPrimarysBlock.Hash(), newHeader.Hash()) { + c.logger.Debug("replaced primary but new primary has a different block to the initial one") + // return the original error + return err + } + + // try again with the new primary + return c.backwards(ctx, verifiedHeader, newPrimarysBlock.Header) + } + verifiedHeader = interimHeader + } + + return nil +} + +// lightBlockFromPrimary retrieves the lightBlock from the primary provider +// at the specified height. This method also handles provider behavior as follows: +// +// 1. If the provider does not respond or does not have the block, it tries again +// with a different provider +// 2. If all providers return the same error, the light client forwards the error to +// where the initial request came from +// 3. If the provider provides an invalid light block, is deemed unreliable or returns +// any other error, the primary is permanently dropped and is replaced by a witness. +func (c *Client) lightBlockFromPrimary(ctx context.Context, height int64) (*types.LightBlock, error) { + c.providerMutex.Lock() + l, err := c.primary.LightBlock(ctx, height) + c.providerMutex.Unlock() + + switch err { + case nil: + // Everything went smoothly. We reset the lightBlockRequests and return the light block + return l, nil + + case context.Canceled, context.DeadlineExceeded: + return l, err + + case provider.ErrNoResponse, provider.ErrLightBlockNotFound, provider.ErrHeightTooHigh: + // we find a new witness to replace the primary + c.logger.Info("error from light block request from primary, replacing...", + "error", err, "height", height, "primary", c.primary) + return c.findNewPrimary(ctx, height, false) + + default: + // The light client has most likely received either provider.ErrUnreliableProvider or provider.ErrBadLightBlock + // These errors mean that the light client should drop the primary and try with another provider instead + c.logger.Info("error from light block request from primary, removing...", + "error", err, "height", height, "primary", c.primary) + return c.findNewPrimary(ctx, height, true) + } +} + +// NOTE: requires a providerMutex lock +func (c *Client) removeWitnesses(indexes []int) error { + // check that we will still have witnesses remaining + if len(c.witnesses) <= len(indexes) { + return ErrNoWitnesses + } + + // we need to make sure that we remove witnesses by index in the reverse + // order so as to not affect the indexes themselves + sort.Ints(indexes) + for i := len(indexes) - 1; i >= 0; i-- { + c.witnesses[indexes[i]] = c.witnesses[len(c.witnesses)-1] + c.witnesses = c.witnesses[:len(c.witnesses)-1] + } + + return nil +} + +type witnessResponse struct { + lb *types.LightBlock + witnessIndex int + err error +} + +// findNewPrimary concurrently sends a light block request, promoting the first witness to return +// a valid light block as the new primary. The remove option indicates whether the primary should be +// entire removed or just appended to the back of the witnesses list. This method also handles witness +// errors. If no witness is available, it returns the last error of the witness. +func (c *Client) findNewPrimary(ctx context.Context, height int64, remove bool) (*types.LightBlock, error) { + c.providerMutex.Lock() + defer c.providerMutex.Unlock() + + if len(c.witnesses) == 0 { + return nil, ErrNoWitnesses + } + + var ( + witnessResponsesC = make(chan witnessResponse, len(c.witnesses)) + witnessesToRemove []int + lastError error + wg sync.WaitGroup + ) + + // send out a light block request to all witnesses + subctx, cancel := context.WithCancel(ctx) + defer cancel() + for index := range c.witnesses { + wg.Add(1) + go func(witnessIndex int, witnessResponsesC chan witnessResponse) { + defer wg.Done() + + lb, err := c.witnesses[witnessIndex].LightBlock(subctx, height) + witnessResponsesC <- witnessResponse{lb, witnessIndex, err} + }(index, witnessResponsesC) + } + + // process all the responses as they come in + for i := 0; i < cap(witnessResponsesC); i++ { + response := <-witnessResponsesC + switch response.err { + // success! We have found a new primary + case nil: + cancel() // cancel all remaining requests to other witnesses + + wg.Wait() // wait for all goroutines to finish + + // if we are not intending on removing the primary then append the old primary to the end of the witness slice + if !remove { + c.witnesses = append(c.witnesses, c.primary) + } + + // promote respondent as the new primary + c.logger.Debug("found new primary", "primary", c.witnesses[response.witnessIndex]) + c.primary = c.witnesses[response.witnessIndex] + + // add promoted witness to the list of witnesses to be removed + witnessesToRemove = append(witnessesToRemove, response.witnessIndex) + + // remove witnesses marked as bad (the client must do this before we alter the witness slice and change the indexes + // of witnesses). Removal is done in descending order + if err := c.removeWitnesses(witnessesToRemove); err != nil { + return nil, err + } + + // return the light block that new primary responded with + return response.lb, nil + + // process benign errors by logging them only + case provider.ErrNoResponse, provider.ErrLightBlockNotFound, provider.ErrHeightTooHigh: + lastError = response.err + c.logger.Debug("error on light block request from witness", + "error", response.err, "primary", c.witnesses[response.witnessIndex]) + continue + + // process malevolent errors like ErrUnreliableProvider and ErrBadLightBlock by removing the witness + default: + lastError = response.err + c.logger.Error("error on light block request from witness, removing...", + "error", response.err, "primary", c.witnesses[response.witnessIndex]) + witnessesToRemove = append(witnessesToRemove, response.witnessIndex) + } + } + + // remove witnesses marked as bad. Removal is done in descending order + if err := c.removeWitnesses(witnessesToRemove); err != nil { + c.logger.Error("failed to remove witnesses", "err", err, "witnessesToRemove", witnessesToRemove) + } + + return nil, lastError +} + +// compareFirstLightBlockWithWitnesses compares light block l with all witnesses. If any +// witness reports a different header than h, the function returns an error. +func (c *Client) compareFirstLightBlockWithWitnesses(ctx context.Context, l *types.LightBlock) error { + compareCtx, cancel := context.WithCancel(ctx) + defer cancel() + + c.providerMutex.Lock() + defer c.providerMutex.Unlock() + + if len(c.witnesses) == 0 { + return ErrNoWitnesses + } + + errc := make(chan error, len(c.witnesses)) + for i, witness := range c.witnesses { + go c.compareNewLightBlockWithWitness(compareCtx, errc, l, witness, i) + } + + witnessesToRemove := make([]int, 0, len(c.witnesses)) + + // handle errors from the header comparisons as they come in + for i := 0; i < cap(errc); i++ { + err := <-errc + + switch e := err.(type) { + case nil: + continue + case ErrConflictingHeaders: + c.logger.Error("Witness reports a conflicting header. "+ + "Please check if the primary is correct or use a different witness.", + "witness", c.witnesses[e.WitnessIndex], "err", err) + return err + case errBadWitness: + // If witness sent us an invalid header, then remove it + c.logger.Info("Witness sent an invalid light block, removing...", + "witness", c.witnesses[e.WitnessIndex], + "err", err) + witnessesToRemove = append(witnessesToRemove, e.WitnessIndex) + case ErrProposerPrioritiesDiverge: + c.logger.Error("Witness reports conflicting proposer priorities. "+ + "Please check if the primary is correct or use a different witness.", + "witness", c.witnesses[e.WitnessIndex], "err", err) + return err + default: // benign errors can be ignored with the exception of context errors + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + + // the witness either didn't respond or didn't have the block. We ignore it. + c.logger.Info("Error comparing first header with witness. You may want to consider removing the witness", + "err", err) + } + + } + + // remove witnesses that have misbehaved + if err := c.removeWitnesses(witnessesToRemove); err != nil { + c.logger.Error("Failed to remove witnesses", "err", err, "witnessesToRemove", witnessesToRemove) + } + + return nil +} diff --git a/light/client_benchmark_test.go b/light/client_benchmark_test.go new file mode 100644 index 0000000..08e866d --- /dev/null +++ b/light/client_benchmark_test.go @@ -0,0 +1,110 @@ +package light_test + +import ( + "context" + "testing" + "time" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/light/provider" + mockp "github.com/cometbft/cometbft/light/provider/mock" + dbs "github.com/cometbft/cometbft/light/store/db" +) + +// NOTE: block is produced every minute. Make sure the verification time +// provided in the function call is correct for the size of the blockchain. The +// benchmarking may take some time hence it can be more useful to set the time +// or the amount of iterations use the flag -benchtime t -> i.e. -benchtime 5m +// or -benchtime 100x. +// +// Remember that none of these benchmarks account for network latency. +var ( + benchmarkFullNode = mockp.New(genMockNode(chainID, 1000, 100, 1, bTime)) + genesisBlock, _ = benchmarkFullNode.LightBlock(context.Background(), 1) +) + +func BenchmarkSequence(b *testing.B) { + c, err := light.NewClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: 24 * time.Hour, + Height: 1, + Hash: genesisBlock.Hash(), + }, + benchmarkFullNode, + []provider.Provider{benchmarkFullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.SequentialVerification(), + ) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + + for n := 0; n < b.N; n++ { + _, err = c.VerifyLightBlockAtHeight(context.Background(), 1000, bTime.Add(1000*time.Minute)) + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkBisection(b *testing.B) { + c, err := light.NewClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: 24 * time.Hour, + Height: 1, + Hash: genesisBlock.Hash(), + }, + benchmarkFullNode, + []provider.Provider{benchmarkFullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + + for n := 0; n < b.N; n++ { + _, err = c.VerifyLightBlockAtHeight(context.Background(), 1000, bTime.Add(1000*time.Minute)) + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkBackwards(b *testing.B) { + trustedBlock, _ := benchmarkFullNode.LightBlock(context.Background(), 0) + c, err := light.NewClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: 24 * time.Hour, + Height: trustedBlock.Height, + Hash: trustedBlock.Hash(), + }, + benchmarkFullNode, + []provider.Provider{benchmarkFullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + + for n := 0; n < b.N; n++ { + _, err = c.VerifyLightBlockAtHeight(context.Background(), 1, bTime) + if err != nil { + b.Fatal(err) + } + } +} diff --git a/light/client_test.go b/light/client_test.go new file mode 100644 index 0000000..6e0c5e3 --- /dev/null +++ b/light/client_test.go @@ -0,0 +1,1212 @@ +package light_test + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/light/provider" + mockp "github.com/cometbft/cometbft/light/provider/mock" + dbs "github.com/cometbft/cometbft/light/store/db" + "github.com/cometbft/cometbft/types" +) + +const ( + chainID = test.DefaultTestChainID +) + +var ( + ctx = context.Background() + keys = genPrivKeys(4) + vals = keys.ToValidators(20, 10) + bTime, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") + h1 = keys.GenSignedHeader(chainID, 1, bTime, nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + // 3/3 signed. + vals2 = vals.CopyIncrementProposerPriority(1) + h2 = keys.GenSignedHeaderLastBlockID(chainID, 2, bTime.Add(30*time.Minute), nil, vals2, vals2, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys), types.BlockID{Hash: h1.Hash()}) + // 3/3 signed. + vals3 = vals2.CopyIncrementProposerPriority(1) + h3 = keys.GenSignedHeaderLastBlockID(chainID, 3, bTime.Add(1*time.Hour), nil, vals3, vals3, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys), types.BlockID{Hash: h2.Hash()}) + trustPeriod = 4 * time.Hour + trustOptions = light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: h1.Hash(), + } + valSet = map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals2, + 3: vals3, + 4: vals.CopyIncrementProposerPriority(1), + } + headerSet = map[int64]*types.SignedHeader{ + 1: h1, + // interim header (3/3 signed) + 2: h2, + // last header (3/3 signed) + 3: h3, + } + l1 = &types.LightBlock{SignedHeader: h1, ValidatorSet: vals} + l2 = &types.LightBlock{SignedHeader: h2, ValidatorSet: vals2} + fullNode = mockp.New( + chainID, + headerSet, + valSet, + ) + deadNode = mockp.NewDeadMock(chainID) + largeFullNode = mockp.New(genMockNode(chainID, 10, 3, 0, bTime)) +) + +func TestValidateTrustOptions(t *testing.T) { + testCases := []struct { + err bool + to light.TrustOptions + }{ + { + false, + trustOptions, + }, + { + true, + light.TrustOptions{ + Period: -1 * time.Hour, + Height: 1, + Hash: h1.Hash(), + }, + }, + { + true, + light.TrustOptions{ + Period: 1 * time.Hour, + Height: 0, + Hash: h1.Hash(), + }, + }, + { + true, + light.TrustOptions{ + Period: 1 * time.Hour, + Height: 1, + Hash: []byte("incorrect hash"), + }, + }, + } + + for _, tc := range testCases { + err := tc.to.ValidateBasic() + if tc.err { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + } +} + +func TestMock(t *testing.T) { + l, _ := fullNode.LightBlock(ctx, 3) + assert.Equal(t, int64(3), l.Height) +} + +func TestClient_SequentialVerification(t *testing.T) { + newKeys := genPrivKeys(4) + newVals := newKeys.ToValidators(10, 1) + differentVals, _ := types.RandValidatorSet(10, 100) + + testCases := []struct { + name string + otherHeaders map[int64]*types.SignedHeader // all except ^ + vals map[int64]*types.ValidatorSet + initErr bool + verifyErr bool + }{ + { + "good", + headerSet, + valSet, + false, + false, + }, + { + "bad: different first header", + map[int64]*types.SignedHeader{ + // different header + 1: keys.GenSignedHeader(chainID, 1, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + }, + map[int64]*types.ValidatorSet{ + 1: vals, + }, + true, + false, + }, + { + "bad: no first signed header", + map[int64]*types.SignedHeader{}, + map[int64]*types.ValidatorSet{ + 1: differentVals, + }, + true, + true, + }, + { + "bad: different first validator set", + map[int64]*types.SignedHeader{ + 1: h1, + }, + map[int64]*types.ValidatorSet{ + 1: differentVals, + }, + true, + true, + }, + { + "bad: 1/3 signed interim header", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + // interim header (1/3 signed) + 2: keys.GenSignedHeader(chainID, 2, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), len(keys)-1, len(keys)), + // last header (3/3 signed) + 3: keys.GenSignedHeader(chainID, 3, bTime.Add(2*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + }, + valSet, + false, + true, + }, + { + "bad: 1/3 signed last header", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + // interim header (3/3 signed) + 2: keys.GenSignedHeader(chainID, 2, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + // last header (1/3 signed) + 3: keys.GenSignedHeader(chainID, 3, bTime.Add(2*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), len(keys)-1, len(keys)), + }, + valSet, + false, + true, + }, + { + "bad: different validator set at height 3", + headerSet, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: newVals, + }, + false, + true, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + mockp.New( + chainID, + tc.otherHeaders, + tc.vals, + ), + []provider.Provider{mockp.New( + chainID, + tc.otherHeaders, + tc.vals, + )}, + dbs.New(dbm.NewMemDB(), chainID), + light.SequentialVerification(), + light.Logger(log.TestingLogger()), + ) + + if tc.initErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(3*time.Hour)) + if tc.verifyErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestClient_SkippingVerification(t *testing.T) { + // required for 2nd test case + newKeys := genPrivKeys(4) + newVals := newKeys.ToValidators(10, 1) + + // 1/3+ of vals, 2/3- of newVals + transitKeys := keys.Extend(3) + transitVals := transitKeys.ToValidators(10, 1) + + testCases := []struct { + name string + otherHeaders map[int64]*types.SignedHeader // all except ^ + vals map[int64]*types.ValidatorSet + initErr bool + verifyErr bool + }{ + { + "good", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + // last header (3/3 signed) + 3: h3, + }, + valSet, + false, + false, + }, + { + "good, but val set changes by 2/3 (1/3 of vals is still present)", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + 3: transitKeys.GenSignedHeader(chainID, 3, bTime.Add(2*time.Hour), nil, transitVals, transitVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(transitKeys)), + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: transitVals, + }, + false, + false, + }, + { + "good, but val set changes 100% at height 2", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + // interim header (3/3 signed) + 2: keys.GenSignedHeader(chainID, 2, bTime.Add(1*time.Hour), nil, vals, newVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + // last header (0/4 of the original val set signed) + 3: newKeys.GenSignedHeader(chainID, 3, bTime.Add(2*time.Hour), nil, newVals, newVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(newKeys)), + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: newVals, + }, + false, + false, + }, + { + "bad: last header signed by newVals, interim header has no signers", + map[int64]*types.SignedHeader{ + // trusted header + 1: h1, + // last header (0/4 of the original val set signed) + 2: keys.GenSignedHeader(chainID, 2, bTime.Add(1*time.Hour), nil, vals, newVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, 0), + // last header (0/4 of the original val set signed) + 3: newKeys.GenSignedHeader(chainID, 3, bTime.Add(2*time.Hour), nil, newVals, newVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(newKeys)), + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: newVals, + }, + false, + true, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + mockp.New( + chainID, + tc.otherHeaders, + tc.vals, + ), + []provider.Provider{mockp.New( + chainID, + tc.otherHeaders, + tc.vals, + )}, + dbs.New(dbm.NewMemDB(), chainID), + light.SkippingVerification(light.DefaultTrustLevel), + light.Logger(log.TestingLogger()), + ) + if tc.initErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(3*time.Hour)) + if tc.verifyErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +// start from a large light block to make sure that the pivot height doesn't select a height outside +// the appropriate range +func TestClientLargeBisectionVerification(t *testing.T) { + veryLargeFullNode := mockp.New(genMockNode(chainID, 100, 3, 0, bTime)) + trustedLightBlock, err := veryLargeFullNode.LightBlock(ctx, 5) + require.NoError(t, err) + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: trustedLightBlock.Height, + Hash: trustedLightBlock.Hash(), + }, + veryLargeFullNode, + []provider.Provider{veryLargeFullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.SkippingVerification(light.DefaultTrustLevel), + ) + require.NoError(t, err) + h, err := c.Update(ctx, bTime.Add(100*time.Minute)) + assert.NoError(t, err) + h2, err := veryLargeFullNode.LightBlock(ctx, 100) + require.NoError(t, err) + assert.Equal(t, h, h2) +} + +func TestClientBisectionBetweenTrustedHeaders(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: h1.Hash(), + }, + fullNode, + []provider.Provider{fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.SkippingVerification(light.DefaultTrustLevel), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(2*time.Hour)) + require.NoError(t, err) + + // confirm that the client already doesn't have the light block + _, err = c.TrustedLightBlock(2) + require.Error(t, err) + + // verify using bisection the light block between the two trusted light blocks + _, err = c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(1*time.Hour)) + assert.NoError(t, err) +} + +func TestClient_Cleanup(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + _, err = c.TrustedLightBlock(1) + require.NoError(t, err) + + err = c.Cleanup() + require.NoError(t, err) + + // Check no light blocks exist after Cleanup. + l, err := c.TrustedLightBlock(1) + assert.Error(t, err) + assert.Nil(t, l) +} + +// trustedHeader.Height == options.Height +func TestClientRestoresTrustedHeaderAfterStartup1(t *testing.T) { + // 1. options.Hash == trustedHeader.Hash + { + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.NotNil(t, l) + assert.Equal(t, l.Hash(), h1.Hash()) + assert.Equal(t, l.ValidatorSet.Hash(), h1.ValidatorsHash.Bytes()) + } + + // 2. options.Hash != trustedHeader.Hash + { + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + // header1 != h1 + header1 := keys.GenSignedHeader(chainID, 1, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + + primary := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + // trusted header + 1: header1, + }, + valSet, + ) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: header1.Hash(), + }, + primary, + []provider.Provider{primary}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + if assert.NotNil(t, l) { + assert.Equal(t, l.Hash(), header1.Hash()) + assert.NoError(t, l.ValidateBasic(chainID)) + } + } +} + +// trustedHeader.Height < options.Height +func TestClientRestoresTrustedHeaderAfterStartup2(t *testing.T) { + // 1. options.Hash == trustedHeader.Hash + { + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 2, + Hash: h2.Hash(), + }, + fullNode, + []provider.Provider{fullNode}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // Check we still have the 1st header (+header+). + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.NotNil(t, l) + assert.Equal(t, l.Hash(), h1.Hash()) + assert.NoError(t, l.ValidateBasic(chainID)) + } + + // 2. options.Hash != trustedHeader.Hash + // This could happen if previous provider was lying to us. + { + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + // header1 != header + diffHeader1 := keys.GenSignedHeader(chainID, 1, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + + diffHeader2 := keys.GenSignedHeader(chainID, 2, bTime.Add(2*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + + primary := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: diffHeader1, + 2: diffHeader2, + }, + valSet, + ) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 2, + Hash: diffHeader2.Hash(), + }, + primary, + []provider.Provider{primary}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // Check we no longer have the invalid 1st header (+header+). + l, err := c.TrustedLightBlock(1) + assert.Error(t, err) + assert.Nil(t, l) + } +} + +// trustedHeader.Height > options.Height +func TestClientRestoresTrustedHeaderAfterStartup3(t *testing.T) { + // 1. options.Hash == trustedHeader.Hash + { + // load the first three headers into the trusted store + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + err = trustedStore.SaveLightBlock(l2) + require.NoError(t, err) + + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // Check we still have the 1st light block. + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.NotNil(t, l) + assert.Equal(t, l.Hash(), h1.Hash()) + assert.NoError(t, l.ValidateBasic(chainID)) + + // Check we no longer have 2nd light block. + l, err = c.TrustedLightBlock(2) + assert.Error(t, err) + assert.Nil(t, l) + + l, err = c.TrustedLightBlock(3) + assert.Error(t, err) + assert.Nil(t, l) + } + + // 2. options.Hash != trustedHeader.Hash + // This could happen if previous provider was lying to us. + { + trustedStore := dbs.New(dbm.NewMemDB(), chainID) + err := trustedStore.SaveLightBlock(l1) + require.NoError(t, err) + + // header1 != header + header1 := keys.GenSignedHeader(chainID, 1, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + + header2 := keys.GenSignedHeader(chainID, 2, bTime.Add(2*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + err = trustedStore.SaveLightBlock(&types.LightBlock{ + SignedHeader: header2, + ValidatorSet: vals, + }) + require.NoError(t, err) + + primary := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: header1, + }, + valSet, + ) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: header1.Hash(), + }, + primary, + []provider.Provider{primary}, + trustedStore, + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // Check we have swapped invalid 1st light block (+lightblock+) with correct one (+lightblock2+). + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.NotNil(t, l) + assert.Equal(t, l.Hash(), header1.Hash()) + assert.NoError(t, l.ValidateBasic(chainID)) + + // Check we no longer have invalid 2nd light block (+lightblock2+). + l, err = c.TrustedLightBlock(2) + assert.Error(t, err) + assert.Nil(t, l) + } +} + +func TestClient_Update(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // should result in downloading & verifying header #3 + l, err := c.Update(ctx, bTime.Add(2*time.Hour)) + assert.NoError(t, err) + if assert.NotNil(t, l) { + assert.EqualValues(t, 3, l.Height) + assert.NoError(t, l.ValidateBasic(chainID)) + } +} + +func TestClient_Concurrency(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(2*time.Hour)) + require.NoError(t, err) + + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + + // NOTE: Cleanup, Stop, VerifyLightBlockAtHeight and Verify are not supposed + // to be concurrenly safe. + + assert.Equal(t, chainID, c.ChainID()) + + _, err := c.LastTrustedHeight() + assert.NoError(t, err) + + _, err = c.FirstTrustedHeight() + assert.NoError(t, err) + + l, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.NotNil(t, l) + }() + } + + wg.Wait() +} + +func TestClientReplacesPrimaryWithWitnessIfPrimaryIsUnavailable(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + deadNode, + []provider.Provider{fullNode, fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + + require.NoError(t, err) + _, err = c.Update(ctx, bTime.Add(2*time.Hour)) + require.NoError(t, err) + + assert.NotEqual(t, c.Primary(), deadNode) + assert.Equal(t, 2, len(c.Witnesses())) +} + +func TestClient_BackwardsVerification(t *testing.T) { + { + trustHeader, _ := largeFullNode.LightBlock(ctx, 6) + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Minute, + Height: trustHeader.Height, + Hash: trustHeader.Hash(), + }, + largeFullNode, + []provider.Provider{largeFullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + // 1) verify before the trusted header using backwards => expect no error + h, err := c.VerifyLightBlockAtHeight(ctx, 5, bTime.Add(6*time.Minute)) + require.NoError(t, err) + if assert.NotNil(t, h) { + assert.EqualValues(t, 5, h.Height) + } + + // 2) untrusted header is expired but trusted header is not => expect no error + h, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(8*time.Minute)) + assert.NoError(t, err) + assert.NotNil(t, h) + + // 3) already stored headers should return the header without error + h, err = c.VerifyLightBlockAtHeight(ctx, 5, bTime.Add(6*time.Minute)) + assert.NoError(t, err) + assert.NotNil(t, h) + + // 4a) First verify latest header + _, err = c.VerifyLightBlockAtHeight(ctx, 9, bTime.Add(9*time.Minute)) + require.NoError(t, err) + + // 4b) Verify backwards using bisection => expect no error + _, err = c.VerifyLightBlockAtHeight(ctx, 7, bTime.Add(9*time.Minute)) + assert.NoError(t, err) + // shouldn't have verified this header in the process + _, err = c.TrustedLightBlock(8) + assert.Error(t, err) + + // 5) Try bisection method, but closest header (at 7) has expired + // so expect error + _, err = c.VerifyLightBlockAtHeight(ctx, 8, bTime.Add(12*time.Minute)) + assert.Error(t, err) + + } + { + testCases := []struct { + provider provider.Provider + }{ + { + // 7) provides incorrect height + mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: keys.GenSignedHeader(chainID, 1, bTime.Add(30*time.Minute), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + 3: h3, + }, + valSet, + ), + }, + { + // 8) provides incorrect hash + mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: keys.GenSignedHeader(chainID, 2, bTime.Add(30*time.Minute), nil, vals, vals, + hash("app_hash2"), hash("cons_hash23"), hash("results_hash30"), 0, len(keys)), + 3: h3, + }, + valSet, + ), + }, + } + + for idx, tc := range testCases { + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 1 * time.Hour, + Height: 3, + Hash: h3.Hash(), + }, + tc.provider, + []provider.Provider{tc.provider}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err, idx) + + _, err = c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(1*time.Hour).Add(1*time.Second)) + assert.Error(t, err, idx) + } + } +} + +func TestClient_NewClientFromTrustedStore(t *testing.T) { + // 1) Initiate DB and fill with a "trusted" header + db := dbs.New(dbm.NewMemDB(), chainID) + err := db.SaveLightBlock(l1) + require.NoError(t, err) + + c, err := light.NewClientFromTrustedStore( + chainID, + trustPeriod, + deadNode, + []provider.Provider{deadNode}, + db, + ) + require.NoError(t, err) + + // 2) Check light block exists (deadNode is being used to ensure we're not getting + // it from primary) + h, err := c.TrustedLightBlock(1) + assert.NoError(t, err) + assert.EqualValues(t, l1.Height, h.Height) +} + +func TestClientRemovesWitnessIfItSendsUsIncorrectHeader(t *testing.T) { + // different headers hash then primary plus less than 1/3 signed (no fork) + badProvider1 := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: keys.GenSignedHeaderLastBlockID(chainID, 2, bTime.Add(30*time.Minute), nil, vals2, vals2, + hash("app_hash2"), hash("cons_hash"), hash("results_hash"), + len(keys), len(keys), types.BlockID{Hash: h1.Hash()}), + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals2, + }, + ) + // header is empty + badProvider2 := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: h2, + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals2, + }, + ) + + lb1, _ := badProvider1.LightBlock(ctx, 2) + require.NotEqual(t, lb1.Hash(), l1.Hash()) + + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{badProvider1, badProvider2}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + // witness should have behaved properly -> no error + require.NoError(t, err) + assert.EqualValues(t, 2, len(c.Witnesses())) + + // witness behaves incorrectly -> removed from list, no error + l, err := c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(2*time.Hour)) + assert.NoError(t, err) + assert.EqualValues(t, 1, len(c.Witnesses())) + // light block should still be verified + assert.EqualValues(t, 2, l.Height) + + // remaining witnesses don't have light block -> error + _, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(2*time.Hour)) + if assert.Error(t, err) { + assert.Equal(t, light.ErrFailedHeaderCrossReferencing, err) + } + // witness does not have a light block -> left in the list + assert.EqualValues(t, 1, len(c.Witnesses())) +} + +func TestClient_TrustedValidatorSet(t *testing.T) { + differentVals, _ := types.RandValidatorSet(10, 100) + badValSetNode := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + // 3/3 signed, but validator set at height 2 below is invalid -> witness + // should be removed. + 2: keys.GenSignedHeaderLastBlockID(chainID, 2, bTime.Add(30*time.Minute), nil, vals, vals, + hash("app_hash2"), hash("cons_hash"), hash("results_hash"), + 0, len(keys), types.BlockID{Hash: h1.Hash()}), + 3: h3, + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: differentVals, + 3: differentVals, + }, + ) + + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{badValSetNode, fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + assert.Equal(t, 2, len(c.Witnesses())) + + _, err = c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(2*time.Hour).Add(1*time.Second)) + assert.NoError(t, err) + assert.Equal(t, 1, len(c.Witnesses())) +} + +func TestClientPrunesHeadersAndValidatorSets(t *testing.T) { + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{fullNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.PruningSize(1), + ) + require.NoError(t, err) + _, err = c.TrustedLightBlock(1) + require.NoError(t, err) + + h, err := c.Update(ctx, bTime.Add(2*time.Hour)) + require.NoError(t, err) + require.Equal(t, int64(3), h.Height) + + _, err = c.TrustedLightBlock(1) + assert.Error(t, err) +} + +func TestClientEnsureValidHeadersAndValSets(t *testing.T) { + emptyValSet := &types.ValidatorSet{ + Validators: nil, + Proposer: nil, + } + + testCases := []struct { + headers map[int64]*types.SignedHeader + vals map[int64]*types.ValidatorSet + err bool + }{ + { + headerSet, + valSet, + false, + }, + { + headerSet, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: nil, + }, + true, + }, + { + map[int64]*types.SignedHeader{ + 1: h1, + 2: h2, + 3: nil, + }, + valSet, + true, + }, + { + headerSet, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + 3: emptyValSet, + }, + true, + }, + } + + for _, tc := range testCases { + badNode := mockp.New( + chainID, + tc.headers, + tc.vals, + ) + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + badNode, + []provider.Provider{badNode, badNode}, + dbs.New(dbm.NewMemDB(), chainID), + light.MaxRetryAttempts(1), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 3, bTime.Add(2*time.Hour)) + if tc.err { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + } +} + +func TestClientHandlesContexts(t *testing.T) { + p := mockp.New(genMockNode(chainID, 100, 10, 1, bTime)) + genBlock, err := p.LightBlock(ctx, 1) + require.NoError(t, err) + + // instantiate the light client with a timeout + ctxTimeOut, cancel := context.WithTimeout(ctx, 10*time.Millisecond) + defer cancel() + _, err = light.NewClient( + ctxTimeOut, + chainID, + light.TrustOptions{ + Period: 24 * time.Hour, + Height: 1, + Hash: genBlock.Hash(), + }, + p, + []provider.Provider{p, p}, + dbs.New(dbm.NewMemDB(), chainID), + ) + require.Error(t, ctxTimeOut.Err()) + require.Error(t, err) + require.True(t, errors.Is(err, context.DeadlineExceeded)) + + // instantiate the client for real + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 24 * time.Hour, + Height: 1, + Hash: genBlock.Hash(), + }, + p, + []provider.Provider{p, p}, + dbs.New(dbm.NewMemDB(), chainID), + ) + require.NoError(t, err) + + // verify a block with a timeout + ctxTimeOutBlock, cancel := context.WithTimeout(ctx, 10*time.Millisecond) + defer cancel() + _, err = c.VerifyLightBlockAtHeight(ctxTimeOutBlock, 100, bTime.Add(100*time.Minute)) + require.Error(t, ctxTimeOutBlock.Err()) + require.Error(t, err) + require.True(t, errors.Is(err, context.DeadlineExceeded)) + + // verify a block with a cancel + ctxCancel, cancel := context.WithCancel(ctx) + defer cancel() + time.AfterFunc(10*time.Millisecond, cancel) + _, err = c.VerifyLightBlockAtHeight(ctxCancel, 100, bTime.Add(100*time.Minute)) + require.Error(t, ctxCancel.Err()) + require.Error(t, err) + require.True(t, errors.Is(err, context.Canceled)) +} + +// TestClientErrorsDifferentProposerPriorities tests the case where the witness +// sends us a light block with a validator set with different proposer priorities. +func TestClientErrorsDifferentProposerPriorities(t *testing.T) { + primary := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: h2, + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals2, + }, + ) + witness := mockp.New( + chainID, + map[int64]*types.SignedHeader{ + 1: h1, + 2: h2, + }, + map[int64]*types.ValidatorSet{ + 1: vals, + 2: vals, + }, + ) + + // Proposer priorities in vals and vals2 are different. + // This is because vals2 = vals.CopyIncrementProposerPriority(1) + require.Equal(t, vals.Hash(), vals2.Hash()) + require.NotEqual(t, vals.ProposerPriorityHash(), vals2.ProposerPriorityHash()) + + c, err := light.NewClient( + ctx, + chainID, + trustOptions, + fullNode, + []provider.Provider{primary, witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + // witness should have behaved properly -> no error + require.NoError(t, err) + assert.EqualValues(t, 2, len(c.Witnesses())) + + // witness behaves incorrectly, but we can't prove who's guilty -> error + _, err = c.VerifyLightBlockAtHeight(ctx, 2, bTime.Add(2*time.Hour)) + require.Error(t, err) + + // witness left in the list + assert.EqualValues(t, 2, len(c.Witnesses())) +} diff --git a/light/detector.go b/light/detector.go new file mode 100644 index 0000000..f7634b1 --- /dev/null +++ b/light/detector.go @@ -0,0 +1,437 @@ +package light + +import ( + "bytes" + "context" + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/light/provider" + "github.com/cometbft/cometbft/types" +) + +// The detector component of the light client detects and handles attacks on the light client. +// More info here: +// cometbft/docs/architecture/adr-047-handling-evidence-from-light-client.md + +// detectDivergence is a second wall of defense for the light client. +// +// It takes the target verified header and compares it with the headers of a set of +// witness providers that the light client is connected to. If a conflicting header +// is returned it verifies and examines the conflicting header against the verified +// trace that was produced from the primary. If successful, it produces two sets of evidence +// and sends them to the opposite provider before halting. +// +// If there are no conflicting headers, the light client deems the verified target header +// trusted and saves it to the trusted store. +func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.LightBlock, now time.Time) error { + if len(primaryTrace) < 2 { + return errors.New("nil or single block primary trace") + } + var ( + headerMatched bool + lastVerifiedBlock = primaryTrace[len(primaryTrace)-1] + lastVerifiedHeader = lastVerifiedBlock.SignedHeader + witnessesToRemove = make([]int, 0) + ) + c.logger.Debug("Running detector against trace", "finalizeBlockHeight", lastVerifiedHeader.Height, + "endBlockHash", lastVerifiedHeader.Hash, "length", len(primaryTrace)) + + c.providerMutex.Lock() + defer c.providerMutex.Unlock() + + if len(c.witnesses) == 0 { + return ErrNoWitnesses + } + + // launch one goroutine per witness to retrieve the light block of the target height + // and compare it with the header from the primary + errc := make(chan error, len(c.witnesses)) + for i, witness := range c.witnesses { + go c.compareNewLightBlockWithWitness(ctx, errc, lastVerifiedBlock, witness, i) + } + + // handle errors from the header comparisons as they come in + for i := 0; i < cap(errc); i++ { + err := <-errc + + switch e := err.(type) { + case nil: // at least one header matched + headerMatched = true + case ErrConflictingHeaders: + // We have conflicting headers. This could possibly imply an attack on the light client. + // First we need to verify the witness's header using the same skipping verification and then we + // need to find the point that the headers diverge and examine this for any evidence of an attack. + // + // We combine these actions together, verifying the witnesses headers and outputting the trace + // which captures the bifurcation point and if successful provides the information to create valid evidence. + err := c.handleConflictingHeaders(ctx, primaryTrace, e.Block, e.WitnessIndex, now) + if err != nil { + // return information of the attack + return err + } + // if attempt to generate conflicting headers failed then remove witness + witnessesToRemove = append(witnessesToRemove, e.WitnessIndex) + + case errBadWitness: + // these are all malevolent errors and should result in removing the + // witness + c.logger.Info("witness returned an error during header comparison, removing...", + "witness", c.witnesses[e.WitnessIndex], "err", err) + witnessesToRemove = append(witnessesToRemove, e.WitnessIndex) + case ErrProposerPrioritiesDiverge: + c.logger.Info("witness reported validator set with different proposer priorities", + "witness", c.witnesses[e.WitnessIndex], "err", err) + return e + default: + // Benign errors which can be ignored unless there was a context + // canceled + if errors.Is(e, context.Canceled) || errors.Is(e, context.DeadlineExceeded) { + return e + } + c.logger.Info("error in light block request to witness", "err", err) + } + } + + // remove witnesses that have misbehaved + if err := c.removeWitnesses(witnessesToRemove); err != nil { + return err + } + + // 1. If we had at least one witness that returned the same header then we + // conclude that we can trust the header + if headerMatched { + return nil + } + + // 2. Else all witnesses have either not responded, don't have the block or sent invalid blocks. + return ErrFailedHeaderCrossReferencing +} + +// compareNewLightBlockWithWitness takes the verified header from the primary and compares it with a +// header from a specified witness. The function can return one of three errors: +// +// 1: ErrConflictingHeaders -> there may have been an attack on this light client +// 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one +// +// Note: In the case of an invalid header we remove the witness +// +// 3: nil -> the hashes of the two headers match +func (c *Client) compareNewLightBlockWithWitness(ctx context.Context, errc chan error, l *types.LightBlock, + witness provider.Provider, witnessIndex int, +) { + h := l.SignedHeader + + lightBlock, err := witness.LightBlock(ctx, h.Height) + switch err { + // no error means we move on to checking the hash of the two headers + case nil: + break + + // the witness hasn't been helpful in comparing headers, we mark the response and continue + // comparing with the rest of the witnesses + case provider.ErrNoResponse, provider.ErrLightBlockNotFound, context.DeadlineExceeded, context.Canceled: + errc <- err + return + + // the witness' head of the blockchain is lower than the height of the primary. This could be one of + // two things: + // 1) The witness is lagging behind + // 2) The primary may be performing a lunatic attack with a height and time in the future + case provider.ErrHeightTooHigh: + // The light client now asks for the latest header that the witness has + var isTargetHeight bool + isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness) + if err != nil { + errc <- err + return + } + + // if the witness caught up and has returned a block of the target height then we can + // break from this switch case and continue to verify the hashes + if isTargetHeight { + break + } + + // witness' last header is below the primary's header. We check the times to see if the blocks + // have conflicting times + if !lightBlock.Time.Before(h.Time) { + errc <- ErrConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex} + return + } + + // the witness is behind. We wait for a period WAITING = 2 * DRIFT + LAG. + // This should give the witness ample time if it is a participating member + // of consensus to produce a block that has a time that is after the primary's + // block time. If not the witness is too far behind and the light client removes it + time.Sleep(2*c.maxClockDrift + c.maxBlockLag) + isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness) + if err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + errc <- err + } else { + errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex} + } + return + } + if isTargetHeight { + break + } + + // the witness still doesn't have a block at the height of the primary. + // Check if there is a conflicting time + if !lightBlock.Time.Before(h.Time) { + errc <- ErrConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex} + return + } + + // Following this request response procedure, the witness has been unable to produce a block + // that can somehow conflict with the primary's block. We thus conclude that the witness + // is too far behind and thus we return a no response error. + // + // NOTE: If the clock drift / lag has been miscalibrated it is feasible that the light client has + // drifted too far ahead for any witness to be able provide a comparable block and thus may allow + // for a malicious primary to attack it + errc <- provider.ErrNoResponse + return + + default: + // all other errors (i.e. invalid block, closed connection or unreliable provider) we mark the + // witness as bad and remove it + errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex} + return + } + + if !bytes.Equal(h.Hash(), lightBlock.Hash()) { + errc <- ErrConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex} + } + + // ProposerPriorityHash is not part of the header hash, so we need to check it separately. + wanted, got := l.ValidatorSet.ProposerPriorityHash(), lightBlock.ValidatorSet.ProposerPriorityHash() + if !bytes.Equal(wanted, got) { + errc <- ErrProposerPrioritiesDiverge{WitnessHash: got, WitnessIndex: witnessIndex, PrimaryHash: wanted} + } + + c.logger.Debug("Matching header received by witness", "height", h.Height, "witness", witnessIndex) + errc <- nil +} + +// sendEvidence sends evidence to a provider on a best effort basis. +func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) { + err := receiver.ReportEvidence(ctx, ev) + if err != nil { + c.logger.Error("Failed to report evidence to provider", "ev", ev, "provider", receiver) + } +} + +// handleConflictingHeaders handles the primary style of attack, which is where a primary and witness have +// two headers of the same height but with different hashes +func (c *Client) handleConflictingHeaders( + ctx context.Context, + primaryTrace []*types.LightBlock, + challengingBlock *types.LightBlock, + witnessIndex int, + now time.Time, +) error { + supportingWitness := c.witnesses[witnessIndex] + witnessTrace, primaryBlock, err := c.examineConflictingHeaderAgainstTrace( + ctx, + primaryTrace, + challengingBlock, + supportingWitness, + now, + ) + if err != nil { + c.logger.Info("error validating witness's divergent header", "witness", supportingWitness, "err", err) + return nil + } + + // We are suspecting that the primary is faulty, hence we hold the witness as the source of truth + // and generate evidence against the primary that we can send to the witness + commonBlock, trustedBlock := witnessTrace[0], witnessTrace[len(witnessTrace)-1] + evidenceAgainstPrimary := newLightClientAttackEvidence(primaryBlock, trustedBlock, commonBlock) + c.logger.Error("ATTEMPTED ATTACK DETECTED. Sending evidence againt primary by witness", "ev", evidenceAgainstPrimary, + "primary", c.primary, "witness", supportingWitness) + c.sendEvidence(ctx, evidenceAgainstPrimary, supportingWitness) + + if primaryBlock.Commit.Round != witnessTrace[len(witnessTrace)-1].Commit.Round { + c.logger.Info("The light client has detected, and prevented, an attempted amnesia attack." + + " We think this attack is pretty unlikely, so if you see it, that's interesting to us." + + " Can you let us know by opening an issue through https://github.com/cometbft/cometbft/issues/new?") + } + + // This may not be valid because the witness itself is at fault. So now we reverse it, examining the + // trace provided by the witness and holding the primary as the source of truth. Note: primary may not + // respond but this is okay as we will halt anyway. + primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace( + ctx, + witnessTrace, + primaryBlock, + c.primary, + now, + ) + if err != nil { + c.logger.Info("Error validating primary's divergent header", "primary", c.primary, "err", err) + return ErrLightClientAttack + } + + // We now use the primary trace to create evidence against the witness and send it to the primary + commonBlock, trustedBlock = primaryTrace[0], primaryTrace[len(primaryTrace)-1] + evidenceAgainstWitness := newLightClientAttackEvidence(witnessBlock, trustedBlock, commonBlock) + c.logger.Error("Sending evidence against witness by primary", "ev", evidenceAgainstWitness, + "primary", c.primary, "witness", supportingWitness) + c.sendEvidence(ctx, evidenceAgainstWitness, c.primary) + // We return the error and don't process anymore witnesses + return ErrLightClientAttack +} + +// examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that +// it has received from another and preforms verifySkipping at the heights of each of the intermediate +// headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen. +// +// 1. The light client verifies a header that is different to the intermediate header in the trace. This +// is the bifurcation point and the light client can create evidence from it +// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we +// return the error and remove the witness +// +// CONTRACT: +// 1. Trace can not be empty len(trace) > 0 +// 2. The last block in the trace can not be of a lower height than the target block +// trace[len(trace)-1].Height >= targetBlock.Height +// 3. The +func (c *Client) examineConflictingHeaderAgainstTrace( + ctx context.Context, + trace []*types.LightBlock, + targetBlock *types.LightBlock, + source provider.Provider, now time.Time, +) ([]*types.LightBlock, *types.LightBlock, error) { + + var ( + previouslyVerifiedBlock, sourceBlock *types.LightBlock + sourceTrace []*types.LightBlock + err error + ) + + if targetBlock.Height < trace[0].Height { + return nil, nil, fmt.Errorf("target block has a height lower than the trusted height (%d < %d)", + targetBlock.Height, trace[0].Height) + } + + for idx, traceBlock := range trace { + // this case only happens in a forward lunatic attack. We treat the block with the + // height directly after the targetBlock as the divergent block + if traceBlock.Height > targetBlock.Height { + // sanity check that the time of the traceBlock is indeed less than that of the targetBlock. If the trace + // was correctly verified we should expect monotonically increasing time. This means that if the block at + // the end of the trace has a lesser time than the target block then all blocks in the trace should have a + // lesser time + if traceBlock.Time.After(targetBlock.Time) { + return nil, nil, + errors.New("sanity check failed: expected traceblock to have a lesser time than the target block") + } + + // before sending back the divergent block and trace we need to ensure we have verified + // the final gap between the previouslyVerifiedBlock and the targetBlock + if previouslyVerifiedBlock.Height != targetBlock.Height { + sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, targetBlock, now) + if err != nil { + return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err) + } + } + return sourceTrace, traceBlock, nil + } + + // get the corresponding block from the source to verify and match up against the traceBlock + if traceBlock.Height == targetBlock.Height { + sourceBlock = targetBlock + } else { + sourceBlock, err = source.LightBlock(ctx, traceBlock.Height) + if err != nil { + return nil, nil, fmt.Errorf("failed to examine trace: %w", err) + } + } + + // The first block in the trace MUST be the same to the light block that the source produces + // else we cannot continue with verification. + if idx == 0 { + if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) { + return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)", + thash, shash) + } + previouslyVerifiedBlock = sourceBlock + continue + } + + // we check that the source provider can verify a block at the same height of the + // intermediate height + sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now) + if err != nil { + return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err) + } + // check if the headers verified by the source has diverged from the trace + if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) { + // Bifurcation point found! + return sourceTrace, traceBlock, nil + } + + // headers are still the same. update the previouslyVerifiedBlock + previouslyVerifiedBlock = sourceBlock + } + + // We have reached the end of the trace. This should never happen. This can only happen if one of the stated + // prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height + // or that trace[i].Hash() != targetBlock.Hash() + return nil, nil, errNoDivergence + +} + +// getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries +// the target height else it returns the latest. returns true if it successfully managed to acquire the target +// height. +func (c *Client) getTargetBlockOrLatest( + ctx context.Context, + height int64, + witness provider.Provider, +) (bool, *types.LightBlock, error) { + lightBlock, err := witness.LightBlock(ctx, 0) + if err != nil { + return false, nil, err + } + + if lightBlock.Height == height { + // the witness has caught up to the height of the provider's signed header. We + // can resume with checking the hashes. + return true, lightBlock, nil + } + + if lightBlock.Height > height { + // the witness has caught up. We recursively call the function again. However in order + // to avoid a wild goose chase where the witness sends us one header below and one header + // above the height we set a timeout to the context + lightBlock, err := witness.LightBlock(ctx, height) + return true, lightBlock, err + } + + return false, lightBlock, nil +} + +// newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out +// all the fields such that it is ready to be sent to a full node. +func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence { + ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted} + // if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we + // return the height of the conflicting block else if it is a lunatic attack and the validator sets + // are not the same then we send the height of the common header. + if ev.ConflictingHeaderIsInvalid(trusted.Header) { + ev.CommonHeight = common.Height + ev.Timestamp = common.Time + ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower() + } else { + ev.CommonHeight = trusted.Height + ev.Timestamp = trusted.Time + ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower() + } + ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader) + return ev +} diff --git a/light/detector_test.go b/light/detector_test.go new file mode 100644 index 0000000..ca86e1d --- /dev/null +++ b/light/detector_test.go @@ -0,0 +1,430 @@ +package light_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/light/provider" + mockp "github.com/cometbft/cometbft/light/provider/mock" + dbs "github.com/cometbft/cometbft/light/store/db" + "github.com/cometbft/cometbft/types" +) + +func TestLightClientAttackEvidence_Lunatic(t *testing.T) { + // primary performs a lunatic attack + var ( + latestHeight = int64(10) + valSize = 5 + divergenceHeight = int64(6) + primaryHeaders = make(map[int64]*types.SignedHeader, latestHeight) + primaryValidators = make(map[int64]*types.ValidatorSet, latestHeight) + ) + + witnessHeaders, witnessValidators, chainKeys := genMockNodeWithKeys(chainID, latestHeight, valSize, 2, bTime) + witness := mockp.New(chainID, witnessHeaders, witnessValidators) + forgedKeys := chainKeys[divergenceHeight-1].ChangeKeys(3) // we change 3 out of the 5 validators (still 2/5 remain) + forgedVals := forgedKeys.ToValidators(2, 0) + + for height := int64(1); height <= latestHeight; height++ { + if height < divergenceHeight { + primaryHeaders[height] = witnessHeaders[height] + primaryValidators[height] = witnessValidators[height] + continue + } + primaryHeaders[height] = forgedKeys.GenSignedHeader(chainID, height, bTime.Add(time.Duration(height)*time.Minute), + nil, forgedVals, forgedVals, hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(forgedKeys)) + primaryValidators[height] = forgedVals + } + primary := mockp.New(chainID, primaryHeaders, primaryValidators) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: primaryHeaders[1].Hash(), + }, + primary, + []provider.Provider{witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + require.NoError(t, err) + + // Check verification returns an error. + _, err = c.VerifyLightBlockAtHeight(ctx, 10, bTime.Add(1*time.Hour)) + if assert.Error(t, err) { + assert.Equal(t, light.ErrLightClientAttack, err) + } + + // Check evidence was sent to both full nodes. + evAgainstPrimary := &types.LightClientAttackEvidence{ + // after the divergence height the valset doesn't change so we expect the evidence to be for height 10 + ConflictingBlock: &types.LightBlock{ + SignedHeader: primaryHeaders[10], + ValidatorSet: primaryValidators[10], + }, + CommonHeight: 4, + } + assert.True(t, witness.HasEvidence(evAgainstPrimary)) + + evAgainstWitness := &types.LightClientAttackEvidence{ + // when forming evidence against witness we learn that the canonical chain continued to change validator sets + // hence the conflicting block is at 7 + ConflictingBlock: &types.LightBlock{ + SignedHeader: witnessHeaders[7], + ValidatorSet: witnessValidators[7], + }, + CommonHeight: 4, + } + assert.True(t, primary.HasEvidence(evAgainstWitness)) +} + +func TestLightClientAttackEvidence_Equivocation(t *testing.T) { + verificationOptions := map[string]light.Option{ + "sequential": light.SequentialVerification(), + "skipping": light.SkippingVerification(light.DefaultTrustLevel), + } + + for s, verificationOption := range verificationOptions { + t.Log("==> verification", s) + + // primary performs an equivocation attack + var ( + latestHeight = int64(10) + valSize = 5 + divergenceHeight = int64(6) + primaryHeaders = make(map[int64]*types.SignedHeader, latestHeight) + primaryValidators = make(map[int64]*types.ValidatorSet, latestHeight) + ) + // validators don't change in this network (however we still use a map just for convenience) + witnessHeaders, witnessValidators, chainKeys := genMockNodeWithKeys(chainID, latestHeight+2, valSize, 2, bTime) + witness := mockp.New(chainID, witnessHeaders, witnessValidators) + + for height := int64(1); height <= latestHeight; height++ { + if height < divergenceHeight { + primaryHeaders[height] = witnessHeaders[height] + primaryValidators[height] = witnessValidators[height] + continue + } + // we don't have a network partition so we will make 4/5 (greater than 2/3) malicious and vote again for + // a different block (which we do by adding txs) + primaryHeaders[height] = chainKeys[height].GenSignedHeader(chainID, height, + bTime.Add(time.Duration(height)*time.Minute), []types.Tx{[]byte("abcd")}, + witnessValidators[height], witnessValidators[height+1], hash("app_hash"), + hash("cons_hash"), hash("results_hash"), 0, len(chainKeys[height])-1) + primaryValidators[height] = witnessValidators[height] + } + primary := mockp.New(chainID, primaryHeaders, primaryValidators) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: primaryHeaders[1].Hash(), + }, + primary, + []provider.Provider{witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + verificationOption, + ) + require.NoError(t, err) + + // Check verification returns an error. + _, err = c.VerifyLightBlockAtHeight(ctx, 10, bTime.Add(1*time.Hour)) + if assert.Error(t, err) { + assert.Equal(t, light.ErrLightClientAttack, err) + } + + // Check evidence was sent to both full nodes. + // Common height should be set to the height of the divergent header in the instance + // of an equivocation attack and the validator sets are the same as what the witness has + evAgainstPrimary := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: primaryHeaders[divergenceHeight], + ValidatorSet: primaryValidators[divergenceHeight], + }, + CommonHeight: divergenceHeight, + } + assert.True(t, witness.HasEvidence(evAgainstPrimary)) + + evAgainstWitness := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: witnessHeaders[divergenceHeight], + ValidatorSet: witnessValidators[divergenceHeight], + }, + CommonHeight: divergenceHeight, + } + assert.True(t, primary.HasEvidence(evAgainstWitness)) + } +} + +func TestLightClientAttackEvidence_ForwardLunatic(t *testing.T) { + // primary performs a lunatic attack but changes the time of the header to + // something in the future relative to the blockchain + var ( + latestHeight = int64(10) + valSize = 5 + forgedHeight = int64(12) + proofHeight = int64(11) + primaryHeaders = make(map[int64]*types.SignedHeader, forgedHeight) + primaryValidators = make(map[int64]*types.ValidatorSet, forgedHeight) + ) + + witnessHeaders, witnessValidators, chainKeys := genMockNodeWithKeys(chainID, latestHeight, valSize, 2, bTime) + + // primary has the exact same headers except it forges one extra header in the future using keys from 2/5ths of + // the validators + for h := range witnessHeaders { + primaryHeaders[h] = witnessHeaders[h] + primaryValidators[h] = witnessValidators[h] + } + forgedKeys := chainKeys[latestHeight].ChangeKeys(3) // we change 3 out of the 5 validators (still 2/5 remain) + primaryValidators[forgedHeight] = forgedKeys.ToValidators(2, 0) + primaryHeaders[forgedHeight] = forgedKeys.GenSignedHeader( + chainID, + forgedHeight, + bTime.Add(time.Duration(latestHeight+1)*time.Minute), // 11 mins + nil, + primaryValidators[forgedHeight], + primaryValidators[forgedHeight], + hash("app_hash"), + hash("cons_hash"), + hash("results_hash"), + 0, len(forgedKeys), + ) + + witness := mockp.New(chainID, witnessHeaders, witnessValidators) + primary := mockp.New(chainID, primaryHeaders, primaryValidators) + + laggingWitness := witness.Copy(chainID) + + // In order to perform the attack, the primary needs at least one accomplice as a witness to also + // send the forged block + accomplice := primary + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: primaryHeaders[1].Hash(), + }, + primary, + []provider.Provider{witness, accomplice}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxClockDrift(1*time.Second), + light.MaxBlockLag(1*time.Second), + ) + require.NoError(t, err) + + // two seconds later, the supporting withness should receive the header that can be used + // to prove that there was an attack + vals := chainKeys[latestHeight].ToValidators(2, 0) + newLb := &types.LightBlock{ + SignedHeader: chainKeys[latestHeight].GenSignedHeader( + chainID, + proofHeight, + bTime.Add(time.Duration(proofHeight+1)*time.Minute), // 12 mins + nil, + vals, + vals, + hash("app_hash"), + hash("cons_hash"), + hash("results_hash"), + 0, len(chainKeys), + ), + ValidatorSet: vals, + } + go func() { + time.Sleep(2 * time.Second) + witness.AddLightBlock(newLb) + }() + + // Now assert that verification returns an error. We craft the light clients time to be a little ahead of the chain + // to allow a window for the attack to manifest itself. + _, err = c.Update(ctx, bTime.Add(time.Duration(forgedHeight)*time.Minute)) + if assert.Error(t, err) { + assert.Equal(t, light.ErrLightClientAttack, err) + } + + // Check evidence was sent to the witness against the full node + evAgainstPrimary := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: primaryHeaders[forgedHeight], + ValidatorSet: primaryValidators[forgedHeight], + }, + CommonHeight: latestHeight, + } + assert.True(t, witness.HasEvidence(evAgainstPrimary)) + + // We attempt the same call but now the supporting witness has a block which should + // immediately conflict in time with the primary + _, err = c.VerifyLightBlockAtHeight(ctx, forgedHeight, bTime.Add(time.Duration(forgedHeight)*time.Minute)) + if assert.Error(t, err) { + assert.Equal(t, light.ErrLightClientAttack, err) + } + assert.True(t, witness.HasEvidence(evAgainstPrimary)) + + // Lastly we test the unfortunate case where the light clients supporting witness doesn't update + // in enough time + c, err = light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Period: 4 * time.Hour, + Height: 1, + Hash: primaryHeaders[1].Hash(), + }, + primary, + []provider.Provider{laggingWitness, accomplice}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxClockDrift(1*time.Second), + light.MaxBlockLag(1*time.Second), + ) + require.NoError(t, err) + + _, err = c.Update(ctx, bTime.Add(time.Duration(forgedHeight)*time.Minute)) + assert.NoError(t, err) +} + +// 1. Different nodes therefore a divergent header is produced. +// => light client returns an error upon creation because primary and witness +// have a different view. +func TestClientDivergentTraces1(t *testing.T) { + primary := mockp.New(genMockNode(chainID, 10, 5, 2, bTime)) + firstBlock, err := primary.LightBlock(ctx, 1) + require.NoError(t, err) + witness := mockp.New(genMockNode(chainID, 10, 5, 2, bTime)) + + _, err = light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Height: 1, + Hash: firstBlock.Hash(), + Period: 4 * time.Hour, + }, + primary, + []provider.Provider{witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + require.Error(t, err) + assert.Contains(t, err.Error(), "does not match primary") +} + +// 2. Two out of three nodes don't respond but the third has a header that matches +// => verification should be successful and all the witnesses should remain +func TestClientDivergentTraces2(t *testing.T) { + primary := mockp.New(genMockNode(chainID, 10, 5, 2, bTime)) + firstBlock, err := primary.LightBlock(ctx, 1) + require.NoError(t, err) + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Height: 1, + Hash: firstBlock.Hash(), + Period: 4 * time.Hour, + }, + primary, + []provider.Provider{deadNode, deadNode, primary}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 10, bTime.Add(1*time.Hour)) + assert.NoError(t, err) + assert.Equal(t, 3, len(c.Witnesses())) +} + +// 3. witness has the same first header, but different second header +// => creation should succeed, but the verification should fail +func TestClientDivergentTraces3(t *testing.T) { + _, primaryHeaders, primaryVals := genMockNode(chainID, 10, 5, 2, bTime) + primary := mockp.New(chainID, primaryHeaders, primaryVals) + + firstBlock, err := primary.LightBlock(ctx, 1) + require.NoError(t, err) + + _, mockHeaders, mockVals := genMockNode(chainID, 10, 5, 2, bTime) + mockHeaders[1] = primaryHeaders[1] + mockVals[1] = primaryVals[1] + witness := mockp.New(chainID, mockHeaders, mockVals) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Height: 1, + Hash: firstBlock.Hash(), + Period: 4 * time.Hour, + }, + primary, + []provider.Provider{witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + light.MaxRetryAttempts(1), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 10, bTime.Add(1*time.Hour)) + assert.Error(t, err) + assert.Equal(t, 1, len(c.Witnesses())) +} + +// 4. Witness has a divergent header but can not produce a valid trace to back it up. +// It should be ignored +func TestClientDivergentTraces4(t *testing.T) { + _, primaryHeaders, primaryVals := genMockNode(chainID, 10, 5, 2, bTime) + primary := mockp.New(chainID, primaryHeaders, primaryVals) + + firstBlock, err := primary.LightBlock(ctx, 1) + require.NoError(t, err) + + _, mockHeaders, mockVals := genMockNode(chainID, 10, 5, 2, bTime) + witness := primary.Copy(chainID) + witness.AddLightBlock(&types.LightBlock{ + SignedHeader: mockHeaders[10], + ValidatorSet: mockVals[10], + }) + + c, err := light.NewClient( + ctx, + chainID, + light.TrustOptions{ + Height: 1, + Hash: firstBlock.Hash(), + Period: 4 * time.Hour, + }, + primary, + []provider.Provider{witness}, + dbs.New(dbm.NewMemDB(), chainID), + light.Logger(log.TestingLogger()), + ) + require.NoError(t, err) + + _, err = c.VerifyLightBlockAtHeight(ctx, 10, bTime.Add(1*time.Hour)) + assert.Error(t, err) + assert.Equal(t, 1, len(c.Witnesses())) +} diff --git a/light/doc.go b/light/doc.go new file mode 100644 index 0000000..c9f7c75 --- /dev/null +++ b/light/doc.go @@ -0,0 +1,127 @@ +/* +package light provides a light client implementation. + +The concept of light clients was introduced in the Bitcoin white paper. It +describes a watcher of distributed consensus process that only validates the +consensus algorithm and not the state machine transactions within. + +CometBFT light clients allow bandwidth & compute-constrained devices, such as +smartphones, low-power embedded chips, or other blockchains to efficiently +verify the consensus of a CometBFT blockchain. This forms the basis of safe +and efficient state synchronization for new network nodes and inter-blockchain +communication (where a light client of one CometBFT instance runs in another +chain's state machine). + +In a network that is expected to reliably punish validators for misbehavior by +slashing bonded stake and where the validator set changes infrequently, clients +can take advantage of this assumption to safely synchronize a light client +without downloading the intervening headers. + +Light clients (and full nodes) operating in the Proof Of Stake context need a +trusted block height from a trusted source that is no older than 1 unbonding +window plus a configurable evidence submission synchrony bound. This is called +weak subjectivity. + +Weak subjectivity is required in Proof of Stake blockchains because it is +costless for an attacker to buy up voting keys that are no longer bonded and +fork the network at some point in its prior history. See Vitalik's post at +[Proof of Stake: How I Learned to Love Weak +Subjectivity](https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity/). + +NOTE: CometBFT provides a somewhat different (stronger) light client model +than Bitcoin under eclipse, since the eclipsing node(s) can only fool the light +client if they have two-thirds of the private keys from the last root-of-trust. + +# Common structures + +* SignedHeader + +SignedHeader is a block header along with a commit -- enough validator +precommit-vote signatures to prove its validity (> 2/3 of the voting power) +given the validator set responsible for signing that header. + +The hash of the next validator set is included and signed in the SignedHeader. +This lets the light client keep track of arbitrary changes to the validator set, +as every change to the validator set must be approved by inclusion in the +header and signed in the commit. + +In the worst case, with every block changing the validators around completely, +a light client can sync up with every block header to verify each validator set +change on the chain. In practice, most applications will not have frequent +drastic updates to the validator set, so the logic defined in this package for +light client syncing is optimized to use intelligent bisection. + +# What this package provides + +This package provides three major things: + +1. Client implementation (see client.go) +2. Pure functions to verify a new header (see verifier.go) +3. Secure RPC proxy + +## 1. Client implementation (see client.go) + +Example usage: + + db, err := dbm.NewGoLevelDB("light-client-db", dbDir) + if err != nil { + // handle error + } + + c, err := NewHTTPClient( + chainID, + TrustOptions{ + Period: 504 * time.Hour, // 21 days + Height: 100, + Hash: header.Hash(), + }, + "http://localhost:26657", + []string{"http://witness1:26657"}, + dbs.New(db, ""), + ) + if err != nil { + // handle error + } + + h, err := c.TrustedHeader(100) + if err != nil { + // handle error + } + fmt.Println("header", h) + +Check out other examples in example_test.go + +## 2. Pure functions to verify a new header (see verifier.go) + +Verify function verifies a new header against some trusted header. See +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/README.md +for details. + +There are two methods of verification: sequential and bisection + +Sequential uses the headers hashes and the validator sets to verify each adjacent header until +it reaches the target header. + +Bisection finds the middle header between a trusted and new header, reiterating the action until it +verifies a header. A cache of headers requested by the primary is kept such that when a +verification is made, and the light client tries again to verify the new header in the middle, +the light client does not need to ask for all the same headers again. + +refer to docs/imgs/light_client_bisection_alg.png + +## 3. Secure RPC proxy + +CometBFT RPC exposes a lot of info, but a malicious node could return any +data it wants to queries, or even to block headers, even making up fake +signatures from non-existent validators to justify it. Secure RPC proxy serves +as a wrapper, which verifies all the headers, using a light client connected to +some other node. + +See +https://docs.cometbft.com/v0.38.x/core/light-client.html +for usage example. +Or see +https://github.com/cometbft/cometbft/tree/v0.38.x/spec/consensus/light-client +for the full spec +*/ +package light diff --git a/light/errors.go b/light/errors.go new file mode 100644 index 0000000..d47a786 --- /dev/null +++ b/light/errors.go @@ -0,0 +1,121 @@ +package light + +import ( + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/types" +) + +// ErrOldHeaderExpired means the old (trusted) header has expired according to +// the given trustingPeriod and current time. If so, the light client must be +// reset subjectively. +type ErrOldHeaderExpired struct { + At time.Time + Now time.Time +} + +func (e ErrOldHeaderExpired) Error() string { + return fmt.Sprintf("old header has expired at %v (now: %v)", e.At, e.Now) +} + +// ErrNewValSetCantBeTrusted means the new validator set cannot be trusted +// because < 1/3rd (+trustLevel+) of the old validator set has signed. +type ErrNewValSetCantBeTrusted struct { + Reason types.ErrNotEnoughVotingPowerSigned +} + +func (e ErrNewValSetCantBeTrusted) Error() string { + return fmt.Sprintf("cant trust new val set: %v", e.Reason) +} + +// ErrInvalidHeader means the header either failed the basic validation or +// commit is not signed by 2/3+. +type ErrInvalidHeader struct { + Reason error +} + +func (e ErrInvalidHeader) Error() string { + return fmt.Sprintf("invalid header: %v", e.Reason) +} + +// ErrFailedHeaderCrossReferencing is returned when the detector was not able to cross reference the header +// with any of the connected witnesses. +var ErrFailedHeaderCrossReferencing = errors.New("all witnesses have either not responded, don't have the " + + " blocks or sent invalid blocks. You should look to change your witnesses" + + " or review the light client's logs for more information") + +// ErrVerificationFailed means either sequential or skipping verification has +// failed to verify from header #1 to header #2 due to some reason. +type ErrVerificationFailed struct { + From int64 + To int64 + Reason error +} + +// Unwrap returns underlying reason. +func (e ErrVerificationFailed) Unwrap() error { + return e.Reason +} + +func (e ErrVerificationFailed) Error() string { + return fmt.Sprintf("verify from #%d to #%d failed: %v", e.From, e.To, e.Reason) +} + +// ErrLightClientAttack is returned when the light client has detected an attempt +// to verify a false header and has sent the evidence to either a witness or primary. +var ErrLightClientAttack = errors.New(`attempted attack detected. + Light client received valid conflicting header from witness. + Unable to verify header. Evidence has been sent to both providers. + Check logs for full evidence and trace`, +) + +// ErrNoWitnesses means that there are not enough witnesses connected to +// continue running the light client. +var ErrNoWitnesses = errors.New("no witnesses connected. please reset light client") + +// ErrConflictingHeaders is thrown when two conflicting headers are discovered. +type ErrConflictingHeaders struct { + Block *types.LightBlock + WitnessIndex int +} + +func (e ErrConflictingHeaders) Error() string { + return fmt.Sprintf( + "header hash (%X) from witness (%d) does not match primary", + e.Block.Hash(), e.WitnessIndex) +} + +// ErrProposerPrioritiesDiverge is thrown when two conflicting headers are +// discovered, but the error is non-attributable comparing to ErrConflictingHeaders. +// The difference is in validator set proposer priorities, which may change +// with every round of consensus. +type ErrProposerPrioritiesDiverge struct { + WitnessHash []byte + WitnessIndex int + PrimaryHash []byte +} + +func (e ErrProposerPrioritiesDiverge) Error() string { + return fmt.Sprintf( + "validator set's proposer priority hashes do not match: witness[%d]=%X, primary=%X", + e.WitnessIndex, e.WitnessHash, e.PrimaryHash) +} + +// ----------------------------- INTERNAL ERRORS --------------------------------- + +// errBadWitness is returned when the witness either does not respond or +// responds with an invalid header. +type errBadWitness struct { + Reason error + WitnessIndex int +} + +func (e errBadWitness) Error() string { + return fmt.Sprintf("Witness %d returned error: %s", e.WitnessIndex, e.Reason.Error()) +} + +var errNoDivergence = errors.New( + "sanity check failed: no divergence between the original trace and the provider's new trace", +) diff --git a/light/example_test.go b/light/example_test.go new file mode 100644 index 0000000..810bc81 --- /dev/null +++ b/light/example_test.go @@ -0,0 +1,161 @@ +package light_test + +import ( + "context" + "fmt" + stdlog "log" + "os" + "testing" + "time" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/light/provider" + httpp "github.com/cometbft/cometbft/light/provider/http" + dbs "github.com/cometbft/cometbft/light/store/db" + rpctest "github.com/cometbft/cometbft/rpc/test" +) + +// Automatically getting new headers and verifying them. +func ExampleClient_Update() { + // give CometBFT time to generate some blocks + time.Sleep(5 * time.Second) + + dbDir, err := os.MkdirTemp("", "light-client-example") + if err != nil { + stdlog.Fatal(err) + } + defer os.RemoveAll(dbDir) + + config := rpctest.GetConfig() + + primary, err := httpp.New(chainID, config.RPC.ListenAddress) + if err != nil { + stdlog.Fatal(err) + } + + block, err := primary.LightBlock(context.Background(), 2) + if err != nil { + stdlog.Fatal(err) + } + + db, err := dbm.NewGoLevelDB("light-client-db", dbDir) + if err != nil { + stdlog.Fatal(err) + } + + c, err := light.NewClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: 504 * time.Hour, // 21 days + Height: 2, + Hash: block.Hash(), + }, + primary, + []provider.Provider{primary}, // NOTE: primary should not be used here + dbs.New(db, chainID), + light.Logger(log.TestingLogger()), + ) + if err != nil { + stdlog.Fatal(err) + } + defer func() { + if err := c.Cleanup(); err != nil { + stdlog.Fatal(err) + } + }() + + time.Sleep(2 * time.Second) + + h, err := c.Update(context.Background(), time.Now()) + if err != nil { + stdlog.Fatal(err) + } + + if h != nil && h.Height > 2 { + fmt.Println("successful update") + } else { + fmt.Println("update failed") + } + // Output: successful update +} + +// Manually getting light blocks and verifying them. +func ExampleClient_VerifyLightBlockAtHeight() { + // give CometBFT time to generate some blocks + time.Sleep(5 * time.Second) + + dbDir, err := os.MkdirTemp("", "light-client-example") + if err != nil { + stdlog.Fatal(err) + } + defer os.RemoveAll(dbDir) + + config := rpctest.GetConfig() + + primary, err := httpp.New(chainID, config.RPC.ListenAddress) + if err != nil { + stdlog.Fatal(err) + } + + block, err := primary.LightBlock(context.Background(), 2) + if err != nil { + stdlog.Fatal(err) + } + + db, err := dbm.NewGoLevelDB("light-client-db", dbDir) + if err != nil { + stdlog.Fatal(err) + } + + c, err := light.NewClient( + context.Background(), + chainID, + light.TrustOptions{ + Period: 504 * time.Hour, // 21 days + Height: 2, + Hash: block.Hash(), + }, + primary, + []provider.Provider{primary}, // NOTE: primary should not be used here + dbs.New(db, chainID), + light.Logger(log.TestingLogger()), + ) + if err != nil { + stdlog.Fatal(err) + } + defer func() { + if err := c.Cleanup(); err != nil { + stdlog.Fatal(err) + } + }() + + _, err = c.VerifyLightBlockAtHeight(context.Background(), 3, time.Now()) + if err != nil { + stdlog.Fatal(err) + } + + h, err := c.TrustedLightBlock(3) + if err != nil { + stdlog.Fatal(err) + } + + fmt.Println("got header", h.Height) + // Output: got header 3 +} + +func TestMain(m *testing.M) { + // start a CometBFT node (and kvstore) in the background to test against + app := kvstore.NewInMemoryApplication() + node := rpctest.StartTendermint(app, rpctest.SuppressStdout) + + code := m.Run() + + // and shut down proper at the end + rpctest.StopTendermint(node) + os.Exit(code) +} diff --git a/light/helpers_test.go b/light/helpers_test.go new file mode 100644 index 0000000..a061e27 --- /dev/null +++ b/light/helpers_test.go @@ -0,0 +1,256 @@ +package light_test + +import ( + "time" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" +) + +// privKeys is a helper type for testing. +// +// It lets us simulate signing with many keys. The main use case is to create +// a set, and call GenSignedHeader to get properly signed header for testing. +// +// You can set different weights of validators each time you call ToValidators, +// and can optionally extend the validator set later with Extend. +type privKeys []crypto.PrivKey + +// genPrivKeys produces an array of private keys to generate commits. +func genPrivKeys(n int) privKeys { + res := make(privKeys, n) + for i := range res { + res[i] = ed25519.GenPrivKey() + } + return res +} + +// // Change replaces the key at index i. +// func (pkz privKeys) Change(i int) privKeys { +// res := make(privKeys, len(pkz)) +// copy(res, pkz) +// res[i] = ed25519.GenPrivKey() +// return res +// } + +// Extend adds n more keys (to remove, just take a slice). +func (pkz privKeys) Extend(n int) privKeys { + extra := genPrivKeys(n) + return append(pkz, extra...) +} + +// // GenSecpPrivKeys produces an array of secp256k1 private keys to generate commits. +// func GenSecpPrivKeys(n int) privKeys { +// res := make(privKeys, n) +// for i := range res { +// res[i] = secp256k1.GenPrivKey() +// } +// return res +// } + +// // ExtendSecp adds n more secp256k1 keys (to remove, just take a slice). +// func (pkz privKeys) ExtendSecp(n int) privKeys { +// extra := GenSecpPrivKeys(n) +// return append(pkz, extra...) +// } + +// ToValidators produces a valset from the set of keys. +// The first key has weight `init` and it increases by `inc` every step +// so we can have all the same weight, or a simple linear distribution +// (should be enough for testing). +func (pkz privKeys) ToValidators(init, inc int64) *types.ValidatorSet { + res := make([]*types.Validator, len(pkz)) + for i, k := range pkz { + res[i] = types.NewValidator(k.PubKey(), init+int64(i)*inc) + } + return types.NewValidatorSet(res) +} + +// signHeader properly signs the header with all keys from first to last exclusive. +func (pkz privKeys) signHeader(header *types.Header, valSet *types.ValidatorSet, first, last int) *types.Commit { + commitSigs := make([]types.CommitSig, len(pkz)) + for i := 0; i < len(pkz); i++ { + commitSigs[i] = types.NewCommitSigAbsent() + } + + blockID := types.BlockID{ + Hash: header.Hash(), + PartSetHeader: types.PartSetHeader{Total: 1, Hash: crypto.CRandBytes(32)}, + } + + // Fill in the votes we want. + for i := first; i < last && i < len(pkz); i++ { + vote := makeVote(header, valSet, pkz[i], blockID) + commitSigs[vote.ValidatorIndex] = vote.CommitSig() + } + + return &types.Commit{ + Height: header.Height, + Round: 1, + BlockID: blockID, + Signatures: commitSigs, + } +} + +func makeVote(header *types.Header, valset *types.ValidatorSet, + key crypto.PrivKey, blockID types.BlockID) *types.Vote { + + addr := key.PubKey().Address() + idx, _ := valset.GetByAddress(addr) + vote := &types.Vote{ + ValidatorAddress: addr, + ValidatorIndex: idx, + Height: header.Height, + Round: 1, + Timestamp: cmttime.Now(), + Type: cmtproto.PrecommitType, + BlockID: blockID, + } + + v := vote.ToProto() + // Sign it + signBytes := types.VoteSignBytes(header.ChainID, v) + sig, err := key.Sign(signBytes) + if err != nil { + panic(err) + } + vote.Signature = sig + + extSignBytes := types.VoteExtensionSignBytes(header.ChainID, v) + extSig, err := key.Sign(extSignBytes) + if err != nil { + panic(err) + } + vote.ExtensionSignature = extSig + + return vote +} + +func genHeader(chainID string, height int64, bTime time.Time, txs types.Txs, + valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte) *types.Header { + + return &types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 0}, + ChainID: chainID, + Height: height, + Time: bTime, + // LastBlockID + // LastCommitHash + ValidatorsHash: valset.Hash(), + NextValidatorsHash: nextValset.Hash(), + DataHash: txs.Hash(), + AppHash: appHash, + ConsensusHash: consHash, + LastResultsHash: resHash, + ProposerAddress: valset.Validators[0].Address, + } +} + +// GenSignedHeader calls genHeader and signHeader and combines them into a SignedHeader. +func (pkz privKeys) GenSignedHeader(chainID string, height int64, bTime time.Time, txs types.Txs, + valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int) *types.SignedHeader { + + header := genHeader(chainID, height, bTime, txs, valset, nextValset, appHash, consHash, resHash) + return &types.SignedHeader{ + Header: header, + Commit: pkz.signHeader(header, valset, first, last), + } +} + +// GenSignedHeaderLastBlockID calls genHeader and signHeader and combines them into a SignedHeader. +func (pkz privKeys) GenSignedHeaderLastBlockID(chainID string, height int64, bTime time.Time, txs types.Txs, + valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int, + lastBlockID types.BlockID) *types.SignedHeader { + + header := genHeader(chainID, height, bTime, txs, valset, nextValset, appHash, consHash, resHash) + header.LastBlockID = lastBlockID + return &types.SignedHeader{ + Header: header, + Commit: pkz.signHeader(header, valset, first, last), + } +} + +func (pkz privKeys) ChangeKeys(delta int) privKeys { + newKeys := pkz[delta:] + return newKeys.Extend(delta) +} + +// Generates the header and validator set to create a full entire mock node with blocks to height ( +// blockSize) and with variation in validator sets. BlockIntervals are in per minute. +// NOTE: Expected to have a large validator set size ~ 100 validators. +func genMockNodeWithKeys( + chainID string, + blockSize int64, + valSize int, + valVariation float32, + bTime time.Time) ( + map[int64]*types.SignedHeader, + map[int64]*types.ValidatorSet, + map[int64]privKeys) { + + var ( + headers = make(map[int64]*types.SignedHeader, blockSize) + valset = make(map[int64]*types.ValidatorSet, blockSize+1) + keymap = make(map[int64]privKeys, blockSize+1) + keys = genPrivKeys(valSize) + totalVariation = valVariation + valVariationInt int + newKeys privKeys + ) + + valVariationInt = int(totalVariation) + totalVariation = -float32(valVariationInt) + newKeys = keys.ChangeKeys(valVariationInt) + keymap[1] = keys + keymap[2] = newKeys + + // genesis header and vals + lastHeader := keys.GenSignedHeader(chainID, 1, bTime.Add(1*time.Minute), nil, + keys.ToValidators(2, 0), newKeys.ToValidators(2, 0), hash("app_hash"), hash("cons_hash"), + hash("results_hash"), 0, len(keys)) + currentHeader := lastHeader + headers[1] = currentHeader + valset[1] = keys.ToValidators(2, 0) + keys = newKeys + + for height := int64(2); height <= blockSize; height++ { + totalVariation += valVariation + valVariationInt = int(totalVariation) + totalVariation = -float32(valVariationInt) + newKeys = keys.ChangeKeys(valVariationInt) + currentHeader = keys.GenSignedHeaderLastBlockID(chainID, height, bTime.Add(time.Duration(height)*time.Minute), + nil, + keys.ToValidators(2, 0), newKeys.ToValidators(2, 0), hash("app_hash"), hash("cons_hash"), + hash("results_hash"), 0, len(keys), types.BlockID{Hash: lastHeader.Hash()}) + headers[height] = currentHeader + valset[height] = keys.ToValidators(2, 0) + lastHeader = currentHeader + keys = newKeys + keymap[height+1] = keys + } + + return headers, valset, keymap +} + +func genMockNode( + chainID string, + blockSize int64, + valSize int, + valVariation float32, + bTime time.Time) ( + string, + map[int64]*types.SignedHeader, + map[int64]*types.ValidatorSet) { + headers, valset, _ := genMockNodeWithKeys(chainID, blockSize, valSize, valVariation, bTime) + return chainID, headers, valset +} + +func hash(s string) []byte { + return tmhash.Sum([]byte(s)) +} diff --git a/light/provider/errors.go b/light/provider/errors.go new file mode 100644 index 0000000..ec8d6f5 --- /dev/null +++ b/light/provider/errors.go @@ -0,0 +1,29 @@ +package provider + +import ( + "errors" + "fmt" +) + +var ( + // ErrHeightTooHigh is returned when the height is higher than the last + // block that the provider has. The light client will not remove the provider + ErrHeightTooHigh = errors.New("height requested is too high") + // ErrLightBlockNotFound is returned when a provider can't find the + // requested header (i.e. it has been pruned). + // The light client will not remove the provider + ErrLightBlockNotFound = errors.New("light block not found") + // ErrNoResponse is returned if the provider doesn't respond to the + // request in a gieven time + ErrNoResponse = errors.New("client failed to respond") +) + +// ErrBadLightBlock is returned when a provider returns an invalid +// light block. +type ErrBadLightBlock struct { + Reason error +} + +func (e ErrBadLightBlock) Error() string { + return fmt.Sprintf("client provided bad signed header: %s", e.Reason.Error()) +} diff --git a/light/provider/http/http.go b/light/provider/http/http.go new file mode 100644 index 0000000..bac51dc --- /dev/null +++ b/light/provider/http/http.go @@ -0,0 +1,230 @@ +package http + +import ( + "context" + "fmt" + "math/rand" + "regexp" + "strings" + "time" + + "github.com/cometbft/cometbft/light/provider" + rpcclient "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cometbft/cometbft/types" +) + +var ( + // This is very brittle, see: https://github.com/tendermint/tendermint/issues/4740 + regexpMissingHeight = regexp.MustCompile(`height \d+ is not available`) + regexpTooHigh = regexp.MustCompile(`height \d+ must be less than or equal to`) + regexpTimedOut = regexp.MustCompile(`Timeout exceeded`) + + maxRetryAttempts = 5 + timeout uint = 5 // sec. +) + +// http provider uses an RPC client to obtain the necessary information. +type http struct { + chainID string + client rpcclient.RemoteClient +} + +// New creates a HTTP provider, which is using the rpchttp.HTTP client under +// the hood. If no scheme is provided in the remote URL, http will be used by +// default. The 5s timeout is used for all requests. +func New(chainID, remote string) (provider.Provider, error) { + // Ensure URL scheme is set (default HTTP) when not provided. + if !strings.Contains(remote, "://") { + remote = "http://" + remote + } + + httpClient, err := rpchttp.NewWithTimeout(remote, "/websocket", timeout) + if err != nil { + return nil, err + } + + return NewWithClient(chainID, httpClient), nil +} + +// NewWithClient allows you to provide a custom client. +func NewWithClient(chainID string, client rpcclient.RemoteClient) provider.Provider { + return &http{ + client: client, + chainID: chainID, + } +} + +// ChainID returns a chainID this provider was configured with. +func (p *http) ChainID() string { + return p.chainID +} + +func (p *http) String() string { + return fmt.Sprintf("http{%s}", p.client.Remote()) +} + +// LightBlock fetches a LightBlock at the given height and checks the +// chainID matches. +func (p *http) LightBlock(ctx context.Context, height int64) (*types.LightBlock, error) { + h, err := validateHeight(height) + if err != nil { + return nil, provider.ErrBadLightBlock{Reason: err} + } + + sh, err := p.signedHeader(ctx, h) + if err != nil { + return nil, err + } + + if height != 0 && sh.Height != height { + return nil, provider.ErrBadLightBlock{ + Reason: fmt.Errorf("height %d responded doesn't match height %d requested", sh.Height, height), + } + } + + vs, err := p.validatorSet(ctx, &sh.Height) + if err != nil { + return nil, err + } + + lb := &types.LightBlock{ + SignedHeader: sh, + ValidatorSet: vs, + } + + err = lb.ValidateBasic(p.chainID) + if err != nil { + return nil, provider.ErrBadLightBlock{Reason: err} + } + + return lb, nil +} + +// ReportEvidence calls `/broadcast_evidence` endpoint. +func (p *http) ReportEvidence(ctx context.Context, ev types.Evidence) error { + _, err := p.client.BroadcastEvidence(ctx, ev) + return err +} + +func (p *http) validatorSet(ctx context.Context, height *int64) (*types.ValidatorSet, error) { + // Since the malicious node could report a massive number of pages, making us + // spend a considerable time iterating, we restrict the number of pages here. + // => 10000 validators max + const maxPages = 100 + + var ( + perPage = 100 + vals = []*types.Validator{} + page = 1 + total = -1 + ) + +OUTER_LOOP: + for len(vals) != total && page <= maxPages { + for attempt := 1; attempt <= maxRetryAttempts; attempt++ { + res, err := p.client.Validators(ctx, height, &page, &perPage) + switch { + case err == nil: + // Validate response. + if len(res.Validators) == 0 { + return nil, provider.ErrBadLightBlock{ + Reason: fmt.Errorf("validator set is empty (height: %d, page: %d, per_page: %d)", + height, page, perPage), + } + } + if res.Total <= 0 { + return nil, provider.ErrBadLightBlock{ + Reason: fmt.Errorf("total number of vals is <= 0: %d (height: %d, page: %d, per_page: %d)", + res.Total, height, page, perPage), + } + } + + total = res.Total + vals = append(vals, res.Validators...) + page++ + continue OUTER_LOOP + + case regexpTooHigh.MatchString(err.Error()): + return nil, provider.ErrHeightTooHigh + + case regexpMissingHeight.MatchString(err.Error()): + return nil, provider.ErrLightBlockNotFound + + // if we have exceeded retry attempts then return no response error + case attempt == maxRetryAttempts: + return nil, provider.ErrNoResponse + + case regexpTimedOut.MatchString(err.Error()): + // we wait and try again with exponential backoff + time.Sleep(backoffTimeout(uint16(attempt))) + continue + + // context canceled or connection refused we return the error + default: + return nil, err + } + + } + } + + valSet, err := types.ValidatorSetFromExistingValidators(vals) + if err != nil { + return nil, provider.ErrBadLightBlock{Reason: err} + } + return valSet, nil +} + +func (p *http) signedHeader(ctx context.Context, height *int64) (*types.SignedHeader, error) { + for attempt := 1; attempt <= maxRetryAttempts; attempt++ { + commit, err := p.client.Commit(ctx, height) + switch { + case err == nil: + // See https://github.com/cometbft/cometbft/issues/575 + // If the node is starting at a non-zero height, but does not yet + // have any blocks, it can return an empty signed header without + // returning an error. + if commit.IsEmpty() { + // Technically this means that the provider still needs to + // catch up. + return nil, provider.ErrHeightTooHigh + } + return &commit.SignedHeader, nil + + case regexpTooHigh.MatchString(err.Error()): + return nil, provider.ErrHeightTooHigh + + case regexpMissingHeight.MatchString(err.Error()): + return nil, provider.ErrLightBlockNotFound + + case regexpTimedOut.MatchString(err.Error()): + // we wait and try again with exponential backoff + time.Sleep(backoffTimeout(uint16(attempt))) + continue + + // either context was canceled or connection refused. + default: + return nil, err + } + } + return nil, provider.ErrNoResponse +} + +func validateHeight(height int64) (*int64, error) { + if height < 0 { + return nil, fmt.Errorf("expected height >= 0, got height %d", height) + } + + h := &height + if height == 0 { + h = nil + } + return h, nil +} + +// exponential backoff (with jitter) +// 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation +func backoffTimeout(attempt uint16) time.Duration { + //nolint:gosec // G404: Use of weak random number generator + return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond +} diff --git a/light/provider/http/http_test.go b/light/provider/http/http_test.go new file mode 100644 index 0000000..26a184f --- /dev/null +++ b/light/provider/http/http_test.go @@ -0,0 +1,93 @@ +package http_test + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/light/provider" + lighthttp "github.com/cometbft/cometbft/light/provider/http" + rpcclient "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + rpctest "github.com/cometbft/cometbft/rpc/test" + "github.com/cometbft/cometbft/types" +) + +func TestNewProvider(t *testing.T) { + c, err := lighthttp.New("chain-test", "192.168.0.1:26657") + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("%s", c), "http{http://192.168.0.1:26657}") + + c, err = lighthttp.New("chain-test", "http://153.200.0.1:26657") + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("%s", c), "http{http://153.200.0.1:26657}") + + c, err = lighthttp.New("chain-test", "153.200.0.1") + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("%s", c), "http{http://153.200.0.1}") +} + +func TestProvider(t *testing.T) { + app := kvstore.NewInMemoryApplication() + app.RetainBlocks = 10 + node := rpctest.StartTendermint(app) + + cfg := rpctest.GetConfig() + defer os.RemoveAll(cfg.RootDir) + rpcAddr := cfg.RPC.ListenAddress + genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile()) + require.NoError(t, err) + chainID := genDoc.ChainID + + c, err := rpchttp.New(rpcAddr, "/websocket") + require.Nil(t, err) + + p := lighthttp.NewWithClient(chainID, c) + require.NoError(t, err) + require.NotNil(t, p) + + // let it produce some blocks + err = rpcclient.WaitForHeight(c, 10, nil) + require.NoError(t, err) + + // let's get the highest block + lb, err := p.LightBlock(context.Background(), 0) + require.NoError(t, err) + require.NotNil(t, lb) + assert.True(t, lb.Height < 1000) + + // let's check this is valid somehow + assert.Nil(t, lb.ValidateBasic(chainID)) + + // historical queries now work :) + lower := lb.Height - 3 + lb, err = p.LightBlock(context.Background(), lower) + require.NoError(t, err) + assert.Equal(t, lower, lb.Height) + + // fetching missing heights (both future and pruned) should return appropriate errors + lb, err = p.LightBlock(context.Background(), 1000) + require.Error(t, err) + require.Nil(t, lb) + assert.Equal(t, provider.ErrHeightTooHigh, err) + + _, err = p.LightBlock(context.Background(), 1) + require.Error(t, err) + require.Nil(t, lb) + assert.Equal(t, provider.ErrLightBlockNotFound, err) + + // stop the full node and check that a no response error is returned + rpctest.StopTendermint(node) + time.Sleep(10 * time.Second) + lb, err = p.LightBlock(context.Background(), lower+2) + // we should see a connection refused + require.Error(t, err) + require.Contains(t, err.Error(), "connection refused") + require.Nil(t, lb) +} diff --git a/light/provider/mock/deadmock.go b/light/provider/mock/deadmock.go new file mode 100644 index 0000000..18fd9f7 --- /dev/null +++ b/light/provider/mock/deadmock.go @@ -0,0 +1,29 @@ +package mock + +import ( + "context" + + "github.com/cometbft/cometbft/light/provider" + "github.com/cometbft/cometbft/types" +) + +type deadMock struct { + chainID string +} + +// NewDeadMock creates a mock provider that always errors. +func NewDeadMock(chainID string) provider.Provider { + return &deadMock{chainID: chainID} +} + +func (p *deadMock) ChainID() string { return p.chainID } + +func (p *deadMock) String() string { return "deadMock" } + +func (p *deadMock) LightBlock(context.Context, int64) (*types.LightBlock, error) { + return nil, provider.ErrNoResponse +} + +func (p *deadMock) ReportEvidence(context.Context, types.Evidence) error { + return provider.ErrNoResponse +} diff --git a/light/provider/mock/mock.go b/light/provider/mock/mock.go new file mode 100644 index 0000000..126d84b --- /dev/null +++ b/light/provider/mock/mock.go @@ -0,0 +1,131 @@ +package mock + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/cometbft/cometbft/light/provider" + "github.com/cometbft/cometbft/types" +) + +type Mock struct { + chainID string + + mtx sync.Mutex + headers map[int64]*types.SignedHeader + vals map[int64]*types.ValidatorSet + evidenceToReport map[string]types.Evidence // hash => evidence + latestHeight int64 +} + +var _ provider.Provider = (*Mock)(nil) + +// New creates a mock provider with the given set of headers and validator +// sets. +func New(chainID string, headers map[int64]*types.SignedHeader, vals map[int64]*types.ValidatorSet) *Mock { + height := int64(0) + for h := range headers { + if h > height { + height = h + } + } + return &Mock{ + chainID: chainID, + headers: headers, + vals: vals, + evidenceToReport: make(map[string]types.Evidence), + latestHeight: height, + } +} + +// ChainID returns the blockchain ID. +func (p *Mock) ChainID() string { + return p.chainID +} + +func (p *Mock) String() string { + var headers strings.Builder + for _, h := range p.headers { + fmt.Fprintf(&headers, " %d:%X", h.Height, h.Hash()) + } + + var vals strings.Builder + for _, v := range p.vals { + fmt.Fprintf(&vals, " %X", v.Hash()) + } + + return fmt.Sprintf("Mock{headers: %s, vals: %v}", headers.String(), vals.String()) +} + +func (p *Mock) LightBlock(ctx context.Context, height int64) (*types.LightBlock, error) { + p.mtx.Lock() + defer p.mtx.Unlock() + + // allocate a window of time for contexts to be canceled + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(10 * time.Millisecond): + } + + var lb *types.LightBlock + + if height > p.latestHeight { + return nil, provider.ErrHeightTooHigh + } + + if height == 0 && len(p.headers) > 0 { + height = p.latestHeight + } + + if _, ok := p.headers[height]; ok { + sh := p.headers[height] + vals := p.vals[height] + lb = &types.LightBlock{ + SignedHeader: sh, + ValidatorSet: vals, + } + } + if lb == nil { + return nil, provider.ErrLightBlockNotFound + } + if lb.SignedHeader == nil || lb.ValidatorSet == nil { + return nil, provider.ErrBadLightBlock{Reason: errors.New("nil header or vals")} + } + if err := lb.ValidateBasic(lb.ChainID); err != nil { + return nil, provider.ErrBadLightBlock{Reason: err} + } + return lb, nil +} + +func (p *Mock) ReportEvidence(_ context.Context, ev types.Evidence) error { + p.evidenceToReport[string(ev.Hash())] = ev + return nil +} + +func (p *Mock) HasEvidence(ev types.Evidence) bool { + _, ok := p.evidenceToReport[string(ev.Hash())] + return ok +} + +func (p *Mock) AddLightBlock(lb *types.LightBlock) { + p.mtx.Lock() + defer p.mtx.Unlock() + + if err := lb.ValidateBasic(lb.ChainID); err != nil { + panic(fmt.Sprintf("unable to add light block, err: %v", err)) + } + p.headers[lb.Height] = lb.SignedHeader + p.vals[lb.Height] = lb.ValidatorSet + if lb.Height > p.latestHeight { + p.latestHeight = lb.Height + } +} + +func (p *Mock) Copy(id string) *Mock { + return New(id, p.headers, p.vals) +} diff --git a/light/provider/provider.go b/light/provider/provider.go new file mode 100644 index 0000000..27e8978 --- /dev/null +++ b/light/provider/provider.go @@ -0,0 +1,29 @@ +package provider + +import ( + "context" + + "github.com/cometbft/cometbft/types" +) + +// Provider provides information for the light client to sync (verification +// happens in the client). +type Provider interface { + // ChainID returns the blockchain ID. + ChainID() string + + // LightBlock returns the LightBlock that corresponds to the given + // height. + // + // 0 - the latest. + // height must be >= 0. + // + // If the provider fails to fetch the LightBlock due to the IO or other + // issues, an error will be returned. + // If there's no LightBlock for the given height, ErrLightBlockNotFound + // error is returned. + LightBlock(ctx context.Context, height int64) (*types.LightBlock, error) + + // ReportEvidence reports an evidence of misbehavior. + ReportEvidence(context.Context, types.Evidence) error +} diff --git a/light/proxy/proxy.go b/light/proxy/proxy.go new file mode 100644 index 0000000..9477d2f --- /dev/null +++ b/light/proxy/proxy.go @@ -0,0 +1,122 @@ +package proxy + +import ( + "context" + "fmt" + "net" + "net/http" + + "github.com/cometbft/cometbft/libs/log" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/light" + lrpc "github.com/cometbft/cometbft/light/rpc" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" +) + +// A Proxy defines parameters for running an HTTP server proxy. +type Proxy struct { + Addr string // TCP address to listen on, ":http" if empty + Config *rpcserver.Config + Client *lrpc.Client + Logger log.Logger + Listener net.Listener +} + +// NewProxy creates the struct used to run an HTTP server for serving light +// client rpc requests. +func NewProxy( + lightClient *light.Client, + listenAddr, providerAddr string, + config *rpcserver.Config, + logger log.Logger, + opts ...lrpc.Option, +) (*Proxy, error) { + rpcClient, err := rpchttp.NewWithTimeout(providerAddr, "/websocket", uint(config.WriteTimeout.Seconds())) + if err != nil { + return nil, fmt.Errorf("failed to create http client for %s: %w", providerAddr, err) + } + + return &Proxy{ + Addr: listenAddr, + Config: config, + Client: lrpc.NewClient(rpcClient, lightClient, opts...), + Logger: logger, + }, nil +} + +// ListenAndServe configures the rpcserver.WebsocketManager, sets up the RPC +// routes to proxy via Client, and starts up an HTTP server on the TCP network +// address p.Addr. +// See http#Server#ListenAndServe. +func (p *Proxy) ListenAndServe() error { + listener, mux, err := p.listen() + if err != nil { + return err + } + p.Listener = listener + + return rpcserver.Serve( + listener, + mux, + p.Logger, + p.Config, + ) +} + +// ListenAndServeTLS acts identically to ListenAndServe, except that it expects +// HTTPS connections. +// See http#Server#ListenAndServeTLS. +func (p *Proxy) ListenAndServeTLS(certFile, keyFile string) error { + listener, mux, err := p.listen() + if err != nil { + return err + } + p.Listener = listener + + return rpcserver.ServeTLS( + listener, + mux, + certFile, + keyFile, + p.Logger, + p.Config, + ) +} + +func (p *Proxy) listen() (net.Listener, *http.ServeMux, error) { + mux := http.NewServeMux() + + // 1) Register regular routes. + r := RPCRoutes(p.Client) + rpcserver.RegisterRPCFuncs(mux, r, p.Logger) + + // 2) Allow websocket connections. + wmLogger := p.Logger.With("protocol", "websocket") + wm := rpcserver.NewWebsocketManager(r, + rpcserver.OnDisconnect(func(remoteAddr string) { + err := p.Client.UnsubscribeAll(context.Background(), remoteAddr) + if err != nil && err != cmtpubsub.ErrSubscriptionNotFound { + wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err) + } + }), + rpcserver.ReadLimit(p.Config.MaxBodyBytes), + ) + wm.SetLogger(wmLogger) + mux.HandleFunc("/websocket", wm.WebsocketHandler) + + // 3) Start a client. + if !p.Client.IsRunning() { + if err := p.Client.Start(); err != nil { + return nil, mux, fmt.Errorf("can't start client: %w", err) + } + } + + // 4) Start listening for new connections. + listener, err := rpcserver.Listen(p.Addr, p.Config.MaxOpenConnections) + if err != nil { + return nil, mux, err + } + + return listener, mux, nil +} diff --git a/light/proxy/routes.go b/light/proxy/routes.go new file mode 100644 index 0000000..1e197d2 --- /dev/null +++ b/light/proxy/routes.go @@ -0,0 +1,302 @@ +package proxy + +import ( + "github.com/cometbft/cometbft/libs/bytes" + lrpc "github.com/cometbft/cometbft/light/rpc" + rpcclient "github.com/cometbft/cometbft/rpc/client" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +func RPCRoutes(c *lrpc.Client) map[string]*rpcserver.RPCFunc { + return map[string]*rpcserver.RPCFunc{ + // Subscribe/unsubscribe are reserved for websocket events. + "subscribe": rpcserver.NewWSRPCFunc(c.SubscribeWS, "query"), + "unsubscribe": rpcserver.NewWSRPCFunc(c.UnsubscribeWS, "query"), + "unsubscribe_all": rpcserver.NewWSRPCFunc(c.UnsubscribeAllWS, ""), + + // info API + "health": rpcserver.NewRPCFunc(makeHealthFunc(c), ""), + "status": rpcserver.NewRPCFunc(makeStatusFunc(c), ""), + "net_info": rpcserver.NewRPCFunc(makeNetInfoFunc(c), ""), + "blockchain": rpcserver.NewRPCFunc(makeBlockchainInfoFunc(c), "minHeight,maxHeight", rpcserver.Cacheable()), + "genesis": rpcserver.NewRPCFunc(makeGenesisFunc(c), "", rpcserver.Cacheable()), + "genesis_chunked": rpcserver.NewRPCFunc(makeGenesisChunkedFunc(c), "", rpcserver.Cacheable()), + "block": rpcserver.NewRPCFunc(makeBlockFunc(c), "height", rpcserver.Cacheable("height")), + "header": rpcserver.NewRPCFunc(makeHeaderFunc(c), "height", rpcserver.Cacheable("height")), + "header_by_hash": rpcserver.NewRPCFunc(makeHeaderByHashFunc(c), "hash", rpcserver.Cacheable()), + "block_by_hash": rpcserver.NewRPCFunc(makeBlockByHashFunc(c), "hash", rpcserver.Cacheable()), + "block_results": rpcserver.NewRPCFunc(makeBlockResultsFunc(c), "height", rpcserver.Cacheable("height")), + "commit": rpcserver.NewRPCFunc(makeCommitFunc(c), "height", rpcserver.Cacheable("height")), + "tx": rpcserver.NewRPCFunc(makeTxFunc(c), "hash,prove", rpcserver.Cacheable()), + "tx_search": rpcserver.NewRPCFunc(makeTxSearchFunc(c), "query,prove,page,per_page,order_by"), + "block_search": rpcserver.NewRPCFunc(makeBlockSearchFunc(c), "query,page,per_page,order_by"), + "validators": rpcserver.NewRPCFunc(makeValidatorsFunc(c), "height,page,per_page", rpcserver.Cacheable("height")), + "dump_consensus_state": rpcserver.NewRPCFunc(makeDumpConsensusStateFunc(c), ""), + "consensus_state": rpcserver.NewRPCFunc(makeConsensusStateFunc(c), ""), + "consensus_params": rpcserver.NewRPCFunc(makeConsensusParamsFunc(c), "height", rpcserver.Cacheable("height")), + "unconfirmed_txs": rpcserver.NewRPCFunc(makeUnconfirmedTxsFunc(c), "limit"), + "num_unconfirmed_txs": rpcserver.NewRPCFunc(makeNumUnconfirmedTxsFunc(c), ""), + + // tx broadcast API + "broadcast_tx_commit": rpcserver.NewRPCFunc(makeBroadcastTxCommitFunc(c), "tx"), + "broadcast_tx_sync": rpcserver.NewRPCFunc(makeBroadcastTxSyncFunc(c), "tx"), + "broadcast_tx_async": rpcserver.NewRPCFunc(makeBroadcastTxAsyncFunc(c), "tx"), + + // abci API + "abci_query": rpcserver.NewRPCFunc(makeABCIQueryFunc(c), "path,data,height,prove"), + "abci_info": rpcserver.NewRPCFunc(makeABCIInfoFunc(c), "", rpcserver.Cacheable()), + + // evidence API + "broadcast_evidence": rpcserver.NewRPCFunc(makeBroadcastEvidenceFunc(c), "evidence"), + } +} + +type rpcHealthFunc func(ctx *rpctypes.Context) (*ctypes.ResultHealth, error) + +func makeHealthFunc(c *lrpc.Client) rpcHealthFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultHealth, error) { + return c.Health(ctx.Context()) + } +} + +type rpcStatusFunc func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) + +func makeStatusFunc(c *lrpc.Client) rpcStatusFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) { + return c.Status(ctx.Context()) + } +} + +type rpcNetInfoFunc func(ctx *rpctypes.Context, minHeight, maxHeight int64) (*ctypes.ResultNetInfo, error) + +func makeNetInfoFunc(c *lrpc.Client) rpcNetInfoFunc { + return func(ctx *rpctypes.Context, minHeight, maxHeight int64) (*ctypes.ResultNetInfo, error) { + return c.NetInfo(ctx.Context()) + } +} + +type rpcBlockchainInfoFunc func(ctx *rpctypes.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) + +func makeBlockchainInfoFunc(c *lrpc.Client) rpcBlockchainInfoFunc { + return func(ctx *rpctypes.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) { + return c.BlockchainInfo(ctx.Context(), minHeight, maxHeight) + } +} + +type rpcGenesisFunc func(ctx *rpctypes.Context) (*ctypes.ResultGenesis, error) + +func makeGenesisFunc(c *lrpc.Client) rpcGenesisFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultGenesis, error) { + return c.Genesis(ctx.Context()) + } +} + +type rpcGenesisChunkedFunc func(ctx *rpctypes.Context, chunk uint) (*ctypes.ResultGenesisChunk, error) + +func makeGenesisChunkedFunc(c *lrpc.Client) rpcGenesisChunkedFunc { + return func(ctx *rpctypes.Context, chunk uint) (*ctypes.ResultGenesisChunk, error) { + return c.GenesisChunked(ctx.Context(), chunk) + } +} + +type rpcBlockFunc func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultBlock, error) + +func makeBlockFunc(c *lrpc.Client) rpcBlockFunc { + return func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultBlock, error) { + return c.Block(ctx.Context(), height) + } +} + +type rpcHeaderFunc func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultHeader, error) + +func makeHeaderFunc(c *lrpc.Client) rpcHeaderFunc { + return func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultHeader, error) { + return c.Header(ctx.Context(), height) + } +} + +type rpcHeaderByHashFunc func(ctx *rpctypes.Context, hash []byte) (*ctypes.ResultHeader, error) + +func makeHeaderByHashFunc(c *lrpc.Client) rpcHeaderByHashFunc { + return func(ctx *rpctypes.Context, hash []byte) (*ctypes.ResultHeader, error) { + return c.HeaderByHash(ctx.Context(), hash) + } +} + +type rpcBlockByHashFunc func(ctx *rpctypes.Context, hash []byte) (*ctypes.ResultBlock, error) + +func makeBlockByHashFunc(c *lrpc.Client) rpcBlockByHashFunc { + return func(ctx *rpctypes.Context, hash []byte) (*ctypes.ResultBlock, error) { + return c.BlockByHash(ctx.Context(), hash) + } +} + +type rpcBlockResultsFunc func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultBlockResults, error) + +func makeBlockResultsFunc(c *lrpc.Client) rpcBlockResultsFunc { + return func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultBlockResults, error) { + return c.BlockResults(ctx.Context(), height) + } +} + +type rpcCommitFunc func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultCommit, error) + +func makeCommitFunc(c *lrpc.Client) rpcCommitFunc { + return func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultCommit, error) { + return c.Commit(ctx.Context(), height) + } +} + +type rpcTxFunc func(ctx *rpctypes.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) + +func makeTxFunc(c *lrpc.Client) rpcTxFunc { + return func(ctx *rpctypes.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) { + return c.Tx(ctx.Context(), hash, prove) + } +} + +type rpcTxSearchFunc func( + ctx *rpctypes.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, +) (*ctypes.ResultTxSearch, error) + +func makeTxSearchFunc(c *lrpc.Client) rpcTxSearchFunc { + return func( + ctx *rpctypes.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, + ) (*ctypes.ResultTxSearch, error) { + return c.TxSearch(ctx.Context(), query, prove, page, perPage, orderBy) + } +} + +type rpcBlockSearchFunc func( + ctx *rpctypes.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, +) (*ctypes.ResultBlockSearch, error) + +func makeBlockSearchFunc(c *lrpc.Client) rpcBlockSearchFunc { + return func( + ctx *rpctypes.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, + ) (*ctypes.ResultBlockSearch, error) { + return c.BlockSearch(ctx.Context(), query, page, perPage, orderBy) + } +} + +type rpcValidatorsFunc func(ctx *rpctypes.Context, height *int64, + page, perPage *int) (*ctypes.ResultValidators, error) + +func makeValidatorsFunc(c *lrpc.Client) rpcValidatorsFunc { + return func(ctx *rpctypes.Context, height *int64, page, perPage *int) (*ctypes.ResultValidators, error) { + return c.Validators(ctx.Context(), height, page, perPage) + } +} + +type rpcDumpConsensusStateFunc func(ctx *rpctypes.Context) (*ctypes.ResultDumpConsensusState, error) + +func makeDumpConsensusStateFunc(c *lrpc.Client) rpcDumpConsensusStateFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultDumpConsensusState, error) { + return c.DumpConsensusState(ctx.Context()) + } +} + +type rpcConsensusStateFunc func(ctx *rpctypes.Context) (*ctypes.ResultConsensusState, error) + +func makeConsensusStateFunc(c *lrpc.Client) rpcConsensusStateFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultConsensusState, error) { + return c.ConsensusState(ctx.Context()) + } +} + +type rpcConsensusParamsFunc func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultConsensusParams, error) + +func makeConsensusParamsFunc(c *lrpc.Client) rpcConsensusParamsFunc { + return func(ctx *rpctypes.Context, height *int64) (*ctypes.ResultConsensusParams, error) { + return c.ConsensusParams(ctx.Context(), height) + } +} + +type rpcUnconfirmedTxsFunc func(ctx *rpctypes.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) + +func makeUnconfirmedTxsFunc(c *lrpc.Client) rpcUnconfirmedTxsFunc { + return func(ctx *rpctypes.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) { + return c.UnconfirmedTxs(ctx.Context(), limit) + } +} + +type rpcNumUnconfirmedTxsFunc func(ctx *rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, error) + +func makeNumUnconfirmedTxsFunc(c *lrpc.Client) rpcNumUnconfirmedTxsFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, error) { + return c.NumUnconfirmedTxs(ctx.Context()) + } +} + +type rpcBroadcastTxCommitFunc func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) + +func makeBroadcastTxCommitFunc(c *lrpc.Client) rpcBroadcastTxCommitFunc { + return func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { + return c.BroadcastTxCommit(ctx.Context(), tx) + } +} + +type rpcBroadcastTxSyncFunc func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) + +func makeBroadcastTxSyncFunc(c *lrpc.Client) rpcBroadcastTxSyncFunc { + return func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.BroadcastTxSync(ctx.Context(), tx) + } +} + +type rpcBroadcastTxAsyncFunc func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) + +func makeBroadcastTxAsyncFunc(c *lrpc.Client) rpcBroadcastTxAsyncFunc { + return func(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.BroadcastTxAsync(ctx.Context(), tx) + } +} + +type rpcABCIQueryFunc func(ctx *rpctypes.Context, path string, + data bytes.HexBytes, height int64, prove bool) (*ctypes.ResultABCIQuery, error) + +func makeABCIQueryFunc(c *lrpc.Client) rpcABCIQueryFunc { + return func(ctx *rpctypes.Context, path string, data bytes.HexBytes, + height int64, prove bool, + ) (*ctypes.ResultABCIQuery, error) { + return c.ABCIQueryWithOptions(ctx.Context(), path, data, rpcclient.ABCIQueryOptions{ + Height: height, + Prove: prove, + }) + } +} + +type rpcABCIInfoFunc func(ctx *rpctypes.Context) (*ctypes.ResultABCIInfo, error) + +func makeABCIInfoFunc(c *lrpc.Client) rpcABCIInfoFunc { + return func(ctx *rpctypes.Context) (*ctypes.ResultABCIInfo, error) { + return c.ABCIInfo(ctx.Context()) + } +} + +type rpcBroadcastEvidenceFunc func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) + +func makeBroadcastEvidenceFunc(c *lrpc.Client) rpcBroadcastEvidenceFunc { + return func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { + return c.BroadcastEvidence(ctx.Context(), ev) + } +} diff --git a/light/rpc/client.go b/light/rpc/client.go new file mode 100644 index 0000000..e625896 --- /dev/null +++ b/light/rpc/client.go @@ -0,0 +1,680 @@ +package rpc + +import ( + "bytes" + "context" + "errors" + "fmt" + "regexp" + "time" + + "github.com/cometbft/cometbft/crypto/merkle" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtmath "github.com/cometbft/cometbft/libs/math" + service "github.com/cometbft/cometbft/libs/service" + rpcclient "github.com/cometbft/cometbft/rpc/client" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +var errNegOrZeroHeight = errors.New("negative or zero height") + +// KeyPathFunc builds a merkle path out of the given path and key. +type KeyPathFunc func(path string, key []byte) (merkle.KeyPath, error) + +// LightClient is an interface that contains functionality needed by Client from the light client. +// +//go:generate ../../scripts/mockery_generate.sh LightClient +type LightClient interface { + ChainID() string + Update(ctx context.Context, now time.Time) (*types.LightBlock, error) + VerifyLightBlockAtHeight(ctx context.Context, height int64, now time.Time) (*types.LightBlock, error) + TrustedLightBlock(height int64) (*types.LightBlock, error) +} + +var _ rpcclient.Client = (*Client)(nil) + +// Client is an RPC client, which uses light#Client to verify data (if it can +// be proved). Note, merkle.DefaultProofRuntime is used to verify values +// returned by ABCI#Query. +type Client struct { + service.BaseService + + next rpcclient.Client + lc LightClient + + // proof runtime used to verify values returned by ABCIQuery + prt *merkle.ProofRuntime + keyPathFn KeyPathFunc +} + +var _ rpcclient.Client = (*Client)(nil) + +// Option allow you to tweak Client. +type Option func(*Client) + +// KeyPathFn option can be used to set a function, which parses a given path +// and builds the merkle path for the prover. It must be provided if you want +// to call ABCIQuery or ABCIQueryWithOptions. +func KeyPathFn(fn KeyPathFunc) Option { + return func(c *Client) { + c.keyPathFn = fn + } +} + +// DefaultMerkleKeyPathFn creates a function used to generate merkle key paths +// from a path string and a key. This is the default used by the cosmos SDK. +// This merkle key paths are required when verifying /abci_query calls +func DefaultMerkleKeyPathFn() KeyPathFunc { + // regexp for extracting store name from /abci_query path + storeNameRegexp := regexp.MustCompile(`\/store\/(.+)\/key`) + + return func(path string, key []byte) (merkle.KeyPath, error) { + matches := storeNameRegexp.FindStringSubmatch(path) + if len(matches) != 2 { + return nil, fmt.Errorf("can't find store name in %s using %s", path, storeNameRegexp) + } + storeName := matches[1] + + kp := merkle.KeyPath{} + kp = kp.AppendKey([]byte(storeName), merkle.KeyEncodingURL) + kp = kp.AppendKey(key, merkle.KeyEncodingURL) + return kp, nil + } +} + +// NewClient returns a new client. +func NewClient(next rpcclient.Client, lc LightClient, opts ...Option) *Client { + c := &Client{ + next: next, + lc: lc, + prt: merkle.DefaultProofRuntime(), + } + c.BaseService = *service.NewBaseService(nil, "Client", c) + for _, o := range opts { + o(c) + } + return c +} + +func (c *Client) OnStart() error { + if !c.next.IsRunning() { + return c.next.Start() + } + return nil +} + +func (c *Client) OnStop() { + if c.next.IsRunning() { + if err := c.next.Stop(); err != nil { + c.Logger.Error("Error stopping on next", "err", err) + } + } +} + +func (c *Client) Status(ctx context.Context) (*ctypes.ResultStatus, error) { + return c.next.Status(ctx) +} + +func (c *Client) ABCIInfo(ctx context.Context) (*ctypes.ResultABCIInfo, error) { + return c.next.ABCIInfo(ctx) +} + +// ABCIQuery requests proof by default. +func (c *Client) ABCIQuery(ctx context.Context, path string, data cmtbytes.HexBytes) (*ctypes.ResultABCIQuery, error) { + return c.ABCIQueryWithOptions(ctx, path, data, rpcclient.DefaultABCIQueryOptions) +} + +// ABCIQueryWithOptions returns an error if opts.Prove is false. +func (c *Client) ABCIQueryWithOptions(ctx context.Context, path string, data cmtbytes.HexBytes, + opts rpcclient.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + + // always request the proof + opts.Prove = true + + res, err := c.next.ABCIQueryWithOptions(ctx, path, data, opts) + if err != nil { + return nil, err + } + resp := res.Response + + // Validate the response. + if resp.IsErr() { + return nil, fmt.Errorf("err response code: %v", resp.Code) + } + if len(resp.Key) == 0 { + return nil, errors.New("empty key") + } + if resp.ProofOps == nil || len(resp.ProofOps.Ops) == 0 { + return nil, errors.New("no proof ops") + } + if resp.Height <= 0 { + return nil, errNegOrZeroHeight + } + + // Update the light client if we're behind. + // NOTE: AppHash for height H is in header H+1. + nextHeight := resp.Height + 1 + l, err := c.updateLightClientIfNeededTo(ctx, &nextHeight) + if err != nil { + return nil, err + } + + // Validate the value proof against the trusted header. + if resp.Value != nil { + // 1) build a Merkle key path from path and resp.Key + if c.keyPathFn == nil { + return nil, errors.New("please configure Client with KeyPathFn option") + } + + kp, err := c.keyPathFn(path, resp.Key) + if err != nil { + return nil, fmt.Errorf("can't build merkle key path: %w", err) + } + + // 2) verify value + err = c.prt.VerifyValue(resp.ProofOps, l.AppHash, kp.String(), resp.Value) + if err != nil { + return nil, fmt.Errorf("verify value proof: %w", err) + } + } else { // OR validate the absence proof against the trusted header. + err = c.prt.VerifyAbsence(resp.ProofOps, l.AppHash, string(resp.Key)) + if err != nil { + return nil, fmt.Errorf("verify absence proof: %w", err) + } + } + + return &ctypes.ResultABCIQuery{Response: resp}, nil +} + +func (c *Client) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { + return c.next.BroadcastTxCommit(ctx, tx) +} + +func (c *Client) BroadcastTxAsync(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.next.BroadcastTxAsync(ctx, tx) +} + +func (c *Client) BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.next.BroadcastTxSync(ctx, tx) +} + +func (c *Client) UnconfirmedTxs(ctx context.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) { + return c.next.UnconfirmedTxs(ctx, limit) +} + +func (c *Client) NumUnconfirmedTxs(ctx context.Context) (*ctypes.ResultUnconfirmedTxs, error) { + return c.next.NumUnconfirmedTxs(ctx) +} + +func (c *Client) CheckTx(ctx context.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) { + return c.next.CheckTx(ctx, tx) +} + +func (c *Client) NetInfo(ctx context.Context) (*ctypes.ResultNetInfo, error) { + return c.next.NetInfo(ctx) +} + +func (c *Client) DumpConsensusState(ctx context.Context) (*ctypes.ResultDumpConsensusState, error) { + return c.next.DumpConsensusState(ctx) +} + +func (c *Client) ConsensusState(ctx context.Context) (*ctypes.ResultConsensusState, error) { + return c.next.ConsensusState(ctx) +} + +func (c *Client) ConsensusParams(ctx context.Context, height *int64) (*ctypes.ResultConsensusParams, error) { + res, err := c.next.ConsensusParams(ctx, height) + if err != nil { + return nil, err + } + + // Validate res. + if err := res.ConsensusParams.ValidateBasic(); err != nil { + return nil, err + } + if res.BlockHeight <= 0 { + return nil, errNegOrZeroHeight + } + + // Update the light client if we're behind. + l, err := c.updateLightClientIfNeededTo(ctx, &res.BlockHeight) + if err != nil { + return nil, err + } + + // Verify hash. + if cH, tH := res.ConsensusParams.Hash(), l.ConsensusHash; !bytes.Equal(cH, tH) { + return nil, fmt.Errorf("params hash %X does not match trusted hash %X", + cH, tH) + } + + return res, nil +} + +func (c *Client) Health(ctx context.Context) (*ctypes.ResultHealth, error) { + return c.next.Health(ctx) +} + +// BlockchainInfo calls rpcclient#BlockchainInfo and then verifies every header +// returned. +func (c *Client) BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) { + res, err := c.next.BlockchainInfo(ctx, minHeight, maxHeight) + if err != nil { + return nil, err + } + + // Validate res. + for i, meta := range res.BlockMetas { + if meta == nil { + return nil, fmt.Errorf("nil block meta %d", i) + } + if err := meta.ValidateBasic(); err != nil { + return nil, fmt.Errorf("invalid block meta %d: %w", i, err) + } + } + + // Update the light client if we're behind. + if len(res.BlockMetas) > 0 { + lastHeight := res.BlockMetas[len(res.BlockMetas)-1].Header.Height + if _, err := c.updateLightClientIfNeededTo(ctx, &lastHeight); err != nil { + return nil, err + } + } + + // Verify each of the BlockMetas. + for _, meta := range res.BlockMetas { + h, err := c.lc.TrustedLightBlock(meta.Header.Height) + if err != nil { + return nil, fmt.Errorf("trusted header %d: %w", meta.Header.Height, err) + } + if bmH, tH := meta.Header.Hash(), h.Hash(); !bytes.Equal(bmH, tH) { + return nil, fmt.Errorf("block meta header %X does not match with trusted header %X", + bmH, tH) + } + } + + return res, nil +} + +func (c *Client) Genesis(ctx context.Context) (*ctypes.ResultGenesis, error) { + return c.next.Genesis(ctx) +} + +func (c *Client) GenesisChunked(ctx context.Context, id uint) (*ctypes.ResultGenesisChunk, error) { + return c.next.GenesisChunked(ctx, id) +} + +// Block calls rpcclient#Block and then verifies the result. +func (c *Client) Block(ctx context.Context, height *int64) (*ctypes.ResultBlock, error) { + res, err := c.next.Block(ctx, height) + if err != nil { + return nil, err + } + + // Validate res. + if err := res.BlockID.ValidateBasic(); err != nil { + return nil, err + } + if err := res.Block.ValidateBasic(); err != nil { + return nil, err + } + if bmH, bH := res.BlockID.Hash, res.Block.Hash(); !bytes.Equal(bmH, bH) { + return nil, fmt.Errorf("blockID %X does not match with block %X", + bmH, bH) + } + + // Update the light client if we're behind. + l, err := c.updateLightClientIfNeededTo(ctx, &res.Block.Height) + if err != nil { + return nil, err + } + + // Verify block. + if bH, tH := res.Block.Hash(), l.Hash(); !bytes.Equal(bH, tH) { + return nil, fmt.Errorf("block header %X does not match with trusted header %X", + bH, tH) + } + + return res, nil +} + +// BlockByHash calls rpcclient#BlockByHash and then verifies the result. +func (c *Client) BlockByHash(ctx context.Context, hash []byte) (*ctypes.ResultBlock, error) { + res, err := c.next.BlockByHash(ctx, hash) + if err != nil { + return nil, err + } + + // Validate res. + if err := res.BlockID.ValidateBasic(); err != nil { + return nil, err + } + if err := res.Block.ValidateBasic(); err != nil { + return nil, err + } + if bmH, bH := res.BlockID.Hash, res.Block.Hash(); !bytes.Equal(bmH, bH) { + return nil, fmt.Errorf("blockID %X does not match with block %X", + bmH, bH) + } + + // Update the light client if we're behind. + l, err := c.updateLightClientIfNeededTo(ctx, &res.Block.Height) + if err != nil { + return nil, err + } + + // Verify block. + if bH, tH := res.Block.Hash(), l.Hash(); !bytes.Equal(bH, tH) { + return nil, fmt.Errorf("block header %X does not match with trusted header %X", + bH, tH) + } + + return res, nil +} + +// BlockResults returns the block results for the given height. If no height is +// provided, the results of the block preceding the latest are returned. +// NOTE: Light client only verifies the tx results +func (c *Client) BlockResults(ctx context.Context, height *int64) (*ctypes.ResultBlockResults, error) { + var h int64 + if height == nil { + res, err := c.next.Status(ctx) + if err != nil { + return nil, fmt.Errorf("can't get latest height: %w", err) + } + // Can't return the latest block results here because we won't be able to + // prove them. Return the results for the previous block instead. + h = res.SyncInfo.LatestBlockHeight - 1 + } else { + h = *height + } + + res, err := c.next.BlockResults(ctx, &h) + if err != nil { + return nil, err + } + + // Validate res. + if res.Height <= 0 { + return nil, errNegOrZeroHeight + } + + // Update the light client if we're behind. + nextHeight := h + 1 + trustedBlock, err := c.updateLightClientIfNeededTo(ctx, &nextHeight) + if err != nil { + return nil, err + } + + // Build a Merkle tree out of the above 3 binary slices. + rH := state.TxResultsHash(res.TxsResults) + + // Verify block results. + if !bytes.Equal(rH, trustedBlock.LastResultsHash) { + return nil, fmt.Errorf("last results %X does not match with trusted last results %X", + rH, trustedBlock.LastResultsHash) + } + + return res, nil +} + +// Header fetches and verifies the header directly via the light client +func (c *Client) Header(ctx context.Context, height *int64) (*ctypes.ResultHeader, error) { + lb, err := c.updateLightClientIfNeededTo(ctx, height) + if err != nil { + return nil, err + } + + return &ctypes.ResultHeader{Header: lb.Header}, nil +} + +// HeaderByHash calls rpcclient#HeaderByHash and updates the client if it's falling behind. +func (c *Client) HeaderByHash(ctx context.Context, hash cmtbytes.HexBytes) (*ctypes.ResultHeader, error) { + res, err := c.next.HeaderByHash(ctx, hash) + if err != nil { + return nil, err + } + + if err := res.Header.ValidateBasic(); err != nil { + return nil, err + } + + lb, err := c.updateLightClientIfNeededTo(ctx, &res.Header.Height) + if err != nil { + return nil, err + } + + if !bytes.Equal(lb.Hash(), res.Header.Hash()) { + return nil, fmt.Errorf("primary header hash does not match trusted header hash. (%X != %X)", + lb.Hash(), res.Header.Hash()) + } + + return res, nil +} + +func (c *Client) Commit(ctx context.Context, height *int64) (*ctypes.ResultCommit, error) { + // Update the light client if we're behind and retrieve the light block at the requested height + // or at the latest height if no height is provided. + l, err := c.updateLightClientIfNeededTo(ctx, height) + if err != nil { + return nil, err + } + + return &ctypes.ResultCommit{ + SignedHeader: *l.SignedHeader, + CanonicalCommit: true, + }, nil +} + +// Tx calls rpcclient#Tx method and then verifies the proof if such was +// requested. +func (c *Client) Tx(ctx context.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) { + res, err := c.next.Tx(ctx, hash, prove) + if err != nil || !prove { + return res, err + } + + // Validate res. + if res.Height <= 0 { + return nil, errNegOrZeroHeight + } + + // Update the light client if we're behind. + l, err := c.updateLightClientIfNeededTo(ctx, &res.Height) + if err != nil { + return nil, err + } + + // Validate the proof. + return res, res.Proof.Validate(l.DataHash) +} + +func (c *Client) TxSearch( + ctx context.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, +) (*ctypes.ResultTxSearch, error) { + return c.next.TxSearch(ctx, query, prove, page, perPage, orderBy) +} + +func (c *Client) BlockSearch( + ctx context.Context, + query string, + page, perPage *int, + orderBy string, +) (*ctypes.ResultBlockSearch, error) { + return c.next.BlockSearch(ctx, query, page, perPage, orderBy) +} + +// Validators fetches and verifies validators. +func (c *Client) Validators( + ctx context.Context, + height *int64, + pagePtr, perPagePtr *int, +) (*ctypes.ResultValidators, error) { + + // Update the light client if we're behind and retrieve the light block at the + // requested height or at the latest height if no height is provided. + l, err := c.updateLightClientIfNeededTo(ctx, height) + if err != nil { + return nil, err + } + + totalCount := len(l.ValidatorSet.Validators) + perPage := validatePerPage(perPagePtr) + page, err := validatePage(pagePtr, perPage, totalCount) + if err != nil { + return nil, err + } + + skipCount := validateSkipCount(page, perPage) + v := l.ValidatorSet.Validators[skipCount : skipCount+cmtmath.MinInt(perPage, totalCount-skipCount)] + + return &ctypes.ResultValidators{ + BlockHeight: l.Height, + Validators: v, + Count: len(v), + Total: totalCount}, nil +} + +func (c *Client) BroadcastEvidence(ctx context.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { + return c.next.BroadcastEvidence(ctx, ev) +} + +func (c *Client) Subscribe(ctx context.Context, subscriber, query string, + outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) { + return c.next.Subscribe(ctx, subscriber, query, outCapacity...) +} + +func (c *Client) Unsubscribe(ctx context.Context, subscriber, query string) error { + return c.next.Unsubscribe(ctx, subscriber, query) +} + +func (c *Client) UnsubscribeAll(ctx context.Context, subscriber string) error { + return c.next.UnsubscribeAll(ctx, subscriber) +} + +func (c *Client) updateLightClientIfNeededTo(ctx context.Context, height *int64) (*types.LightBlock, error) { + var ( + l *types.LightBlock + err error + ) + if height == nil { + l, err = c.lc.Update(ctx, time.Now()) + } else { + l, err = c.lc.VerifyLightBlockAtHeight(ctx, *height, time.Now()) + } + if err != nil { + return nil, fmt.Errorf("failed to update light client to %d: %w", *height, err) + } + return l, nil +} + +func (c *Client) RegisterOpDecoder(typ string, dec merkle.OpDecoder) { + c.prt.RegisterOpDecoder(typ, dec) +} + +// SubscribeWS subscribes for events using the given query and remote address as +// a subscriber, but does not verify responses (UNSAFE)! +// TODO: verify data +func (c *Client) SubscribeWS(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, error) { + out, err := c.next.Subscribe(context.Background(), ctx.RemoteAddr(), query) + if err != nil { + return nil, err + } + + go func() { + for { + select { + case resultEvent := <-out: + // We should have a switch here that performs a validation + // depending on the event's type. + ctx.WSConn.TryWriteRPCResponse( + rpctypes.NewRPCSuccessResponse( + rpctypes.JSONRPCStringID(fmt.Sprintf("%v#event", ctx.JSONReq.ID)), + resultEvent, + )) + case <-c.Quit(): + return + } + } + }() + + return &ctypes.ResultSubscribe{}, nil +} + +// UnsubscribeWS calls original client's Unsubscribe using remote address as a +// subscriber. +func (c *Client) UnsubscribeWS(ctx *rpctypes.Context, query string) (*ctypes.ResultUnsubscribe, error) { + err := c.next.Unsubscribe(context.Background(), ctx.RemoteAddr(), query) + if err != nil { + return nil, err + } + return &ctypes.ResultUnsubscribe{}, nil +} + +// UnsubscribeAllWS calls original client's UnsubscribeAll using remote address +// as a subscriber. +func (c *Client) UnsubscribeAllWS(ctx *rpctypes.Context) (*ctypes.ResultUnsubscribe, error) { + err := c.next.UnsubscribeAll(context.Background(), ctx.RemoteAddr()) + if err != nil { + return nil, err + } + return &ctypes.ResultUnsubscribe{}, nil +} + +// XXX: Copied from rpc/core/env.go +const ( + // see README + defaultPerPage = 30 + maxPerPage = 100 +) + +func validatePage(pagePtr *int, perPage, totalCount int) (int, error) { + if perPage < 1 { + panic(fmt.Sprintf("zero or negative perPage: %d", perPage)) + } + + if pagePtr == nil { // no page parameter + return 1, nil + } + + pages := ((totalCount - 1) / perPage) + 1 + if pages == 0 { + pages = 1 // one page (even if it's empty) + } + page := *pagePtr + if page <= 0 || page > pages { + return 1, fmt.Errorf("page should be within [1, %d] range, given %d", pages, page) + } + + return page, nil +} + +func validatePerPage(perPagePtr *int) int { + if perPagePtr == nil { // no per_page parameter + return defaultPerPage + } + + perPage := *perPagePtr + if perPage < 1 { + return defaultPerPage + } else if perPage > maxPerPage { + return maxPerPage + } + return perPage +} + +func validateSkipCount(page, perPage int) int { + skipCount := (page - 1) * perPage + if skipCount < 0 { + return 0 + } + + return skipCount +} diff --git a/light/rpc/mocks/light_client.go b/light/rpc/mocks/light_client.go new file mode 100644 index 0000000..fcebe7a --- /dev/null +++ b/light/rpc/mocks/light_client.go @@ -0,0 +1,140 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + time "time" + + types "github.com/cometbft/cometbft/types" +) + +// LightClient is an autogenerated mock type for the LightClient type +type LightClient struct { + mock.Mock +} + +// ChainID provides a mock function with no fields +func (_m *LightClient) ChainID() string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for ChainID") + } + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// TrustedLightBlock provides a mock function with given fields: height +func (_m *LightClient) TrustedLightBlock(height int64) (*types.LightBlock, error) { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for TrustedLightBlock") + } + + var r0 *types.LightBlock + var r1 error + if rf, ok := ret.Get(0).(func(int64) (*types.LightBlock, error)); ok { + return rf(height) + } + if rf, ok := ret.Get(0).(func(int64) *types.LightBlock); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.LightBlock) + } + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Update provides a mock function with given fields: ctx, now +func (_m *LightClient) Update(ctx context.Context, now time.Time) (*types.LightBlock, error) { + ret := _m.Called(ctx, now) + + if len(ret) == 0 { + panic("no return value specified for Update") + } + + var r0 *types.LightBlock + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, time.Time) (*types.LightBlock, error)); ok { + return rf(ctx, now) + } + if rf, ok := ret.Get(0).(func(context.Context, time.Time) *types.LightBlock); ok { + r0 = rf(ctx, now) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.LightBlock) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, time.Time) error); ok { + r1 = rf(ctx, now) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// VerifyLightBlockAtHeight provides a mock function with given fields: ctx, height, now +func (_m *LightClient) VerifyLightBlockAtHeight(ctx context.Context, height int64, now time.Time) (*types.LightBlock, error) { + ret := _m.Called(ctx, height, now) + + if len(ret) == 0 { + panic("no return value specified for VerifyLightBlockAtHeight") + } + + var r0 *types.LightBlock + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, int64, time.Time) (*types.LightBlock, error)); ok { + return rf(ctx, height, now) + } + if rf, ok := ret.Get(0).(func(context.Context, int64, time.Time) *types.LightBlock); ok { + r0 = rf(ctx, height, now) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.LightBlock) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, int64, time.Time) error); ok { + r1 = rf(ctx, height, now) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewLightClient creates a new instance of LightClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLightClient(t interface { + mock.TestingT + Cleanup(func()) +}) *LightClient { + mock := &LightClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/light/setup.go b/light/setup.go new file mode 100644 index 0000000..682f29e --- /dev/null +++ b/light/setup.go @@ -0,0 +1,80 @@ +package light + +import ( + "context" + "time" + + "github.com/cometbft/cometbft/light/provider" + "github.com/cometbft/cometbft/light/provider/http" + "github.com/cometbft/cometbft/light/store" +) + +// NewHTTPClient initiates an instance of a light client using HTTP addresses +// for both the primary provider and witnesses of the light client. A trusted +// header and hash must be passed to initialize the client. +// +// See all Option(s) for the additional configuration. +// See NewClient. +func NewHTTPClient( + ctx context.Context, + chainID string, + trustOptions TrustOptions, + primaryAddress string, + witnessesAddresses []string, + trustedStore store.Store, + options ...Option) (*Client, error) { + + providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) + if err != nil { + return nil, err + } + + return NewClient( + ctx, + chainID, + trustOptions, + providers[len(providers)-1], + providers[:len(providers)-1], + trustedStore, + options...) +} + +// NewHTTPClientFromTrustedStore initiates an instance of a light client using +// HTTP addresses for both the primary provider and witnesses and uses a +// trusted store as the root of trust. +// +// See all Option(s) for the additional configuration. +// See NewClientFromTrustedStore. +func NewHTTPClientFromTrustedStore( + chainID string, + trustingPeriod time.Duration, + primaryAddress string, + witnessesAddresses []string, + trustedStore store.Store, + options ...Option) (*Client, error) { + + providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) + if err != nil { + return nil, err + } + + return NewClientFromTrustedStore( + chainID, + trustingPeriod, + providers[len(providers)-1], + providers[:len(providers)-1], + trustedStore, + options...) +} + +func providersFromAddresses(addrs []string, chainID string) ([]provider.Provider, error) { + providers := make([]provider.Provider, len(addrs)) + for idx, address := range addrs { + p, err := http.New(chainID, address) + if err != nil { + return nil, err + } + providers[idx] = p + } + return providers, nil +} diff --git a/light/store/db/db.go b/light/store/db/db.go new file mode 100644 index 0000000..78fa573 --- /dev/null +++ b/light/store/db/db.go @@ -0,0 +1,327 @@ +package db + +import ( + "encoding/binary" + "fmt" + "regexp" + "strconv" + + dbm "github.com/cometbft/cometbft-db" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/light/store" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +var sizeKey = []byte("size") + +type dbs struct { + db dbm.DB + prefix string + + mtx cmtsync.RWMutex + size uint16 +} + +// New returns a Store that wraps any DB (with an optional prefix in case you +// want to use one DB with many light clients). +func New(db dbm.DB, prefix string) store.Store { + size := uint16(0) + bz, err := db.Get(sizeKey) + if err == nil && len(bz) > 0 { + size = unmarshalSize(bz) + } + + return &dbs{db: db, prefix: prefix, size: size} +} + +// SaveLightBlock persists LightBlock to the db. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) SaveLightBlock(lb *types.LightBlock) error { + if lb.Height <= 0 { + panic("negative or zero height") + } + + lbpb, err := lb.ToProto() + if err != nil { + return fmt.Errorf("unable to convert light block to protobuf: %w", err) + } + + lbBz, err := lbpb.Marshal() + if err != nil { + return fmt.Errorf("marshaling LightBlock: %w", err) + } + + s.mtx.Lock() + defer s.mtx.Unlock() + + b := s.db.NewBatch() + defer b.Close() + if err = b.Set(s.lbKey(lb.Height), lbBz); err != nil { + return err + } + if err = b.Set(sizeKey, marshalSize(s.size+1)); err != nil { + return err + } + if err = b.WriteSync(); err != nil { + return err + } + s.size++ + + return nil +} + +// DeleteLightBlockAndValidatorSet deletes the LightBlock from +// the db. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) DeleteLightBlock(height int64) error { + if height <= 0 { + panic("negative or zero height") + } + + s.mtx.Lock() + defer s.mtx.Unlock() + + b := s.db.NewBatch() + defer b.Close() + if err := b.Delete(s.lbKey(height)); err != nil { + return err + } + if err := b.Set(sizeKey, marshalSize(s.size-1)); err != nil { + return err + } + if err := b.WriteSync(); err != nil { + return err + } + s.size-- + + return nil +} + +// LightBlock retrieves the LightBlock at the given height. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) LightBlock(height int64) (*types.LightBlock, error) { + if height <= 0 { + panic("negative or zero height") + } + + bz, err := s.db.Get(s.lbKey(height)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil, store.ErrLightBlockNotFound + } + + var lbpb cmtproto.LightBlock + err = lbpb.Unmarshal(bz) + if err != nil { + return nil, fmt.Errorf("unmarshal error: %w", err) + } + + lightBlock, err := types.LightBlockFromProto(&lbpb) + if err != nil { + return nil, fmt.Errorf("proto conversion error: %w", err) + } + + return lightBlock, err +} + +// LastLightBlockHeight returns the last LightBlock height stored. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) LastLightBlockHeight() (int64, error) { + itr, err := s.db.ReverseIterator( + s.lbKey(1), + append(s.lbKey(1<<63-1), byte(0x00)), + ) + if err != nil { + panic(err) + } + defer itr.Close() + + for itr.Valid() { + key := itr.Key() + _, height, ok := parseLbKey(key) + if ok { + return height, nil + } + itr.Next() + } + + return -1, itr.Error() +} + +// FirstLightBlockHeight returns the first LightBlock height stored. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) FirstLightBlockHeight() (int64, error) { + itr, err := s.db.Iterator( + s.lbKey(1), + append(s.lbKey(1<<63-1), byte(0x00)), + ) + if err != nil { + panic(err) + } + defer itr.Close() + + for itr.Valid() { + key := itr.Key() + _, height, ok := parseLbKey(key) + if ok { + return height, nil + } + itr.Next() + } + + return -1, itr.Error() +} + +// LightBlockBefore iterates over light blocks until it finds a block before +// the given height. It returns ErrLightBlockNotFound if no such block exists. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) LightBlockBefore(height int64) (*types.LightBlock, error) { + if height <= 0 { + panic("negative or zero height") + } + + itr, err := s.db.ReverseIterator( + s.lbKey(1), + s.lbKey(height), + ) + if err != nil { + panic(err) + } + defer itr.Close() + + for itr.Valid() { + key := itr.Key() + _, existingHeight, ok := parseLbKey(key) + if ok { + return s.LightBlock(existingHeight) + } + itr.Next() + } + if err = itr.Error(); err != nil { + return nil, err + } + + return nil, store.ErrLightBlockNotFound +} + +// Prune prunes header & validator set pairs until there are only size pairs +// left. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) Prune(size uint16) error { + // 1) Check how many we need to prune. + s.mtx.RLock() + sSize := s.size + s.mtx.RUnlock() + + if sSize <= size { // nothing to prune + return nil + } + numToPrune := sSize - size + + // 2) Iterate over headers and perform a batch operation. + itr, err := s.db.Iterator( + s.lbKey(1), + append(s.lbKey(1<<63-1), byte(0x00)), + ) + if err != nil { + return err + } + defer itr.Close() + + b := s.db.NewBatch() + defer b.Close() + + pruned := 0 + for itr.Valid() && numToPrune > 0 { + key := itr.Key() + _, height, ok := parseLbKey(key) + if ok { + if err = b.Delete(s.lbKey(height)); err != nil { + return err + } + } + itr.Next() + numToPrune-- + pruned++ + } + if err = itr.Error(); err != nil { + return err + } + + err = b.WriteSync() + if err != nil { + return err + } + + // 3) Update size. + s.mtx.Lock() + defer s.mtx.Unlock() + + s.size -= uint16(pruned) + + if wErr := s.db.SetSync(sizeKey, marshalSize(s.size)); wErr != nil { + return fmt.Errorf("failed to persist size: %w", wErr) + } + + return nil +} + +// Size returns the number of header & validator set pairs. +// +// Safe for concurrent use by multiple goroutines. +func (s *dbs) Size() uint16 { + s.mtx.RLock() + defer s.mtx.RUnlock() + return s.size +} + +func (s *dbs) lbKey(height int64) []byte { + return []byte(fmt.Sprintf("lb/%s/%020d", s.prefix, height)) +} + +var keyPattern = regexp.MustCompile(`^(lb)/([^/]*)/([0-9]+)$`) + +func parseKey(key []byte) (part string, prefix string, height int64, ok bool) { + submatch := keyPattern.FindSubmatch(key) + if submatch == nil { + return "", "", 0, false + } + part = string(submatch[1]) + prefix = string(submatch[2]) + height, err := strconv.ParseInt(string(submatch[3]), 10, 64) + if err != nil { + return "", "", 0, false + } + ok = true // good! + return +} + +func parseLbKey(key []byte) (prefix string, height int64, ok bool) { + var part string + part, prefix, height, ok = parseKey(key) + if part != "lb" { + return "", 0, false + } + return +} + +func marshalSize(size uint16) []byte { + bs := make([]byte, 2) + binary.LittleEndian.PutUint16(bs, size) + return bs +} + +func unmarshalSize(bz []byte) uint16 { + return binary.LittleEndian.Uint16(bz) +} diff --git a/light/store/db/db_test.go b/light/store/db/db_test.go new file mode 100644 index 0000000..62e635d --- /dev/null +++ b/light/store/db/db_test.go @@ -0,0 +1,196 @@ +package db + +import ( + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +func TestLast_FirstLightBlockHeight(t *testing.T) { + dbStore := New(dbm.NewMemDB(), "TestLast_FirstLightBlockHeight") + + // Empty store + height, err := dbStore.LastLightBlockHeight() + require.NoError(t, err) + assert.EqualValues(t, -1, height) + + height, err = dbStore.FirstLightBlockHeight() + require.NoError(t, err) + assert.EqualValues(t, -1, height) + + // 1 key + err = dbStore.SaveLightBlock(randLightBlock(int64(1))) + require.NoError(t, err) + + height, err = dbStore.LastLightBlockHeight() + require.NoError(t, err) + assert.EqualValues(t, 1, height) + + height, err = dbStore.FirstLightBlockHeight() + require.NoError(t, err) + assert.EqualValues(t, 1, height) +} + +func Test_SaveLightBlock(t *testing.T) { + dbStore := New(dbm.NewMemDB(), "Test_SaveLightBlockAndValidatorSet") + + // Empty store + h, err := dbStore.LightBlock(1) + require.Error(t, err) + assert.Nil(t, h) + + // 1 key + err = dbStore.SaveLightBlock(randLightBlock(1)) + require.NoError(t, err) + + size := dbStore.Size() + assert.Equal(t, uint16(1), size) + t.Log(size) + + h, err = dbStore.LightBlock(1) + require.NoError(t, err) + assert.NotNil(t, h) + + // Empty store + err = dbStore.DeleteLightBlock(1) + require.NoError(t, err) + + h, err = dbStore.LightBlock(1) + require.Error(t, err) + assert.Nil(t, h) +} + +func Test_LightBlockBefore(t *testing.T) { + dbStore := New(dbm.NewMemDB(), "Test_LightBlockBefore") + + assert.Panics(t, func() { + _, _ = dbStore.LightBlockBefore(0) + _, _ = dbStore.LightBlockBefore(100) + }) + + err := dbStore.SaveLightBlock(randLightBlock(int64(2))) + require.NoError(t, err) + + h, err := dbStore.LightBlockBefore(3) + require.NoError(t, err) + if assert.NotNil(t, h) { + assert.EqualValues(t, 2, h.Height) + } +} + +func Test_Prune(t *testing.T) { + dbStore := New(dbm.NewMemDB(), "Test_Prune") + + // Empty store + assert.EqualValues(t, 0, dbStore.Size()) + err := dbStore.Prune(0) + require.NoError(t, err) + + // One header + err = dbStore.SaveLightBlock(randLightBlock(2)) + require.NoError(t, err) + + assert.EqualValues(t, 1, dbStore.Size()) + + err = dbStore.Prune(1) + require.NoError(t, err) + assert.EqualValues(t, 1, dbStore.Size()) + + err = dbStore.Prune(0) + require.NoError(t, err) + assert.EqualValues(t, 0, dbStore.Size()) + + // Multiple headers + for i := 1; i <= 10; i++ { + err = dbStore.SaveLightBlock(randLightBlock(int64(i))) + require.NoError(t, err) + } + + err = dbStore.Prune(11) + require.NoError(t, err) + assert.EqualValues(t, 10, dbStore.Size()) + + err = dbStore.Prune(7) + require.NoError(t, err) + assert.EqualValues(t, 7, dbStore.Size()) +} + +func Test_Concurrency(t *testing.T) { + dbStore := New(dbm.NewMemDB(), "Test_Prune") + + var wg sync.WaitGroup + for i := 1; i <= 100; i++ { + wg.Add(1) + go func(i int64) { + defer wg.Done() + + err := dbStore.SaveLightBlock(randLightBlock(i)) + require.NoError(t, err) + + _, err = dbStore.LightBlock(i) + if err != nil { + t.Log(err) + } + + _, err = dbStore.LastLightBlockHeight() + if err != nil { + t.Log(err) + } + _, err = dbStore.FirstLightBlockHeight() + if err != nil { + t.Log(err) + } + + err = dbStore.Prune(2) + if err != nil { + t.Log(err) + } + _ = dbStore.Size() + + err = dbStore.DeleteLightBlock(1) + if err != nil { + t.Log(err) + } + }(int64(i)) + } + + wg.Wait() +} + +func randLightBlock(height int64) *types.LightBlock { + vals, _ := types.RandValidatorSet(2, 1) + return &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: &types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 0}, + ChainID: cmtrand.Str(12), + Height: height, + Time: time.Now(), + LastBlockID: types.BlockID{}, + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: crypto.CRandBytes(tmhash.Size), + NextValidatorsHash: crypto.CRandBytes(tmhash.Size), + ConsensusHash: crypto.CRandBytes(tmhash.Size), + AppHash: crypto.CRandBytes(tmhash.Size), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + }, + Commit: &types.Commit{}, + }, + ValidatorSet: vals, + } +} diff --git a/light/store/errors.go b/light/store/errors.go new file mode 100644 index 0000000..33be0ca --- /dev/null +++ b/light/store/errors.go @@ -0,0 +1,9 @@ +package store + +import "errors" + +var ( + // ErrLightBlockNotFound is returned when a store does not have the + // requested header. + ErrLightBlockNotFound = errors.New("light block not found") +) diff --git a/light/store/store.go b/light/store/store.go new file mode 100644 index 0000000..d65239b --- /dev/null +++ b/light/store/store.go @@ -0,0 +1,48 @@ +package store + +import "github.com/cometbft/cometbft/types" + +// Store is anything that can persistently store headers. +type Store interface { + // SaveSignedHeaderAndValidatorSet saves a SignedHeader (h: sh.Height) and a + // ValidatorSet (h: sh.Height). + // + // height must be > 0. + SaveLightBlock(lb *types.LightBlock) error + + // DeleteSignedHeaderAndValidatorSet deletes SignedHeader (h: height) and + // ValidatorSet (h: height). + // + // height must be > 0. + DeleteLightBlock(height int64) error + + // LightBlock returns the LightBlock that corresponds to the given + // height. + // + // height must be > 0. + // + // If LightBlock is not found, ErrLightBlockNotFound is returned. + LightBlock(height int64) (*types.LightBlock, error) + + // LastLightBlockHeight returns the last (newest) LightBlock height. + // + // If the store is empty, -1 and nil error are returned. + LastLightBlockHeight() (int64, error) + + // FirstLightBlockHeight returns the first (oldest) LightBlock height. + // + // If the store is empty, -1 and nil error are returned. + FirstLightBlockHeight() (int64, error) + + // LightBlockBefore returns the LightBlock before a certain height. + // + // height must be > 0 && <= LastLightBlockHeight. + LightBlockBefore(height int64) (*types.LightBlock, error) + + // Prune removes headers & the associated validator sets when Store reaches a + // defined size (number of header & validator set pairs). + Prune(size uint16) error + + // Size returns a number of currently existing header & validator set pairs. + Size() uint16 +} diff --git a/light/trust_options.go b/light/trust_options.go new file mode 100644 index 0000000..a5d80d0 --- /dev/null +++ b/light/trust_options.go @@ -0,0 +1,53 @@ +package light + +import ( + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/crypto/tmhash" +) + +// TrustOptions are the trust parameters needed when a new light client +// connects to the network or when an existing light client that has been +// offline for longer than the trusting period connects to the network. +// +// The expectation is the user will get this information from a trusted source +// like a validator, a friend, or a secure website. A more user friendly +// solution with trust tradeoffs is that we establish an https based protocol +// with a default end point that populates this information. Also an on-chain +// registry of roots-of-trust (e.g. on the Cosmos Hub) seems likely in the +// future. +type TrustOptions struct { + // tp: trusting period. + // + // Should be significantly less than the unbonding period (e.g. unbonding + // period = 3 weeks, trusting period = 2 weeks). + // + // More specifically, trusting period + time needed to check headers + time + // needed to report and punish misbehavior should be less than the unbonding + // period. + Period time.Duration + + // Header's Height and Hash must both be provided to force the trusting of a + // particular header. + Height int64 + Hash []byte +} + +// ValidateBasic performs basic validation. +func (opts TrustOptions) ValidateBasic() error { + if opts.Period <= 0 { + return errors.New("negative or zero period") + } + if opts.Height <= 0 { + return errors.New("zero or negative height") + } + if len(opts.Hash) != tmhash.Size { + return fmt.Errorf("expected hash size to be %d bytes, got %d bytes", + tmhash.Size, + len(opts.Hash), + ) + } + return nil +} diff --git a/light/verifier.go b/light/verifier.go new file mode 100644 index 0000000..721a7de --- /dev/null +++ b/light/verifier.go @@ -0,0 +1,245 @@ +package light + +import ( + "bytes" + "errors" + "fmt" + "time" + + cmtmath "github.com/cometbft/cometbft/libs/math" + "github.com/cometbft/cometbft/types" +) + +var ( + // DefaultTrustLevel - new header can be trusted if at least one correct + // validator signed it. + DefaultTrustLevel = cmtmath.Fraction{Numerator: 1, Denominator: 3} +) + +// VerifyNonAdjacent verifies non-adjacent untrustedHeader against +// trustedHeader. It ensures that: +// +// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) +// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) +// c) trustLevel ([1/3, 1]) of trustedHeaderVals (or trustedHeaderNextVals) +// signed correctly (if not, ErrNewValSetCantBeTrusted is returned) +// d) more than 2/3 of untrustedVals have signed h2 +// (otherwise, ErrInvalidHeader is returned) +// e) headers are non-adjacent. +// +// maxClockDrift defines how much untrustedHeader.Time can drift into the +// future. +func VerifyNonAdjacent( + trustedHeader *types.SignedHeader, // height=X + trustedVals *types.ValidatorSet, // height=X or height=X+1 + untrustedHeader *types.SignedHeader, // height=Y + untrustedVals *types.ValidatorSet, // height=Y + trustingPeriod time.Duration, + now time.Time, + maxClockDrift time.Duration, + trustLevel cmtmath.Fraction) error { + + if untrustedHeader.Height == trustedHeader.Height+1 { + return errors.New("headers must be non adjacent in height") + } + + if HeaderExpired(trustedHeader, trustingPeriod, now) { + return ErrOldHeaderExpired{trustedHeader.Time.Add(trustingPeriod), now} + } + + if err := verifyNewHeaderAndVals( + untrustedHeader, untrustedVals, + trustedHeader, + now, maxClockDrift); err != nil { + return ErrInvalidHeader{err} + } + + // Ensure that +`trustLevel` (default 1/3) or more of last trusted validators signed correctly. + err := trustedVals.VerifyCommitLightTrusting(trustedHeader.ChainID, untrustedHeader.Commit, trustLevel) + if err != nil { + switch e := err.(type) { + case types.ErrNotEnoughVotingPowerSigned: + return ErrNewValSetCantBeTrusted{e} + default: + return e + } + } + + // Ensure that +2/3 of new validators signed correctly. + // + // NOTE: this should always be the last check because untrustedVals can be + // intentionally made very large to DOS the light client. not the case for + // VerifyAdjacent, where validator set is known in advance. + if err := untrustedVals.VerifyCommitLight(trustedHeader.ChainID, untrustedHeader.Commit.BlockID, + untrustedHeader.Height, untrustedHeader.Commit); err != nil { + return ErrInvalidHeader{err} + } + + return nil +} + +// VerifyAdjacent verifies directly adjacent untrustedHeader against +// trustedHeader. It ensures that: +// +// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) +// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) +// c) untrustedHeader.ValidatorsHash equals trustedHeader.NextValidatorsHash +// d) more than 2/3 of new validators (untrustedVals) have signed h2 +// (otherwise, ErrInvalidHeader is returned) +// e) headers are adjacent. +// +// maxClockDrift defines how much untrustedHeader.Time can drift into the +// future. +func VerifyAdjacent( + trustedHeader *types.SignedHeader, // height=X + untrustedHeader *types.SignedHeader, // height=X+1 + untrustedVals *types.ValidatorSet, // height=X+1 + trustingPeriod time.Duration, + now time.Time, + maxClockDrift time.Duration) error { + + if untrustedHeader.Height != trustedHeader.Height+1 { + return errors.New("headers must be adjacent in height") + } + + if HeaderExpired(trustedHeader, trustingPeriod, now) { + return ErrOldHeaderExpired{trustedHeader.Time.Add(trustingPeriod), now} + } + + if err := verifyNewHeaderAndVals( + untrustedHeader, untrustedVals, + trustedHeader, + now, maxClockDrift); err != nil { + return ErrInvalidHeader{err} + } + + // Check the validator hashes are the same + if !bytes.Equal(untrustedHeader.ValidatorsHash, trustedHeader.NextValidatorsHash) { + err := fmt.Errorf("expected old header next validators (%X) to match those from new header (%X)", + trustedHeader.NextValidatorsHash, + untrustedHeader.ValidatorsHash, + ) + return err + } + + // Ensure that +2/3 of new validators signed correctly. + if err := untrustedVals.VerifyCommitLight(trustedHeader.ChainID, untrustedHeader.Commit.BlockID, + untrustedHeader.Height, untrustedHeader.Commit); err != nil { + return ErrInvalidHeader{err} + } + + return nil +} + +// Verify combines both VerifyAdjacent and VerifyNonAdjacent functions. +func Verify( + trustedHeader *types.SignedHeader, // height=X + trustedVals *types.ValidatorSet, // height=X or height=X+1 + untrustedHeader *types.SignedHeader, // height=Y + untrustedVals *types.ValidatorSet, // height=Y + trustingPeriod time.Duration, + now time.Time, + maxClockDrift time.Duration, + trustLevel cmtmath.Fraction) error { + + if untrustedHeader.Height != trustedHeader.Height+1 { + return VerifyNonAdjacent(trustedHeader, trustedVals, untrustedHeader, untrustedVals, + trustingPeriod, now, maxClockDrift, trustLevel) + } + + return VerifyAdjacent(trustedHeader, untrustedHeader, untrustedVals, trustingPeriod, now, maxClockDrift) +} + +func verifyNewHeaderAndVals( + untrustedHeader *types.SignedHeader, + untrustedVals *types.ValidatorSet, + trustedHeader *types.SignedHeader, + now time.Time, + maxClockDrift time.Duration) error { + + if err := untrustedHeader.ValidateBasic(trustedHeader.ChainID); err != nil { + return fmt.Errorf("untrustedHeader.ValidateBasic failed: %w", err) + } + + if untrustedHeader.Height <= trustedHeader.Height { + return fmt.Errorf("expected new header height %d to be greater than one of old header %d", + untrustedHeader.Height, + trustedHeader.Height) + } + + if !untrustedHeader.Time.After(trustedHeader.Time) { + return fmt.Errorf("expected new header time %v to be after old header time %v", + untrustedHeader.Time, + trustedHeader.Time) + } + + if !untrustedHeader.Time.Before(now.Add(maxClockDrift)) { + return fmt.Errorf("new header has a time from the future %v (now: %v; max clock drift: %v)", + untrustedHeader.Time, + now, + maxClockDrift) + } + + if !bytes.Equal(untrustedHeader.ValidatorsHash, untrustedVals.Hash()) { + return fmt.Errorf("expected new header validators (%X) to match those that were supplied (%X) at height %d", + untrustedHeader.ValidatorsHash, + untrustedVals.Hash(), + untrustedHeader.Height, + ) + } + + return nil +} + +// ValidateTrustLevel checks that trustLevel is within the allowed range [1/3, +// 1]. If not, it returns an error. 1/3 is the minimum amount of trust needed +// which does not break the security model. +func ValidateTrustLevel(lvl cmtmath.Fraction) error { + if lvl.Numerator*3 < lvl.Denominator || // < 1/3 + lvl.Numerator > lvl.Denominator || // > 1 + lvl.Denominator == 0 { + return fmt.Errorf("trustLevel must be within [1/3, 1], given %v", lvl) + } + return nil +} + +// HeaderExpired return true if the given header expired. +func HeaderExpired(h *types.SignedHeader, trustingPeriod time.Duration, now time.Time) bool { + expirationTime := h.Time.Add(trustingPeriod) + return !expirationTime.After(now) +} + +// VerifyBackwards verifies an untrusted header with a height one less than +// that of an adjacent trusted header. It ensures that: +// +// a) untrusted header is valid +// b) untrusted header has a time before the trusted header +// c) that the LastBlockID hash of the trusted header is the same as the hash +// of the trusted header +// +// For any of these cases ErrInvalidHeader is returned. +func VerifyBackwards(untrustedHeader, trustedHeader *types.Header) error { + if err := untrustedHeader.ValidateBasic(); err != nil { + return ErrInvalidHeader{err} + } + + if untrustedHeader.ChainID != trustedHeader.ChainID { + return ErrInvalidHeader{errors.New("header belongs to another chain")} + } + + if !untrustedHeader.Time.Before(trustedHeader.Time) { + return ErrInvalidHeader{ + fmt.Errorf("expected older header time %v to be before new header time %v", + untrustedHeader.Time, + trustedHeader.Time)} + } + + if !bytes.Equal(untrustedHeader.Hash(), trustedHeader.LastBlockID.Hash) { + return ErrInvalidHeader{ + fmt.Errorf("older header hash %X does not match trusted header's last block %X", + untrustedHeader.Hash(), + trustedHeader.LastBlockID.Hash)} + } + + return nil +} diff --git a/light/verifier_test.go b/light/verifier_test.go new file mode 100644 index 0000000..788c30d --- /dev/null +++ b/light/verifier_test.go @@ -0,0 +1,335 @@ +package light_test + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + cmtmath "github.com/cometbft/cometbft/libs/math" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/types" +) + +const ( + maxClockDrift = 10 * time.Second +) + +func TestVerifyAdjacentHeaders(t *testing.T) { + const ( + chainID = "TestVerifyAdjacentHeaders" + lastHeight = 1 + nextHeight = 2 + ) + + var ( + keys = genPrivKeys(4) + // 20, 30, 40, 50 - the first 3 don't have 2/3, the last 3 do! + vals = keys.ToValidators(20, 10) + bTime, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") + header = keys.GenSignedHeader(chainID, lastHeight, bTime, nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + ) + + testCases := []struct { + newHeader *types.SignedHeader + newVals *types.ValidatorSet + trustingPeriod time.Duration + now time.Time + expErr error + expErrText string + }{ + // same header -> no error + 0: { + header, + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "headers must be adjacent in height", + }, + // different chainID -> error + 1: { + keys.GenSignedHeader("different-chainID", nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "header belongs to another chain", + }, + // new header's time is before old header's time -> error + 2: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(-1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "to be after old header time", + }, + // new header's time is from the future -> error + 3: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(3*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "new header has a time from the future", + }, + // new header's time is from the future, but it's acceptable (< maxClockDrift) -> no error + 4: { + keys.GenSignedHeader(chainID, nextHeight, + bTime.Add(2*time.Hour).Add(maxClockDrift).Add(-1*time.Millisecond), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 3/3 signed -> no error + 5: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 2/3 signed -> no error + 6: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 1, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 1/3 signed -> error + 7: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), len(keys)-1, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + light.ErrInvalidHeader{Reason: types.ErrNotEnoughVotingPowerSigned{Got: 50, Needed: 93}}, + "", + }, + // vals does not match with what we have -> error + 8: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, keys.ToValidators(10, 1), vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + keys.ToValidators(10, 1), + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "to match those from new header", + }, + // vals are inconsistent with newHeader -> error + 9: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + keys.ToValidators(10, 1), + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "to match those that were supplied", + }, + // old header has expired -> error + 10: { + keys.GenSignedHeader(chainID, nextHeight, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + keys.ToValidators(10, 1), + 1 * time.Hour, + bTime.Add(1 * time.Hour), + nil, + "old header has expired", + }, + } + + for i, tc := range testCases { + tc := tc + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + err := light.VerifyAdjacent(header, tc.newHeader, tc.newVals, tc.trustingPeriod, tc.now, maxClockDrift) + switch { + case tc.expErr != nil && assert.Error(t, err): + assert.Equal(t, tc.expErr, err) + case tc.expErrText != "": + assert.Contains(t, err.Error(), tc.expErrText) + default: + assert.NoError(t, err) + } + }) + } + +} + +func TestVerifyNonAdjacentHeaders(t *testing.T) { + const ( + chainID = "TestVerifyNonAdjacentHeaders" + lastHeight = 1 + ) + + var ( + keys = genPrivKeys(4) + // 20, 30, 40, 50 - the first 3 don't have 2/3, the last 3 do! + vals = keys.ToValidators(20, 10) + bTime, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") + header = keys.GenSignedHeader(chainID, lastHeight, bTime, nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + + // 30, 40, 50 + twoThirds = keys[1:] + twoThirdsVals = twoThirds.ToValidators(30, 10) + + // 50 + oneThird = keys[len(keys)-1:] + oneThirdVals = oneThird.ToValidators(50, 10) + + // 20 + lessThanOneThird = keys[0:1] + lessThanOneThirdVals = lessThanOneThird.ToValidators(20, 10) + ) + + testCases := []struct { + newHeader *types.SignedHeader + newVals *types.ValidatorSet + trustingPeriod time.Duration + now time.Time + expErr error + expErrText string + }{ + // 3/3 new vals signed, 3/3 old vals present -> no error + 0: { + keys.GenSignedHeader(chainID, 3, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 2/3 new vals signed, 3/3 old vals present -> no error + 1: { + keys.GenSignedHeader(chainID, 4, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 1, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 1/3 new vals signed, 3/3 old vals present -> error + 2: { + keys.GenSignedHeader(chainID, 5, bTime.Add(1*time.Hour), nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), len(keys)-1, len(keys)), + vals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + light.ErrInvalidHeader{types.ErrNotEnoughVotingPowerSigned{Got: 50, Needed: 93}}, + "", + }, + // 3/3 new vals signed, 2/3 old vals present -> no error + 3: { + twoThirds.GenSignedHeader(chainID, 5, bTime.Add(1*time.Hour), nil, twoThirdsVals, twoThirdsVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(twoThirds)), + twoThirdsVals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 3/3 new vals signed, 1/3 old vals present -> no error + 4: { + oneThird.GenSignedHeader(chainID, 5, bTime.Add(1*time.Hour), nil, oneThirdVals, oneThirdVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(oneThird)), + oneThirdVals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + nil, + "", + }, + // 3/3 new vals signed, less than 1/3 old vals present -> error + 5: { + lessThanOneThird.GenSignedHeader(chainID, 5, bTime.Add(1*time.Hour), nil, lessThanOneThirdVals, lessThanOneThirdVals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(lessThanOneThird)), + lessThanOneThirdVals, + 3 * time.Hour, + bTime.Add(2 * time.Hour), + light.ErrNewValSetCantBeTrusted{types.ErrNotEnoughVotingPowerSigned{Got: 20, Needed: 46}}, + "", + }, + } + + for i, tc := range testCases { + tc := tc + t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { + err := light.VerifyNonAdjacent(header, vals, tc.newHeader, tc.newVals, tc.trustingPeriod, + tc.now, maxClockDrift, + light.DefaultTrustLevel) + + switch { + case tc.expErr != nil && assert.Error(t, err): + assert.Equal(t, tc.expErr, err) + case tc.expErrText != "": + assert.Contains(t, err.Error(), tc.expErrText) + default: + assert.NoError(t, err) + } + }) + } +} + +func TestVerifyReturnsErrorIfTrustLevelIsInvalid(t *testing.T) { + const ( + chainID = "TestVerifyReturnsErrorIfTrustLevelIsInvalid" + lastHeight = 1 + ) + + var ( + keys = genPrivKeys(4) + // 20, 30, 40, 50 - the first 3 don't have 2/3, the last 3 do! + vals = keys.ToValidators(20, 10) + bTime, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") + header = keys.GenSignedHeader(chainID, lastHeight, bTime, nil, vals, vals, + hash("app_hash"), hash("cons_hash"), hash("results_hash"), 0, len(keys)) + ) + + err := light.Verify(header, vals, header, vals, 2*time.Hour, time.Now(), maxClockDrift, + cmtmath.Fraction{Numerator: 2, Denominator: 1}) + assert.Error(t, err) +} + +func TestValidateTrustLevel(t *testing.T) { + testCases := []struct { + lvl cmtmath.Fraction + valid bool + }{ + // valid + 0: {cmtmath.Fraction{Numerator: 1, Denominator: 1}, true}, + 1: {cmtmath.Fraction{Numerator: 1, Denominator: 3}, true}, + 2: {cmtmath.Fraction{Numerator: 2, Denominator: 3}, true}, + 3: {cmtmath.Fraction{Numerator: 3, Denominator: 3}, true}, + 4: {cmtmath.Fraction{Numerator: 4, Denominator: 5}, true}, + + // invalid + 5: {cmtmath.Fraction{Numerator: 6, Denominator: 5}, false}, + 6: {cmtmath.Fraction{Numerator: 0, Denominator: 1}, false}, + 7: {cmtmath.Fraction{Numerator: 0, Denominator: 0}, false}, + 8: {cmtmath.Fraction{Numerator: 1, Denominator: 0}, false}, + } + + for _, tc := range testCases { + err := light.ValidateTrustLevel(tc.lvl) + if !tc.valid { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + } +} diff --git a/mempool/bench_test.go b/mempool/bench_test.go new file mode 100644 index 0000000..35fe5c4 --- /dev/null +++ b/mempool/bench_test.go @@ -0,0 +1,149 @@ +package mempool + +import ( + "sync/atomic" + "testing" + + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/proxy" + "github.com/stretchr/testify/require" +) + +func BenchmarkReap(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + mp.config.Size = 100_000_000 // so that the mempool never saturates + addTxs(b, mp, 0, 10000) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + mp.ReapMaxBytesMaxGas(100_000_000, -1) + } +} + +func BenchmarkCheckTx(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + mp.config.Size = 100_000_000 + b.ResetTimer() + + for i := 0; i < b.N; i++ { + b.StopTimer() + tx := kvstore.NewTxFromID(i) + b.StartTimer() + + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(b, err, i) + } +} + +func BenchmarkParallelCheckTx(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + mp.config.Size = 100_000_000 + var txcnt uint64 + next := func() uint64 { + return atomic.AddUint64(&txcnt, 1) + } + + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + tx := kvstore.NewTxFromID(int(next())) + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(b, err, tx) + } + }) +} + +func BenchmarkCheckDuplicateTx(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + mp.config.Size = 2 + + tx := kvstore.NewTxFromID(1) + if err := mp.CheckTx(tx, nil, TxInfo{}); err != nil { + b.Fatal(err) + } + err := mp.FlushAppConn() + require.NoError(b, err) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + err := mp.CheckTx(tx, nil, TxInfo{}) + require.ErrorAs(b, err, &ErrTxInCache, "tx should be duplicate") + } +} + +func BenchmarkUpdate(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + numTxs := 1000 + b.ResetTimer() + for i := 1; i <= b.N; i++ { + b.StopTimer() + txs := addTxs(b, mp, i*numTxs, numTxs) + require.Equal(b, len(txs), mp.Size(), len(txs)) + b.StartTimer() + + doUpdate(b, mp, int64(i), txs) + require.Zero(b, mp.Size()) + } +} + +func BenchmarkUpdateAndRecheck(b *testing.B) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + numTxs := 1000 + b.ResetTimer() + for i := 1; i <= b.N; i++ { + b.StopTimer() + mp.Flush() + txs := addTxs(b, mp, i*numTxs, numTxs) + require.Equal(b, len(txs), mp.Size(), len(txs)) + b.StartTimer() + + // Update a part of txs and recheck the rest. + doUpdate(b, mp, int64(i), txs[:numTxs/2]) + } + +} + +func BenchmarkUpdateRemoteClient(b *testing.B) { + mp, cleanup := newMempoolWithAsyncConnection(b) + defer cleanup() + + b.ResetTimer() + for i := 1; i <= b.N; i++ { + b.StopTimer() + tx := kvstore.NewTxFromID(i) + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(b, err) + err = mp.FlushAppConn() + require.NoError(b, err) + require.Equal(b, 1, mp.Size()) + b.StartTimer() + + txs := mp.ReapMaxTxs(mp.Size()) + doUpdate(b, mp, int64(i), txs) + } + +} diff --git a/mempool/cache.go b/mempool/cache.go new file mode 100644 index 0000000..9a7802f --- /dev/null +++ b/mempool/cache.go @@ -0,0 +1,120 @@ +package mempool + +import ( + "container/list" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/types" +) + +// TxCache defines an interface for raw transaction caching in a mempool. +// Currently, a TxCache does not allow direct reading or getting of transaction +// values. A TxCache is used primarily to push transactions and removing +// transactions. Pushing via Push returns a boolean telling the caller if the +// transaction already exists in the cache or not. +type TxCache interface { + // Reset resets the cache to an empty state. + Reset() + + // Push adds the given raw transaction to the cache and returns true if it was + // newly added. Otherwise, it returns false. + Push(tx types.Tx) bool + + // Remove removes the given raw transaction from the cache. + Remove(tx types.Tx) + + // Has reports whether tx is present in the cache. Checking for presence is + // not treated as an access of the value. + Has(tx types.Tx) bool +} + +var _ TxCache = (*LRUTxCache)(nil) + +// LRUTxCache maintains a thread-safe LRU cache of raw transactions. The cache +// only stores the hash of the raw transaction. +type LRUTxCache struct { + mtx cmtsync.Mutex + size int + cacheMap map[types.TxKey]*list.Element + list *list.List +} + +func NewLRUTxCache(cacheSize int) *LRUTxCache { + return &LRUTxCache{ + size: cacheSize, + cacheMap: make(map[types.TxKey]*list.Element, cacheSize), + list: list.New(), + } +} + +// GetList returns the underlying linked-list that backs the LRU cache. Note, +// this should be used for testing purposes only! +func (c *LRUTxCache) GetList() *list.List { + return c.list +} + +func (c *LRUTxCache) Reset() { + c.mtx.Lock() + defer c.mtx.Unlock() + + c.cacheMap = make(map[types.TxKey]*list.Element, c.size) + c.list.Init() +} + +func (c *LRUTxCache) Push(tx types.Tx) bool { + c.mtx.Lock() + defer c.mtx.Unlock() + + key := tx.Key() + + moved, ok := c.cacheMap[key] + if ok { + c.list.MoveToBack(moved) + return false + } + + if c.list.Len() >= c.size { + front := c.list.Front() + if front != nil { + frontKey := front.Value.(types.TxKey) + delete(c.cacheMap, frontKey) + c.list.Remove(front) + } + } + + e := c.list.PushBack(key) + c.cacheMap[key] = e + + return true +} + +func (c *LRUTxCache) Remove(tx types.Tx) { + c.mtx.Lock() + defer c.mtx.Unlock() + + key := tx.Key() + e := c.cacheMap[key] + delete(c.cacheMap, key) + + if e != nil { + c.list.Remove(e) + } +} + +func (c *LRUTxCache) Has(tx types.Tx) bool { + c.mtx.Lock() + defer c.mtx.Unlock() + + _, ok := c.cacheMap[tx.Key()] + return ok +} + +// NopTxCache defines a no-op raw transaction cache. +type NopTxCache struct{} + +var _ TxCache = (*NopTxCache)(nil) + +func (NopTxCache) Reset() {} +func (NopTxCache) Push(types.Tx) bool { return true } +func (NopTxCache) Remove(types.Tx) {} +func (NopTxCache) Has(types.Tx) bool { return false } diff --git a/mempool/cache_bench_test.go b/mempool/cache_bench_test.go new file mode 100644 index 0000000..e8df409 --- /dev/null +++ b/mempool/cache_bench_test.go @@ -0,0 +1,41 @@ +package mempool + +import ( + "encoding/binary" + "testing" +) + +func BenchmarkCacheInsertTime(b *testing.B) { + cache := NewLRUTxCache(b.N) + + txs := make([][]byte, b.N) + for i := 0; i < b.N; i++ { + txs[i] = make([]byte, 8) + binary.BigEndian.PutUint64(txs[i], uint64(i)) + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + cache.Push(txs[i]) + } +} + +// This benchmark is probably skewed, since we actually will be removing +// txs in parallel, which may cause some overhead due to mutex locking. +func BenchmarkCacheRemoveTime(b *testing.B) { + cache := NewLRUTxCache(b.N) + + txs := make([][]byte, b.N) + for i := 0; i < b.N; i++ { + txs[i] = make([]byte, 8) + binary.BigEndian.PutUint64(txs[i], uint64(i)) + cache.Push(txs[i]) + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + cache.Remove(txs[i]) + } +} diff --git a/mempool/cache_test.go b/mempool/cache_test.go new file mode 100644 index 0000000..b6951b8 --- /dev/null +++ b/mempool/cache_test.go @@ -0,0 +1,114 @@ +package mempool + +import ( + "crypto/rand" + "crypto/sha256" + "testing" + + "fmt" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" + "github.com/stretchr/testify/require" +) + +func TestCacheRemove(t *testing.T) { + cache := NewLRUTxCache(100) + numTxs := 10 + + txs := make([][]byte, numTxs) + for i := 0; i < numTxs; i++ { + // probability of collision is 2**-256 + txBytes := make([]byte, 32) + _, err := rand.Read(txBytes) + require.NoError(t, err) + + txs[i] = txBytes + cache.Push(txBytes) + + // make sure its added to both the linked list and the map + require.Equal(t, i+1, len(cache.cacheMap)) + require.Equal(t, i+1, cache.list.Len()) + } + + for i := 0; i < numTxs; i++ { + cache.Remove(txs[i]) + // make sure its removed from both the map and the linked list + require.Equal(t, numTxs-(i+1), len(cache.cacheMap)) + require.Equal(t, numTxs-(i+1), cache.list.Len()) + } +} + +func TestCacheAfterUpdate(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + // reAddIndices & txsInCache can have elements > numTxsToCreate + // also assumes max index is 255 for convenience + // txs in cache also checks order of elements + tests := []struct { + numTxsToCreate int + updateIndices []int + reAddIndices []int + txsInCache []int + }{ + {1, []int{}, []int{1}, []int{1, 0}}, // adding new txs works + {2, []int{1}, []int{}, []int{1, 0}}, // update doesn't remove tx from cache + {2, []int{2}, []int{}, []int{2, 1, 0}}, // update adds new tx to cache + {2, []int{1}, []int{1}, []int{1, 0}}, // re-adding after update doesn't make dupe + } + for tcIndex, tc := range tests { + for i := 0; i < tc.numTxsToCreate; i++ { + tx := kvstore.NewTx(fmt.Sprintf("%d", i), "value") + err := mp.CheckTx(tx, func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + }, TxInfo{}) + require.NoError(t, err) + } + + updateTxs := []types.Tx{} + for _, v := range tc.updateIndices { + tx := kvstore.NewTx(fmt.Sprintf("%d", v), "value") + updateTxs = append(updateTxs, tx) + } + err := mp.Update(int64(tcIndex), updateTxs, abciResponses(len(updateTxs), abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + + for _, v := range tc.reAddIndices { + tx := kvstore.NewTx(fmt.Sprintf("%d", v), "value") + _ = mp.CheckTx(tx, func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + }, TxInfo{}) + } + + cache := mp.cache.(*LRUTxCache) + node := cache.GetList().Front() + counter := 0 + for node != nil { + require.NotEqual(t, len(tc.txsInCache), counter, + "cache larger than expected on testcase %d", tcIndex) + + nodeVal := node.Value.(types.TxKey) + expTx := kvstore.NewTx(fmt.Sprintf("%d", tc.txsInCache[len(tc.txsInCache)-counter-1]), "value") + expectedBz := sha256.Sum256(expTx) + // Reference for reading the errors: + // >>> sha256('\x00').hexdigest() + // '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' + // >>> sha256('\x01').hexdigest() + // '4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a' + // >>> sha256('\x02').hexdigest() + // 'dbc1b4c900ffe48d575b5da5c638040125f65db0fe3e24494b76ea986457d986' + + require.EqualValues(t, expectedBz, nodeVal, "Equality failed on index %d, tc %d", counter, tcIndex) + counter++ + node = node.Next() + } + require.Equal(t, len(tc.txsInCache), counter, + "cache smaller than expected on testcase %d", tcIndex) + mp.Flush() + } +} diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go new file mode 100644 index 0000000..4eea9a0 --- /dev/null +++ b/mempool/clist_mempool.go @@ -0,0 +1,801 @@ +package mempool + +import ( + "bytes" + "context" + "fmt" + "sync" + "sync/atomic" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/clist" + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" +) + +// CListMempool is an ordered in-memory pool for transactions before they are +// proposed in a consensus round. Transaction validity is checked using the +// CheckTx abci message before the transaction is added to the pool. The +// mempool uses a concurrent list structure for storing transactions that can +// be efficiently accessed by multiple concurrent readers. +type CListMempool struct { + height atomic.Int64 // the last block Update()'d to + txsBytes atomic.Int64 // total size of mempool, in bytes + + // notify listeners (ie. consensus) when txs are available + notifiedTxsAvailable atomic.Bool + txsAvailable chan struct{} // fires once for each height, when the mempool is not empty + + config *config.MempoolConfig + + // Exclusive mutex for Update method to prevent concurrent execution of + // CheckTx or ReapMaxBytesMaxGas(ReapMaxTxs) methods. + updateMtx cmtsync.RWMutex + preCheck PreCheckFunc + postCheck PostCheckFunc + + txs *clist.CList // concurrent linked-list of good txs + proxyAppConn proxy.AppConnMempool + + // Keeps track of the rechecking process. + recheck *recheck + + // Map for quick access to txs to record sender in CheckTx. + // txsMap: txKey -> CElement + txsMap sync.Map + + // Keep a cache of already-seen txs. + // This reduces the pressure on the proxyApp. + cache TxCache + + logger log.Logger + metrics *Metrics +} + +var _ Mempool = &CListMempool{} + +// CListMempoolOption sets an optional parameter on the mempool. +type CListMempoolOption func(*CListMempool) + +// NewCListMempool returns a new mempool with the given configuration and +// connection to an application. +func NewCListMempool( + cfg *config.MempoolConfig, + proxyAppConn proxy.AppConnMempool, + height int64, + options ...CListMempoolOption, +) *CListMempool { + mp := &CListMempool{ + config: cfg, + proxyAppConn: proxyAppConn, + txs: clist.New(), + recheck: newRecheck(), + logger: log.NewNopLogger(), + metrics: NopMetrics(), + } + mp.height.Store(height) + + if cfg.CacheSize > 0 { + mp.cache = NewLRUTxCache(cfg.CacheSize) + } else { + mp.cache = NopTxCache{} + } + + proxyAppConn.SetResponseCallback(mp.globalCb) + + for _, option := range options { + option(mp) + } + + return mp +} + +func (mem *CListMempool) getCElement(txKey types.TxKey) (*clist.CElement, bool) { + if e, ok := mem.txsMap.Load(txKey); ok { + return e.(*clist.CElement), true + } + return nil, false +} + +func (mem *CListMempool) getMemTx(txKey types.TxKey) *mempoolTx { + if e, ok := mem.getCElement(txKey); ok { + return e.Value.(*mempoolTx) + } + return nil +} + +func (mem *CListMempool) removeAllTxs() { + for e := mem.txs.Front(); e != nil; e = e.Next() { + mem.txs.Remove(e) + e.DetachPrev() + } + + mem.txsMap.Range(func(key, _ interface{}) bool { + mem.txsMap.Delete(key) + return true + }) +} + +// NOTE: not thread safe - should only be called once, on startup +func (mem *CListMempool) EnableTxsAvailable() { + mem.txsAvailable = make(chan struct{}, 1) +} + +// SetLogger sets the Logger. +func (mem *CListMempool) SetLogger(l log.Logger) { + mem.logger = l +} + +// WithPreCheck sets a filter for the mempool to reject a tx if f(tx) returns +// false. This is ran before CheckTx. Only applies to the first created block. +// After that, Update overwrites the existing value. +func WithPreCheck(f PreCheckFunc) CListMempoolOption { + return func(mem *CListMempool) { mem.preCheck = f } +} + +// WithPostCheck sets a filter for the mempool to reject a tx if f(tx) returns +// false. This is ran after CheckTx. Only applies to the first created block. +// After that, Update overwrites the existing value. +func WithPostCheck(f PostCheckFunc) CListMempoolOption { + return func(mem *CListMempool) { mem.postCheck = f } +} + +// WithMetrics sets the metrics. +func WithMetrics(metrics *Metrics) CListMempoolOption { + return func(mem *CListMempool) { mem.metrics = metrics } +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) Lock() { + if mem.recheck.setRecheckFull() { + mem.logger.Debug("the state of recheckFull has flipped") + } + mem.updateMtx.Lock() +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) Unlock() { + mem.updateMtx.Unlock() +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) Size() int { + return mem.txs.Len() +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) SizeBytes() int64 { + return mem.txsBytes.Load() +} + +// Lock() must be help by the caller during execution. +func (mem *CListMempool) FlushAppConn() error { + err := mem.proxyAppConn.Flush(context.TODO()) + if err != nil { + return ErrFlushAppConn{Err: err} + } + + return nil +} + +// XXX: Unsafe! Calling Flush may leave mempool in inconsistent state. +func (mem *CListMempool) Flush() { + mem.updateMtx.RLock() + defer mem.updateMtx.RUnlock() + + mem.txsBytes.Store(0) + mem.cache.Reset() + + mem.removeAllTxs() +} + +// TxsFront returns the first transaction in the ordered list for peer +// goroutines to call .NextWait() on. +// FIXME: leaking implementation details! +// +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) TxsFront() *clist.CElement { + return mem.txs.Front() +} + +// TxsWaitChan returns a channel to wait on transactions. It will be closed +// once the mempool is not empty (ie. the internal `mem.txs` has at least one +// element) +// +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) TxsWaitChan() <-chan struct{} { + return mem.txs.WaitChan() +} + +// It blocks if we're waiting on Update() or Reap(). +// cb: A callback from the CheckTx command. +// +// It gets called from another goroutine. +// +// CONTRACT: Either cb will get called, or err returned. +// +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) CheckTx( + tx types.Tx, + cb func(*abci.ResponseCheckTx), + txInfo TxInfo, +) error { + mem.updateMtx.RLock() + // use defer to unlock mutex because application (*local client*) might panic + defer mem.updateMtx.RUnlock() + + txSize := len(tx) + + if err := mem.isFull(txSize); err != nil { + mem.metrics.RejectedTxs.Add(1) + return err + } + + if txSize > mem.config.MaxTxBytes { + return ErrTxTooLarge{ + Max: mem.config.MaxTxBytes, + Actual: txSize, + } + } + + if mem.preCheck != nil { + if err := mem.preCheck(tx); err != nil { + return ErrPreCheck{Err: err} + } + } + + // NOTE: proxyAppConn may error if tx buffer is full + if err := mem.proxyAppConn.Error(); err != nil { + return ErrAppConnMempool{Err: err} + } + + if !mem.cache.Push(tx) { // if the transaction already exists in the cache + // Record a new sender for a tx we've already seen. + // Note it's possible a tx is still in the cache but no longer in the mempool + // (eg. after committing a block, txs are removed from mempool but not cache), + // so we only record the sender for txs still in the mempool. + if memTx := mem.getMemTx(tx.Key()); memTx != nil { + memTx.addSender(txInfo.SenderID) + // TODO: consider punishing peer for dups, + // its non-trivial since invalid txs can become valid, + // but they can spam the same tx with little cost to them atm. + } + return ErrTxInCache + } + + reqRes, err := mem.proxyAppConn.CheckTxAsync(context.TODO(), &abci.RequestCheckTx{Tx: tx}) + if err != nil { + panic(fmt.Errorf("CheckTx request for tx %s failed: %w", log.NewLazySprintf("%v", tx.Hash()), err)) + } + reqRes.SetCallback(mem.reqResCb(tx, txInfo, cb)) + + return nil +} + +// Global callback that will be called after every ABCI response. +// Having a single global callback avoids needing to set a callback for each request. +// However, processing the checkTx response requires the peerID (so we can track which txs we heard from who), +// and peerID is not included in the ABCI request, so we have to set request-specific callbacks that +// include this information. If we're not in the midst of a recheck, this function will just return, +// so the request specific callback can do the work. +// +// When rechecking, we don't need the peerID, so the recheck callback happens +// here. +func (mem *CListMempool) globalCb(req *abci.Request, res *abci.Response) { + switch r := req.Value.(type) { + case *abci.Request_CheckTx: + // Process only Recheck responses. + if r.CheckTx.Type != abci.CheckTxType_Recheck { + return + } + default: + // ignore other type of requests + return + } + + switch r := res.Value.(type) { + case *abci.Response_CheckTx: + tx := types.Tx(req.GetCheckTx().Tx) + if mem.recheck.done() { + mem.logger.Error("rechecking has finished; discard late recheck response", + "tx", log.NewLazySprintf("%v", tx.Key())) + return + } + mem.metrics.RecheckTimes.Add(1) + mem.resCbRecheck(tx, r.CheckTx) + + // update metrics + mem.metrics.Size.Set(float64(mem.Size())) + + default: + // ignore other messages + } +} + +// Request specific callback that should be set on individual reqRes objects +// to incorporate local information when processing the response. +// This allows us to track the peer that sent us this tx, so we can avoid sending it back to them. +// NOTE: alternatively, we could include this information in the ABCI request itself. +// +// External callers of CheckTx, like the RPC, can also pass an externalCb through here that is called +// when all other response processing is complete. +// +// Used in CheckTx to record PeerID who sent us the tx. +func (mem *CListMempool) reqResCb( + tx []byte, + txInfo TxInfo, + externalCb func(*abci.ResponseCheckTx), +) func(res *abci.Response) { + return func(res *abci.Response) { + if !mem.recheck.done() { + panic(log.NewLazySprintf("rechecking has not finished; cannot check new tx %v", + types.Tx(tx).Hash())) + } + + mem.resCbFirstTime(tx, txInfo, res) + + // update metrics + mem.metrics.Size.Set(float64(mem.Size())) + mem.metrics.SizeBytes.Set(float64(mem.SizeBytes())) + + // passed in by the caller of CheckTx, eg. the RPC + if externalCb != nil { + externalCb(res.GetCheckTx()) + } + } +} + +// Called from: +// - resCbFirstTime (lock not held) if tx is valid +func (mem *CListMempool) addTx(memTx *mempoolTx) { + e := mem.txs.PushBack(memTx) + mem.txsMap.Store(memTx.tx.Key(), e) + mem.txsBytes.Add(int64(len(memTx.tx))) + mem.metrics.TxSizeBytes.Observe(float64(len(memTx.tx))) +} + +// RemoveTxByKey removes a transaction from the mempool by its TxKey index. +// Called from: +// - Update (lock held) if tx was committed +// - resCbRecheck (lock not held) if tx was invalidated +func (mem *CListMempool) RemoveTxByKey(txKey types.TxKey) error { + if elem, ok := mem.getCElement(txKey); ok { + mem.txs.Remove(elem) + elem.DetachPrev() + mem.txsMap.Delete(txKey) + tx := elem.Value.(*mempoolTx).tx + mem.txsBytes.Add(int64(-len(tx))) + return nil + } + return ErrTxNotFound +} + +func (mem *CListMempool) isFull(txSize int) error { + memSize := mem.Size() + txsBytes := mem.SizeBytes() + if memSize >= mem.config.Size || int64(txSize)+txsBytes > mem.config.MaxTxsBytes { + return ErrMempoolIsFull{ + NumTxs: memSize, + MaxTxs: mem.config.Size, + TxsBytes: txsBytes, + MaxTxsBytes: mem.config.MaxTxsBytes, + } + } + + if mem.recheck.consideredFull() { + return ErrRecheckFull + } + + return nil +} + +// callback, which is called after the app checked the tx for the first time. +// +// The case where the app checks the tx for the second and subsequent times is +// handled by the resCbRecheck callback. +func (mem *CListMempool) resCbFirstTime( + tx []byte, + txInfo TxInfo, + res *abci.Response, +) { + switch r := res.Value.(type) { + case *abci.Response_CheckTx: + var postCheckErr error + if mem.postCheck != nil { + postCheckErr = mem.postCheck(tx, r.CheckTx) + } + if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil { + // Check mempool isn't full again to reduce the chance of exceeding the + // limits. + if err := mem.isFull(len(tx)); err != nil { + // remove from cache (mempool might have a space later) + mem.cache.Remove(tx) + // use debug level to avoid spamming logs when traffic is high + mem.logger.Debug(err.Error()) + mem.metrics.RejectedTxs.Add(1) + return + } + + // Check transaction not already in the mempool + if e, ok := mem.txsMap.Load(types.Tx(tx).Key()); ok { + memTx := e.(*clist.CElement).Value.(*mempoolTx) + memTx.addSender(txInfo.SenderID) + mem.logger.Debug( + "transaction already there, not adding it again", + "tx", types.Tx(tx).Hash(), + "res", r, + "height", mem.height.Load(), + "total", mem.Size(), + ) + mem.metrics.RejectedTxs.Add(1) + return + } + + memTx := &mempoolTx{ + height: mem.height.Load(), + gasWanted: r.CheckTx.GasWanted, + tx: tx, + } + memTx.addSender(txInfo.SenderID) + mem.addTx(memTx) + mem.logger.Debug( + "added good transaction", + "tx", types.Tx(tx).Hash(), + "res", r, + "height", mem.height.Load(), + "total", mem.Size(), + ) + mem.notifyTxsAvailable() + } else { + // ignore bad transaction + mem.logger.Debug( + "rejected bad transaction", + "tx", types.Tx(tx).Hash(), + "peerID", txInfo.SenderP2PID, + "res", r, + "err", postCheckErr, + ) + mem.metrics.FailedTxs.Add(1) + + if !mem.config.KeepInvalidTxsInCache { + // remove from cache (it might be good later) + mem.cache.Remove(tx) + } + } + + default: + // ignore other messages + } +} + +// callback, which is called after the app rechecked the tx. +// +// The case where the app checks the tx for the first time is handled by the +// resCbFirstTime callback. +func (mem *CListMempool) resCbRecheck(tx types.Tx, res *abci.ResponseCheckTx) { + // Check whether tx is still in the list of transactions that can be rechecked. + if !mem.recheck.findNextEntryMatching(&tx) { + // Reached the end of the list and didn't find a matching tx; rechecking has finished. + return + } + + var postCheckErr error + if mem.postCheck != nil { + postCheckErr = mem.postCheck(tx, res) + } + + if (res.Code != abci.CodeTypeOK) || postCheckErr != nil { + // Tx became invalidated due to newly committed block. + mem.logger.Debug("tx is no longer valid", "tx", tx.Hash(), "res", res, "postCheckErr", postCheckErr) + if err := mem.RemoveTxByKey(tx.Key()); err != nil { + mem.logger.Debug("Transaction could not be removed from mempool", "err", err) + } + if !mem.config.KeepInvalidTxsInCache { + mem.cache.Remove(tx) + mem.metrics.EvictedTxs.Add(1) + } + } +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) TxsAvailable() <-chan struct{} { + return mem.txsAvailable +} + +func (mem *CListMempool) notifyTxsAvailable() { + if mem.Size() == 0 { + panic("notified txs available but mempool is empty!") + } + if mem.txsAvailable != nil && mem.notifiedTxsAvailable.CompareAndSwap(false, true) { + // channel cap is 1, so this will send once + select { + case mem.txsAvailable <- struct{}{}: + default: + } + } +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs { + mem.updateMtx.RLock() + defer mem.updateMtx.RUnlock() + + var ( + totalGas int64 + runningSize int64 + ) + + // TODO: we will get a performance boost if we have a good estimate of avg + // size per tx, and set the initial capacity based off of that. + // txs := make([]types.Tx, 0, cmtmath.MinInt(mem.txs.Len(), max/mem.avgTxSize)) + txs := make([]types.Tx, 0, mem.txs.Len()) + for e := mem.txs.Front(); e != nil; e = e.Next() { + memTx := e.Value.(*mempoolTx) + + txs = append(txs, memTx.tx) + + dataSize := types.ComputeProtoSizeForTxs([]types.Tx{memTx.tx}) + + // Check total size requirement + if maxBytes > -1 && runningSize+dataSize > maxBytes { + return txs[:len(txs)-1] + } + + runningSize += dataSize + + // Check total gas requirement. + // If maxGas is negative, skip this check. + // Since newTotalGas < masGas, which + // must be non-negative, it follows that this won't overflow. + newTotalGas := totalGas + memTx.gasWanted + if maxGas > -1 && newTotalGas > maxGas { + return txs[:len(txs)-1] + } + totalGas = newTotalGas + } + return txs +} + +// Safe for concurrent use by multiple goroutines. +func (mem *CListMempool) ReapMaxTxs(max int) types.Txs { + mem.updateMtx.RLock() + defer mem.updateMtx.RUnlock() + + if max < 0 { + max = mem.txs.Len() + } + + txs := make([]types.Tx, 0, cmtmath.MinInt(mem.txs.Len(), max)) + for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() { + memTx := e.Value.(*mempoolTx) + txs = append(txs, memTx.tx) + } + return txs +} + +// Lock() must be help by the caller during execution. +func (mem *CListMempool) Update( + height int64, + txs types.Txs, + txResults []*abci.ExecTxResult, + preCheck PreCheckFunc, + postCheck PostCheckFunc, +) error { + mem.logger.Debug("Update", "height", height, "len(txs)", len(txs)) + + // Set height + mem.height.Store(height) + mem.notifiedTxsAvailable.Store(false) + + if preCheck != nil { + mem.preCheck = preCheck + } + if postCheck != nil { + mem.postCheck = postCheck + } + + for i, tx := range txs { + if txResults[i].Code == abci.CodeTypeOK { + // Add valid committed tx to the cache (if missing). + _ = mem.cache.Push(tx) + } else if !mem.config.KeepInvalidTxsInCache { + // Allow invalid transactions to be resubmitted. + mem.cache.Remove(tx) + } + + // Remove committed tx from the mempool. + // + // Note an evil proposer can drop valid txs! + // Mempool before: + // 100 -> 101 -> 102 + // Block, proposed by an evil proposer: + // 101 -> 102 + // Mempool after: + // 100 + // https://github.com/tendermint/tendermint/issues/3322. + if err := mem.RemoveTxByKey(tx.Key()); err != nil { + mem.logger.Debug("Committed transaction not in local mempool (not an error)", + "key", tx.Key(), + "error", err.Error()) + } + } + + // Recheck txs left in the mempool to remove them if they became invalid in the new state. + if mem.config.Recheck { + mem.recheckTxs() + } + + // Notify if there are still txs left in the mempool. + if mem.Size() > 0 { + mem.notifyTxsAvailable() + } + + // Update metrics + mem.metrics.Size.Set(float64(mem.Size())) + mem.metrics.SizeBytes.Set(float64(mem.SizeBytes())) + + return nil +} + +// recheckTxs sends all transactions in the mempool to the app for re-validation. When the function +// returns, all recheck responses from the app have been processed. +func (mem *CListMempool) recheckTxs() { + mem.logger.Debug("recheck txs", "height", mem.height.Load(), "num-txs", mem.Size()) + + if mem.Size() <= 0 { + return + } + + mem.recheck.init(mem.txs.Front(), mem.txs.Back()) + + // NOTE: globalCb may be called concurrently, but CheckTx cannot be executed concurrently + // because this function has the lock (via Update and Lock). + for e := mem.txs.Front(); e != nil; e = e.Next() { + tx := e.Value.(*mempoolTx).tx + mem.recheck.numPendingTxs.Add(1) + + // Send a CheckTx request to the app. If we're using a sync client, the resCbRecheck + // callback will be called right after receiving the response. + _, err := mem.proxyAppConn.CheckTxAsync(context.TODO(), &abci.RequestCheckTx{ + Tx: tx, + Type: abci.CheckTxType_Recheck, + }) + if err != nil { + panic(fmt.Errorf("(re-)CheckTx request for tx %s failed: %w", log.NewLazySprintf("%v", tx.Hash()), err)) + } + } + + // Flush any pending asynchronous recheck requests to process. + mem.proxyAppConn.Flush(context.TODO()) + + // Give some time to finish processing the responses; then finish the rechecking process, even + // if not all txs were rechecked. + select { + case <-time.After(mem.config.RecheckTimeout): + mem.recheck.setDone() + mem.logger.Error("timed out waiting for recheck responses") + case <-mem.recheck.doneRechecking(): + } + + if n := mem.recheck.numPendingTxs.Load(); n > 0 { + mem.logger.Error("not all txs were rechecked", "not-rechecked", n) + } + mem.logger.Debug("done rechecking txs", "height", mem.height.Load(), "num-txs", mem.Size()) +} + +// The cursor and end pointers define a dynamic list of transactions that could be rechecked. The +// end pointer is fixed. When a recheck response for a transaction is received, cursor will point to +// the entry in the mempool corresponding to that transaction, thus narrowing the list. Transactions +// corresponding to entries between the old and current positions of cursor will be ignored for +// rechecking. This is to guarantee that recheck responses are processed in the same sequential +// order as they appear in the mempool. +type recheck struct { + cursor *clist.CElement // next expected recheck response + end *clist.CElement // last entry in the mempool to recheck + doneCh chan struct{} // to signal that rechecking has finished successfully (for async app connections) + numPendingTxs atomic.Int32 // number of transactions still pending to recheck + isRechecking atomic.Bool // true iff the rechecking process has begun and is not yet finished + recheckFull atomic.Bool // whether rechecking TXs cannot be completed before a new block is decided +} + +func newRecheck() *recheck { + return &recheck{ + doneCh: make(chan struct{}, 1), + } +} + +func (rc *recheck) init(first, last *clist.CElement) { + if !rc.done() { + panic("Having more than one rechecking process at a time is not possible.") + } + rc.cursor = first + rc.end = last + rc.numPendingTxs.Store(0) + rc.isRechecking.Store(true) +} + +// done returns true when there is no recheck response to process. +// Safe for concurrent use by multiple goroutines. +func (rc *recheck) done() bool { + return !rc.isRechecking.Load() +} + +// setDone registers that rechecking has finished. +func (rc *recheck) setDone() { + rc.cursor = nil + rc.recheckFull.Store(false) + rc.isRechecking.Store(false) +} + +// setNextEntry sets cursor to the next entry in the list. If there is no next, cursor will be nil. +func (rc *recheck) setNextEntry() { + rc.cursor = rc.cursor.Next() +} + +// tryFinish will check if the cursor is at the end of the list and notify the channel that +// rechecking has finished. It returns true iff it's done rechecking. +func (rc *recheck) tryFinish() bool { + if rc.cursor == rc.end { + // Reached end of the list without finding a matching tx. + rc.setDone() + } + if rc.done() { + // Notify that recheck has finished. + select { + case rc.doneCh <- struct{}{}: + default: + } + return true + } + return false +} + +// findNextEntryMatching searches for the next transaction matching the given transaction, which +// corresponds to the recheck response to be processed next. Then it checks if it has reached the +// end of the list, so it can finish rechecking. +// +// The goal is to guarantee that transactions are rechecked in the order in which they are in the +// mempool. Transactions whose recheck response arrive late or don't arrive at all are skipped and +// not rechecked. +func (rc *recheck) findNextEntryMatching(tx *types.Tx) bool { + found := false + for ; !rc.done(); rc.setNextEntry() { + expectedTx := rc.cursor.Value.(*mempoolTx).tx + if bytes.Equal(*tx, expectedTx) { + // Found an entry in the list of txs to recheck that matches tx. + found = true + rc.numPendingTxs.Add(-1) + break + } + } + + if !rc.tryFinish() { + // Not finished yet; set the cursor for processing the next recheck response. + rc.setNextEntry() + } + return found +} + +// doneRechecking returns the channel used to signal that rechecking has finished. +func (rc *recheck) doneRechecking() <-chan struct{} { + return rc.doneCh +} + +// setRecheckFull sets recheckFull to true if rechecking is still in progress. It returns true iff +// the value of recheckFull has changed. +func (rc *recheck) setRecheckFull() bool { + rechecking := !rc.done() + recheckFull := rc.recheckFull.Swap(rechecking) + return rechecking != recheckFull +} + +// consideredFull returns true iff the mempool should be considered as full while rechecking is in +// progress. +func (rc *recheck) consideredFull() bool { + return rc.recheckFull.Load() +} diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go new file mode 100644 index 0000000..09e7ab0 --- /dev/null +++ b/mempool/clist_mempool_test.go @@ -0,0 +1,1046 @@ +package mempool + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + mrand "math/rand" + "os" + "sync" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + abciclient "github.com/cometbft/cometbft/abci/client" + abciclimocks "github.com/cometbft/cometbft/abci/client/mocks" + "github.com/cometbft/cometbft/abci/example/kvstore" + abciserver "github.com/cometbft/cometbft/abci/server" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" +) + +// A cleanupFunc cleans up any config / test files created for a particular +// test. +type cleanupFunc func() + +func newMempoolWithAppMock(client abciclient.Client) (*CListMempool, cleanupFunc, error) { + conf := test.ResetTestRoot("mempool_test") + + mp, cu := newMempoolWithAppAndConfigMock(conf, client) + return mp, cu, nil +} + +func newMempoolWithAppAndConfigMock( + cfg *config.Config, + client abciclient.Client, +) (*CListMempool, cleanupFunc) { + appConnMem := client + appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool")) + err := appConnMem.Start() + if err != nil { + panic(err) + } + + mp := NewCListMempool(cfg.Mempool, appConnMem, 0) + mp.SetLogger(log.TestingLogger()) + + return mp, func() { os.RemoveAll(cfg.RootDir) } +} + +func newMempoolWithApp(cc proxy.ClientCreator) (*CListMempool, cleanupFunc) { + conf := test.ResetTestRoot("mempool_test") + + mp, cu := newMempoolWithAppAndConfig(cc, conf) + return mp, cu +} + +func newMempoolWithAppAndConfig(cc proxy.ClientCreator, cfg *config.Config) (*CListMempool, cleanupFunc) { + appConnMem, _ := cc.NewABCIClient() + appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool")) + err := appConnMem.Start() + if err != nil { + panic(err) + } + + mp := NewCListMempool(cfg.Mempool, appConnMem, 0) + mp.SetLogger(log.TestingLogger()) + + return mp, func() { os.RemoveAll(cfg.RootDir) } +} + +func ensureNoFire(t *testing.T, ch <-chan struct{}, timeoutMS int) { + timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond) + select { + case <-ch: + t.Fatal("Expected not to fire") + case <-timer.C: + } +} + +func ensureFire(t *testing.T, ch <-chan struct{}, timeoutMS int) { + timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond) + select { + case <-ch: + case <-timer.C: + t.Fatal("Expected to fire") + } +} + +func callCheckTx(t *testing.T, mp Mempool, txs types.Txs, peerID uint16) { + txInfo := TxInfo{SenderID: peerID} + for i, tx := range txs { + if err := mp.CheckTx(tx, nil, txInfo); err != nil { + // Skip invalid txs. + // TestMempoolFilters will fail otherwise. It asserts a number of txs + // returned. + if IsPreCheckError(err) { + continue + } + t.Fatalf("CheckTx failed: %v while checking #%d tx", err, i) + } + } +} + +// Generate a list of random transactions. +func NewRandomTxs(numTxs int, txLen int) types.Txs { + txs := make(types.Txs, numTxs) + for i := 0; i < numTxs; i++ { + txBytes := kvstore.NewRandomTx(txLen) + txs[i] = txBytes + } + return txs +} + +// Generate a list of random transactions of a given size and call CheckTx on +// each of them. +func addRandomTxs(t *testing.T, mp Mempool, count int, peerID uint16) []types.Tx { + t.Helper() + txs := NewRandomTxs(count, 20) + callCheckTx(t, mp, txs, peerID) + return txs +} + +func addTxs(tb testing.TB, mp Mempool, first, num int) []types.Tx { + tb.Helper() + txs := make([]types.Tx, 0, num) + for i := first; i < num; i++ { + tx := kvstore.NewTxFromID(i) + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(tb, err) + txs = append(txs, tx) + } + return txs +} + +func TestReapMaxBytesMaxGas(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + // Ensure gas calculation behaves as expected + addRandomTxs(t, mp, 1, UnknownPeerID) + tx0 := mp.TxsFront().Value.(*mempoolTx) + require.Equal(t, tx0.gasWanted, int64(1), "transactions gas was set incorrectly") + // ensure each tx is 20 bytes long + require.Equal(t, len(tx0.tx), 20, "Tx is longer than 20 bytes") + mp.Flush() + + // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs. + // each tx has 20 bytes + tests := []struct { + numTxsToCreate int + maxBytes int64 + maxGas int64 + expectedNumTxs int + }{ + {20, -1, -1, 20}, + {20, -1, 0, 0}, + {20, -1, 10, 10}, + {20, -1, 30, 20}, + {20, 0, -1, 0}, + {20, 0, 10, 0}, + {20, 10, 10, 0}, + {20, 24, 10, 1}, + {20, 240, 5, 5}, + {20, 240, -1, 10}, + {20, 240, 10, 10}, + {20, 240, 15, 10}, + {20, 20000, -1, 20}, + {20, 20000, 5, 5}, + {20, 20000, 30, 20}, + } + for tcIndex, tt := range tests { + addRandomTxs(t, mp, tt.numTxsToCreate, UnknownPeerID) + got := mp.ReapMaxBytesMaxGas(tt.maxBytes, tt.maxGas) + assert.Equal(t, tt.expectedNumTxs, len(got), "Got %d txs, expected %d, tc #%d", + len(got), tt.expectedNumTxs, tcIndex) + mp.Flush() + } +} + +func TestMempoolFilters(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + emptyTxArr := []types.Tx{[]byte{}} + + nopPreFilter := func(tx types.Tx) error { return nil } + nopPostFilter := func(tx types.Tx, res *abci.ResponseCheckTx) error { return nil } + + // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs. + // each tx has 20 bytes + tests := []struct { + numTxsToCreate int + preFilter PreCheckFunc + postFilter PostCheckFunc + expectedNumTxs int + }{ + {10, nopPreFilter, nopPostFilter, 10}, + {10, PreCheckMaxBytes(10), nopPostFilter, 0}, + {10, PreCheckMaxBytes(22), nopPostFilter, 10}, + {10, nopPreFilter, PostCheckMaxGas(-1), 10}, + {10, nopPreFilter, PostCheckMaxGas(0), 0}, + {10, nopPreFilter, PostCheckMaxGas(1), 10}, + {10, nopPreFilter, PostCheckMaxGas(3000), 10}, + {10, PreCheckMaxBytes(10), PostCheckMaxGas(20), 0}, + {10, PreCheckMaxBytes(30), PostCheckMaxGas(20), 10}, + {10, PreCheckMaxBytes(22), PostCheckMaxGas(1), 10}, + {10, PreCheckMaxBytes(22), PostCheckMaxGas(0), 0}, + } + for tcIndex, tt := range tests { + err := mp.Update(1, emptyTxArr, abciResponses(len(emptyTxArr), abci.CodeTypeOK), tt.preFilter, tt.postFilter) + require.NoError(t, err) + addRandomTxs(t, mp, tt.numTxsToCreate, UnknownPeerID) + require.Equal(t, tt.expectedNumTxs, mp.Size(), "mempool had the incorrect size, on test case %d", tcIndex) + mp.Flush() + } +} + +func TestMempoolUpdate(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + // 1. Adds valid txs to the cache + { + tx1 := kvstore.NewTxFromID(1) + err := mp.Update(1, []types.Tx{tx1}, abciResponses(1, abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + err = mp.CheckTx(tx1, nil, TxInfo{}) + if assert.Error(t, err) { + assert.Equal(t, ErrTxInCache, err) + } + } + + // 2. Removes valid txs from the mempool + { + tx2 := kvstore.NewTxFromID(2) + err := mp.CheckTx(tx2, nil, TxInfo{}) + require.NoError(t, err) + err = mp.Update(1, []types.Tx{tx2}, abciResponses(1, abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + assert.Zero(t, mp.Size()) + } + + // 3. Removes invalid transactions from the cache and the mempool (if present) + { + tx3 := kvstore.NewTxFromID(3) + err := mp.CheckTx(tx3, nil, TxInfo{}) + require.NoError(t, err) + err = mp.Update(1, []types.Tx{tx3}, abciResponses(1, 1), nil, nil) + require.NoError(t, err) + assert.Zero(t, mp.Size()) + + err = mp.CheckTx(tx3, nil, TxInfo{}) + require.NoError(t, err) + } +} + +func TestMempoolUpdateDoesNotPanicWhenApplicationMissedTx(t *testing.T) { + var callback abciclient.Callback + mockClient := new(abciclimocks.Client) + mockClient.On("Start").Return(nil) + mockClient.On("SetLogger", mock.Anything) + + mockClient.On("Error").Return(nil).Times(4) + mockClient.On("SetResponseCallback", mock.MatchedBy(func(cb abciclient.Callback) bool { callback = cb; return true })) + mockClient.On("Flush", mock.Anything).Return(nil) + + mp, cleanup, err := newMempoolWithAppMock(mockClient) + require.NoError(t, err) + defer cleanup() + + // Add 4 transactions to the mempool by calling the mempool's `CheckTx` on each of them. + txs := []types.Tx{[]byte{0x01}, []byte{0x02}, []byte{0x03}, []byte{0x04}} + for _, tx := range txs { + reqRes := newReqRes(tx, abci.CodeTypeOK, abci.CheckTxType_New) + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(reqRes, nil) + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(t, err) + + // ensure that the callback that the mempool sets on the ReqRes is run. + reqRes.InvokeCallback() + } + require.Len(t, txs, mp.Size()) + require.True(t, mp.recheck.done()) + + // Calling update to remove the first transaction from the mempool. + // This call also triggers the mempool to recheck its remaining transactions. + err = mp.Update(0, []types.Tx{txs[0]}, abciResponses(1, abci.CodeTypeOK), nil, nil) + require.Nil(t, err) + + // The mempool has now sent its requests off to the client to be rechecked + // and is waiting for the corresponding callbacks to be called. + // We now call the mempool-supplied callback on the first and third transaction. + // This simulates the client dropping the second request. + // Previous versions of this code panicked when the ABCI application missed + // a recheck-tx request. + resp := &abci.ResponseCheckTx{Code: abci.CodeTypeOK} + req := &abci.RequestCheckTx{Tx: txs[1]} + callback(abci.ToRequestCheckTx(req), abci.ToResponseCheckTx(resp)) + + req = &abci.RequestCheckTx{Tx: txs[3]} + callback(abci.ToRequestCheckTx(req), abci.ToResponseCheckTx(resp)) + mockClient.AssertExpectations(t) +} + +func TestMempool_KeepInvalidTxsInCache(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + wcfg := config.DefaultConfig() + wcfg.Mempool.KeepInvalidTxsInCache = true + mp, cleanup := newMempoolWithAppAndConfig(cc, wcfg) + defer cleanup() + + // 1. An invalid transaction must remain in the cache after Update + { + a := make([]byte, 8) + binary.BigEndian.PutUint64(a, 0) + + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, 1) + + err := mp.CheckTx(b, nil, TxInfo{}) + require.NoError(t, err) + + // simulate new block + _, err = app.FinalizeBlock(context.Background(), &abci.RequestFinalizeBlock{ + Txs: [][]byte{a, b}, + }) + require.NoError(t, err) + err = mp.Update(1, []types.Tx{a, b}, + []*abci.ExecTxResult{{Code: abci.CodeTypeOK}, {Code: 2}}, nil, nil) + require.NoError(t, err) + + // a must be added to the cache + err = mp.CheckTx(a, nil, TxInfo{}) + if assert.Error(t, err) { + assert.Equal(t, ErrTxInCache, err) + } + + // b must remain in the cache + err = mp.CheckTx(b, nil, TxInfo{}) + if assert.Error(t, err) { + assert.Equal(t, ErrTxInCache, err) + } + } + + // 2. An invalid transaction must remain in the cache + { + a := make([]byte, 8) + binary.BigEndian.PutUint64(a, 0) + + // remove a from the cache to test (2) + mp.cache.Remove(a) + + err := mp.CheckTx(a, nil, TxInfo{}) + require.NoError(t, err) + } +} + +func TestTxsAvailable(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + mp.EnableTxsAvailable() + + timeoutMS := 500 + + // with no txs, it shouldnt fire + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) + + // send a bunch of txs, it should only fire once + txs := addRandomTxs(t, mp, 100, UnknownPeerID) + ensureFire(t, mp.TxsAvailable(), timeoutMS) + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) + + // call update with half the txs. + // it should fire once now for the new height + // since there are still txs left + committedTxs, remainingTxs := txs[:50], txs[50:] + if err := mp.Update(1, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil { + t.Error(err) + } + ensureFire(t, mp.TxsAvailable(), timeoutMS) + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) + + // send a bunch more txs. we already fired for this height so it shouldnt fire again + moreTxs := addRandomTxs(t, mp, 50, UnknownPeerID) + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) + + // now call update with all the txs. it should not fire as there are no txs left + committedTxs = append(remainingTxs, moreTxs...) + if err := mp.Update(2, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil { + t.Error(err) + } + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) + + // send a bunch more txs, it should only fire once + addRandomTxs(t, mp, 100, UnknownPeerID) + ensureFire(t, mp.TxsAvailable(), timeoutMS) + ensureNoFire(t, mp.TxsAvailable(), timeoutMS) +} + +func TestSerialReap(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + + mp, cleanup := newMempoolWithApp(cc) + defer cleanup() + + appConnCon, _ := cc.NewABCIClient() + appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus")) + err := appConnCon.Start() + require.Nil(t, err) + + cacheMap := make(map[string]struct{}) + deliverTxsRange := func(start, end int) { + // Deliver some txs. + for i := start; i < end; i++ { + txBytes := kvstore.NewTx(fmt.Sprintf("%d", i), "true") + err := mp.CheckTx(txBytes, nil, TxInfo{}) + _, cached := cacheMap[string(txBytes)] + if cached { + require.NotNil(t, err, "expected error for cached tx") + } else { + require.Nil(t, err, "expected no err for uncached tx") + } + cacheMap[string(txBytes)] = struct{}{} + + // Duplicates are cached and should return error + err = mp.CheckTx(txBytes, nil, TxInfo{}) + require.NotNil(t, err, "Expected error after CheckTx on duplicated tx") + } + } + + reapCheck := func(exp int) { + txs := mp.ReapMaxBytesMaxGas(-1, -1) + require.Equal(t, len(txs), exp, fmt.Sprintf("Expected to reap %v txs but got %v", exp, len(txs))) + } + + updateRange := func(start, end int) { + txs := make(types.Txs, end-start) + for i := start; i < end; i++ { + txs[i-start] = kvstore.NewTx(fmt.Sprintf("%d", i), "true") + } + if err := mp.Update(0, txs, abciResponses(len(txs), abci.CodeTypeOK), nil, nil); err != nil { + t.Error(err) + } + } + + commitRange := func(start, end int) { + // Deliver some txs in a block + txs := make([][]byte, end-start) + for i := start; i < end; i++ { + txs[i-start] = kvstore.NewTx(fmt.Sprintf("%d", i), "true") + } + + res, err := appConnCon.FinalizeBlock(context.Background(), &abci.RequestFinalizeBlock{Txs: txs}) + if err != nil { + t.Errorf("client error committing tx: %v", err) + } + for _, txResult := range res.TxResults { + if txResult.IsErr() { + t.Errorf("error committing tx. Code:%v result:%X log:%v", + txResult.Code, txResult.Data, txResult.Log) + } + } + if len(res.AppHash) != 8 { + t.Errorf("error committing. Hash:%X", res.AppHash) + } + + _, err = appConnCon.Commit(context.Background(), &abci.RequestCommit{}) + if err != nil { + t.Errorf("client error committing: %v", err) + } + } + + //---------------------------------------- + + // Deliver some txs. + deliverTxsRange(0, 100) + + // Reap the txs. + reapCheck(100) + + // Reap again. We should get the same amount + reapCheck(100) + + // Deliver 0 to 999, we should reap 900 new txs + // because 100 were already counted. + deliverTxsRange(0, 1000) + + // Reap the txs. + reapCheck(1000) + + // Reap again. We should get the same amount + reapCheck(1000) + + // Commit from the conensus AppConn + commitRange(0, 500) + updateRange(0, 500) + + // We should have 500 left. + reapCheck(500) + + // Deliver 100 invalid txs and 100 valid txs + deliverTxsRange(900, 1100) + + // We should have 600 now. + reapCheck(600) +} + +func TestMempool_CheckTxChecksTxSize(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + + mempl, cleanup := newMempoolWithApp(cc) + defer cleanup() + + maxTxSize := mempl.config.MaxTxBytes + + testCases := []struct { + len int + err bool + }{ + // check small txs. no error + 0: {10, false}, + 1: {1000, false}, + 2: {1000000, false}, + + // check around maxTxSize + 3: {maxTxSize - 1, false}, + 4: {maxTxSize, false}, + 5: {maxTxSize + 1, true}, + } + + for i, testCase := range testCases { + caseString := fmt.Sprintf("case %d, len %d", i, testCase.len) + + tx := cmtrand.Bytes(testCase.len) + + err := mempl.CheckTx(tx, nil, TxInfo{}) + bv := gogotypes.BytesValue{Value: tx} + bz, err2 := bv.Marshal() + require.NoError(t, err2) + require.Equal(t, len(bz), proto.Size(&bv), caseString) + + if !testCase.err { + require.NoError(t, err, caseString) + } else { + require.Equal(t, err, ErrTxTooLarge{ + Max: maxTxSize, + Actual: testCase.len, + }, caseString) + } + } +} + +func TestMempoolTxsBytes(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + + cfg := test.ResetTestRoot("mempool_test") + + cfg.Mempool.MaxTxsBytes = 100 + mp, cleanup := newMempoolWithAppAndConfig(cc, cfg) + defer cleanup() + + // 1. zero by default + assert.EqualValues(t, 0, mp.SizeBytes()) + + // 2. len(tx) after CheckTx + tx1 := kvstore.NewRandomTx(10) + err := mp.CheckTx(tx1, nil, TxInfo{}) + require.NoError(t, err) + assert.EqualValues(t, 10, mp.SizeBytes()) + + // 3. zero again after tx is removed by Update + err = mp.Update(1, []types.Tx{tx1}, abciResponses(1, abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + assert.EqualValues(t, 0, mp.SizeBytes()) + + // 4. zero after Flush + tx2 := kvstore.NewRandomTx(20) + err = mp.CheckTx(tx2, nil, TxInfo{}) + require.NoError(t, err) + assert.EqualValues(t, 20, mp.SizeBytes()) + + mp.Flush() + assert.EqualValues(t, 0, mp.SizeBytes()) + + // 5. ErrMempoolIsFull is returned when/if MaxTxsBytes limit is reached. + tx3 := kvstore.NewRandomTx(100) + err = mp.CheckTx(tx3, nil, TxInfo{}) + require.NoError(t, err) + + tx4 := kvstore.NewRandomTx(10) + err = mp.CheckTx(tx4, nil, TxInfo{}) + if assert.Error(t, err) { + assert.IsType(t, ErrMempoolIsFull{}, err) + } + + // 6. zero after tx is rechecked and removed due to not being valid anymore + app2 := kvstore.NewInMemoryApplication() + cc = proxy.NewLocalClientCreator(app2) + + mp, cleanup = newMempoolWithApp(cc) + defer cleanup() + + txBytes := kvstore.NewRandomTx(10) + + err = mp.CheckTx(txBytes, nil, TxInfo{}) + require.NoError(t, err) + assert.EqualValues(t, 10, mp.SizeBytes()) + + appConnCon, _ := cc.NewABCIClient() + appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus")) + err = appConnCon.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := appConnCon.Stop(); err != nil { + t.Error(err) + } + }) + + res, err := appConnCon.FinalizeBlock(context.Background(), &abci.RequestFinalizeBlock{Txs: [][]byte{txBytes}}) + require.NoError(t, err) + require.EqualValues(t, 0, res.TxResults[0].Code) + require.NotEmpty(t, res.AppHash) + + _, err = appConnCon.Commit(context.Background(), &abci.RequestCommit{}) + require.NoError(t, err) + + // Pretend like we committed nothing so txBytes gets rechecked and removed. + err = mp.Update(1, []types.Tx{}, abciResponses(0, abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + assert.EqualValues(t, 10, mp.SizeBytes()) + + // 7. Test RemoveTxByKey function + err = mp.CheckTx(tx1, nil, TxInfo{}) + require.NoError(t, err) + assert.EqualValues(t, 20, mp.SizeBytes()) + assert.Error(t, mp.RemoveTxByKey(types.Tx([]byte{0x07}).Key())) + assert.EqualValues(t, 20, mp.SizeBytes()) + assert.NoError(t, mp.RemoveTxByKey(types.Tx(tx1).Key())) + assert.EqualValues(t, 10, mp.SizeBytes()) +} + +func TestMempoolNoCacheOverflow(t *testing.T) { + mp, cleanup := newMempoolWithAsyncConnection(t) + defer cleanup() + + // add tx0 + tx0 := kvstore.NewTxFromID(0) + err := mp.CheckTx(tx0, nil, TxInfo{}) + require.NoError(t, err) + err = mp.FlushAppConn() + require.NoError(t, err) + + // saturate the cache to remove tx0 + for i := 1; i <= mp.config.CacheSize; i++ { + err = mp.CheckTx(kvstore.NewTxFromID(i), nil, TxInfo{}) + require.NoError(t, err) + } + err = mp.FlushAppConn() + require.NoError(t, err) + assert.False(t, mp.cache.Has(kvstore.NewTxFromID(0))) + + // add again tx0 + err = mp.CheckTx(tx0, nil, TxInfo{}) + require.NoError(t, err) + err = mp.FlushAppConn() + require.NoError(t, err) + + // tx0 should appear only once in mp.txs + found := 0 + for e := mp.txs.Front(); e != nil; e = e.Next() { + if types.Tx.Key(e.Value.(*mempoolTx).tx) == types.Tx.Key(tx0) { + found++ + } + } + assert.True(t, found == 1) +} + +// This will non-deterministically catch some concurrency failures like +// https://github.com/tendermint/tendermint/issues/3509 +// TODO: all of the tests should probably also run using the remote proxy app +// since otherwise we're not actually testing the concurrency of the mempool here! +func TestMempoolRemoteAppConcurrency(t *testing.T) { + mp, cleanup := newMempoolWithAsyncConnection(t) + defer cleanup() + + // generate small number of txs + nTxs := 10 + txLen := 200 + txs := make([]types.Tx, nTxs) + for i := 0; i < nTxs; i++ { + txs[i] = kvstore.NewRandomTx(txLen) + } + + // simulate a group of peers sending them over and over + n := mp.config.Size + maxPeers := 5 + for i := 0; i < n; i++ { + peerID := mrand.Intn(maxPeers) + txNum := mrand.Intn(nTxs) + tx := txs[txNum] + + // this will err with ErrTxInCache many times ... + mp.CheckTx(tx, nil, TxInfo{SenderID: uint16(peerID)}) //nolint: errcheck // will error + } + + require.NoError(t, mp.FlushAppConn()) +} + +func TestMempoolConcurrentUpdateAndReceiveCheckTxResponse(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + + cfg := test.ResetTestRoot("mempool_test") + mp, cleanup := newMempoolWithAppAndConfig(cc, cfg) + defer cleanup() + + for h := 1; h <= 100; h++ { + // Two concurrent threads for each height. One updates the mempool with one valid tx, + // writing the pool's height; the other, receives a CheckTx response, reading the height. + var wg sync.WaitGroup + wg.Add(2) + + go func(h int) { + defer wg.Done() + + doUpdate(t, mp, int64(h), []types.Tx{tx}) + require.Equal(t, int64(h), mp.height.Load(), "height mismatch") + }(h) + + go func(h int) { + defer wg.Done() + + tx := kvstore.NewTxFromID(h) + mp.resCbFirstTime(tx, TxInfo{}, abci.ToResponseCheckTx(&abci.ResponseCheckTx{Code: abci.CodeTypeOK})) + require.Equal(t, h, mp.Size(), "pool size mismatch") + }(h) + + wg.Wait() + } +} + +func TestMempoolNotifyTxsAvailable(t *testing.T) { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + + cfg := test.ResetTestRoot("mempool_test") + mp, cleanup := newMempoolWithAppAndConfig(cc, cfg) + defer cleanup() + + mp.EnableTxsAvailable() + assert.NotNil(t, mp.txsAvailable) + require.False(t, mp.notifiedTxsAvailable.Load()) + + // Adding a new valid tx to the pool will notify a tx is available + tx := kvstore.NewTxFromID(1) + mp.resCbFirstTime(tx, TxInfo{}, abci.ToResponseCheckTx(&abci.ResponseCheckTx{Code: abci.CodeTypeOK})) + require.Equal(t, 1, mp.Size(), "pool size mismatch") + require.True(t, mp.notifiedTxsAvailable.Load()) + require.Len(t, mp.TxsAvailable(), 1) + <-mp.TxsAvailable() + + // Receiving CheckTx response for a tx already in the pool should not notify of available txs + mp.resCbFirstTime(tx, TxInfo{}, abci.ToResponseCheckTx(&abci.ResponseCheckTx{Code: abci.CodeTypeOK})) + require.Equal(t, 1, mp.Size()) + require.True(t, mp.notifiedTxsAvailable.Load()) + require.Empty(t, mp.TxsAvailable()) + + // Updating the pool will remove the tx and set the variable to false + err := mp.Update(1, []types.Tx{tx}, abciResponses(1, abci.CodeTypeOK), nil, nil) + require.NoError(t, err) + require.Zero(t, mp.Size()) + require.False(t, mp.notifiedTxsAvailable.Load()) +} + +// Test that adding a transaction panics when the CheckTx request fails. +func TestMempoolSyncCheckTxReturnError(t *testing.T) { + mockClient := new(abciclimocks.Client) + mockClient.On("Start").Return(nil) + mockClient.On("SetLogger", mock.Anything) + mockClient.On("SetResponseCallback", mock.Anything) + + mp, cleanup, err := newMempoolWithAppMock(mockClient) + require.NoError(t, err) + defer cleanup() + + // The app will return an error on a CheckTx request. + tx := []byte{0x01} + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(nil, errors.New("")).Once() + + // Adding the transaction should panic when the call to the app returns an error. + defer func() { + if r := recover(); r == nil { + t.Errorf("CheckTx did not panic") + } + }() + err = mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(t, err) +} + +// Test that rechecking panics when a CheckTx request fails, when using a sync ABCI client. +func TestMempoolSyncRecheckTxReturnError(t *testing.T) { + mockClient := new(abciclimocks.Client) + mockClient.On("Start").Return(nil) + mockClient.On("SetLogger", mock.Anything) + mockClient.On("SetResponseCallback", mock.Anything) + mockClient.On("Error").Return(nil) + + mp, cleanup, err := newMempoolWithAppMock(mockClient) + require.NoError(t, err) + defer cleanup() + + // First we add a two transactions to the mempool. + txs := []types.Tx{[]byte{0x01}, []byte{0x02}} + for _, tx := range txs { + reqRes := newReqRes(tx, abci.CodeTypeOK, abci.CheckTxType_New) + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(reqRes, nil).Once() + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(t, err) + + // ensure that the callback that the mempool sets on the ReqRes is run. + reqRes.InvokeCallback() + } + require.Len(t, txs, mp.Size()) + + // The first tx is valid when rechecking and the client will call the callback right after the + // response from the app and before returning. + reqRes0 := newReqRes(txs[0], abci.CodeTypeOK, abci.CheckTxType_Recheck) + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(reqRes0, nil).Once() + + // On the second CheckTx request, the app returns an error. + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(nil, errors.New("")).Once() + + // Rechecking should panic when the call to the app returns an error. + defer func() { + if r := recover(); r == nil { + t.Errorf("recheckTxs did not panic") + } + }() + mp.recheckTxs() +} + +// Test that rechecking finishes correctly when a CheckTx response never arrives, when using an +// async ABCI client. +func TestMempoolAsyncRecheckTxReturnError(t *testing.T) { + var callback abciclient.Callback + mockClient := new(abciclimocks.Client) + mockClient.On("Start").Return(nil) + mockClient.On("SetLogger", mock.Anything) + mockClient.On("Error").Return(nil).Times(4) + mockClient.On("SetResponseCallback", mock.MatchedBy(func(cb abciclient.Callback) bool { callback = cb; return true })) + + mp, cleanup, err := newMempoolWithAppMock(mockClient) + require.NoError(t, err) + defer cleanup() + + // Add 4 txs to the mempool. + txs := []types.Tx{[]byte{0x01}, []byte{0x02}, []byte{0x03}, []byte{0x04}} + for _, tx := range txs { + reqRes := newReqRes(tx, abci.CodeTypeOK, abci.CheckTxType_New) + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(reqRes, nil).Once() + err := mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(t, err) + + // ensure that the callback that the mempool sets on the ReqRes is run. + reqRes.InvokeCallback() + } + + // The 4 txs are added to the mempool. + require.Len(t, txs, mp.Size()) + + // Check that recheck has not started. + require.True(t, mp.recheck.done()) + require.Nil(t, mp.recheck.cursor) + require.Nil(t, mp.recheck.end) + require.False(t, mp.recheck.isRechecking.Load()) + mockClient.AssertExpectations(t) + + // One call to CheckTxAsync per tx, for rechecking. + mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(nil, nil).Times(4) + + // On the async client, the callbacks are executed when flushing the connection. The app replies + // to the request for the first tx (valid) and for the third tx (invalid), so the callback is + // invoked twice. The app does not reply to the requests for the second and fourth txs, so the + // callback is not invoked on these two cases. + mockClient.On("Flush", mock.Anything).Run(func(_ mock.Arguments) { + // First tx is valid. + reqRes1 := newReqRes(txs[0], abci.CodeTypeOK, abci.CheckTxType_Recheck) + callback(reqRes1.Request, reqRes1.Response) + // Third tx is invalid. + reqRes2 := newReqRes(txs[2], 1, abci.CheckTxType_Recheck) + callback(reqRes2.Request, reqRes2.Response) + }).Return(nil) + + // mp.recheck.done() should be true only before and after calling recheckTxs. + mp.recheckTxs() + require.True(t, mp.recheck.done()) + require.False(t, mp.recheck.isRechecking.Load()) + require.Nil(t, mp.recheck.cursor) + require.NotNil(t, mp.recheck.end) + require.Equal(t, mp.recheck.end, mp.txs.Back()) + require.Equal(t, len(txs)-1, mp.Size()) // one invalid tx was removed + require.Equal(t, int32(2), mp.recheck.numPendingTxs.Load()) + + mockClient.AssertExpectations(t) +} + +// This test used to cause a data race when rechecking (see https://github.com/cometbft/cometbft/issues/1827). +func TestMempoolRecheckRace(t *testing.T) { + mp, cleanup := newMempoolWithAsyncConnection(t) + defer cleanup() + + // Add a bunch of transactions to the mempool. + var err error + txs := newUniqueTxs(10) + for _, tx := range txs { + err = mp.CheckTx(tx, nil, TxInfo{}) + require.NoError(t, err) + } + + // Update one transaction to force rechecking the rest. + doUpdate(t, mp, 1, txs[:1]) + + // Recheck has finished + require.True(t, mp.recheck.done()) + require.Nil(t, mp.recheck.cursor) + + // Add again the same transaction that was updated. Recheck has finished so adding this tx + // should not result in a data race on the variable recheck.cursor. + err = mp.CheckTx(txs[:1][0], nil, TxInfo{}) + require.Equal(t, err, ErrTxInCache) + require.Zero(t, mp.recheck.numPendingTxs.Load()) +} + +// Test adding transactions while a concurrent routine reaps txs and updates the mempool, simulating +// the consensus module, when using an async ABCI client. +func TestMempoolConcurrentCheckTxAndUpdate(t *testing.T) { + mp, cleanup := newMempoolWithAsyncConnection(t) + defer cleanup() + + maxHeight := 100 + var wg sync.WaitGroup + wg.Add(1) + + // A process that continuously reaps and update the mempool, simulating creation and committing + // of blocks by the consensus module. + go func() { + defer wg.Done() + + time.Sleep(50 * time.Millisecond) // wait a bit to have some txs in mempool before starting updating + for h := 1; h <= maxHeight; h++ { + if mp.Size() == 0 { + break + } + txs := mp.ReapMaxBytesMaxGas(100, -1) + doUpdate(t, mp, int64(h), txs) + } + }() + + // Concurrently, add transactions (one per height). + for h := 1; h <= maxHeight; h++ { + err := mp.CheckTx(kvstore.NewTxFromID(h), nil, TxInfo{}) + require.NoError(t, err) + } + + wg.Wait() + + // All added transactions should have been removed from the mempool. + require.Zero(t, mp.Size()) +} + +func newMempoolWithAsyncConnection(tb testing.TB) (*CListMempool, cleanupFunc) { + tb.Helper() + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmtrand.Str(6)) + app := kvstore.NewInMemoryApplication() + _, server := newRemoteApp(tb, sockPath, app) + tb.Cleanup(func() { + if err := server.Stop(); err != nil { + tb.Error(err) + } + }) + cfg := test.ResetTestRoot("mempool_test") + return newMempoolWithAppAndConfig(proxy.NewRemoteClientCreator(sockPath, "socket", true), cfg) +} + +// caller must close server. +func newRemoteApp(tb testing.TB, addr string, app abci.Application) (abciclient.Client, service.Service) { + tb.Helper() + clientCreator, err := abciclient.NewClient(addr, "socket", true) + require.NoError(tb, err) + + // Start server + server := abciserver.NewSocketServer(addr, app) + server.SetLogger(log.TestingLogger().With("module", "abci-server")) + if err := server.Start(); err != nil { + tb.Fatalf("Error starting socket server: %v", err.Error()) + } + + return clientCreator, server +} + +func newReqRes(tx types.Tx, code uint32, requestType abci.CheckTxType) *abciclient.ReqRes { //nolint: unparam + reqRes := abciclient.NewReqRes(abci.ToRequestCheckTx(&abci.RequestCheckTx{Tx: tx, Type: requestType})) + reqRes.Response = abci.ToResponseCheckTx(&abci.ResponseCheckTx{Code: code}) + return reqRes +} + +func abciResponses(n int, code uint32) []*abci.ExecTxResult { + responses := make([]*abci.ExecTxResult, 0, n) + for i := 0; i < n; i++ { + responses = append(responses, &abci.ExecTxResult{Code: code}) + } + return responses +} + +func doUpdate(tb testing.TB, mp Mempool, height int64, txs []types.Tx) { + tb.Helper() + mp.Lock() + err := mp.FlushAppConn() + require.NoError(tb, err) + err = mp.Update(height, txs, abciResponses(len(txs), abci.CodeTypeOK), nil, nil) + require.NoError(tb, err) + mp.Unlock() +} diff --git a/mempool/doc.go b/mempool/doc.go new file mode 100644 index 0000000..50a339b --- /dev/null +++ b/mempool/doc.go @@ -0,0 +1,23 @@ +// The mempool pushes new txs onto the proxyAppConn. +// It gets a stream of (req, res) tuples from the proxy. +// The mempool stores good txs in a concurrent linked-list. + +// Multiple concurrent go-routines can traverse this linked-list +// safely by calling .NextWait() on each element. + +// So we have several go-routines: +// 1. Consensus calling Update() and ReapMaxBytesMaxGas() synchronously +// 2. Many mempool reactor's peer routines calling CheckTx() +// 3. Many mempool reactor's peer routines traversing the txs linked list + +// To manage these goroutines, there are three methods of locking. +// 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe) +// 2. Mutations to the linked-list elements are atomic +// 3. CheckTx() and/or ReapMaxBytesMaxGas() calls can be paused upon Update(), protected by .updateMtx + +// Garbage collection of old elements from mempool.txs is handlde via the +// DetachPrev() call, which makes old elements not reachable by peer +// broadcastTxRoutine(). + +// TODO: Better handle abci client errors. (make it automatically handle connection errors) +package mempool diff --git a/mempool/errors.go b/mempool/errors.go new file mode 100644 index 0000000..944f407 --- /dev/null +++ b/mempool/errors.go @@ -0,0 +1,89 @@ +package mempool + +import ( + "errors" + "fmt" +) + +// ErrTxNotFound is returned to the client if tx is not found in mempool +var ErrTxNotFound = errors.New("transaction not found in mempool") + +// ErrTxInCache is returned to the client if we saw tx earlier +var ErrTxInCache = errors.New("tx already exists in cache") + +// ErrRecheckFull is returned when checking if the mempool is full and +// rechecking is still in progress after a new block was committed. +var ErrRecheckFull = errors.New("mempool is still rechecking after a new committed block, so it is considered as full") + +// ErrTxTooLarge defines an error when a transaction is too big to be sent in a +// message to other peers. +type ErrTxTooLarge struct { + Max int + Actual int +} + +func (e ErrTxTooLarge) Error() string { + return fmt.Sprintf("Tx too large. Max size is %d, but got %d", e.Max, e.Actual) +} + +// ErrMempoolIsFull defines an error where CometBFT and the application cannot +// handle that much load. +type ErrMempoolIsFull struct { + NumTxs int + MaxTxs int + TxsBytes int64 + MaxTxsBytes int64 + RecheckFull bool +} + +func (e ErrMempoolIsFull) Error() string { + return fmt.Sprintf( + "mempool is full: number of txs %d (max: %d), total txs bytes %d (max: %d)", + e.NumTxs, + e.MaxTxs, + e.TxsBytes, + e.MaxTxsBytes, + ) +} + +// ErrPreCheck defines an error where a transaction fails a pre-check. +type ErrPreCheck struct { + Err error +} + +func (e ErrPreCheck) Error() string { + return fmt.Sprintf("tx pre check: %v", e.Err) +} + +func (e ErrPreCheck) Unwrap() error { + return e.Err +} + +// IsPreCheckError returns true if err is due to pre check failure. +func IsPreCheckError(err error) bool { + return errors.As(err, &ErrPreCheck{}) +} + +type ErrAppConnMempool struct { + Err error +} + +func (e ErrAppConnMempool) Error() string { + return fmt.Sprintf("appConn mempool: %v", e.Err) +} + +func (e ErrAppConnMempool) Unwrap() error { + return e.Err +} + +type ErrFlushAppConn struct { + Err error +} + +func (e ErrFlushAppConn) Error() string { + return fmt.Sprintf("flush appConn mempool: %v", e.Err) +} + +func (e ErrFlushAppConn) Unwrap() error { + return e.Err +} diff --git a/mempool/ids.go b/mempool/ids.go new file mode 100644 index 0000000..36ff87d --- /dev/null +++ b/mempool/ids.go @@ -0,0 +1,71 @@ +package mempool + +import ( + "fmt" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" +) + +type mempoolIDs struct { + mtx cmtsync.RWMutex + peerMap map[p2p.ID]uint16 + nextID uint16 // assumes that a node will never have over 65536 active peers + activeIDs map[uint16]struct{} // used to check if a given peerID key is used, the value doesn't matter +} + +// Reserve searches for the next unused ID and assigns it to the +// peer. +func (ids *mempoolIDs) ReserveForPeer(peer p2p.Peer) { + ids.mtx.Lock() + defer ids.mtx.Unlock() + + curID := ids.nextPeerID() + ids.peerMap[peer.ID()] = curID + ids.activeIDs[curID] = struct{}{} +} + +// nextPeerID returns the next unused peer ID to use. +// This assumes that ids's mutex is already locked. +func (ids *mempoolIDs) nextPeerID() uint16 { + if len(ids.activeIDs) == MaxActiveIDs { + panic(fmt.Sprintf("node has maximum %d active IDs and wanted to get one more", MaxActiveIDs)) + } + + _, idExists := ids.activeIDs[ids.nextID] + for idExists { + ids.nextID++ + _, idExists = ids.activeIDs[ids.nextID] + } + curID := ids.nextID + ids.nextID++ + return curID +} + +// Reclaim returns the ID reserved for the peer back to unused pool. +func (ids *mempoolIDs) Reclaim(peer p2p.Peer) { + ids.mtx.Lock() + defer ids.mtx.Unlock() + + removedID, ok := ids.peerMap[peer.ID()] + if ok { + delete(ids.activeIDs, removedID) + delete(ids.peerMap, peer.ID()) + } +} + +// GetForPeer returns an ID reserved for the peer. +func (ids *mempoolIDs) GetForPeer(peer p2p.Peer) uint16 { + ids.mtx.RLock() + defer ids.mtx.RUnlock() + + return ids.peerMap[peer.ID()] +} + +func newMempoolIDs() *mempoolIDs { + return &mempoolIDs{ + peerMap: make(map[p2p.ID]uint16), + activeIDs: map[uint16]struct{}{0: {}}, + nextID: 1, // reserve unknownPeerID(0) for mempoolReactor.BroadcastTx + } +} diff --git a/mempool/ids_test.go b/mempool/ids_test.go new file mode 100644 index 0000000..3ab6a12 --- /dev/null +++ b/mempool/ids_test.go @@ -0,0 +1,42 @@ +package mempool + +import ( + "net" + "testing" + + "github.com/cometbft/cometbft/p2p/mock" + "github.com/stretchr/testify/assert" +) + +func TestMempoolIDsBasic(t *testing.T) { + ids := newMempoolIDs() + + peer := mock.NewPeer(net.IP{127, 0, 0, 1}) + + ids.ReserveForPeer(peer) + assert.EqualValues(t, 1, ids.GetForPeer(peer)) + ids.Reclaim(peer) + + ids.ReserveForPeer(peer) + assert.EqualValues(t, 2, ids.GetForPeer(peer)) + ids.Reclaim(peer) +} + +func TestMempoolIDsPanicsIfNodeRequestsOvermaxActiveIDs(t *testing.T) { + if testing.Short() { + return + } + + // 0 is already reserved for UnknownPeerID + ids := newMempoolIDs() + + for i := 0; i < MaxActiveIDs-1; i++ { + peer := mock.NewPeer(net.IP{127, 0, 0, 1}) + ids.ReserveForPeer(peer) + } + + assert.Panics(t, func() { + peer := mock.NewPeer(net.IP{127, 0, 0, 1}) + ids.ReserveForPeer(peer) + }) +} diff --git a/mempool/mempool.go b/mempool/mempool.go new file mode 100644 index 0000000..36edba1 --- /dev/null +++ b/mempool/mempool.go @@ -0,0 +1,149 @@ +package mempool + +import ( + "crypto/sha256" + "fmt" + "math" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/types" +) + +const ( + MempoolChannel = byte(0x30) + + // PeerCatchupSleepIntervalMS defines how much time to sleep if a peer is behind + PeerCatchupSleepIntervalMS = 100 + + // UnknownPeerID is the peer ID to use when running CheckTx when there is + // no peer (e.g. RPC) + UnknownPeerID uint16 = 0 + + MaxActiveIDs = math.MaxUint16 +) + +//go:generate ../scripts/mockery_generate.sh Mempool + +// Mempool defines the mempool interface. +// +// Updates to the mempool need to be synchronized with committing a block so +// applications can reset their transient state on Commit. +type Mempool interface { + // CheckTx executes a new transaction against the application to determine + // its validity and whether it should be added to the mempool. + CheckTx(tx types.Tx, callback func(*abci.ResponseCheckTx), txInfo TxInfo) error + + // RemoveTxByKey removes a transaction, identified by its key, + // from the mempool. + RemoveTxByKey(txKey types.TxKey) error + + // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes + // bytes total with the condition that the total gasWanted must be less than + // maxGas. + // + // If both maxes are negative, there is no cap on the size of all returned + // transactions (~ all available transactions). + ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs + + // ReapMaxTxs reaps up to max transactions from the mempool. If max is + // negative, there is no cap on the size of all returned transactions + // (~ all available transactions). + ReapMaxTxs(max int) types.Txs + + // Lock locks the mempool. The consensus must be able to hold lock to safely + // update. + // Before acquiring the lock, it signals the mempool that a new update is coming. + // If the mempool is still rechecking at this point, it should be considered full. + Lock() + + // Unlock unlocks the mempool. + Unlock() + + // Update informs the mempool that the given txs were committed and can be + // discarded. + // + // NOTE: + // 1. This should be called *after* block is committed by consensus. + // 2. Lock/Unlock must be managed by the caller. + Update( + blockHeight int64, + blockTxs types.Txs, + deliverTxResponses []*abci.ExecTxResult, + newPreFn PreCheckFunc, + newPostFn PostCheckFunc, + ) error + + // FlushAppConn flushes the mempool connection to ensure async callback calls + // are done, e.g. from CheckTx. + // + // NOTE: + // 1. Lock/Unlock must be managed by caller. + FlushAppConn() error + + // Flush removes all transactions from the mempool and caches. + Flush() + + // TxsAvailable returns a channel which fires once for every height, and only + // when transactions are available in the mempool. + // + // NOTE: + // 1. The returned channel may be nil if EnableTxsAvailable was not called. + TxsAvailable() <-chan struct{} + + // EnableTxsAvailable initializes the TxsAvailable channel, ensuring it will + // trigger once every height when transactions are available. + EnableTxsAvailable() + + // Size returns the number of transactions in the mempool. + Size() int + + // SizeBytes returns the total size of all txs in the mempool. + SizeBytes() int64 +} + +// PreCheckFunc is an optional filter executed before CheckTx and rejects +// transaction if false is returned. An example would be to ensure that a +// transaction doesn't exceeded the block size. +type PreCheckFunc func(types.Tx) error + +// PostCheckFunc is an optional filter executed after CheckTx and rejects +// transaction if false is returned. An example would be to ensure a +// transaction doesn't require more gas than available for the block. +type PostCheckFunc func(types.Tx, *abci.ResponseCheckTx) error + +// PreCheckMaxBytes checks that the size of the transaction is smaller or equal +// to the expected maxBytes. +func PreCheckMaxBytes(maxBytes int64) PreCheckFunc { + return func(tx types.Tx) error { + txSize := types.ComputeProtoSizeForTxs([]types.Tx{tx}) + + if txSize > maxBytes { + return fmt.Errorf("tx size is too big: %d, max: %d", txSize, maxBytes) + } + + return nil + } +} + +// PostCheckMaxGas checks that the wanted gas is smaller or equal to the passed +// maxGas. Returns nil if maxGas is -1. +func PostCheckMaxGas(maxGas int64) PostCheckFunc { + return func(tx types.Tx, res *abci.ResponseCheckTx) error { + if maxGas == -1 { + return nil + } + if res.GasWanted < 0 { + return fmt.Errorf("gas wanted %d is negative", + res.GasWanted) + } + if res.GasWanted > maxGas { + return fmt.Errorf("gas wanted %d is greater than max gas %d", + res.GasWanted, maxGas) + } + + return nil + } +} + +// TxKey is the fixed length array key used as an index. +type TxKey [sha256.Size]byte diff --git a/mempool/mempoolTx.go b/mempool/mempoolTx.go new file mode 100644 index 0000000..b387b4b --- /dev/null +++ b/mempool/mempoolTx.go @@ -0,0 +1,34 @@ +package mempool + +import ( + "sync" + "sync/atomic" + + "github.com/cometbft/cometbft/types" +) + +// mempoolTx is an entry in the mempool +type mempoolTx struct { + height int64 // height that this tx had been validated in + gasWanted int64 // amount of gas this tx states it will require + tx types.Tx // validated by the application + + // ids of peers who've sent us this tx (as a map for quick lookups). + // senders: PeerID -> bool + senders sync.Map +} + +// Height returns the height for this transaction +func (memTx *mempoolTx) Height() int64 { + return atomic.LoadInt64(&memTx.height) +} + +func (memTx *mempoolTx) isSender(peerID uint16) bool { + _, ok := memTx.senders.Load(peerID) + return ok +} + +func (memTx *mempoolTx) addSender(senderID uint16) bool { + _, added := memTx.senders.LoadOrStore(senderID, true) + return added +} diff --git a/mempool/metrics.gen.go b/mempool/metrics.gen.go new file mode 100644 index 0000000..69be716 --- /dev/null +++ b/mempool/metrics.gen.go @@ -0,0 +1,81 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package mempool + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Size: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "size", + Help: "Number of uncommitted transactions in the mempool.", + }, labels).With(labelsAndValues...), + SizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "size_bytes", + Help: "Total size of the mempool in bytes.", + }, labels).With(labelsAndValues...), + TxSizeBytes: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "tx_size_bytes", + Help: "Histogram of transaction sizes in bytes.", + + Buckets: stdprometheus.ExponentialBuckets(1, 3, 7), + }, labels).With(labelsAndValues...), + FailedTxs: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "failed_txs", + Help: "FailedTxs defines the number of failed transactions. These are transactions that failed to make it into the mempool because they were deemed invalid. metrics:Number of failed transactions.", + }, labels).With(labelsAndValues...), + RejectedTxs: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "rejected_txs", + Help: "RejectedTxs defines the number of rejected transactions. These are transactions that failed to make it into the mempool due to resource limits, e.g. mempool is full. metrics:Number of rejected transactions.", + }, labels).With(labelsAndValues...), + EvictedTxs: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "evicted_txs", + Help: "EvictedTxs defines the number of evicted transactions. These are valid transactions that passed CheckTx and make it into the mempool but later became invalid. metrics:Number of evicted transactions.", + }, labels).With(labelsAndValues...), + RecheckTimes: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "recheck_times", + Help: "Number of times transactions are rechecked in the mempool.", + }, labels).With(labelsAndValues...), + ActiveOutboundConnections: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "active_outbound_connections", + Help: "Number of connections being actively used for gossiping transactions (experimental feature).", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Size: discard.NewGauge(), + SizeBytes: discard.NewGauge(), + TxSizeBytes: discard.NewHistogram(), + FailedTxs: discard.NewCounter(), + RejectedTxs: discard.NewCounter(), + EvictedTxs: discard.NewCounter(), + RecheckTimes: discard.NewCounter(), + ActiveOutboundConnections: discard.NewGauge(), + } +} diff --git a/mempool/metrics.go b/mempool/metrics.go new file mode 100644 index 0000000..61ab964 --- /dev/null +++ b/mempool/metrics.go @@ -0,0 +1,51 @@ +package mempool + +import ( + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "mempool" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +// see MetricsProvider for descriptions. +type Metrics struct { + // Number of uncommitted transactions in the mempool. + Size metrics.Gauge + + // Total size of the mempool in bytes. + SizeBytes metrics.Gauge + + // Histogram of transaction sizes in bytes. + TxSizeBytes metrics.Histogram `metrics_buckettype:"exp" metrics_bucketsizes:"1,3,7"` + + // FailedTxs defines the number of failed transactions. These are + // transactions that failed to make it into the mempool because they were + // deemed invalid. + // metrics:Number of failed transactions. + FailedTxs metrics.Counter + + // RejectedTxs defines the number of rejected transactions. These are + // transactions that failed to make it into the mempool due to resource + // limits, e.g. mempool is full. + // metrics:Number of rejected transactions. + RejectedTxs metrics.Counter + + // EvictedTxs defines the number of evicted transactions. These are valid + // transactions that passed CheckTx and make it into the mempool but later + // became invalid. + // metrics:Number of evicted transactions. + EvictedTxs metrics.Counter + + // Number of times transactions are rechecked in the mempool. + RecheckTimes metrics.Counter + + // Number of connections being actively used for gossiping transactions + // (experimental feature). + ActiveOutboundConnections metrics.Gauge +} diff --git a/mempool/mocks/mempool.go b/mempool/mocks/mempool.go new file mode 100644 index 0000000..5b19e27 --- /dev/null +++ b/mempool/mocks/mempool.go @@ -0,0 +1,219 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + abcitypes "github.com/cometbft/cometbft/abci/types" + mempool "github.com/cometbft/cometbft/mempool" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/types" +) + +// Mempool is an autogenerated mock type for the Mempool type +type Mempool struct { + mock.Mock +} + +// CheckTx provides a mock function with given fields: tx, callback, txInfo +func (_m *Mempool) CheckTx(tx types.Tx, callback func(*abcitypes.ResponseCheckTx), txInfo mempool.TxInfo) error { + ret := _m.Called(tx, callback, txInfo) + + if len(ret) == 0 { + panic("no return value specified for CheckTx") + } + + var r0 error + if rf, ok := ret.Get(0).(func(types.Tx, func(*abcitypes.ResponseCheckTx), mempool.TxInfo) error); ok { + r0 = rf(tx, callback, txInfo) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// EnableTxsAvailable provides a mock function with no fields +func (_m *Mempool) EnableTxsAvailable() { + _m.Called() +} + +// Flush provides a mock function with no fields +func (_m *Mempool) Flush() { + _m.Called() +} + +// FlushAppConn provides a mock function with no fields +func (_m *Mempool) FlushAppConn() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for FlushAppConn") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Lock provides a mock function with no fields +func (_m *Mempool) Lock() { + _m.Called() +} + +// ReapMaxBytesMaxGas provides a mock function with given fields: maxBytes, maxGas +func (_m *Mempool) ReapMaxBytesMaxGas(maxBytes int64, maxGas int64) types.Txs { + ret := _m.Called(maxBytes, maxGas) + + if len(ret) == 0 { + panic("no return value specified for ReapMaxBytesMaxGas") + } + + var r0 types.Txs + if rf, ok := ret.Get(0).(func(int64, int64) types.Txs); ok { + r0 = rf(maxBytes, maxGas) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Txs) + } + } + + return r0 +} + +// ReapMaxTxs provides a mock function with given fields: max +func (_m *Mempool) ReapMaxTxs(max int) types.Txs { + ret := _m.Called(max) + + if len(ret) == 0 { + panic("no return value specified for ReapMaxTxs") + } + + var r0 types.Txs + if rf, ok := ret.Get(0).(func(int) types.Txs); ok { + r0 = rf(max) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Txs) + } + } + + return r0 +} + +// RemoveTxByKey provides a mock function with given fields: txKey +func (_m *Mempool) RemoveTxByKey(txKey types.TxKey) error { + ret := _m.Called(txKey) + + if len(ret) == 0 { + panic("no return value specified for RemoveTxByKey") + } + + var r0 error + if rf, ok := ret.Get(0).(func(types.TxKey) error); ok { + r0 = rf(txKey) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Size provides a mock function with no fields +func (_m *Mempool) Size() int { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Size") + } + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + return r0 +} + +// SizeBytes provides a mock function with no fields +func (_m *Mempool) SizeBytes() int64 { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for SizeBytes") + } + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// TxsAvailable provides a mock function with no fields +func (_m *Mempool) TxsAvailable() <-chan struct{} { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for TxsAvailable") + } + + var r0 <-chan struct{} + if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan struct{}) + } + } + + return r0 +} + +// Unlock provides a mock function with no fields +func (_m *Mempool) Unlock() { + _m.Called() +} + +// Update provides a mock function with given fields: blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn +func (_m *Mempool) Update(blockHeight int64, blockTxs types.Txs, deliverTxResponses []*abcitypes.ExecTxResult, newPreFn mempool.PreCheckFunc, newPostFn mempool.PostCheckFunc) error { + ret := _m.Called(blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn) + + if len(ret) == 0 { + panic("no return value specified for Update") + } + + var r0 error + if rf, ok := ret.Get(0).(func(int64, types.Txs, []*abcitypes.ExecTxResult, mempool.PreCheckFunc, mempool.PostCheckFunc) error); ok { + r0 = rf(blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// NewMempool creates a new instance of Mempool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMempool(t interface { + mock.TestingT + Cleanup(func()) +}) *Mempool { + mock := &Mempool{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/mempool/nop_mempool.go b/mempool/nop_mempool.go new file mode 100644 index 0000000..38f80ea --- /dev/null +++ b/mempool/nop_mempool.go @@ -0,0 +1,107 @@ +package mempool + +import ( + "errors" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/types" +) + +// NopMempool is a mempool that does nothing. +// +// The ABCI app is responsible for storing, disseminating, and proposing transactions. +// See [ADR-111](../docs/architecture/adr-111-nop-mempool.md). +type NopMempool struct{} + +// errNotAllowed indicates that the operation is not allowed with `nop` mempool. +var errNotAllowed = errors.New("not allowed with `nop` mempool") + +var _ Mempool = &NopMempool{} + +// CheckTx always returns an error. +func (*NopMempool) CheckTx(types.Tx, func(*abci.ResponseCheckTx), TxInfo) error { + return errNotAllowed +} + +// RemoveTxByKey always returns an error. +func (*NopMempool) RemoveTxByKey(types.TxKey) error { return errNotAllowed } + +// ReapMaxBytesMaxGas always returns nil. +func (*NopMempool) ReapMaxBytesMaxGas(int64, int64) types.Txs { return nil } + +// ReapMaxTxs always returns nil. +func (*NopMempool) ReapMaxTxs(int) types.Txs { return nil } + +// Lock does nothing. +func (*NopMempool) Lock() {} + +// Unlock does nothing. +func (*NopMempool) Unlock() {} + +// Update does nothing. +func (*NopMempool) Update( + int64, + types.Txs, + []*abci.ExecTxResult, + PreCheckFunc, + PostCheckFunc, +) error { + return nil +} + +// FlushAppConn does nothing. +func (*NopMempool) FlushAppConn() error { return nil } + +// Flush does nothing. +func (*NopMempool) Flush() {} + +// TxsAvailable always returns nil. +func (*NopMempool) TxsAvailable() <-chan struct{} { + return nil +} + +// EnableTxsAvailable does nothing. +func (*NopMempool) EnableTxsAvailable() {} + +// SetTxRemovedCallback does nothing. +func (*NopMempool) SetTxRemovedCallback(func(txKey types.TxKey)) {} + +// Size always returns 0. +func (*NopMempool) Size() int { return 0 } + +// SizeBytes always returns 0. +func (*NopMempool) SizeBytes() int64 { return 0 } + +// NopMempoolReactor is a mempool reactor that does nothing. +type NopMempoolReactor struct { + service.BaseService +} + +// NewNopMempoolReactor returns a new `nop` reactor. +// +// To be used only in RPC. +func NewNopMempoolReactor() *NopMempoolReactor { + return &NopMempoolReactor{*service.NewBaseService(nil, "NopMempoolReactor", nil)} +} + +var _ p2p.Reactor = &NopMempoolReactor{} + +// GetChannels always returns nil. +func (*NopMempoolReactor) GetChannels() []*p2p.ChannelDescriptor { return nil } + +// AddPeer does nothing. +func (*NopMempoolReactor) AddPeer(p2p.Peer) {} + +// InitPeer always returns nil. +func (*NopMempoolReactor) InitPeer(p2p.Peer) p2p.Peer { return nil } + +// RemovePeer does nothing. +func (*NopMempoolReactor) RemovePeer(p2p.Peer, interface{}) {} + +// Receive does nothing. +func (*NopMempoolReactor) Receive(p2p.Envelope) {} + +// SetSwitch does nothing. +func (*NopMempoolReactor) SetSwitch(*p2p.Switch) {} diff --git a/mempool/nop_mempool_test.go b/mempool/nop_mempool_test.go new file mode 100644 index 0000000..51169e5 --- /dev/null +++ b/mempool/nop_mempool_test.go @@ -0,0 +1,38 @@ +package mempool + +import ( + "testing" + + "github.com/cometbft/cometbft/types" + "github.com/stretchr/testify/assert" +) + +var tx = types.Tx([]byte{0x01}) + +func TestNopMempool_Basic(t *testing.T) { + mem := &NopMempool{} + + assert.Equal(t, 0, mem.Size()) + assert.Equal(t, int64(0), mem.SizeBytes()) + + err := mem.CheckTx(tx, nil, TxInfo{}) + assert.Equal(t, errNotAllowed, err) + + err = mem.RemoveTxByKey(tx.Key()) + assert.Equal(t, errNotAllowed, err) + + txs := mem.ReapMaxBytesMaxGas(0, 0) + assert.Nil(t, txs) + + txs = mem.ReapMaxTxs(0) + assert.Nil(t, txs) + + err = mem.FlushAppConn() + assert.NoError(t, err) + + err = mem.Update(0, nil, nil, nil, nil) + assert.NoError(t, err) + + txsAvailable := mem.TxsAvailable() + assert.Nil(t, txsAvailable) +} diff --git a/mempool/reactor.go b/mempool/reactor.go new file mode 100644 index 0000000..304db98 --- /dev/null +++ b/mempool/reactor.go @@ -0,0 +1,264 @@ +package mempool + +import ( + "context" + "errors" + "time" + + "fmt" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/clist" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + protomem "github.com/cometbft/cometbft/proto/tendermint/mempool" + "github.com/cometbft/cometbft/types" + "golang.org/x/sync/semaphore" +) + +// Reactor handles mempool tx broadcasting amongst peers. +// It maintains a map from peer ID to counter, to prevent gossiping txs to the +// peers you received it from. +type Reactor struct { + p2p.BaseReactor + config *cfg.MempoolConfig + mempool *CListMempool + ids *mempoolIDs + + // Semaphores to keep track of how many connections to peers are active for broadcasting + // transactions. Each semaphore has a capacity that puts an upper bound on the number of + // connections for different groups of peers. + activePersistentPeersSemaphore *semaphore.Weighted + activeNonPersistentPeersSemaphore *semaphore.Weighted +} + +// NewReactor returns a new Reactor with the given config and mempool. +func NewReactor(config *cfg.MempoolConfig, mempool *CListMempool) *Reactor { + memR := &Reactor{ + config: config, + mempool: mempool, + ids: newMempoolIDs(), + } + memR.BaseReactor = *p2p.NewBaseReactor("Mempool", memR) + memR.activePersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers)) + memR.activeNonPersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers)) + + return memR +} + +// InitPeer implements Reactor by creating a state for the peer. +func (memR *Reactor) InitPeer(peer p2p.Peer) p2p.Peer { + memR.ids.ReserveForPeer(peer) + return peer +} + +// SetLogger sets the Logger on the reactor and the underlying mempool. +func (memR *Reactor) SetLogger(l log.Logger) { + memR.Logger = l + memR.mempool.SetLogger(l) +} + +// OnStart implements p2p.BaseReactor. +func (memR *Reactor) OnStart() error { + if !memR.config.Broadcast { + memR.Logger.Info("Tx broadcasting is disabled") + } + return nil +} + +// GetChannels implements Reactor by returning the list of channels for this +// reactor. +func (memR *Reactor) GetChannels() []*p2p.ChannelDescriptor { + largestTx := make([]byte, memR.config.MaxTxBytes) + batchMsg := protomem.Message{ + Sum: &protomem.Message_Txs{ + Txs: &protomem.Txs{Txs: [][]byte{largestTx}}, + }, + } + + return []*p2p.ChannelDescriptor{ + { + ID: MempoolChannel, + Priority: 5, + RecvMessageCapacity: batchMsg.Size(), + MessageType: &protomem.Message{}, + }, + } +} + +// AddPeer implements Reactor. +// It starts a broadcast routine ensuring all txs are forwarded to the given peer. +func (memR *Reactor) AddPeer(peer p2p.Peer) { + if memR.config.Broadcast { + go func() { + // Always forward transactions to unconditional peers. + if !memR.Switch.IsPeerUnconditional(peer.ID()) { + // Depending on the type of peer, we choose a semaphore to limit the gossiping peers. + var peerSemaphore *semaphore.Weighted + if peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers > 0 { + peerSemaphore = memR.activePersistentPeersSemaphore + } else if !peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers > 0 { + peerSemaphore = memR.activeNonPersistentPeersSemaphore + } + + if peerSemaphore != nil { + for peer.IsRunning() { + // Block on the semaphore until a slot is available to start gossiping with this peer. + // Do not block indefinitely, in case the peer is disconnected before gossiping starts. + ctxTimeout, cancel := context.WithTimeout(context.TODO(), 30*time.Second) + // Block sending transactions to peer until one of the connections become + // available in the semaphore. + err := peerSemaphore.Acquire(ctxTimeout, 1) + cancel() + + if err != nil { + continue + } + + // Release semaphore to allow other peer to start sending transactions. + defer peerSemaphore.Release(1) + break + } + } + } + + memR.mempool.metrics.ActiveOutboundConnections.Add(1) + defer memR.mempool.metrics.ActiveOutboundConnections.Add(-1) + memR.broadcastTxRoutine(peer) + }() + } +} + +// RemovePeer implements Reactor. +func (memR *Reactor) RemovePeer(peer p2p.Peer, _ interface{}) { + memR.ids.Reclaim(peer) + // broadcast routine checks if peer is gone and returns +} + +// Receive implements Reactor. +// It adds any received transactions to the mempool. +func (memR *Reactor) Receive(e p2p.Envelope) { + memR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID, "msg", e.Message) + switch msg := e.Message.(type) { + case *protomem.Txs: + protoTxs := msg.GetTxs() + if len(protoTxs) == 0 { + memR.Logger.Error("received empty txs from peer", "src", e.Src) + return + } + txInfo := TxInfo{SenderID: memR.ids.GetForPeer(e.Src)} + if e.Src != nil { + txInfo.SenderP2PID = e.Src.ID() + } + + var err error + for _, tx := range protoTxs { + ntx := types.Tx(tx) + err = memR.mempool.CheckTx(ntx, nil, txInfo) + if err != nil { + switch { + case errors.Is(err, ErrTxInCache): + memR.Logger.Debug("Tx already exists in cache", "tx", ntx.String()) + case errors.As(err, &ErrMempoolIsFull{}): + // using debug level to avoid flooding when traffic is high + memR.Logger.Debug(err.Error()) + default: + memR.Logger.Info("Could not check tx", "tx", ntx.String(), "err", err) + } + } + } + default: + memR.Logger.Error("unknown message type", "src", e.Src, "chId", e.ChannelID, "msg", e.Message) + memR.Switch.StopPeerForError(e.Src, fmt.Errorf("mempool cannot handle message of type: %T", e.Message)) + return + } + + // broadcasting happens from go routines per peer +} + +// PeerState describes the state of a peer. +type PeerState interface { + GetHeight() int64 +} + +// Send new mempool txs to peer. +func (memR *Reactor) broadcastTxRoutine(peer p2p.Peer) { + peerID := memR.ids.GetForPeer(peer) + var next *clist.CElement + + for { + // In case of both next.NextWaitChan() and peer.Quit() are variable at the same time + if !memR.IsRunning() || !peer.IsRunning() { + return + } + + // This happens because the CElement we were looking at got garbage + // collected (removed). That is, .NextWait() returned nil. Go ahead and + // start from the beginning. + if next == nil { + select { + case <-memR.mempool.TxsWaitChan(): // Wait until a tx is available + if next = memR.mempool.TxsFront(); next == nil { + continue + } + case <-peer.Quit(): + return + case <-memR.Quit(): + return + } + } + + // Make sure the peer is up to date. + peerState, ok := peer.Get(types.PeerStateKey).(PeerState) + if !ok { + // Peer does not have a state yet. We set it in the consensus reactor, but + // when we add peer in Switch, the order we call reactors#AddPeer is + // different every time due to us using a map. Sometimes other reactors + // will be initialized before the consensus reactor. We should wait a few + // milliseconds and retry. + time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond) + continue + } + + // Allow for a lag of 1 block. + memTx := next.Value.(*mempoolTx) + if peerState.GetHeight() < memTx.Height()-1 { + time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond) + continue + } + + // NOTE: Transaction batching was disabled due to + // https://github.com/tendermint/tendermint/issues/5796 + + if !memTx.isSender(peerID) { + success := peer.Send(p2p.Envelope{ + ChannelID: MempoolChannel, + Message: &protomem.Txs{Txs: [][]byte{memTx.tx}}, + }) + if !success { + time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond) + continue + } + } + + select { + case <-next.NextWaitChan(): + // see the start of the for loop for nil check + next = next.Next() + case <-peer.Quit(): + return + case <-memR.Quit(): + return + } + } +} + +// TxsMessage is a Message containing transactions. +type TxsMessage struct { + Txs []types.Tx +} + +// String returns a string representation of the TxsMessage. +func (m *TxsMessage) String() string { + return fmt.Sprintf("[TxsMessage %v]", m.Txs) +} diff --git a/mempool/reactor_test.go b/mempool/reactor_test.go new file mode 100644 index 0000000..90eda3c --- /dev/null +++ b/mempool/reactor_test.go @@ -0,0 +1,434 @@ +package mempool + +import ( + "encoding/hex" + "errors" + "sync" + "testing" + "time" + + "github.com/fortytw2/leaktest" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/mock" + memproto "github.com/cometbft/cometbft/proto/tendermint/mempool" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" +) + +const ( + numTxs = 1000 + timeout = 120 * time.Second // ridiculously high because CircleCI is slow +) + +type peerState struct { + height int64 +} + +func (ps peerState) GetHeight() int64 { + return ps.height +} + +// Send a bunch of txs to the first reactor's mempool and wait for them all to +// be received in the others. +func TestReactorBroadcastTxsMessage(t *testing.T) { + config := cfg.TestConfig() + // if there were more than two reactors, the order of transactions could not be + // asserted in waitForTxsOnReactors (due to transactions gossiping). If we + // replace Connect2Switches (full mesh) with a func, which connects first + // reactor to others and nothing else, this test should also pass with >2 reactors. + const N = 2 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + peer.Set(types.PeerStateKey, peerState{1}) + } + } + + txs := addRandomTxs(t, reactors[0].mempool, numTxs, UnknownPeerID) + waitForTxsOnReactors(t, txs, reactors) +} + +// regression test for https://github.com/cometbft/cometbft/issues/5408 +func TestReactorConcurrency(t *testing.T) { + config := cfg.TestConfig() + const N = 2 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + peer.Set(types.PeerStateKey, peerState{1}) + } + } + var wg sync.WaitGroup + + const numTxs = 5 + + for i := 0; i < 1000; i++ { + wg.Add(2) + + // 1. submit a bunch of txs + // 2. update the whole mempool + txs := addRandomTxs(t, reactors[0].mempool, numTxs, UnknownPeerID) + go func() { + defer wg.Done() + + reactors[0].mempool.Lock() + defer reactors[0].mempool.Unlock() + + txResponses := make([]*abci.ExecTxResult, len(txs)) + for i := range txs { + txResponses[i] = &abci.ExecTxResult{Code: 0} + } + err := reactors[0].mempool.Update(1, txs, txResponses, nil, nil) + assert.NoError(t, err) + }() + + // 1. submit a bunch of txs + // 2. update none + _ = addRandomTxs(t, reactors[1].mempool, numTxs, UnknownPeerID) + go func() { + defer wg.Done() + + reactors[1].mempool.Lock() + defer reactors[1].mempool.Unlock() + err := reactors[1].mempool.Update(1, []types.Tx{}, make([]*abci.ExecTxResult, 0), nil, nil) + assert.NoError(t, err) + }() + + // 1. flush the mempool + reactors[1].mempool.Flush() + } + + wg.Wait() +} + +// Send a bunch of txs to the first reactor's mempool, claiming it came from peer +// ensure peer gets no txs. +func TestReactorNoBroadcastToSender(t *testing.T) { + config := cfg.TestConfig() + const N = 2 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + peer.Set(types.PeerStateKey, peerState{1}) + } + } + + const peerID = 1 + addRandomTxs(t, reactors[0].mempool, numTxs, peerID) + ensureNoTxs(t, reactors[peerID], 100*time.Millisecond) +} + +func TestMempoolReactorMaxTxBytes(t *testing.T) { + config := cfg.TestConfig() + + const N = 2 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + peer.Set(types.PeerStateKey, peerState{1}) + } + } + + // Broadcast a tx, which has the max size + // => ensure it's received by the second reactor. + tx1 := kvstore.NewRandomTx(config.Mempool.MaxTxBytes) + err := reactors[0].mempool.CheckTx(tx1, func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + }, TxInfo{SenderID: UnknownPeerID}) + require.NoError(t, err) + waitForTxsOnReactors(t, []types.Tx{tx1}, reactors) + + reactors[0].mempool.Flush() + reactors[1].mempool.Flush() + + // Broadcast a tx, which is beyond the max size + // => ensure it's not sent + tx2 := kvstore.NewRandomTx(config.Mempool.MaxTxBytes + 1) + err = reactors[0].mempool.CheckTx(tx2, func(resp *abci.ResponseCheckTx) { + require.False(t, resp.IsErr()) + }, TxInfo{SenderID: UnknownPeerID}) + require.Error(t, err) +} + +func TestBroadcastTxForPeerStopsWhenPeerStops(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + + config := cfg.TestConfig() + const N = 2 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + + // stop peer + sw := reactors[1].Switch + sw.StopPeerForError(sw.Peers().List()[0], errors.New("some reason")) + + // check that we are not leaking any go-routines + // i.e. broadcastTxRoutine finishes when peer is stopped + leaktest.CheckTimeout(t, 10*time.Second)() +} + +func TestBroadcastTxForPeerStopsWhenReactorStops(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + + config := cfg.TestConfig() + const N = 2 + _, switches := makeAndConnectReactors(config, N) + + // stop reactors + for _, s := range switches { + assert.NoError(t, s.Stop()) + } + + // check that we are not leaking any go-routines + // i.e. broadcastTxRoutine finishes when reactor is stopped + leaktest.CheckTimeout(t, 10*time.Second)() +} + +// TODO: This test tests that we don't panic and are able to generate new +// PeerIDs for each peer we add. It seems as though we should be able to test +// this in a much more direct way. +// https://github.com/cometbft/cometbft/issues/9639 +func TestDontExhaustMaxActiveIDs(t *testing.T) { + config := cfg.TestConfig() + const N = 1 + reactors, _ := makeAndConnectReactors(config, N) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + reactor := reactors[0] + + for i := 0; i < MaxActiveIDs+1; i++ { + peer := mock.NewPeer(nil) + reactor.Receive(p2p.Envelope{ + ChannelID: MempoolChannel, + Src: peer, + Message: &memproto.Message{}, // This uses the wrong message type on purpose to stop the peer as in an error state in the reactor. + }, + ) + reactor.AddPeer(peer) + } +} + +// Test the experimental feature that limits the number of outgoing connections for gossiping +// transactions (only non-persistent peers). +// Note: in this test we know which gossip connections are active or not because of how the p2p +// functions are currently implemented, which affects the order in which peers are added to the +// mempool reactor. +func TestMempoolReactorMaxActiveOutboundConnections(t *testing.T) { + config := cfg.TestConfig() + config.Mempool.ExperimentalMaxGossipConnectionsToNonPersistentPeers = 1 + reactors, _ := makeAndConnectReactors(config, 4) + defer func() { + for _, r := range reactors { + if err := r.Stop(); err != nil { + assert.NoError(t, err) + } + } + }() + for _, r := range reactors { + for _, peer := range r.Switch.Peers().List() { + peer.Set(types.PeerStateKey, peerState{1}) + } + } + + // Add a bunch transactions to the first reactor. + txs := newUniqueTxs(100) + callCheckTx(t, reactors[0].mempool, txs, UnknownPeerID) + + // Wait for all txs to be in the mempool of the second reactor; the other reactors should not + // receive any tx. (The second reactor only sends transactions to the first reactor.) + checkTxsInMempool(t, txs, reactors[1], 0) + for _, r := range reactors[2:] { + require.Zero(t, r.mempool.Size()) + } + + // Disconnect the second reactor from the first reactor. + firstPeer := reactors[0].Switch.Peers().List()[0] + reactors[0].Switch.StopPeerGracefully(firstPeer) + + // Now the third reactor should start receiving transactions from the first reactor; the fourth + // reactor's mempool should still be empty. + checkTxsInMempool(t, txs, reactors[2], 0) + for _, r := range reactors[3:] { + require.Zero(t, r.mempool.Size()) + } +} + +// mempoolLogger is a TestingLogger which uses a different +// color for each validator ("validator" key must exist). +func mempoolLogger() log.Logger { + return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor { + for i := 0; i < len(keyvals)-1; i += 2 { + if keyvals[i] == "validator" { + return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))} + } + } + return term.FgBgColor{} + }) +} + +// connect N mempool reactors through N switches +func makeAndConnectReactors(config *cfg.Config, n int) ([]*Reactor, []*p2p.Switch) { + reactors := make([]*Reactor, n) + logger := mempoolLogger() + for i := 0; i < n; i++ { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + mempool, cleanup := newMempoolWithApp(cc) + defer cleanup() + + reactors[i] = NewReactor(config.Mempool, mempool) // so we dont start the consensus states + reactors[i].SetLogger(logger.With("validator", i)) + } + + switches := p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch { + s.AddReactor("MEMPOOL", reactors[i]) + return s + + }, p2p.Connect2Switches) + return reactors, switches +} + +func newUniqueTxs(n int) types.Txs { + txs := make(types.Txs, n) + for i := 0; i < n; i++ { + txs[i] = kvstore.NewTxFromID(i) + } + return txs +} + +func waitForTxsOnReactors(t *testing.T, txs types.Txs, reactors []*Reactor) { + // wait for the txs in all mempools + wg := new(sync.WaitGroup) + for i, reactor := range reactors { + wg.Add(1) + go func(r *Reactor, reactorIndex int) { + defer wg.Done() + checkTxsInOrder(t, txs, r, reactorIndex) + }(reactor, i) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + timer := time.After(timeout) + select { + case <-timer: + t.Fatal("Timed out waiting for txs") + case <-done: + } +} + +// Wait until the mempool has a certain number of transactions. +func waitForNumTxsInMempool(numTxs int, mempool Mempool) { + for mempool.Size() < numTxs { + time.Sleep(time.Millisecond * 100) + } +} + +// Wait until all txs are in the mempool and check that the number of txs in the +// mempool is as expected. +func checkTxsInMempool(t *testing.T, txs types.Txs, reactor *Reactor, _ int) { + waitForNumTxsInMempool(len(txs), reactor.mempool) + + reapedTxs := reactor.mempool.ReapMaxTxs(len(txs)) + require.Equal(t, len(txs), len(reapedTxs)) + require.Equal(t, len(txs), reactor.mempool.Size()) +} + +// Wait until all txs are in the mempool and check that they are in the same +// order as given. +func checkTxsInOrder(t *testing.T, txs types.Txs, reactor *Reactor, reactorIndex int) { + waitForNumTxsInMempool(len(txs), reactor.mempool) + + // Check that all transactions in the mempool are in the same order as txs. + reapedTxs := reactor.mempool.ReapMaxTxs(len(txs)) + for i, tx := range txs { + assert.Equalf(t, tx, reapedTxs[i], + "txs at index %d on reactor %d don't match: %v vs %v", i, reactorIndex, tx, reapedTxs[i]) + } +} + +// ensure no txs on reactor after some timeout +func ensureNoTxs(t *testing.T, reactor *Reactor, timeout time.Duration) { + time.Sleep(timeout) // wait for the txs in all mempools + assert.Zero(t, reactor.mempool.Size()) +} + +func TestMempoolVectors(t *testing.T) { + testCases := []struct { + testName string + tx []byte + expBytes string + }{ + {"tx 1", []byte{123}, "0a030a017b"}, + {"tx 2", []byte("proto encoding in mempool"), "0a1b0a1970726f746f20656e636f64696e6720696e206d656d706f6f6c"}, + } + + for _, tc := range testCases { + tc := tc + + msg := memproto.Message{ + Sum: &memproto.Message_Txs{ + Txs: &memproto.Txs{Txs: [][]byte{tc.tx}}, + }, + } + bz, err := msg.Marshal() + require.NoError(t, err, tc.testName) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + } +} diff --git a/mempool/tx.go b/mempool/tx.go new file mode 100644 index 0000000..f232be8 --- /dev/null +++ b/mempool/tx.go @@ -0,0 +1,17 @@ +package mempool + +import ( + "github.com/cometbft/cometbft/p2p" +) + +// TxInfo are parameters that get passed when attempting to add a tx to the +// mempool. +type TxInfo struct { + // SenderID is the internal peer ID used in the mempool to identify the + // sender, storing two bytes with each transaction instead of 20 bytes for + // the types.NodeID. + SenderID uint16 + + // SenderP2PID is the actual p2p.ID of the sender, used e.g. for logging. + SenderP2PID p2p.ID +} diff --git a/networks/local/Makefile b/networks/local/Makefile new file mode 100644 index 0000000..bb17b0c --- /dev/null +++ b/networks/local/Makefile @@ -0,0 +1,7 @@ +# Makefile for the "localnode" docker image. + +all: + docker buildx build --platform linux/amd64 --tag cometbft/localnode localnode + +.PHONY: all + diff --git a/networks/local/README.md b/networks/local/README.md new file mode 100644 index 0000000..8c7f6d2 --- /dev/null +++ b/networks/local/README.md @@ -0,0 +1,3 @@ +# Local Cluster with Docker Compose + +See the [docs](https://docs.cometbft.com/v0.38.x/networks/docker-compose.html). diff --git a/networks/local/localnode/Dockerfile b/networks/local/localnode/Dockerfile new file mode 100644 index 0000000..2ea29b7 --- /dev/null +++ b/networks/local/localnode/Dockerfile @@ -0,0 +1,15 @@ +FROM alpine:3.19 + +RUN apk update && \ + apk upgrade && \ + apk --no-cache add curl jq file + +VOLUME /cometbft +WORKDIR /cometbft +EXPOSE 26656 26657 +ENTRYPOINT ["/usr/bin/wrapper.sh"] +CMD ["node", "--proxy_app", "kvstore"] +STOPSIGNAL SIGTERM + +COPY wrapper.sh /usr/bin/wrapper.sh +COPY config-template.toml /etc/cometbft/config-template.toml diff --git a/networks/local/localnode/config-template.toml b/networks/local/localnode/config-template.toml new file mode 100644 index 0000000..669e5fd --- /dev/null +++ b/networks/local/localnode/config-template.toml @@ -0,0 +1,2 @@ +[rpc] +laddr = "tcp://0.0.0.0:26657" diff --git a/networks/local/localnode/wrapper.sh b/networks/local/localnode/wrapper.sh new file mode 100755 index 0000000..c3ad1d5 --- /dev/null +++ b/networks/local/localnode/wrapper.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env sh + +## +## Input parameters +## +BINARY=/cometbft/${BINARY:-cometbft} +ID=${ID:-0} +LOG=${LOG:-cometbft.log} + +## +## Assert linux binary +## +if ! [ -f "${BINARY}" ]; then + echo "The binary $(basename "${BINARY}") cannot be found. Please add the binary to the shared folder. Please use the BINARY environment variable if the name of the binary is not 'cometbft' E.g.: -e BINARY=my_test_binary" + + exit 1 +fi +BINARY_CHECK="$(file "$BINARY" | grep 'ELF 64-bit LSB executable, x86-64')" +if [ -z "${BINARY_CHECK}" ]; then + echo "Binary needs to be OS linux, ARCH amd64 (build with 'make build-linux')" + exit 1 +fi + +## +## Run binary with all parameters +## +export CMTHOME="/cometbft/node${ID}" + +if [ -d "`dirname ${CMTHOME}/${LOG}`" ]; then + "$BINARY" "$@" | tee "${CMTHOME}/${LOG}" +else + "$BINARY" "$@" +fi + +chmod 777 -R /cometbft + diff --git a/node/doc.go b/node/doc.go new file mode 100644 index 0000000..35653d4 --- /dev/null +++ b/node/doc.go @@ -0,0 +1,39 @@ +/* +Package node is the main entry point, where the Node struct, which +represents a full node, is defined. + +Adding new p2p.Reactor(s) + +To add a new p2p.Reactor, use the CustomReactors option: + + node, err := NewNode( + config, + privVal, + nodeKey, + clientCreator, + genesisDocProvider, + dbProvider, + metricsProvider, + logger, + CustomReactors(map[string]p2p.Reactor{"CUSTOM": customReactor}), + ) + +Replacing existing p2p.Reactor(s) + +To replace the built-in p2p.Reactor, use the CustomReactors option: + + node, err := NewNode( + config, + privVal, + nodeKey, + clientCreator, + genesisDocProvider, + dbProvider, + metricsProvider, + logger, + CustomReactors(map[string]p2p.Reactor{"BLOCKSYNC": customBlocksyncReactor}), + ) + +The list of existing reactors can be found in CustomReactors documentation. +*/ +package node diff --git a/node/node.go b/node/node.go new file mode 100644 index 0000000..8f498e4 --- /dev/null +++ b/node/node.go @@ -0,0 +1,977 @@ +package node + +import ( + "bytes" + "context" + "fmt" + "net" + "net/http" + "os" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" + + bc "github.com/cometbft/cometbft/blocksync" + cfg "github.com/cometbft/cometbft/config" + cs "github.com/cometbft/cometbft/consensus" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/light" + + "github.com/cometbft/cometbft/libs/log" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/service" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/pex" + "github.com/cometbft/cometbft/proxy" + rpccore "github.com/cometbft/cometbft/rpc/core" + grpccore "github.com/cometbft/cometbft/rpc/grpc" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/state/txindex/null" + "github.com/cometbft/cometbft/statesync" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" + + _ "net/http/pprof" //nolint: gosec +) + +// Node is the highest level interface to a full CometBFT node. +// It includes all configuration information and running services. +type Node struct { + service.BaseService + + // config + config *cfg.Config + genesisDoc *types.GenesisDoc // initial validator set + privValidator types.PrivValidator // local node's validator key + + // network + transport *p2p.MultiplexTransport + sw *p2p.Switch // p2p connections + addrBook pex.AddrBook // known peers + nodeInfo p2p.NodeInfo + nodeKey *p2p.NodeKey // our node privkey + isListening bool + + // services + eventBus *types.EventBus // pub/sub for services + stateStore sm.Store + blockStore *store.BlockStore // store the blockchain to disk + bcReactor p2p.Reactor // for block-syncing + mempoolReactor p2p.Reactor // for gossipping transactions + mempool mempl.Mempool + stateSync bool // whether the node should state sync on startup + stateSyncReactor *statesync.Reactor // for hosting and restoring state sync snapshots + stateSyncProvider statesync.StateProvider // provides state data for bootstrapping a node + stateSyncGenesis sm.State // provides the genesis state for state sync + consensusState *cs.State // latest consensus state + consensusReactor *cs.Reactor // for participating in the consensus + pexReactor *pex.Reactor // for exchanging peer addresses + evidencePool *evidence.Pool // tracking evidence + proxyApp proxy.AppConns // connection to the application + rpcListeners []net.Listener // rpc servers + txIndexer txindex.TxIndexer + blockIndexer indexer.BlockIndexer + indexerService *txindex.IndexerService + prometheusSrv *http.Server + pprofSrv *http.Server +} + +// Option sets a parameter for the node. +type Option func(*Node) + +// CustomReactors allows you to add custom reactors (name -> p2p.Reactor) to +// the node's Switch. +// +// WARNING: using any name from the below list of the existing reactors will +// result in replacing it with the custom one. +// +// - MEMPOOL +// - BLOCKSYNC +// - CONSENSUS +// - EVIDENCE +// - PEX +// - STATESYNC +func CustomReactors(reactors map[string]p2p.Reactor) Option { + return func(n *Node) { + for name, reactor := range reactors { + if existingReactor := n.sw.Reactor(name); existingReactor != nil { + n.sw.Logger.Info("Replacing existing reactor with a custom one", + "name", name, "existing", existingReactor, "custom", reactor) + n.sw.RemoveReactor(name, existingReactor) + } + n.sw.AddReactor(name, reactor) + // register the new channels to the nodeInfo + // NOTE: This is a bit messy now with the type casting but is + // cleaned up in the following version when NodeInfo is changed from + // and interface to a concrete type + if ni, ok := n.nodeInfo.(p2p.DefaultNodeInfo); ok { + for _, chDesc := range reactor.GetChannels() { + if !ni.HasChannel(chDesc.ID) { + ni.Channels = append(ni.Channels, chDesc.ID) + n.transport.AddChannel(chDesc.ID) + } + } + n.nodeInfo = ni + } else { + n.Logger.Error("Node info is not of type DefaultNodeInfo. Custom reactor channels can not be added.") + } + } + } +} + +// StateProvider overrides the state provider used by state sync to retrieve trusted app hashes and +// build a State object for bootstrapping the node. +// WARNING: this interface is considered unstable and subject to change. +func StateProvider(stateProvider statesync.StateProvider) Option { + return func(n *Node) { + n.stateSyncProvider = stateProvider + } +} + +// BootstrapState synchronizes the stores with the application after state sync +// has been performed offline. It is expected that the block store and state +// store are empty at the time the function is called. +// +// If the block store is not empty, the function returns an error. +func BootstrapState(ctx context.Context, config *cfg.Config, dbProvider cfg.DBProvider, height uint64, appHash []byte) error { + return BootstrapStateWithGenProvider(ctx, config, dbProvider, DefaultGenesisDocProviderFunc(config), height, appHash) +} + +// BootstrapStateWithGenProvider synchronizes the stores with the application after state sync +// has been performed offline. It is expected that the block store and state +// store are empty at the time the function is called. +// +// If the block store is not empty, the function returns an error. +func BootstrapStateWithGenProvider(ctx context.Context, config *cfg.Config, dbProvider cfg.DBProvider, genProvider GenesisDocProvider, height uint64, appHash []byte) (err error) { + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + if ctx == nil { + ctx = context.Background() + } + + if config == nil { + logger.Info("no config provided, using default configuration") + config = cfg.DefaultConfig() + } + + if dbProvider == nil { + dbProvider = cfg.DefaultDBProvider + } + blockStore, stateDB, err := initDBs(config, dbProvider) + + defer func() { + if derr := blockStore.Close(); derr != nil { + logger.Error("Failed to close blockstore", "err", derr) + // Set the return value + err = derr + } + }() + + if err != nil { + return err + } + + if !blockStore.IsEmpty() { + return fmt.Errorf("blockstore not empty, trying to initialize non empty state") + } + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: config.Storage.DiscardABCIResponses, + }) + + defer func() { + if derr := stateStore.Close(); derr != nil { + logger.Error("Failed to close statestore", "err", derr) + // Set the return value + err = derr + } + }() + state, err := stateStore.Load() + if err != nil { + return err + } + + if !state.IsEmpty() { + return fmt.Errorf("state not empty, trying to initialize non empty state") + } + + genState, _, err := LoadStateFromDBOrGenesisDocProvider(stateDB, genProvider) + if err != nil { + return err + } + + stateProvider, err := statesync.NewLightClientStateProvider( + ctx, + genState.ChainID, genState.Version, genState.InitialHeight, + config.StateSync.RPCServers, light.TrustOptions{ + Period: config.StateSync.TrustPeriod, + Height: config.StateSync.TrustHeight, + Hash: config.StateSync.TrustHashBytes(), + }, logger.With("module", "light")) + if err != nil { + return fmt.Errorf("failed to set up light client state provider: %w", err) + } + + state, err = stateProvider.State(ctx, height) + if err != nil { + return err + } + if appHash == nil { + logger.Info("warning: cannot verify appHash. Verification will happen when node boots up!") + } else { + if !bytes.Equal(appHash, state.AppHash) { + if err := blockStore.Close(); err != nil { + logger.Error("failed to close blockstore: %w", err) + } + if err := stateStore.Close(); err != nil { + logger.Error("failed to close statestore: %w", err) + } + return fmt.Errorf("the app hash returned by the light client does not match the provided appHash, expected %X, got %X", state.AppHash, appHash) + } + } + + commit, err := stateProvider.Commit(ctx, height) + if err != nil { + return err + } + + if err = stateStore.Bootstrap(state); err != nil { + return err + } + + err = blockStore.SaveSeenCommit(state.LastBlockHeight, commit) + if err != nil { + return err + } + + // Once the stores are bootstrapped, we need to set the height at which the node has finished + // statesyncing. This will allow the blocksync reactor to fetch blocks at a proper height. + // In case this operation fails, it is equivalent to a failure in online state sync where the operator + // needs to manually delete the state and blockstores and rerun the bootstrapping process. + err = stateStore.SetOfflineStateSyncHeight(state.LastBlockHeight) + if err != nil { + return fmt.Errorf("failed to set synced height: %w", err) + } + + return err +} + +//------------------------------------------------------------------------------ + +// NewNode returns a new, ready to go, CometBFT Node. +func NewNode(config *cfg.Config, + privValidator types.PrivValidator, + nodeKey *p2p.NodeKey, + clientCreator proxy.ClientCreator, + genesisDocProvider GenesisDocProvider, + dbProvider cfg.DBProvider, + metricsProvider MetricsProvider, + logger log.Logger, + options ...Option, +) (*Node, error) { + return NewNodeWithContext(context.TODO(), config, privValidator, + nodeKey, clientCreator, genesisDocProvider, dbProvider, + metricsProvider, logger, options...) +} + +// NewNodeWithContext is cancellable version of NewNode. +func NewNodeWithContext(ctx context.Context, + config *cfg.Config, + privValidator types.PrivValidator, + nodeKey *p2p.NodeKey, + clientCreator proxy.ClientCreator, + genesisDocProvider GenesisDocProvider, + dbProvider cfg.DBProvider, + metricsProvider MetricsProvider, + logger log.Logger, + options ...Option, +) (*Node, error) { + blockStore, stateDB, err := initDBs(config, dbProvider) + if err != nil { + return nil, err + } + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: config.Storage.DiscardABCIResponses, + }) + + state, genDoc, err := LoadStateFromDBOrGenesisDocProvider(stateDB, genesisDocProvider) + if err != nil { + return nil, err + } + + csMetrics, p2pMetrics, memplMetrics, smMetrics, abciMetrics, bsMetrics, ssMetrics := metricsProvider(genDoc.ChainID) + + // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query). + proxyApp, err := createAndStartProxyAppConns(clientCreator, logger, abciMetrics) + if err != nil { + return nil, err + } + + // EventBus and IndexerService must be started before the handshake because + // we might need to index the txs of the replayed block as this might not have happened + // when the node stopped last time (i.e. the node stopped after it saved the block + // but before it indexed the txs) + eventBus, err := createAndStartEventBus(logger) + if err != nil { + return nil, err + } + + indexerService, txIndexer, blockIndexer, err := createAndStartIndexerService(config, + genDoc.ChainID, dbProvider, eventBus, logger) + if err != nil { + return nil, err + } + + // If an address is provided, listen on the socket for a connection from an + // external signing process. + if config.PrivValidatorListenAddr != "" { + // FIXME: we should start services inside OnStart + privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, genDoc.ChainID, logger) + if err != nil { + return nil, fmt.Errorf("error with private validator socket client: %w", err) + } + } + + pubKey, err := privValidator.GetPubKey() + if err != nil { + return nil, fmt.Errorf("can't get pubkey: %w", err) + } + localAddr := pubKey.Address() + + // Determine whether we should attempt state sync. + stateSync := config.StateSync.Enable && !onlyValidatorIsUs(state, localAddr) + if stateSync && state.LastBlockHeight > 0 { + logger.Info("Found local state with non-zero height, skipping state sync") + stateSync = false + } + + // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state, + // and replays any blocks as necessary to sync CometBFT with the app. + consensusLogger := logger.With("module", "consensus") + if !stateSync { + if err := doHandshake(ctx, stateStore, state, blockStore, genDoc, eventBus, proxyApp, consensusLogger); err != nil { + return nil, err + } + + // Reload the state. It will have the Version.Consensus.App set by the + // Handshake, and may have other modifications as well (ie. depending on + // what happened during block replay). + state, err = stateStore.Load() + if err != nil { + return nil, fmt.Errorf("cannot load state: %w", err) + } + } + + // Determine whether we should do block sync. This must happen after the handshake, since the + // app may modify the validator set, specifying ourself as the only validator. + blockSync := !onlyValidatorIsUs(state, localAddr) + + logNodeStartupInfo(state, pubKey, logger, consensusLogger) + + mempool, mempoolReactor := createMempoolAndMempoolReactor(config, proxyApp, state, memplMetrics, logger) + + evidenceReactor, evidencePool, err := createEvidenceReactor(config, dbProvider, stateStore, blockStore, logger) + if err != nil { + return nil, err + } + + // make block executor for consensus and blocksync reactors to execute blocks + blockExec := sm.NewBlockExecutor( + stateStore, + logger.With("module", "state"), + proxyApp.Consensus(), + mempool, + evidencePool, + blockStore, + sm.BlockExecutorWithMetrics(smMetrics), + ) + + offlineStateSyncHeight := int64(0) + if blockStore.Height() == 0 { + offlineStateSyncHeight, err = blockExec.Store().GetOfflineStateSyncHeight() + if err != nil && err.Error() != "value empty" { + panic(fmt.Sprintf("failed to retrieve statesynced height from store %s; expected state store height to be %v", err, state.LastBlockHeight)) + } + } + // Don't start block sync if we're doing a state sync first. + bcReactor, err := createBlocksyncReactor(config, state, blockExec, blockStore, blockSync && !stateSync, localAddr, logger, bsMetrics, offlineStateSyncHeight) + if err != nil { + return nil, fmt.Errorf("could not create blocksync reactor: %w", err) + } + + consensusReactor, consensusState := createConsensusReactor( + config, state, blockExec, blockStore, mempool, evidencePool, + privValidator, csMetrics, stateSync || blockSync, eventBus, consensusLogger, offlineStateSyncHeight, + ) + + err = stateStore.SetOfflineStateSyncHeight(0) + if err != nil { + panic(fmt.Sprintf("failed to reset the offline state sync height %s", err)) + } + // Set up state sync reactor, and schedule a sync if requested. + // FIXME The way we do phased startups (e.g. replay -> block sync -> consensus) is very messy, + // we should clean this whole thing up. See: + // https://github.com/tendermint/tendermint/issues/4644 + stateSyncReactor := statesync.NewReactor( + *config.StateSync, + proxyApp.Snapshot(), + proxyApp.Query(), + ssMetrics, + ) + stateSyncReactor.SetLogger(logger.With("module", "statesync")) + + nodeInfo, err := makeNodeInfo(config, nodeKey, txIndexer, genDoc, state) + if err != nil { + return nil, err + } + + transport, peerFilters := createTransport(config, nodeInfo, nodeKey, proxyApp) + + p2pLogger := logger.With("module", "p2p") + sw := createSwitch( + config, transport, p2pMetrics, peerFilters, mempoolReactor, bcReactor, + stateSyncReactor, consensusReactor, evidenceReactor, nodeInfo, nodeKey, p2pLogger, + ) + + err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " ")) + if err != nil { + return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err) + } + + err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " ")) + if err != nil { + return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err) + } + + addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey) + if err != nil { + return nil, fmt.Errorf("could not create addrbook: %w", err) + } + + // Optionally, start the pex reactor + // + // TODO: + // + // We need to set Seeds and PersistentPeers on the switch, + // since it needs to be able to use these (and their DNS names) + // even if the PEX is off. We can include the DNS name in the NetAddress, + // but it would still be nice to have a clear list of the current "PersistentPeers" + // somewhere that we can return with net_info. + // + // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it. + // Note we currently use the addrBook regardless at least for AddOurAddress + var pexReactor *pex.Reactor + if config.P2P.PexReactor { + pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger) + } + + // Add private IDs to addrbook to block those peers being added + addrBook.AddPrivateIDs(splitAndTrimEmpty(config.P2P.PrivatePeerIDs, ",", " ")) + + node := &Node{ + config: config, + genesisDoc: genDoc, + privValidator: privValidator, + + transport: transport, + sw: sw, + addrBook: addrBook, + nodeInfo: nodeInfo, + nodeKey: nodeKey, + + stateStore: stateStore, + blockStore: blockStore, + bcReactor: bcReactor, + mempoolReactor: mempoolReactor, + mempool: mempool, + consensusState: consensusState, + consensusReactor: consensusReactor, + stateSyncReactor: stateSyncReactor, + stateSync: stateSync, + stateSyncGenesis: state, // Shouldn't be necessary, but need a way to pass the genesis state + pexReactor: pexReactor, + evidencePool: evidencePool, + proxyApp: proxyApp, + txIndexer: txIndexer, + indexerService: indexerService, + blockIndexer: blockIndexer, + eventBus: eventBus, + } + node.BaseService = *service.NewBaseService(logger, "Node", node) + + for _, option := range options { + option(node) + } + + return node, nil +} + +// OnStart starts the Node. It implements service.Service. +func (n *Node) OnStart() error { + now := cmttime.Now() + genTime := n.genesisDoc.GenesisTime + if genTime.After(now) { + n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime) + time.Sleep(genTime.Sub(now)) + } + + // run pprof server if it is enabled + if n.config.RPC.IsPprofEnabled() { + n.pprofSrv = n.startPprofServer() + } + + // begin prometheus metrics gathering if it is enabled + if n.config.Instrumentation.IsPrometheusEnabled() { + n.prometheusSrv = n.startPrometheusServer() + } + + // Start the RPC server before the P2P server + // so we can eg. receive txs for the first block + if n.config.RPC.ListenAddress != "" { + listeners, err := n.startRPC() + if err != nil { + return err + } + n.rpcListeners = listeners + } + + // Start the transport. + addr, err := p2p.NewNetAddressString(p2p.IDAddressString(n.nodeKey.ID(), n.config.P2P.ListenAddress)) + if err != nil { + return err + } + if err := n.transport.Listen(*addr); err != nil { + return err + } + + n.isListening = true + + // Start the switch (the P2P server). + err = n.sw.Start() + if err != nil { + return err + } + + // Always connect to persistent peers + err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " ")) + if err != nil { + return fmt.Errorf("could not dial peers from persistent_peers field: %w", err) + } + + // Run state sync + if n.stateSync { + bcR, ok := n.bcReactor.(blockSyncReactor) + if !ok { + return fmt.Errorf("this blocksync reactor does not support switching from state sync") + } + err := startStateSync(n.stateSyncReactor, bcR, n.stateSyncProvider, + n.config.StateSync, n.stateStore, n.blockStore, n.stateSyncGenesis) + if err != nil { + return fmt.Errorf("failed to start state sync: %w", err) + } + } + + return nil +} + +// OnStop stops the Node. It implements service.Service. +func (n *Node) OnStop() { + n.BaseService.OnStop() + + n.Logger.Info("Stopping Node") + + // first stop the non-reactor services + if err := n.eventBus.Stop(); err != nil { + n.Logger.Error("Error closing eventBus", "err", err) + } + if n.indexerService != nil { + if err := n.indexerService.Stop(); err != nil { + n.Logger.Error("Error closing indexerService", "err", err) + } + } + // now stop the reactors + if err := n.sw.Stop(); err != nil { + n.Logger.Error("Error closing switch", "err", err) + } + + if err := n.transport.Close(); err != nil { + n.Logger.Error("Error closing transport", "err", err) + } + + n.isListening = false + + // finally stop the listeners / external services + for _, l := range n.rpcListeners { + n.Logger.Info("Closing rpc listener", "listener", l) + if err := l.Close(); err != nil { + n.Logger.Error("Error closing listener", "listener", l, "err", err) + } + } + + if pvsc, ok := n.privValidator.(service.Service); ok { + if err := pvsc.Stop(); err != nil { + n.Logger.Error("Error closing private validator", "err", err) + } + } + + if n.prometheusSrv != nil { + if err := n.prometheusSrv.Shutdown(context.Background()); err != nil { + // Error from closing listeners, or context timeout: + n.Logger.Error("Prometheus HTTP server Shutdown", "err", err) + } + } + if n.pprofSrv != nil { + if err := n.pprofSrv.Shutdown(context.Background()); err != nil { + n.Logger.Error("Pprof HTTP server Shutdown", "err", err) + } + } + if n.blockStore != nil { + n.Logger.Info("Closing blockstore") + if err := n.blockStore.Close(); err != nil { + n.Logger.Error("problem closing blockstore", "err", err) + } + } + if n.stateStore != nil { + n.Logger.Info("Closing statestore") + if err := n.stateStore.Close(); err != nil { + n.Logger.Error("problem closing statestore", "err", err) + } + } + if n.evidencePool != nil { + n.Logger.Info("Closing evidencestore") + if err := n.EvidencePool().Close(); err != nil { + n.Logger.Error("problem closing evidencestore", "err", err) + } + } +} + +// ConfigureRPC makes sure RPC has all the objects it needs to operate. +func (n *Node) ConfigureRPC() (*rpccore.Environment, error) { + pubKey, err := n.privValidator.GetPubKey() + if pubKey == nil || err != nil { + return nil, fmt.Errorf("can't get pubkey: %w", err) + } + rpcCoreEnv := rpccore.Environment{ + ProxyAppQuery: n.proxyApp.Query(), + ProxyAppMempool: n.proxyApp.Mempool(), + + StateStore: n.stateStore, + BlockStore: n.blockStore, + EvidencePool: n.evidencePool, + ConsensusState: n.consensusState, + P2PPeers: n.sw, + P2PTransport: n, + PubKey: pubKey, + + GenDoc: n.genesisDoc, + TxIndexer: n.txIndexer, + BlockIndexer: n.blockIndexer, + ConsensusReactor: n.consensusReactor, + EventBus: n.eventBus, + Mempool: n.mempool, + + Logger: n.Logger.With("module", "rpc"), + + Config: *n.config.RPC, + } + if err := rpcCoreEnv.InitGenesisChunks(); err != nil { + return nil, err + } + return &rpcCoreEnv, nil +} + +func (n *Node) startRPC() ([]net.Listener, error) { + env, err := n.ConfigureRPC() + if err != nil { + return nil, err + } + + listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ") + routes := env.GetRoutes() + + if n.config.RPC.Unsafe { + env.AddUnsafeRoutes(routes) + } + + config := rpcserver.DefaultConfig() + config.MaxRequestBatchSize = n.config.RPC.MaxRequestBatchSize + config.MaxBodyBytes = n.config.RPC.MaxBodyBytes + config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes + config.MaxOpenConnections = n.config.RPC.MaxOpenConnections + // If necessary adjust global WriteTimeout to ensure it's greater than + // TimeoutBroadcastTxCommit. + // See https://github.com/tendermint/tendermint/issues/3435 + if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit { + config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second + } + + // we may expose the rpc over both a unix and tcp socket + listeners := make([]net.Listener, len(listenAddrs)) + for i, listenAddr := range listenAddrs { + mux := http.NewServeMux() + rpcLogger := n.Logger.With("module", "rpc-server") + wmLogger := rpcLogger.With("protocol", "websocket") + wm := rpcserver.NewWebsocketManager(routes, + rpcserver.OnDisconnect(func(remoteAddr string) { + err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr) + if err != nil && err != cmtpubsub.ErrSubscriptionNotFound { + wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err) + } + }), + rpcserver.ReadLimit(config.MaxBodyBytes), + rpcserver.WriteChanCapacity(n.config.RPC.WebSocketWriteBufferSize), + ) + wm.SetLogger(wmLogger) + mux.HandleFunc("/websocket", wm.WebsocketHandler) + rpcserver.RegisterRPCFuncs(mux, routes, rpcLogger) + listener, err := rpcserver.Listen( + listenAddr, + config.MaxOpenConnections, + ) + if err != nil { + return nil, err + } + + var rootHandler http.Handler = mux + if n.config.RPC.IsCorsEnabled() { + corsMiddleware := cors.New(cors.Options{ + AllowedOrigins: n.config.RPC.CORSAllowedOrigins, + AllowedMethods: n.config.RPC.CORSAllowedMethods, + AllowedHeaders: n.config.RPC.CORSAllowedHeaders, + }) + rootHandler = corsMiddleware.Handler(mux) + } + if n.config.RPC.IsTLSEnabled() { + go func() { + if err := rpcserver.ServeTLS( + listener, + rootHandler, + n.config.RPC.CertFile(), + n.config.RPC.KeyFile(), + rpcLogger, + config, + ); err != nil { + n.Logger.Error("Error serving server with TLS", "err", err) + } + }() + } else { + go func() { + if err := rpcserver.Serve( + listener, + rootHandler, + rpcLogger, + config, + ); err != nil { + n.Logger.Error("Error serving server", "err", err) + } + }() + } + + listeners[i] = listener + } + + // we expose a simplified api over grpc for convenience to app devs + grpcListenAddr := n.config.RPC.GRPCListenAddress + if grpcListenAddr != "" { + config := rpcserver.DefaultConfig() + config.MaxBodyBytes = n.config.RPC.MaxBodyBytes + config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes + // NOTE: GRPCMaxOpenConnections is used, not MaxOpenConnections + config.MaxOpenConnections = n.config.RPC.GRPCMaxOpenConnections + // If necessary adjust global WriteTimeout to ensure it's greater than + // TimeoutBroadcastTxCommit. + // See https://github.com/tendermint/tendermint/issues/3435 + if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit { + config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second + } + listener, err := rpcserver.Listen(grpcListenAddr, config.MaxOpenConnections) + if err != nil { + return nil, err + } + go func() { + //nolint:staticcheck // SA1019: core_grpc.StartGRPCClient is deprecated: A new gRPC API will be introduced after v0.38. + if err := grpccore.StartGRPCServer(env, listener); err != nil { + n.Logger.Error("Error starting gRPC server", "err", err) + } + }() + listeners = append(listeners, listener) + + } + + return listeners, nil +} + +// startPrometheusServer starts a Prometheus HTTP server, listening for metrics +// collectors on addr. +func (n *Node) startPrometheusServer() *http.Server { + srv := &http.Server{ + Addr: n.config.Instrumentation.PrometheusListenAddr, + Handler: promhttp.InstrumentMetricHandler( + prometheus.DefaultRegisterer, promhttp.HandlerFor( + prometheus.DefaultGatherer, + promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections}, + ), + ), + ReadHeaderTimeout: readHeaderTimeout, + } + go func() { + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + // Error starting or closing listener: + n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err) + } + }() + return srv +} + +// starts a ppro +func (n *Node) startPprofServer() *http.Server { + srv := &http.Server{ + Addr: n.config.RPC.PprofListenAddress, + Handler: nil, + ReadHeaderTimeout: readHeaderTimeout, + } + go func() { + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + // Error starting or closing listener: + n.Logger.Error("pprof HTTP server ListenAndServe", "err", err) + } + }() + return srv +} + +// Switch returns the Node's Switch. +func (n *Node) Switch() *p2p.Switch { + return n.sw +} + +// BlockStore returns the Node's BlockStore. +func (n *Node) BlockStore() *store.BlockStore { + return n.blockStore +} + +// ConsensusReactor returns the Node's ConsensusReactor. +func (n *Node) ConsensusReactor() *cs.Reactor { + return n.consensusReactor +} + +// MempoolReactor returns the Node's mempool reactor. +func (n *Node) MempoolReactor() p2p.Reactor { + return n.mempoolReactor +} + +// Mempool returns the Node's mempool. +func (n *Node) Mempool() mempl.Mempool { + return n.mempool +} + +// PEXReactor returns the Node's PEXReactor. It returns nil if PEX is disabled. +func (n *Node) PEXReactor() *pex.Reactor { + return n.pexReactor +} + +// EvidencePool returns the Node's EvidencePool. +func (n *Node) EvidencePool() *evidence.Pool { + return n.evidencePool +} + +// EventBus returns the Node's EventBus. +func (n *Node) EventBus() *types.EventBus { + return n.eventBus +} + +// PrivValidator returns the Node's PrivValidator. +// XXX: for convenience only! +func (n *Node) PrivValidator() types.PrivValidator { + return n.privValidator +} + +// GenesisDoc returns the Node's GenesisDoc. +func (n *Node) GenesisDoc() *types.GenesisDoc { + return n.genesisDoc +} + +// ProxyApp returns the Node's AppConns, representing its connections to the ABCI application. +func (n *Node) ProxyApp() proxy.AppConns { + return n.proxyApp +} + +// Config returns the Node's config. +func (n *Node) Config() *cfg.Config { + return n.config +} + +//------------------------------------------------------------------------------ + +func (n *Node) Listeners() []string { + return []string{ + fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress), + } +} + +func (n *Node) IsListening() bool { + return n.isListening +} + +// NodeInfo returns the Node's Info from the Switch. +func (n *Node) NodeInfo() p2p.NodeInfo { + return n.nodeInfo +} + +func makeNodeInfo( + config *cfg.Config, + nodeKey *p2p.NodeKey, + txIndexer txindex.TxIndexer, + genDoc *types.GenesisDoc, + state sm.State, +) (p2p.DefaultNodeInfo, error) { + txIndexerStatus := "on" + if _, ok := txIndexer.(*null.TxIndex); ok { + txIndexerStatus = "off" + } + + nodeInfo := p2p.DefaultNodeInfo{ + ProtocolVersion: p2p.NewProtocolVersion( + version.P2PProtocol, // global + state.Version.Consensus.Block, + state.Version.Consensus.App, + ), + DefaultNodeID: nodeKey.ID(), + Network: genDoc.ChainID, + Version: version.TMCoreSemVer, + Channels: []byte{ + bc.BlocksyncChannel, + cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel, + mempl.MempoolChannel, + evidence.EvidenceChannel, + statesync.SnapshotChannel, statesync.ChunkChannel, + }, + Moniker: config.Moniker, + Other: p2p.DefaultNodeInfoOther{ + TxIndex: txIndexerStatus, + RPCAddress: config.RPC.ListenAddress, + }, + } + + if config.P2P.PexReactor { + nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel) + } + + lAddr := config.P2P.ExternalAddress + + if lAddr == "" { + lAddr = config.P2P.ListenAddress + } + + nodeInfo.ListenAddr = lAddr + + err := nodeInfo.Validate() + return nodeInfo, err +} diff --git a/node/node_test.go b/node/node_test.go new file mode 100644 index 0000000..4694b46 --- /dev/null +++ b/node/node_test.go @@ -0,0 +1,503 @@ +package node + +import ( + "context" + "fmt" + "net" + "net/http" + "os" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/abci/example/kvstore" + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/conn" + p2pmock "github.com/cometbft/cometbft/p2p/mock" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +func TestNodeStartStop(t *testing.T) { + config := test.ResetTestRoot("node_node_test") + defer os.RemoveAll(config.RootDir) + + // create & start node + n, err := DefaultNewNode(config, log.TestingLogger()) + require.NoError(t, err) + err = n.Start() + require.NoError(t, err) + + t.Logf("Started node %v", n.sw.NodeInfo()) + + // wait for the node to produce a block + blocksSub, err := n.EventBus().Subscribe(context.Background(), "node_test", types.EventQueryNewBlock) + require.NoError(t, err) + select { + case <-blocksSub.Out(): + case <-blocksSub.Canceled(): + t.Fatal("blocksSub was canceled") + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for the node to produce a block") + } + + // stop the node + go func() { + err = n.Stop() + require.NoError(t, err) + }() + + select { + case <-n.Quit(): + case <-time.After(5 * time.Second): + pid := os.Getpid() + p, err := os.FindProcess(pid) + if err != nil { + panic(err) + } + err = p.Signal(syscall.SIGABRT) + fmt.Println(err) + t.Fatal("timed out waiting for shutdown") + } +} + +func TestSplitAndTrimEmpty(t *testing.T) { + testCases := []struct { + s string + sep string + cutset string + expected []string + }{ + {"a,b,c", ",", " ", []string{"a", "b", "c"}}, + {" a , b , c ", ",", " ", []string{"a", "b", "c"}}, + {" a, b, c ", ",", " ", []string{"a", "b", "c"}}, + {" a, ", ",", " ", []string{"a"}}, + {" ", ",", " ", []string{}}, + } + + for _, tc := range testCases { + assert.Equal(t, tc.expected, splitAndTrimEmpty(tc.s, tc.sep, tc.cutset), "%s", tc.s) + } +} + +func TestNodeDelayedStart(t *testing.T) { + config := test.ResetTestRoot("node_delayed_start_test") + defer os.RemoveAll(config.RootDir) + now := cmttime.Now() + + // create & start node + n, err := DefaultNewNode(config, log.TestingLogger()) + n.GenesisDoc().GenesisTime = now.Add(2 * time.Second) + require.NoError(t, err) + + err = n.Start() + require.NoError(t, err) + defer n.Stop() //nolint:errcheck // ignore for tests + + startTime := cmttime.Now() + assert.Equal(t, true, startTime.After(n.GenesisDoc().GenesisTime)) +} + +func TestNodeSetAppVersion(t *testing.T) { + config := test.ResetTestRoot("node_app_version_test") + defer os.RemoveAll(config.RootDir) + + // create & start node + n, err := DefaultNewNode(config, log.TestingLogger()) + require.NoError(t, err) + + // default config uses the kvstore app + appVersion := kvstore.AppVersion + + // check version is set in state + state, err := n.stateStore.Load() + require.NoError(t, err) + assert.Equal(t, state.Version.Consensus.App, appVersion) + + // check version is set in node info + assert.Equal(t, n.nodeInfo.(p2p.DefaultNodeInfo).ProtocolVersion.App, appVersion) +} + +func TestPprofServer(t *testing.T) { + config := test.ResetTestRoot("node_pprof_test") + defer os.RemoveAll(config.RootDir) + config.RPC.PprofListenAddress = testFreeAddr(t) + + // should not work yet + _, err := http.Get("http://" + config.RPC.PprofListenAddress) //nolint: bodyclose + assert.Error(t, err) + + n, err := DefaultNewNode(config, log.TestingLogger()) + assert.NoError(t, err) + assert.NoError(t, n.Start()) + defer func() { + require.NoError(t, n.Stop()) + }() + assert.NotNil(t, n.pprofSrv) + + resp, err := http.Get("http://" + config.RPC.PprofListenAddress + "/debug/pprof") + assert.NoError(t, err) + defer resp.Body.Close() + assert.Equal(t, 200, resp.StatusCode) +} + +func TestNodeSetPrivValTCP(t *testing.T) { + addr := "tcp://" + testFreeAddr(t) + + config := test.ResetTestRoot("node_priv_val_tcp_test") + defer os.RemoveAll(config.RootDir) + config.PrivValidatorListenAddr = addr + + dialer := privval.DialTCPFn(addr, 100*time.Millisecond, ed25519.GenPrivKey()) + dialerEndpoint := privval.NewSignerDialerEndpoint( + log.TestingLogger(), + dialer, + ) + privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint) + + signerServer := privval.NewSignerServer( + dialerEndpoint, + test.DefaultTestChainID, + types.NewMockPV(), + ) + + go func() { + err := signerServer.Start() + if err != nil { + panic(err) + } + }() + defer signerServer.Stop() //nolint:errcheck // ignore for tests + + n, err := DefaultNewNode(config, log.TestingLogger()) + require.NoError(t, err) + assert.IsType(t, &privval.RetrySignerClient{}, n.PrivValidator()) +} + +// address without a protocol must result in error +func TestPrivValidatorListenAddrNoProtocol(t *testing.T) { + addrNoPrefix := testFreeAddr(t) + + config := test.ResetTestRoot("node_priv_val_tcp_test") + defer os.RemoveAll(config.RootDir) + config.PrivValidatorListenAddr = addrNoPrefix + + _, err := DefaultNewNode(config, log.TestingLogger()) + assert.Error(t, err) +} + +func TestNodeSetPrivValIPC(t *testing.T) { + tmpfile := "/tmp/kms." + cmtrand.Str(6) + ".sock" + defer os.Remove(tmpfile) // clean up + + config := test.ResetTestRoot("node_priv_val_tcp_test") + defer os.RemoveAll(config.RootDir) + config.PrivValidatorListenAddr = "unix://" + tmpfile + + dialer := privval.DialUnixFn(tmpfile) + dialerEndpoint := privval.NewSignerDialerEndpoint( + log.TestingLogger(), + dialer, + ) + privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint) + + pvsc := privval.NewSignerServer( + dialerEndpoint, + test.DefaultTestChainID, + types.NewMockPV(), + ) + + go func() { + err := pvsc.Start() + require.NoError(t, err) + }() + defer pvsc.Stop() //nolint:errcheck // ignore for tests + + n, err := DefaultNewNode(config, log.TestingLogger()) + require.NoError(t, err) + assert.IsType(t, &privval.RetrySignerClient{}, n.PrivValidator()) +} + +// testFreeAddr claims a free port so we don't block on listener being ready. +func testFreeAddr(t *testing.T) string { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + + return fmt.Sprintf("127.0.0.1:%d", ln.Addr().(*net.TCPAddr).Port) +} + +// create a proposal block using real and full +// mempool and evidence pool and validate it. +func TestCreateProposalBlock(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + config := test.ResetTestRoot("node_create_proposal") + defer os.RemoveAll(config.RootDir) + cc := proxy.NewLocalClientCreator(kvstore.NewInMemoryApplication()) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.Nil(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + logger := log.TestingLogger() + + var height int64 = 1 + state, stateDB, privVals := state(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + var ( + partSize uint32 = 256 + maxBytes int64 = 16384 + ) + maxEvidenceBytes := maxBytes / 2 + state.ConsensusParams.Block.MaxBytes = maxBytes + state.ConsensusParams.Evidence.MaxBytes = maxEvidenceBytes + proposerAddr, _ := state.Validators.GetByIndex(0) + + // Make Mempool + memplMetrics := mempl.NopMetrics() + mempool := mempl.NewCListMempool(config.Mempool, + proxyApp.Mempool(), + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state))) + + // Make EvidencePool + evidenceDB := dbm.NewMemDB() + blockStore := store.NewBlockStore(dbm.NewMemDB()) + evidencePool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + require.NoError(t, err) + evidencePool.SetLogger(logger) + + // fill the evidence pool with more evidence + // than can fit in a block + var currentBytes int64 + for currentBytes <= maxEvidenceBytes { + ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, time.Now(), privVals[0], "test-chain") + require.NoError(t, err) + currentBytes += int64(len(ev.Bytes())) + evidencePool.ReportConflictingVotes(ev.VoteA, ev.VoteB) + } + + evList, size := evidencePool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + require.Less(t, size, state.ConsensusParams.Evidence.MaxBytes+1) + evData := &types.EvidenceData{Evidence: evList} + require.EqualValues(t, size, evData.ByteSize()) + + // fill the mempool with more txs + // than can fit in a block + txLength := 100 + for i := 0; i <= int(maxBytes)/txLength; i++ { + tx := cmtrand.Bytes(txLength) + err := mempool.CheckTx(tx, nil, mempl.TxInfo{}) + assert.NoError(t, err) + } + + blockExec := sm.NewBlockExecutor( + stateStore, + logger, + proxyApp.Consensus(), + mempool, + evidencePool, + blockStore, + ) + + extCommit := &types.ExtendedCommit{Height: height - 1} + block, err := blockExec.CreateProposalBlock( + ctx, + height, + state, + extCommit, + proposerAddr, + ) + require.NoError(t, err) + + // check that the part set does not exceed the maximum block size + partSet, err := block.MakePartSet(partSize) + require.NoError(t, err) + assert.Less(t, partSet.ByteSize(), maxBytes) + + partSetFromHeader := types.NewPartSetFromHeader(partSet.Header()) + for partSetFromHeader.Count() < partSetFromHeader.Total() { + added, err := partSetFromHeader.AddPart(partSet.GetPart(int(partSetFromHeader.Count()))) + require.NoError(t, err) + require.True(t, added) + } + assert.EqualValues(t, partSetFromHeader.ByteSize(), partSet.ByteSize()) + + err = blockExec.ValidateBlock(state, block) + assert.NoError(t, err) +} + +func TestMaxProposalBlockSize(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + config := test.ResetTestRoot("node_create_proposal") + defer os.RemoveAll(config.RootDir) + cc := proxy.NewLocalClientCreator(kvstore.NewInMemoryApplication()) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.Nil(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + logger := log.TestingLogger() + + var height int64 = 1 + state, stateDB, _ := state(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + var maxBytes int64 = 16384 + var partSize uint32 = 256 + state.ConsensusParams.Block.MaxBytes = maxBytes + proposerAddr, _ := state.Validators.GetByIndex(0) + + // Make Mempool + memplMetrics := mempl.NopMetrics() + mempool := mempl.NewCListMempool(config.Mempool, + proxyApp.Mempool(), + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state))) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + // fill the mempool with one txs just below the maximum size + txLength := int(types.MaxDataBytesNoEvidence(maxBytes, 1)) + tx := cmtrand.Bytes(txLength - 4) // to account for the varint + err = mempool.CheckTx(tx, nil, mempl.TxInfo{}) + assert.NoError(t, err) + + blockExec := sm.NewBlockExecutor( + stateStore, + logger, + proxyApp.Consensus(), + mempool, + sm.EmptyEvidencePool{}, + blockStore, + ) + + extCommit := &types.ExtendedCommit{Height: height - 1} + block, err := blockExec.CreateProposalBlock( + ctx, + height, + state, + extCommit, + proposerAddr, + ) + require.NoError(t, err) + + pb, err := block.ToProto() + require.NoError(t, err) + assert.Less(t, int64(pb.Size()), maxBytes) + + // check that the part set does not exceed the maximum block size + partSet, err := block.MakePartSet(partSize) + require.NoError(t, err) + assert.EqualValues(t, partSet.ByteSize(), int64(pb.Size())) +} + +func TestNodeNewNodeCustomReactors(t *testing.T) { + config := test.ResetTestRoot("node_new_node_custom_reactors_test") + defer os.RemoveAll(config.RootDir) + + cr := p2pmock.NewReactor() + cr.Channels = []*conn.ChannelDescriptor{ + { + ID: byte(0x31), + Priority: 5, + SendQueueCapacity: 100, + RecvMessageCapacity: 100, + }, + } + customBlocksyncReactor := p2pmock.NewReactor() + + nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) + require.NoError(t, err) + + n, err := NewNode(config, + privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()), + nodeKey, + proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()), + DefaultGenesisDocProviderFunc(config), + cfg.DefaultDBProvider, + DefaultMetricsProvider(config.Instrumentation), + log.TestingLogger(), + CustomReactors(map[string]p2p.Reactor{"FOO": cr, "BLOCKSYNC": customBlocksyncReactor}), + ) + require.NoError(t, err) + + err = n.Start() + require.NoError(t, err) + defer n.Stop() //nolint:errcheck // ignore for tests + + assert.True(t, cr.IsRunning()) + assert.Equal(t, cr, n.Switch().Reactor("FOO")) + + assert.True(t, customBlocksyncReactor.IsRunning()) + assert.Equal(t, customBlocksyncReactor, n.Switch().Reactor("BLOCKSYNC")) + + channels := n.NodeInfo().(p2p.DefaultNodeInfo).Channels + assert.Contains(t, channels, mempl.MempoolChannel) + assert.Contains(t, channels, cr.Channels[0].ID) +} + +func state(nVals int, height int64) (sm.State, dbm.DB, []types.PrivValidator) { + privVals := make([]types.PrivValidator, nVals) + vals := make([]types.GenesisValidator, nVals) + for i := 0; i < nVals; i++ { + privVal := types.NewMockPV() + privVals[i] = privVal + vals[i] = types.GenesisValidator{ + Address: privVal.PrivKey.PubKey().Address(), + PubKey: privVal.PrivKey.PubKey(), + Power: 1000, + Name: fmt.Sprintf("test%d", i), + } + } + s, _ := sm.MakeGenesisState(&types.GenesisDoc{ + ChainID: "test-chain", + Validators: vals, + AppHash: nil, + }) + + // save validators to db for 2 heights + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + if err := stateStore.Save(s); err != nil { + panic(err) + } + + for i := 1; i < int(height); i++ { + s.LastBlockHeight++ + s.LastValidators = s.Validators.Copy() + if err := stateStore.Save(s); err != nil { + panic(err) + } + } + return s, stateDB, privVals +} diff --git a/node/setup.go b/node/setup.go new file mode 100644 index 0000000..87d0007 --- /dev/null +++ b/node/setup.go @@ -0,0 +1,663 @@ +package node + +import ( + "bytes" + "context" + "errors" + "fmt" + "net" + "strings" + "time" + + _ "net/http/pprof" //nolint: gosec // securely exposed on separate, optional port + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/blocksync" + cfg "github.com/cometbft/cometbft/config" + cs "github.com/cometbft/cometbft/consensus" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/evidence" + "github.com/cometbft/cometbft/statesync" + + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/pex" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/indexer/block" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" + + _ "github.com/lib/pq" // provide the psql db driver +) + +const readHeaderTimeout = 10 * time.Second + +// GenesisDocProvider returns a GenesisDoc. +// It allows the GenesisDoc to be pulled from sources other than the +// filesystem, for instance from a distributed key-value store cluster. +type GenesisDocProvider func() (*types.GenesisDoc, error) + +// DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads +// the GenesisDoc from the config.GenesisFile() on the filesystem. +func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider { + return func() (*types.GenesisDoc, error) { + return types.GenesisDocFromFile(config.GenesisFile()) + } +} + +// Provider takes a config and a logger and returns a ready to go Node. +type Provider func(*cfg.Config, log.Logger) (*Node, error) + +// DefaultNewNode returns a CometBFT node with default settings for the +// PrivValidator, ClientCreator, GenesisDoc, and DBProvider. +// It implements NodeProvider. +func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) { + nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) + if err != nil { + return nil, fmt.Errorf("failed to load or gen node key %s: %w", config.NodeKeyFile(), err) + } + + return NewNode(config, + privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()), + nodeKey, + proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()), + DefaultGenesisDocProviderFunc(config), + cfg.DefaultDBProvider, + DefaultMetricsProvider(config.Instrumentation), + logger, + ) +} + +// MetricsProvider returns a consensus, p2p and mempool Metrics. +type MetricsProvider func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics, *proxy.Metrics, *blocksync.Metrics, *statesync.Metrics) + +// DefaultMetricsProvider returns Metrics build using Prometheus client library +// if Prometheus is enabled. Otherwise, it returns no-op Metrics. +func DefaultMetricsProvider(config *cfg.InstrumentationConfig) MetricsProvider { + return func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics, *proxy.Metrics, *blocksync.Metrics, *statesync.Metrics) { + if config.Prometheus { + return cs.PrometheusMetrics(config.Namespace, "chain_id", chainID), + p2p.PrometheusMetrics(config.Namespace, "chain_id", chainID), + mempl.PrometheusMetrics(config.Namespace, "chain_id", chainID), + sm.PrometheusMetrics(config.Namespace, "chain_id", chainID), + proxy.PrometheusMetrics(config.Namespace, "chain_id", chainID), + blocksync.PrometheusMetrics(config.Namespace, "chain_id", chainID), + statesync.PrometheusMetrics(config.Namespace, "chain_id", chainID) + } + return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics(), sm.NopMetrics(), proxy.NopMetrics(), blocksync.NopMetrics(), statesync.NopMetrics() + } +} + +type blockSyncReactor interface { + SwitchToBlockSync(sm.State) error +} + +//------------------------------------------------------------------------------ + +func initDBs(config *cfg.Config, dbProvider cfg.DBProvider) (blockStore *store.BlockStore, stateDB dbm.DB, err error) { + var blockStoreDB dbm.DB + blockStoreDB, err = dbProvider(&cfg.DBContext{ID: "blockstore", Config: config}) + if err != nil { + return + } + blockStore = store.NewBlockStore(blockStoreDB) + + stateDB, err = dbProvider(&cfg.DBContext{ID: "state", Config: config}) + if err != nil { + return + } + + return +} + +func createAndStartProxyAppConns(clientCreator proxy.ClientCreator, logger log.Logger, metrics *proxy.Metrics) (proxy.AppConns, error) { + proxyApp := proxy.NewAppConns(clientCreator, metrics) + proxyApp.SetLogger(logger.With("module", "proxy")) + if err := proxyApp.Start(); err != nil { + return nil, fmt.Errorf("error starting proxy app connections: %v", err) + } + return proxyApp, nil +} + +func createAndStartEventBus(logger log.Logger) (*types.EventBus, error) { + eventBus := types.NewEventBus() + eventBus.SetLogger(logger.With("module", "events")) + if err := eventBus.Start(); err != nil { + return nil, err + } + return eventBus, nil +} + +func createAndStartIndexerService( + config *cfg.Config, + chainID string, + dbProvider cfg.DBProvider, + eventBus *types.EventBus, + logger log.Logger, +) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) { + var ( + txIndexer txindex.TxIndexer + blockIndexer indexer.BlockIndexer + ) + + txIndexer, blockIndexer, allIndexersDisabled, err := block.IndexerFromConfigWithDisabledIndexers(config, dbProvider, chainID) + if err != nil { + return nil, nil, nil, err + } + if allIndexersDisabled { + return nil, txIndexer, blockIndexer, nil + } + + txIndexer.SetLogger(logger.With("module", "txindex")) + blockIndexer.SetLogger(logger.With("module", "txindex")) + + indexerService := txindex.NewIndexerService(txIndexer, blockIndexer, eventBus, false) + indexerService.SetLogger(logger.With("module", "txindex")) + if err := indexerService.Start(); err != nil { + return nil, nil, nil, err + } + + return indexerService, txIndexer, blockIndexer, nil +} + +func doHandshake( + ctx context.Context, + stateStore sm.Store, + state sm.State, + blockStore sm.BlockStore, + genDoc *types.GenesisDoc, + eventBus types.BlockEventPublisher, + proxyApp proxy.AppConns, + consensusLogger log.Logger, +) error { + handshaker := cs.NewHandshaker(stateStore, state, blockStore, genDoc) + handshaker.SetLogger(consensusLogger) + handshaker.SetEventBus(eventBus) + if err := handshaker.HandshakeWithContext(ctx, proxyApp); err != nil { + return fmt.Errorf("error during handshake: %v", err) + } + return nil +} + +func logNodeStartupInfo(state sm.State, pubKey crypto.PubKey, logger, consensusLogger log.Logger) { + // Log the version info. + logger.Info("Version info", + "tendermint_version", version.TMCoreSemVer, + "abci", version.ABCISemVer, + "block", version.BlockProtocol, + "p2p", version.P2PProtocol, + "commit_hash", version.TMGitCommitHash, + ) + + // If the state and software differ in block version, at least log it. + if state.Version.Consensus.Block != version.BlockProtocol { + logger.Info("Software and state have different block protocols", + "software", version.BlockProtocol, + "state", state.Version.Consensus.Block, + ) + } + + addr := pubKey.Address() + // Log whether this node is a validator or an observer + if state.Validators.HasAddress(addr) { + consensusLogger.Info("This node is a validator", "addr", addr, "pubKey", pubKey) + } else { + consensusLogger.Info("This node is not a validator", "addr", addr, "pubKey", pubKey) + } +} + +func onlyValidatorIsUs(state sm.State, localAddr crypto.Address) bool { + if state.Validators.Size() > 1 { + return false + } + valAddr, _ := state.Validators.GetByIndex(0) + return bytes.Equal(localAddr, valAddr) +} + +// createMempoolAndMempoolReactor creates a mempool and a mempool reactor based on the config. +func createMempoolAndMempoolReactor( + config *cfg.Config, + proxyApp proxy.AppConns, + state sm.State, + memplMetrics *mempl.Metrics, + logger log.Logger, +) (mempl.Mempool, p2p.Reactor) { + switch config.Mempool.Type { + // allow empty string for backward compatibility + case cfg.MempoolTypeFlood, "": + logger = logger.With("module", "mempool") + mp := mempl.NewCListMempool( + config.Mempool, + proxyApp.Mempool(), + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + mempl.WithPreCheck(sm.TxPreCheck(state)), + mempl.WithPostCheck(sm.TxPostCheck(state)), + ) + mp.SetLogger(logger) + reactor := mempl.NewReactor( + config.Mempool, + mp, + ) + if config.Consensus.WaitForTxs() { + mp.EnableTxsAvailable() + } + reactor.SetLogger(logger) + + return mp, reactor + case cfg.MempoolTypeNop: + // Strictly speaking, there's no need to have a `mempl.NopMempoolReactor`, but + // adding it leads to a cleaner code. + return &mempl.NopMempool{}, mempl.NewNopMempoolReactor() + default: + panic(fmt.Sprintf("unknown mempool type: %q", config.Mempool.Type)) + } +} + +func createEvidenceReactor(config *cfg.Config, dbProvider cfg.DBProvider, + stateStore sm.Store, blockStore *store.BlockStore, logger log.Logger, +) (*evidence.Reactor, *evidence.Pool, error) { + evidenceDB, err := dbProvider(&cfg.DBContext{ID: "evidence", Config: config}) + if err != nil { + return nil, nil, err + } + evidenceLogger := logger.With("module", "evidence") + evidencePool, err := evidence.NewPool(evidenceDB, stateStore, blockStore) + if err != nil { + return nil, nil, err + } + evidenceReactor := evidence.NewReactor(evidencePool) + evidenceReactor.SetLogger(evidenceLogger) + return evidenceReactor, evidencePool, nil +} + +func createBlocksyncReactor(config *cfg.Config, + state sm.State, + blockExec *sm.BlockExecutor, + blockStore *store.BlockStore, + blockSync bool, + localAddr crypto.Address, + logger log.Logger, + metrics *blocksync.Metrics, + offlineStateSyncHeight int64, +) (bcReactor p2p.Reactor, err error) { + switch config.BlockSync.Version { + case "v0": + bcReactor = blocksync.NewReactorWithAddr(state.Copy(), blockExec, blockStore, blockSync, localAddr, metrics, offlineStateSyncHeight) + case "v1", "v2": + return nil, fmt.Errorf("block sync version %s has been deprecated. Please use v0", config.BlockSync.Version) + default: + return nil, fmt.Errorf("unknown block sync version %s", config.BlockSync.Version) + } + + bcReactor.SetLogger(logger.With("module", "blocksync")) + return bcReactor, nil +} + +func createConsensusReactor(config *cfg.Config, + state sm.State, + blockExec *sm.BlockExecutor, + blockStore sm.BlockStore, + mempool mempl.Mempool, + evidencePool *evidence.Pool, + privValidator types.PrivValidator, + csMetrics *cs.Metrics, + waitSync bool, + eventBus *types.EventBus, + consensusLogger log.Logger, + offlineStateSyncHeight int64, +) (*cs.Reactor, *cs.State) { + consensusState := cs.NewState( + config.Consensus, + state.Copy(), + blockExec, + blockStore, + mempool, + evidencePool, + cs.StateMetrics(csMetrics), + cs.OfflineStateSyncHeight(offlineStateSyncHeight), + ) + consensusState.SetLogger(consensusLogger) + if privValidator != nil { + consensusState.SetPrivValidator(privValidator) + } + consensusReactor := cs.NewReactor(consensusState, waitSync, cs.ReactorMetrics(csMetrics)) + consensusReactor.SetLogger(consensusLogger) + // services which will be publishing and/or subscribing for messages (events) + // consensusReactor will set it on consensusState and blockExecutor + consensusReactor.SetEventBus(eventBus) + return consensusReactor, consensusState +} + +func createTransport( + config *cfg.Config, + nodeInfo p2p.NodeInfo, + nodeKey *p2p.NodeKey, + proxyApp proxy.AppConns, +) ( + *p2p.MultiplexTransport, + []p2p.PeerFilterFunc, +) { + var ( + mConnConfig = p2p.MConnConfig(config.P2P) + transport = p2p.NewMultiplexTransport(nodeInfo, *nodeKey, mConnConfig) + connFilters = []p2p.ConnFilterFunc{} + peerFilters = []p2p.PeerFilterFunc{} + ) + + if !config.P2P.AllowDuplicateIP { + connFilters = append(connFilters, p2p.ConnDuplicateIPFilter()) + } + + // Filter peers by addr or pubkey with an ABCI query. + // If the query return code is OK, add peer. + if config.FilterPeers { + connFilters = append( + connFilters, + // ABCI query for address filtering. + func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error { + res, err := proxyApp.Query().Query(context.TODO(), &abci.RequestQuery{ + Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()), + }) + if err != nil { + return err + } + if res.IsErr() { + return fmt.Errorf("error querying abci app: %v", res) + } + + return nil + }, + ) + + peerFilters = append( + peerFilters, + // ABCI query for ID filtering. + func(_ p2p.IPeerSet, p p2p.Peer) error { + res, err := proxyApp.Query().Query(context.TODO(), &abci.RequestQuery{ + Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()), + }) + if err != nil { + return err + } + if res.IsErr() { + return fmt.Errorf("error querying abci app: %v", res) + } + + return nil + }, + ) + } + + p2p.MultiplexTransportConnFilters(connFilters...)(transport) + + // Limit the number of incoming connections. + max := config.P2P.MaxNumInboundPeers + len(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " ")) + p2p.MultiplexTransportMaxIncomingConnections(max)(transport) + + return transport, peerFilters +} + +func createSwitch(config *cfg.Config, + transport p2p.Transport, + p2pMetrics *p2p.Metrics, + peerFilters []p2p.PeerFilterFunc, + mempoolReactor p2p.Reactor, + bcReactor p2p.Reactor, + stateSyncReactor *statesync.Reactor, + consensusReactor *cs.Reactor, + evidenceReactor *evidence.Reactor, + nodeInfo p2p.NodeInfo, + nodeKey *p2p.NodeKey, + p2pLogger log.Logger, +) *p2p.Switch { + sw := p2p.NewSwitch( + config.P2P, + transport, + p2p.WithMetrics(p2pMetrics), + p2p.SwitchPeerFilters(peerFilters...), + ) + sw.SetLogger(p2pLogger) + if config.Mempool.Type != cfg.MempoolTypeNop { + sw.AddReactor("MEMPOOL", mempoolReactor) + } + sw.AddReactor("BLOCKSYNC", bcReactor) + sw.AddReactor("CONSENSUS", consensusReactor) + sw.AddReactor("EVIDENCE", evidenceReactor) + sw.AddReactor("STATESYNC", stateSyncReactor) + + sw.SetNodeInfo(nodeInfo) + sw.SetNodeKey(nodeKey) + + p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", config.NodeKeyFile()) + return sw +} + +func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch, + p2pLogger log.Logger, nodeKey *p2p.NodeKey, +) (pex.AddrBook, error) { + addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict) + addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile())) + + // Add ourselves to addrbook to prevent dialing ourselves + if config.P2P.ExternalAddress != "" { + addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ExternalAddress)) + if err != nil { + return nil, fmt.Errorf("p2p.external_address is incorrect: %w", err) + } + addrBook.AddOurAddress(addr) + } + if config.P2P.ListenAddress != "" { + addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ListenAddress)) + if err != nil { + return nil, fmt.Errorf("p2p.laddr is incorrect: %w", err) + } + addrBook.AddOurAddress(addr) + } + + sw.SetAddrBook(addrBook) + + return addrBook, nil +} + +func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config, + sw *p2p.Switch, logger log.Logger, +) *pex.Reactor { + // TODO persistent peers ? so we can have their DNS addrs saved + pexReactor := pex.NewReactor(addrBook, + &pex.ReactorConfig{ + Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "), + SeedMode: config.P2P.SeedMode, + // See consensus/reactor.go: blocksToContributeToBecomeGoodPeer 10000 + // blocks assuming 10s blocks ~ 28 hours. + // TODO (melekes): make it dynamic based on the actual block latencies + // from the live network. + // https://github.com/tendermint/tendermint/issues/3523 + SeedDisconnectWaitPeriod: 28 * time.Hour, + PersistentPeersMaxDialPeriod: config.P2P.PersistentPeersMaxDialPeriod, + }) + pexReactor.SetLogger(logger.With("module", "pex")) + sw.AddReactor("PEX", pexReactor) + return pexReactor +} + +// startStateSync starts an asynchronous state sync process, then switches to block sync mode. +func startStateSync( + ssR *statesync.Reactor, + bcR blockSyncReactor, + stateProvider statesync.StateProvider, + config *cfg.StateSyncConfig, + stateStore sm.Store, + blockStore *store.BlockStore, + state sm.State, +) error { + ssR.Logger.Info("Starting state sync") + + if stateProvider == nil { + var err error + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + stateProvider, err = statesync.NewLightClientStateProvider( + ctx, + state.ChainID, state.Version, state.InitialHeight, + config.RPCServers, light.TrustOptions{ + Period: config.TrustPeriod, + Height: config.TrustHeight, + Hash: config.TrustHashBytes(), + }, ssR.Logger.With("module", "light")) + if err != nil { + return fmt.Errorf("failed to set up light client state provider: %w", err) + } + } + + go func() { + state, commit, err := ssR.Sync(stateProvider, config.DiscoveryTime) + if err != nil { + ssR.Logger.Error("State sync failed", "err", err) + return + } + err = stateStore.Bootstrap(state) + if err != nil { + ssR.Logger.Error("Failed to bootstrap node with new state", "err", err) + return + } + err = blockStore.SaveSeenCommit(state.LastBlockHeight, commit) + if err != nil { + ssR.Logger.Error("Failed to store last seen commit", "err", err) + return + } + + err = bcR.SwitchToBlockSync(state) + if err != nil { + ssR.Logger.Error("Failed to switch to block sync", "err", err) + return + } + }() + return nil +} + +//------------------------------------------------------------------------------ + +var genesisDocKey = []byte("genesisDoc") + +// LoadStateFromDBOrGenesisDocProvider attempts to load the state from the +// database, or creates one using the given genesisDocProvider. On success this also +// returns the genesis doc loaded through the given provider. +func LoadStateFromDBOrGenesisDocProvider( + stateDB dbm.DB, + genesisDocProvider GenesisDocProvider, +) (sm.State, *types.GenesisDoc, error) { + // Get genesis doc + genDoc, err := loadGenesisDoc(stateDB) + if err != nil { + genDoc, err = genesisDocProvider() + if err != nil { + return sm.State{}, nil, err + } + + err = genDoc.ValidateAndComplete() + if err != nil { + return sm.State{}, nil, fmt.Errorf("error in genesis doc: %w", err) + } + // save genesis doc to prevent a certain class of user errors (e.g. when it + // was changed, accidentally or not). Also good for audit trail. + if err := saveGenesisDoc(stateDB, genDoc); err != nil { + return sm.State{}, nil, err + } + } + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc) + if err != nil { + return sm.State{}, nil, err + } + return state, genDoc, nil +} + +// panics if failed to unmarshal bytes +func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) { + b, err := db.Get(genesisDocKey) + if err != nil { + panic(err) + } + if len(b) == 0 { + return nil, errors.New("genesis doc not found") + } + var genDoc *types.GenesisDoc + err = cmtjson.Unmarshal(b, &genDoc) + if err != nil { + panic(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, b)) + } + return genDoc, nil +} + +// panics if failed to marshal the given genesis document +func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) error { + b, err := cmtjson.Marshal(genDoc) + if err != nil { + return fmt.Errorf("failed to save genesis doc due to marshaling error: %w", err) + } + return db.SetSync(genesisDocKey, b) +} + +func createAndStartPrivValidatorSocketClient( + listenAddr, + chainID string, + logger log.Logger, +) (types.PrivValidator, error) { + pve, err := privval.NewSignerListener(listenAddr, logger) + if err != nil { + return nil, fmt.Errorf("failed to start private validator: %w", err) + } + + pvsc, err := privval.NewSignerClient(pve, chainID) + if err != nil { + return nil, fmt.Errorf("failed to start private validator: %w", err) + } + + // try to get a pubkey from private validate first time + _, err = pvsc.GetPubKey() + if err != nil { + return nil, fmt.Errorf("can't get pubkey: %w", err) + } + + const ( + retries = 50 // 50 * 100ms = 5s total + timeout = 100 * time.Millisecond + ) + pvscWithRetries := privval.NewRetrySignerClient(pvsc, retries, timeout) + + return pvscWithRetries, nil +} + +// splitAndTrimEmpty slices s into all subslices separated by sep and returns a +// slice of the string s with all leading and trailing Unicode code points +// contained in cutset removed. If sep is empty, SplitAndTrim splits after each +// UTF-8 sequence. First part is equivalent to strings.SplitN with a count of +// -1. also filter out empty strings, only return non-empty strings. +func splitAndTrimEmpty(s, sep, cutset string) []string { + if s == "" { + return []string{} + } + + spl := strings.Split(s, sep) + nonEmptyStrings := make([]string, 0, len(spl)) + for i := 0; i < len(spl); i++ { + element := strings.Trim(spl[i], cutset) + if element != "" { + nonEmptyStrings = append(nonEmptyStrings, element) + } + } + return nonEmptyStrings +} diff --git a/p2p/README.md b/p2p/README.md new file mode 100644 index 0000000..3ac1513 --- /dev/null +++ b/p2p/README.md @@ -0,0 +1,10 @@ +# p2p + +The p2p package provides an abstraction around peer-to-peer communication. + +Docs: + +- [Connection](../spec/p2p/legacy-docs/connection.md) for details on how connections and multiplexing work +- [Peer](../spec/p2p/legacy-docs/node.md) for details on peer ID, handshakes, and peer exchange +- [Node](../spec/p2p/legacy-docs/node.md) for details about different types of nodes and how they should work +- [Config](../spec/p2p/legacy-docs/config.md) for details on some config option diff --git a/p2p/base_reactor.go b/p2p/base_reactor.go new file mode 100644 index 0000000..0e1513b --- /dev/null +++ b/p2p/base_reactor.go @@ -0,0 +1,67 @@ +package p2p + +import ( + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/p2p/conn" +) + +// Reactor is responsible for handling incoming messages on one or more +// Channel. Switch calls GetChannels when reactor is added to it. When a new +// peer joins our node, InitPeer and AddPeer are called. RemovePeer is called +// when the peer is stopped. Receive is called when a message is received on a +// channel associated with this reactor. +// +// Peer#Send or Peer#TrySend should be used to send the message to a peer. +type Reactor interface { + service.Service // Start, Stop + + // SetSwitch allows setting a switch. + SetSwitch(*Switch) + + // GetChannels returns the list of MConnection.ChannelDescriptor. Make sure + // that each ID is unique across all the reactors added to the switch. + GetChannels() []*conn.ChannelDescriptor + + // InitPeer is called by the switch before the peer is started. Use it to + // initialize data for the peer (e.g. peer state). + // + // NOTE: The switch won't call AddPeer nor RemovePeer if it fails to start + // the peer. Do not store any data associated with the peer in the reactor + // itself unless you don't want to have a state, which is never cleaned up. + InitPeer(peer Peer) Peer + + // AddPeer is called by the switch after the peer is added and successfully + // started. Use it to start goroutines communicating with the peer. + AddPeer(peer Peer) + + // RemovePeer is called by the switch when the peer is stopped (due to error + // or other reason). + RemovePeer(peer Peer, reason interface{}) + + // Receive is called by the switch when an envelope is received from any connected + // peer on any of the channels registered by the reactor + Receive(Envelope) +} + +//-------------------------------------- + +type BaseReactor struct { + service.BaseService // Provides Start, Stop, .Quit + Switch *Switch +} + +func NewBaseReactor(name string, impl Reactor) *BaseReactor { + return &BaseReactor{ + BaseService: *service.NewBaseService(nil, name, impl), + Switch: nil, + } +} + +func (br *BaseReactor) SetSwitch(sw *Switch) { + br.Switch = sw +} +func (*BaseReactor) GetChannels() []*conn.ChannelDescriptor { return nil } +func (*BaseReactor) AddPeer(Peer) {} +func (*BaseReactor) RemovePeer(Peer, interface{}) {} +func (*BaseReactor) Receive(Envelope) {} +func (*BaseReactor) InitPeer(peer Peer) Peer { return peer } diff --git a/p2p/conn/conn_go110.go b/p2p/conn/conn_go110.go new file mode 100644 index 0000000..7dc61d0 --- /dev/null +++ b/p2p/conn/conn_go110.go @@ -0,0 +1,16 @@ +//go:build go1.10 +// +build go1.10 + +package conn + +// Go1.10 has a proper net.Conn implementation that +// has the SetDeadline method implemented as per +// https://github.com/golang/go/commit/e2dd8ca946be884bb877e074a21727f1a685a706 +// lest we run into problems like +// https://github.com/tendermint/tendermint/issues/851 + +import "net" + +func NetPipe() (net.Conn, net.Conn) { + return net.Pipe() +} diff --git a/p2p/conn/conn_notgo110.go b/p2p/conn/conn_notgo110.go new file mode 100644 index 0000000..b598f99 --- /dev/null +++ b/p2p/conn/conn_notgo110.go @@ -0,0 +1,33 @@ +//go:build !go1.10 +// +build !go1.10 + +package conn + +import ( + "net" + "time" +) + +// Only Go1.10 has a proper net.Conn implementation that +// has the SetDeadline method implemented as per +// https://github.com/golang/go/commit/e2dd8ca946be884bb877e074a21727f1a685a706 +// lest we run into problems like +// https://github.com/tendermint/tendermint/issues/851 +// so for go versions < Go1.10 use our custom net.Conn creator +// that doesn't return an `Unimplemented error` for net.Conn. +// Before https://github.com/cometbft/cometbft/commit/49faa79bdce5663894b3febbf4955fb1d172df04 +// we hadn't cared about errors from SetDeadline so swallow them up anyways. +type pipe struct { + net.Conn +} + +func (p *pipe) SetDeadline(t time.Time) error { + return nil +} + +func NetPipe() (net.Conn, net.Conn) { + p1, p2 := net.Pipe() + return &pipe{p1}, &pipe{p2} +} + +var _ net.Conn = (*pipe)(nil) diff --git a/p2p/conn/connection.go b/p2p/conn/connection.go new file mode 100644 index 0000000..4fb3a86 --- /dev/null +++ b/p2p/conn/connection.go @@ -0,0 +1,954 @@ +package conn + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "net" + "reflect" + "runtime/debug" + "sync/atomic" + "time" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/config" + flow "github.com/cometbft/cometbft/libs/flowrate" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/protoio" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/libs/timer" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +const ( + defaultMaxPacketMsgPayloadSize = 1024 + + numBatchPacketMsgs = 10 + minReadBufferSize = 1024 + minWriteBufferSize = 65536 + updateStats = 2 * time.Second + + // some of these defaults are written in the user config + // flushThrottle, sendRate, recvRate + // TODO: remove values present in config + defaultFlushThrottle = 100 * time.Millisecond + + defaultSendQueueCapacity = 1 + defaultRecvBufferCapacity = 4096 + defaultRecvMessageCapacity = 22020096 // 21MB + defaultSendRate = int64(512000) // 500KB/s + defaultRecvRate = int64(512000) // 500KB/s + defaultSendTimeout = 10 * time.Second + defaultPingInterval = 60 * time.Second + defaultPongTimeout = 45 * time.Second +) + +type ( + receiveCbFunc func(chID byte, msgBytes []byte) + errorCbFunc func(interface{}) +) + +/* +Each peer has one `MConnection` (multiplex connection) instance. + +__multiplex__ *noun* a system or signal involving simultaneous transmission of +several messages along a single channel of communication. + +Each `MConnection` handles message transmission on multiple abstract communication +`Channel`s. Each channel has a globally unique byte id. +The byte id and the relative priorities of each `Channel` are configured upon +initialization of the connection. + +There are two methods for sending messages: + + func (m MConnection) Send(chID byte, msgBytes []byte) bool {} + func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {} + +`Send(chID, msgBytes)` is a blocking call that waits until `msg` is +successfully queued for the channel with the given id byte `chID`, or until the +request times out. The message `msg` is serialized using Protobuf. + +`TrySend(chID, msgBytes)` is a nonblocking call that returns false if the +channel's queue is full. + +Inbound message bytes are handled with an onReceive callback function. +*/ +type MConnection struct { + service.BaseService + + conn net.Conn + bufConnReader *bufio.Reader + bufConnWriter *bufio.Writer + sendMonitor *flow.Monitor + recvMonitor *flow.Monitor + send chan struct{} + pong chan struct{} + channels []*Channel + channelsIdx map[byte]*Channel + onReceive receiveCbFunc + onError errorCbFunc + errored uint32 + config MConnConfig + + // Closing quitSendRoutine will cause the sendRoutine to eventually quit. + // doneSendRoutine is closed when the sendRoutine actually quits. + quitSendRoutine chan struct{} + doneSendRoutine chan struct{} + + // Closing quitRecvRouting will cause the recvRouting to eventually quit. + quitRecvRoutine chan struct{} + + // used to ensure FlushStop and OnStop + // are safe to call concurrently. + stopMtx cmtsync.Mutex + + flushTimer *timer.ThrottleTimer // flush writes as necessary but throttled. + pingTimer *time.Ticker // send pings periodically + + // close conn if pong is not received in pongTimeout + pongTimer *time.Timer + pongTimeoutCh chan bool // true - timeout, false - peer sent pong + + chStatsTimer *time.Ticker // update channel stats periodically + + created time.Time // time of creation + + _maxPacketMsgSize int +} + +// MConnConfig is a MConnection configuration. +type MConnConfig struct { + SendRate int64 `mapstructure:"send_rate"` + RecvRate int64 `mapstructure:"recv_rate"` + + // Maximum payload size + MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"` + + // Interval to flush writes (throttled) + FlushThrottle time.Duration `mapstructure:"flush_throttle"` + + // Interval to send pings + PingInterval time.Duration `mapstructure:"ping_interval"` + + // Maximum wait time for pongs + PongTimeout time.Duration `mapstructure:"pong_timeout"` + + // Fuzz connection + TestFuzz bool `mapstructure:"test_fuzz"` + TestFuzzConfig *config.FuzzConnConfig `mapstructure:"test_fuzz_config"` +} + +// DefaultMConnConfig returns the default config. +func DefaultMConnConfig() MConnConfig { + return MConnConfig{ + SendRate: defaultSendRate, + RecvRate: defaultRecvRate, + MaxPacketMsgPayloadSize: defaultMaxPacketMsgPayloadSize, + FlushThrottle: defaultFlushThrottle, + PingInterval: defaultPingInterval, + PongTimeout: defaultPongTimeout, + } +} + +// NewMConnection wraps net.Conn and creates multiplex connection +func NewMConnection( + conn net.Conn, + chDescs []*ChannelDescriptor, + onReceive receiveCbFunc, + onError errorCbFunc, +) *MConnection { + return NewMConnectionWithConfig( + conn, + chDescs, + onReceive, + onError, + DefaultMConnConfig()) +} + +// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config +func NewMConnectionWithConfig( + conn net.Conn, + chDescs []*ChannelDescriptor, + onReceive receiveCbFunc, + onError errorCbFunc, + config MConnConfig, +) *MConnection { + if config.PongTimeout >= config.PingInterval { + panic("pongTimeout must be less than pingInterval (otherwise, next ping will reset pong timer)") + } + + mconn := &MConnection{ + conn: conn, + bufConnReader: bufio.NewReaderSize(conn, minReadBufferSize), + bufConnWriter: bufio.NewWriterSize(conn, minWriteBufferSize), + sendMonitor: flow.New(0, 0), + recvMonitor: flow.New(0, 0), + send: make(chan struct{}, 1), + pong: make(chan struct{}, 1), + onReceive: onReceive, + onError: onError, + config: config, + created: time.Now(), + } + + // Create channels + channelsIdx := map[byte]*Channel{} + channels := []*Channel{} + + for _, desc := range chDescs { + channel := newChannel(mconn, *desc) + channelsIdx[channel.desc.ID] = channel + channels = append(channels, channel) + } + mconn.channels = channels + mconn.channelsIdx = channelsIdx + + mconn.BaseService = *service.NewBaseService(nil, "MConnection", mconn) + + // maxPacketMsgSize() is a bit heavy, so call just once + mconn._maxPacketMsgSize = mconn.maxPacketMsgSize() + + return mconn +} + +func (c *MConnection) SetLogger(l log.Logger) { + c.BaseService.SetLogger(l) + for _, ch := range c.channels { + ch.SetLogger(l) + } +} + +// OnStart implements BaseService +func (c *MConnection) OnStart() error { + if err := c.BaseService.OnStart(); err != nil { + return err + } + c.flushTimer = timer.NewThrottleTimer("flush", c.config.FlushThrottle) + c.pingTimer = time.NewTicker(c.config.PingInterval) + c.pongTimeoutCh = make(chan bool, 1) + c.chStatsTimer = time.NewTicker(updateStats) + c.quitSendRoutine = make(chan struct{}) + c.doneSendRoutine = make(chan struct{}) + c.quitRecvRoutine = make(chan struct{}) + go c.sendRoutine() + go c.recvRoutine() + return nil +} + +// stopServices stops the BaseService and timers and closes the quitSendRoutine. +// if the quitSendRoutine was already closed, it returns true, otherwise it returns false. +// It uses the stopMtx to ensure only one of FlushStop and OnStop can do this at a time. +func (c *MConnection) stopServices() (alreadyStopped bool) { + c.stopMtx.Lock() + defer c.stopMtx.Unlock() + + select { + case <-c.quitSendRoutine: + // already quit + return true + default: + } + + select { + case <-c.quitRecvRoutine: + // already quit + return true + default: + } + + c.BaseService.OnStop() + c.flushTimer.Stop() + c.pingTimer.Stop() + c.chStatsTimer.Stop() + + // inform the recvRouting that we are shutting down + close(c.quitRecvRoutine) + close(c.quitSendRoutine) + return false +} + +// FlushStop replicates the logic of OnStop. +// It additionally ensures that all successful +// .Send() calls will get flushed before closing +// the connection. +func (c *MConnection) FlushStop() { + if c.stopServices() { + return + } + + // this block is unique to FlushStop + { + // wait until the sendRoutine exits + // so we dont race on calling sendSomePacketMsgs + <-c.doneSendRoutine + + // Send and flush all pending msgs. + // Since sendRoutine has exited, we can call this + // safely + w := protoio.NewDelimitedWriter(c.bufConnWriter) + eof := c.sendSomePacketMsgs(w) + for !eof { + eof = c.sendSomePacketMsgs(w) + } + c.flush() + + // Now we can close the connection + } + + c.conn.Close() + + // We can't close pong safely here because + // recvRoutine may write to it after we've stopped. + // Though it doesn't need to get closed at all, + // we close it @ recvRoutine. + + // c.Stop() +} + +// OnStop implements BaseService +func (c *MConnection) OnStop() { + if c.stopServices() { + return + } + + c.conn.Close() + + // We can't close pong safely here because + // recvRoutine may write to it after we've stopped. + // Though it doesn't need to get closed at all, + // we close it @ recvRoutine. +} + +func (c *MConnection) String() string { + return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr()) +} + +func (c *MConnection) flush() { + c.Logger.Debug("Flush", "conn", c) + err := c.bufConnWriter.Flush() + if err != nil { + c.Logger.Debug("MConnection flush failed", "err", err) + } +} + +// Catch panics, usually caused by remote disconnects. +func (c *MConnection) _recover() { + if r := recover(); r != nil { + c.Logger.Error("MConnection panicked", "err", r, "stack", string(debug.Stack())) + c.stopForError(fmt.Errorf("recovered from panic: %v", r)) + } +} + +func (c *MConnection) stopForError(r interface{}) { + if err := c.Stop(); err != nil { + c.Logger.Error("Error stopping connection", "err", err) + } + if atomic.CompareAndSwapUint32(&c.errored, 0, 1) { + if c.onError != nil { + c.onError(r) + } + } +} + +// Queues a message to be sent to channel. +func (c *MConnection) Send(chID byte, msgBytes []byte) bool { + if !c.IsRunning() { + return false + } + + c.Logger.Debug("Send", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes)) + + // Send message to channel. + channel, ok := c.channelsIdx[chID] + if !ok { + c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID)) + return false + } + + success := channel.sendBytes(msgBytes) + if success { + // Wake up sendRoutine if necessary + select { + case c.send <- struct{}{}: + default: + } + } else { + c.Logger.Debug("Send failed", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes)) + } + return success +} + +// Queues a message to be sent to channel. +// Nonblocking, returns true if successful. +func (c *MConnection) TrySend(chID byte, msgBytes []byte) bool { + if !c.IsRunning() { + return false + } + + c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes)) + + // Send message to channel. + channel, ok := c.channelsIdx[chID] + if !ok { + c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID)) + return false + } + + ok = channel.trySendBytes(msgBytes) + if ok { + // Wake up sendRoutine if necessary + select { + case c.send <- struct{}{}: + default: + } + } + + return ok +} + +// CanSend returns true if you can send more data onto the chID, false +// otherwise. Use only as a heuristic. +func (c *MConnection) CanSend(chID byte) bool { + if !c.IsRunning() { + return false + } + + channel, ok := c.channelsIdx[chID] + if !ok { + c.Logger.Error(fmt.Sprintf("Unknown channel %X", chID)) + return false + } + return channel.canSend() +} + +// sendRoutine polls for packets to send from channels. +func (c *MConnection) sendRoutine() { + defer c._recover() + + protoWriter := protoio.NewDelimitedWriter(c.bufConnWriter) + +FOR_LOOP: + for { + var _n int + var err error + SELECTION: + select { + case <-c.flushTimer.Ch: + // NOTE: flushTimer.Set() must be called every time + // something is written to .bufConnWriter. + c.flush() + case <-c.chStatsTimer.C: + for _, channel := range c.channels { + channel.updateStats() + } + case <-c.pingTimer.C: + c.Logger.Debug("Send Ping") + _n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{})) + if err != nil { + c.Logger.Error("Failed to send PacketPing", "err", err) + break SELECTION + } + c.sendMonitor.Update(_n) + c.Logger.Debug("Starting pong timer", "dur", c.config.PongTimeout) + c.pongTimer = time.AfterFunc(c.config.PongTimeout, func() { + select { + case c.pongTimeoutCh <- true: + default: + } + }) + c.flush() + case timeout := <-c.pongTimeoutCh: + if timeout { + c.Logger.Debug("Pong timeout") + err = errors.New("pong timeout") + } else { + c.stopPongTimer() + } + case <-c.pong: + c.Logger.Debug("Send Pong") + _n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + if err != nil { + c.Logger.Error("Failed to send PacketPong", "err", err) + break SELECTION + } + c.sendMonitor.Update(_n) + c.flush() + case <-c.quitSendRoutine: + break FOR_LOOP + case <-c.send: + // Send some PacketMsgs + eof := c.sendSomePacketMsgs(protoWriter) + if !eof { + // Keep sendRoutine awake. + select { + case c.send <- struct{}{}: + default: + } + } + } + + if !c.IsRunning() { + break FOR_LOOP + } + if err != nil { + c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err) + c.stopForError(err) + break FOR_LOOP + } + } + + // Cleanup + c.stopPongTimer() + close(c.doneSendRoutine) +} + +// Returns true if messages from channels were exhausted. +// Blocks in accordance to .sendMonitor throttling. +func (c *MConnection) sendSomePacketMsgs(w protoio.Writer) bool { + // Block until .sendMonitor says we can write. + // Once we're ready we send more than we asked for, + // but amortized it should even out. + c.sendMonitor.Limit(c._maxPacketMsgSize, c.config.SendRate, true) + + // Now send some PacketMsgs. + return c.sendBatchPacketMsgs(w, numBatchPacketMsgs) +} + +// Returns true if messages from channels were exhausted. +func (c *MConnection) sendBatchPacketMsgs(w protoio.Writer, batchSize int) bool { + // Send a batch of PacketMsgs. + totalBytesWritten := 0 + defer func() { + if totalBytesWritten > 0 { + c.sendMonitor.Update(totalBytesWritten) + } + }() + for i := 0; i < batchSize; i++ { + channel := selectChannelToGossipOn(c.channels) + // nothing to send across any channel. + if channel == nil { + return true + } + bytesWritten, err := c.sendPacketMsgOnChannel(w, channel) + if err { + return true + } + totalBytesWritten += bytesWritten + } + return false +} + +// selects a channel to gossip our next message on. +// TODO: Make "batchChannelToGossipOn", so we can do our proto marshaling overheads in parallel, +// and we can avoid re-checking for `isSendPending`. +// We can easily mock the recentlySent differences for the batch choosing. +func selectChannelToGossipOn(channels []*Channel) *Channel { + // Choose a channel to create a PacketMsg from. + // The chosen channel will be the one whose recentlySent/priority is the least. + var leastRatio float32 = math.MaxFloat32 + var leastChannel *Channel + for _, channel := range channels { + // If nothing to send, skip this channel + // TODO: Skip continually looking for isSendPending on channels we've already skipped in this batch-send. + if !channel.isSendPending() { + continue + } + // Get ratio, and keep track of lowest ratio. + // TODO: RecentlySent right now is bytes. This should be refactored to num messages to fix + // gossip prioritization bugs. + ratio := float32(channel.recentlySent) / float32(channel.desc.Priority) + if ratio < leastRatio { + leastRatio = ratio + leastChannel = channel + } + } + return leastChannel +} + +// returns (num_bytes_written, error_occurred). +func (c *MConnection) sendPacketMsgOnChannel(w protoio.Writer, sendChannel *Channel) (int, bool) { + // Make & send a PacketMsg from this channel + n, err := sendChannel.writePacketMsgTo(w) + if err != nil { + c.Logger.Error("Failed to write PacketMsg", "err", err) + c.stopForError(err) + return n, true + } + // TODO: Change this to only add flush signals at the start and end of the batch. + c.flushTimer.Set() + return n, false +} + +// recvRoutine reads PacketMsgs and reconstructs the message using the channels' "recving" buffer. +// After a whole message has been assembled, it's pushed to onReceive(). +// Blocks depending on how the connection is throttled. +// Otherwise, it never blocks. +func (c *MConnection) recvRoutine() { + defer c._recover() + + protoReader := protoio.NewDelimitedReader(c.bufConnReader, c._maxPacketMsgSize) + +FOR_LOOP: + for { + // Block until .recvMonitor says we can read. + c.recvMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.RecvRate), true) + + // Peek into bufConnReader for debugging + /* + if numBytes := c.bufConnReader.Buffered(); numBytes > 0 { + bz, err := c.bufConnReader.Peek(cmtmath.MinInt(numBytes, 100)) + if err == nil { + // return + } else { + c.Logger.Debug("Error peeking connection buffer", "err", err) + // return nil + } + c.Logger.Info("Peek connection buffer", "numBytes", numBytes, "bz", bz) + } + */ + + // Read packet type + var packet tmp2p.Packet + + _n, err := protoReader.ReadMsg(&packet) + c.recvMonitor.Update(_n) + if err != nil { + // stopServices was invoked and we are shutting down + // receiving is excpected to fail since we will close the connection + select { + case <-c.quitRecvRoutine: + break FOR_LOOP + default: + } + + if c.IsRunning() { + if err == io.EOF { + c.Logger.Info("Connection is closed @ recvRoutine (likely by the other side)", "conn", c) + } else { + c.Logger.Debug("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err) + } + c.stopForError(err) + } + break FOR_LOOP + } + + // Read more depending on packet type. + switch pkt := packet.Sum.(type) { + case *tmp2p.Packet_PacketPing: + // TODO: prevent abuse, as they cause flush()'s. + // https://github.com/tendermint/tendermint/issues/1190 + c.Logger.Debug("Receive Ping") + select { + case c.pong <- struct{}{}: + default: + // never block + } + case *tmp2p.Packet_PacketPong: + c.Logger.Debug("Receive Pong") + select { + case c.pongTimeoutCh <- false: + default: + // never block + } + case *tmp2p.Packet_PacketMsg: + channelID := byte(pkt.PacketMsg.ChannelID) + channel, ok := c.channelsIdx[channelID] + if pkt.PacketMsg.ChannelID < 0 || pkt.PacketMsg.ChannelID > math.MaxUint8 || !ok || channel == nil { + err := fmt.Errorf("unknown channel %X", pkt.PacketMsg.ChannelID) + c.Logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err) + c.stopForError(err) + break FOR_LOOP + } + + msgBytes, err := channel.recvPacketMsg(*pkt.PacketMsg) + if err != nil { + if c.IsRunning() { + c.Logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err) + c.stopForError(err) + } + break FOR_LOOP + } + if msgBytes != nil { + c.Logger.Debug("Received bytes", "chID", channelID, "msgBytes", msgBytes) + // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine + c.onReceive(channelID, msgBytes) + } + default: + err := fmt.Errorf("unknown message type %v", reflect.TypeOf(packet)) + c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err) + c.stopForError(err) + break FOR_LOOP + } + } + + // Cleanup + close(c.pong) + //nolint:revive + for range c.pong { + // Drain + } +} + +// not goroutine-safe +func (c *MConnection) stopPongTimer() { + if c.pongTimer != nil { + _ = c.pongTimer.Stop() + c.pongTimer = nil + } +} + +// maxPacketMsgSize returns a maximum size of PacketMsg +func (c *MConnection) maxPacketMsgSize() int { + bz, err := proto.Marshal(mustWrapPacket(&tmp2p.PacketMsg{ + ChannelID: 0x01, + EOF: true, + Data: make([]byte, c.config.MaxPacketMsgPayloadSize), + })) + if err != nil { + panic(err) + } + return len(bz) +} + +type ConnectionStatus struct { + Duration time.Duration + SendMonitor flow.Status + RecvMonitor flow.Status + Channels []ChannelStatus +} + +type ChannelStatus struct { + ID byte + SendQueueCapacity int + SendQueueSize int + Priority int + RecentlySent int64 +} + +func (c *MConnection) Status() ConnectionStatus { + var status ConnectionStatus + status.Duration = time.Since(c.created) + status.SendMonitor = c.sendMonitor.Status() + status.RecvMonitor = c.recvMonitor.Status() + status.Channels = make([]ChannelStatus, len(c.channels)) + for i, channel := range c.channels { + channel := channel + status.Channels[i] = ChannelStatus{ + ID: channel.desc.ID, + SendQueueCapacity: cap(channel.sendQueue), + SendQueueSize: int(atomic.LoadInt32(&channel.sendQueueSize)), + Priority: channel.desc.Priority, + RecentlySent: atomic.LoadInt64(&channel.recentlySent), + } + } + return status +} + +//----------------------------------------------------------------------------- + +type ChannelDescriptor struct { + ID byte + Priority int + SendQueueCapacity int + RecvBufferCapacity int + RecvMessageCapacity int + MessageType proto.Message +} + +func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) { + if chDesc.SendQueueCapacity == 0 { + chDesc.SendQueueCapacity = defaultSendQueueCapacity + } + if chDesc.RecvBufferCapacity == 0 { + chDesc.RecvBufferCapacity = defaultRecvBufferCapacity + } + if chDesc.RecvMessageCapacity == 0 { + chDesc.RecvMessageCapacity = defaultRecvMessageCapacity + } + filled = chDesc + return +} + +// TODO: lowercase. +// NOTE: not goroutine-safe. +type Channel struct { + conn *MConnection + desc ChannelDescriptor + sendQueue chan []byte + sendQueueSize int32 // atomic. + recving []byte + sending []byte + recentlySent int64 // exponential moving average + + maxPacketMsgPayloadSize int + + Logger log.Logger +} + +func newChannel(conn *MConnection, desc ChannelDescriptor) *Channel { + desc = desc.FillDefaults() + if desc.Priority <= 0 { + panic("Channel default priority must be a positive integer") + } + return &Channel{ + conn: conn, + desc: desc, + sendQueue: make(chan []byte, desc.SendQueueCapacity), + recving: make([]byte, 0, desc.RecvBufferCapacity), + maxPacketMsgPayloadSize: conn.config.MaxPacketMsgPayloadSize, + } +} + +func (ch *Channel) SetLogger(l log.Logger) { + ch.Logger = l +} + +// Queues message to send to this channel. +// Goroutine-safe +// Times out (and returns false) after defaultSendTimeout +func (ch *Channel) sendBytes(bytes []byte) bool { + select { + case ch.sendQueue <- bytes: + atomic.AddInt32(&ch.sendQueueSize, 1) + return true + case <-time.After(defaultSendTimeout): + return false + } +} + +// Queues message to send to this channel. +// Nonblocking, returns true if successful. +// Goroutine-safe +func (ch *Channel) trySendBytes(bytes []byte) bool { + select { + case ch.sendQueue <- bytes: + atomic.AddInt32(&ch.sendQueueSize, 1) + return true + default: + return false + } +} + +// Goroutine-safe +func (ch *Channel) loadSendQueueSize() (size int) { + return int(atomic.LoadInt32(&ch.sendQueueSize)) +} + +// Goroutine-safe +// Use only as a heuristic. +func (ch *Channel) canSend() bool { + return ch.loadSendQueueSize() < defaultSendQueueCapacity +} + +// Returns true if any PacketMsgs are pending to be sent. +// Call before calling nextPacketMsg() +// Goroutine-safe +func (ch *Channel) isSendPending() bool { + if len(ch.sending) == 0 { + if len(ch.sendQueue) == 0 { + return false + } + ch.sending = <-ch.sendQueue + } + return true +} + +// Creates a new PacketMsg to send. +// Not goroutine-safe +func (ch *Channel) nextPacketMsg() tmp2p.PacketMsg { + packet := tmp2p.PacketMsg{ChannelID: int32(ch.desc.ID)} + maxSize := ch.maxPacketMsgPayloadSize + if len(ch.sending) <= maxSize { + packet.Data = ch.sending + packet.EOF = true + ch.sending = nil + atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize + } else { + packet.Data = ch.sending[:maxSize] + packet.EOF = false + ch.sending = ch.sending[maxSize:] + } + return packet +} + +// Writes next PacketMsg to w and updates c.recentlySent. +// Not goroutine-safe. +func (ch *Channel) writePacketMsgTo(w protoio.Writer) (n int, err error) { + packet := ch.nextPacketMsg() + n, err = w.WriteMsg(mustWrapPacket(&packet)) + if err != nil { + return 0, err + } + atomic.AddInt64(&ch.recentlySent, int64(n)) + return n, nil +} + +// Handles incoming PacketMsgs. It returns a message bytes if message is +// complete. NOTE message bytes may change on next call to recvPacketMsg. +// Not goroutine-safe +func (ch *Channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) { + ch.Logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet) + recvCap, recvReceived := ch.desc.RecvMessageCapacity, len(ch.recving)+len(packet.Data) + if recvCap < recvReceived { + return nil, fmt.Errorf("received message exceeds available capacity: %v < %v", recvCap, recvReceived) + } + ch.recving = append(ch.recving, packet.Data...) + if packet.EOF { + msgBytes := ch.recving + + // clear the slice without re-allocating. + // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go + // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes, + // at which point the recving slice stops being used and should be garbage collected + ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity) + return msgBytes, nil + } + return nil, nil +} + +// Call this periodically to update stats for throttling purposes. +// Not goroutine-safe +func (ch *Channel) updateStats() { + // Exponential decay of stats. + // TODO: optimize. + atomic.StoreInt64(&ch.recentlySent, int64(float64(atomic.LoadInt64(&ch.recentlySent))*0.8)) +} + +//---------------------------------------- +// Packet + +// mustWrapPacket takes a packet kind (oneof) and wraps it in a tmp2p.Packet message. +func mustWrapPacket(pb proto.Message) *tmp2p.Packet { + var msg tmp2p.Packet + + switch pb := pb.(type) { + case *tmp2p.Packet: // already a packet + msg = *pb + case *tmp2p.PacketPing: + msg = tmp2p.Packet{ + Sum: &tmp2p.Packet_PacketPing{ + PacketPing: pb, + }, + } + case *tmp2p.PacketPong: + msg = tmp2p.Packet{ + Sum: &tmp2p.Packet_PacketPong{ + PacketPong: pb, + }, + } + case *tmp2p.PacketMsg: + msg = tmp2p.Packet{ + Sum: &tmp2p.Packet_PacketMsg{ + PacketMsg: pb, + }, + } + default: + panic(fmt.Errorf("unknown packet type %T", pb)) + } + + return &msg +} diff --git a/p2p/conn/connection_test.go b/p2p/conn/connection_test.go new file mode 100644 index 0000000..f79dd2f --- /dev/null +++ b/p2p/conn/connection_test.go @@ -0,0 +1,633 @@ +package conn + +import ( + "encoding/hex" + "net" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/fortytw2/leaktest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/protoio" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" + "github.com/cometbft/cometbft/proto/tendermint/types" +) + +const maxPingPongPacketSize = 1024 // bytes + +func createTestMConnection(conn net.Conn) *MConnection { + onReceive := func(chID byte, msgBytes []byte) { + } + onError := func(r interface{}) { + } + c := createMConnectionWithCallbacks(conn, onReceive, onError) + c.SetLogger(log.TestingLogger()) + return c +} + +func createMConnectionWithCallbacks( + conn net.Conn, + onReceive func(chID byte, msgBytes []byte), + onError func(r interface{}), +) *MConnection { + cfg := DefaultMConnConfig() + cfg.PingInterval = 90 * time.Millisecond + cfg.PongTimeout = 45 * time.Millisecond + chDescs := []*ChannelDescriptor{{ID: 0x01, Priority: 1, SendQueueCapacity: 1}} + c := NewMConnectionWithConfig(conn, chDescs, onReceive, onError, cfg) + c.SetLogger(log.TestingLogger()) + return c +} + +func TestMConnectionSendFlushStop(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + clientConn := createTestMConnection(client) + err := clientConn.Start() + require.Nil(t, err) + defer clientConn.Stop() //nolint:errcheck // ignore for tests + + msg := []byte("abc") + assert.True(t, clientConn.Send(0x01, msg)) + + msgLength := 14 + + // start the reader in a new routine, so we can flush + errCh := make(chan error) + go func() { + msgB := make([]byte, msgLength) + _, err := server.Read(msgB) + if err != nil { + t.Error(err) + return + } + errCh <- err + }() + + // stop the conn - it should flush all conns + clientConn.FlushStop() + + timer := time.NewTimer(3 * time.Second) + select { + case <-errCh: + case <-timer.C: + t.Error("timed out waiting for msgs to be read") + } +} + +func TestMConnectionSend(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + mconn := createTestMConnection(client) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + msg := []byte("Ant-Man") + assert.True(t, mconn.Send(0x01, msg)) + // Note: subsequent Send/TrySend calls could pass because we are reading from + // the send queue in a separate goroutine. + _, err = server.Read(make([]byte, len(msg))) + if err != nil { + t.Error(err) + } + assert.True(t, mconn.CanSend(0x01)) + + msg = []byte("Spider-Man") + assert.True(t, mconn.TrySend(0x01, msg)) + _, err = server.Read(make([]byte, len(msg))) + if err != nil { + t.Error(err) + } + + assert.False(t, mconn.CanSend(0x05), "CanSend should return false because channel is unknown") + assert.False(t, mconn.Send(0x05, []byte("Absorbing Man")), "Send should return false because channel is unknown") +} + +func TestMConnectionReceive(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn1 := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn1.Start() + require.Nil(t, err) + defer mconn1.Stop() //nolint:errcheck // ignore for tests + + mconn2 := createTestMConnection(server) + err = mconn2.Start() + require.Nil(t, err) + defer mconn2.Stop() //nolint:errcheck // ignore for tests + + msg := []byte("Cyclops") + assert.True(t, mconn2.Send(0x01, msg)) + + select { + case receivedBytes := <-receivedCh: + assert.Equal(t, msg, receivedBytes) + case err := <-errorsCh: + t.Fatalf("Expected %s, got %+v", msg, err) + case <-time.After(500 * time.Millisecond): + t.Fatalf("Did not receive %s message in 500ms", msg) + } +} + +func TestMConnectionStatus(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + mconn := createTestMConnection(client) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + status := mconn.Status() + assert.NotNil(t, status) + assert.Zero(t, status.Channels[0].SendQueueSize) +} + +func TestMConnectionPongTimeoutResultsInError(t *testing.T) { + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + serverGotPing := make(chan struct{}) + go func() { + // read ping + var pkt tmp2p.Packet + _, err := protoio.NewDelimitedReader(server, maxPingPongPacketSize).ReadMsg(&pkt) + require.NoError(t, err) + serverGotPing <- struct{}{} + }() + <-serverGotPing + + pongTimerExpired := mconn.config.PongTimeout + 200*time.Millisecond + select { + case msgBytes := <-receivedCh: + t.Fatalf("Expected error, but got %v", msgBytes) + case err := <-errorsCh: + assert.NotNil(t, err) + case <-time.After(pongTimerExpired): + t.Fatalf("Expected to receive error after %v", pongTimerExpired) + } +} + +func TestMConnectionMultiplePongsInTheBeginning(t *testing.T) { + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + // sending 3 pongs in a row (abuse) + protoWriter := protoio.NewDelimitedWriter(server) + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + + serverGotPing := make(chan struct{}) + go func() { + // read ping (one byte) + var packet tmp2p.Packet + _, err := protoio.NewDelimitedReader(server, maxPingPongPacketSize).ReadMsg(&packet) + require.NoError(t, err) + serverGotPing <- struct{}{} + + // respond with pong + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + }() + <-serverGotPing + + pongTimerExpired := mconn.config.PongTimeout + 20*time.Millisecond + select { + case msgBytes := <-receivedCh: + t.Fatalf("Expected no data, but got %v", msgBytes) + case err := <-errorsCh: + t.Fatalf("Expected no error, but got %v", err) + case <-time.After(pongTimerExpired): + assert.True(t, mconn.IsRunning()) + } +} + +func TestMConnectionMultiplePings(t *testing.T) { + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + // sending 3 pings in a row (abuse) + // see https://github.com/tendermint/tendermint/issues/1190 + protoReader := protoio.NewDelimitedReader(server, maxPingPongPacketSize) + protoWriter := protoio.NewDelimitedWriter(server) + var pkt tmp2p.Packet + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{})) + require.NoError(t, err) + + _, err = protoReader.ReadMsg(&pkt) + require.NoError(t, err) + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{})) + require.NoError(t, err) + + _, err = protoReader.ReadMsg(&pkt) + require.NoError(t, err) + + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{})) + require.NoError(t, err) + + _, err = protoReader.ReadMsg(&pkt) + require.NoError(t, err) + + assert.True(t, mconn.IsRunning()) +} + +func TestMConnectionPingPongs(t *testing.T) { + // check that we are not leaking any go-routines + defer leaktest.CheckTimeout(t, 10*time.Second)() + + server, client := net.Pipe() + + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + serverGotPing := make(chan struct{}) + go func() { + protoReader := protoio.NewDelimitedReader(server, maxPingPongPacketSize) + protoWriter := protoio.NewDelimitedWriter(server) + var pkt tmp2p.PacketPing + + // read ping + _, err = protoReader.ReadMsg(&pkt) + require.NoError(t, err) + serverGotPing <- struct{}{} + + // respond with pong + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + + time.Sleep(mconn.config.PingInterval) + + // read ping + _, err = protoReader.ReadMsg(&pkt) + require.NoError(t, err) + serverGotPing <- struct{}{} + + // respond with pong + _, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{})) + require.NoError(t, err) + }() + <-serverGotPing + <-serverGotPing + + pongTimerExpired := (mconn.config.PongTimeout + 20*time.Millisecond) * 2 + select { + case msgBytes := <-receivedCh: + t.Fatalf("Expected no data, but got %v", msgBytes) + case err := <-errorsCh: + t.Fatalf("Expected no error, but got %v", err) + case <-time.After(2 * pongTimerExpired): + assert.True(t, mconn.IsRunning()) + } +} + +func TestMConnectionStopsAndReturnsError(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + if err := client.Close(); err != nil { + t.Error(err) + } + + select { + case receivedBytes := <-receivedCh: + t.Fatalf("Expected error, got %v", receivedBytes) + case err := <-errorsCh: + assert.NotNil(t, err) + assert.False(t, mconn.IsRunning()) + case <-time.After(500 * time.Millisecond): + t.Fatal("Did not receive error in 500ms") + } +} + +func newClientAndServerConnsForReadErrors(t *testing.T, chOnErr chan struct{}) (*MConnection, *MConnection) { + server, client := NetPipe() + + onReceive := func(chID byte, msgBytes []byte) {} + onError := func(r interface{}) {} + + // create client conn with two channels + chDescs := []*ChannelDescriptor{ + {ID: 0x01, Priority: 1, SendQueueCapacity: 1}, + {ID: 0x02, Priority: 1, SendQueueCapacity: 1}, + } + mconnClient := NewMConnection(client, chDescs, onReceive, onError) + mconnClient.SetLogger(log.TestingLogger().With("module", "client")) + err := mconnClient.Start() + require.Nil(t, err) + + // create server conn with 1 channel + // it fires on chOnErr when there's an error + serverLogger := log.TestingLogger().With("module", "server") + onError = func(r interface{}) { + chOnErr <- struct{}{} + } + mconnServer := createMConnectionWithCallbacks(server, onReceive, onError) + mconnServer.SetLogger(serverLogger) + err = mconnServer.Start() + require.Nil(t, err) + return mconnClient, mconnServer +} + +func expectSend(ch chan struct{}) bool { + after := time.After(time.Second * 5) + select { + case <-ch: + return true + case <-after: + return false + } +} + +func TestMConnectionReadErrorBadEncoding(t *testing.T) { + chOnErr := make(chan struct{}) + mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) + + client := mconnClient.conn + + // Write it. + _, err := client.Write([]byte{1, 2, 3, 4, 5}) + require.NoError(t, err) + assert.True(t, expectSend(chOnErr), "badly encoded msgPacket") + + t.Cleanup(func() { + if err := mconnClient.Stop(); err != nil { + t.Log(err) + } + }) + + t.Cleanup(func() { + if err := mconnServer.Stop(); err != nil { + t.Log(err) + } + }) +} + +func TestMConnectionReadErrorUnknownChannel(t *testing.T) { + chOnErr := make(chan struct{}) + mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) + + msg := []byte("Ant-Man") + + // fail to send msg on channel unknown by client + assert.False(t, mconnClient.Send(0x03, msg)) + + // send msg on channel unknown by the server. + // should cause an error + assert.True(t, mconnClient.Send(0x02, msg)) + assert.True(t, expectSend(chOnErr), "unknown channel") + + t.Cleanup(func() { + if err := mconnClient.Stop(); err != nil { + t.Log(err) + } + }) + + t.Cleanup(func() { + if err := mconnServer.Stop(); err != nil { + t.Log(err) + } + }) +} + +func TestMConnectionReadErrorLongMessage(t *testing.T) { + chOnErr := make(chan struct{}) + chOnRcv := make(chan struct{}) + + mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) + defer mconnClient.Stop() //nolint:errcheck // ignore for tests + defer mconnServer.Stop() //nolint:errcheck // ignore for tests + + mconnServer.onReceive = func(chID byte, msgBytes []byte) { + chOnRcv <- struct{}{} + } + + client := mconnClient.conn + protoWriter := protoio.NewDelimitedWriter(client) + + // send msg thats just right + var packet = tmp2p.PacketMsg{ + ChannelID: 0x01, + EOF: true, + Data: make([]byte, mconnClient.config.MaxPacketMsgPayloadSize), + } + + _, err := protoWriter.WriteMsg(mustWrapPacket(&packet)) + require.NoError(t, err) + assert.True(t, expectSend(chOnRcv), "msg just right") + + // send msg thats too long + packet = tmp2p.PacketMsg{ + ChannelID: 0x01, + EOF: true, + Data: make([]byte, mconnClient.config.MaxPacketMsgPayloadSize+100), + } + + _, err = protoWriter.WriteMsg(mustWrapPacket(&packet)) + require.Error(t, err) + assert.True(t, expectSend(chOnErr), "msg too long") +} + +func TestMConnectionReadErrorUnknownMsgType(t *testing.T) { + chOnErr := make(chan struct{}) + mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) + defer mconnClient.Stop() //nolint:errcheck // ignore for tests + defer mconnServer.Stop() //nolint:errcheck // ignore for tests + + // send msg with unknown msg type + _, err := protoio.NewDelimitedWriter(mconnClient.conn).WriteMsg(&types.Header{ChainID: "x"}) + require.NoError(t, err) + assert.True(t, expectSend(chOnErr), "unknown msg type") +} + +func TestMConnectionTrySend(t *testing.T) { + server, client := NetPipe() + defer server.Close() + defer client.Close() + + mconn := createTestMConnection(client) + err := mconn.Start() + require.Nil(t, err) + defer mconn.Stop() //nolint:errcheck // ignore for tests + + msg := []byte("Semicolon-Woman") + resultCh := make(chan string, 2) + assert.True(t, mconn.TrySend(0x01, msg)) + _, err = server.Read(make([]byte, len(msg))) + require.NoError(t, err) + assert.True(t, mconn.CanSend(0x01)) + assert.True(t, mconn.TrySend(0x01, msg)) + assert.False(t, mconn.CanSend(0x01)) + go func() { + mconn.TrySend(0x01, msg) + resultCh <- "TrySend" + }() + assert.False(t, mconn.CanSend(0x01)) + assert.False(t, mconn.TrySend(0x01, msg)) + assert.Equal(t, "TrySend", <-resultCh) +} + +//nolint:lll //ignore line length for tests +func TestConnVectors(t *testing.T) { + + testCases := []struct { + testName string + msg proto.Message + expBytes string + }{ + {"PacketPing", &tmp2p.PacketPing{}, "0a00"}, + {"PacketPong", &tmp2p.PacketPong{}, "1200"}, + {"PacketMsg", &tmp2p.PacketMsg{ChannelID: 1, EOF: false, Data: []byte("data transmitted over the wire")}, "1a2208011a1e64617461207472616e736d6974746564206f766572207468652077697265"}, + } + + for _, tc := range testCases { + tc := tc + + pm := mustWrapPacket(tc.msg) + bz, err := pm.Marshal() + require.NoError(t, err, tc.testName) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + } +} + +func TestMConnectionChannelOverflow(t *testing.T) { + chOnErr := make(chan struct{}) + chOnRcv := make(chan struct{}) + + mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) + t.Cleanup(stopAll(t, mconnClient, mconnServer)) + + mconnServer.onReceive = func(chID byte, msgBytes []byte) { + chOnRcv <- struct{}{} + } + + client := mconnClient.conn + protoWriter := protoio.NewDelimitedWriter(client) + + var packet = tmp2p.PacketMsg{ + ChannelID: 0x01, + EOF: true, + Data: []byte(`42`), + } + _, err := protoWriter.WriteMsg(mustWrapPacket(&packet)) + require.NoError(t, err) + assert.True(t, expectSend(chOnRcv)) + + packet.ChannelID = int32(1025) + _, err = protoWriter.WriteMsg(mustWrapPacket(&packet)) + require.NoError(t, err) + assert.False(t, expectSend(chOnRcv)) + +} + +type stopper interface { + Stop() error +} + +func stopAll(t *testing.T, stoppers ...stopper) func() { + return func() { + for _, s := range stoppers { + if err := s.Stop(); err != nil { + t.Log(err) + } + } + } +} diff --git a/p2p/conn/evil_secret_connection_test.go b/p2p/conn/evil_secret_connection_test.go new file mode 100644 index 0000000..8ebfb44 --- /dev/null +++ b/p2p/conn/evil_secret_connection_test.go @@ -0,0 +1,275 @@ +package conn + +import ( + "bytes" + "errors" + "io" + "testing" + + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/oasisprotocol/curve25519-voi/primitives/merlin" + "github.com/stretchr/testify/assert" + "golang.org/x/crypto/chacha20poly1305" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/libs/protoio" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +type buffer struct { + next bytes.Buffer +} + +func (b *buffer) Read(data []byte) (n int, err error) { + return b.next.Read(data) +} + +func (b *buffer) Write(data []byte) (n int, err error) { + return b.next.Write(data) +} + +func (b *buffer) Bytes() []byte { + return b.next.Bytes() +} + +func (b *buffer) Close() error { + return nil +} + +type evilConn struct { + secretConn *SecretConnection + buffer *buffer + + locEphPub *[32]byte + locEphPriv *[32]byte + remEphPub *[32]byte + privKey crypto.PrivKey + + readStep int + writeStep int + readOffset int + + shareEphKey bool + badEphKey bool + shareAuthSignature bool + badAuthSignature bool +} + +func newEvilConn(shareEphKey, badEphKey, shareAuthSignature, badAuthSignature bool) *evilConn { + privKey := ed25519.GenPrivKey() + locEphPub, locEphPriv := genEphKeys() + var rep [32]byte + c := &evilConn{ + locEphPub: locEphPub, + locEphPriv: locEphPriv, + remEphPub: &rep, + privKey: privKey, + + shareEphKey: shareEphKey, + badEphKey: badEphKey, + shareAuthSignature: shareAuthSignature, + badAuthSignature: badAuthSignature, + } + + return c +} + +func (c *evilConn) Read(data []byte) (n int, err error) { + if !c.shareEphKey { + return 0, io.EOF + } + + switch c.readStep { + case 0: + if !c.badEphKey { + lc := *c.locEphPub + bz, err := protoio.MarshalDelimited(&gogotypes.BytesValue{Value: lc[:]}) + if err != nil { + panic(err) + } + copy(data, bz[c.readOffset:]) + n = len(data) + } else { + bz, err := protoio.MarshalDelimited(&gogotypes.BytesValue{Value: []byte("drop users;")}) + if err != nil { + panic(err) + } + copy(data, bz) + n = len(data) + } + c.readOffset += n + + if n >= 32 { + c.readOffset = 0 + c.readStep = 1 + if !c.shareAuthSignature { + c.readStep = 2 + } + } + + return n, nil + case 1: + signature := c.signChallenge() + if !c.badAuthSignature { + pkpb, err := cryptoenc.PubKeyToProto(c.privKey.PubKey()) + if err != nil { + panic(err) + } + bz, err := protoio.MarshalDelimited(&tmp2p.AuthSigMessage{PubKey: pkpb, Sig: signature}) + if err != nil { + panic(err) + } + n, err = c.secretConn.Write(bz) + if err != nil { + panic(err) + } + if c.readOffset > len(c.buffer.Bytes()) { + return len(data), nil + } + copy(data, c.buffer.Bytes()[c.readOffset:]) + } else { + bz, err := protoio.MarshalDelimited(&gogotypes.BytesValue{Value: []byte("select * from users;")}) + if err != nil { + panic(err) + } + n, err = c.secretConn.Write(bz) + if err != nil { + panic(err) + } + if c.readOffset > len(c.buffer.Bytes()) { + return len(data), nil + } + copy(data, c.buffer.Bytes()) + } + c.readOffset += len(data) + return n, nil + default: + return 0, io.EOF + } +} + +func (c *evilConn) Write(data []byte) (n int, err error) { + switch c.writeStep { + case 0: + var ( + bytes gogotypes.BytesValue + remEphPub [32]byte + ) + err := protoio.UnmarshalDelimited(data, &bytes) + if err != nil { + panic(err) + } + copy(remEphPub[:], bytes.Value) + c.remEphPub = &remEphPub + c.writeStep = 1 + if !c.shareAuthSignature { + c.writeStep = 2 + } + return len(data), nil + case 1: + // Signature is not needed, therefore skipped. + return len(data), nil + default: + return 0, io.EOF + } +} + +func (c *evilConn) Close() error { + return nil +} + +func (c *evilConn) signChallenge() []byte { + // Sort by lexical order. + loEphPub, hiEphPub := sort32(c.locEphPub, c.remEphPub) + + transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH") + + transcript.AppendMessage(labelEphemeralLowerPublicKey, loEphPub[:]) + transcript.AppendMessage(labelEphemeralUpperPublicKey, hiEphPub[:]) + + // Check if the local ephemeral public key was the least, lexicographically + // sorted. + locIsLeast := bytes.Equal(c.locEphPub[:], loEphPub[:]) + + // Compute common diffie hellman secret using X25519. + dhSecret, err := computeDHSecret(c.remEphPub, c.locEphPriv) + if err != nil { + panic(err) + } + + transcript.AppendMessage(labelDHSecret, dhSecret[:]) + + // Generate the secret used for receiving, sending, challenge via HKDF-SHA2 + // on the transcript state (which itself also uses HKDF-SHA2 to derive a key + // from the dhSecret). + recvSecret, sendSecret := deriveSecrets(dhSecret, locIsLeast) + + const challengeSize = 32 + var challenge [challengeSize]byte + transcript.ExtractBytes(challenge[:], labelSecretConnectionMac) + + sendAead, err := chacha20poly1305.New(sendSecret[:]) + if err != nil { + panic(errors.New("invalid send SecretConnection Key")) + } + recvAead, err := chacha20poly1305.New(recvSecret[:]) + if err != nil { + panic(errors.New("invalid receive SecretConnection Key")) + } + + b := &buffer{} + c.secretConn = &SecretConnection{ + conn: b, + recvBuffer: nil, + recvNonce: new([aeadNonceSize]byte), + sendNonce: new([aeadNonceSize]byte), + recvAead: recvAead, + sendAead: sendAead, + recvFrame: make([]byte, totalFrameSize), + recvSealedFrame: make([]byte, totalFrameSize+aeadSizeOverhead), + sendFrame: make([]byte, totalFrameSize), + sendSealedFrame: make([]byte, totalFrameSize+aeadSizeOverhead), + } + c.buffer = b + + // Sign the challenge bytes for authentication. + locSignature, err := signChallenge(&challenge, c.privKey) + if err != nil { + panic(err) + } + + return locSignature +} + +// TestMakeSecretConnection creates an evil connection and tests that +// MakeSecretConnection errors at different stages. +func TestMakeSecretConnection(t *testing.T) { + testCases := []struct { + name string + conn *evilConn + errMsg string + }{ + {"refuse to share ethimeral key", newEvilConn(false, false, false, false), "EOF"}, + {"share bad ethimeral key", newEvilConn(true, true, false, false), "wrong wireType"}, + {"refuse to share auth signature", newEvilConn(true, false, false, false), "EOF"}, + {"share bad auth signature", newEvilConn(true, false, true, true), "failed to decrypt SecretConnection"}, + {"all good", newEvilConn(true, false, true, false), ""}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + privKey := ed25519.GenPrivKey() + _, err := MakeSecretConnection(tc.conn, privKey) + if tc.errMsg != "" { + if assert.Error(t, err) { + assert.Contains(t, err.Error(), tc.errMsg) + } + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/p2p/conn/secret_connection.go b/p2p/conn/secret_connection.go new file mode 100644 index 0000000..ec6d1a6 --- /dev/null +++ b/p2p/conn/secret_connection.go @@ -0,0 +1,462 @@ +package conn + +import ( + "bytes" + "crypto/cipher" + crand "crypto/rand" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "net" + "time" + + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/oasisprotocol/curve25519-voi/primitives/merlin" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/hkdf" + "golang.org/x/crypto/nacl/box" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/libs/async" + "github.com/cometbft/cometbft/libs/protoio" + cmtsync "github.com/cometbft/cometbft/libs/sync" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +// 4 + 1024 == 1028 total frame size +const ( + dataLenSize = 4 + dataMaxSize = 1024 + totalFrameSize = dataMaxSize + dataLenSize + aeadSizeOverhead = 16 // overhead of poly 1305 authentication tag + aeadKeySize = chacha20poly1305.KeySize + aeadNonceSize = chacha20poly1305.NonceSize + + labelEphemeralLowerPublicKey = "EPHEMERAL_LOWER_PUBLIC_KEY" + labelEphemeralUpperPublicKey = "EPHEMERAL_UPPER_PUBLIC_KEY" + labelDHSecret = "DH_SECRET" + labelSecretConnectionMac = "SECRET_CONNECTION_MAC" +) + +var ( + ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer") + + secretConnKeyAndChallengeGen = []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN") +) + +// SecretConnection implements net.Conn. +// It is an implementation of the STS protocol. +// See https://github.com/cometbft/cometbft/blob/0.1/docs/sts-final.pdf for +// details on the protocol. +// +// Consumers of the SecretConnection are responsible for authenticating +// the remote peer's pubkey against known information, like a nodeID. +// Otherwise they are vulnerable to MITM. +// (TODO(ismail): see also https://github.com/tendermint/tendermint/issues/3010) +type SecretConnection struct { + + // immutable + recvAead cipher.AEAD + sendAead cipher.AEAD + + remPubKey crypto.PubKey + conn io.ReadWriteCloser + + // net.Conn must be thread safe: + // https://golang.org/pkg/net/#Conn. + // Since we have internal mutable state, + // we need mtxs. But recv and send states + // are independent, so we can use two mtxs. + // All .Read are covered by recvMtx, + // all .Write are covered by sendMtx. + recvMtx cmtsync.Mutex + recvBuffer []byte + recvNonce *[aeadNonceSize]byte + recvFrame []byte + recvSealedFrame []byte + + sendMtx cmtsync.Mutex + sendNonce *[aeadNonceSize]byte + sendFrame []byte + sendSealedFrame []byte +} + +// MakeSecretConnection performs handshake and returns a new authenticated +// SecretConnection. +// Returns nil if there is an error in handshake. +// Caller should call conn.Close() +// See docs/sts-final.pdf for more information. +func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) { + var ( + locPubKey = locPrivKey.PubKey() + ) + + // Generate ephemeral keys for perfect forward secrecy. + locEphPub, locEphPriv := genEphKeys() + + // Write local ephemeral pubkey and receive one too. + // NOTE: every 32-byte string is accepted as a Curve25519 public key (see + // DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf) + remEphPub, err := shareEphPubKey(conn, locEphPub) + if err != nil { + return nil, err + } + + // Sort by lexical order. + loEphPub, hiEphPub := sort32(locEphPub, remEphPub) + + transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH") + + transcript.AppendMessage(labelEphemeralLowerPublicKey, loEphPub[:]) + transcript.AppendMessage(labelEphemeralUpperPublicKey, hiEphPub[:]) + + // Check if the local ephemeral public key was the least, lexicographically + // sorted. + locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:]) + + // Compute common diffie hellman secret using X25519. + dhSecret, err := computeDHSecret(remEphPub, locEphPriv) + if err != nil { + return nil, err + } + + transcript.AppendMessage(labelDHSecret, dhSecret[:]) + + // Generate the secret used for receiving, sending, challenge via HKDF-SHA2 + // on the transcript state (which itself also uses HKDF-SHA2 to derive a key + // from the dhSecret). + recvSecret, sendSecret := deriveSecrets(dhSecret, locIsLeast) + + const challengeSize = 32 + var challenge [challengeSize]byte + transcript.ExtractBytes(challenge[:], labelSecretConnectionMac) + + sendAead, err := chacha20poly1305.New(sendSecret[:]) + if err != nil { + return nil, errors.New("invalid send SecretConnection Key") + } + recvAead, err := chacha20poly1305.New(recvSecret[:]) + if err != nil { + return nil, errors.New("invalid receive SecretConnection Key") + } + + sc := &SecretConnection{ + conn: conn, + recvBuffer: nil, + recvNonce: new([aeadNonceSize]byte), + sendNonce: new([aeadNonceSize]byte), + recvAead: recvAead, + sendAead: sendAead, + recvFrame: make([]byte, totalFrameSize), + recvSealedFrame: make([]byte, aeadSizeOverhead+totalFrameSize), + sendFrame: make([]byte, totalFrameSize), + sendSealedFrame: make([]byte, aeadSizeOverhead+totalFrameSize), + } + + // Sign the challenge bytes for authentication. + locSignature, err := signChallenge(&challenge, locPrivKey) + if err != nil { + return nil, err + } + + // Share (in secret) each other's pubkey & challenge signature + authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature) + if err != nil { + return nil, err + } + + remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig + if _, ok := remPubKey.(ed25519.PubKey); !ok { + return nil, fmt.Errorf("expected ed25519 pubkey, got %T", remPubKey) + } + if !remPubKey.VerifySignature(challenge[:], remSignature) { + return nil, errors.New("challenge verification failed") + } + + // We've authorized. + sc.remPubKey = remPubKey + return sc, nil +} + +// RemotePubKey returns authenticated remote pubkey +func (sc *SecretConnection) RemotePubKey() crypto.PubKey { + return sc.remPubKey +} + +// Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`. +// CONTRACT: data smaller than dataMaxSize is written atomically. +func (sc *SecretConnection) Write(data []byte) (n int, err error) { + sc.sendMtx.Lock() + defer sc.sendMtx.Unlock() + sealedFrame, frame := sc.sendSealedFrame, sc.sendFrame + + for 0 < len(data) { + if err := func() error { + var chunk []byte + if dataMaxSize < len(data) { + chunk = data[:dataMaxSize] + data = data[dataMaxSize:] + } else { + chunk = data + data = nil + } + chunkLength := len(chunk) + binary.LittleEndian.PutUint32(frame, uint32(chunkLength)) + copy(frame[dataLenSize:], chunk) + + // encrypt the frame + sc.sendAead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil) + incrNonce(sc.sendNonce) + // end encryption + + _, err = sc.conn.Write(sealedFrame) + if err != nil { + return err + } + n += len(chunk) + return nil + }(); err != nil { + return n, err + } + } + return n, err +} + +// CONTRACT: data smaller than dataMaxSize is read atomically. +func (sc *SecretConnection) Read(data []byte) (n int, err error) { + sc.recvMtx.Lock() + defer sc.recvMtx.Unlock() + + // read off and update the recvBuffer, if non-empty + if 0 < len(sc.recvBuffer) { + n = copy(data, sc.recvBuffer) + sc.recvBuffer = sc.recvBuffer[n:] + return n, err + } + + // read off the conn + sealedFrame := sc.recvSealedFrame + _, err = io.ReadFull(sc.conn, sealedFrame) + if err != nil { + return n, err + } + + // decrypt the frame. + // reads and updates the sc.recvNonce + frame := sc.recvFrame + _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil) + if err != nil { + return n, fmt.Errorf("failed to decrypt SecretConnection: %w", err) + } + incrNonce(sc.recvNonce) + // end decryption + + // copy checkLength worth into data, + // set recvBuffer to the rest. + var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes + if chunkLength > dataMaxSize { + return 0, errors.New("chunkLength is greater than dataMaxSize") + } + var chunk = frame[dataLenSize : dataLenSize+chunkLength] + n = copy(data, chunk) + if n < len(chunk) { + sc.recvBuffer = make([]byte, len(chunk)-n) + copy(sc.recvBuffer, chunk[n:]) + } + return n, err +} + +// Implements net.Conn +func (sc *SecretConnection) Close() error { return sc.conn.Close() } +func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() } +func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } +func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) } +func (sc *SecretConnection) SetReadDeadline(t time.Time) error { + return sc.conn.(net.Conn).SetReadDeadline(t) +} +func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { + return sc.conn.(net.Conn).SetWriteDeadline(t) +} + +func genEphKeys() (ephPub, ephPriv *[32]byte) { + var err error + // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek), + // we do not "clamp" the private key scalar: + // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74 + ephPub, ephPriv, err = box.GenerateKey(crand.Reader) + if err != nil { + panic("Could not generate ephemeral key-pair") + } + return +} + +func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { + + // Send our pubkey and receive theirs in tandem. + var trs, _ = async.Parallel( + func(_ int) (val interface{}, abort bool, err error) { + lc := *locEphPub + _, err = protoio.NewDelimitedWriter(conn).WriteMsg(&gogotypes.BytesValue{Value: lc[:]}) + if err != nil { + return nil, true, err // abort + } + return nil, false, nil + }, + func(_ int) (val interface{}, abort bool, err error) { + var bytes gogotypes.BytesValue + _, err = protoio.NewDelimitedReader(conn, 1024*1024).ReadMsg(&bytes) + if err != nil { + return nil, true, err // abort + } + + var _remEphPub [32]byte + copy(_remEphPub[:], bytes.Value) + return _remEphPub, false, nil + }, + ) + + // If error: + if trs.FirstError() != nil { + err = trs.FirstError() + return remEphPub, err + } + + // Otherwise: + var _remEphPub = trs.FirstValue().([32]byte) + return &_remEphPub, nil +} + +func deriveSecrets( + dhSecret *[32]byte, + locIsLeast bool, +) (recvSecret, sendSecret *[aeadKeySize]byte) { + hash := sha256.New + hkdf := hkdf.New(hash, dhSecret[:], nil, secretConnKeyAndChallengeGen) + // get enough data for 2 aead keys, and a 32 byte challenge + res := new([2*aeadKeySize + 32]byte) + _, err := io.ReadFull(hkdf, res[:]) + if err != nil { + panic(err) + } + + recvSecret = new([aeadKeySize]byte) + sendSecret = new([aeadKeySize]byte) + + // bytes 0 through aeadKeySize - 1 are one aead key. + // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key. + // which key corresponds to sending and receiving key depends on whether + // the local key is less than the remote key. + if locIsLeast { + copy(recvSecret[:], res[0:aeadKeySize]) + copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2]) + } else { + copy(sendSecret[:], res[0:aeadKeySize]) + copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2]) + } + + return +} + +// computeDHSecret computes a Diffie-Hellman shared secret key +// from our own local private key and the other's public key. +func computeDHSecret(remPubKey, locPrivKey *[32]byte) (*[32]byte, error) { + shrKey, err := curve25519.X25519(locPrivKey[:], remPubKey[:]) + if err != nil { + return nil, err + } + var shrKeyArray [32]byte + copy(shrKeyArray[:], shrKey) + return &shrKeyArray, nil +} + +func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) { + if bytes.Compare(foo[:], bar[:]) < 0 { + lo = foo + hi = bar + } else { + lo = bar + hi = foo + } + return +} + +func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) ([]byte, error) { + signature, err := locPrivKey.Sign(challenge[:]) + if err != nil { + return nil, err + } + return signature, nil +} + +type authSigMessage struct { + Key crypto.PubKey + Sig []byte +} + +func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) { + + // Send our info and receive theirs in tandem. + var trs, _ = async.Parallel( + func(_ int) (val interface{}, abort bool, err error) { + pbpk, err := cryptoenc.PubKeyToProto(pubKey) + if err != nil { + return nil, true, err + } + _, err = protoio.NewDelimitedWriter(sc).WriteMsg(&tmp2p.AuthSigMessage{PubKey: pbpk, Sig: signature}) + if err != nil { + return nil, true, err // abort + } + return nil, false, nil + }, + func(_ int) (val interface{}, abort bool, err error) { + var pba tmp2p.AuthSigMessage + _, err = protoio.NewDelimitedReader(sc, 1024*1024).ReadMsg(&pba) + if err != nil { + return nil, true, err // abort + } + + pk, err := cryptoenc.PubKeyFromProto(pba.PubKey) + if err != nil { + return nil, true, err // abort + } + + _recvMsg := authSigMessage{ + Key: pk, + Sig: pba.Sig, + } + return _recvMsg, false, nil + }, + ) + + // If error: + if trs.FirstError() != nil { + err = trs.FirstError() + return recvMsg, err + } + + var _recvMsg = trs.FirstValue().(authSigMessage) + return _recvMsg, nil +} + +//-------------------------------------------------------------------------------- + +// Increment nonce little-endian by 1 with wraparound. +// Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four +// bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes +// (little-endian in nonce[4:]). +func incrNonce(nonce *[aeadNonceSize]byte) { + counter := binary.LittleEndian.Uint64(nonce[4:]) + if counter == math.MaxUint64 { + // Terminates the session and makes sure the nonce would not re-used. + // See https://github.com/tendermint/tendermint/issues/3531 + panic("can't increase nonce without overflow") + } + counter++ + binary.LittleEndian.PutUint64(nonce[4:], counter) +} diff --git a/p2p/conn/secret_connection_test.go b/p2p/conn/secret_connection_test.go new file mode 100644 index 0000000..b180391 --- /dev/null +++ b/p2p/conn/secret_connection_test.go @@ -0,0 +1,474 @@ +package conn + +import ( + "bufio" + "encoding/hex" + "flag" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/sr25519" + "github.com/cometbft/cometbft/libs/async" + cmtos "github.com/cometbft/cometbft/libs/os" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +// Run go test -update from within this module +// to update the golden test vector file +var update = flag.Bool("update", false, "update .golden files") + +type kvstoreConn struct { + *io.PipeReader + *io.PipeWriter +} + +func (drw kvstoreConn) Close() (err error) { + err2 := drw.PipeWriter.CloseWithError(io.EOF) + err1 := drw.PipeReader.Close() + if err2 != nil { + return err + } + return err1 +} + +type privKeyWithNilPubKey struct { + orig crypto.PrivKey +} + +func (pk privKeyWithNilPubKey) Bytes() []byte { return pk.orig.Bytes() } +func (pk privKeyWithNilPubKey) Sign(msg []byte) ([]byte, error) { return pk.orig.Sign(msg) } +func (pk privKeyWithNilPubKey) PubKey() crypto.PubKey { return nil } +func (pk privKeyWithNilPubKey) Equals(pk2 crypto.PrivKey) bool { return pk.orig.Equals(pk2) } +func (pk privKeyWithNilPubKey) Type() string { return "privKeyWithNilPubKey" } + +func TestSecretConnectionHandshake(t *testing.T) { + fooSecConn, barSecConn := makeSecretConnPair(t) + if err := fooSecConn.Close(); err != nil { + t.Error(err) + } + if err := barSecConn.Close(); err != nil { + t.Error(err) + } +} + +func TestConcurrentWrite(t *testing.T) { + fooSecConn, barSecConn := makeSecretConnPair(t) + fooWriteText := cmtrand.Str(dataMaxSize) + + // write from two routines. + // should be safe from race according to net.Conn: + // https://golang.org/pkg/net/#Conn + n := 100 + wg := new(sync.WaitGroup) + wg.Add(3) + go writeLots(t, wg, fooSecConn, fooWriteText, n) + go writeLots(t, wg, fooSecConn, fooWriteText, n) + + // Consume reads from bar's reader + readLots(t, wg, barSecConn, n*2) + wg.Wait() + + if err := fooSecConn.Close(); err != nil { + t.Error(err) + } +} + +func TestConcurrentRead(t *testing.T) { + fooSecConn, barSecConn := makeSecretConnPair(t) + fooWriteText := cmtrand.Str(dataMaxSize) + n := 100 + + // read from two routines. + // should be safe from race according to net.Conn: + // https://golang.org/pkg/net/#Conn + wg := new(sync.WaitGroup) + wg.Add(3) + go readLots(t, wg, fooSecConn, n/2) + go readLots(t, wg, fooSecConn, n/2) + + // write to bar + writeLots(t, wg, barSecConn, fooWriteText, n) + wg.Wait() + + if err := fooSecConn.Close(); err != nil { + t.Error(err) + } +} + +func TestSecretConnectionReadWrite(t *testing.T) { + fooConn, barConn := makeKVStoreConnPair() + fooWrites, barWrites := []string{}, []string{} + fooReads, barReads := []string{}, []string{} + + // Pre-generate the things to write (for foo & bar) + for i := 0; i < 100; i++ { + fooWrites = append(fooWrites, cmtrand.Str((cmtrand.Int()%(dataMaxSize*5))+1)) + barWrites = append(barWrites, cmtrand.Str((cmtrand.Int()%(dataMaxSize*5))+1)) + } + + // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa + genNodeRunner := func(id string, nodeConn kvstoreConn, nodeWrites []string, nodeReads *[]string) async.Task { + return func(_ int) (interface{}, bool, error) { + // Initiate cryptographic private key and secret connection trhough nodeConn. + nodePrvKey := ed25519.GenPrivKey() + nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey) + if err != nil { + t.Errorf("failed to establish SecretConnection for node: %v", err) + return nil, true, err + } + // In parallel, handle some reads and writes. + trs, ok := async.Parallel( + func(_ int) (interface{}, bool, error) { + // Node writes: + for _, nodeWrite := range nodeWrites { + n, err := nodeSecretConn.Write([]byte(nodeWrite)) + if err != nil { + t.Errorf("failed to write to nodeSecretConn: %v", err) + return nil, true, err + } + if n != len(nodeWrite) { + err = fmt.Errorf("failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n) + t.Error(err) + return nil, true, err + } + } + if err := nodeConn.PipeWriter.Close(); err != nil { + t.Error(err) + return nil, true, err + } + return nil, false, nil + }, + func(_ int) (interface{}, bool, error) { + // Node reads: + readBuffer := make([]byte, dataMaxSize) + for { + n, err := nodeSecretConn.Read(readBuffer) + if err == io.EOF { + if err := nodeConn.PipeReader.Close(); err != nil { + t.Error(err) + return nil, true, err + } + return nil, false, nil + } else if err != nil { + t.Errorf("failed to read from nodeSecretConn: %v", err) + return nil, true, err + } + *nodeReads = append(*nodeReads, string(readBuffer[:n])) + } + }, + ) + assert.True(t, ok, "Unexpected task abortion") + + // If error: + if trs.FirstError() != nil { + return nil, true, trs.FirstError() + } + + // Otherwise: + return nil, false, nil + } + } + + // Run foo & bar in parallel + trs, ok := async.Parallel( + genNodeRunner("foo", fooConn, fooWrites, &fooReads), + genNodeRunner("bar", barConn, barWrites, &barReads), + ) + require.Nil(t, trs.FirstError()) + require.True(t, ok, "unexpected task abortion") + + // A helper to ensure that the writes and reads match. + // Additionally, small writes (<= dataMaxSize) must be atomically read. + compareWritesReads := func(writes []string, reads []string) { + for { + // Pop next write & corresponding reads + read := "" + write := writes[0] + readCount := 0 + for _, readChunk := range reads { + read += readChunk + readCount++ + if len(write) <= len(read) { + break + } + if len(write) <= dataMaxSize { + break // atomicity of small writes + } + } + // Compare + if write != read { + t.Errorf("expected to read %X, got %X", write, read) + } + // Iterate + writes = writes[1:] + reads = reads[readCount:] + if len(writes) == 0 { + break + } + } + } + + compareWritesReads(fooWrites, barReads) + compareWritesReads(barWrites, fooReads) +} + +func TestDeriveSecretsAndChallengeGolden(t *testing.T) { + goldenFilepath := filepath.Join("testdata", t.Name()+".golden") + if *update { + t.Logf("Updating golden test vector file %s", goldenFilepath) + data := createGoldenTestVectors(t) + err := cmtos.WriteFile(goldenFilepath, []byte(data), 0o644) + require.NoError(t, err) + } + f, err := os.Open(goldenFilepath) + if err != nil { + log.Fatal(err) + } + defer f.Close() + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Text() + params := strings.Split(line, ",") + randSecretVector, err := hex.DecodeString(params[0]) + require.Nil(t, err) + randSecret := new([32]byte) + copy((*randSecret)[:], randSecretVector) + locIsLeast, err := strconv.ParseBool(params[1]) + require.Nil(t, err) + expectedRecvSecret, err := hex.DecodeString(params[2]) + require.Nil(t, err) + expectedSendSecret, err := hex.DecodeString(params[3]) + require.Nil(t, err) + + recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) + require.Equal(t, expectedRecvSecret, (*recvSecret)[:], "Recv Secrets aren't equal") + require.Equal(t, expectedSendSecret, (*sendSecret)[:], "Send Secrets aren't equal") + } +} + +func TestNilPubkey(t *testing.T) { + fooConn, barConn := makeKVStoreConnPair() + defer fooConn.Close() + defer barConn.Close() + fooPrvKey := ed25519.GenPrivKey() + barPrvKey := privKeyWithNilPubKey{ed25519.GenPrivKey()} + + go MakeSecretConnection(fooConn, fooPrvKey) //nolint:errcheck // ignore for tests + + _, err := MakeSecretConnection(barConn, barPrvKey) + require.Error(t, err) + assert.Equal(t, "toproto: key type is not supported", err.Error()) +} + +func TestNonEd25519Pubkey(t *testing.T) { + fooConn, barConn := makeKVStoreConnPair() + defer fooConn.Close() + defer barConn.Close() + fooPrvKey := ed25519.GenPrivKey() + barPrvKey := sr25519.GenPrivKey() + + go MakeSecretConnection(fooConn, fooPrvKey) //nolint:errcheck // ignore for tests + + _, err := MakeSecretConnection(barConn, barPrvKey) + require.Error(t, err) + assert.Contains(t, err.Error(), "is not supported") +} + +func writeLots(t *testing.T, wg *sync.WaitGroup, conn io.Writer, txt string, n int) { + defer wg.Done() + for i := 0; i < n; i++ { + _, err := conn.Write([]byte(txt)) + if err != nil { + t.Errorf("failed to write to fooSecConn: %v", err) + return + } + } +} + +func readLots(t *testing.T, wg *sync.WaitGroup, conn io.Reader, n int) { + readBuffer := make([]byte, dataMaxSize) + for i := 0; i < n; i++ { + _, err := conn.Read(readBuffer) + assert.NoError(t, err) + } + wg.Done() +} + +// Creates the data for a test vector file. +// The file format is: +// Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge) +func createGoldenTestVectors(*testing.T) string { + data := "" + for i := 0; i < 32; i++ { + randSecretVector := cmtrand.Bytes(32) + randSecret := new([32]byte) + copy((*randSecret)[:], randSecretVector) + data += hex.EncodeToString((*randSecret)[:]) + "," + locIsLeast := cmtrand.Bool() + data += strconv.FormatBool(locIsLeast) + "," + recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) + data += hex.EncodeToString((*recvSecret)[:]) + "," + data += hex.EncodeToString((*sendSecret)[:]) + "," + } + return data +} + +// Each returned ReadWriteCloser is akin to a net.Connection +func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) { + barReader, fooWriter := io.Pipe() + fooReader, barWriter := io.Pipe() + return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter} +} + +func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) { + var ( + fooConn, barConn = makeKVStoreConnPair() + fooPrvKey = ed25519.GenPrivKey() + fooPubKey = fooPrvKey.PubKey() + barPrvKey = ed25519.GenPrivKey() + barPubKey = barPrvKey.PubKey() + ) + + // Make connections from both sides in parallel. + trs, ok := async.Parallel( + func(_ int) (val interface{}, abort bool, err error) { + fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) + if err != nil { + tb.Errorf("failed to establish SecretConnection for foo: %v", err) + return nil, true, err + } + remotePubBytes := fooSecConn.RemotePubKey() + if !remotePubBytes.Equals(barPubKey) { + err = fmt.Errorf("unexpected fooSecConn.RemotePubKey. Expected %v, got %v", + barPubKey, fooSecConn.RemotePubKey()) + tb.Error(err) + return nil, true, err + } + return nil, false, nil + }, + func(_ int) (val interface{}, abort bool, err error) { + barSecConn, err = MakeSecretConnection(barConn, barPrvKey) + if barSecConn == nil { + tb.Errorf("failed to establish SecretConnection for bar: %v", err) + return nil, true, err + } + remotePubBytes := barSecConn.RemotePubKey() + if !remotePubBytes.Equals(fooPubKey) { + err = fmt.Errorf("unexpected barSecConn.RemotePubKey. Expected %v, got %v", + fooPubKey, barSecConn.RemotePubKey()) + tb.Error(err) + return nil, true, err + } + return nil, false, nil + }, + ) + + require.Nil(tb, trs.FirstError()) + require.True(tb, ok, "Unexpected task abortion") + + return fooSecConn, barSecConn +} + +// Benchmarks + +func BenchmarkWriteSecretConnection(b *testing.B) { + b.StopTimer() + b.ReportAllocs() + fooSecConn, barSecConn := makeSecretConnPair(b) + randomMsgSizes := []int{ + dataMaxSize / 10, + dataMaxSize / 3, + dataMaxSize / 2, + dataMaxSize, + dataMaxSize * 3 / 2, + dataMaxSize * 2, + dataMaxSize * 7 / 2, + } + fooWriteBytes := make([][]byte, 0, len(randomMsgSizes)) + for _, size := range randomMsgSizes { + fooWriteBytes = append(fooWriteBytes, cmtrand.Bytes(size)) + } + // Consume reads from bar's reader + go func() { + readBuffer := make([]byte, dataMaxSize) + for { + _, err := barSecConn.Read(readBuffer) + if err == io.EOF { + return + } else if err != nil { + b.Errorf("failed to read from barSecConn: %v", err) + return + } + } + }() + + b.StartTimer() + for i := 0; i < b.N; i++ { + idx := cmtrand.Intn(len(fooWriteBytes)) + _, err := fooSecConn.Write(fooWriteBytes[idx]) + if err != nil { + b.Errorf("failed to write to fooSecConn: %v", err) + return + } + } + b.StopTimer() + + if err := fooSecConn.Close(); err != nil { + b.Error(err) + } + // barSecConn.Close() race condition +} + +func BenchmarkReadSecretConnection(b *testing.B) { + b.StopTimer() + b.ReportAllocs() + fooSecConn, barSecConn := makeSecretConnPair(b) + randomMsgSizes := []int{ + dataMaxSize / 10, + dataMaxSize / 3, + dataMaxSize / 2, + dataMaxSize, + dataMaxSize * 3 / 2, + dataMaxSize * 2, + dataMaxSize * 7 / 2, + } + fooWriteBytes := make([][]byte, 0, len(randomMsgSizes)) + for _, size := range randomMsgSizes { + fooWriteBytes = append(fooWriteBytes, cmtrand.Bytes(size)) + } + go func() { + for i := 0; i < b.N; i++ { + idx := cmtrand.Intn(len(fooWriteBytes)) + _, err := fooSecConn.Write(fooWriteBytes[idx]) + if err != nil { + b.Errorf("failed to write to fooSecConn: %v, %v,%v", err, i, b.N) + return + } + } + }() + + b.StartTimer() + for i := 0; i < b.N; i++ { + readBuffer := make([]byte, dataMaxSize) + _, err := barSecConn.Read(readBuffer) + + if err == io.EOF { + return + } else if err != nil { + b.Fatalf("Failed to read from barSecConn: %v", err) + } + } + b.StopTimer() +} diff --git a/p2p/conn/testdata/TestDeriveSecretsAndChallengeGolden.golden b/p2p/conn/testdata/TestDeriveSecretsAndChallengeGolden.golden new file mode 100644 index 0000000..9e03b4e --- /dev/null +++ b/p2p/conn/testdata/TestDeriveSecretsAndChallengeGolden.golden @@ -0,0 +1,32 @@ +9fe4a5a73df12dbd8659b1d9280873fe993caefec6b0ebc2686dd65027148e03,true,80a83ad6afcb6f8175192e41973aed31dd75e3c106f813d986d9567a4865eb2f,96362a04f628a0666d9866147326898bb0847b8db8680263ad19e6336d4eed9e,2632c3fd20f456c5383ed16aa1d56dc7875a2b0fc0d5ff053c3ada8934098c69 +0716764b370d543fee692af03832c16410f0a56e4ddb79604ea093b10bb6f654,false,84f2b1e8658456529a2c324f46c3406c3c6fecd5fbbf9169f60bed8956a8b03d,cba357ae33d7234520d5742102a2a6cdb39b7db59c14a58fa8aadd310127630f,576643a8fcc1a4cf866db900f4a150dbe35d44a1b3ff36e4911565c3fa22fc32 +358dd73aae2c5b7b94b57f950408a3c681e748777ecab2063c8ca51a63588fa8,false,c2e2f664c8ee561af8e1e30553373be4ae23edecc8c6bd762d44b2afb7f2a037,d1563f428ac1c023c15d8082b2503157fe9ecbde4fb3493edd69ebc299b4970c,89fb6c6439b12fe11a4c604b8ad883f7dc76be33df590818fe5eb15ddb01face +0958308bdb583e639dd399a98cd21077d834b4b5e30771275a5a73a62efcc7e0,false,523c0ae97039173566f7ab4b8f271d8d78feef5a432d618e58ced4f80f7c1696,c1b743401c6e4508e62b8245ea7c3252bbad082e10af10e80608084d63877977,d7c52adf12ebc69677aec4bd387b0c5a35570fe61cb7b8ae55f3ab14b1b79be0 +d93d134e72f58f177642ac30f36b2d3cd4720aa7e60feb1296411a9009cf4524,false,47a427bcc1ef6f0ce31dbf343bc8bbf49554b4dd1e2330fd97d0df23ecdbba10,73e23adb7801179349ecf9c8cdf64d71d64a9f1145ba6730e5d029f99eaf8840,a8fdcb77f591bfba7b8483aa15ae7b42054ba68625d51dec005896dfe910281f +6104474c791cda24d952b356fb41a5d273c0ce6cc87d270b1701d0523cd5aa13,true,1cb4397b9e478430321af4647da2ccbef62ff8888542d31cca3f626766c8080f,673b23318826bd31ad1a4995c6e5095c4b092f5598aa0a96381a3e977bc0eaf9,4a25a25c5f75d6cc512f2ba8c1546e6263e9ef8269f0c046c37838cc66aa83e6 +8a6002503c15cab763e27c53fc449f6854a210c95cdd67e4466b0f2cb46b629c,false,f01ff06aef356c87f8d2646ff9ed8b855497c2ca00ea330661d84ef421a67e63,4f59bb23090010614877265a1597f1a142fa97b7208e1d554435763505f36f6a,1aadcb1c8b5993da102cebcb60c545b03197c98137064530840f45d917ad300e +31a57c6b1fe33beb1f7ebbbfc06d58c4f307cd355b6f9753e58f3edec16c7559,false,13e126c4cb240349dccf0dc843977671d34a1daffd0517d06ed66b703344db22,d491431906a306af45ecf9f1977e32d7f65a79f5139f931760416de27554b687,5ea7e8e3d5a30503423341609d360d246b61a9159fc07f253a46e357977cd745 +71a3c79718b824627faeefdce887d9465b353bd962cc5e97c5b5dfedab457ef9,true,e2e8eea547dcee7eafa89ae41f48ab049beac24935fad75258924fd5273d23cb,45d2e839bf36a3616cbe8a9bdbd4e7b288bf5bf1e6e79c07995eb2b18eb2eaff,7ee50e0810bc9f98e56bc46de5da22d84b3efa52fe5d85db4b2344530ef17ed8 +2e9dba2eb4f9019c2628ff5899744469c26caf793636f30ddb76601751aee968,false,8bfc3b314e4468d4e19c9d28b7bfd5b5532263105273b0fe80801f6146313993,b77d2b223e27038f978ab87a725859f6995f903056bdbd594ab04f0b2cbad517,9032be49a9cbcd1de6fee332f8f24ebf545c05e0175b98c564e7d1e69630ae20 +81322b22c835efb26d78051f3a3840a9d01aa558c019ecfa26483b5c5535728c,true,61eacb7e9665e362ef492ef950cea58f8bc67434ab7ee5545139147adf395da4,0f600ef0c358cae938969f434c2ec0ce3be632fdf5246b7bb8ee3ff294036ecd,a7026b4c21fe225ecd775ae81249405c6f492882eb85f3f8e2232f11e515561e +826b86c5e8cb4173ff2d05c48e3537140c5e0f26f7866bbcd4e57616806e1be2,true,ae44dabd077d227c8d898930a7705a2b785c8849121282106c045bb58b66eb36,24b2c1b1e2a9ebe387df6dfb9fbde6c681e4eeb0a33bb1c3df3789087f56ffe3,b37a64ea97431b25cb271c4c8435f6dd97118b35da57168f3c3c269920f7bbc1 +18b5a7b973d4b263072e69515c5b6ed22191c3d6e851aaba872904672f8344ec,true,ce402af2fb93b6ef18cd406f7c437d3cbfb09141b7a02116b1cfbabbf75ad84a,c86bdb1709ef0f4a31a818843660f83338b9db77e262bb7c6546138e51c6046b,11fcd8e59c4e7f6050d3cd332337db794ae31260c159e409af3ed8f4d6523bf4 +26d10c56872b72bb76ae7c7b3f074afb3d4a364e5e3f8c661be9b4f5a522ea75,true,1c9782a8485c4ecb13904ec551a7f9300ecd687abfbe63c91c7fd583f84a7a4d,ae3f4ccd0dfee8b514f67db2e923714d324935b9ae9e488d088ebb79569d8cc4,8139a3ab728b0e765e4d90549ab8eed7e1048a83267eafa7442208a7f627558a +558838dfcfe94105c46a4ade4548e6c96271d33e6c752661356cc66024615bae,true,d5a38625be74177318072cf877f2427ce2327e9b58d2eb134d0ac52c9126572f,dead938f77007e3164b6eee4cd153433d03ca5d9ec64f41aa6b2d6a069edeeda,4a081a356361da429c564cf7ac8e217121bbe8c5ee5c9632bae0b7ddbe94f9d4 +f4a3f6a93a4827a59682fd8bf1a8e4fd9aaff01a337a86e1966c8fff0e746014,true,39a0aea2a8ac7f0524d63e395a25b98fc3844ed039f20b11058019dca2b3840f,6ff53243426ded506d22501ae0f989d9946b86a8bb2550d7ed6e90fdf41d0e7c,8784e728bf12f465ed20dc6f0e1d949a68e5795d4799536427a6f859547b7fd6 +1717020e1c4fca1b4926dba16671c0c04e4f19c621c646cb4525fa533b1c205c,false,b9a909767f3044608b4e314b149a729bef199f8311310e1ecd2072e5659b7194,7baf0ff4b980919cf545312f45234976f0b6c574aac5b772024f73248aad7538,99a18e1e4b039ef3777a8fdd0d9ffaccaf3b4523b6d26adacfe91cc5fcd9977e +de769062be27b2a4248dd5be315960c8d231738417ece670c2d6a1c52877b59e,true,cc6c2086718b21813513894546e85766d34c754e81fd6a19c12fc322ffb9b1c3,5a7da7500191c65a5f1fbb2a6122717edc70ca0469baf2bbbd6ca8255b93c077,8c0d32091dc687f1399c754a617d224742726bece848b50c35b4db5f0469ace7 +7c5549f36767e02ebf49a4616467199459aa6932dcc091f182f822185659559a,true,d8335e606128b0c621ff6cda99dc62babf4a4436c574c5c478c20122712727d0,0a7c673cccd6f7fd4ed1673f7d0f2cb08961faced123ca901b74581d5bdc8b25,16ac1eb2a39384716c7d490272d87e76c10665fdb331e1883435de175ce4460e +ecf8261ebda248dc7796f98987efe1b7be363a59037c9e61044490d08a077610,true,53def80fcdba01367c0ea36459b57409f59a771f57a8259b54f24785e5656b7d,90140870b3b1e84c9dcf7836eac0581b16fe0a40307619d267c6f871e1efce6a,c6d1836b66c1a722a377c7eb058995a0ef8711839c6d6a0cdd6ad1ff70f935a5 +21c0ef76ce0eae9391ceabfb08a861899db55ac4ccf010ed672599669c6938f2,false,8af5482cc015093f261d5b7ce87035dda41d8318b9960b52cca3e5f0d3f61808,f4d5338bcb57262e1034f01ed3858ca1e5d66a73f18588e72f3dc8c6a730be0c,7ba82c2820c95e3354d9a6ab4920ebcd7938ce19e25930fee58439246b0321b1 +05f3b66d6b0fe906137e60b4719083a2465106badedcdae3a4c91c46c5367340,false,e5c9e074e95c2896fa4093830e96e9cf159b8dcba2ead21f37237cf6e9a9aaa2,b3a0a50309b4ca23cd34363fd8df30e73ec4a275973986c2e11a53752eff0a3b,358a62056ff05f27185b9952d291c6346171937f6811cafbacddd82e17010f39 +fef0251cff7c5d1ba0514f1820a8265453365fd9f5bb8a92f955dc007a40e730,true,e35a0aff6e9060a39c15d276a1337f1948d0be0aef81fcd563a6783115b5283d,20a8efe83474253d70e5fd847df0cd26222cd39e9210687b68c0a23b73429108,2989fab4278b32f4f40dc02227ab30e10f62e15ab7aa7382da769b1d084e33df +1b7bb172baa2753ec9c3e81a7a9b4c6ef10f9ed7afcafa975395f095eca63a54,false,a98257203987d0c4d260d8feef841466977276612e268b69b5ce4191af161b29,ea177a20d6c1f73f9667090568f9197943037d6586f7e2d6b7b81756fc71df5f,844eff318ef4c6ee45f158c1946ff999e40ffac70883ab6d6b90995f246e69a2 +5ee9b60a25753066d0ecc1155ca6afcc6b853ba558c9533c134a93b82e756856,true,9889460b95ca9545864a4a5194891b7d475362428d6d797532da10bf1fc92076,a7a96739abd8eceb6751afc98df68e29f7af16fbfda3d4710df9c35b6dcdb4d5,998326285c90a2ea2e1f6c6dac79530742645e3dd1b2b42a0733388a99cab81b +a102613781872f88a949d82cb5efcc2e0f437010a950d71b87929ecb480af3b3,false,e099080a55b9b29ccecbbb0d91dbe49defcc217efd1de0588e0836ce5970d327,319293b8660a3cea9879487645ddadda72a5c60079c9154bb0dbb8a0c9cda79e,4d567f1b1a1b304347cf7b129e4c7a05aa57e2bbb8ea335db9e33d05fab12e4d +1d4538180d06f37c43e8caa2d0d80aa7c5d701c8c3e31508704131427837f5cc,true,73afeeb46efc03d2b9f20fc271752528e52b8931287296a7e4367c96bccb32bd,59dc4b69d9ccf6f77715e47fb9bf454f1b90bbd05f1d2bbd07c7d6666f31c91f,ac59d735dfcdc3a0a4ce5a10f09dea8c6afd47de9c0308dc817e3789c8aee963 +e4c480af1b0e3487a331761f64eb3f020a2b8ffa25ad17e00f57aa7ec2c5e84d,true,1145e9f001c70d364e97fcdbc88a2a3d6aecdd975212923820f90a0b215f11f6,b802ac7ef21c8abaeae024c76e3fa70a2a82f73e0bb7c7fe76752ad1742af2e6,0a95876e30617e32ae25acd3af97c37dc075825f800def3f2bf3f68a268744e9 +3a7a83dd657dd6277bcfa957534f40d9b559039aad752066a8d7ed9a6d9c0ab5,false,f90a251ad2338b19cfee6a7965f6f5098136974abb99b3d24553fa6117384978,e422ed7567e5602731b3d980106d0546ef4a4da5eb7175d66a452df12d37bad2,b086bed71dfb6662cb10e2b4fb16a7c22394f488e822fc19697db6077f6caf6f +273e8560c2b1734e863a6542bded7a6fcbfb49a12770bd8866d4863dceea3ae9,false,3b7849a362e7b7ba8c8b8a0cd00df5180604987dbda6c03f37d9a09fdb27fb28,e6cdf4d767df0f411e970da8dda6acd3c2c34ce63908d8a6dbf3715daa0318e4,359a4a39fbdffc808161a48a3ffbe77fc6a03ff52324c22510a42e46c08a6f22 +9b4f8702991be9569b6c0b07a2173104d41325017b27d68fa5af91cdab164c4d,true,598323677db11ece050289f31881ee8caacb59376c7182f9055708b2a4673f84,7675adc1264b6758beb097a991f766f62796f78c1cfa58a4de3d81c36434d3ae,d5d8d610ffd85b04cbe1c73ff5becd5917c513d9625b001f51d486d0dadcefe3 +e1a686ba0169eb97379ebf9d22e073819450ee5ad5f049c8e93016e8d2ec1430,false,ffe461e6075865cde2704aa148fd29bcf0af245803f446cb6153244f25617993,46df6c25fa0344e662490c4da0bddca626644e67e66705840ef08aae35c343fa,e9a56d75acad4272ab0c49ee5919a4e86e6c5695ef065704c1e592d4e7b41a10 diff --git a/p2p/conn_set.go b/p2p/conn_set.go new file mode 100644 index 0000000..8f4c53c --- /dev/null +++ b/p2p/conn_set.go @@ -0,0 +1,82 @@ +package p2p + +import ( + "net" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// ConnSet is a lookup table for connections and all their ips. +type ConnSet interface { + Has(net.Conn) bool + HasIP(net.IP) bool + Set(net.Conn, []net.IP) + Remove(net.Conn) + RemoveAddr(net.Addr) +} + +type connSetItem struct { + conn net.Conn + ips []net.IP +} + +type connSet struct { + cmtsync.RWMutex + + conns map[string]connSetItem +} + +// NewConnSet returns a ConnSet implementation. +func NewConnSet() ConnSet { + return &connSet{ + conns: map[string]connSetItem{}, + } +} + +func (cs *connSet) Has(c net.Conn) bool { + cs.RLock() + defer cs.RUnlock() + + _, ok := cs.conns[c.RemoteAddr().String()] + + return ok +} + +func (cs *connSet) HasIP(ip net.IP) bool { + cs.RLock() + defer cs.RUnlock() + + for _, c := range cs.conns { + for _, known := range c.ips { + if known.Equal(ip) { + return true + } + } + } + + return false +} + +func (cs *connSet) Remove(c net.Conn) { + cs.Lock() + defer cs.Unlock() + + delete(cs.conns, c.RemoteAddr().String()) +} + +func (cs *connSet) RemoveAddr(addr net.Addr) { + cs.Lock() + defer cs.Unlock() + + delete(cs.conns, addr.String()) +} + +func (cs *connSet) Set(c net.Conn, ips []net.IP) { + cs.Lock() + defer cs.Unlock() + + cs.conns[c.RemoteAddr().String()] = connSetItem{ + conn: c, + ips: ips, + } +} diff --git a/p2p/errors.go b/p2p/errors.go new file mode 100644 index 0000000..c1bb7d3 --- /dev/null +++ b/p2p/errors.go @@ -0,0 +1,191 @@ +package p2p + +import ( + "fmt" + "net" +) + +// ErrFilterTimeout indicates that a filter operation timed out. +type ErrFilterTimeout struct{} + +func (e ErrFilterTimeout) Error() string { + return "filter timed out" +} + +// ErrRejected indicates that a Peer was rejected carrying additional +// information as to the reason. +type ErrRejected struct { + addr NetAddress + conn net.Conn + err error + id ID + isAuthFailure bool + isDuplicate bool + isFiltered bool + isIncompatible bool + isNodeInfoInvalid bool + isSelf bool +} + +// Addr returns the NetAddress for the rejected Peer. +func (e ErrRejected) Addr() NetAddress { + return e.addr +} + +func (e ErrRejected) Error() string { + if e.isAuthFailure { + return fmt.Sprintf("auth failure: %s", e.err) + } + + if e.isDuplicate { + if e.conn != nil { + return fmt.Sprintf( + "duplicate CONN<%s>", + e.conn.RemoteAddr().String(), + ) + } + if e.id != "" { + return fmt.Sprintf("duplicate ID<%v>", e.id) + } + } + + if e.isFiltered { + if e.conn != nil { + return fmt.Sprintf( + "filtered CONN<%s>: %s", + e.conn.RemoteAddr().String(), + e.err, + ) + } + + if e.id != "" { + return fmt.Sprintf("filtered ID<%v>: %s", e.id, e.err) + } + } + + if e.isIncompatible { + return fmt.Sprintf("incompatible: %s", e.err) + } + + if e.isNodeInfoInvalid { + return fmt.Sprintf("invalid NodeInfo: %s", e.err) + } + + if e.isSelf { + return fmt.Sprintf("self ID<%v>", e.id) + } + + return fmt.Sprintf("%s", e.err) +} + +// IsAuthFailure when Peer authentication was unsuccessful. +func (e ErrRejected) IsAuthFailure() bool { return e.isAuthFailure } + +// IsDuplicate when Peer ID or IP are present already. +func (e ErrRejected) IsDuplicate() bool { return e.isDuplicate } + +// IsFiltered when Peer ID or IP was filtered. +func (e ErrRejected) IsFiltered() bool { return e.isFiltered } + +// IsIncompatible when Peer NodeInfo is not compatible with our own. +func (e ErrRejected) IsIncompatible() bool { return e.isIncompatible } + +// IsNodeInfoInvalid when the sent NodeInfo is not valid. +func (e ErrRejected) IsNodeInfoInvalid() bool { return e.isNodeInfoInvalid } + +// IsSelf when Peer is our own node. +func (e ErrRejected) IsSelf() bool { return e.isSelf } + +// ErrSwitchDuplicatePeerID to be raised when a peer is connecting with a known +// ID. +type ErrSwitchDuplicatePeerID struct { + ID ID +} + +func (e ErrSwitchDuplicatePeerID) Error() string { + return fmt.Sprintf("duplicate peer ID %v", e.ID) +} + +// ErrSwitchDuplicatePeerIP to be raised whena a peer is connecting with a known +// IP. +type ErrSwitchDuplicatePeerIP struct { + IP net.IP +} + +func (e ErrSwitchDuplicatePeerIP) Error() string { + return fmt.Sprintf("duplicate peer IP %v", e.IP.String()) +} + +// ErrSwitchConnectToSelf to be raised when trying to connect to itself. +type ErrSwitchConnectToSelf struct { + Addr *NetAddress +} + +func (e ErrSwitchConnectToSelf) Error() string { + return fmt.Sprintf("connect to self: %v", e.Addr) +} + +type ErrSwitchAuthenticationFailure struct { + Dialed *NetAddress + Got ID +} + +func (e ErrSwitchAuthenticationFailure) Error() string { + return fmt.Sprintf( + "failed to authenticate peer. Dialed %v, but got peer with ID %s", + e.Dialed, + e.Got, + ) +} + +// ErrTransportClosed is raised when the Transport has been closed. +type ErrTransportClosed struct{} + +func (e ErrTransportClosed) Error() string { + return "transport has been closed" +} + +// ErrPeerRemoval is raised when attempting to remove a peer results in an error. +type ErrPeerRemoval struct{} + +func (e ErrPeerRemoval) Error() string { + return "peer removal failed" +} + +//------------------------------------------------------------------- + +type ErrNetAddressNoID struct { + Addr string +} + +func (e ErrNetAddressNoID) Error() string { + return fmt.Sprintf("address (%s) does not contain ID", e.Addr) +} + +type ErrNetAddressInvalid struct { + Addr string + Err error +} + +func (e ErrNetAddressInvalid) Error() string { + return fmt.Sprintf("invalid address (%s): %v", e.Addr, e.Err) +} + +type ErrNetAddressLookup struct { + Addr string + Err error +} + +func (e ErrNetAddressLookup) Error() string { + return fmt.Sprintf("error looking up host (%s): %v", e.Addr, e.Err) +} + +// ErrCurrentlyDialingOrExistingAddress indicates that we're currently +// dialing this address or it belongs to an existing peer. +type ErrCurrentlyDialingOrExistingAddress struct { + Addr string +} + +func (e ErrCurrentlyDialingOrExistingAddress) Error() string { + return fmt.Sprintf("connection with %s has been established or dialed", e.Addr) +} diff --git a/p2p/fuzz.go b/p2p/fuzz.go new file mode 100644 index 0000000..116b521 --- /dev/null +++ b/p2p/fuzz.go @@ -0,0 +1,153 @@ +package p2p + +import ( + "net" + "time" + + "github.com/cometbft/cometbft/config" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// FuzzedConnection wraps any net.Conn and depending on the mode either delays +// reads/writes or randomly drops reads/writes/connections. +type FuzzedConnection struct { + conn net.Conn + + mtx cmtsync.Mutex + start <-chan time.Time + active bool + + config *config.FuzzConnConfig +} + +// FuzzConn creates a new FuzzedConnection. Fuzzing starts immediately. +func FuzzConn(conn net.Conn) net.Conn { + return FuzzConnFromConfig(conn, config.DefaultFuzzConnConfig()) +} + +// FuzzConnFromConfig creates a new FuzzedConnection from a config. Fuzzing +// starts immediately. +func FuzzConnFromConfig(conn net.Conn, config *config.FuzzConnConfig) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: make(<-chan time.Time), + active: true, + config: config, + } +} + +// FuzzConnAfter creates a new FuzzedConnection. Fuzzing starts when the +// duration elapses. +func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn { + return FuzzConnAfterFromConfig(conn, d, config.DefaultFuzzConnConfig()) +} + +// FuzzConnAfterFromConfig creates a new FuzzedConnection from a config. +// Fuzzing starts when the duration elapses. +func FuzzConnAfterFromConfig( + conn net.Conn, + d time.Duration, + config *config.FuzzConnConfig, +) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: time.After(d), + active: false, + config: config, + } +} + +// Config returns the connection's config. +func (fc *FuzzedConnection) Config() *config.FuzzConnConfig { + return fc.config +} + +// Read implements net.Conn. +func (fc *FuzzedConnection) Read(data []byte) (n int, err error) { + if fc.fuzz() { + return 0, nil + } + return fc.conn.Read(data) +} + +// Write implements net.Conn. +func (fc *FuzzedConnection) Write(data []byte) (n int, err error) { + if fc.fuzz() { + return 0, nil + } + return fc.conn.Write(data) +} + +// Close implements net.Conn. +func (fc *FuzzedConnection) Close() error { return fc.conn.Close() } + +// LocalAddr implements net.Conn. +func (fc *FuzzedConnection) LocalAddr() net.Addr { return fc.conn.LocalAddr() } + +// RemoteAddr implements net.Conn. +func (fc *FuzzedConnection) RemoteAddr() net.Addr { return fc.conn.RemoteAddr() } + +// SetDeadline implements net.Conn. +func (fc *FuzzedConnection) SetDeadline(t time.Time) error { return fc.conn.SetDeadline(t) } + +// SetReadDeadline implements net.Conn. +func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error { + return fc.conn.SetReadDeadline(t) +} + +// SetWriteDeadline implements net.Conn. +func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { + return fc.conn.SetWriteDeadline(t) +} + +func (fc *FuzzedConnection) randomDuration() time.Duration { + maxDelayMillis := int(fc.config.MaxDelay.Nanoseconds() / 1000) + return time.Millisecond * time.Duration(cmtrand.Int()%maxDelayMillis) //nolint: gas +} + +// implements the fuzz (delay, kill conn) +// and returns whether or not the read/write should be ignored +func (fc *FuzzedConnection) fuzz() bool { + if !fc.shouldFuzz() { + return false + } + + switch fc.config.Mode { + case config.FuzzModeDrop: + // randomly drop the r/w, drop the conn, or sleep + r := cmtrand.Float64() + switch { + case r <= fc.config.ProbDropRW: + return true + case r < fc.config.ProbDropRW+fc.config.ProbDropConn: + // XXX: can't this fail because machine precision? + // XXX: do we need an error? + fc.Close() + return true + case r < fc.config.ProbDropRW+fc.config.ProbDropConn+fc.config.ProbSleep: + time.Sleep(fc.randomDuration()) + } + case config.FuzzModeDelay: + // sleep a bit + time.Sleep(fc.randomDuration()) + } + return false +} + +func (fc *FuzzedConnection) shouldFuzz() bool { + if fc.active { + return true + } + + fc.mtx.Lock() + defer fc.mtx.Unlock() + + select { + case <-fc.start: + fc.active = true + return true + default: + return false + } +} diff --git a/p2p/key.go b/p2p/key.go new file mode 100644 index 0000000..ed03ad2 --- /dev/null +++ b/p2p/key.go @@ -0,0 +1,120 @@ +package p2p + +import ( + "bytes" + "encoding/hex" + "fmt" + "os" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtos "github.com/cometbft/cometbft/libs/os" +) + +// ID is a hex-encoded crypto.Address +type ID string + +// IDByteLength is the length of a crypto.Address. Currently only 20. +// TODO: support other length addresses ? +const IDByteLength = crypto.AddressSize + +//------------------------------------------------------------------------------ +// Persistent peer ID +// TODO: encrypt on disk + +// NodeKey is the persistent peer key. +// It contains the nodes private key for authentication. +type NodeKey struct { + PrivKey crypto.PrivKey `json:"priv_key"` // our priv key +} + +// ID returns the peer's canonical ID - the hash of its public key. +func (nodeKey *NodeKey) ID() ID { + return PubKeyToID(nodeKey.PubKey()) +} + +// PubKey returns the peer's PubKey +func (nodeKey *NodeKey) PubKey() crypto.PubKey { + return nodeKey.PrivKey.PubKey() +} + +// PubKeyToID returns the ID corresponding to the given PubKey. +// It's the hex-encoding of the pubKey.Address(). +func PubKeyToID(pubKey crypto.PubKey) ID { + return ID(hex.EncodeToString(pubKey.Address())) +} + +// LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If +// the file does not exist, it generates and saves a new NodeKey. +func LoadOrGenNodeKey(filePath string) (*NodeKey, error) { + if cmtos.FileExists(filePath) { + nodeKey, err := LoadNodeKey(filePath) + if err != nil { + return nil, err + } + return nodeKey, nil + } + + privKey := ed25519.GenPrivKey() + nodeKey := &NodeKey{ + PrivKey: privKey, + } + + if err := nodeKey.SaveAs(filePath); err != nil { + return nil, err + } + + return nodeKey, nil +} + +// LoadNodeKey loads NodeKey located in filePath. +func LoadNodeKey(filePath string) (*NodeKey, error) { + jsonBytes, err := os.ReadFile(filePath) + if err != nil { + return nil, err + } + nodeKey := new(NodeKey) + err = cmtjson.Unmarshal(jsonBytes, nodeKey) + if err != nil { + return nil, err + } + return nodeKey, nil +} + +// SaveAs persists the NodeKey to filePath. +func (nodeKey *NodeKey) SaveAs(filePath string) error { + jsonBytes, err := cmtjson.Marshal(nodeKey) + if err != nil { + return err + } + err = os.WriteFile(filePath, jsonBytes, 0600) + if err != nil { + return err + } + return nil +} + +//------------------------------------------------------------------------------ + +// MakePoWTarget returns the big-endian encoding of 2^(targetBits - difficulty) - 1. +// It can be used as a Proof of Work target. +// NOTE: targetBits must be a multiple of 8 and difficulty must be less than targetBits. +func MakePoWTarget(difficulty, targetBits uint) []byte { + if targetBits%8 != 0 { + panic(fmt.Sprintf("targetBits (%d) not a multiple of 8", targetBits)) + } + if difficulty >= targetBits { + panic(fmt.Sprintf("difficulty (%d) >= targetBits (%d)", difficulty, targetBits)) + } + targetBytes := targetBits / 8 + zeroPrefixLen := (int(difficulty) / 8) + prefix := bytes.Repeat([]byte{0}, zeroPrefixLen) + mod := (difficulty % 8) + if mod > 0 { + nonZeroPrefix := byte(1<<(8-mod) - 1) + prefix = append(prefix, nonZeroPrefix) + } + tailLen := int(targetBytes) - len(prefix) + return append(prefix, bytes.Repeat([]byte{0xFF}, tailLen)...) +} diff --git a/p2p/key_test.go b/p2p/key_test.go new file mode 100644 index 0000000..804856f --- /dev/null +++ b/p2p/key_test.go @@ -0,0 +1,81 @@ +package p2p + +import ( + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func TestLoadOrGenNodeKey(t *testing.T) { + filePath := filepath.Join(os.TempDir(), cmtrand.Str(12)+"_peer_id.json") + + nodeKey, err := LoadOrGenNodeKey(filePath) + assert.Nil(t, err) + + nodeKey2, err := LoadOrGenNodeKey(filePath) + assert.Nil(t, err) + + assert.Equal(t, nodeKey, nodeKey2) +} + +func TestLoadNodeKey(t *testing.T) { + filePath := filepath.Join(os.TempDir(), cmtrand.Str(12)+"_peer_id.json") + + _, err := LoadNodeKey(filePath) + assert.True(t, os.IsNotExist(err)) + + _, err = LoadOrGenNodeKey(filePath) + require.NoError(t, err) + + nodeKey, err := LoadNodeKey(filePath) + assert.NoError(t, err) + assert.NotNil(t, nodeKey) +} + +func TestNodeKeySaveAs(t *testing.T) { + filePath := filepath.Join(os.TempDir(), cmtrand.Str(12)+"_peer_id.json") + + assert.NoFileExists(t, filePath) + + privKey := ed25519.GenPrivKey() + nodeKey := &NodeKey{ + PrivKey: privKey, + } + err := nodeKey.SaveAs(filePath) + assert.NoError(t, err) + assert.FileExists(t, filePath) +} + +//---------------------------------------------------------- + +func padBytes(bz []byte, targetBytes int) []byte { + return append(bz, bytes.Repeat([]byte{0xFF}, targetBytes-len(bz))...) +} + +func TestPoWTarget(t *testing.T) { + + targetBytes := 20 + cases := []struct { + difficulty uint + target []byte + }{ + {0, padBytes([]byte{}, targetBytes)}, + {1, padBytes([]byte{127}, targetBytes)}, + {8, padBytes([]byte{0}, targetBytes)}, + {9, padBytes([]byte{0, 127}, targetBytes)}, + {10, padBytes([]byte{0, 63}, targetBytes)}, + {16, padBytes([]byte{0, 0}, targetBytes)}, + {17, padBytes([]byte{0, 0, 127}, targetBytes)}, + } + + for _, c := range cases { + assert.Equal(t, MakePoWTarget(c.difficulty, 20*8), c.target) + } +} diff --git a/p2p/metrics.gen.go b/p2p/metrics.gen.go new file mode 100644 index 0000000..91c80f6 --- /dev/null +++ b/p2p/metrics.gen.go @@ -0,0 +1,72 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package p2p + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Peers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "peers", + Help: "Number of peers.", + }, labels).With(labelsAndValues...), + PeerReceiveBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "peer_receive_bytes_total", + Help: "Number of bytes received from a given peer.", + }, append(labels, "peer_id", "chID")).With(labelsAndValues...), + PeerSendBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "peer_send_bytes_total", + Help: "Number of bytes sent to a given peer.", + }, append(labels, "peer_id", "chID")).With(labelsAndValues...), + PeerPendingSendBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "peer_pending_send_bytes", + Help: "Pending bytes to be sent to a given peer.", + }, append(labels, "peer_id")).With(labelsAndValues...), + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "num_txs", + Help: "Number of transactions submitted by each peer.", + }, append(labels, "peer_id")).With(labelsAndValues...), + MessageReceiveBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "message_receive_bytes_total", + Help: "Number of bytes of each message type received.", + }, append(labels, "message_type")).With(labelsAndValues...), + MessageSendBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "message_send_bytes_total", + Help: "Number of bytes of each message type sent.", + }, append(labels, "message_type")).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Peers: discard.NewGauge(), + PeerReceiveBytesTotal: discard.NewCounter(), + PeerSendBytesTotal: discard.NewCounter(), + PeerPendingSendBytes: discard.NewGauge(), + NumTxs: discard.NewGauge(), + MessageReceiveBytesTotal: discard.NewCounter(), + MessageSendBytesTotal: discard.NewCounter(), + } +} diff --git a/p2p/metrics.go b/p2p/metrics.go new file mode 100644 index 0000000..a37d518 --- /dev/null +++ b/p2p/metrics.go @@ -0,0 +1,78 @@ +package p2p + +import ( + "fmt" + "reflect" + "regexp" + "sync" + + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "p2p" +) + +var ( + // valueToLabelRegexp is used to find the golang package name and type name + // so that the name can be turned into a prometheus label where the characters + // in the label do not include prometheus special characters such as '*' and '.'. + valueToLabelRegexp = regexp.MustCompile(`\*?(\w+)\.(.*)`) +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Number of peers. + Peers metrics.Gauge + // Number of bytes received from a given peer. + PeerReceiveBytesTotal metrics.Counter `metrics_labels:"peer_id,chID"` + // Number of bytes sent to a given peer. + PeerSendBytesTotal metrics.Counter `metrics_labels:"peer_id,chID"` + // Pending bytes to be sent to a given peer. + PeerPendingSendBytes metrics.Gauge `metrics_labels:"peer_id"` + // Number of transactions submitted by each peer. + NumTxs metrics.Gauge `metrics_labels:"peer_id"` + // Number of bytes of each message type received. + MessageReceiveBytesTotal metrics.Counter `metrics_labels:"message_type"` + // Number of bytes of each message type sent. + MessageSendBytesTotal metrics.Counter `metrics_labels:"message_type"` +} + +type metricsLabelCache struct { + mtx *sync.RWMutex + messageLabelNames map[reflect.Type]string +} + +// ValueToMetricLabel is a method that is used to produce a prometheus label value of the golang +// type that is passed in. +// This method uses a map on the Metrics struct so that each label name only needs +// to be produced once to prevent expensive string operations. +func (m *metricsLabelCache) ValueToMetricLabel(i interface{}) string { + t := reflect.TypeOf(i) + m.mtx.RLock() + + if s, ok := m.messageLabelNames[t]; ok { + m.mtx.RUnlock() + return s + } + m.mtx.RUnlock() + + s := t.String() + ss := valueToLabelRegexp.FindStringSubmatch(s) + l := fmt.Sprintf("%s_%s", ss[1], ss[2]) + m.mtx.Lock() + defer m.mtx.Unlock() + m.messageLabelNames[t] = l + return l +} + +func newMetricsLabelCache() *metricsLabelCache { + return &metricsLabelCache{ + mtx: &sync.RWMutex{}, + messageLabelNames: map[reflect.Type]string{}, + } +} diff --git a/p2p/mock/peer.go b/p2p/mock/peer.go new file mode 100644 index 0000000..76eae59 --- /dev/null +++ b/p2p/mock/peer.go @@ -0,0 +1,73 @@ +package mock + +import ( + "net" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/conn" +) + +type Peer struct { + *service.BaseService + ip net.IP + id p2p.ID + addr *p2p.NetAddress + kv map[string]interface{} + Outbound, Persistent bool +} + +// NewPeer creates and starts a new mock peer. If the ip +// is nil, random routable address is used. +func NewPeer(ip net.IP) *Peer { + var netAddr *p2p.NetAddress + if ip == nil { + _, netAddr = p2p.CreateRoutableAddr() + } else { + netAddr = p2p.NewNetAddressIPPort(ip, 26656) + } + nodeKey := p2p.NodeKey{PrivKey: ed25519.GenPrivKey()} + netAddr.ID = nodeKey.ID() + mp := &Peer{ + ip: ip, + id: nodeKey.ID(), + addr: netAddr, + kv: make(map[string]interface{}), + } + mp.BaseService = service.NewBaseService(nil, "MockPeer", mp) + if err := mp.Start(); err != nil { + panic(err) + } + return mp +} + +func (mp *Peer) FlushStop() { mp.Stop() } //nolint:errcheck //ignore error +func (mp *Peer) TrySend(_ p2p.Envelope) bool { return true } +func (mp *Peer) Send(_ p2p.Envelope) bool { return true } +func (mp *Peer) NodeInfo() p2p.NodeInfo { + return p2p.DefaultNodeInfo{ + DefaultNodeID: mp.addr.ID, + ListenAddr: mp.addr.DialString(), + } +} +func (mp *Peer) Status() conn.ConnectionStatus { return conn.ConnectionStatus{} } +func (mp *Peer) ID() p2p.ID { return mp.id } +func (mp *Peer) IsOutbound() bool { return mp.Outbound } +func (mp *Peer) IsPersistent() bool { return mp.Persistent } +func (mp *Peer) Get(key string) interface{} { + if value, ok := mp.kv[key]; ok { + return value + } + return nil +} + +func (mp *Peer) Set(key string, value interface{}) { + mp.kv[key] = value +} +func (mp *Peer) RemoteIP() net.IP { return mp.ip } +func (mp *Peer) SocketAddr() *p2p.NetAddress { return mp.addr } +func (mp *Peer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } +func (mp *Peer) CloseConn() error { return nil } +func (mp *Peer) SetRemovalFailed() {} +func (mp *Peer) GetRemovalFailed() bool { return false } diff --git a/p2p/mock/reactor.go b/p2p/mock/reactor.go new file mode 100644 index 0000000..8d2e06f --- /dev/null +++ b/p2p/mock/reactor.go @@ -0,0 +1,25 @@ +package mock + +import ( + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/conn" +) + +type Reactor struct { + p2p.BaseReactor + + Channels []*conn.ChannelDescriptor +} + +func NewReactor() *Reactor { + r := &Reactor{} + r.BaseReactor = *p2p.NewBaseReactor("Mock-PEX", r) + r.SetLogger(log.TestingLogger()) + return r +} + +func (r *Reactor) GetChannels() []*conn.ChannelDescriptor { return r.Channels } +func (r *Reactor) AddPeer(_ p2p.Peer) {} +func (r *Reactor) RemovePeer(_ p2p.Peer, _ interface{}) {} +func (r *Reactor) Receive(_ p2p.Envelope) {} diff --git a/p2p/mocks/peer.go b/p2p/mocks/peer.go new file mode 100644 index 0000000..aca4bbc --- /dev/null +++ b/p2p/mocks/peer.go @@ -0,0 +1,448 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + log "github.com/cometbft/cometbft/libs/log" + conn "github.com/cometbft/cometbft/p2p/conn" + + mock "github.com/stretchr/testify/mock" + + net "net" + + p2p "github.com/cometbft/cometbft/p2p" +) + +// Peer is an autogenerated mock type for the Peer type +type Peer struct { + mock.Mock +} + +// CloseConn provides a mock function with no fields +func (_m *Peer) CloseConn() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for CloseConn") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// FlushStop provides a mock function with no fields +func (_m *Peer) FlushStop() { + _m.Called() +} + +// Get provides a mock function with given fields: _a0 +func (_m *Peer) Get(_a0 string) interface{} { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Get") + } + + var r0 interface{} + if rf, ok := ret.Get(0).(func(string) interface{}); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(interface{}) + } + } + + return r0 +} + +// GetRemovalFailed provides a mock function with no fields +func (_m *Peer) GetRemovalFailed() bool { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetRemovalFailed") + } + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// ID provides a mock function with no fields +func (_m *Peer) ID() p2p.ID { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for ID") + } + + var r0 p2p.ID + if rf, ok := ret.Get(0).(func() p2p.ID); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(p2p.ID) + } + + return r0 +} + +// IsOutbound provides a mock function with no fields +func (_m *Peer) IsOutbound() bool { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for IsOutbound") + } + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// IsPersistent provides a mock function with no fields +func (_m *Peer) IsPersistent() bool { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for IsPersistent") + } + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// IsRunning provides a mock function with no fields +func (_m *Peer) IsRunning() bool { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for IsRunning") + } + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// NodeInfo provides a mock function with no fields +func (_m *Peer) NodeInfo() p2p.NodeInfo { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for NodeInfo") + } + + var r0 p2p.NodeInfo + if rf, ok := ret.Get(0).(func() p2p.NodeInfo); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(p2p.NodeInfo) + } + } + + return r0 +} + +// OnReset provides a mock function with no fields +func (_m *Peer) OnReset() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for OnReset") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStart provides a mock function with no fields +func (_m *Peer) OnStart() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for OnStart") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStop provides a mock function with no fields +func (_m *Peer) OnStop() { + _m.Called() +} + +// Quit provides a mock function with no fields +func (_m *Peer) Quit() <-chan struct{} { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Quit") + } + + var r0 <-chan struct{} + if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan struct{}) + } + } + + return r0 +} + +// RemoteAddr provides a mock function with no fields +func (_m *Peer) RemoteAddr() net.Addr { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for RemoteAddr") + } + + var r0 net.Addr + if rf, ok := ret.Get(0).(func() net.Addr); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(net.Addr) + } + } + + return r0 +} + +// RemoteIP provides a mock function with no fields +func (_m *Peer) RemoteIP() net.IP { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for RemoteIP") + } + + var r0 net.IP + if rf, ok := ret.Get(0).(func() net.IP); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(net.IP) + } + } + + return r0 +} + +// Reset provides a mock function with no fields +func (_m *Peer) Reset() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Reset") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Send provides a mock function with given fields: _a0 +func (_m *Peer) Send(_a0 p2p.Envelope) bool { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Send") + } + + var r0 bool + if rf, ok := ret.Get(0).(func(p2p.Envelope) bool); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// Set provides a mock function with given fields: _a0, _a1 +func (_m *Peer) Set(_a0 string, _a1 interface{}) { + _m.Called(_a0, _a1) +} + +// SetLogger provides a mock function with given fields: _a0 +func (_m *Peer) SetLogger(_a0 log.Logger) { + _m.Called(_a0) +} + +// SetRemovalFailed provides a mock function with no fields +func (_m *Peer) SetRemovalFailed() { + _m.Called() +} + +// SocketAddr provides a mock function with no fields +func (_m *Peer) SocketAddr() *p2p.NetAddress { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for SocketAddr") + } + + var r0 *p2p.NetAddress + if rf, ok := ret.Get(0).(func() *p2p.NetAddress); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*p2p.NetAddress) + } + } + + return r0 +} + +// Start provides a mock function with no fields +func (_m *Peer) Start() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Start") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Status provides a mock function with no fields +func (_m *Peer) Status() conn.ConnectionStatus { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Status") + } + + var r0 conn.ConnectionStatus + if rf, ok := ret.Get(0).(func() conn.ConnectionStatus); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(conn.ConnectionStatus) + } + + return r0 +} + +// Stop provides a mock function with no fields +func (_m *Peer) Stop() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Stop") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// String provides a mock function with no fields +func (_m *Peer) String() string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for String") + } + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// TrySend provides a mock function with given fields: _a0 +func (_m *Peer) TrySend(_a0 p2p.Envelope) bool { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for TrySend") + } + + var r0 bool + if rf, ok := ret.Get(0).(func(p2p.Envelope) bool); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// NewPeer creates a new instance of Peer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeer(t interface { + mock.TestingT + Cleanup(func()) +}) *Peer { + mock := &Peer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/p2p/netaddress.go b/p2p/netaddress.go new file mode 100644 index 0000000..f31ed02 --- /dev/null +++ b/p2p/netaddress.go @@ -0,0 +1,419 @@ +// Modified for CometBFT +// Originally Copyright (c) 2013-2014 Conformal Systems LLC. +// https://github.com/conformal/btcd/blob/master/LICENSE + +package p2p + +import ( + "encoding/hex" + "errors" + "flag" + "fmt" + "net" + "strconv" + "strings" + "time" + + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +// EmptyNetAddress defines the string representation of an empty NetAddress +const EmptyNetAddress = "" + +// NetAddress defines information about a peer on the network +// including its ID, IP address, and port. +type NetAddress struct { + ID ID `json:"id"` + IP net.IP `json:"ip"` + Port uint16 `json:"port"` +} + +// IDAddressString returns id@hostPort. It strips the leading +// protocol from protocolHostPort if it exists. +func IDAddressString(id ID, protocolHostPort string) string { + hostPort := removeProtocolIfDefined(protocolHostPort) + return fmt.Sprintf("%s@%s", id, hostPort) +} + +// NewNetAddress returns a new NetAddress using the provided TCP +// address. When testing, other net.Addr (except TCP) will result in +// using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will +// panic. Panics if ID is invalid. +// TODO: socks proxies? +func NewNetAddress(id ID, addr net.Addr) *NetAddress { + tcpAddr, ok := addr.(*net.TCPAddr) + if !ok { + if flag.Lookup("test.v") == nil { // normal run + panic(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) + } + // in testing + netAddr := NewNetAddressIPPort(net.IP("127.0.0.1"), 0) + netAddr.ID = id + return netAddr + } + + if err := validateID(id); err != nil { + panic(fmt.Sprintf("Invalid ID %v: %v (addr: %v)", id, err, addr)) + } + + ip := tcpAddr.IP + port := uint16(tcpAddr.Port) + na := NewNetAddressIPPort(ip, port) + na.ID = id + return na +} + +// NewNetAddressString returns a new NetAddress using the provided address in +// the form of "ID@IP:Port". +// Also resolves the host if host is not an IP. +// Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup) +func NewNetAddressString(addr string) (*NetAddress, error) { + addrWithoutProtocol := removeProtocolIfDefined(addr) + spl := strings.Split(addrWithoutProtocol, "@") + if len(spl) != 2 { + return nil, ErrNetAddressNoID{addr} + } + + // get ID + if err := validateID(ID(spl[0])); err != nil { + return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} + } + var id ID + id, addrWithoutProtocol = ID(spl[0]), spl[1] + + // get host and port + host, portStr, err := net.SplitHostPort(addrWithoutProtocol) + if err != nil { + return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} + } + if len(host) == 0 { + return nil, ErrNetAddressInvalid{ + addrWithoutProtocol, + errors.New("host is empty")} + } + + ip := net.ParseIP(host) + if ip == nil { + ips, err := net.LookupIP(host) + if err != nil { + return nil, ErrNetAddressLookup{host, err} + } + ip = ips[0] + } + + port, err := strconv.ParseUint(portStr, 10, 16) + if err != nil { + return nil, ErrNetAddressInvalid{portStr, err} + } + + na := NewNetAddressIPPort(ip, uint16(port)) + na.ID = id + return na, nil +} + +// NewNetAddressStrings returns an array of NetAddress'es build using +// the provided strings. +func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) { + netAddrs := make([]*NetAddress, 0) + errs := make([]error, 0) + for _, addr := range addrs { + netAddr, err := NewNetAddressString(addr) + if err != nil { + errs = append(errs, err) + } else { + netAddrs = append(netAddrs, netAddr) + } + } + return netAddrs, errs +} + +// NewNetAddressIPPort returns a new NetAddress using the provided IP +// and port number. +func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { + return &NetAddress{ + IP: ip, + Port: port, + } +} + +// NetAddressFromProto converts a Protobuf NetAddress into a native struct. +func NetAddressFromProto(pb tmp2p.NetAddress) (*NetAddress, error) { + ip := net.ParseIP(pb.IP) + if ip == nil { + return nil, fmt.Errorf("invalid IP address %v", pb.IP) + } + if pb.Port >= 1<<16 { + return nil, fmt.Errorf("invalid port number %v", pb.Port) + } + return &NetAddress{ + ID: ID(pb.ID), + IP: ip, + Port: uint16(pb.Port), + }, nil +} + +// NetAddressesFromProto converts a slice of Protobuf NetAddresses into a native slice. +func NetAddressesFromProto(pbs []tmp2p.NetAddress) ([]*NetAddress, error) { + nas := make([]*NetAddress, 0, len(pbs)) + for _, pb := range pbs { + na, err := NetAddressFromProto(pb) + if err != nil { + return nil, err + } + nas = append(nas, na) + } + return nas, nil +} + +// NetAddressesToProto converts a slice of NetAddresses into a Protobuf slice. +func NetAddressesToProto(nas []*NetAddress) []tmp2p.NetAddress { + pbs := make([]tmp2p.NetAddress, 0, len(nas)) + for _, na := range nas { + if na != nil { + pbs = append(pbs, na.ToProto()) + } + } + return pbs +} + +// ToProto converts a NetAddress to Protobuf. +func (na *NetAddress) ToProto() tmp2p.NetAddress { + return tmp2p.NetAddress{ + ID: string(na.ID), + IP: na.IP.String(), + Port: uint32(na.Port), + } +} + +// Equals reports whether na and other are the same addresses, +// including their ID, IP, and Port. +func (na *NetAddress) Equals(other interface{}) bool { + if o, ok := other.(*NetAddress); ok { + return na.String() == o.String() + } + return false +} + +// Same returns true is na has the same non-empty ID or DialString as other. +func (na *NetAddress) Same(other interface{}) bool { + if o, ok := other.(*NetAddress); ok { + if na.DialString() == o.DialString() { + return true + } + if na.ID != "" && na.ID == o.ID { + return true + } + } + return false +} + +// String representation: @: +func (na *NetAddress) String() string { + if na == nil { + return EmptyNetAddress + } + + addrStr := na.DialString() + if na.ID != "" { + addrStr = IDAddressString(na.ID, addrStr) + } + + return addrStr +} + +func (na *NetAddress) DialString() string { + if na == nil { + return "" + } + return net.JoinHostPort( + na.IP.String(), + strconv.FormatUint(uint64(na.Port), 10), + ) +} + +// Dial calls net.Dial on the address. +func (na *NetAddress) Dial() (net.Conn, error) { + conn, err := net.Dial("tcp", na.DialString()) + if err != nil { + return nil, err + } + return conn, nil +} + +// DialTimeout calls net.DialTimeout on the address. +func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { + conn, err := net.DialTimeout("tcp", na.DialString(), timeout) + if err != nil { + return nil, err + } + return conn, nil +} + +// Routable returns true if the address is routable. +func (na *NetAddress) Routable() bool { + if err := na.Valid(); err != nil { + return false + } + // TODO(oga) bitcoind doesn't include RFC3849 here, but should we? + return !na.RFC1918() && !na.RFC3927() && !na.RFC4862() && !na.RFC4193() && !na.RFC4843() && !na.Local() +} + +// For IPv4 these are either a 0 or all bits set address. For IPv6 a zero +// address or one that matches the RFC3849 documentation address format. +func (na *NetAddress) Valid() error { + if err := validateID(na.ID); err != nil { + return fmt.Errorf("invalid ID: %w", err) + } + + if na.IP == nil { + return errors.New("no IP") + } + if na.IP.IsUnspecified() || na.RFC3849() || na.IP.Equal(net.IPv4bcast) { + return errors.New("invalid IP") + } + return nil +} + +// HasID returns true if the address has an ID. +// NOTE: It does not check whether the ID is valid or not. +func (na *NetAddress) HasID() bool { + return string(na.ID) != "" +} + +// Local returns true if it is a local address. +func (na *NetAddress) Local() bool { + return na.IP.IsLoopback() || zero4.Contains(na.IP) +} + +// ReachabilityTo checks whenever o can be reached from na. +func (na *NetAddress) ReachabilityTo(o *NetAddress) int { + const ( + Unreachable = 0 + Default = iota + Teredo + Ipv6Weak + Ipv4 + Ipv6Strong + ) + switch { + case !na.Routable(): + return Unreachable + case na.RFC4380(): + switch { + case !o.Routable(): + return Default + case o.RFC4380(): + return Teredo + case o.IP.To4() != nil: + return Ipv4 + default: // ipv6 + return Ipv6Weak + } + case na.IP.To4() != nil: + if o.Routable() && o.IP.To4() != nil { + return Ipv4 + } + return Default + default: /* ipv6 */ + var tunneled bool + // Is our v6 is tunneled? + if o.RFC3964() || o.RFC6052() || o.RFC6145() { + tunneled = true + } + switch { + case !o.Routable(): + return Default + case o.RFC4380(): + return Teredo + case o.IP.To4() != nil: + return Ipv4 + case tunneled: + // only prioritize ipv6 if we aren't tunneling it. + return Ipv6Weak + } + return Ipv6Strong + } +} + +// RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) +// RFC3849: IPv6 Documentation address (2001:0DB8::/32) +// RFC3927: IPv4 Autoconfig (169.254.0.0/16) +// RFC3964: IPv6 6to4 (2002::/16) +// RFC4193: IPv6 unique local (FC00::/7) +// RFC4380: IPv6 Teredo tunneling (2001::/32) +// RFC4843: IPv6 ORCHID: (2001:10::/28) +// RFC4862: IPv6 Autoconfig (FE80::/64) +// RFC6052: IPv6 well known prefix (64:FF9B::/96) +// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96 +var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} +var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} +var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)} +var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)} +var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)} +var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)} +var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)} +var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)} +var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)} +var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)} +var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)} +var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)} +var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)} +var ( + // onionCatNet defines the IPv6 address block used to support Tor. + // bitcoind encodes a .onion address as a 16 byte number by decoding the + // address prior to the .onion (i.e. the key hash) base32 into a ten + // byte number. It then stores the first 6 bytes of the address as + // 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43. + // + // This is the same range used by OnionCat, which is part part of the + // RFC4193 unique local IPv6 range. + // + // In summary the format is: + // { magic 6 bytes, 10 bytes base32 decode of key hash } + onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128) +) + +// ipNet returns a net.IPNet struct given the passed IP address string, number +// of one bits to include at the start of the mask, and the total number of bits +// for the mask. +func ipNet(ip string, ones, bits int) net.IPNet { + return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)} +} + +func (na *NetAddress) RFC1918() bool { + return rfc1918_10.Contains(na.IP) || + rfc1918_192.Contains(na.IP) || + rfc1918_172.Contains(na.IP) +} +func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) } +func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) } +func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) } +func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) } +func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) } +func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) } +func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) } +func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) } +func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) } +func (na *NetAddress) OnionCatTor() bool { return onionCatNet.Contains(na.IP) } + +func removeProtocolIfDefined(addr string) string { + if strings.Contains(addr, "://") { + return strings.Split(addr, "://")[1] + } + return addr + +} + +func validateID(id ID) error { + if len(id) == 0 { + return errors.New("no ID") + } + idBytes, err := hex.DecodeString(string(id)) + if err != nil { + return err + } + if len(idBytes) != IDByteLength { + return fmt.Errorf("invalid hex length - got %d, expected %d", len(idBytes), IDByteLength) + } + return nil +} diff --git a/p2p/netaddress_test.go b/p2p/netaddress_test.go new file mode 100644 index 0000000..f8aaa3a --- /dev/null +++ b/p2p/netaddress_test.go @@ -0,0 +1,192 @@ +package p2p + +import ( + "net" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNetAddress_String(t *testing.T) { + tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") + require.Nil(t, err) + + netAddr := NewNetAddress("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) + + var wg sync.WaitGroup + + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _ = netAddr.String() + }() + } + + wg.Wait() + + s := netAddr.String() + require.Equal(t, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", s) +} + +func TestNewNetAddress(t *testing.T) { + tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") + require.Nil(t, err) + + assert.Panics(t, func() { + NewNetAddress("", tcpAddr) + }) + + addr := NewNetAddress("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) + assert.Equal(t, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", addr.String()) + + assert.NotPanics(t, func() { + NewNetAddress("", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8000}) + }, "Calling NewNetAddress with UDPAddr should not panic in testing") +} + +func TestNewNetAddressString(t *testing.T) { + testCases := []struct { + name string + addr string + expected string + correct bool + }{ + {"no node id and no protocol", "127.0.0.1:8080", "", false}, + {"no node id w/ tcp input", "tcp://127.0.0.1:8080", "", false}, + {"no node id w/ udp input", "udp://127.0.0.1:8080", "", false}, + + { + "no protocol", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + true, + }, + { + "tcp input", + "tcp://deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + true, + }, + { + "udp input", + "udp://deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + true, + }, + {"malformed tcp input", "tcp//deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", "", false}, + {"malformed udp input", "udp//deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", "", false}, + + // {"127.0.0:8080", false}, + {"invalid host", "notahost", "", false}, + {"invalid port", "127.0.0.1:notapath", "", false}, + {"invalid host w/ port", "notahost:8080", "", false}, + {"just a port", "8082", "", false}, + {"non-existent port", "127.0.0:8080000", "", false}, + + {"too short nodeId", "deadbeef@127.0.0.1:8080", "", false}, + {"too short, not hex nodeId", "this-isnot-hex@127.0.0.1:8080", "", false}, + {"not hex nodeId", "xxxxbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", "", false}, + + {"too short nodeId w/tcp", "tcp://deadbeef@127.0.0.1:8080", "", false}, + {"too short notHex nodeId w/tcp", "tcp://this-isnot-hex@127.0.0.1:8080", "", false}, + {"notHex nodeId w/tcp", "tcp://xxxxbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", "", false}, + { + "correct nodeId w/tcp", + "tcp://deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + true, + }, + + {"no node id", "tcp://@127.0.0.1:8080", "", false}, + {"no node id or IP", "tcp://@", "", false}, + {"tcp no host, w/ port", "tcp://:26656", "", false}, + {"empty", "", "", false}, + {"node id delimiter 1", "@", "", false}, + {"node id delimiter 2", " @", "", false}, + {"node id delimiter 3", " @ ", "", false}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + addr, err := NewNetAddressString(tc.addr) + if tc.correct { + if assert.Nil(t, err, tc.addr) { + assert.Equal(t, tc.expected, addr.String()) + } + } else { + assert.NotNil(t, err, tc.addr) + } + }) + } +} + +func TestNewNetAddressStrings(t *testing.T) { + addrs, errs := NewNetAddressStrings([]string{ + "127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeed@127.0.0.2:8080"}) + assert.Len(t, errs, 1) + assert.Equal(t, 2, len(addrs)) +} + +func TestNewNetAddressIPPort(t *testing.T) { + addr := NewNetAddressIPPort(net.ParseIP("127.0.0.1"), 8080) + assert.Equal(t, "127.0.0.1:8080", addr.String()) +} + +func TestNetAddressProperties(t *testing.T) { + // TODO add more test cases + testCases := []struct { + addr string + valid bool + local bool + routable bool + }{ + {"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", true, true, false}, + {"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@ya.ru:80", true, false, true}, + } + + for _, tc := range testCases { + addr, err := NewNetAddressString(tc.addr) + require.Nil(t, err) + + err = addr.Valid() + if tc.valid { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } + assert.Equal(t, tc.local, addr.Local()) + assert.Equal(t, tc.routable, addr.Routable()) + } +} + +func TestNetAddressReachabilityTo(t *testing.T) { + // TODO add more test cases + testCases := []struct { + addr string + other string + reachability int + }{ + { + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8081", + 0, + }, + {"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@ya.ru:80", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", 1}, + } + + for _, tc := range testCases { + addr, err := NewNetAddressString(tc.addr) + require.Nil(t, err) + + other, err := NewNetAddressString(tc.other) + require.Nil(t, err) + + assert.Equal(t, tc.reachability, addr.ReachabilityTo(other)) + } +} diff --git a/p2p/node_info.go b/p2p/node_info.go new file mode 100644 index 0000000..2b36dc0 --- /dev/null +++ b/p2p/node_info.go @@ -0,0 +1,276 @@ +package p2p + +import ( + "bytes" + "errors" + "fmt" + "reflect" + + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtstrings "github.com/cometbft/cometbft/libs/strings" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" + "github.com/cometbft/cometbft/version" +) + +const ( + maxNodeInfoSize = 10240 // 10KB + maxNumChannels = 16 // plenty of room for upgrades, for now +) + +// Max size of the NodeInfo struct +func MaxNodeInfoSize() int { + return maxNodeInfoSize +} + +//------------------------------------------------------------- + +// NodeInfo exposes basic info of a node +// and determines if we're compatible. +type NodeInfo interface { + ID() ID + nodeInfoAddress + nodeInfoTransport +} + +type nodeInfoAddress interface { + NetAddress() (*NetAddress, error) +} + +// nodeInfoTransport validates a nodeInfo and checks +// our compatibility with it. It's for use in the handshake. +type nodeInfoTransport interface { + Validate() error + CompatibleWith(other NodeInfo) error +} + +//------------------------------------------------------------- + +// ProtocolVersion contains the protocol versions for the software. +type ProtocolVersion struct { + P2P uint64 `json:"p2p"` + Block uint64 `json:"block"` + App uint64 `json:"app"` +} + +// defaultProtocolVersion populates the Block and P2P versions using +// the global values, but not the App. +var defaultProtocolVersion = NewProtocolVersion( + version.P2PProtocol, + version.BlockProtocol, + 0, +) + +// NewProtocolVersion returns a fully populated ProtocolVersion. +func NewProtocolVersion(p2p, block, app uint64) ProtocolVersion { + return ProtocolVersion{ + P2P: p2p, + Block: block, + App: app, + } +} + +//------------------------------------------------------------- + +// Assert DefaultNodeInfo satisfies NodeInfo +var _ NodeInfo = DefaultNodeInfo{} + +// DefaultNodeInfo is the basic node information exchanged +// between two peers during the CometBFT P2P handshake. +type DefaultNodeInfo struct { + ProtocolVersion ProtocolVersion `json:"protocol_version"` + + // Authenticate + // TODO: replace with NetAddress + DefaultNodeID ID `json:"id"` // authenticated identifier + ListenAddr string `json:"listen_addr"` // accepting incoming + + // Check compatibility. + // Channels are HexBytes so easier to read as JSON + Network string `json:"network"` // network/chain ID + Version string `json:"version"` // major.minor.revision + Channels cmtbytes.HexBytes `json:"channels"` // channels this node knows about + + // ASCIIText fields + Moniker string `json:"moniker"` // arbitrary moniker + Other DefaultNodeInfoOther `json:"other"` // other application specific data +} + +// DefaultNodeInfoOther is the misc. applcation specific data +type DefaultNodeInfoOther struct { + TxIndex string `json:"tx_index"` + RPCAddress string `json:"rpc_address"` +} + +// ID returns the node's peer ID. +func (info DefaultNodeInfo) ID() ID { + return info.DefaultNodeID +} + +// Validate checks the self-reported DefaultNodeInfo is safe. +// It returns an error if there +// are too many Channels, if there are any duplicate Channels, +// if the ListenAddr is malformed, or if the ListenAddr is a host name +// that can not be resolved to some IP. +// TODO: constraints for Moniker/Other? Or is that for the UI ? +// JAE: It needs to be done on the client, but to prevent ambiguous +// unicode characters, maybe it's worth sanitizing it here. +// In the future we might want to validate these, once we have a +// name-resolution system up. +// International clients could then use punycode (or we could use +// url-encoding), and we just need to be careful with how we handle that in our +// clients. (e.g. off by default). +func (info DefaultNodeInfo) Validate() error { + + // ID is already validated. + + // Validate ListenAddr. + _, err := NewNetAddressString(IDAddressString(info.ID(), info.ListenAddr)) + if err != nil { + return err + } + + // Network is validated in CompatibleWith. + + // Validate Version + if len(info.Version) > 0 && + (!cmtstrings.IsASCIIText(info.Version) || cmtstrings.ASCIITrim(info.Version) == "") { + + return fmt.Errorf("info.Version must be valid ASCII text without tabs, but got %v", info.Version) + } + + // Validate Channels - ensure max and check for duplicates. + if len(info.Channels) > maxNumChannels { + return fmt.Errorf("info.Channels is too long (%v). Max is %v", len(info.Channels), maxNumChannels) + } + channels := make(map[byte]struct{}) + for _, ch := range info.Channels { + _, ok := channels[ch] + if ok { + return fmt.Errorf("info.Channels contains duplicate channel id %v", ch) + } + channels[ch] = struct{}{} + } + + // Validate Moniker. + if !cmtstrings.IsASCIIText(info.Moniker) || cmtstrings.ASCIITrim(info.Moniker) == "" { + return fmt.Errorf("info.Moniker must be valid non-empty ASCII text without tabs, but got %v", info.Moniker) + } + + // Validate Other. + other := info.Other + txIndex := other.TxIndex + switch txIndex { + case "", "on", "off": + default: + return fmt.Errorf("info.Other.TxIndex should be either 'on', 'off', or empty string, got '%v'", txIndex) + } + // XXX: Should we be more strict about address formats? + rpcAddr := other.RPCAddress + if len(rpcAddr) > 0 && (!cmtstrings.IsASCIIText(rpcAddr) || cmtstrings.ASCIITrim(rpcAddr) == "") { + return fmt.Errorf("info.Other.RPCAddress=%v must be valid ASCII text without tabs", rpcAddr) + } + + return nil +} + +// CompatibleWith checks if two DefaultNodeInfo are compatible with eachother. +// CONTRACT: two nodes are compatible if the Block version and network match +// and they have at least one channel in common. +func (info DefaultNodeInfo) CompatibleWith(otherInfo NodeInfo) error { + other, ok := otherInfo.(DefaultNodeInfo) + if !ok { + return fmt.Errorf("wrong NodeInfo type. Expected DefaultNodeInfo, got %v", reflect.TypeOf(otherInfo)) + } + + if info.ProtocolVersion.Block != other.ProtocolVersion.Block { + return fmt.Errorf("peer is on a different Block version. Got %v, expected %v", + other.ProtocolVersion.Block, info.ProtocolVersion.Block) + } + + // nodes must be on the same network + if info.Network != other.Network { + return fmt.Errorf("peer is on a different network. Got %v, expected %v", other.Network, info.Network) + } + + // if we have no channels, we're just testing + if len(info.Channels) == 0 { + return nil + } + + // for each of our channels, check if they have it + found := false +OUTER_LOOP: + for _, ch1 := range info.Channels { + for _, ch2 := range other.Channels { + if ch1 == ch2 { + found = true + break OUTER_LOOP // only need one + } + } + } + if !found { + return fmt.Errorf("peer has no common channels. Our channels: %v ; Peer channels: %v", info.Channels, other.Channels) + } + return nil +} + +// NetAddress returns a NetAddress derived from the DefaultNodeInfo - +// it includes the authenticated peer ID and the self-reported +// ListenAddr. Note that the ListenAddr is not authenticated and +// may not match that address actually dialed if its an outbound peer. +func (info DefaultNodeInfo) NetAddress() (*NetAddress, error) { + idAddr := IDAddressString(info.ID(), info.ListenAddr) + return NewNetAddressString(idAddr) +} + +func (info DefaultNodeInfo) HasChannel(chID byte) bool { + return bytes.Contains(info.Channels, []byte{chID}) +} + +func (info DefaultNodeInfo) ToProto() *tmp2p.DefaultNodeInfo { + + dni := new(tmp2p.DefaultNodeInfo) + dni.ProtocolVersion = tmp2p.ProtocolVersion{ + P2P: info.ProtocolVersion.P2P, + Block: info.ProtocolVersion.Block, + App: info.ProtocolVersion.App, + } + + dni.DefaultNodeID = string(info.DefaultNodeID) + dni.ListenAddr = info.ListenAddr + dni.Network = info.Network + dni.Version = info.Version + dni.Channels = info.Channels + dni.Moniker = info.Moniker + dni.Other = tmp2p.DefaultNodeInfoOther{ + TxIndex: info.Other.TxIndex, + RPCAddress: info.Other.RPCAddress, + } + + return dni +} + +func DefaultNodeInfoFromToProto(pb *tmp2p.DefaultNodeInfo) (DefaultNodeInfo, error) { + if pb == nil { + return DefaultNodeInfo{}, errors.New("nil node info") + } + dni := DefaultNodeInfo{ + ProtocolVersion: ProtocolVersion{ + P2P: pb.ProtocolVersion.P2P, + Block: pb.ProtocolVersion.Block, + App: pb.ProtocolVersion.App, + }, + DefaultNodeID: ID(pb.DefaultNodeID), + ListenAddr: pb.ListenAddr, + Network: pb.Network, + Version: pb.Version, + Channels: pb.Channels, + Moniker: pb.Moniker, + Other: DefaultNodeInfoOther{ + TxIndex: pb.Other.TxIndex, + RPCAddress: pb.Other.RPCAddress, + }, + } + + return dni, nil +} diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go new file mode 100644 index 0000000..781e1b0 --- /dev/null +++ b/p2p/node_info_test.go @@ -0,0 +1,128 @@ +package p2p + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/crypto/ed25519" +) + +func TestNodeInfoValidate(t *testing.T) { + + // empty fails + ni := DefaultNodeInfo{} + assert.Error(t, ni.Validate()) + + channels := make([]byte, maxNumChannels) + for i := 0; i < maxNumChannels; i++ { + channels[i] = byte(i) + } + dupChannels := make([]byte, 5) + copy(dupChannels, channels[:5]) + dupChannels = append(dupChannels, testCh) + + nonASCII := "¢§µ" + emptyTab := "\t" + emptySpace := " " + + testCases := []struct { + testName string + malleateNodeInfo func(*DefaultNodeInfo) + expectErr bool + }{ + { + "Too Many Channels", + func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, //nolint: gocritic + true, + }, + {"Duplicate Channel", func(ni *DefaultNodeInfo) { ni.Channels = dupChannels }, true}, + {"Good Channels", func(ni *DefaultNodeInfo) { ni.Channels = ni.Channels[:5] }, false}, + + {"Invalid NetAddress", func(ni *DefaultNodeInfo) { ni.ListenAddr = "not-an-address" }, true}, + {"Good NetAddress", func(ni *DefaultNodeInfo) { ni.ListenAddr = "0.0.0.0:26656" }, false}, + + {"Non-ASCII Version", func(ni *DefaultNodeInfo) { ni.Version = nonASCII }, true}, + {"Empty tab Version", func(ni *DefaultNodeInfo) { ni.Version = emptyTab }, true}, + {"Empty space Version", func(ni *DefaultNodeInfo) { ni.Version = emptySpace }, true}, + {"Empty Version", func(ni *DefaultNodeInfo) { ni.Version = "" }, false}, + + {"Non-ASCII Moniker", func(ni *DefaultNodeInfo) { ni.Moniker = nonASCII }, true}, + {"Empty tab Moniker", func(ni *DefaultNodeInfo) { ni.Moniker = emptyTab }, true}, + {"Empty space Moniker", func(ni *DefaultNodeInfo) { ni.Moniker = emptySpace }, true}, + {"Empty Moniker", func(ni *DefaultNodeInfo) { ni.Moniker = "" }, true}, + {"Good Moniker", func(ni *DefaultNodeInfo) { ni.Moniker = "hey its me" }, false}, + + {"Non-ASCII TxIndex", func(ni *DefaultNodeInfo) { ni.Other.TxIndex = nonASCII }, true}, + {"Empty tab TxIndex", func(ni *DefaultNodeInfo) { ni.Other.TxIndex = emptyTab }, true}, + {"Empty space TxIndex", func(ni *DefaultNodeInfo) { ni.Other.TxIndex = emptySpace }, true}, + {"Empty TxIndex", func(ni *DefaultNodeInfo) { ni.Other.TxIndex = "" }, false}, + {"Off TxIndex", func(ni *DefaultNodeInfo) { ni.Other.TxIndex = "off" }, false}, + + {"Non-ASCII RPCAddress", func(ni *DefaultNodeInfo) { ni.Other.RPCAddress = nonASCII }, true}, + {"Empty tab RPCAddress", func(ni *DefaultNodeInfo) { ni.Other.RPCAddress = emptyTab }, true}, + {"Empty space RPCAddress", func(ni *DefaultNodeInfo) { ni.Other.RPCAddress = emptySpace }, true}, + {"Empty RPCAddress", func(ni *DefaultNodeInfo) { ni.Other.RPCAddress = "" }, false}, + {"Good RPCAddress", func(ni *DefaultNodeInfo) { ni.Other.RPCAddress = "0.0.0.0:26657" }, false}, + } + + nodeKey := NodeKey{PrivKey: ed25519.GenPrivKey()} + name := "testing" + + // test case passes + ni = testNodeInfo(nodeKey.ID(), name).(DefaultNodeInfo) + ni.Channels = channels + assert.NoError(t, ni.Validate()) + + for _, tc := range testCases { + ni := testNodeInfo(nodeKey.ID(), name).(DefaultNodeInfo) + ni.Channels = channels + tc.malleateNodeInfo(&ni) + err := ni.Validate() + if tc.expectErr { + assert.Error(t, err, tc.testName) + } else { + assert.NoError(t, err, tc.testName) + } + } + +} + +func TestNodeInfoCompatible(t *testing.T) { + + nodeKey1 := NodeKey{PrivKey: ed25519.GenPrivKey()} + nodeKey2 := NodeKey{PrivKey: ed25519.GenPrivKey()} + name := "testing" + + var newTestChannel byte = 0x2 + + // test NodeInfo is compatible + ni1 := testNodeInfo(nodeKey1.ID(), name).(DefaultNodeInfo) + ni2 := testNodeInfo(nodeKey2.ID(), name).(DefaultNodeInfo) + assert.NoError(t, ni1.CompatibleWith(ni2)) + + // add another channel; still compatible + ni2.Channels = append(ni2.Channels, newTestChannel) + assert.True(t, ni2.HasChannel(newTestChannel)) + assert.NoError(t, ni1.CompatibleWith(ni2)) + + // wrong NodeInfo type is not compatible + _, netAddr := CreateRoutableAddr() + ni3 := mockNodeInfo{netAddr} + assert.Error(t, ni1.CompatibleWith(ni3)) + + testCases := []struct { + testName string + malleateNodeInfo func(*DefaultNodeInfo) + }{ + {"Wrong block version", func(ni *DefaultNodeInfo) { ni.ProtocolVersion.Block++ }}, + {"Wrong network", func(ni *DefaultNodeInfo) { ni.Network += "-wrong" }}, + {"No common channels", func(ni *DefaultNodeInfo) { ni.Channels = []byte{newTestChannel} }}, + } + + for _, tc := range testCases { + ni := testNodeInfo(nodeKey2.ID(), name).(DefaultNodeInfo) + tc.malleateNodeInfo(&ni) + assert.Error(t, ni1.CompatibleWith(ni)) + } +} diff --git a/p2p/peer.go b/p2p/peer.go new file mode 100644 index 0000000..fa19b08 --- /dev/null +++ b/p2p/peer.go @@ -0,0 +1,443 @@ +package p2p + +import ( + "fmt" + "net" + "reflect" + "time" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/libs/cmap" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + + cmtconn "github.com/cometbft/cometbft/p2p/conn" +) + +//go:generate ../scripts/mockery_generate.sh Peer + +const metricsTickerDuration = 10 * time.Second + +// Peer is an interface representing a peer connected on a reactor. +type Peer interface { + service.Service + FlushStop() + + ID() ID // peer's cryptographic ID + RemoteIP() net.IP // remote IP of the connection + RemoteAddr() net.Addr // remote address of the connection + + IsOutbound() bool // did we dial the peer + IsPersistent() bool // do we redial this peer when we disconnect + + CloseConn() error // close original connection + + NodeInfo() NodeInfo // peer's info + Status() cmtconn.ConnectionStatus + SocketAddr() *NetAddress // actual address of the socket + + Send(Envelope) bool + TrySend(Envelope) bool + + Set(string, interface{}) + Get(string) interface{} + + SetRemovalFailed() + GetRemovalFailed() bool +} + +//---------------------------------------------------------- + +// peerConn contains the raw connection and its config. +type peerConn struct { + outbound bool + persistent bool + conn net.Conn // source connection + + socketAddr *NetAddress + + // cached RemoteIP() + ip net.IP +} + +func newPeerConn( + outbound, persistent bool, + conn net.Conn, + socketAddr *NetAddress, +) peerConn { + + return peerConn{ + outbound: outbound, + persistent: persistent, + conn: conn, + socketAddr: socketAddr, + } +} + +// ID only exists for SecretConnection. +// NOTE: Will panic if conn is not *SecretConnection. +func (pc peerConn) ID() ID { + return PubKeyToID(pc.conn.(*cmtconn.SecretConnection).RemotePubKey()) +} + +// Return the IP from the connection RemoteAddr +func (pc peerConn) RemoteIP() net.IP { + if pc.ip != nil { + return pc.ip + } + + host, _, err := net.SplitHostPort(pc.conn.RemoteAddr().String()) + if err != nil { + panic(err) + } + + ips, err := net.LookupIP(host) + if err != nil { + panic(err) + } + + pc.ip = ips[0] + + return pc.ip +} + +// peer implements Peer. +// +// Before using a peer, you will need to perform a handshake on connection. +type peer struct { + service.BaseService + + // raw peerConn and the multiplex connection + peerConn + mconn *cmtconn.MConnection + + // peer's node info and the channel it knows about + // channels = nodeInfo.Channels + // cached to avoid copying nodeInfo in hasChannel + nodeInfo NodeInfo + channels []byte + + // User data + Data *cmap.CMap + + metrics *Metrics + metricsTicker *time.Ticker + mlc *metricsLabelCache + + // When removal of a peer fails, we set this flag + removalAttemptFailed bool +} + +type PeerOption func(*peer) + +func newPeer( + pc peerConn, + mConfig cmtconn.MConnConfig, + nodeInfo NodeInfo, + reactorsByCh map[byte]Reactor, + msgTypeByChID map[byte]proto.Message, + chDescs []*cmtconn.ChannelDescriptor, + onPeerError func(Peer, interface{}), + mlc *metricsLabelCache, + options ...PeerOption, +) *peer { + p := &peer{ + peerConn: pc, + nodeInfo: nodeInfo, + channels: nodeInfo.(DefaultNodeInfo).Channels, + Data: cmap.NewCMap(), + metricsTicker: time.NewTicker(metricsTickerDuration), + metrics: NopMetrics(), + mlc: mlc, + } + + p.mconn = createMConnection( + pc.conn, + p, + reactorsByCh, + msgTypeByChID, + chDescs, + onPeerError, + mConfig, + ) + p.BaseService = *service.NewBaseService(nil, "Peer", p) + for _, option := range options { + option(p) + } + + return p +} + +// String representation. +func (p *peer) String() string { + if p.outbound { + return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.ID()) + } + + return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.ID()) +} + +//--------------------------------------------------- +// Implements service.Service + +// SetLogger implements BaseService. +func (p *peer) SetLogger(l log.Logger) { + p.Logger = l + p.mconn.SetLogger(l) +} + +// OnStart implements BaseService. +func (p *peer) OnStart() error { + if err := p.BaseService.OnStart(); err != nil { + return err + } + + if err := p.mconn.Start(); err != nil { + return err + } + + go p.metricsReporter() + return nil +} + +// FlushStop mimics OnStop but additionally ensures that all successful +// .Send() calls will get flushed before closing the connection. +// NOTE: it is not safe to call this method more than once. +func (p *peer) FlushStop() { + p.metricsTicker.Stop() + p.BaseService.OnStop() + p.mconn.FlushStop() // stop everything and close the conn +} + +// OnStop implements BaseService. +func (p *peer) OnStop() { + p.metricsTicker.Stop() + p.BaseService.OnStop() + if err := p.mconn.Stop(); err != nil { // stop everything and close the conn + p.Logger.Debug("Error while stopping peer", "err", err) + } +} + +//--------------------------------------------------- +// Implements Peer + +// ID returns the peer's ID - the hex encoded hash of its pubkey. +func (p *peer) ID() ID { + return p.nodeInfo.ID() +} + +// IsOutbound returns true if the connection is outbound, false otherwise. +func (p *peer) IsOutbound() bool { + return p.outbound +} + +// IsPersistent returns true if the peer is persitent, false otherwise. +func (p *peer) IsPersistent() bool { + return p.persistent +} + +// NodeInfo returns a copy of the peer's NodeInfo. +func (p *peer) NodeInfo() NodeInfo { + return p.nodeInfo +} + +// SocketAddr returns the address of the socket. +// For outbound peers, it's the address dialed (after DNS resolution). +// For inbound peers, it's the address returned by the underlying connection +// (not what's reported in the peer's NodeInfo). +func (p *peer) SocketAddr() *NetAddress { + return p.socketAddr +} + +// Status returns the peer's ConnectionStatus. +func (p *peer) Status() cmtconn.ConnectionStatus { + return p.mconn.Status() +} + +// Send msg bytes to the channel identified by chID byte. Returns false if the +// send queue is full after timeout, specified by MConnection. +func (p *peer) Send(e Envelope) bool { + return p.send(e.ChannelID, e.Message, p.mconn.Send) +} + +// TrySend msg bytes to the channel identified by chID byte. Immediately returns +// false if the send queue is full. +func (p *peer) TrySend(e Envelope) bool { + return p.send(e.ChannelID, e.Message, p.mconn.TrySend) +} + +func (p *peer) send(chID byte, msg proto.Message, sendFunc func(byte, []byte) bool) bool { + if !p.IsRunning() { + return false + } else if !p.hasChannel(chID) { + return false + } + metricLabelValue := p.mlc.ValueToMetricLabel(msg) + if w, ok := msg.(Wrapper); ok { + msg = w.Wrap() + } + msgBytes, err := proto.Marshal(msg) + if err != nil { + p.Logger.Error("marshaling message to send", "error", err) + return false + } + res := sendFunc(chID, msgBytes) + if res { + labels := []string{ + "peer_id", string(p.ID()), + "chID", fmt.Sprintf("%#x", chID), + } + p.metrics.PeerSendBytesTotal.With(labels...).Add(float64(len(msgBytes))) + p.metrics.MessageSendBytesTotal.With("message_type", metricLabelValue).Add(float64(len(msgBytes))) + } + return res +} + +// Get the data for a given key. +func (p *peer) Get(key string) interface{} { + return p.Data.Get(key) +} + +// Set sets the data for the given key. +func (p *peer) Set(key string, data interface{}) { + p.Data.Set(key, data) +} + +// hasChannel returns true if the peer reported +// knowing about the given chID. +func (p *peer) hasChannel(chID byte) bool { + for _, ch := range p.channels { + if ch == chID { + return true + } + } + // NOTE: probably will want to remove this + // but could be helpful while the feature is new + p.Logger.Debug( + "Unknown channel for peer", + "channel", + chID, + "channels", + p.channels, + ) + return false +} + +// CloseConn closes original connection. Used for cleaning up in cases where the peer had not been started at all. +func (p *peer) CloseConn() error { + return p.conn.Close() +} + +func (p *peer) SetRemovalFailed() { + p.removalAttemptFailed = true +} + +func (p *peer) GetRemovalFailed() bool { + return p.removalAttemptFailed +} + +//--------------------------------------------------- +// methods only used for testing +// TODO: can we remove these? + +// CloseConn closes the underlying connection +func (pc *peerConn) CloseConn() { + pc.conn.Close() +} + +// RemoteAddr returns peer's remote network address. +func (p *peer) RemoteAddr() net.Addr { + return p.conn.RemoteAddr() +} + +// CanSend returns true if the send queue is not full, false otherwise. +func (p *peer) CanSend(chID byte) bool { + if !p.IsRunning() { + return false + } + return p.mconn.CanSend(chID) +} + +//--------------------------------------------------- + +func PeerMetrics(metrics *Metrics) PeerOption { + return func(p *peer) { + p.metrics = metrics + } +} + +func (p *peer) metricsReporter() { + for { + select { + case <-p.metricsTicker.C: + status := p.mconn.Status() + var sendQueueSize float64 + for _, chStatus := range status.Channels { + sendQueueSize += float64(chStatus.SendQueueSize) + } + + p.metrics.PeerPendingSendBytes.With("peer_id", string(p.ID())).Set(sendQueueSize) + case <-p.Quit(): + return + } + } +} + +//------------------------------------------------------------------ +// helper funcs + +func createMConnection( + conn net.Conn, + p *peer, + reactorsByCh map[byte]Reactor, + msgTypeByChID map[byte]proto.Message, + chDescs []*cmtconn.ChannelDescriptor, + onPeerError func(Peer, interface{}), + config cmtconn.MConnConfig, +) *cmtconn.MConnection { + + onReceive := func(chID byte, msgBytes []byte) { + reactor := reactorsByCh[chID] + if reactor == nil { + // Note that its ok to panic here as it's caught in the conn._recover, + // which does onPeerError. + panic(fmt.Sprintf("Unknown channel %X", chID)) + } + mt := msgTypeByChID[chID] + msg := proto.Clone(mt) + err := proto.Unmarshal(msgBytes, msg) + if err != nil { + panic(fmt.Errorf("unmarshaling message: %s into type: %s", err, reflect.TypeOf(mt))) + } + labels := []string{ + "peer_id", string(p.ID()), + "chID", fmt.Sprintf("%#x", chID), + } + if w, ok := msg.(Unwrapper); ok { + msg, err = w.Unwrap() + if err != nil { + panic(fmt.Errorf("unwrapping message: %s", err)) + } + } + p.metrics.PeerReceiveBytesTotal.With(labels...).Add(float64(len(msgBytes))) + p.metrics.MessageReceiveBytesTotal.With("message_type", p.mlc.ValueToMetricLabel(msg)).Add(float64(len(msgBytes))) + reactor.Receive(Envelope{ + ChannelID: chID, + Src: p, + Message: msg, + }) + } + + onError := func(r interface{}) { + onPeerError(p, r) + } + + return cmtconn.NewMConnectionWithConfig( + conn, + chDescs, + onReceive, + onError, + config, + ) +} diff --git a/p2p/peer_set.go b/p2p/peer_set.go new file mode 100644 index 0000000..baa4373 --- /dev/null +++ b/p2p/peer_set.go @@ -0,0 +1,157 @@ +package p2p + +import ( + "net" + + cmtsync "github.com/cometbft/cometbft/libs/sync" +) + +// IPeerSet has a (immutable) subset of the methods of PeerSet. +type IPeerSet interface { + Has(key ID) bool + HasIP(ip net.IP) bool + Get(key ID) Peer + List() []Peer + Size() int +} + +//----------------------------------------------------------------------------- + +// PeerSet is a special structure for keeping a table of peers. +// Iteration over the peers is super fast and thread-safe. +type PeerSet struct { + mtx cmtsync.Mutex + lookup map[ID]*peerSetItem + list []Peer +} + +type peerSetItem struct { + peer Peer + index int +} + +// NewPeerSet creates a new peerSet with a list of initial capacity of 256 items. +func NewPeerSet() *PeerSet { + return &PeerSet{ + lookup: make(map[ID]*peerSetItem), + list: make([]Peer, 0, 256), + } +} + +// Add adds the peer to the PeerSet. +// It returns an error carrying the reason, if the peer is already present. +func (ps *PeerSet) Add(peer Peer) error { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + if ps.lookup[peer.ID()] != nil { + return ErrSwitchDuplicatePeerID{peer.ID()} + } + if peer.GetRemovalFailed() { + return ErrPeerRemoval{} + } + + index := len(ps.list) + // Appending is safe even with other goroutines + // iterating over the ps.list slice. + ps.list = append(ps.list, peer) + ps.lookup[peer.ID()] = &peerSetItem{peer, index} + return nil +} + +// Has returns true if the set contains the peer referred to by this +// peerKey, otherwise false. +func (ps *PeerSet) Has(peerKey ID) bool { + ps.mtx.Lock() + _, ok := ps.lookup[peerKey] + ps.mtx.Unlock() + return ok +} + +// HasIP returns true if the set contains the peer referred to by this IP +// address, otherwise false. +func (ps *PeerSet) HasIP(peerIP net.IP) bool { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + return ps.hasIP(peerIP) +} + +// hasIP does not acquire a lock so it can be used in public methods which +// already lock. +func (ps *PeerSet) hasIP(peerIP net.IP) bool { + for _, item := range ps.lookup { + if item.peer.RemoteIP().Equal(peerIP) { + return true + } + } + + return false +} + +// Get looks up a peer by the provided peerKey. Returns nil if peer is not +// found. +func (ps *PeerSet) Get(peerKey ID) Peer { + ps.mtx.Lock() + defer ps.mtx.Unlock() + item, ok := ps.lookup[peerKey] + if ok { + return item.peer + } + return nil +} + +// Remove discards peer by its Key, if the peer was previously memoized. +// Returns true if the peer was removed, and false if it was not found. +// in the set. +func (ps *PeerSet) Remove(peer Peer) bool { + ps.mtx.Lock() + defer ps.mtx.Unlock() + + item := ps.lookup[peer.ID()] + if item == nil { + // Removing the peer has failed so we set a flag to mark that a removal was attempted. + // This can happen when the peer add routine from the switch is running in + // parallel to the receive routine of MConn. + // There is an error within MConn but the switch has not actually added the peer to the peer set yet. + // Setting this flag will prevent a peer from being added to a node's peer set afterwards. + peer.SetRemovalFailed() + return false + } + + index := item.index + // Create a new copy of the list but with one less item. + // (we must copy because we'll be mutating the list). + newList := make([]Peer, len(ps.list)-1) + copy(newList, ps.list) + // If it's the last peer, that's an easy special case. + if index == len(ps.list)-1 { + ps.list = newList + delete(ps.lookup, peer.ID()) + return true + } + + // Replace the popped item with the last item in the old list. + lastPeer := ps.list[len(ps.list)-1] + lastPeerKey := lastPeer.ID() + lastPeerItem := ps.lookup[lastPeerKey] + newList[index] = lastPeer + lastPeerItem.index = index + ps.list = newList + delete(ps.lookup, peer.ID()) + return true +} + +// Size returns the number of unique items in the peerSet. +func (ps *PeerSet) Size() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return len(ps.list) +} + +// List returns the threadsafe list of peers. +func (ps *PeerSet) List() []Peer { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return ps.list +} diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go new file mode 100644 index 0000000..6d1d73f --- /dev/null +++ b/p2p/peer_set_test.go @@ -0,0 +1,192 @@ +package p2p + +import ( + "net" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/service" +) + +// mockPeer for testing the PeerSet +type mockPeer struct { + service.BaseService + ip net.IP + id ID +} + +func (mp *mockPeer) FlushStop() { mp.Stop() } //nolint:errcheck // ignore error +func (mp *mockPeer) TrySend(Envelope) bool { return true } +func (mp *mockPeer) Send(Envelope) bool { return true } +func (mp *mockPeer) NodeInfo() NodeInfo { return DefaultNodeInfo{} } +func (mp *mockPeer) Status() ConnectionStatus { return ConnectionStatus{} } +func (mp *mockPeer) ID() ID { return mp.id } +func (mp *mockPeer) IsOutbound() bool { return false } +func (mp *mockPeer) IsPersistent() bool { return true } +func (mp *mockPeer) Get(s string) interface{} { return s } +func (mp *mockPeer) Set(string, interface{}) {} +func (mp *mockPeer) RemoteIP() net.IP { return mp.ip } +func (mp *mockPeer) SocketAddr() *NetAddress { return nil } +func (mp *mockPeer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } +func (mp *mockPeer) CloseConn() error { return nil } +func (mp *mockPeer) SetRemovalFailed() {} +func (mp *mockPeer) GetRemovalFailed() bool { return false } + +// Returns a mock peer +func newMockPeer(ip net.IP) *mockPeer { + if ip == nil { + ip = net.IP{127, 0, 0, 1} + } + nodeKey := NodeKey{PrivKey: ed25519.GenPrivKey()} + return &mockPeer{ + ip: ip, + id: nodeKey.ID(), + } +} + +func TestPeerSetAddRemoveOne(t *testing.T) { + t.Parallel() + + peerSet := NewPeerSet() + + var peerList []Peer + for i := 0; i < 5; i++ { + p := newMockPeer(net.IP{127, 0, 0, byte(i)}) + if err := peerSet.Add(p); err != nil { + t.Error(err) + } + peerList = append(peerList, p) + } + + n := len(peerList) + // 1. Test removing from the front + for i, peerAtFront := range peerList { + removed := peerSet.Remove(peerAtFront) + assert.True(t, removed) + wantSize := n - i - 1 + for j := 0; j < 2; j++ { + assert.Equal(t, false, peerSet.Has(peerAtFront.ID()), "#%d Run #%d: failed to remove peer", i, j) + assert.Equal(t, wantSize, peerSet.Size(), "#%d Run #%d: failed to remove peer and decrement size", i, j) + // Test the route of removing the now non-existent element + removed := peerSet.Remove(peerAtFront) + assert.False(t, removed) + } + } + + // 2. Next we are testing removing the peer at the end + // a) Replenish the peerSet + for _, peer := range peerList { + if err := peerSet.Add(peer); err != nil { + t.Error(err) + } + } + + // b) In reverse, remove each element + for i := n - 1; i >= 0; i-- { + peerAtEnd := peerList[i] + removed := peerSet.Remove(peerAtEnd) + assert.True(t, removed) + assert.Equal(t, false, peerSet.Has(peerAtEnd.ID()), "#%d: failed to remove item at end", i) + assert.Equal(t, i, peerSet.Size(), "#%d: differing sizes after peerSet.Remove(atEndPeer)", i) + } +} + +func TestPeerSetAddRemoveMany(t *testing.T) { + t.Parallel() + peerSet := NewPeerSet() + + peers := []Peer{} + N := 100 + for i := 0; i < N; i++ { + peer := newMockPeer(net.IP{127, 0, 0, byte(i)}) + if err := peerSet.Add(peer); err != nil { + t.Errorf("failed to add new peer") + } + if peerSet.Size() != i+1 { + t.Errorf("failed to add new peer and increment size") + } + peers = append(peers, peer) + } + + for i, peer := range peers { + removed := peerSet.Remove(peer) + assert.True(t, removed) + if peerSet.Has(peer.ID()) { + t.Errorf("failed to remove peer") + } + if peerSet.Size() != len(peers)-i-1 { + t.Errorf("failed to remove peer and decrement size") + } + } +} + +func TestPeerSetAddDuplicate(t *testing.T) { + t.Parallel() + peerSet := NewPeerSet() + peer := newMockPeer(nil) + + n := 20 + errsChan := make(chan error) + // Add the same asynchronously to test the + // concurrent guarantees of our APIs, and + // our expectation in the end is that only + // one addition succeeded, but the rest are + // instances of ErrSwitchDuplicatePeer. + for i := 0; i < n; i++ { + go func() { + errsChan <- peerSet.Add(peer) + }() + } + + // Now collect and tally the results + errsTally := make(map[string]int) + for i := 0; i < n; i++ { + err := <-errsChan + + switch err.(type) { + case ErrSwitchDuplicatePeerID: + errsTally["duplicateID"]++ + default: + errsTally["other"]++ + } + } + + // Our next procedure is to ensure that only one addition + // succeeded and that the rest are each ErrSwitchDuplicatePeer. + wantErrCount, gotErrCount := n-1, errsTally["duplicateID"] + assert.Equal(t, wantErrCount, gotErrCount, "invalid ErrSwitchDuplicatePeer count") + + wantNilErrCount, gotNilErrCount := 1, errsTally["other"] + assert.Equal(t, wantNilErrCount, gotNilErrCount, "invalid nil errCount") +} + +func TestPeerSetGet(t *testing.T) { + t.Parallel() + + var ( + peerSet = NewPeerSet() + peer = newMockPeer(nil) + ) + + assert.Nil(t, peerSet.Get(peer.ID()), "expecting a nil lookup, before .Add") + + if err := peerSet.Add(peer); err != nil { + t.Fatalf("Failed to add new peer: %v", err) + } + + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + // Add them asynchronously to test the + // concurrent guarantees of our APIs. + wg.Add(1) + go func(i int) { + defer wg.Done() + have, want := peerSet.Get(peer.ID()), peer + assert.Equal(t, have, want, "%d: have %v, want %v", i, have, want) + }(i) + } + wg.Wait() +} diff --git a/p2p/peer_test.go b/p2p/peer_test.go new file mode 100644 index 0000000..dc4d953 --- /dev/null +++ b/p2p/peer_test.go @@ -0,0 +1,242 @@ +package p2p + +import ( + "fmt" + golog "log" + "net" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/proto/tendermint/p2p" + + "github.com/cometbft/cometbft/config" + cmtconn "github.com/cometbft/cometbft/p2p/conn" +) + +func TestPeerBasic(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + t.Cleanup(rp.Stop) + + p, err := createOutboundPeerAndPerformHandshake(rp.Addr(), cfg, cmtconn.DefaultMConnConfig()) + require.Nil(err) + + err = p.Start() + require.Nil(err) + t.Cleanup(func() { + if err := p.Stop(); err != nil { + t.Error(err) + } + }) + + assert.True(p.IsRunning()) + assert.True(p.IsOutbound()) + assert.False(p.IsPersistent()) + p.persistent = true + assert.True(p.IsPersistent()) + assert.Equal(rp.Addr().DialString(), p.RemoteAddr().String()) + assert.Equal(rp.ID(), p.ID()) +} + +func TestPeerSend(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + config := cfg + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: config} + rp.Start() + t.Cleanup(rp.Stop) + + p, err := createOutboundPeerAndPerformHandshake(rp.Addr(), config, cmtconn.DefaultMConnConfig()) + require.Nil(err) + + err = p.Start() + require.Nil(err) + + t.Cleanup(func() { + if err := p.Stop(); err != nil { + t.Error(err) + } + }) + + assert.True(p.CanSend(testCh)) + assert.True(p.Send(Envelope{ChannelID: testCh, Message: &p2p.Message{}})) +} + +func createOutboundPeerAndPerformHandshake( + addr *NetAddress, + config *config.P2PConfig, + mConfig cmtconn.MConnConfig, +) (*peer, error) { + chDescs := []*cmtconn.ChannelDescriptor{ + {ID: testCh, Priority: 1}, + } + reactorsByCh := map[byte]Reactor{testCh: NewTestReactor(chDescs, true)} + msgTypeByChID := map[byte]proto.Message{ + testCh: &p2p.Message{}, + } + pk := ed25519.GenPrivKey() + pc, err := testOutboundPeerConn(addr, config, false, pk) + if err != nil { + return nil, err + } + timeout := 1 * time.Second + ourNodeInfo := testNodeInfo(addr.ID, "host_peer") + peerNodeInfo, err := handshake(pc.conn, timeout, ourNodeInfo) + if err != nil { + return nil, err + } + + p := newPeer(pc, mConfig, peerNodeInfo, reactorsByCh, msgTypeByChID, chDescs, func(p Peer, r interface{}) {}, newMetricsLabelCache()) + p.SetLogger(log.TestingLogger().With("peer", addr)) + return p, nil +} + +func testDial(addr *NetAddress, cfg *config.P2PConfig) (net.Conn, error) { + if cfg.TestDialFail { + return nil, fmt.Errorf("dial err (peerConfig.DialFail == true)") + } + + conn, err := addr.DialTimeout(cfg.DialTimeout) + if err != nil { + return nil, err + } + return conn, nil +} + +func testOutboundPeerConn( + addr *NetAddress, + config *config.P2PConfig, + persistent bool, + ourNodePrivKey crypto.PrivKey, +) (peerConn, error) { + + var pc peerConn + conn, err := testDial(addr, config) + if err != nil { + return pc, fmt.Errorf("error creating peer: %w", err) + } + + pc, err = testPeerConn(conn, config, true, persistent, ourNodePrivKey, addr) + if err != nil { + if cerr := conn.Close(); cerr != nil { + return pc, fmt.Errorf("%v: %w", cerr.Error(), err) + } + return pc, err + } + + // ensure dialed ID matches connection ID + if addr.ID != pc.ID() { + if cerr := conn.Close(); cerr != nil { + return pc, fmt.Errorf("%v: %w", cerr.Error(), err) + } + return pc, ErrSwitchAuthenticationFailure{addr, pc.ID()} + } + + return pc, nil +} + +type remotePeer struct { + PrivKey crypto.PrivKey + Config *config.P2PConfig + addr *NetAddress + channels bytes.HexBytes + listenAddr string + listener net.Listener +} + +func (rp *remotePeer) Addr() *NetAddress { + return rp.addr +} + +func (rp *remotePeer) ID() ID { + return PubKeyToID(rp.PrivKey.PubKey()) +} + +func (rp *remotePeer) Start() { + if rp.listenAddr == "" { + rp.listenAddr = "127.0.0.1:0" + } + + l, e := net.Listen("tcp", rp.listenAddr) // any available address + if e != nil { + golog.Fatalf("net.Listen tcp :0: %+v", e) + } + rp.listener = l + rp.addr = NewNetAddress(PubKeyToID(rp.PrivKey.PubKey()), l.Addr()) + if rp.channels == nil { + rp.channels = []byte{testCh} + } + go rp.accept() +} + +func (rp *remotePeer) Stop() { + rp.listener.Close() +} + +func (rp *remotePeer) Dial(addr *NetAddress) (net.Conn, error) { + conn, err := addr.DialTimeout(1 * time.Second) + if err != nil { + return nil, err + } + pc, err := testInboundPeerConn(conn, rp.Config, rp.PrivKey) + if err != nil { + return nil, err + } + _, err = handshake(pc.conn, time.Second, rp.nodeInfo()) + if err != nil { + return nil, err + } + return conn, err +} + +func (rp *remotePeer) accept() { + conns := []net.Conn{} + + for { + conn, err := rp.listener.Accept() + if err != nil { + golog.Printf("Failed to accept conn: %+v", err) + for _, conn := range conns { + _ = conn.Close() + } + return + } + + pc, err := testInboundPeerConn(conn, rp.Config, rp.PrivKey) + if err != nil { + golog.Fatalf("Failed to create a peer: %+v", err) + } + + _, err = handshake(pc.conn, time.Second, rp.nodeInfo()) + if err != nil { + golog.Fatalf("Failed to perform handshake: %+v", err) + } + + conns = append(conns, conn) + } +} + +func (rp *remotePeer) nodeInfo() NodeInfo { + return DefaultNodeInfo{ + ProtocolVersion: defaultProtocolVersion, + DefaultNodeID: rp.Addr().ID, + ListenAddr: rp.listener.Addr().String(), + Network: "testing", + Version: "1.2.3-rc0-deadbeef", + Channels: rp.channels, + Moniker: "remote_peer", + } +} diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go new file mode 100644 index 0000000..7368119 --- /dev/null +++ b/p2p/pex/addrbook.go @@ -0,0 +1,947 @@ +// Modified for CometBFT +// Originally Copyright (c) 2013-2014 Conformal Systems LLC. +// https://github.com/conformal/btcd/blob/master/LICENSE + +package pex + +import ( + "encoding/binary" + "fmt" + "hash" + "math" + "math/rand" + "net" + "sync" + "time" + + "github.com/minio/highwayhash" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" +) + +const ( + bucketTypeNew = 0x01 + bucketTypeOld = 0x02 +) + +// AddrBook is an address book used for tracking peers +// so we can gossip about them to others and select +// peers to dial. +// TODO: break this up? +type AddrBook interface { + service.Service + + // Add our own addresses so we don't later add ourselves + AddOurAddress(*p2p.NetAddress) + // Check if it is our address + OurAddress(*p2p.NetAddress) bool + + AddPrivateIDs([]string) + + // Add and remove an address + AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error + RemoveAddress(*p2p.NetAddress) + + // Check if the address is in the book + HasAddress(*p2p.NetAddress) bool + + // Do we need more peers? + NeedMoreAddrs() bool + // Is Address Book Empty? Answer should not depend on being in your own + // address book, or private peers + Empty() bool + + // Pick an address to dial + PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress + + // Mark address + MarkGood(p2p.ID) + MarkAttempt(*p2p.NetAddress) + MarkBad(*p2p.NetAddress, time.Duration) // Move peer to bad peers list + // Add bad peers back to addrBook + ReinstateBadPeers() + + IsGood(*p2p.NetAddress) bool + IsBanned(*p2p.NetAddress) bool + + // Send a selection of addresses to peers + GetSelection() []*p2p.NetAddress + // Send a selection of addresses with bias + GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress + + Size() int + + // Persist to disk + Save() +} + +var _ AddrBook = (*addrBook)(nil) + +// addrBook - concurrency safe peer address manager. +// Implements AddrBook. +type addrBook struct { + service.BaseService + + // accessed concurrently + mtx cmtsync.Mutex + rand *cmtrand.Rand + ourAddrs map[string]struct{} + privateIDs map[p2p.ID]struct{} + addrLookup map[p2p.ID]*knownAddress // new & old + badPeers map[p2p.ID]*knownAddress // blacklisted peers + bucketsOld []map[string]*knownAddress + bucketsNew []map[string]*knownAddress + nOld int + nNew int + + // immutable after creation + filePath string + key string // random prefix for bucket placement + routabilityStrict bool + hasher hash.Hash64 + + wg sync.WaitGroup +} + +func mustNewHasher() hash.Hash64 { + key := crypto.CRandBytes(highwayhash.Size) + hasher, err := highwayhash.New64(key) + if err != nil { + panic(err) + } + return hasher +} + +// NewAddrBook creates a new address book. +// Use Start to begin processing asynchronous address updates. +func NewAddrBook(filePath string, routabilityStrict bool) AddrBook { + am := &addrBook{ + rand: cmtrand.NewRand(), + ourAddrs: make(map[string]struct{}), + privateIDs: make(map[p2p.ID]struct{}), + addrLookup: make(map[p2p.ID]*knownAddress), + badPeers: make(map[p2p.ID]*knownAddress), + filePath: filePath, + routabilityStrict: routabilityStrict, + } + am.init() + am.BaseService = *service.NewBaseService(nil, "AddrBook", am) + return am +} + +// Initialize the buckets. +// When modifying this, don't forget to update loadFromFile() +func (a *addrBook) init() { + a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits + // New addr buckets + a.bucketsNew = make([]map[string]*knownAddress, newBucketCount) + for i := range a.bucketsNew { + a.bucketsNew[i] = make(map[string]*knownAddress) + } + // Old addr buckets + a.bucketsOld = make([]map[string]*knownAddress, oldBucketCount) + for i := range a.bucketsOld { + a.bucketsOld[i] = make(map[string]*knownAddress) + } + a.hasher = mustNewHasher() +} + +// OnStart implements Service. +func (a *addrBook) OnStart() error { + if err := a.BaseService.OnStart(); err != nil { + return err + } + a.loadFromFile(a.filePath) + + // wg.Add to ensure that any invocation of .Wait() + // later on will wait for saveRoutine to terminate. + a.wg.Add(1) + go a.saveRoutine() + + return nil +} + +// OnStop implements Service. +func (a *addrBook) OnStop() { + a.BaseService.OnStop() +} + +func (a *addrBook) Wait() { + a.wg.Wait() +} + +func (a *addrBook) FilePath() string { + return a.filePath +} + +//------------------------------------------------------- + +// AddOurAddress one of our addresses. +func (a *addrBook) AddOurAddress(addr *p2p.NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + + a.Logger.Info("Add our address to book", "addr", addr) + a.ourAddrs[addr.String()] = struct{}{} +} + +// OurAddress returns true if it is our address. +func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool { + a.mtx.Lock() + defer a.mtx.Unlock() + + _, ok := a.ourAddrs[addr.String()] + return ok +} + +func (a *addrBook) AddPrivateIDs(ids []string) { + a.mtx.Lock() + defer a.mtx.Unlock() + + for _, id := range ids { + a.privateIDs[p2p.ID(id)] = struct{}{} + } +} + +// AddAddress implements AddrBook +// Add address to a "new" bucket. If it's already in one, only add it probabilistically. +// Returns error if the addr is non-routable. Does not add self. +// NOTE: addr must not be nil +func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error { + a.mtx.Lock() + defer a.mtx.Unlock() + + return a.addAddress(addr, src) +} + +// RemoveAddress implements AddrBook - removes the address from the book. +func (a *addrBook) RemoveAddress(addr *p2p.NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + + a.removeAddress(addr) +} + +// IsGood returns true if peer was ever marked as good and haven't +// done anything wrong since then. +func (a *addrBook) IsGood(addr *p2p.NetAddress) bool { + a.mtx.Lock() + defer a.mtx.Unlock() + + return a.addrLookup[addr.ID].isOld() +} + +// IsBanned returns true if the peer is currently banned +func (a *addrBook) IsBanned(addr *p2p.NetAddress) bool { + a.mtx.Lock() + _, ok := a.badPeers[addr.ID] + a.mtx.Unlock() + + return ok +} + +// HasAddress returns true if the address is in the book. +func (a *addrBook) HasAddress(addr *p2p.NetAddress) bool { + a.mtx.Lock() + defer a.mtx.Unlock() + + ka := a.addrLookup[addr.ID] + return ka != nil +} + +// NeedMoreAddrs implements AddrBook - returns true if there are not have enough addresses in the book. +func (a *addrBook) NeedMoreAddrs() bool { + return a.Size() < needAddressThreshold +} + +// Empty implements AddrBook - returns true if there are no addresses in the address book. +// Does not count the peer appearing in its own address book, or private peers. +func (a *addrBook) Empty() bool { + return a.Size() == 0 +} + +// PickAddress implements AddrBook. It picks an address to connect to. +// The address is picked randomly from an old or new bucket according +// to the biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to that range) +// and determines how biased we are to pick an address from a new bucket. +// PickAddress returns nil if the AddrBook is empty or if we try to pick +// from an empty bucket. +func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress { + a.mtx.Lock() + defer a.mtx.Unlock() + + bookSize := a.size() + if bookSize <= 0 { + if bookSize < 0 { + panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) + } + return nil + } + if biasTowardsNewAddrs > 100 { + biasTowardsNewAddrs = 100 + } + if biasTowardsNewAddrs < 0 { + biasTowardsNewAddrs = 0 + } + + // Bias between new and old addresses. + oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(biasTowardsNewAddrs)) + newCorrelation := math.Sqrt(float64(a.nNew)) * float64(biasTowardsNewAddrs) + + // pick a random peer from a random bucket + var bucket map[string]*knownAddress + pickFromOldBucket := (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation + if (pickFromOldBucket && a.nOld == 0) || + (!pickFromOldBucket && a.nNew == 0) { + return nil + } + // loop until we pick a random non-empty bucket + for len(bucket) == 0 { + if pickFromOldBucket { + bucket = a.bucketsOld[a.rand.Intn(len(a.bucketsOld))] + } else { + bucket = a.bucketsNew[a.rand.Intn(len(a.bucketsNew))] + } + } + // pick a random index and loop over the map to return that index + randIndex := a.rand.Intn(len(bucket)) + for _, ka := range bucket { + if randIndex == 0 { + return ka.Addr + } + randIndex-- + } + return nil +} + +// MarkGood implements AddrBook - it marks the peer as good and +// moves it into an "old" bucket. +func (a *addrBook) MarkGood(id p2p.ID) { + a.mtx.Lock() + defer a.mtx.Unlock() + + ka := a.addrLookup[id] + if ka == nil { + return + } + ka.markGood() + if ka.isNew() { + if err := a.moveToOld(ka); err != nil { + a.Logger.Error("Error moving address to old", "err", err) + } + } +} + +// MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address. +func (a *addrBook) MarkAttempt(addr *p2p.NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + + ka := a.addrLookup[addr.ID] + if ka == nil { + return + } + ka.markAttempt() +} + +// MarkBad implements AddrBook. Kicks address out from book, places +// the address in the badPeers pool. +func (a *addrBook) MarkBad(addr *p2p.NetAddress, banTime time.Duration) { + a.mtx.Lock() + defer a.mtx.Unlock() + + if a.addBadPeer(addr, banTime) { + a.removeAddress(addr) + } +} + +// ReinstateBadPeers removes bad peers from ban list and places them into a new +// bucket. +func (a *addrBook) ReinstateBadPeers() { + a.mtx.Lock() + defer a.mtx.Unlock() + + for _, ka := range a.badPeers { + if ka.isBanned() { + continue + } + + bucket, err := a.calcNewBucket(ka.Addr, ka.Src) + if err != nil { + a.Logger.Error("Failed to calculate new bucket (bad peer won't be reinstantiated)", + "addr", ka.Addr, "err", err) + continue + } + + if err := a.addToNewBucket(ka, bucket); err != nil { + a.Logger.Error("Error adding peer to new bucket", "err", err) + } + delete(a.badPeers, ka.ID()) + + a.Logger.Info("Reinstated address", "addr", ka.Addr) + } +} + +// GetSelection implements AddrBook. +// It randomly selects some addresses (old & new). Suitable for peer-exchange protocols. +// Must never return a nil address. +func (a *addrBook) GetSelection() []*p2p.NetAddress { + a.mtx.Lock() + defer a.mtx.Unlock() + + bookSize := a.size() + if bookSize <= 0 { + if bookSize < 0 { + panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) + } + return nil + } + + numAddresses := cmtmath.MaxInt( + cmtmath.MinInt(minGetSelection, bookSize), + bookSize*getSelectionPercent/100) + numAddresses = cmtmath.MinInt(maxGetSelection, numAddresses) + + // XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk, + // could we just select a random numAddresses of indexes? + allAddr := make([]*p2p.NetAddress, bookSize) + i := 0 + for _, ka := range a.addrLookup { + allAddr[i] = ka.Addr + i++ + } + + // Fisher-Yates shuffle the array. We only need to do the first + // `numAddresses' since we are throwing the rest. + for i := 0; i < numAddresses; i++ { + // pick a number between current index and the end + j := cmtrand.Intn(len(allAddr)-i) + i + allAddr[i], allAddr[j] = allAddr[j], allAddr[i] + } + + // slice off the limit we are willing to share. + return allAddr[:numAddresses] +} + +func percentageOfNum(p, n int) int { + return int(math.Round((float64(p) / float64(100)) * float64(n))) +} + +// GetSelectionWithBias implements AddrBook. +// It randomly selects some addresses (old & new). Suitable for peer-exchange protocols. +// Must never return a nil address. +// +// Each address is picked randomly from an old or new bucket according to the +// biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to +// that range) and determines how biased we are to pick an address from a new +// bucket. +func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress { + a.mtx.Lock() + defer a.mtx.Unlock() + + bookSize := a.size() + if bookSize <= 0 { + if bookSize < 0 { + panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) + } + return nil + } + + if biasTowardsNewAddrs > 100 { + biasTowardsNewAddrs = 100 + } + if biasTowardsNewAddrs < 0 { + biasTowardsNewAddrs = 0 + } + + numAddresses := cmtmath.MaxInt( + cmtmath.MinInt(minGetSelection, bookSize), + bookSize*getSelectionPercent/100) + numAddresses = cmtmath.MinInt(maxGetSelection, numAddresses) + + // number of new addresses that, if possible, should be in the beginning of the selection + // if there are no enough old addrs, will choose new addr instead. + numRequiredNewAdd := cmtmath.MaxInt(percentageOfNum(biasTowardsNewAddrs, numAddresses), numAddresses-a.nOld) + selection := a.randomPickAddresses(bucketTypeNew, numRequiredNewAdd) + selection = append(selection, a.randomPickAddresses(bucketTypeOld, numAddresses-len(selection))...) + return selection +} + +//------------------------------------------------ + +// Size returns the number of addresses in the book. +func (a *addrBook) Size() int { + a.mtx.Lock() + defer a.mtx.Unlock() + + return a.size() +} + +func (a *addrBook) size() int { + return a.nNew + a.nOld +} + +//---------------------------------------------------------- + +// Save persists the address book to disk. +func (a *addrBook) Save() { + a.saveToFile(a.filePath) // thread safe +} + +func (a *addrBook) saveRoutine() { + defer a.wg.Done() + + saveFileTicker := time.NewTicker(dumpAddressInterval) +out: + for { + select { + case <-saveFileTicker.C: + a.saveToFile(a.filePath) + case <-a.Quit(): + break out + } + } + saveFileTicker.Stop() + a.saveToFile(a.filePath) +} + +//---------------------------------------------------------- + +func (a *addrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress { + switch bucketType { + case bucketTypeNew: + return a.bucketsNew[bucketIdx] + case bucketTypeOld: + return a.bucketsOld[bucketIdx] + default: + panic("Invalid bucket type") + } +} + +// Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full. +// NOTE: currently it always returns true. +func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) error { + // Consistency check to ensure we don't add an already known address + if ka.isOld() { + return errAddrBookOldAddressNewBucket{ka.Addr, bucketIdx} + } + + addrStr := ka.Addr.String() + bucket := a.getBucket(bucketTypeNew, bucketIdx) + + // Already exists? + if _, ok := bucket[addrStr]; ok { + return nil + } + + // Enforce max addresses. + if len(bucket) > newBucketSize { + a.Logger.Info("new bucket is full, expiring new") + a.expireNew(bucketIdx) + } + + // Add to bucket. + bucket[addrStr] = ka + // increment nNew if the peer doesnt already exist in a bucket + if ka.addBucketRef(bucketIdx) == 1 { + a.nNew++ + } + + // Add it to addrLookup + a.addrLookup[ka.ID()] = ka + return nil +} + +// Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full. +func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { + // Sanity check + if ka.isNew() { + a.Logger.Error(fmt.Sprintf("Cannot add new address to old bucket: %v", ka)) + return false + } + if len(ka.Buckets) != 0 { + a.Logger.Error(fmt.Sprintf("Cannot add already old address to another old bucket: %v", ka)) + return false + } + + addrStr := ka.Addr.String() + bucket := a.getBucket(bucketTypeOld, bucketIdx) + + // Already exists? + if _, ok := bucket[addrStr]; ok { + return true + } + + // Enforce max addresses. + if len(bucket) > oldBucketSize { + return false + } + + // Add to bucket. + bucket[addrStr] = ka + if ka.addBucketRef(bucketIdx) == 1 { + a.nOld++ + } + + // Ensure in addrLookup + a.addrLookup[ka.ID()] = ka + + return true +} + +func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { + if ka.BucketType != bucketType { + a.Logger.Error(fmt.Sprintf("Bucket type mismatch: %v", ka)) + return + } + bucket := a.getBucket(bucketType, bucketIdx) + delete(bucket, ka.Addr.String()) + if ka.removeBucketRef(bucketIdx) == 0 { + if bucketType == bucketTypeNew { + a.nNew-- + } else { + a.nOld-- + } + delete(a.addrLookup, ka.ID()) + } +} + +func (a *addrBook) removeFromAllBuckets(ka *knownAddress) { + for _, bucketIdx := range ka.Buckets { + bucket := a.getBucket(ka.BucketType, bucketIdx) + delete(bucket, ka.Addr.String()) + } + ka.Buckets = nil + if ka.BucketType == bucketTypeNew { + a.nNew-- + } else { + a.nOld-- + } + delete(a.addrLookup, ka.ID()) +} + +//---------------------------------------------------------- + +func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { + bucket := a.getBucket(bucketType, bucketIdx) + var oldest *knownAddress + for _, ka := range bucket { + if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) { + oldest = ka + } + } + return oldest +} + +// adds the address to a "new" bucket. if its already in one, +// it only adds it probabilistically +func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error { + if addr == nil || src == nil { + return ErrAddrBookNilAddr{addr, src} + } + + if err := addr.Valid(); err != nil { + return ErrAddrBookInvalidAddr{Addr: addr, AddrErr: err} + } + + if _, ok := a.badPeers[addr.ID]; ok { + return ErrAddressBanned{addr} + } + + if _, ok := a.privateIDs[addr.ID]; ok { + return ErrAddrBookPrivate{addr} + } + + if _, ok := a.privateIDs[src.ID]; ok { + return ErrAddrBookPrivateSrc{src} + } + + // TODO: we should track ourAddrs by ID and by IP:PORT and refuse both. + if _, ok := a.ourAddrs[addr.String()]; ok { + return ErrAddrBookSelf{addr} + } + + if a.routabilityStrict && !addr.Routable() { + return ErrAddrBookNonRoutable{addr} + } + + ka := a.addrLookup[addr.ID] + if ka != nil { + // If its already old and the address ID's are the same, ignore it. + // Thereby avoiding issues with a node on the network attempting to change + // the IP of a known node ID. (Which could yield an eclipse attack on the node) + if ka.isOld() && ka.Addr.ID == addr.ID { + return nil + } + // Already in max new buckets. + if len(ka.Buckets) == maxNewBucketsPerAddress { + return nil + } + // The more entries we have, the less likely we are to add more. + factor := int32(2 * len(ka.Buckets)) + if a.rand.Int31n(factor) != 0 { + return nil + } + } else { + ka = newKnownAddress(addr, src) + } + + bucket, err := a.calcNewBucket(addr, src) + if err != nil { + return err + } + return a.addToNewBucket(ka, bucket) +} + +func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddress { + var buckets []map[string]*knownAddress + switch bucketType { + case bucketTypeNew: + buckets = a.bucketsNew + case bucketTypeOld: + buckets = a.bucketsOld + default: + panic("unexpected bucketType") + } + total := 0 + for _, bucket := range buckets { + total += len(bucket) + } + addresses := make([]*knownAddress, 0, total) + for _, bucket := range buckets { + for _, ka := range bucket { + addresses = append(addresses, ka) + } + } + selection := make([]*p2p.NetAddress, 0, num) + chosenSet := make(map[string]bool, num) + rand.Shuffle(total, func(i, j int) { + addresses[i], addresses[j] = addresses[j], addresses[i] + }) + for _, addr := range addresses { + if chosenSet[addr.Addr.String()] { + continue + } + chosenSet[addr.Addr.String()] = true + selection = append(selection, addr.Addr) + if len(selection) >= num { + return selection + } + } + return selection +} + +// Make space in the new buckets by expiring the really bad entries. +// If no bad entries are available we remove the oldest. +func (a *addrBook) expireNew(bucketIdx int) { + for addrStr, ka := range a.bucketsNew[bucketIdx] { + // If an entry is bad, throw it away + if ka.isBad() { + a.Logger.Info("expire new", "msg", log.NewLazySprintf("expiring bad address %v", addrStr)) + a.removeFromBucket(ka, bucketTypeNew, bucketIdx) + return + } + } + + // If we haven't thrown out a bad entry, throw out the oldest entry + oldest := a.pickOldest(bucketTypeNew, bucketIdx) + a.removeFromBucket(oldest, bucketTypeNew, bucketIdx) +} + +// Promotes an address from new to old. If the destination bucket is full, +// demote the oldest one to a "new" bucket. +// TODO: Demote more probabilistically? +func (a *addrBook) moveToOld(ka *knownAddress) error { + // Sanity check + if ka.isOld() { + a.Logger.Error(fmt.Sprintf("Cannot promote address that is already old %v", ka)) + return nil + } + if len(ka.Buckets) == 0 { + a.Logger.Error(fmt.Sprintf("Cannot promote address that isn't in any new buckets %v", ka)) + return nil + } + + // Remove from all (new) buckets. + a.removeFromAllBuckets(ka) + // It's officially old now. + ka.BucketType = bucketTypeOld + + // Try to add it to its oldBucket destination. + oldBucketIdx, err := a.calcOldBucket(ka.Addr) + if err != nil { + return err + } + added := a.addToOldBucket(ka, oldBucketIdx) + if !added { + // No room; move the oldest to a new bucket + oldest := a.pickOldest(bucketTypeOld, oldBucketIdx) + a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx) + newBucketIdx, err := a.calcNewBucket(oldest.Addr, oldest.Src) + if err != nil { + return err + } + if err := a.addToNewBucket(oldest, newBucketIdx); err != nil { + a.Logger.Error("Error adding peer to old bucket", "err", err) + } + + // Finally, add our ka to old bucket again. + added = a.addToOldBucket(ka, oldBucketIdx) + if !added { + a.Logger.Error(fmt.Sprintf("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) + } + } + return nil +} + +func (a *addrBook) removeAddress(addr *p2p.NetAddress) { + ka := a.addrLookup[addr.ID] + if ka == nil { + return + } + a.Logger.Info("Remove address from book", "addr", addr) + a.removeFromAllBuckets(ka) +} + +func (a *addrBook) addBadPeer(addr *p2p.NetAddress, banTime time.Duration) bool { + // check it exists in addrbook + ka := a.addrLookup[addr.ID] + // check address is not already there + if ka == nil { + return false + } + + if _, alreadyBadPeer := a.badPeers[addr.ID]; !alreadyBadPeer { + // add to bad peer list + ka.ban(banTime) + a.badPeers[addr.ID] = ka + a.Logger.Info("Add address to blacklist", "addr", addr) + } + return true +} + +//--------------------------------------------------------------------- +// calculate bucket placements + +// hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets +func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) (int, error) { + data1 := []byte{} + data1 = append(data1, []byte(a.key)...) + data1 = append(data1, []byte(a.groupKey(addr))...) + data1 = append(data1, []byte(a.groupKey(src))...) + hash1, err := a.hash(data1) + if err != nil { + return 0, err + } + hash64 := binary.BigEndian.Uint64(hash1) + hash64 %= newBucketsPerGroup + var hashbuf [8]byte + binary.BigEndian.PutUint64(hashbuf[:], hash64) + data2 := []byte{} + data2 = append(data2, []byte(a.key)...) + data2 = append(data2, a.groupKey(src)...) + data2 = append(data2, hashbuf[:]...) + + hash2, err := a.hash(data2) + if err != nil { + return 0, err + } + result := int(binary.BigEndian.Uint64(hash2) % newBucketCount) + return result, nil +} + +// hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets +func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) (int, error) { + data1 := []byte{} + data1 = append(data1, []byte(a.key)...) + data1 = append(data1, []byte(addr.String())...) + hash1, err := a.hash(data1) + if err != nil { + return 0, err + } + hash64 := binary.BigEndian.Uint64(hash1) + hash64 %= oldBucketsPerGroup + var hashbuf [8]byte + binary.BigEndian.PutUint64(hashbuf[:], hash64) + data2 := []byte{} + data2 = append(data2, []byte(a.key)...) + data2 = append(data2, a.groupKey(addr)...) + data2 = append(data2, hashbuf[:]...) + + hash2, err := a.hash(data2) + if err != nil { + return 0, err + } + result := int(binary.BigEndian.Uint64(hash2) % oldBucketCount) + return result, nil +} + +// Return a string representing the network group of this address. +// This is the /16 for IPv4 (e.g. 1.2.0.0), the /32 (/36 for he.net) for IPv6, the string +// "local" for a local address and the string "unroutable" for an unroutable +// address. +func (a *addrBook) groupKey(na *p2p.NetAddress) string { + return groupKeyFor(na, a.routabilityStrict) +} + +func groupKeyFor(na *p2p.NetAddress, routabilityStrict bool) string { + if routabilityStrict && na.Local() { + return "local" + } + if routabilityStrict && !na.Routable() { + return "unroutable" + } + + if ipv4 := na.IP.To4(); ipv4 != nil { + return na.IP.Mask(net.CIDRMask(16, 32)).String() + } + + if na.RFC6145() || na.RFC6052() { + // last four bytes are the ip address + ip := na.IP[12:16] + return ip.Mask(net.CIDRMask(16, 32)).String() + } + + if na.RFC3964() { + ip := na.IP[2:6] + return ip.Mask(net.CIDRMask(16, 32)).String() + } + + if na.RFC4380() { + // teredo tunnels have the last 4 bytes as the v4 address XOR + // 0xff. + ip := net.IP(make([]byte, 4)) + for i, byte := range na.IP[12:16] { + ip[i] = byte ^ 0xff + } + return ip.Mask(net.CIDRMask(16, 32)).String() + } + + if na.OnionCatTor() { + // group is keyed off the first 4 bits of the actual onion key. + return fmt.Sprintf("tor:%d", na.IP[6]&((1<<4)-1)) + } + + // OK, so now we know ourselves to be a IPv6 address. + // bitcoind uses /32 for everything, except for Hurricane Electric's + // (he.net) IP range, which it uses /36 for. + bits := 32 + heNet := &net.IPNet{IP: net.ParseIP("2001:470::"), Mask: net.CIDRMask(32, 128)} + if heNet.Contains(na.IP) { + bits = 36 + } + ipv6Mask := net.CIDRMask(bits, 128) + return na.IP.Mask(ipv6Mask).String() +} + +func (a *addrBook) hash(b []byte) ([]byte, error) { + a.hasher.Reset() + a.hasher.Write(b) + return a.hasher.Sum(nil), nil +} diff --git a/p2p/pex/addrbook_test.go b/p2p/pex/addrbook_test.go new file mode 100644 index 0000000..a475566 --- /dev/null +++ b/p2p/pex/addrbook_test.go @@ -0,0 +1,804 @@ +package pex + +import ( + "encoding/hex" + "fmt" + "math" + "net" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/p2p" +) + +// FIXME These tests should not rely on .(*addrBook) assertions + +func TestAddrBookPickAddress(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + // 0 addresses + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + assert.Zero(t, book.Size()) + + addr := book.PickAddress(50) + assert.Nil(t, addr, "expected no address") + + randAddrs := randNetAddressPairs(t, 1) + addrSrc := randAddrs[0] + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + + // pick an address when we only have new address + addr = book.PickAddress(0) + assert.NotNil(t, addr, "expected an address") + addr = book.PickAddress(50) + assert.NotNil(t, addr, "expected an address") + addr = book.PickAddress(100) + assert.NotNil(t, addr, "expected an address") + + // pick an address when we only have old address + book.MarkGood(addrSrc.addr.ID) + addr = book.PickAddress(0) + assert.NotNil(t, addr, "expected an address") + addr = book.PickAddress(50) + assert.NotNil(t, addr, "expected an address") + + // in this case, nNew==0 but we biased 100% to new, so we return nil + addr = book.PickAddress(100) + assert.Nil(t, addr, "did not expected an address") +} + +func TestAddrBookSaveLoad(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + // 0 addresses + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + book.Save() + + book = NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + err := book.Start() + require.NoError(t, err) + + assert.True(t, book.Empty()) + + // 100 addresses + randAddrs := randNetAddressPairs(t, 100) + + for _, addrSrc := range randAddrs { + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + } + + assert.Equal(t, 100, book.Size()) + book.Save() + + book = NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + err = book.Start() + require.NoError(t, err) + + assert.Equal(t, 100, book.Size()) +} + +func TestAddrBookLookup(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + randAddrs := randNetAddressPairs(t, 100) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + for _, addrSrc := range randAddrs { + addr := addrSrc.addr + src := addrSrc.src + err := book.AddAddress(addr, src) + require.NoError(t, err) + + ka := book.HasAddress(addr) + assert.True(t, ka, "Expected to find KnownAddress %v but wasn't there.", addr) + } +} + +func TestAddrBookPromoteToOld(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + randAddrs := randNetAddressPairs(t, 100) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + for _, addrSrc := range randAddrs { + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + } + + // Attempt all addresses. + for _, addrSrc := range randAddrs { + book.MarkAttempt(addrSrc.addr) + } + + // Promote half of them + for i, addrSrc := range randAddrs { + if i%2 == 0 { + book.MarkGood(addrSrc.addr.ID) + } + } + + // TODO: do more testing :) + + selection := book.GetSelection() + t.Logf("selection: %v", selection) + + if len(selection) > book.Size() { + t.Errorf("selection could not be bigger than the book") + } + + selection = book.GetSelectionWithBias(30) + t.Logf("selection: %v", selection) + + if len(selection) > book.Size() { + t.Errorf("selection with bias could not be bigger than the book") + } + + assert.Equal(t, book.Size(), 100, "expecting book size to be 100") +} + +func TestAddrBookHandlesDuplicates(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + randAddrs := randNetAddressPairs(t, 100) + + differentSrc := randIPv4Address(t) + for _, addrSrc := range randAddrs { + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + err = book.AddAddress(addrSrc.addr, addrSrc.src) // duplicate + require.NoError(t, err) + err = book.AddAddress(addrSrc.addr, differentSrc) // different src + require.NoError(t, err) + } + + assert.Equal(t, 100, book.Size()) +} + +type netAddressPair struct { + addr *p2p.NetAddress + src *p2p.NetAddress +} + +func randNetAddressPairs(t *testing.T, n int) []netAddressPair { + randAddrs := make([]netAddressPair, n) + for i := 0; i < n; i++ { + randAddrs[i] = netAddressPair{addr: randIPv4Address(t), src: randIPv4Address(t)} + } + return randAddrs +} + +func randIPv4Address(t *testing.T) *p2p.NetAddress { + for { + ip := fmt.Sprintf("%v.%v.%v.%v", + cmtrand.Intn(254)+1, + cmtrand.Intn(255), + cmtrand.Intn(255), + cmtrand.Intn(255), + ) + port := cmtrand.Intn(65535-1) + 1 + id := p2p.ID(hex.EncodeToString(cmtrand.Bytes(p2p.IDByteLength))) + idAddr := p2p.IDAddressString(id, fmt.Sprintf("%v:%v", ip, port)) + addr, err := p2p.NewNetAddressString(idAddr) + assert.Nil(t, err, "error generating rand network address") + if addr.Routable() { + return addr + } + } +} + +func TestAddrBookRemoveAddress(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + addr := randIPv4Address(t) + err := book.AddAddress(addr, addr) + require.NoError(t, err) + assert.Equal(t, 1, book.Size()) + + book.RemoveAddress(addr) + assert.Equal(t, 0, book.Size()) + + nonExistingAddr := randIPv4Address(t) + book.RemoveAddress(nonExistingAddr) + assert.Equal(t, 0, book.Size()) +} + +func TestAddrBookGetSelectionWithOneMarkedGood(t *testing.T) { + // create a book with 10 addresses, 1 good/old and 9 new + book, fname := createAddrBookWithMOldAndNNewAddrs(t, 1, 9) + defer deleteTempFile(fname) + + addrs := book.GetSelectionWithBias(biasToSelectNewPeers) + assert.NotNil(t, addrs) + assertMOldAndNNewAddrsInSelection(t, 1, 9, addrs, book) +} + +func TestAddrBookGetSelectionWithOneNotMarkedGood(t *testing.T) { + // create a book with 10 addresses, 9 good/old and 1 new + book, fname := createAddrBookWithMOldAndNNewAddrs(t, 9, 1) + defer deleteTempFile(fname) + + addrs := book.GetSelectionWithBias(biasToSelectNewPeers) + assert.NotNil(t, addrs) + assertMOldAndNNewAddrsInSelection(t, 9, 1, addrs, book) +} + +func TestAddrBookGetSelectionReturnsNilWhenAddrBookIsEmpty(t *testing.T) { + book, fname := createAddrBookWithMOldAndNNewAddrs(t, 0, 0) + defer deleteTempFile(fname) + + addrs := book.GetSelectionWithBias(biasToSelectNewPeers) + assert.Nil(t, addrs) +} + +func TestAddrBookGetSelection(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + // 1) empty book + assert.Empty(t, book.GetSelection()) + + // 2) add one address + addr := randIPv4Address(t) + err := book.AddAddress(addr, addr) + require.NoError(t, err) + + assert.Equal(t, 1, len(book.GetSelection())) + assert.Equal(t, addr, book.GetSelection()[0]) + + // 3) add a bunch of addresses + randAddrs := randNetAddressPairs(t, 100) + for _, addrSrc := range randAddrs { + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + } + + // check there is no duplicates + addrs := make(map[string]*p2p.NetAddress) + selection := book.GetSelection() + for _, addr := range selection { + if dup, ok := addrs[addr.String()]; ok { + t.Fatalf("selection %v contains duplicates %v", selection, dup) + } + addrs[addr.String()] = addr + } + + if len(selection) > book.Size() { + t.Errorf("selection %v could not be bigger than the book", selection) + } +} + +func TestAddrBookGetSelectionWithBias(t *testing.T) { + const biasTowardsNewAddrs = 30 + + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + // 1) empty book + selection := book.GetSelectionWithBias(biasTowardsNewAddrs) + assert.Empty(t, selection) + + // 2) add one address + addr := randIPv4Address(t) + err := book.AddAddress(addr, addr) + require.NoError(t, err) + + selection = book.GetSelectionWithBias(biasTowardsNewAddrs) + assert.Equal(t, 1, len(selection)) + assert.Equal(t, addr, selection[0]) + + // 3) add a bunch of addresses + randAddrs := randNetAddressPairs(t, 100) + for _, addrSrc := range randAddrs { + err := book.AddAddress(addrSrc.addr, addrSrc.src) + require.NoError(t, err) + } + + // check there is no duplicates + addrs := make(map[string]*p2p.NetAddress) + selection = book.GetSelectionWithBias(biasTowardsNewAddrs) + for _, addr := range selection { + if dup, ok := addrs[addr.String()]; ok { + t.Fatalf("selection %v contains duplicates %v", selection, dup) + } + addrs[addr.String()] = addr + } + + if len(selection) > book.Size() { + t.Fatalf("selection %v could not be bigger than the book", selection) + } + + // 4) mark 80% of the addresses as good + randAddrsLen := len(randAddrs) + for i, addrSrc := range randAddrs { + if int((float64(i)/float64(randAddrsLen))*100) >= 20 { + book.MarkGood(addrSrc.addr.ID) + } + } + + selection = book.GetSelectionWithBias(biasTowardsNewAddrs) + + // check that ~70% of addresses returned are good + good := 0 + for _, addr := range selection { + if book.IsGood(addr) { + good++ + } + } + + got, expected := int((float64(good)/float64(len(selection)))*100), 100-biasTowardsNewAddrs + + // compute some slack to protect against small differences due to rounding: + slack := int(math.Round(float64(100) / float64(len(selection)))) + if got > expected+slack { + t.Fatalf( + "got more good peers (%% got: %d, %% expected: %d, number of good addrs: %d, total: %d)", + got, + expected, + good, + len(selection), + ) + } + if got < expected-slack { + t.Fatalf( + "got fewer good peers (%% got: %d, %% expected: %d, number of good addrs: %d, total: %d)", + got, + expected, + good, + len(selection), + ) + } +} + +func TestAddrBookHasAddress(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + addr := randIPv4Address(t) + err := book.AddAddress(addr, addr) + require.NoError(t, err) + + assert.True(t, book.HasAddress(addr)) + + book.RemoveAddress(addr) + + assert.False(t, book.HasAddress(addr)) +} + +func testCreatePrivateAddrs(t *testing.T, numAddrs int) ([]*p2p.NetAddress, []string) { + addrs := make([]*p2p.NetAddress, numAddrs) + for i := 0; i < numAddrs; i++ { + addrs[i] = randIPv4Address(t) + } + + private := make([]string, numAddrs) + for i, addr := range addrs { + private[i] = string(addr.ID) + } + return addrs, private +} + +func TestBanBadPeers(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + addr := randIPv4Address(t) + _ = book.AddAddress(addr, addr) + + book.MarkBad(addr, 1*time.Second) + // addr should not reachable + assert.False(t, book.HasAddress(addr)) + assert.True(t, book.IsBanned(addr)) + + err := book.AddAddress(addr, addr) + // book should not add address from the blacklist + assert.Error(t, err) + + time.Sleep(1 * time.Second) + book.ReinstateBadPeers() + // address should be reinstated in the new bucket + assert.EqualValues(t, 1, book.Size()) + assert.True(t, book.HasAddress(addr)) + assert.False(t, book.IsGood(addr)) +} + +func TestAddrBookEmpty(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + // Check that empty book is empty + require.True(t, book.Empty()) + // Check that book with our address is empty + book.AddOurAddress(randIPv4Address(t)) + require.True(t, book.Empty()) + // Check that book with private addrs is empty + _, privateIds := testCreatePrivateAddrs(t, 5) + book.AddPrivateIDs(privateIds) + require.True(t, book.Empty()) + + // Check that book with address is not empty + err := book.AddAddress(randIPv4Address(t), randIPv4Address(t)) + require.NoError(t, err) + require.False(t, book.Empty()) +} + +func TestPrivatePeers(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + + addrs, private := testCreatePrivateAddrs(t, 10) + book.AddPrivateIDs(private) + + // private addrs must not be added + for _, addr := range addrs { + err := book.AddAddress(addr, addr) + if assert.Error(t, err) { + _, ok := err.(ErrAddrBookPrivate) + assert.True(t, ok) + } + } + + // addrs coming from private peers must not be added + err := book.AddAddress(randIPv4Address(t), addrs[0]) + if assert.Error(t, err) { + _, ok := err.(ErrAddrBookPrivateSrc) + assert.True(t, ok) + } +} + +func testAddrBookAddressSelection(t *testing.T, bookSize int) { + // generate all combinations of old (m) and new addresses + for nBookOld := 0; nBookOld <= bookSize; nBookOld++ { + nBookNew := bookSize - nBookOld + dbgStr := fmt.Sprintf("book of size %d (new %d, old %d)", bookSize, nBookNew, nBookOld) + + // create book and get selection + book, fname := createAddrBookWithMOldAndNNewAddrs(t, nBookOld, nBookNew) + defer deleteTempFile(fname) + addrs := book.GetSelectionWithBias(biasToSelectNewPeers) + assert.NotNil(t, addrs, "%s - expected a non-nil selection", dbgStr) + nAddrs := len(addrs) + assert.NotZero(t, nAddrs, "%s - expected at least one address in selection", dbgStr) + + // check there's no nil addresses + for _, addr := range addrs { + if addr == nil { + t.Fatalf("%s - got nil address in selection %v", dbgStr, addrs) + } + } + + // XXX: shadowing + nOld, nNew := countOldAndNewAddrsInSelection(addrs, book) + + // Given: + // n - num new addrs, m - num old addrs + // k - num new addrs expected in the beginning (based on bias %) + // i=min(n, max(k,r-m)), aka expNew + // j=min(m, r-i), aka expOld + // + // We expect this layout: + // indices: 0...i-1 i...i+j-1 + // addresses: N0..Ni-1 O0..Oj-1 + // + // There is at least one partition and at most three. + var ( + k = percentageOfNum(biasToSelectNewPeers, nAddrs) + expNew = cmtmath.MinInt(nNew, cmtmath.MaxInt(k, nAddrs-nBookOld)) + expOld = cmtmath.MinInt(nOld, nAddrs-expNew) + ) + + // Verify that the number of old and new addresses are as expected + if nNew != expNew { + t.Fatalf("%s - expected new addrs %d, got %d", dbgStr, expNew, nNew) + } + if nOld != expOld { + t.Fatalf("%s - expected old addrs %d, got %d", dbgStr, expOld, nOld) + } + + // Verify that the order of addresses is as expected + // Get the sequence types and lengths of the selection + seqLens, seqTypes, err := analyseSelectionLayout(book, addrs) + assert.NoError(t, err, "%s", dbgStr) + + // Build a list with the expected lengths of partitions and another with the expected types, e.g.: + // expSeqLens = [10, 22], expSeqTypes = [1, 2] + // means we expect 10 new (type 1) addresses followed by 22 old (type 2) addresses. + var expSeqLens []int + var expSeqTypes []int + + switch { + case expOld == 0: // all new addresses + expSeqLens = []int{nAddrs} + expSeqTypes = []int{1} + case expNew == 0: // all old addresses + expSeqLens = []int{nAddrs} + expSeqTypes = []int{2} + case nAddrs-expNew-expOld == 0: // new addresses, old addresses + expSeqLens = []int{expNew, expOld} + expSeqTypes = []int{1, 2} + } + + assert.Equal(t, expSeqLens, seqLens, + "%s - expected sequence lengths of old/new %v, got %v", + dbgStr, expSeqLens, seqLens) + assert.Equal(t, expSeqTypes, seqTypes, + "%s - expected sequence types (1-new, 2-old) was %v, got %v", + dbgStr, expSeqTypes, seqTypes) + } +} + +func TestMultipleAddrBookAddressSelection(t *testing.T) { + // test books with smaller size, < N + const N = 32 + for bookSize := 1; bookSize < N; bookSize++ { + testAddrBookAddressSelection(t, bookSize) + } + + // Test for two books with sizes from following ranges + ranges := [...][]int{{33, 100}, {100, 175}} + bookSizes := make([]int, 0, len(ranges)) + for _, r := range ranges { + bookSizes = append(bookSizes, cmtrand.Intn(r[1]-r[0])+r[0]) + } + t.Logf("Testing address selection for the following book sizes %v\n", bookSizes) + for _, bookSize := range bookSizes { + testAddrBookAddressSelection(t, bookSize) + } +} + +func TestAddrBookAddDoesNotOverwriteOldIP(t *testing.T) { + fname := createTempFileName("addrbook_test") + defer deleteTempFile(fname) + + // This test creates adds a peer to the address book and marks it good + // It then attempts to override the peer's IP, by adding a peer with the same ID + // but different IP. We distinguish the IP's by "RealIP" and "OverrideAttemptIP" + peerID := "678503e6c8f50db7279c7da3cb9b072aac4bc0d5" + peerRealIP := "1.1.1.1:26656" + peerOverrideAttemptIP := "2.2.2.2:26656" + SrcAddr := "b0dd378c3fbc4c156cd6d302a799f0d2e4227201@159.89.121.174:26656" + + // There is a chance that AddAddress will ignore the new peer its given. + // So we repeat trying to override the peer several times, + // to ensure we aren't in a case that got probabilistically ignored + numOverrideAttempts := 10 + + peerRealAddr, err := p2p.NewNetAddressString(peerID + "@" + peerRealIP) + require.Nil(t, err) + + peerOverrideAttemptAddr, err := p2p.NewNetAddressString(peerID + "@" + peerOverrideAttemptIP) + require.Nil(t, err) + + src, err := p2p.NewNetAddressString(SrcAddr) + require.Nil(t, err) + + book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) + err = book.AddAddress(peerRealAddr, src) + require.Nil(t, err) + book.MarkAttempt(peerRealAddr) + book.MarkGood(peerRealAddr.ID) + + // Double check that adding a peer again doesn't error + err = book.AddAddress(peerRealAddr, src) + require.Nil(t, err) + + // Try changing ip but keeping the same node id. (change 1.1.1.1 to 2.2.2.2) + // This should just be ignored, and not error. + for i := 0; i < numOverrideAttempts; i++ { + err = book.AddAddress(peerOverrideAttemptAddr, src) + require.Nil(t, err) + } + // Now check that the IP was not overridden. + // This is done by sampling several peers from addr book + // and ensuring they all have the correct IP. + // In the expected functionality, this test should only have 1 Peer, hence will pass. + for i := 0; i < numOverrideAttempts; i++ { + selection := book.GetSelection() + for _, addr := range selection { + require.Equal(t, addr.IP, peerRealAddr.IP) + } + } +} + +func TestAddrBookGroupKey(t *testing.T) { + // non-strict routability + testCases := []struct { + name string + ip string + expKey string + }{ + // IPv4 normal. + {"ipv4 normal class a", "12.1.2.3", "12.1.0.0"}, + {"ipv4 normal class b", "173.1.2.3", "173.1.0.0"}, + {"ipv4 normal class c", "196.1.2.3", "196.1.0.0"}, + + // IPv6/IPv4 translations. + {"ipv6 rfc3964 with ipv4 encap", "2002:0c01:0203::", "12.1.0.0"}, + {"ipv6 rfc4380 toredo ipv4", "2001:0:1234::f3fe:fdfc", "12.1.0.0"}, + {"ipv6 rfc6052 well-known prefix with ipv4", "64:ff9b::0c01:0203", "12.1.0.0"}, + {"ipv6 rfc6145 translated ipv4", "::ffff:0:0c01:0203", "12.1.0.0"}, + + // Tor. + {"ipv6 tor onioncat", "fd87:d87e:eb43:1234::5678", "tor:2"}, + {"ipv6 tor onioncat 2", "fd87:d87e:eb43:1245::6789", "tor:2"}, + {"ipv6 tor onioncat 3", "fd87:d87e:eb43:1345::6789", "tor:3"}, + + // IPv6 normal. + {"ipv6 normal", "2602:100::1", "2602:100::"}, + {"ipv6 normal 2", "2602:0100::1234", "2602:100::"}, + {"ipv6 hurricane electric", "2001:470:1f10:a1::2", "2001:470:1000::"}, + {"ipv6 hurricane electric 2", "2001:0470:1f10:a1::2", "2001:470:1000::"}, + } + + for i, tc := range testCases { + nip := net.ParseIP(tc.ip) + key := groupKeyFor(p2p.NewNetAddressIPPort(nip, 26656), false) + assert.Equal(t, tc.expKey, key, "#%d", i) + } + + // strict routability + testCases = []struct { + name string + ip string + expKey string + }{ + // Local addresses. + {"ipv4 localhost", "127.0.0.1", "local"}, + {"ipv6 localhost", "::1", "local"}, + {"ipv4 zero", "0.0.0.0", "local"}, + {"ipv4 first octet zero", "0.1.2.3", "local"}, + + // Unroutable addresses. + {"ipv4 invalid bcast", "255.255.255.255", "unroutable"}, + {"ipv4 rfc1918 10/8", "10.1.2.3", "unroutable"}, + {"ipv4 rfc1918 172.16/12", "172.16.1.2", "unroutable"}, + {"ipv4 rfc1918 192.168/16", "192.168.1.2", "unroutable"}, + {"ipv6 rfc3849 2001:db8::/32", "2001:db8::1234", "unroutable"}, + {"ipv4 rfc3927 169.254/16", "169.254.1.2", "unroutable"}, + {"ipv6 rfc4193 fc00::/7", "fc00::1234", "unroutable"}, + {"ipv6 rfc4843 2001:10::/28", "2001:10::1234", "unroutable"}, + {"ipv6 rfc4862 fe80::/64", "fe80::1234", "unroutable"}, + } + + for i, tc := range testCases { + nip := net.ParseIP(tc.ip) + key := groupKeyFor(p2p.NewNetAddressIPPort(nip, 26656), true) + assert.Equal(t, tc.expKey, key, "#%d", i) + } +} + +func assertMOldAndNNewAddrsInSelection(t *testing.T, m, n int, addrs []*p2p.NetAddress, book *addrBook) { + nOld, nNew := countOldAndNewAddrsInSelection(addrs, book) + assert.Equal(t, m, nOld, "old addresses") + assert.Equal(t, n, nNew, "new addresses") +} + +func createTempFileName(prefix string) string { + f, err := os.CreateTemp("", prefix) + if err != nil { + panic(err) + } + fname := f.Name() + err = f.Close() + if err != nil { + panic(err) + } + return fname +} + +func deleteTempFile(fname string) { + err := os.Remove(fname) + if err != nil { + panic(err) + } +} + +func createAddrBookWithMOldAndNNewAddrs(t *testing.T, nOld, nNew int) (book *addrBook, fname string) { + fname = createTempFileName("addrbook_test") + + book = NewAddrBook(fname, true).(*addrBook) + book.SetLogger(log.TestingLogger()) + assert.Zero(t, book.Size()) + + randAddrs := randNetAddressPairs(t, nOld) + for _, addr := range randAddrs { + err := book.AddAddress(addr.addr, addr.src) + require.NoError(t, err) + book.MarkGood(addr.addr.ID) + } + + randAddrs = randNetAddressPairs(t, nNew) + for _, addr := range randAddrs { + err := book.AddAddress(addr.addr, addr.src) + require.NoError(t, err) + } + + return +} + +func countOldAndNewAddrsInSelection(addrs []*p2p.NetAddress, book *addrBook) (nOld, nNew int) { + for _, addr := range addrs { + if book.IsGood(addr) { + nOld++ + } else { + nNew++ + } + } + return +} + +// Analyze the layout of the selection specified by 'addrs' +// Returns: +// - seqLens - the lengths of the sequences of addresses of same type +// - seqTypes - the types of sequences in selection +func analyseSelectionLayout(book *addrBook, addrs []*p2p.NetAddress) (seqLens, seqTypes []int, err error) { + // address types are: 0 - nil, 1 - new, 2 - old + var ( + prevType = 0 + currentSeqLen = 0 + ) + + for _, addr := range addrs { + addrType := 0 + if book.IsGood(addr) { + addrType = 2 + } else { + addrType = 1 + } + if addrType != prevType && prevType != 0 { + seqLens = append(seqLens, currentSeqLen) + seqTypes = append(seqTypes, prevType) + currentSeqLen = 0 + } + currentSeqLen++ + prevType = addrType + } + + seqLens = append(seqLens, currentSeqLen) + seqTypes = append(seqTypes, prevType) + + return +} diff --git a/p2p/pex/bench_test.go b/p2p/pex/bench_test.go new file mode 100644 index 0000000..3adb52c --- /dev/null +++ b/p2p/pex/bench_test.go @@ -0,0 +1,24 @@ +package pex + +import ( + "testing" + + "github.com/cometbft/cometbft/p2p" +) + +func BenchmarkAddrBook_hash(b *testing.B) { + book := &addrBook{ + ourAddrs: make(map[string]struct{}), + privateIDs: make(map[p2p.ID]struct{}), + addrLookup: make(map[p2p.ID]*knownAddress), + badPeers: make(map[p2p.ID]*knownAddress), + filePath: "", + routabilityStrict: true, + } + book.init() + msg := []byte(`foobar`) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, _ = book.hash(msg) + } +} diff --git a/p2p/pex/errors.go b/p2p/pex/errors.go new file mode 100644 index 0000000..0a2eccf --- /dev/null +++ b/p2p/pex/errors.go @@ -0,0 +1,89 @@ +package pex + +import ( + "errors" + "fmt" + + "github.com/cometbft/cometbft/p2p" +) + +type ErrAddrBookNonRoutable struct { + Addr *p2p.NetAddress +} + +func (err ErrAddrBookNonRoutable) Error() string { + return fmt.Sprintf("Cannot add non-routable address %v", err.Addr) +} + +type errAddrBookOldAddressNewBucket struct { + Addr *p2p.NetAddress + BucketID int +} + +func (err errAddrBookOldAddressNewBucket) Error() string { + return fmt.Sprintf("failed consistency check!"+ + " Cannot add pre-existing address %v into new bucket %v", + err.Addr, err.BucketID) +} + +type ErrAddrBookSelf struct { + Addr *p2p.NetAddress +} + +func (err ErrAddrBookSelf) Error() string { + return fmt.Sprintf("Cannot add ourselves with address %v", err.Addr) +} + +type ErrAddrBookPrivate struct { + Addr *p2p.NetAddress +} + +func (err ErrAddrBookPrivate) Error() string { + return fmt.Sprintf("Cannot add private peer with address %v", err.Addr) +} + +func (err ErrAddrBookPrivate) PrivateAddr() bool { + return true +} + +type ErrAddrBookPrivateSrc struct { + Src *p2p.NetAddress +} + +func (err ErrAddrBookPrivateSrc) Error() string { + return fmt.Sprintf("Cannot add peer coming from private peer with address %v", err.Src) +} + +func (err ErrAddrBookPrivateSrc) PrivateAddr() bool { + return true +} + +type ErrAddrBookNilAddr struct { + Addr *p2p.NetAddress + Src *p2p.NetAddress +} + +func (err ErrAddrBookNilAddr) Error() string { + return fmt.Sprintf("Cannot add a nil address. Got (addr, src) = (%v, %v)", err.Addr, err.Src) +} + +type ErrAddrBookInvalidAddr struct { + Addr *p2p.NetAddress + AddrErr error +} + +func (err ErrAddrBookInvalidAddr) Error() string { + return fmt.Sprintf("Cannot add invalid address %v: %v", err.Addr, err.AddrErr) +} + +// ErrAddressBanned is thrown when the address has been banned and therefore cannot be used +type ErrAddressBanned struct { + Addr *p2p.NetAddress +} + +func (err ErrAddressBanned) Error() string { + return fmt.Sprintf("Address: %v is currently banned", err.Addr) +} + +// ErrUnsolicitedList is thrown when a peer provides a list of addresses that have not been asked for. +var ErrUnsolicitedList = errors.New("unsolicited pexAddrsMessage") diff --git a/p2p/pex/file.go b/p2p/pex/file.go new file mode 100644 index 0000000..27be4af --- /dev/null +++ b/p2p/pex/file.go @@ -0,0 +1,83 @@ +package pex + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/cometbft/cometbft/libs/tempfile" +) + +/* Loading & Saving */ + +type addrBookJSON struct { + Key string `json:"key"` + Addrs []*knownAddress `json:"addrs"` +} + +func (a *addrBook) saveToFile(filePath string) { + a.mtx.Lock() + defer a.mtx.Unlock() + + a.Logger.Info("Saving AddrBook to file", "size", a.size()) + + addrs := make([]*knownAddress, 0, len(a.addrLookup)) + for _, ka := range a.addrLookup { + addrs = append(addrs, ka) + } + aJSON := &addrBookJSON{ + Key: a.key, + Addrs: addrs, + } + + jsonBytes, err := json.MarshalIndent(aJSON, "", "\t") + if err != nil { + a.Logger.Error("Failed to save AddrBook to file", "err", err) + return + } + err = tempfile.WriteFileAtomic(filePath, jsonBytes, 0644) + if err != nil { + a.Logger.Error("Failed to save AddrBook to file", "file", filePath, "err", err) + } +} + +// Returns false if file does not exist. +// cmn.Panics if file is corrupt. +func (a *addrBook) loadFromFile(filePath string) bool { + // If doesn't exist, do nothing. + _, err := os.Stat(filePath) + if os.IsNotExist(err) { + return false + } + + // Load addrBookJSON{} + r, err := os.Open(filePath) + if err != nil { + panic(fmt.Sprintf("Error opening file %s: %v", filePath, err)) + } + defer r.Close() + aJSON := &addrBookJSON{} + dec := json.NewDecoder(r) + err = dec.Decode(aJSON) + if err != nil { + panic(fmt.Sprintf("Error reading file %s: %v", filePath, err)) + } + + // Restore all the fields... + // Restore the key + a.key = aJSON.Key + // Restore .bucketsNew & .bucketsOld + for _, ka := range aJSON.Addrs { + for _, bucketIndex := range ka.Buckets { + bucket := a.getBucket(ka.BucketType, bucketIndex) + bucket[ka.Addr.String()] = ka + } + a.addrLookup[ka.ID()] = ka + if ka.BucketType == bucketTypeNew { + a.nNew++ + } else { + a.nOld++ + } + } + return true +} diff --git a/p2p/pex/known_address.go b/p2p/pex/known_address.go new file mode 100644 index 0000000..8613ebd --- /dev/null +++ b/p2p/pex/known_address.go @@ -0,0 +1,139 @@ +package pex + +import ( + "time" + + "github.com/cometbft/cometbft/p2p" +) + +// knownAddress tracks information about a known network address +// that is used to determine how viable an address is. +type knownAddress struct { + Addr *p2p.NetAddress `json:"addr"` + Src *p2p.NetAddress `json:"src"` + Buckets []int `json:"buckets"` + Attempts int32 `json:"attempts"` + BucketType byte `json:"bucket_type"` + LastAttempt time.Time `json:"last_attempt"` + LastSuccess time.Time `json:"last_success"` + LastBanTime time.Time `json:"last_ban_time"` +} + +func newKnownAddress(addr *p2p.NetAddress, src *p2p.NetAddress) *knownAddress { + return &knownAddress{ + Addr: addr, + Src: src, + Attempts: 0, + LastAttempt: time.Now(), + BucketType: bucketTypeNew, + Buckets: nil, + } +} + +func (ka *knownAddress) ID() p2p.ID { + return ka.Addr.ID +} + +func (ka *knownAddress) isOld() bool { + return ka.BucketType == bucketTypeOld +} + +func (ka *knownAddress) isNew() bool { + return ka.BucketType == bucketTypeNew +} + +func (ka *knownAddress) markAttempt() { + now := time.Now() + ka.LastAttempt = now + ka.Attempts++ +} + +func (ka *knownAddress) markGood() { + now := time.Now() + ka.LastAttempt = now + ka.Attempts = 0 + ka.LastSuccess = now +} + +func (ka *knownAddress) ban(banTime time.Duration) { + if ka.LastBanTime.Before(time.Now().Add(banTime)) { + ka.LastBanTime = time.Now().Add(banTime) + } +} + +func (ka *knownAddress) isBanned() bool { + return ka.LastBanTime.After(time.Now()) +} + +func (ka *knownAddress) addBucketRef(bucketIdx int) int { + for _, bucket := range ka.Buckets { + if bucket == bucketIdx { + // TODO refactor to return error? + // log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka)) + return -1 + } + } + ka.Buckets = append(ka.Buckets, bucketIdx) + return len(ka.Buckets) +} + +func (ka *knownAddress) removeBucketRef(bucketIdx int) int { + buckets := []int{} + for _, bucket := range ka.Buckets { + if bucket != bucketIdx { + buckets = append(buckets, bucket) + } + } + if len(buckets) != len(ka.Buckets)-1 { + // TODO refactor to return error? + // log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka)) + return -1 + } + ka.Buckets = buckets + return len(ka.Buckets) +} + +/* +An address is bad if the address in question is a New address, has not been tried in the last +minute, and meets one of the following criteria: + +1) It claims to be from the future +2) It hasn't been seen in over a week +3) It has failed at least three times and never succeeded +4) It has failed ten times in the last week + +All addresses that meet these criteria are assumed to be worthless and not +worth keeping hold of. +*/ +func (ka *knownAddress) isBad() bool { + // Is Old --> good + if ka.BucketType == bucketTypeOld { + return false + } + + // Has been attempted in the last minute --> good + if ka.LastAttempt.After(time.Now().Add(-1 * time.Minute)) { + return false + } + + // TODO: From the future? + + // Too old? + // TODO: should be a timestamp of last seen, not just last attempt + if ka.LastAttempt.Before(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) { + return true + } + + // Never succeeded? + if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries { + return true + } + + // Hasn't succeeded in too long? + if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) && + ka.Attempts >= maxFailures { + return true + } + + return false +} diff --git a/p2p/pex/params.go b/p2p/pex/params.go new file mode 100644 index 0000000..8e6b25e --- /dev/null +++ b/p2p/pex/params.go @@ -0,0 +1,55 @@ +package pex + +import "time" + +const ( + // addresses under which the address manager will claim to need more addresses. + needAddressThreshold = 1000 + + // interval used to dump the address cache to disk for future use. + dumpAddressInterval = time.Minute * 2 + + // max addresses in each old address bucket. + oldBucketSize = 64 + + // buckets we split old addresses over. + oldBucketCount = 64 + + // max addresses in each new address bucket. + newBucketSize = 64 + + // buckets that we spread new addresses over. + newBucketCount = 256 + + // old buckets over which an address group will be spread. + oldBucketsPerGroup = 4 + + // new buckets over which a source address group will be spread. + newBucketsPerGroup = 32 + + // buckets a frequently seen new address may end up in. + maxNewBucketsPerAddress = 4 + + // days before which we assume an address has vanished + // if we have not seen it announced in that long. + numMissingDays = 7 + + // tries without a single success before we assume an address is bad. + numRetries = 3 + + // max failures we will accept without a success before considering an address bad. + maxFailures = 10 // ? + + // days since the last success before we will consider evicting an address. + minBadDays = 7 + + // % of total addresses known returned by GetSelection. + getSelectionPercent = 23 + + // min addresses that must be returned by GetSelection. Useful for bootstrapping. + minGetSelection = 32 + + // max addresses returned by GetSelection + // NOTE: this must match "maxMsgSize" + maxGetSelection = 250 +) diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go new file mode 100644 index 0000000..5eee9c6 --- /dev/null +++ b/p2p/pex/pex_reactor.go @@ -0,0 +1,755 @@ +package pex + +import ( + "errors" + "fmt" + "sync" + "time" + + "github.com/cometbft/cometbft/libs/cmap" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/conn" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +type Peer = p2p.Peer + +const ( + // PexChannel is a channel for PEX messages + PexChannel = byte(0x00) + + // over-estimate of max NetAddress size + // hexID (40) + IP (16) + Port (2) + Name (100) ... + // NOTE: dont use massive DNS name .. + maxAddressSize = 256 + + // NOTE: amplificaiton factor! + // small request results in up to maxMsgSize response + maxMsgSize = maxAddressSize * maxGetSelection + + // ensure we have enough peers + defaultEnsurePeersPeriod = 30 * time.Second + + // Seed/Crawler constants + + // minTimeBetweenCrawls is a minimum time between attempts to crawl a peer. + minTimeBetweenCrawls = 2 * time.Minute + + // check some peers every this + crawlPeerPeriod = 30 * time.Second + + maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h) + + // if node connects to seed, it does not have any trusted peers. + // Especially in the beginning, node should have more trusted peers than + // untrusted. + biasToSelectNewPeers = 30 // 70 to select good peers + + // if a peer is marked bad, it will be banned for at least this time period + defaultBanTime = 24 * time.Hour +) + +type errMaxAttemptsToDial struct{} + +func (e errMaxAttemptsToDial) Error() string { + return fmt.Sprintf("reached max attempts %d to dial", maxAttemptsToDial) +} + +type errTooEarlyToDial struct { + backoffDuration time.Duration + lastDialed time.Time +} + +func (e errTooEarlyToDial) Error() string { + return fmt.Sprintf( + "too early to dial (backoff duration: %d, last dialed: %v, time since: %v)", + e.backoffDuration, e.lastDialed, time.Since(e.lastDialed)) +} + +// Reactor handles PEX (peer exchange) and ensures that an +// adequate number of peers are connected to the switch. +// +// It uses `AddrBook` (address book) to store `NetAddress`es of the peers. +// +// ## Preventing abuse +// +// Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too. +// Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod. +type Reactor struct { + p2p.BaseReactor + + book AddrBook + config *ReactorConfig + ensurePeersCh chan struct{} // Wakes up ensurePeersRoutine() + ensurePeersPeriod time.Duration // TODO: should go in the config + + // maps to prevent abuse + requestsSent *cmap.CMap // ID->struct{}: unanswered send requests + lastReceivedRequests *cmap.CMap // ID->time.Time: last time peer requested from us + + seedAddrs []*p2p.NetAddress + + attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)} + + // seed/crawled mode fields + crawlPeerInfos map[p2p.ID]crawlPeerInfo +} + +func (r *Reactor) minReceiveRequestInterval() time.Duration { + // NOTE: must be less than ensurePeersPeriod, otherwise we'll request + // peers too quickly from others and they'll think we're bad! + return r.ensurePeersPeriod / 3 +} + +// ReactorConfig holds reactor specific configuration data. +type ReactorConfig struct { + // Seed/Crawler mode + SeedMode bool + + // We want seeds to only advertise good peers. Therefore they should wait at + // least as long as we expect it to take for a peer to become good before + // disconnecting. + SeedDisconnectWaitPeriod time.Duration + + // Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) + PersistentPeersMaxDialPeriod time.Duration + + // Seeds is a list of addresses reactor may use + // if it can't connect to peers in the addrbook. + Seeds []string +} + +type _attemptsToDial struct { + number int + lastDialed time.Time +} + +// NewReactor creates new PEX reactor. +func NewReactor(b AddrBook, config *ReactorConfig) *Reactor { + r := &Reactor{ + book: b, + config: config, + ensurePeersCh: make(chan struct{}), + ensurePeersPeriod: defaultEnsurePeersPeriod, + requestsSent: cmap.NewCMap(), + lastReceivedRequests: cmap.NewCMap(), + crawlPeerInfos: make(map[p2p.ID]crawlPeerInfo), + } + r.BaseReactor = *p2p.NewBaseReactor("PEX", r) + return r +} + +// OnStart implements BaseService +func (r *Reactor) OnStart() error { + err := r.book.Start() + if err != nil && err != service.ErrAlreadyStarted { + return err + } + + numOnline, seedAddrs, err := r.checkSeeds() + if err != nil { + return err + } else if numOnline == 0 && r.book.Empty() { + return errors.New("address book is empty and couldn't resolve any seed nodes") + } + + r.seedAddrs = seedAddrs + + // Check if this node should run + // in seed/crawler mode + if r.config.SeedMode { + go r.crawlPeersRoutine() + } else { + go r.ensurePeersRoutine() + } + return nil +} + +// OnStop implements BaseService +func (r *Reactor) OnStop() { + if err := r.book.Stop(); err != nil { + r.Logger.Error("Error stopping address book", "err", err) + } +} + +// GetChannels implements Reactor +func (r *Reactor) GetChannels() []*conn.ChannelDescriptor { + return []*conn.ChannelDescriptor{ + { + ID: PexChannel, + Priority: 1, + SendQueueCapacity: 10, + RecvMessageCapacity: maxMsgSize, + MessageType: &tmp2p.Message{}, + }, + } +} + +// AddPeer implements Reactor by adding peer to the address book (if inbound) +// or by requesting more addresses (if outbound). +func (r *Reactor) AddPeer(p Peer) { + if p.IsOutbound() { + // For outbound peers, the address is already in the books - + // either via DialPeersAsync or r.Receive. + // Ask it for more peers if we need. + if r.book.NeedMoreAddrs() { + r.RequestAddrs(p) + } + } else { + // inbound peer is its own source + addr, err := p.NodeInfo().NetAddress() + if err != nil { + r.Logger.Error("Failed to get peer NetAddress", "err", err, "peer", p) + return + } + + // Make it explicit that addr and src are the same for an inbound peer. + src := addr + + // add to book. dont RequestAddrs right away because + // we don't trust inbound as much - let ensurePeersRoutine handle it. + err = r.book.AddAddress(addr, src) + r.logErrAddrBook(err) + } +} + +// RemovePeer implements Reactor by resetting peer's requests info. +func (r *Reactor) RemovePeer(p Peer, _ interface{}) { + id := string(p.ID()) + r.requestsSent.Delete(id) + r.lastReceivedRequests.Delete(id) +} + +func (r *Reactor) logErrAddrBook(err error) { + if err != nil { + switch err.(type) { + case ErrAddrBookNilAddr: + r.Logger.Error("Failed to add new address", "err", err) + default: + // non-routable, self, full book, private, etc. + r.Logger.Debug("Failed to add new address", "err", err) + } + } +} + +// Receive implements Reactor by handling incoming PEX messages. +func (r *Reactor) Receive(e p2p.Envelope) { + r.Logger.Debug("Received message", "src", e.Src, "chId", e.ChannelID, "msg", e.Message) + + switch msg := e.Message.(type) { + case *tmp2p.PexRequest: + + // NOTE: this is a prime candidate for amplification attacks, + // so it's important we + // 1) restrict how frequently peers can request + // 2) limit the output size + + // If we're a seed and this is an inbound peer, + // respond once and disconnect. + if r.config.SeedMode && !e.Src.IsOutbound() { + id := string(e.Src.ID()) + v := r.lastReceivedRequests.Get(id) + if v != nil { + // FlushStop/StopPeer are already + // running in a go-routine. + return + } + r.lastReceivedRequests.Set(id, time.Now()) + + // Send addrs and disconnect + r.SendAddrs(e.Src, r.book.GetSelectionWithBias(biasToSelectNewPeers)) + go func() { + // In a go-routine so it doesn't block .Receive. + e.Src.FlushStop() + r.Switch.StopPeerGracefully(e.Src) + }() + + } else { + // Check we're not receiving requests too frequently. + if err := r.receiveRequest(e.Src); err != nil { + r.Switch.StopPeerForError(e.Src, err) + r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime) + return + } + r.SendAddrs(e.Src, r.book.GetSelection()) + } + + case *tmp2p.PexAddrs: + // If we asked for addresses, add them to the book + addrs, err := p2p.NetAddressesFromProto(msg.Addrs) + if err != nil { + r.Switch.StopPeerForError(e.Src, err) + r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime) + return + } + err = r.ReceiveAddrs(addrs, e.Src) + if err != nil { + r.Switch.StopPeerForError(e.Src, err) + if err == ErrUnsolicitedList { + r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime) + } + return + } + + default: + r.Logger.Error(fmt.Sprintf("Unknown message type %T", msg)) + } +} + +// enforces a minimum amount of time between requests +func (r *Reactor) receiveRequest(src Peer) error { + id := string(src.ID()) + v := r.lastReceivedRequests.Get(id) + if v == nil { + // initialize with empty time + lastReceived := time.Time{} + r.lastReceivedRequests.Set(id, lastReceived) + return nil + } + + lastReceived := v.(time.Time) + if lastReceived.Equal(time.Time{}) { + // first time gets a free pass. then we start tracking the time + lastReceived = time.Now() + r.lastReceivedRequests.Set(id, lastReceived) + return nil + } + + now := time.Now() + minInterval := r.minReceiveRequestInterval() + if now.Sub(lastReceived) < minInterval { + return fmt.Errorf( + "peer (%v) sent next PEX request too soon. lastReceived: %v, now: %v, minInterval: %v. Disconnecting", + src.ID(), + lastReceived, + now, + minInterval, + ) + } + r.lastReceivedRequests.Set(id, now) + return nil +} + +// RequestAddrs asks peer for more addresses if we do not already have a +// request out for this peer. +func (r *Reactor) RequestAddrs(p Peer) { + id := string(p.ID()) + if r.requestsSent.Has(id) { + return + } + r.Logger.Debug("Request addrs", "from", p) + r.requestsSent.Set(id, struct{}{}) + p.Send(p2p.Envelope{ + ChannelID: PexChannel, + Message: &tmp2p.PexRequest{}, + }) +} + +// ReceiveAddrs adds the given addrs to the addrbook if theres an open +// request for this peer and deletes the open request. +// If there's no open request for the src peer, it returns an error. +func (r *Reactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error { + id := string(src.ID()) + if !r.requestsSent.Has(id) { + return ErrUnsolicitedList + } + r.requestsSent.Delete(id) + + srcAddr, err := src.NodeInfo().NetAddress() + if err != nil { + return err + } + + for _, netAddr := range addrs { + // NOTE: we check netAddr validity and routability in book#AddAddress. + err = r.book.AddAddress(netAddr, srcAddr) + if err != nil { + r.logErrAddrBook(err) + // XXX: should we be strict about incoming data and disconnect from a + // peer here too? + continue + } + } + + // Try to connect to addresses coming from a seed node without waiting (#2093) + for _, seedAddr := range r.seedAddrs { + if seedAddr.Equals(srcAddr) { + select { + case r.ensurePeersCh <- struct{}{}: + default: + } + break + } + } + + return nil +} + +// SendAddrs sends addrs to the peer. +func (r *Reactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) { + e := p2p.Envelope{ + ChannelID: PexChannel, + Message: &tmp2p.PexAddrs{Addrs: p2p.NetAddressesToProto(netAddrs)}, + } + p.Send(e) +} + +// SetEnsurePeersPeriod sets period to ensure peers connected. +func (r *Reactor) SetEnsurePeersPeriod(d time.Duration) { + r.ensurePeersPeriod = d +} + +// Ensures that sufficient peers are connected. (continuous) +func (r *Reactor) ensurePeersRoutine() { + var ( + seed = cmtrand.NewRand() + jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds()) + ) + + // Randomize first round of communication to avoid thundering herd. + // If no peers are present directly start connecting so we guarantee swift + // setup with the help of configured seeds. + if r.nodeHasSomePeersOrDialingAny() { + time.Sleep(time.Duration(jitter)) + } + + // fire once immediately. + // ensures we dial the seeds right away if the book is empty + r.ensurePeers(true) + + // fire periodically + ticker := time.NewTicker(r.ensurePeersPeriod) + for { + select { + case <-ticker.C: + r.ensurePeers(true) + case <-r.ensurePeersCh: + r.ensurePeers(false) + case <-r.Quit(): + ticker.Stop() + return + } + } +} + +// ensurePeers ensures that sufficient peers are connected. (once) +// +// heuristic that we haven't perfected yet, or, perhaps is manually edited by +// the node operator. It should not be used to compute what addresses are +// already connected or not. +func (r *Reactor) ensurePeers(ensurePeersPeriodElapsed bool) { + var ( + out, in, dial = r.Switch.NumPeers() + numToDial = r.Switch.MaxNumOutboundPeers() - (out + dial) + ) + r.Logger.Info( + "Ensure peers", + "numOutPeers", out, + "numInPeers", in, + "numDialing", dial, + "numToDial", numToDial, + ) + + if numToDial <= 0 { + return + } + + // bias to prefer more vetted peers when we have fewer connections. + // not perfect, but somewhate ensures that we prioritize connecting to more-vetted + // NOTE: range here is [10, 90]. Too high ? + newBias := cmtmath.MinInt(out, 8)*10 + 10 + + toDial := make(map[p2p.ID]*p2p.NetAddress) + // Try maxAttempts times to pick numToDial addresses to dial + maxAttempts := numToDial * 3 + + for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ { + try := r.book.PickAddress(newBias) + if try == nil { + continue + } + if _, selected := toDial[try.ID]; selected { + continue + } + if r.Switch.IsDialingOrExistingAddress(try) { + continue + } + // TODO: consider moving some checks from toDial into here + // so we don't even consider dialing peers that we want to wait + // before dialing again, or have dialed too many times already + toDial[try.ID] = try + } + + // Dial picked addresses + for _, addr := range toDial { + go func(addr *p2p.NetAddress) { + err := r.dialPeer(addr) + if err != nil { + switch err.(type) { + case errMaxAttemptsToDial, errTooEarlyToDial: + r.Logger.Debug(err.Error(), "addr", addr) + default: + r.Logger.Debug(err.Error(), "addr", addr) + } + } + }(addr) + } + + if r.book.NeedMoreAddrs() { + // Check if banned nodes can be reinstated + r.book.ReinstateBadPeers() + } + + if r.book.NeedMoreAddrs() { + + // 1) Pick a random peer and ask for more. + peers := r.Switch.Peers().List() + peersCount := len(peers) + if peersCount > 0 && ensurePeersPeriodElapsed { + peer := peers[cmtrand.Int()%peersCount] + r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer) + r.RequestAddrs(peer) + } + + // 2) Dial seeds if we are not dialing anyone. + // This is done in addition to asking a peer for addresses to work-around + // peers not participating in PEX. + if len(toDial) == 0 { + r.Logger.Info("No addresses to dial. Falling back to seeds") + r.dialSeeds() + } + } +} + +func (r *Reactor) dialAttemptsInfo(addr *p2p.NetAddress) (attempts int, lastDialed time.Time) { + _attempts, ok := r.attemptsToDial.Load(addr.DialString()) + if !ok { + return + } + atd := _attempts.(_attemptsToDial) + return atd.number, atd.lastDialed +} + +func (r *Reactor) dialPeer(addr *p2p.NetAddress) error { + attempts, lastDialed := r.dialAttemptsInfo(addr) + if !r.Switch.IsPeerPersistent(addr) && attempts > maxAttemptsToDial { + r.book.MarkBad(addr, defaultBanTime) + return errMaxAttemptsToDial{} + } + + // exponential backoff if it's not our first attempt to dial given address + if attempts > 0 { + jitter := time.Duration(cmtrand.Float64() * float64(time.Second)) // 1s == (1e9 ns) + backoffDuration := jitter + ((1 << uint(attempts)) * time.Second) + backoffDuration = r.maxBackoffDurationForPeer(addr, backoffDuration) + sinceLastDialed := time.Since(lastDialed) + if sinceLastDialed < backoffDuration { + return errTooEarlyToDial{backoffDuration, lastDialed} + } + } + + err := r.Switch.DialPeerWithAddress(addr) + if err != nil { + if _, ok := err.(p2p.ErrCurrentlyDialingOrExistingAddress); ok { + return err + } + + markAddrInBookBasedOnErr(addr, r.book, err) + switch err.(type) { + case p2p.ErrSwitchAuthenticationFailure: + // NOTE: addr is removed from addrbook in markAddrInBookBasedOnErr + r.attemptsToDial.Delete(addr.DialString()) + default: + r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()}) + } + return fmt.Errorf("dialing failed (attempts: %d): %w", attempts+1, err) + } + + // cleanup any history + r.attemptsToDial.Delete(addr.DialString()) + return nil +} + +// maxBackoffDurationForPeer caps the backoff duration for persistent peers. +func (r *Reactor) maxBackoffDurationForPeer(addr *p2p.NetAddress, planned time.Duration) time.Duration { + if r.config.PersistentPeersMaxDialPeriod > 0 && + planned > r.config.PersistentPeersMaxDialPeriod && + r.Switch.IsPeerPersistent(addr) { + return r.config.PersistentPeersMaxDialPeriod + } + return planned +} + +// checkSeeds checks that addresses are well formed. +// Returns number of seeds we can connect to, along with all seeds addrs. +// return err if user provided any badly formatted seed addresses. +// Doesn't error if the seed node can't be reached. +// numOnline returns -1 if no seed nodes were in the initial configuration. +func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err error) { + lSeeds := len(r.config.Seeds) + if lSeeds == 0 { + return -1, nil, nil + } + netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds) + numOnline = lSeeds - len(errs) + for _, err := range errs { + switch e := err.(type) { + case p2p.ErrNetAddressLookup: + r.Logger.Error("Connecting to seed failed", "err", e) + default: + return 0, nil, fmt.Errorf("seed node configuration has error: %w", e) + } + } + return numOnline, netAddrs, nil +} + +// randomly dial seeds until we connect to one or exhaust them +func (r *Reactor) dialSeeds() { + perm := cmtrand.Perm(len(r.seedAddrs)) + // perm := r.Switch.rng.Perm(lSeeds) + for _, i := range perm { + // dial a random seed + seedAddr := r.seedAddrs[i] + err := r.Switch.DialPeerWithAddress(seedAddr) + + switch err.(type) { + case nil, p2p.ErrCurrentlyDialingOrExistingAddress: + return + } + r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr) + } + // do not write error message if there were no seeds specified in config + if len(r.seedAddrs) > 0 { + r.Switch.Logger.Error("Couldn't connect to any seeds") + } +} + +// AttemptsToDial returns the number of attempts to dial specific address. It +// returns 0 if never attempted or successfully connected. +func (r *Reactor) AttemptsToDial(addr *p2p.NetAddress) int { + lAttempts, attempted := r.attemptsToDial.Load(addr.DialString()) + if attempted { + return lAttempts.(_attemptsToDial).number + } + return 0 +} + +//---------------------------------------------------------- + +// Explores the network searching for more peers. (continuous) +// Seed/Crawler Mode causes this node to quickly disconnect +// from peers, except other seed nodes. +func (r *Reactor) crawlPeersRoutine() { + // If we have any seed nodes, consult them first + if len(r.seedAddrs) > 0 { + r.dialSeeds() + } else { + // Do an initial crawl + r.crawlPeers(r.book.GetSelection()) + } + + // Fire periodically + ticker := time.NewTicker(crawlPeerPeriod) + + for { + select { + case <-ticker.C: + r.attemptDisconnects() + r.crawlPeers(r.book.GetSelection()) + r.cleanupCrawlPeerInfos() + case <-r.Quit(): + return + } + } +} + +// nodeHasSomePeersOrDialingAny returns true if the node is connected to some +// peers or dialing them currently. +func (r *Reactor) nodeHasSomePeersOrDialingAny() bool { + out, in, dial := r.Switch.NumPeers() + return out+in+dial > 0 +} + +// crawlPeerInfo handles temporary data needed for the network crawling +// performed during seed/crawler mode. +type crawlPeerInfo struct { + Addr *p2p.NetAddress `json:"addr"` + // The last time we crawled the peer or attempted to do so. + LastCrawled time.Time `json:"last_crawled"` +} + +// crawlPeers will crawl the network looking for new peer addresses. +func (r *Reactor) crawlPeers(addrs []*p2p.NetAddress) { + now := time.Now() + + for _, addr := range addrs { + peerInfo, ok := r.crawlPeerInfos[addr.ID] + + // Do not attempt to connect with peers we recently crawled. + if ok && now.Sub(peerInfo.LastCrawled) < minTimeBetweenCrawls { + continue + } + + // Record crawling attempt. + r.crawlPeerInfos[addr.ID] = crawlPeerInfo{ + Addr: addr, + LastCrawled: now, + } + + err := r.dialPeer(addr) + if err != nil { + switch err.(type) { + case errMaxAttemptsToDial, errTooEarlyToDial, p2p.ErrCurrentlyDialingOrExistingAddress: + r.Logger.Debug(err.Error(), "addr", addr) + default: + r.Logger.Debug(err.Error(), "addr", addr) + } + continue + } + + peer := r.Switch.Peers().Get(addr.ID) + if peer != nil { + r.RequestAddrs(peer) + } + } +} + +func (r *Reactor) cleanupCrawlPeerInfos() { + for id, info := range r.crawlPeerInfos { + // If we did not crawl a peer for 24 hours, it means the peer was removed + // from the addrbook => remove + // + // 10000 addresses / maxGetSelection = 40 cycles to get all addresses in + // the ideal case, + // 40 * crawlPeerPeriod ~ 20 minutes + if time.Since(info.LastCrawled) > 24*time.Hour { + delete(r.crawlPeerInfos, id) + } + } +} + +// attemptDisconnects checks if we've been with each peer long enough to disconnect +func (r *Reactor) attemptDisconnects() { + for _, peer := range r.Switch.Peers().List() { + if peer.Status().Duration < r.config.SeedDisconnectWaitPeriod { + continue + } + if peer.IsPersistent() { + continue + } + r.Switch.StopPeerGracefully(peer) + } +} + +func markAddrInBookBasedOnErr(addr *p2p.NetAddress, book AddrBook, err error) { + // TODO: detect more "bad peer" scenarios + switch err.(type) { + case p2p.ErrSwitchAuthenticationFailure: + book.MarkBad(addr, defaultBanTime) + default: + book.MarkAttempt(addr) + } +} diff --git a/p2p/pex/pex_reactor_test.go b/p2p/pex/pex_reactor_test.go new file mode 100644 index 0000000..d6a5662 --- /dev/null +++ b/p2p/pex/pex_reactor_test.go @@ -0,0 +1,716 @@ +package pex + +import ( + "encoding/hex" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/p2p/mock" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +var cfg *config.P2PConfig + +func init() { + cfg = config.DefaultP2PConfig() + cfg.PexReactor = true + cfg.AllowDuplicateIP = true +} + +func TestPEXReactorBasic(t *testing.T) { + r, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + assert.NotNil(t, r) + assert.NotEmpty(t, r.GetChannels()) +} + +func TestPEXReactorAddRemovePeer(t *testing.T) { + r, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + size := book.Size() + peer := p2p.CreateRandomPeer(false) + + r.AddPeer(peer) + assert.Equal(t, size+1, book.Size()) + + r.RemovePeer(peer, "peer not available") + + outboundPeer := p2p.CreateRandomPeer(true) + + r.AddPeer(outboundPeer) + assert.Equal(t, size+1, book.Size(), "outbound peers should not be added to the address book") + + r.RemovePeer(outboundPeer, "peer not available") +} + +// --- FAIL: TestPEXReactorRunning (11.10s) +// +// pex_reactor_test.go:411: expected all switches to be connected to at +// least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 => +// {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, ) +// +// EXPLANATION: peers are getting rejected because in switch#addPeer we check +// if any peer (who we already connected to) has the same IP. Even though local +// peers have different IP addresses, they all have the same underlying remote +// IP: 127.0.0.1. +func TestPEXReactorRunning(t *testing.T) { + N := 3 + switches := make([]*p2p.Switch, N) + + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + books := make([]AddrBook, N) + logger := log.TestingLogger() + + // create switches + for i := 0; i < N; i++ { + switches[i] = p2p.MakeSwitch(cfg, i, func(i int, sw *p2p.Switch) *p2p.Switch { + books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false) + books[i].SetLogger(logger.With("pex", i)) + sw.SetAddrBook(books[i]) + + sw.SetLogger(logger.With("pex", i)) + + r := NewReactor(books[i], &ReactorConfig{}) + r.SetLogger(logger.With("pex", i)) + r.SetEnsurePeersPeriod(250 * time.Millisecond) + sw.AddReactor("pex", r) + + return sw + }) + } + + addOtherNodeAddrToAddrBook := func(switchIndex, otherSwitchIndex int) { + addr := switches[otherSwitchIndex].NetAddress() + err := books[switchIndex].AddAddress(addr, addr) + require.NoError(t, err) + } + + addOtherNodeAddrToAddrBook(0, 1) + addOtherNodeAddrToAddrBook(1, 0) + addOtherNodeAddrToAddrBook(2, 1) + + for _, sw := range switches { + err := sw.Start() // start switch and reactors + require.Nil(t, err) + } + + assertPeersWithTimeout(t, switches, 10*time.Millisecond, 10*time.Second, N-1) + + // stop them + for _, s := range switches { + err := s.Stop() + require.NoError(t, err) + } +} + +func TestPEXReactorReceive(t *testing.T) { + r, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + peer := p2p.CreateRandomPeer(false) + + // we have to send a request to receive responses + r.RequestAddrs(peer) + + size := book.Size() + msg := &tmp2p.PexAddrs{Addrs: []tmp2p.NetAddress{peer.SocketAddr().ToProto()}} + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: msg}) + assert.Equal(t, size+1, book.Size()) + + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: &tmp2p.PexRequest{}}) +} + +func TestPEXReactorRequestMessageAbuse(t *testing.T) { + r, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(r) + sw.SetAddrBook(book) + + peer := mock.NewPeer(nil) + peerAddr := peer.SocketAddr() + p2p.AddPeerToSwitchPeerSet(sw, peer) + assert.True(t, sw.Peers().Has(peer.ID())) + err := book.AddAddress(peerAddr, peerAddr) + require.NoError(t, err) + require.True(t, book.HasAddress(peerAddr)) + + id := string(peer.ID()) + + // first time creates the entry + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: &tmp2p.PexRequest{}}) + assert.True(t, r.lastReceivedRequests.Has(id)) + assert.True(t, sw.Peers().Has(peer.ID())) + + // next time sets the last time value + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: &tmp2p.PexRequest{}}) + assert.True(t, r.lastReceivedRequests.Has(id)) + assert.True(t, sw.Peers().Has(peer.ID())) + + // third time is too many too soon - peer is removed + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: &tmp2p.PexRequest{}}) + assert.False(t, r.lastReceivedRequests.Has(id)) + assert.False(t, sw.Peers().Has(peer.ID())) + assert.True(t, book.IsBanned(peerAddr)) +} + +func TestPEXReactorAddrsMessageAbuse(t *testing.T) { + r, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(r) + sw.SetAddrBook(book) + + peer := mock.NewPeer(nil) + p2p.AddPeerToSwitchPeerSet(sw, peer) + assert.True(t, sw.Peers().Has(peer.ID())) + + id := string(peer.ID()) + + // request addrs from the peer + r.RequestAddrs(peer) + assert.True(t, r.requestsSent.Has(id)) + assert.True(t, sw.Peers().Has(peer.ID())) + + msg := &tmp2p.PexAddrs{Addrs: []tmp2p.NetAddress{peer.SocketAddr().ToProto()}} + + // receive some addrs. should clear the request + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: msg}) + assert.False(t, r.requestsSent.Has(id)) + assert.True(t, sw.Peers().Has(peer.ID())) + + // receiving more unsolicited addrs causes a disconnect and ban + r.Receive(p2p.Envelope{ChannelID: PexChannel, Src: peer, Message: msg}) + assert.False(t, sw.Peers().Has(peer.ID())) + assert.True(t, book.IsBanned(peer.SocketAddr())) +} + +func TestCheckSeeds(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + // 1. test creating peer with no seeds works + peerSwitch := testCreateDefaultPeer(dir, 0) + require.Nil(t, peerSwitch.Start()) + peerSwitch.Stop() //nolint:errcheck // ignore for tests + + // 2. create seed + seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{}) + + // 3. test create peer with online seed works + peerSwitch = testCreatePeerWithSeed(dir, 2, seed) + require.Nil(t, peerSwitch.Start()) + peerSwitch.Stop() //nolint:errcheck // ignore for tests + + // 4. test create peer with all seeds having unresolvable DNS fails + badPeerConfig := &ReactorConfig{ + Seeds: []string{ + "ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", + "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657", + }, + } + peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) + require.Error(t, peerSwitch.Start()) + peerSwitch.Stop() //nolint:errcheck // ignore for tests + + // 5. test create peer with one good seed address succeeds + badPeerConfig = &ReactorConfig{ + Seeds: []string{ + "ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", + "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657", + seed.NetAddress().String(), + }, + } + peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) + require.Nil(t, peerSwitch.Start()) + peerSwitch.Stop() //nolint:errcheck // ignore for tests +} + +func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + // 1. create seed + seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{}) + require.Nil(t, seed.Start()) + defer seed.Stop() //nolint:errcheck // ignore for tests + + // 2. create usual peer with only seed configured. + peer := testCreatePeerWithSeed(dir, 1, seed) + require.Nil(t, peer.Start()) + defer peer.Stop() //nolint:errcheck // ignore for tests + + // 3. check that the peer connects to seed immediately + assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1) +} + +func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + var id int + var knownAddrs []*p2p.NetAddress + + // 1. Create some peers + for id = 0; id < 3; id++ { + peer := testCreateDefaultPeer(dir, id) + require.NoError(t, peer.Start()) + addr := peer.NetAddress() + defer peer.Stop() //nolint:errcheck // ignore for tests + + knownAddrs = append(knownAddrs, addr) + t.Log("Created peer", id, addr) + } + + // 2. Create seed node which knows about the previous peers + seed := testCreateSeed(dir, id, knownAddrs, knownAddrs) + require.NoError(t, seed.Start()) + defer seed.Stop() //nolint:errcheck // ignore for tests + t.Log("Created seed", id, seed.NetAddress()) + + // 3. Create a node with only seed configured. + id++ + node := testCreatePeerWithSeed(dir, id, seed) + require.NoError(t, node.Start()) + defer node.Stop() //nolint:errcheck // ignore for tests + t.Log("Created node", id, node.NetAddress()) + + // 4. Check that the node connects to seed immediately + assertPeersWithTimeout(t, []*p2p.Switch{node}, 10*time.Millisecond, 3*time.Second, 1) + + // 5. Check that the node connects to the peers reported by the seed node + assertPeersWithTimeout(t, []*p2p.Switch{node}, 10*time.Millisecond, 1*time.Second, 2) + + // 6. Assert that the configured maximum number of inbound/outbound peers + // are respected, see https://github.com/cometbft/cometbft/issues/486 + outbound, inbound, dialing := node.NumPeers() + assert.LessOrEqual(t, inbound, cfg.MaxNumInboundPeers) + assert.LessOrEqual(t, outbound, cfg.MaxNumOutboundPeers) + assert.LessOrEqual(t, dialing, cfg.MaxNumOutboundPeers+cfg.MaxNumInboundPeers-outbound-inbound) +} + +func TestPEXReactorSeedMode(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + pexRConfig := &ReactorConfig{SeedMode: true, SeedDisconnectWaitPeriod: 10 * time.Millisecond} + pexR, book := createReactor(pexRConfig) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(pexR) + sw.SetAddrBook(book) + err = sw.Start() + require.NoError(t, err) + defer sw.Stop() //nolint:errcheck // ignore for tests + + assert.Zero(t, sw.Peers().Size()) + + peerSwitch := testCreateDefaultPeer(dir, 1) + require.NoError(t, peerSwitch.Start()) + defer peerSwitch.Stop() //nolint:errcheck // ignore for tests + + // 1. Test crawlPeers dials the peer + pexR.crawlPeers([]*p2p.NetAddress{peerSwitch.NetAddress()}) + assert.Equal(t, 1, sw.Peers().Size()) + assert.True(t, sw.Peers().Has(peerSwitch.NodeInfo().ID())) + + // 2. attemptDisconnects should not disconnect because of wait period + pexR.attemptDisconnects() + assert.Equal(t, 1, sw.Peers().Size()) + + // sleep for SeedDisconnectWaitPeriod + time.Sleep(pexRConfig.SeedDisconnectWaitPeriod + 1*time.Millisecond) + + // 3. attemptDisconnects should disconnect after wait period + pexR.attemptDisconnects() + assert.Equal(t, 0, sw.Peers().Size()) +} + +func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + pexRConfig := &ReactorConfig{SeedMode: true, SeedDisconnectWaitPeriod: 1 * time.Millisecond} + pexR, book := createReactor(pexRConfig) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(pexR) + sw.SetAddrBook(book) + err = sw.Start() + require.NoError(t, err) + defer sw.Stop() //nolint:errcheck // ignore for tests + + assert.Zero(t, sw.Peers().Size()) + + peerSwitch := testCreateDefaultPeer(dir, 1) + require.NoError(t, peerSwitch.Start()) + defer peerSwitch.Stop() //nolint:errcheck // ignore for tests + + err = sw.AddPersistentPeers([]string{peerSwitch.NetAddress().String()}) + require.NoError(t, err) + + // 1. Test crawlPeers dials the peer + pexR.crawlPeers([]*p2p.NetAddress{peerSwitch.NetAddress()}) + assert.Equal(t, 1, sw.Peers().Size()) + assert.True(t, sw.Peers().Has(peerSwitch.NodeInfo().ID())) + + // sleep for SeedDisconnectWaitPeriod + time.Sleep(pexRConfig.SeedDisconnectWaitPeriod + 1*time.Millisecond) + + // 2. attemptDisconnects should not disconnect because the peer is persistent + pexR.attemptDisconnects() + assert.Equal(t, 1, sw.Peers().Size()) +} + +func TestPEXReactorDialsPeerUpToMaxAttemptsInSeedMode(t *testing.T) { + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + pexR, book := createReactor(&ReactorConfig{SeedMode: true}) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(pexR) + sw.SetAddrBook(book) + // No need to start sw since crawlPeers is called manually here. + + peer := mock.NewPeer(nil) + addr := peer.SocketAddr() + + err = book.AddAddress(addr, addr) + require.NoError(t, err) + + assert.True(t, book.HasAddress(addr)) + + // imitate maxAttemptsToDial reached + pexR.attemptsToDial.Store(addr.DialString(), _attemptsToDial{maxAttemptsToDial + 1, time.Now()}) + pexR.crawlPeers([]*p2p.NetAddress{addr}) + + assert.False(t, book.HasAddress(addr)) +} + +// connect a peer to a seed, wait a bit, then stop it. +// this should give it time to request addrs and for the seed +// to call FlushStop, and allows us to test calling Stop concurrently +// with FlushStop. Before a fix, this non-deterministically reproduced +// https://github.com/tendermint/tendermint/issues/3231. +func TestPEXReactorSeedModeFlushStop(t *testing.T) { + N := 2 + switches := make([]*p2p.Switch, N) + + // directory to store address books + dir, err := os.MkdirTemp("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + + books := make([]AddrBook, N) + logger := log.TestingLogger() + + // create switches + for i := 0; i < N; i++ { + switches[i] = p2p.MakeSwitch(cfg, i, func(i int, sw *p2p.Switch) *p2p.Switch { + books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false) + books[i].SetLogger(logger.With("pex", i)) + sw.SetAddrBook(books[i]) + + sw.SetLogger(logger.With("pex", i)) + + config := &ReactorConfig{} + if i == 0 { + // first one is a seed node + config = &ReactorConfig{SeedMode: true} + } + r := NewReactor(books[i], config) + r.SetLogger(logger.With("pex", i)) + r.SetEnsurePeersPeriod(250 * time.Millisecond) + sw.AddReactor("pex", r) + + return sw + }) + } + + for _, sw := range switches { + err := sw.Start() // start switch and reactors + require.Nil(t, err) + } + + reactor := switches[0].Reactors()["pex"].(*Reactor) + peerID := switches[1].NodeInfo().ID() + + err = switches[1].DialPeerWithAddress(switches[0].NetAddress()) + assert.NoError(t, err) + + // sleep up to a second while waiting for the peer to send us a message. + // this isn't perfect since it's possible the peer sends us a msg and we FlushStop + // before this loop catches it. but non-deterministically it works pretty well. + for i := 0; i < 1000; i++ { + v := reactor.lastReceivedRequests.Get(string(peerID)) + if v != nil { + break + } + time.Sleep(time.Millisecond) + } + + // by now the FlushStop should have happened. Try stopping the peer. + // it should be safe to do this. + peers := switches[0].Peers().List() + for _, peer := range peers { + err := peer.Stop() + require.NoError(t, err) + } + + // stop the switches + for _, s := range switches { + err := s.Stop() + require.NoError(t, err) + } +} + +func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) { + peer := p2p.CreateRandomPeer(false) + + pexR, book := createReactor(&ReactorConfig{}) + book.AddPrivateIDs([]string{string(peer.NodeInfo().ID())}) + defer teardownReactor(book) + + // we have to send a request to receive responses + pexR.RequestAddrs(peer) + + size := book.Size() + msg := &tmp2p.PexAddrs{Addrs: []tmp2p.NetAddress{peer.SocketAddr().ToProto()}} + pexR.Receive(p2p.Envelope{ + ChannelID: PexChannel, + Src: peer, + Message: msg, + }) + assert.Equal(t, size, book.Size()) + + pexR.AddPeer(peer) + assert.Equal(t, size, book.Size()) +} + +func TestPEXReactorDialPeer(t *testing.T) { + pexR, book := createReactor(&ReactorConfig{}) + defer teardownReactor(book) + + sw := createSwitchAndAddReactors(pexR) + sw.SetAddrBook(book) + + peer := mock.NewPeer(nil) + addr := peer.SocketAddr() + + assert.Equal(t, 0, pexR.AttemptsToDial(addr)) + + // 1st unsuccessful attempt + err := pexR.dialPeer(addr) + require.Error(t, err) + + assert.Equal(t, 1, pexR.AttemptsToDial(addr)) + + // 2nd unsuccessful attempt + err = pexR.dialPeer(addr) + require.Error(t, err) + + // must be skipped because it is too early + assert.Equal(t, 1, pexR.AttemptsToDial(addr)) + + if !testing.Short() { + time.Sleep(3 * time.Second) + + // 3rd attempt + err = pexR.dialPeer(addr) + require.Error(t, err) + + assert.Equal(t, 2, pexR.AttemptsToDial(addr)) + } +} + +func assertPeersWithTimeout( + t *testing.T, + switches []*p2p.Switch, + checkPeriod, timeout time.Duration, + nPeers int, +) { + var ( + ticker = time.NewTicker(checkPeriod) + timeoutCh = time.After(timeout) + ) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + // check peers are connected + allGood := true + for _, s := range switches { + outbound, inbound, _ := s.NumPeers() + if outbound+inbound < nPeers { + allGood = false + break + } + } + if allGood { + return + } + case <-timeoutCh: + numPeersStr := "" + for i, s := range switches { + outbound, inbound, _ := s.NumPeers() + numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound) + } + t.Errorf( + "expected all switches to be connected to at least %d peer(s) (switches: %s)", + nPeers, numPeersStr, + ) + return + } + } +} + +// Creates a peer with the provided config +func testCreatePeerWithConfig(dir string, id int, config *ReactorConfig) *p2p.Switch { + peer := p2p.MakeSwitch( + cfg, + id, + func(i int, sw *p2p.Switch) *p2p.Switch { + book := NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", id)), false) + book.SetLogger(log.TestingLogger().With("book", id)) + sw.SetAddrBook(book) + + r := NewReactor( + book, + config, + ) + r.SetLogger(log.TestingLogger().With("pex", id)) + sw.AddReactor("pex", r) + return sw + }, + ) + return peer +} + +// Creates a peer with the default config +func testCreateDefaultPeer(dir string, id int) *p2p.Switch { + return testCreatePeerWithConfig(dir, id, &ReactorConfig{}) +} + +// Creates a seed which knows about the provided addresses / source address pairs. +// Starting and stopping the seed is left to the caller +func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) *p2p.Switch { + seed := p2p.MakeSwitch( + cfg, + id, + func(i int, sw *p2p.Switch) *p2p.Switch { + book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false) + book.SetLogger(log.TestingLogger()) + for j := 0; j < len(knownAddrs); j++ { + book.AddAddress(knownAddrs[j], srcAddrs[j]) //nolint:errcheck // ignore for tests + book.MarkGood(knownAddrs[j].ID) + } + sw.SetAddrBook(book) + + sw.SetLogger(log.TestingLogger()) + + r := NewReactor(book, &ReactorConfig{}) + r.SetLogger(log.TestingLogger()) + sw.AddReactor("pex", r) + return sw + }, + ) + return seed +} + +// Creates a peer which knows about the provided seed. +// Starting and stopping the peer is left to the caller +func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch { + conf := &ReactorConfig{ + Seeds: []string{seed.NetAddress().String()}, + } + return testCreatePeerWithConfig(dir, id, conf) +} + +func createReactor(conf *ReactorConfig) (r *Reactor, book AddrBook) { + // directory to store address book + dir, err := os.MkdirTemp("", "pex_reactor") + if err != nil { + panic(err) + } + book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true) + book.SetLogger(log.TestingLogger()) + + r = NewReactor(book, conf) + r.SetLogger(log.TestingLogger()) + return +} + +func teardownReactor(book AddrBook) { + // FIXME Shouldn't rely on .(*addrBook) assertion + err := os.RemoveAll(filepath.Dir(book.(*addrBook).FilePath())) + if err != nil { + panic(err) + } +} + +func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch { + sw := p2p.MakeSwitch(cfg, 0, func(i int, sw *p2p.Switch) *p2p.Switch { return sw }) + sw.SetLogger(log.TestingLogger()) + for _, r := range reactors { + sw.AddReactor(r.String(), r) + r.SetSwitch(sw) + } + return sw +} + +func TestPexVectors(t *testing.T) { + addr := tmp2p.NetAddress{ + ID: "1", + IP: "127.0.0.1", + Port: 9090, + } + + testCases := []struct { + testName string + msg proto.Message + expBytes string + }{ + {"PexRequest", &tmp2p.PexRequest{}, "0a00"}, + {"PexAddrs", &tmp2p.PexAddrs{Addrs: []tmp2p.NetAddress{addr}}, "12130a110a013112093132372e302e302e31188247"}, + } + + for _, tc := range testCases { + tc := tc + + w := tc.msg.(p2p.Wrapper).Wrap() + bz, err := proto.Marshal(w) + require.NoError(t, err) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + } +} diff --git a/p2p/switch.go b/p2p/switch.go new file mode 100644 index 0000000..7101927 --- /dev/null +++ b/p2p/switch.go @@ -0,0 +1,865 @@ +package p2p + +import ( + "fmt" + "math" + "sync" + "time" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/cmap" + "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/p2p/conn" +) + +const ( + // wait a random amount of time from this interval + // before dialing peers or reconnecting to help prevent DoS + dialRandomizerIntervalMilliseconds = 3000 + + // repeatedly try to reconnect for a few minutes + // ie. 5 * 20 = 100s + reconnectAttempts = 20 + reconnectInterval = 5 * time.Second + + // then move into exponential backoff mode for ~1day + // ie. 3**10 = 16hrs + reconnectBackOffAttempts = 10 + reconnectBackOffBaseSeconds = 3 +) + +// MConnConfig returns an MConnConfig with fields updated +// from the P2PConfig. +func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig { + mConfig := conn.DefaultMConnConfig() + mConfig.FlushThrottle = cfg.FlushThrottleTimeout + mConfig.SendRate = cfg.SendRate + mConfig.RecvRate = cfg.RecvRate + mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize + mConfig.TestFuzz = cfg.TestFuzz + mConfig.TestFuzzConfig = cfg.TestFuzzConfig + return mConfig +} + +//----------------------------------------------------------------------------- + +// An AddrBook represents an address book from the pex package, which is used +// to store peer addresses. +type AddrBook interface { + AddAddress(addr *NetAddress, src *NetAddress) error + AddPrivateIDs([]string) + AddOurAddress(*NetAddress) + OurAddress(*NetAddress) bool + MarkGood(ID) + RemoveAddress(*NetAddress) + HasAddress(*NetAddress) bool + Save() +} + +// PeerFilterFunc to be implemented by filter hooks after a new Peer has been +// fully setup. +type PeerFilterFunc func(IPeerSet, Peer) error + +//----------------------------------------------------------------------------- + +// Switch handles peer connections and exposes an API to receive incoming messages +// on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one +// or more `Channels`. So while sending outgoing messages is typically performed on the peer, +// incoming messages are received on the reactor. +type Switch struct { + service.BaseService + + config *config.P2PConfig + reactors map[string]Reactor + chDescs []*conn.ChannelDescriptor + reactorsByCh map[byte]Reactor + msgTypeByChID map[byte]proto.Message + peers *PeerSet + dialing *cmap.CMap + reconnecting *cmap.CMap + nodeInfo NodeInfo // our node info + nodeKey *NodeKey // our node privkey + addrBook AddrBook + // peers addresses with whom we'll maintain constant connection + persistentPeersAddrs []*NetAddress + unconditionalPeerIDs map[ID]struct{} + + transport Transport + + filterTimeout time.Duration + peerFilters []PeerFilterFunc + + rng *rand.Rand // seed for randomizing dial times and orders + + metrics *Metrics + mlc *metricsLabelCache +} + +// NetAddress returns the address the switch is listening on. +func (sw *Switch) NetAddress() *NetAddress { + addr := sw.transport.NetAddress() + return &addr +} + +// SwitchOption sets an optional parameter on the Switch. +type SwitchOption func(*Switch) + +// NewSwitch creates a new Switch with the given config. +func NewSwitch( + cfg *config.P2PConfig, + transport Transport, + options ...SwitchOption, +) *Switch { + + sw := &Switch{ + config: cfg, + reactors: make(map[string]Reactor), + chDescs: make([]*conn.ChannelDescriptor, 0), + reactorsByCh: make(map[byte]Reactor), + msgTypeByChID: make(map[byte]proto.Message), + peers: NewPeerSet(), + dialing: cmap.NewCMap(), + reconnecting: cmap.NewCMap(), + metrics: NopMetrics(), + transport: transport, + filterTimeout: defaultFilterTimeout, + persistentPeersAddrs: make([]*NetAddress, 0), + unconditionalPeerIDs: make(map[ID]struct{}), + mlc: newMetricsLabelCache(), + } + + // Ensure we have a completely undeterministic PRNG. + sw.rng = rand.NewRand() + + sw.BaseService = *service.NewBaseService(nil, "P2P Switch", sw) + + for _, option := range options { + option(sw) + } + + return sw +} + +// SwitchFilterTimeout sets the timeout used for peer filters. +func SwitchFilterTimeout(timeout time.Duration) SwitchOption { + return func(sw *Switch) { sw.filterTimeout = timeout } +} + +// SwitchPeerFilters sets the filters for rejection of new peers. +func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption { + return func(sw *Switch) { sw.peerFilters = filters } +} + +// WithMetrics sets the metrics. +func WithMetrics(metrics *Metrics) SwitchOption { + return func(sw *Switch) { sw.metrics = metrics } +} + +//--------------------------------------------------------------------- +// Switch setup + +// AddReactor adds the given reactor to the switch. +// NOTE: Not goroutine safe. +func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor { + for _, chDesc := range reactor.GetChannels() { + chID := chDesc.ID + // No two reactors can share the same channel. + if sw.reactorsByCh[chID] != nil { + panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) + } + sw.chDescs = append(sw.chDescs, chDesc) + sw.reactorsByCh[chID] = reactor + sw.msgTypeByChID[chID] = chDesc.MessageType + } + sw.reactors[name] = reactor + reactor.SetSwitch(sw) + return reactor +} + +// RemoveReactor removes the given Reactor from the Switch. +// NOTE: Not goroutine safe. +func (sw *Switch) RemoveReactor(name string, reactor Reactor) { + for _, chDesc := range reactor.GetChannels() { + // remove channel description + for i := 0; i < len(sw.chDescs); i++ { + if chDesc.ID == sw.chDescs[i].ID { + sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...) + break + } + } + delete(sw.reactorsByCh, chDesc.ID) + delete(sw.msgTypeByChID, chDesc.ID) + } + delete(sw.reactors, name) + reactor.SetSwitch(nil) +} + +// Reactors returns a map of reactors registered on the switch. +// NOTE: Not goroutine safe. +func (sw *Switch) Reactors() map[string]Reactor { + return sw.reactors +} + +// Reactor returns the reactor with the given name. +// NOTE: Not goroutine safe. +func (sw *Switch) Reactor(name string) Reactor { + return sw.reactors[name] +} + +// SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes. +// NOTE: Not goroutine safe. +func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) { + sw.nodeInfo = nodeInfo +} + +// NodeInfo returns the switch's NodeInfo. +// NOTE: Not goroutine safe. +func (sw *Switch) NodeInfo() NodeInfo { + return sw.nodeInfo +} + +// SetNodeKey sets the switch's private key for authenticated encryption. +// NOTE: Not goroutine safe. +func (sw *Switch) SetNodeKey(nodeKey *NodeKey) { + sw.nodeKey = nodeKey +} + +//--------------------------------------------------------------------- +// Service start/stop + +// OnStart implements BaseService. It starts all the reactors and peers. +func (sw *Switch) OnStart() error { + // Start reactors + for _, reactor := range sw.reactors { + err := reactor.Start() + if err != nil { + return fmt.Errorf("failed to start %v: %w", reactor, err) + } + } + + // Start accepting Peers. + go sw.acceptRoutine() + + return nil +} + +// OnStop implements BaseService. It stops all peers and reactors. +func (sw *Switch) OnStop() { + // Stop peers + for _, p := range sw.peers.List() { + sw.stopAndRemovePeer(p, nil) + } + + // Stop reactors + sw.Logger.Debug("Switch: Stopping reactors") + for _, reactor := range sw.reactors { + if err := reactor.Stop(); err != nil { + sw.Logger.Error("error while stopped reactor", "reactor", reactor, "error", err) + } + } +} + +//--------------------------------------------------------------------- +// Peers + +// Broadcast runs a go routine for each attempted send, which will block trying +// to send for defaultSendTimeoutSeconds. Returns a channel which receives +// success values for each attempted send (false if times out). Channel will be +// closed once msg bytes are sent to all peers (or time out). +// +// NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved. +func (sw *Switch) Broadcast(e Envelope) chan bool { + sw.Logger.Debug("Broadcast", "channel", e.ChannelID) + + peers := sw.peers.List() + var wg sync.WaitGroup + wg.Add(len(peers)) + successChan := make(chan bool, len(peers)) + + for _, peer := range peers { + go func(p Peer) { + defer wg.Done() + success := p.Send(e) + successChan <- success + }(peer) + } + + go func() { + wg.Wait() + close(successChan) + }() + + return successChan +} + +// NumPeers returns the count of outbound/inbound and outbound-dialing peers. +// unconditional peers are not counted here. +func (sw *Switch) NumPeers() (outbound, inbound, dialing int) { + peers := sw.peers.List() + for _, peer := range peers { + if peer.IsOutbound() { + if !sw.IsPeerUnconditional(peer.ID()) { + outbound++ + } + } else { + if !sw.IsPeerUnconditional(peer.ID()) { + inbound++ + } + } + } + dialing = sw.dialing.Size() + return +} + +func (sw *Switch) IsPeerUnconditional(id ID) bool { + _, ok := sw.unconditionalPeerIDs[id] + return ok +} + +// MaxNumOutboundPeers returns a maximum number of outbound peers. +func (sw *Switch) MaxNumOutboundPeers() int { + return sw.config.MaxNumOutboundPeers +} + +// Peers returns the set of peers that are connected to the switch. +func (sw *Switch) Peers() IPeerSet { + return sw.peers +} + +// StopPeerForError disconnects from a peer due to external error. +// If the peer is persistent, it will attempt to reconnect. +// TODO: make record depending on reason. +func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) { + if !peer.IsRunning() { + return + } + + sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason) + sw.stopAndRemovePeer(peer, reason) + + if peer.IsPersistent() { + var addr *NetAddress + if peer.IsOutbound() { // socket address for outbound peers + addr = peer.SocketAddr() + } else { // self-reported address for inbound peers + var err error + addr, err = peer.NodeInfo().NetAddress() + if err != nil { + sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong", + "peer", peer, "err", err) + return + } + } + go sw.reconnectToPeer(addr) + } +} + +// StopPeerGracefully disconnects from a peer gracefully. +// TODO: handle graceful disconnects. +func (sw *Switch) StopPeerGracefully(peer Peer) { + sw.Logger.Info("Stopping peer gracefully") + sw.stopAndRemovePeer(peer, nil) +} + +func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) { + sw.transport.Cleanup(peer) + if err := peer.Stop(); err != nil { + sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly + } + + for _, reactor := range sw.reactors { + reactor.RemovePeer(peer, reason) + } + + // Removing a peer should go last to avoid a situation where a peer + // reconnect to our node and the switch calls InitPeer before + // RemovePeer is finished. + // https://github.com/tendermint/tendermint/issues/3338 + if sw.peers.Remove(peer) { + sw.metrics.Peers.Add(float64(-1)) + } else { + // Removal of the peer has failed. The function above sets a flag within the peer to mark this. + // We keep this message here as information to the developer. + sw.Logger.Debug("error on peer removal", ",", "peer", peer.ID()) + } +} + +// reconnectToPeer tries to reconnect to the addr, first repeatedly +// with a fixed interval (approximately 2 minutes), then with +// exponential backoff (approximately close to 24 hours). +// If no success after all that, it stops trying, and leaves it +// to the PEX/Addrbook to find the peer with the addr again +// NOTE: this will keep trying even if the handshake or auth fails. +// TODO: be more explicit with error types so we only retry on certain failures +// - ie. if we're getting ErrDuplicatePeer we can stop +// because the addrbook got us the peer back already +func (sw *Switch) reconnectToPeer(addr *NetAddress) { + if sw.reconnecting.Has(string(addr.ID)) { + return + } + sw.reconnecting.Set(string(addr.ID), addr) + defer sw.reconnecting.Delete(string(addr.ID)) + + start := time.Now() + sw.Logger.Info("Reconnecting to peer", "addr", addr) + + for i := 0; i < reconnectAttempts; i++ { + if !sw.IsRunning() { + return + } + + err := sw.DialPeerWithAddress(addr) + if err == nil { + return // success + } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok { + return + } + + sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr) + // sleep a set amount + sw.randomSleep(reconnectInterval) + continue + } + + sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff", + "addr", addr, "elapsed", time.Since(start)) + for i := 1; i <= reconnectBackOffAttempts; i++ { + if !sw.IsRunning() { + return + } + + // sleep an exponentially increasing amount + sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i)) + sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second) + + err := sw.DialPeerWithAddress(addr) + if err == nil { + return // success + } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok { + return + } + sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr) + } + sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start)) +} + +// SetAddrBook allows to set address book on Switch. +func (sw *Switch) SetAddrBook(addrBook AddrBook) { + sw.addrBook = addrBook +} + +// MarkPeerAsGood marks the given peer as good when it did something useful +// like contributed to consensus. +func (sw *Switch) MarkPeerAsGood(peer Peer) { + if sw.addrBook != nil { + sw.addrBook.MarkGood(peer.ID()) + } +} + +//--------------------------------------------------------------------- +// Dialing + +type privateAddr interface { + PrivateAddr() bool +} + +func isPrivateAddr(err error) bool { + te, ok := err.(privateAddr) + return ok && te.PrivateAddr() +} + +// DialPeersAsync dials a list of peers asynchronously in random order. +// Used to dial peers from config on startup or from unsafe-RPC (trusted sources). +// It ignores ErrNetAddressLookup. However, if there are other errors, first +// encounter is returned. +// Nop if there are no peers. +func (sw *Switch) DialPeersAsync(peers []string) error { + netAddrs, errs := NewNetAddressStrings(peers) + // report all the errors + for _, err := range errs { + sw.Logger.Error("Error in peer's address", "err", err) + } + // return first non-ErrNetAddressLookup error + for _, err := range errs { + if _, ok := err.(ErrNetAddressLookup); ok { + continue + } + return err + } + sw.dialPeersAsync(netAddrs) + return nil +} + +func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) { + ourAddr := sw.NetAddress() + + // TODO: this code feels like it's in the wrong place. + // The integration tests depend on the addrBook being saved + // right away but maybe we can change that. Recall that + // the addrBook is only written to disk every 2min + if sw.addrBook != nil { + // add peers to `addrBook` + for _, netAddr := range netAddrs { + // do not add our address or ID + if !netAddr.Same(ourAddr) { + if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil { + if isPrivateAddr(err) { + sw.Logger.Debug("Won't add peer's address to addrbook", "err", err) + } else { + sw.Logger.Error("Can't add peer's address to addrbook", "err", err) + } + } + } + } + // Persist some peers to disk right away. + // NOTE: integration tests depend on this + sw.addrBook.Save() + } + + // permute the list, dial them in random order. + perm := sw.rng.Perm(len(netAddrs)) + for i := 0; i < len(perm); i++ { + go func(i int) { + j := perm[i] + addr := netAddrs[j] + + if addr.Same(ourAddr) { + sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr) + return + } + + sw.randomSleep(0) + + err := sw.DialPeerWithAddress(addr) + if err != nil { + switch err.(type) { + case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress: + sw.Logger.Debug("Error dialing peer", "err", err) + default: + sw.Logger.Error("Error dialing peer", "err", err) + } + } + }(i) + } +} + +// DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects +// and authenticates successfully. +// If we're currently dialing this address or it belongs to an existing peer, +// ErrCurrentlyDialingOrExistingAddress is returned. +func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error { + if sw.IsDialingOrExistingAddress(addr) { + return ErrCurrentlyDialingOrExistingAddress{addr.String()} + } + + sw.dialing.Set(string(addr.ID), addr) + defer sw.dialing.Delete(string(addr.ID)) + + return sw.addOutboundPeerWithConfig(addr, sw.config) +} + +// sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds] +func (sw *Switch) randomSleep(interval time.Duration) { + r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond + time.Sleep(r + interval) +} + +// IsDialingOrExistingAddress returns true if switch has a peer with the given +// address or dialing it at the moment. +func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool { + return sw.dialing.Has(string(addr.ID)) || + sw.peers.Has(addr.ID) || + (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP)) +} + +// AddPersistentPeers allows you to set persistent peers. It ignores +// ErrNetAddressLookup. However, if there are other errors, first encounter is +// returned. +func (sw *Switch) AddPersistentPeers(addrs []string) error { + sw.Logger.Info("Adding persistent peers", "addrs", addrs) + netAddrs, errs := NewNetAddressStrings(addrs) + // report all the errors + for _, err := range errs { + sw.Logger.Error("Error in peer's address", "err", err) + } + // return first non-ErrNetAddressLookup error + for _, err := range errs { + if _, ok := err.(ErrNetAddressLookup); ok { + continue + } + return err + } + sw.persistentPeersAddrs = netAddrs + return nil +} + +func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error { + sw.Logger.Info("Adding unconditional peer ids", "ids", ids) + for i, id := range ids { + err := validateID(ID(id)) + if err != nil { + return fmt.Errorf("wrong ID #%d: %w", i, err) + } + sw.unconditionalPeerIDs[ID(id)] = struct{}{} + } + return nil +} + +func (sw *Switch) AddPrivatePeerIDs(ids []string) error { + validIDs := make([]string, 0, len(ids)) + for i, id := range ids { + err := validateID(ID(id)) + if err != nil { + return fmt.Errorf("wrong ID #%d: %w", i, err) + } + validIDs = append(validIDs, id) + } + + sw.addrBook.AddPrivateIDs(validIDs) + + return nil +} + +func (sw *Switch) IsPeerPersistent(na *NetAddress) bool { + for _, pa := range sw.persistentPeersAddrs { + if pa.Equals(na) { + return true + } + } + return false +} + +func (sw *Switch) acceptRoutine() { + for { + p, err := sw.transport.Accept(peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + reactorsByCh: sw.reactorsByCh, + msgTypeByChID: sw.msgTypeByChID, + metrics: sw.metrics, + mlc: sw.mlc, + isPersistent: sw.IsPeerPersistent, + }) + if err != nil { + switch err := err.(type) { + case ErrRejected: + if err.IsSelf() { + // Remove the given address from the address book and add to our addresses + // to avoid dialing in the future. + addr := err.Addr() + sw.addrBook.RemoveAddress(&addr) + sw.addrBook.AddOurAddress(&addr) + } + + sw.Logger.Info( + "Inbound Peer rejected", + "err", err, + "numPeers", sw.peers.Size(), + ) + + continue + case ErrFilterTimeout: + sw.Logger.Error( + "Peer filter timed out", + "err", err, + ) + + continue + case ErrTransportClosed: + sw.Logger.Error( + "Stopped accept routine, as transport is closed", + "numPeers", sw.peers.Size(), + ) + default: + sw.Logger.Error( + "Accept on transport errored", + "err", err, + "numPeers", sw.peers.Size(), + ) + // We could instead have a retry loop around the acceptRoutine, + // but that would need to stop and let the node shutdown eventually. + // So might as well panic and let process managers restart the node. + // There's no point in letting the node run without the acceptRoutine, + // since it won't be able to accept new connections. + panic(fmt.Errorf("accept routine exited: %v", err)) + } + + break + } + + if !sw.IsPeerUnconditional(p.NodeInfo().ID()) { + // Ignore connection if we already have enough peers. + _, in, _ := sw.NumPeers() + if in >= sw.config.MaxNumInboundPeers { + sw.Logger.Info( + "Ignoring inbound connection: already have enough inbound peers", + "address", p.SocketAddr(), + "have", in, + "max", sw.config.MaxNumInboundPeers, + ) + + sw.transport.Cleanup(p) + + continue + } + + } + + if err := sw.addPeer(p); err != nil { + sw.transport.Cleanup(p) + if p.IsRunning() { + _ = p.Stop() + } + sw.Logger.Info( + "Ignoring inbound connection: error while adding peer", + "err", err, + "id", p.ID(), + ) + } + } +} + +// dial the peer; make secret connection; authenticate against the dialed ID; +// add the peer. +// if dialing fails, start the reconnect loop. If handshake fails, it's over. +// If peer is started successfully, reconnectLoop will start when +// StopPeerForError is called. +func (sw *Switch) addOutboundPeerWithConfig( + addr *NetAddress, + cfg *config.P2PConfig, +) error { + sw.Logger.Debug("Dialing peer", "address", addr) + + // XXX(xla): Remove the leakage of test concerns in implementation. + if cfg.TestDialFail { + go sw.reconnectToPeer(addr) + return fmt.Errorf("dial err (peerConfig.DialFail == true)") + } + + p, err := sw.transport.Dial(*addr, peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + isPersistent: sw.IsPeerPersistent, + reactorsByCh: sw.reactorsByCh, + msgTypeByChID: sw.msgTypeByChID, + metrics: sw.metrics, + mlc: sw.mlc, + }) + if err != nil { + if e, ok := err.(ErrRejected); ok { + if e.IsSelf() { + // Remove the given address from the address book and add to our addresses + // to avoid dialing in the future. + sw.addrBook.RemoveAddress(addr) + sw.addrBook.AddOurAddress(addr) + + return err + } + } + + // retry persistent peers after + // any dial error besides IsSelf() + if sw.IsPeerPersistent(addr) { + go sw.reconnectToPeer(addr) + } + + return err + } + + if err := sw.addPeer(p); err != nil { + sw.transport.Cleanup(p) + if p.IsRunning() { + _ = p.Stop() + } + return err + } + + return nil +} + +func (sw *Switch) filterPeer(p Peer) error { + // Avoid duplicate + if sw.peers.Has(p.ID()) { + return ErrRejected{id: p.ID(), isDuplicate: true} + } + + errc := make(chan error, len(sw.peerFilters)) + + for _, f := range sw.peerFilters { + go func(f PeerFilterFunc, p Peer, errc chan<- error) { + errc <- f(sw.peers, p) + }(f, p, errc) + } + + for i := 0; i < cap(errc); i++ { + select { + case err := <-errc: + if err != nil { + return ErrRejected{id: p.ID(), err: err, isFiltered: true} + } + case <-time.After(sw.filterTimeout): + return ErrFilterTimeout{} + } + } + + return nil +} + +// addPeer starts up the Peer and adds it to the Switch. Error is returned if +// the peer is filtered out or failed to start or can't be added. +func (sw *Switch) addPeer(p Peer) error { + if err := sw.filterPeer(p); err != nil { + return err + } + + p.SetLogger(sw.Logger.With("peer", p.SocketAddr())) + + // Handle the shut down case where the switch has stopped but we're + // concurrently trying to add a peer. + if !sw.IsRunning() { + // XXX should this return an error or just log and terminate? + sw.Logger.Error("Won't start a peer - switch is not running", "peer", p) + return nil + } + + // Add some data to the peer, which is required by reactors. + for _, reactor := range sw.reactors { + p = reactor.InitPeer(p) + } + + // Start the peer's send/recv routines. + // Must start it before adding it to the peer set + // to prevent Start and Stop from being called concurrently. + err := p.Start() + if err != nil { + // Should never happen + sw.Logger.Error("Error starting peer", "err", err, "peer", p) + return err + } + + // Add the peer to PeerSet. Do this before starting the reactors + // so that if Receive errors, we will find the peer and remove it. + // Add should not err since we already checked peers.Has(). + if err := sw.peers.Add(p); err != nil { + switch err.(type) { + case ErrPeerRemoval: + sw.Logger.Error("Error starting peer ", + " err ", "Peer has already errored and removal was attempted.", + "peer", p.ID()) + } + return err + } + sw.metrics.Peers.Add(float64(1)) + + // Start all the reactor protocols on the peer. + for _, reactor := range sw.reactors { + reactor.AddPeer(p) + } + + sw.Logger.Debug("Added peer", "peer", p) + + return nil +} diff --git a/p2p/switch_test.go b/p2p/switch_test.go new file mode 100644 index 0000000..16bd586 --- /dev/null +++ b/p2p/switch_test.go @@ -0,0 +1,871 @@ +package p2p + +import ( + "bytes" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "regexp" + "strconv" + "sync/atomic" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p/conn" + p2pproto "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +var cfg *config.P2PConfig + +func init() { + cfg = config.DefaultP2PConfig() + cfg.PexReactor = true + cfg.AllowDuplicateIP = true +} + +type PeerMessage struct { + Contents proto.Message + Counter int +} + +type TestReactor struct { + BaseReactor + + mtx cmtsync.Mutex + channels []*conn.ChannelDescriptor + logMessages bool + msgsCounter int + msgsReceived map[byte][]PeerMessage +} + +func NewTestReactor(channels []*conn.ChannelDescriptor, logMessages bool) *TestReactor { + tr := &TestReactor{ + channels: channels, + logMessages: logMessages, + msgsReceived: make(map[byte][]PeerMessage), + } + tr.BaseReactor = *NewBaseReactor("TestReactor", tr) + tr.SetLogger(log.TestingLogger()) + return tr +} + +func (tr *TestReactor) GetChannels() []*conn.ChannelDescriptor { + return tr.channels +} + +func (tr *TestReactor) AddPeer(Peer) {} + +func (tr *TestReactor) RemovePeer(Peer, interface{}) {} + +func (tr *TestReactor) Receive(e Envelope) { + if tr.logMessages { + tr.mtx.Lock() + defer tr.mtx.Unlock() + fmt.Printf("Received: %X, %X\n", e.ChannelID, e.Message) + tr.msgsReceived[e.ChannelID] = append(tr.msgsReceived[e.ChannelID], PeerMessage{Contents: e.Message, Counter: tr.msgsCounter}) + tr.msgsCounter++ + } +} + +func (tr *TestReactor) getMsgs(chID byte) []PeerMessage { + tr.mtx.Lock() + defer tr.mtx.Unlock() + return tr.msgsReceived[chID] +} + +//----------------------------------------------------------------------------- + +// convenience method for creating two switches connected to each other. +// XXX: note this uses net.Pipe and not a proper TCP conn +func MakeSwitchPair(initSwitch func(int, *Switch) *Switch) (*Switch, *Switch) { + // Create two switches that will be interconnected. + switches := MakeConnectedSwitches(cfg, 2, initSwitch, Connect2Switches) + return switches[0], switches[1] +} + +func initSwitchFunc(_ int, sw *Switch) *Switch { + sw.SetAddrBook(&AddrBookMock{ + Addrs: make(map[string]struct{}), + OurAddrs: make(map[string]struct{}), + }) + + // Make two reactors of two channels each + sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{ + {ID: byte(0x00), Priority: 10, MessageType: &p2pproto.Message{}}, + {ID: byte(0x01), Priority: 10, MessageType: &p2pproto.Message{}}, + }, true)) + sw.AddReactor("bar", NewTestReactor([]*conn.ChannelDescriptor{ + {ID: byte(0x02), Priority: 10, MessageType: &p2pproto.Message{}}, + {ID: byte(0x03), Priority: 10, MessageType: &p2pproto.Message{}}, + }, true)) + + return sw +} + +func TestSwitches(t *testing.T) { + s1, s2 := MakeSwitchPair(initSwitchFunc) + t.Cleanup(func() { + if err := s1.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := s2.Stop(); err != nil { + t.Error(err) + } + }) + + if s1.Peers().Size() != 1 { + t.Errorf("expected exactly 1 peer in s1, got %v", s1.Peers().Size()) + } + if s2.Peers().Size() != 1 { + t.Errorf("expected exactly 1 peer in s2, got %v", s2.Peers().Size()) + } + + // Lets send some messages + ch0Msg := &p2pproto.PexAddrs{ + Addrs: []p2pproto.NetAddress{ + { + ID: "1", + }, + }, + } + ch1Msg := &p2pproto.PexAddrs{ + Addrs: []p2pproto.NetAddress{ + { + ID: "1", + }, + }, + } + ch2Msg := &p2pproto.PexAddrs{ + Addrs: []p2pproto.NetAddress{ + { + ID: "2", + }, + }, + } + s1.Broadcast(Envelope{ChannelID: byte(0x00), Message: ch0Msg}) + s1.Broadcast(Envelope{ChannelID: byte(0x01), Message: ch1Msg}) + s1.Broadcast(Envelope{ChannelID: byte(0x02), Message: ch2Msg}) + assertMsgReceivedWithTimeout(t, + ch0Msg, + byte(0x00), + s2.Reactor("foo").(*TestReactor), 200*time.Millisecond, 5*time.Second) + assertMsgReceivedWithTimeout(t, + ch1Msg, + byte(0x01), + s2.Reactor("foo").(*TestReactor), 200*time.Millisecond, 5*time.Second) + assertMsgReceivedWithTimeout(t, + ch2Msg, + byte(0x02), + s2.Reactor("bar").(*TestReactor), 200*time.Millisecond, 5*time.Second) +} + +func assertMsgReceivedWithTimeout( + t *testing.T, + msg proto.Message, + channel byte, + reactor *TestReactor, + checkPeriod, + timeout time.Duration, +) { + ticker := time.NewTicker(checkPeriod) + for { + select { + case <-ticker.C: + msgs := reactor.getMsgs(channel) + expectedBytes, err := proto.Marshal(msgs[0].Contents) + require.NoError(t, err) + gotBytes, err := proto.Marshal(msg) + require.NoError(t, err) + if len(msgs) > 0 { + if !bytes.Equal(expectedBytes, gotBytes) { + t.Fatalf("Unexpected message bytes. Wanted: %X, Got: %X", msg, msgs[0].Counter) + } + return + } + + case <-time.After(timeout): + t.Fatalf("Expected to have received 1 message in channel #%v, got zero", channel) + } + } +} + +func TestSwitchFiltersOutItself(t *testing.T) { + s1 := MakeSwitch(cfg, 1, initSwitchFunc) + + // simulate s1 having a public IP by creating a remote peer with the same ID + rp := &remotePeer{PrivKey: s1.nodeKey.PrivKey, Config: cfg} + rp.Start() + + // addr should be rejected in addPeer based on the same ID + err := s1.DialPeerWithAddress(rp.Addr()) + if assert.Error(t, err) { + if err, ok := err.(ErrRejected); ok { + if !err.IsSelf() { + t.Errorf("expected self to be rejected") + } + } else { + t.Errorf("expected ErrRejected") + } + } + + assert.True(t, s1.addrBook.OurAddress(rp.Addr())) + assert.False(t, s1.addrBook.HasAddress(rp.Addr())) + + rp.Stop() + + assertNoPeersAfterTimeout(t, s1, 100*time.Millisecond) +} + +func TestSwitchPeerFilter(t *testing.T) { + var ( + filters = []PeerFilterFunc{ + func(_ IPeerSet, _ Peer) error { return nil }, + func(_ IPeerSet, _ Peer) error { return fmt.Errorf("denied") }, + func(_ IPeerSet, _ Peer) error { return nil }, + } + sw = MakeSwitch( + cfg, + 1, + initSwitchFunc, + SwitchPeerFilters(filters...), + ) + ) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + t.Cleanup(rp.Stop) + + p, err := sw.transport.Dial(*rp.Addr(), peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + isPersistent: sw.IsPeerPersistent, + reactorsByCh: sw.reactorsByCh, + }) + if err != nil { + t.Fatal(err) + } + + err = sw.addPeer(p) + if err, ok := err.(ErrRejected); ok { + if !err.IsFiltered() { + t.Errorf("expected peer to be filtered") + } + } else { + t.Errorf("expected ErrRejected") + } +} + +func TestSwitchPeerFilterTimeout(t *testing.T) { + var ( + filters = []PeerFilterFunc{ + func(_ IPeerSet, _ Peer) error { + time.Sleep(10 * time.Millisecond) + return nil + }, + } + sw = MakeSwitch( + cfg, + 1, + initSwitchFunc, + SwitchFilterTimeout(5*time.Millisecond), + SwitchPeerFilters(filters...), + ) + ) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Log(err) + } + }) + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + p, err := sw.transport.Dial(*rp.Addr(), peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + isPersistent: sw.IsPeerPersistent, + reactorsByCh: sw.reactorsByCh, + }) + if err != nil { + t.Fatal(err) + } + + err = sw.addPeer(p) + if _, ok := err.(ErrFilterTimeout); !ok { + t.Errorf("expected ErrFilterTimeout") + } +} + +func TestSwitchPeerFilterDuplicate(t *testing.T) { + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + p, err := sw.transport.Dial(*rp.Addr(), peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + isPersistent: sw.IsPeerPersistent, + reactorsByCh: sw.reactorsByCh, + }) + if err != nil { + t.Fatal(err) + } + + if err := sw.addPeer(p); err != nil { + t.Fatal(err) + } + + err = sw.addPeer(p) + if errRej, ok := err.(ErrRejected); ok { + if !errRej.IsDuplicate() { + t.Errorf("expected peer to be duplicate. got %v", errRej) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func assertNoPeersAfterTimeout(t *testing.T, sw *Switch, timeout time.Duration) { + time.Sleep(timeout) + if sw.Peers().Size() != 0 { + t.Fatalf("Expected %v to not connect to some peers, got %d", sw, sw.Peers().Size()) + } +} + +func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.Start() + if err != nil { + t.Error(err) + } + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // simulate remote peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + p, err := sw.transport.Dial(*rp.Addr(), peerConfig{ + chDescs: sw.chDescs, + onPeerError: sw.StopPeerForError, + isPersistent: sw.IsPeerPersistent, + reactorsByCh: sw.reactorsByCh, + }) + require.Nil(err) + + err = sw.addPeer(p) + require.Nil(err) + + require.NotNil(sw.Peers().Get(rp.ID())) + + // simulate failure by closing connection + err = p.(*peer).CloseConn() + require.NoError(err) + + assertNoPeersAfterTimeout(t, sw, 100*time.Millisecond) + assert.False(p.IsRunning()) +} + +func TestSwitchStopPeerForError(t *testing.T) { + s := httptest.NewServer(promhttp.Handler()) + defer s.Close() + + scrapeMetrics := func() string { + resp, err := http.Get(s.URL) + require.NoError(t, err) + defer resp.Body.Close() + buf, _ := io.ReadAll(resp.Body) + return string(buf) + } + + namespace, subsystem, name := config.TestInstrumentationConfig().Namespace, MetricsSubsystem, "peers" + re := regexp.MustCompile(namespace + `_` + subsystem + `_` + name + ` ([0-9\.]+)`) + peersMetricValue := func() float64 { + matches := re.FindStringSubmatch(scrapeMetrics()) + f, _ := strconv.ParseFloat(matches[1], 64) + return f + } + + p2pMetrics := PrometheusMetrics(namespace) + + // make two connected switches + sw1, sw2 := MakeSwitchPair(func(i int, sw *Switch) *Switch { + // set metrics on sw1 + if i == 0 { + opt := WithMetrics(p2pMetrics) + opt(sw) + } + return initSwitchFunc(i, sw) + }) + + assert.Equal(t, len(sw1.Peers().List()), 1) + assert.EqualValues(t, 1, peersMetricValue()) + + // send messages to the peer from sw1 + p := sw1.Peers().List()[0] + p.Send(Envelope{ + ChannelID: 0x1, + Message: &p2pproto.Message{}, + }) + + // stop sw2. this should cause the p to fail, + // which results in calling StopPeerForError internally + t.Cleanup(func() { + if err := sw2.Stop(); err != nil { + t.Error(err) + } + }) + + // now call StopPeerForError explicitly, eg. from a reactor + sw1.StopPeerForError(p, fmt.Errorf("some err")) + + assert.Equal(t, len(sw1.Peers().List()), 0) + assert.EqualValues(t, 0, peersMetricValue()) +} + +func TestSwitchReconnectsToOutboundPersistentPeer(t *testing.T) { + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // 1. simulate failure by closing connection + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + err = sw.AddPersistentPeers([]string{rp.Addr().String()}) + require.NoError(t, err) + + err = sw.DialPeerWithAddress(rp.Addr()) + require.Nil(t, err) + require.NotNil(t, sw.Peers().Get(rp.ID())) + + p := sw.Peers().List()[0] + err = p.(*peer).CloseConn() + require.NoError(t, err) + + waitUntilSwitchHasAtLeastNPeers(sw, 1) + assert.False(t, p.IsRunning()) // old peer instance + assert.Equal(t, 1, sw.Peers().Size()) // new peer instance + + // 2. simulate first time dial failure + rp = &remotePeer{ + PrivKey: ed25519.GenPrivKey(), + Config: cfg, + // Use different interface to prevent duplicate IP filter, this will break + // beyond two peers. + listenAddr: "127.0.0.1:0", + } + rp.Start() + defer rp.Stop() + + conf := config.DefaultP2PConfig() + conf.TestDialFail = true // will trigger a reconnect + err = sw.addOutboundPeerWithConfig(rp.Addr(), conf) + require.NotNil(t, err) + // DialPeerWithAddres - sw.peerConfig resets the dialer + waitUntilSwitchHasAtLeastNPeers(sw, 2) + assert.Equal(t, 2, sw.Peers().Size()) +} + +func TestSwitchReconnectsToInboundPersistentPeer(t *testing.T) { + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // 1. simulate failure by closing the connection + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + err = sw.AddPersistentPeers([]string{rp.Addr().String()}) + require.NoError(t, err) + + conn, err := rp.Dial(sw.NetAddress()) + require.NoError(t, err) + time.Sleep(50 * time.Millisecond) + require.NotNil(t, sw.Peers().Get(rp.ID())) + + conn.Close() + + waitUntilSwitchHasAtLeastNPeers(sw, 1) + assert.Equal(t, 1, sw.Peers().Size()) +} + +func TestSwitchDialPeersAsync(t *testing.T) { + if testing.Short() { + return + } + + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + + err = sw.DialPeersAsync([]string{rp.Addr().String()}) + require.NoError(t, err) + time.Sleep(dialRandomizerIntervalMilliseconds * time.Millisecond) + require.NotNil(t, sw.Peers().Get(rp.ID())) +} + +func waitUntilSwitchHasAtLeastNPeers(sw *Switch, n int) { + for i := 0; i < 20; i++ { + time.Sleep(250 * time.Millisecond) + has := sw.Peers().Size() + if has >= n { + break + } + } +} + +func TestSwitchFullConnectivity(t *testing.T) { + switches := MakeConnectedSwitches(cfg, 3, initSwitchFunc, Connect2Switches) + defer func() { + for _, sw := range switches { + sw := sw + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + } + }() + + for i, sw := range switches { + if sw.Peers().Size() != 2 { + t.Fatalf("Expected each switch to be connected to 2 other, but %d switch only connected to %d", sw.Peers().Size(), i) + } + } +} + +func TestSwitchAcceptRoutine(t *testing.T) { + cfg.MaxNumInboundPeers = 5 + + // Create some unconditional peers. + const unconditionalPeersNum = 2 + var ( + unconditionalPeers = make([]*remotePeer, unconditionalPeersNum) + unconditionalPeerIDs = make([]string, unconditionalPeersNum) + ) + for i := 0; i < unconditionalPeersNum; i++ { + peer := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + peer.Start() + unconditionalPeers[i] = peer + unconditionalPeerIDs[i] = string(peer.ID()) + } + + // make switch + sw := MakeSwitch(cfg, 1, initSwitchFunc) + err := sw.AddUnconditionalPeerIDs(unconditionalPeerIDs) + require.NoError(t, err) + err = sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + err := sw.Stop() + require.NoError(t, err) + }) + + // 0. check there are no peers + assert.Equal(t, 0, sw.Peers().Size()) + + // 1. check we connect up to MaxNumInboundPeers + peers := make([]*remotePeer, 0) + for i := 0; i < cfg.MaxNumInboundPeers; i++ { + peer := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + peers = append(peers, peer) + peer.Start() + c, err := peer.Dial(sw.NetAddress()) + require.NoError(t, err) + // spawn a reading routine to prevent connection from closing + go func(c net.Conn) { + for { + one := make([]byte, 1) + _, err := c.Read(one) + if err != nil { + return + } + } + }(c) + } + time.Sleep(100 * time.Millisecond) + assert.Equal(t, cfg.MaxNumInboundPeers, sw.Peers().Size()) + + // 2. check we close new connections if we already have MaxNumInboundPeers peers + peer := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + peer.Start() + conn, err := peer.Dial(sw.NetAddress()) + require.NoError(t, err) + // check conn is closed + one := make([]byte, 1) + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Millisecond)) + _, err = conn.Read(one) + assert.Error(t, err) + assert.Equal(t, cfg.MaxNumInboundPeers, sw.Peers().Size()) + peer.Stop() + + // 3. check we connect to unconditional peers despite the limit. + for _, peer := range unconditionalPeers { + c, err := peer.Dial(sw.NetAddress()) + require.NoError(t, err) + // spawn a reading routine to prevent connection from closing + go func(c net.Conn) { + for { + one := make([]byte, 1) + _, err := c.Read(one) + if err != nil { + return + } + } + }(c) + } + time.Sleep(10 * time.Millisecond) + assert.Equal(t, cfg.MaxNumInboundPeers+unconditionalPeersNum, sw.Peers().Size()) + + for _, peer := range peers { + peer.Stop() + } + for _, peer := range unconditionalPeers { + peer.Stop() + } +} + +type errorTransport struct { + acceptErr error +} + +func (et errorTransport) NetAddress() NetAddress { + panic("not implemented") +} + +func (et errorTransport) Accept(peerConfig) (Peer, error) { + return nil, et.acceptErr +} + +func (errorTransport) Dial(NetAddress, peerConfig) (Peer, error) { + panic("not implemented") +} + +func (errorTransport) Cleanup(Peer) { + panic("not implemented") +} + +func TestSwitchAcceptRoutineErrorCases(t *testing.T) { + sw := NewSwitch(cfg, errorTransport{ErrFilterTimeout{}}) + assert.NotPanics(t, func() { + err := sw.Start() + require.NoError(t, err) + err = sw.Stop() + require.NoError(t, err) + }) + + sw = NewSwitch(cfg, errorTransport{ErrRejected{conn: nil, err: errors.New("filtered"), isFiltered: true}}) + assert.NotPanics(t, func() { + err := sw.Start() + require.NoError(t, err) + err = sw.Stop() + require.NoError(t, err) + }) + // TODO(melekes) check we remove our address from addrBook + + sw = NewSwitch(cfg, errorTransport{ErrTransportClosed{}}) + assert.NotPanics(t, func() { + err := sw.Start() + require.NoError(t, err) + err = sw.Stop() + require.NoError(t, err) + }) +} + +// mockReactor checks that InitPeer never called before RemovePeer. If that's +// not true, InitCalledBeforeRemoveFinished will return true. +type mockReactor struct { + *BaseReactor + + // atomic + removePeerInProgress uint32 + initCalledBeforeRemoveFinished uint32 +} + +func (r *mockReactor) RemovePeer(Peer, interface{}) { + atomic.StoreUint32(&r.removePeerInProgress, 1) + defer atomic.StoreUint32(&r.removePeerInProgress, 0) + time.Sleep(100 * time.Millisecond) +} + +func (r *mockReactor) InitPeer(peer Peer) Peer { + if atomic.LoadUint32(&r.removePeerInProgress) == 1 { + atomic.StoreUint32(&r.initCalledBeforeRemoveFinished, 1) + } + + return peer +} + +func (r *mockReactor) InitCalledBeforeRemoveFinished() bool { + return atomic.LoadUint32(&r.initCalledBeforeRemoveFinished) == 1 +} + +// see stopAndRemovePeer +func TestSwitchInitPeerIsNotCalledBeforeRemovePeer(t *testing.T) { + // make reactor + reactor := &mockReactor{} + reactor.BaseReactor = NewBaseReactor("mockReactor", reactor) + + // make switch + sw := MakeSwitch(cfg, 1, func(i int, sw *Switch) *Switch { + sw.AddReactor("mock", reactor) + return sw + }) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + // add peer + rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} + rp.Start() + defer rp.Stop() + _, err = rp.Dial(sw.NetAddress()) + require.NoError(t, err) + + // wait till the switch adds rp to the peer set, then stop the peer asynchronously + for { + time.Sleep(20 * time.Millisecond) + if peer := sw.Peers().Get(rp.ID()); peer != nil { + go sw.StopPeerForError(peer, "test") + break + } + } + + // simulate peer reconnecting to us + _, err = rp.Dial(sw.NetAddress()) + require.NoError(t, err) + // wait till the switch adds rp to the peer set + time.Sleep(50 * time.Millisecond) + + // make sure reactor.RemovePeer is finished before InitPeer is called + assert.False(t, reactor.InitCalledBeforeRemoveFinished()) +} + +func BenchmarkSwitchBroadcast(b *testing.B) { + s1, s2 := MakeSwitchPair(func(i int, sw *Switch) *Switch { + // Make bar reactors of bar channels each + sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{ + {ID: byte(0x00), Priority: 10}, + {ID: byte(0x01), Priority: 10}, + }, false)) + sw.AddReactor("bar", NewTestReactor([]*conn.ChannelDescriptor{ + {ID: byte(0x02), Priority: 10}, + {ID: byte(0x03), Priority: 10}, + }, false)) + return sw + }) + + b.Cleanup(func() { + if err := s1.Stop(); err != nil { + b.Error(err) + } + }) + + b.Cleanup(func() { + if err := s2.Stop(); err != nil { + b.Error(err) + } + }) + + // Allow time for goroutines to boot up + time.Sleep(1 * time.Second) + + b.ResetTimer() + + numSuccess, numFailure := 0, 0 + + // Send random message from foo channel to another + for i := 0; i < b.N; i++ { + chID := byte(i % 4) + successChan := s1.Broadcast(Envelope{ChannelID: chID}) + for s := range successChan { + if s { + numSuccess++ + } else { + numFailure++ + } + } + } + + b.Logf("success: %v, failure: %v", numSuccess, numFailure) +} + +func TestSwitchRemovalErr(t *testing.T) { + sw1, sw2 := MakeSwitchPair(func(i int, sw *Switch) *Switch { + return initSwitchFunc(i, sw) + }) + assert.Equal(t, len(sw1.Peers().List()), 1) + p := sw1.Peers().List()[0] + + sw2.StopPeerForError(p, fmt.Errorf("peer should error")) + + assert.Equal(t, sw2.peers.Add(p).Error(), ErrPeerRemoval{}.Error()) +} diff --git a/p2p/test_util.go b/p2p/test_util.go new file mode 100644 index 0000000..9709d69 --- /dev/null +++ b/p2p/test_util.go @@ -0,0 +1,315 @@ +package p2p + +import ( + "fmt" + "net" + "time" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + cmtrand "github.com/cometbft/cometbft/libs/rand" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/p2p/conn" +) + +const testCh = 0x01 + +//------------------------------------------------ + +type mockNodeInfo struct { + addr *NetAddress +} + +func (ni mockNodeInfo) ID() ID { return ni.addr.ID } +func (ni mockNodeInfo) NetAddress() (*NetAddress, error) { return ni.addr, nil } +func (ni mockNodeInfo) Validate() error { return nil } +func (ni mockNodeInfo) CompatibleWith(NodeInfo) error { return nil } + +func AddPeerToSwitchPeerSet(sw *Switch, peer Peer) { + sw.peers.Add(peer) //nolint:errcheck // ignore error +} + +func CreateRandomPeer(outbound bool) Peer { + addr, netAddr := CreateRoutableAddr() + p := &peer{ + peerConn: peerConn{ + outbound: outbound, + socketAddr: netAddr, + }, + nodeInfo: mockNodeInfo{netAddr}, + mconn: &conn.MConnection{}, + metrics: NopMetrics(), + } + p.SetLogger(log.TestingLogger().With("peer", addr)) + return p +} + +func CreateRoutableAddr() (addr string, netAddr *NetAddress) { + for { + var err error + addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656", + cmtrand.Bytes(20), + cmtrand.Int()%256, + cmtrand.Int()%256, + cmtrand.Int()%256, + cmtrand.Int()%256) + netAddr, err = NewNetAddressString(addr) + if err != nil { + panic(err) + } + if netAddr.Routable() { + break + } + } + return +} + +//------------------------------------------------------------------ +// Connects switches via arbitrary net.Conn. Used for testing. + +const TestHost = "localhost" + +// MakeConnectedSwitches returns n switches, connected according to the connect func. +// If connect==Connect2Switches, the switches will be fully connected. +// initSwitch defines how the i'th switch should be initialized (ie. with what reactors). +// NOTE: panics if any switch fails to start. +func MakeConnectedSwitches(cfg *config.P2PConfig, + n int, + initSwitch func(int, *Switch) *Switch, + connect func([]*Switch, int, int), +) []*Switch { + switches := make([]*Switch, n) + for i := 0; i < n; i++ { + switches[i] = MakeSwitch(cfg, i, initSwitch) + } + + if err := StartSwitches(switches); err != nil { + panic(err) + } + + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + connect(switches, i, j) + } + } + + return switches +} + +// Connect2Switches will connect switches i and j via net.Pipe(). +// Blocks until a connection is established. +// NOTE: caller ensures i and j are within bounds. +func Connect2Switches(switches []*Switch, i, j int) { + switchI := switches[i] + switchJ := switches[j] + + c1, c2 := conn.NetPipe() + + doneCh := make(chan struct{}) + go func() { + err := switchI.addPeerWithConnection(c1) + if err != nil { + panic(err) + } + doneCh <- struct{}{} + }() + go func() { + err := switchJ.addPeerWithConnection(c2) + if err != nil { + panic(err) + } + doneCh <- struct{}{} + }() + <-doneCh + <-doneCh +} + +func (sw *Switch) addPeerWithConnection(conn net.Conn) error { + pc, err := testInboundPeerConn(conn, sw.config, sw.nodeKey.PrivKey) + if err != nil { + if err := conn.Close(); err != nil { + sw.Logger.Error("Error closing connection", "err", err) + } + return err + } + + ni, err := handshake(conn, time.Second, sw.nodeInfo) + if err != nil { + if err := conn.Close(); err != nil { + sw.Logger.Error("Error closing connection", "err", err) + } + return err + } + + p := newPeer( + pc, + MConnConfig(sw.config), + ni, + sw.reactorsByCh, + sw.msgTypeByChID, + sw.chDescs, + sw.StopPeerForError, + sw.mlc, + ) + + if err = sw.addPeer(p); err != nil { + pc.CloseConn() + return err + } + + return nil +} + +// StartSwitches calls sw.Start() for each given switch. +// It returns the first encountered error. +func StartSwitches(switches []*Switch) error { + for _, s := range switches { + err := s.Start() // start switch and reactors + if err != nil { + return err + } + } + return nil +} + +func MakeSwitch( + cfg *config.P2PConfig, + i int, + initSwitch func(int, *Switch) *Switch, + opts ...SwitchOption, +) *Switch { + nodeKey := NodeKey{ + PrivKey: ed25519.GenPrivKey(), + } + nodeInfo := testNodeInfo(nodeKey.ID(), fmt.Sprintf("node%d", i)) + addr, err := NewNetAddressString( + IDAddressString(nodeKey.ID(), nodeInfo.(DefaultNodeInfo).ListenAddr), + ) + if err != nil { + panic(err) + } + + t := NewMultiplexTransport(nodeInfo, nodeKey, MConnConfig(cfg)) + + if err := t.Listen(*addr); err != nil { + panic(err) + } + + // TODO: let the config be passed in? + sw := initSwitch(i, NewSwitch(cfg, t, opts...)) + sw.SetLogger(log.TestingLogger().With("switch", i)) + sw.SetNodeKey(&nodeKey) + + ni := nodeInfo.(DefaultNodeInfo) + for ch := range sw.reactorsByCh { + ni.Channels = append(ni.Channels, ch) + } + nodeInfo = ni + + // TODO: We need to setup reactors ahead of time so the NodeInfo is properly + // populated and we don't have to do those awkward overrides and setters. + t.nodeInfo = nodeInfo + sw.SetNodeInfo(nodeInfo) + + return sw +} + +func testInboundPeerConn( + conn net.Conn, + config *config.P2PConfig, + ourNodePrivKey crypto.PrivKey, +) (peerConn, error) { + return testPeerConn(conn, config, false, false, ourNodePrivKey, nil) +} + +func testPeerConn( + rawConn net.Conn, + cfg *config.P2PConfig, + outbound, persistent bool, + ourNodePrivKey crypto.PrivKey, + socketAddr *NetAddress, +) (pc peerConn, err error) { + conn := rawConn + + // Fuzz connection + if cfg.TestFuzz { + // so we have time to do peer handshakes and get set up + conn = FuzzConnAfterFromConfig(conn, 10*time.Second, cfg.TestFuzzConfig) + } + + // Encrypt connection + conn, err = upgradeSecretConn(conn, cfg.HandshakeTimeout, ourNodePrivKey) + if err != nil { + return pc, fmt.Errorf("error creating peer: %w", err) + } + + // Only the information we already have + return newPeerConn(outbound, persistent, conn, socketAddr), nil +} + +//---------------------------------------------------------------- +// rand node info + +func testNodeInfo(id ID, name string) NodeInfo { + return testNodeInfoWithNetwork(id, name, "testing") +} + +func testNodeInfoWithNetwork(id ID, name, network string) NodeInfo { + return DefaultNodeInfo{ + ProtocolVersion: defaultProtocolVersion, + DefaultNodeID: id, + ListenAddr: fmt.Sprintf("127.0.0.1:%d", getFreePort()), + Network: network, + Version: "1.2.3-rc0-deadbeef", + Channels: []byte{testCh}, + Moniker: name, + Other: DefaultNodeInfoOther{ + TxIndex: "on", + RPCAddress: fmt.Sprintf("127.0.0.1:%d", getFreePort()), + }, + } +} + +func getFreePort() int { + port, err := cmtnet.GetFreePort() + if err != nil { + panic(err) + } + return port +} + +type AddrBookMock struct { + Addrs map[string]struct{} + OurAddrs map[string]struct{} + PrivateAddrs map[string]struct{} +} + +var _ AddrBook = (*AddrBookMock)(nil) + +func (book *AddrBookMock) AddAddress(addr *NetAddress, _ *NetAddress) error { + book.Addrs[addr.String()] = struct{}{} + return nil +} +func (book *AddrBookMock) AddOurAddress(addr *NetAddress) { book.OurAddrs[addr.String()] = struct{}{} } +func (book *AddrBookMock) OurAddress(addr *NetAddress) bool { + _, ok := book.OurAddrs[addr.String()] + return ok +} +func (book *AddrBookMock) MarkGood(ID) {} +func (book *AddrBookMock) HasAddress(addr *NetAddress) bool { + _, ok := book.Addrs[addr.String()] + return ok +} + +func (book *AddrBookMock) RemoveAddress(addr *NetAddress) { + delete(book.Addrs, addr.String()) +} +func (book *AddrBookMock) Save() {} +func (book *AddrBookMock) AddPrivateIDs(addrs []string) { + for _, addr := range addrs { + book.PrivateAddrs[addr] = struct{}{} + } +} diff --git a/p2p/transport.go b/p2p/transport.go new file mode 100644 index 0000000..c26056e --- /dev/null +++ b/p2p/transport.go @@ -0,0 +1,618 @@ +package p2p + +import ( + "context" + "fmt" + "net" + "time" + + "golang.org/x/net/netutil" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/libs/protoio" + "github.com/cometbft/cometbft/p2p/conn" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +const ( + defaultDialTimeout = time.Second + defaultFilterTimeout = 5 * time.Second + defaultHandshakeTimeout = 3 * time.Second +) + +// IPResolver is a behavior subset of net.Resolver. +type IPResolver interface { + LookupIPAddr(context.Context, string) ([]net.IPAddr, error) +} + +// accept is the container to carry the upgraded connection and NodeInfo from an +// asynchronously running routine to the Accept method. +type accept struct { + netAddr *NetAddress + conn net.Conn + nodeInfo NodeInfo + err error +} + +// peerConfig is used to bundle data we need to fully setup a Peer with an +// MConn, provided by the caller of Accept and Dial (currently the Switch). This +// a temporary measure until reactor setup is less dynamic and we introduce the +// concept of PeerBehaviour to communicate about significant Peer lifecycle +// events. +// TODO(xla): Refactor out with more static Reactor setup and PeerBehaviour. +type peerConfig struct { + chDescs []*conn.ChannelDescriptor + onPeerError func(Peer, interface{}) + outbound bool + // isPersistent allows you to set a function, which, given socket address + // (for outbound peers) OR self-reported address (for inbound peers), tells + // if the peer is persistent or not. + isPersistent func(*NetAddress) bool + reactorsByCh map[byte]Reactor + msgTypeByChID map[byte]proto.Message + metrics *Metrics + mlc *metricsLabelCache +} + +// Transport emits and connects to Peers. The implementation of Peer is left to +// the transport. Each transport is also responsible to filter establishing +// peers specific to its domain. +type Transport interface { + // Listening address. + NetAddress() NetAddress + + // Accept returns a newly connected Peer. + Accept(peerConfig) (Peer, error) + + // Dial connects to the Peer for the address. + Dial(NetAddress, peerConfig) (Peer, error) + + // Cleanup any resources associated with Peer. + Cleanup(Peer) +} + +// transportLifecycle bundles the methods for callers to control start and stop +// behavior. +type transportLifecycle interface { + Close() error + Listen(NetAddress) error +} + +// ConnFilterFunc to be implemented by filter hooks after a new connection has +// been established. The set of exisiting connections is passed along together +// with all resolved IPs for the new connection. +type ConnFilterFunc func(ConnSet, net.Conn, []net.IP) error + +// ConnDuplicateIPFilter resolves and keeps all ips for an incoming connection +// and refuses new ones if they come from a known ip. +func ConnDuplicateIPFilter() ConnFilterFunc { + return func(cs ConnSet, c net.Conn, ips []net.IP) error { + for _, ip := range ips { + if cs.HasIP(ip) { + return ErrRejected{ + conn: c, + err: fmt.Errorf("ip<%v> already connected", ip), + isDuplicate: true, + } + } + } + + return nil + } +} + +// MultiplexTransportOption sets an optional parameter on the +// MultiplexTransport. +type MultiplexTransportOption func(*MultiplexTransport) + +// MultiplexTransportConnFilters sets the filters for rejection new connections. +func MultiplexTransportConnFilters( + filters ...ConnFilterFunc, +) MultiplexTransportOption { + return func(mt *MultiplexTransport) { mt.connFilters = filters } +} + +// MultiplexTransportFilterTimeout sets the timeout waited for filter calls to +// return. +func MultiplexTransportFilterTimeout( + timeout time.Duration, +) MultiplexTransportOption { + return func(mt *MultiplexTransport) { mt.filterTimeout = timeout } +} + +// MultiplexTransportResolver sets the Resolver used for ip lokkups, defaults to +// net.DefaultResolver. +func MultiplexTransportResolver(resolver IPResolver) MultiplexTransportOption { + return func(mt *MultiplexTransport) { mt.resolver = resolver } +} + +// MultiplexTransportMaxIncomingConnections sets the maximum number of +// simultaneous connections (incoming). Default: 0 (unlimited) +func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption { + return func(mt *MultiplexTransport) { mt.maxIncomingConnections = n } +} + +// MultiplexTransport accepts and dials tcp connections and upgrades them to +// multiplexed peers. +type MultiplexTransport struct { + netAddr NetAddress + listener net.Listener + maxIncomingConnections int // see MaxIncomingConnections + + acceptc chan accept + closec chan struct{} + + // Lookup table for duplicate ip and id checks. + conns ConnSet + connFilters []ConnFilterFunc + + dialTimeout time.Duration + filterTimeout time.Duration + handshakeTimeout time.Duration + nodeInfo NodeInfo + nodeKey NodeKey + resolver IPResolver + + // TODO(xla): This config is still needed as we parameterise peerConn and + // peer currently. All relevant configuration should be refactored into options + // with sane defaults. + mConfig conn.MConnConfig +} + +// Test multiplexTransport for interface completeness. +var _ Transport = (*MultiplexTransport)(nil) +var _ transportLifecycle = (*MultiplexTransport)(nil) + +// NewMultiplexTransport returns a tcp connected multiplexed peer. +func NewMultiplexTransport( + nodeInfo NodeInfo, + nodeKey NodeKey, + mConfig conn.MConnConfig, +) *MultiplexTransport { + return &MultiplexTransport{ + acceptc: make(chan accept), + closec: make(chan struct{}), + dialTimeout: defaultDialTimeout, + filterTimeout: defaultFilterTimeout, + handshakeTimeout: defaultHandshakeTimeout, + mConfig: mConfig, + nodeInfo: nodeInfo, + nodeKey: nodeKey, + conns: NewConnSet(), + resolver: net.DefaultResolver, + } +} + +// NetAddress implements Transport. +func (mt *MultiplexTransport) NetAddress() NetAddress { + return mt.netAddr +} + +// Accept implements Transport. +func (mt *MultiplexTransport) Accept(cfg peerConfig) (Peer, error) { + select { + // This case should never have any side-effectful/blocking operations to + // ensure that quality peers are ready to be used. + case a := <-mt.acceptc: + if a.err != nil { + return nil, a.err + } + + cfg.outbound = false + + return mt.wrapPeer(a.conn, a.nodeInfo, cfg, a.netAddr), nil + case <-mt.closec: + return nil, ErrTransportClosed{} + } +} + +// Dial implements Transport. +func (mt *MultiplexTransport) Dial( + addr NetAddress, + cfg peerConfig, +) (Peer, error) { + c, err := addr.DialTimeout(mt.dialTimeout) + if err != nil { + return nil, err + } + + if mt.mConfig.TestFuzz { + // so we have time to do peer handshakes and get set up. + c = FuzzConnAfterFromConfig(c, 10*time.Second, mt.mConfig.TestFuzzConfig) + } + + // TODO(xla): Evaluate if we should apply filters if we explicitly dial. + if err := mt.filterConn(c); err != nil { + return nil, err + } + + secretConn, nodeInfo, err := mt.upgrade(c, &addr) + if err != nil { + return nil, err + } + + cfg.outbound = true + + p := mt.wrapPeer(secretConn, nodeInfo, cfg, &addr) + + return p, nil +} + +// Close implements transportLifecycle. +func (mt *MultiplexTransport) Close() error { + close(mt.closec) + + if mt.listener != nil { + return mt.listener.Close() + } + + return nil +} + +// Listen implements transportLifecycle. +func (mt *MultiplexTransport) Listen(addr NetAddress) error { + ln, err := net.Listen("tcp", addr.DialString()) + if err != nil { + return err + } + + if mt.maxIncomingConnections > 0 { + ln = netutil.LimitListener(ln, mt.maxIncomingConnections) + } + + mt.netAddr = addr + mt.listener = ln + + go mt.acceptPeers() + + return nil +} + +// AddChannel registers a channel to nodeInfo. +// NOTE: NodeInfo must be of type DefaultNodeInfo else channels won't be updated +// This is a bit messy at the moment but is cleaned up in the following version +// when NodeInfo changes from an interface to a concrete type +func (mt *MultiplexTransport) AddChannel(chID byte) { + if ni, ok := mt.nodeInfo.(DefaultNodeInfo); ok { + if !ni.HasChannel(chID) { + ni.Channels = append(ni.Channels, chID) + } + mt.nodeInfo = ni + } +} + +func (mt *MultiplexTransport) acceptPeers() { + for { + c, err := mt.listener.Accept() + if err != nil { + // If Close() has been called, silently exit. + select { + case _, ok := <-mt.closec: + if !ok { + return + } + default: + // Transport is not closed + } + + mt.acceptc <- accept{err: err} + return + } + + // Connection upgrade and filtering should be asynchronous to avoid + // Head-of-line blocking[0]. + // Reference: https://github.com/tendermint/tendermint/issues/2047 + // + // [0] https://en.wikipedia.org/wiki/Head-of-line_blocking + go func(c net.Conn) { + defer func() { + if r := recover(); r != nil { + err := ErrRejected{ + conn: c, + err: fmt.Errorf("recovered from panic: %v", r), + isAuthFailure: true, + } + select { + case mt.acceptc <- accept{err: err}: + case <-mt.closec: + // Give up if the transport was closed. + _ = c.Close() + return + } + } + }() + + var ( + nodeInfo NodeInfo + secretConn *conn.SecretConnection + netAddr *NetAddress + ) + + err := mt.filterConn(c) + if err == nil { + secretConn, nodeInfo, err = mt.upgrade(c, nil) + if err == nil { + addr := c.RemoteAddr() + id := PubKeyToID(secretConn.RemotePubKey()) + netAddr = NewNetAddress(id, addr) + } + } + + select { + case mt.acceptc <- accept{netAddr, secretConn, nodeInfo, err}: + // Make the upgraded peer available. + case <-mt.closec: + // Give up if the transport was closed. + _ = c.Close() + return + } + }(c) + } +} + +// Cleanup removes the given address from the connections set and +// closes the connection. +func (mt *MultiplexTransport) Cleanup(p Peer) { + mt.conns.RemoveAddr(p.RemoteAddr()) + _ = p.CloseConn() +} + +func (mt *MultiplexTransport) cleanup(c net.Conn) error { + mt.conns.Remove(c) + + return c.Close() +} + +func (mt *MultiplexTransport) filterConn(c net.Conn) (err error) { + defer func() { + if err != nil { + _ = c.Close() + } + }() + + // Reject if connection is already present. + if mt.conns.Has(c) { + return ErrRejected{conn: c, isDuplicate: true} + } + + // Resolve ips for incoming conn. + ips, err := resolveIPs(mt.resolver, c) + if err != nil { + return err + } + + errc := make(chan error, len(mt.connFilters)) + + for _, f := range mt.connFilters { + go func(f ConnFilterFunc, c net.Conn, ips []net.IP, errc chan<- error) { + errc <- f(mt.conns, c, ips) + }(f, c, ips, errc) + } + + for i := 0; i < cap(errc); i++ { + select { + case err := <-errc: + if err != nil { + return ErrRejected{conn: c, err: err, isFiltered: true} + } + case <-time.After(mt.filterTimeout): + return ErrFilterTimeout{} + } + + } + + mt.conns.Set(c, ips) + + return nil +} + +func (mt *MultiplexTransport) upgrade( + c net.Conn, + dialedAddr *NetAddress, +) (secretConn *conn.SecretConnection, nodeInfo NodeInfo, err error) { + defer func() { + if err != nil { + _ = mt.cleanup(c) + } + }() + + secretConn, err = upgradeSecretConn(c, mt.handshakeTimeout, mt.nodeKey.PrivKey) + if err != nil { + return nil, nil, ErrRejected{ + conn: c, + err: fmt.Errorf("secret conn failed: %v", err), + isAuthFailure: true, + } + } + + // For outgoing conns, ensure connection key matches dialed key. + connID := PubKeyToID(secretConn.RemotePubKey()) + if dialedAddr != nil { + if dialedID := dialedAddr.ID; connID != dialedID { + return nil, nil, ErrRejected{ + conn: c, + id: connID, + err: fmt.Errorf( + "conn.ID (%v) dialed ID (%v) mismatch", + connID, + dialedID, + ), + isAuthFailure: true, + } + } + } + + nodeInfo, err = handshake(secretConn, mt.handshakeTimeout, mt.nodeInfo) + if err != nil { + return nil, nil, ErrRejected{ + conn: c, + err: fmt.Errorf("handshake failed: %v", err), + isAuthFailure: true, + } + } + + if err := nodeInfo.Validate(); err != nil { + return nil, nil, ErrRejected{ + conn: c, + err: err, + isNodeInfoInvalid: true, + } + } + + // Ensure connection key matches self reported key. + if connID != nodeInfo.ID() { + return nil, nil, ErrRejected{ + conn: c, + id: connID, + err: fmt.Errorf( + "conn.ID (%v) NodeInfo.ID (%v) mismatch", + connID, + nodeInfo.ID(), + ), + isAuthFailure: true, + } + } + + // Reject self. + if mt.nodeInfo.ID() == nodeInfo.ID() { + return nil, nil, ErrRejected{ + addr: *NewNetAddress(nodeInfo.ID(), c.RemoteAddr()), + conn: c, + id: nodeInfo.ID(), + isSelf: true, + } + } + + if err := mt.nodeInfo.CompatibleWith(nodeInfo); err != nil { + return nil, nil, ErrRejected{ + conn: c, + err: err, + id: nodeInfo.ID(), + isIncompatible: true, + } + } + + return secretConn, nodeInfo, nil +} + +func (mt *MultiplexTransport) wrapPeer( + c net.Conn, + ni NodeInfo, + cfg peerConfig, + socketAddr *NetAddress, +) Peer { + + persistent := false + if cfg.isPersistent != nil { + if cfg.outbound { + persistent = cfg.isPersistent(socketAddr) + } else { + selfReportedAddr, err := ni.NetAddress() + if err == nil { + persistent = cfg.isPersistent(selfReportedAddr) + } + } + } + + peerConn := newPeerConn( + cfg.outbound, + persistent, + c, + socketAddr, + ) + + p := newPeer( + peerConn, + mt.mConfig, + ni, + cfg.reactorsByCh, + cfg.msgTypeByChID, + cfg.chDescs, + cfg.onPeerError, + cfg.mlc, + PeerMetrics(cfg.metrics), + ) + + return p +} + +func handshake( + c net.Conn, + timeout time.Duration, + nodeInfo NodeInfo, +) (NodeInfo, error) { + if err := c.SetDeadline(time.Now().Add(timeout)); err != nil { + return nil, err + } + + var ( + errc = make(chan error, 2) + + pbpeerNodeInfo tmp2p.DefaultNodeInfo + peerNodeInfo DefaultNodeInfo + ourNodeInfo = nodeInfo.(DefaultNodeInfo) + ) + + go func(errc chan<- error, c net.Conn) { + _, err := protoio.NewDelimitedWriter(c).WriteMsg(ourNodeInfo.ToProto()) + errc <- err + }(errc, c) + go func(errc chan<- error, c net.Conn) { + protoReader := protoio.NewDelimitedReader(c, MaxNodeInfoSize()) + _, err := protoReader.ReadMsg(&pbpeerNodeInfo) + errc <- err + }(errc, c) + + for i := 0; i < cap(errc); i++ { + err := <-errc + if err != nil { + return nil, err + } + } + + peerNodeInfo, err := DefaultNodeInfoFromToProto(&pbpeerNodeInfo) + if err != nil { + return nil, err + } + + return peerNodeInfo, c.SetDeadline(time.Time{}) +} + +func upgradeSecretConn( + c net.Conn, + timeout time.Duration, + privKey crypto.PrivKey, +) (*conn.SecretConnection, error) { + if err := c.SetDeadline(time.Now().Add(timeout)); err != nil { + return nil, err + } + + sc, err := conn.MakeSecretConnection(c, privKey) + if err != nil { + return nil, err + } + + return sc, sc.SetDeadline(time.Time{}) +} + +func resolveIPs(resolver IPResolver, c net.Conn) ([]net.IP, error) { + host, _, err := net.SplitHostPort(c.RemoteAddr().String()) + if err != nil { + return nil, err + } + + addrs, err := resolver.LookupIPAddr(context.Background(), host) + if err != nil { + return nil, err + } + + ips := []net.IP{} + + for _, addr := range addrs { + ips = append(ips, addr.IP) + } + + return ips, nil +} diff --git a/p2p/transport_test.go b/p2p/transport_test.go new file mode 100644 index 0000000..ae87df6 --- /dev/null +++ b/p2p/transport_test.go @@ -0,0 +1,706 @@ +package p2p + +import ( + "fmt" + "math/rand" + "net" + "reflect" + "runtime" + "strings" + "testing" + "time" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/protoio" + "github.com/cometbft/cometbft/p2p/conn" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +var defaultNodeName = "host_peer" + +func emptyNodeInfo() NodeInfo { + return DefaultNodeInfo{} +} + +// newMultiplexTransport returns a tcp connected multiplexed peer +// using the default MConnConfig. It's a convenience function used +// for testing. +func newMultiplexTransport( + nodeInfo NodeInfo, + nodeKey NodeKey, +) *MultiplexTransport { + return NewMultiplexTransport( + nodeInfo, nodeKey, conn.DefaultMConnConfig(), + ) +} + +func TestTransportMultiplexConnFilter(t *testing.T) { + mt := newMultiplexTransport( + emptyNodeInfo(), + NodeKey{ + PrivKey: ed25519.GenPrivKey(), + }, + ) + id := mt.nodeKey.ID() + + MultiplexTransportConnFilters( + func(_ ConnSet, _ net.Conn, _ []net.IP) error { return nil }, + func(_ ConnSet, _ net.Conn, _ []net.IP) error { return nil }, + func(_ ConnSet, _ net.Conn, _ []net.IP) error { + return fmt.Errorf("rejected") + }, + )(mt) + + addr, err := NewNetAddressString(IDAddressString(id, "127.0.0.1:0")) + if err != nil { + t.Fatal(err) + } + + if err := mt.Listen(*addr); err != nil { + t.Fatal(err) + } + + errc := make(chan error) + + go func() { + addr := NewNetAddress(id, mt.listener.Addr()) + + _, err := addr.Dial() + if err != nil { + errc <- err + return + } + + close(errc) + }() + + if err := <-errc; err != nil { + t.Errorf("connection failed: %v", err) + } + + _, err = mt.Accept(peerConfig{}) + if e, ok := err.(ErrRejected); ok { + if !e.IsFiltered() { + t.Errorf("expected peer to be filtered, got %v", err) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func TestTransportMultiplexConnFilterTimeout(t *testing.T) { + mt := newMultiplexTransport( + emptyNodeInfo(), + NodeKey{ + PrivKey: ed25519.GenPrivKey(), + }, + ) + id := mt.nodeKey.ID() + + MultiplexTransportFilterTimeout(5 * time.Millisecond)(mt) + MultiplexTransportConnFilters( + func(_ ConnSet, _ net.Conn, _ []net.IP) error { + time.Sleep(1 * time.Second) + return nil + }, + )(mt) + + addr, err := NewNetAddressString(IDAddressString(id, "127.0.0.1:0")) + if err != nil { + t.Fatal(err) + } + + if err := mt.Listen(*addr); err != nil { + t.Fatal(err) + } + + errc := make(chan error) + go func() { + addr := NewNetAddress(id, mt.listener.Addr()) + + _, err := addr.Dial() + if err != nil { + errc <- err + return + } + + close(errc) + }() + + if err := <-errc; err != nil { + t.Errorf("connection failed: %v", err) + } + + _, err = mt.Accept(peerConfig{}) + if _, ok := err.(ErrFilterTimeout); !ok { + t.Errorf("expected ErrFilterTimeout, got %v", err) + } +} + +func TestTransportMultiplexMaxIncomingConnections(t *testing.T) { + pv := ed25519.GenPrivKey() + id := PubKeyToID(pv.PubKey()) + mt := newMultiplexTransport( + testNodeInfo( + id, "transport", + ), + NodeKey{ + PrivKey: pv, + }, + ) + + MultiplexTransportMaxIncomingConnections(0)(mt) + + addr, err := NewNetAddressString(IDAddressString(id, "127.0.0.1:0")) + if err != nil { + t.Fatal(err) + } + const maxIncomingConns = 2 + MultiplexTransportMaxIncomingConnections(maxIncomingConns)(mt) + if err := mt.Listen(*addr); err != nil { + t.Fatal(err) + } + + laddr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + // Connect more peers than max + for i := 0; i <= maxIncomingConns; i++ { + errc := make(chan error) + go testDialer(*laddr, errc) + + err = <-errc + if i < maxIncomingConns { + if err != nil { + t.Errorf("dialer connection failed: %v", err) + } + _, err = mt.Accept(peerConfig{}) + if err != nil { + t.Errorf("connection failed: %v", err) + } + } else if err == nil || !strings.Contains(err.Error(), "i/o timeout") { + // mt actually blocks forever on trying to accept a new peer into a full channel so + // expect the dialer to encounter a timeout error. Calling mt.Accept will block until + // mt is closed. + t.Errorf("expected i/o timeout error, got %v", err) + } + } +} + +func TestTransportMultiplexAcceptMultiple(t *testing.T) { + mt := testSetupMultiplexTransport(t) + laddr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + var ( + seed = rand.New(rand.NewSource(time.Now().UnixNano())) + nDialers = seed.Intn(64) + 64 + errc = make(chan error, nDialers) + ) + + // Setup dialers. + for i := 0; i < nDialers; i++ { + go testDialer(*laddr, errc) + } + + // Catch connection errors. + for i := 0; i < nDialers; i++ { + if err := <-errc; err != nil { + t.Fatal(err) + } + } + + ps := []Peer{} + + // Accept all peers. + for i := 0; i < cap(errc); i++ { + p, err := mt.Accept(peerConfig{}) + if err != nil { + t.Fatal(err) + } + + if err := p.Start(); err != nil { + t.Fatal(err) + } + + ps = append(ps, p) + } + + if have, want := len(ps), cap(errc); have != want { + t.Errorf("have %v, want %v", have, want) + } + + // Stop all peers. + for _, p := range ps { + if err := p.Stop(); err != nil { + t.Fatal(err) + } + } + + if err := mt.Close(); err != nil { + t.Errorf("close errored: %v", err) + } +} + +func testDialer(dialAddr NetAddress, errc chan error) { + var ( + pv = ed25519.GenPrivKey() + dialer = newMultiplexTransport( + testNodeInfo(PubKeyToID(pv.PubKey()), defaultNodeName), + NodeKey{ + PrivKey: pv, + }, + ) + ) + + _, err := dialer.Dial(dialAddr, peerConfig{}) + if err != nil { + errc <- err + return + } + + // Signal that the connection was established. + errc <- nil +} + +func TestTransportMultiplexAcceptNonBlocking(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + var ( + fastNodePV = ed25519.GenPrivKey() + fastNodeInfo = testNodeInfo(PubKeyToID(fastNodePV.PubKey()), "fastnode") + errc = make(chan error) + fastc = make(chan struct{}) + slowc = make(chan struct{}) + slowdonec = make(chan struct{}) + ) + + // Simulate slow Peer. + go func() { + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + c, err := addr.Dial() + if err != nil { + errc <- err + return + } + + close(slowc) + defer func() { + close(slowdonec) + }() + + // Make sure we switch to fast peer goroutine. + runtime.Gosched() + + select { + case <-fastc: + // Fast peer connected. + case <-time.After(200 * time.Millisecond): + // We error if the fast peer didn't succeed. + errc <- fmt.Errorf("fast peer timed out") + } + + sc, err := upgradeSecretConn(c, 200*time.Millisecond, ed25519.GenPrivKey()) + if err != nil { + errc <- err + return + } + + _, err = handshake(sc, 200*time.Millisecond, + testNodeInfo( + PubKeyToID(ed25519.GenPrivKey().PubKey()), + "slow_peer", + )) + if err != nil { + errc <- err + } + }() + + // Simulate fast Peer. + go func() { + <-slowc + + var ( + dialer = newMultiplexTransport( + fastNodeInfo, + NodeKey{ + PrivKey: fastNodePV, + }, + ) + ) + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + _, err := dialer.Dial(*addr, peerConfig{}) + if err != nil { + errc <- err + return + } + + close(fastc) + <-slowdonec + close(errc) + }() + + if err := <-errc; err != nil { + t.Logf("connection failed: %v", err) + } + + p, err := mt.Accept(peerConfig{}) + if err != nil { + t.Fatal(err) + } + + if have, want := p.NodeInfo(), fastNodeInfo; !reflect.DeepEqual(have, want) { + t.Errorf("have %v, want %v", have, want) + } +} + +func TestTransportMultiplexValidateNodeInfo(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + errc := make(chan error) + + go func() { + var ( + pv = ed25519.GenPrivKey() + dialer = newMultiplexTransport( + testNodeInfo(PubKeyToID(pv.PubKey()), ""), // Should not be empty + NodeKey{ + PrivKey: pv, + }, + ) + ) + + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + _, err := dialer.Dial(*addr, peerConfig{}) + if err != nil { + errc <- err + return + } + + close(errc) + }() + + if err := <-errc; err != nil { + t.Errorf("connection failed: %v", err) + } + + _, err := mt.Accept(peerConfig{}) + if e, ok := err.(ErrRejected); ok { + if !e.IsNodeInfoInvalid() { + t.Errorf("expected NodeInfo to be invalid, got %v", err) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func TestTransportMultiplexRejectMissmatchID(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + errc := make(chan error) + + go func() { + dialer := newMultiplexTransport( + testNodeInfo( + PubKeyToID(ed25519.GenPrivKey().PubKey()), "dialer", + ), + NodeKey{ + PrivKey: ed25519.GenPrivKey(), + }, + ) + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + _, err := dialer.Dial(*addr, peerConfig{}) + if err != nil { + errc <- err + return + } + + close(errc) + }() + + if err := <-errc; err != nil { + t.Errorf("connection failed: %v", err) + } + + _, err := mt.Accept(peerConfig{}) + if e, ok := err.(ErrRejected); ok { + if !e.IsAuthFailure() { + t.Errorf("expected auth failure, got %v", e) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func TestTransportMultiplexDialRejectWrongID(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + var ( + pv = ed25519.GenPrivKey() + dialer = newMultiplexTransport( + testNodeInfo(PubKeyToID(pv.PubKey()), ""), // Should not be empty + NodeKey{ + PrivKey: pv, + }, + ) + ) + + wrongID := PubKeyToID(ed25519.GenPrivKey().PubKey()) + addr := NewNetAddress(wrongID, mt.listener.Addr()) + + _, err := dialer.Dial(*addr, peerConfig{}) + if err != nil { + t.Logf("connection failed: %v", err) + if e, ok := err.(ErrRejected); ok { + if !e.IsAuthFailure() { + t.Errorf("expected auth failure, got %v", e) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } + } +} + +func TestTransportMultiplexRejectIncompatible(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + errc := make(chan error) + + go func() { + var ( + pv = ed25519.GenPrivKey() + dialer = newMultiplexTransport( + testNodeInfoWithNetwork(PubKeyToID(pv.PubKey()), "dialer", "incompatible-network"), + NodeKey{ + PrivKey: pv, + }, + ) + ) + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + _, err := dialer.Dial(*addr, peerConfig{}) + if err != nil { + errc <- err + return + } + + close(errc) + }() + + _, err := mt.Accept(peerConfig{}) + if e, ok := err.(ErrRejected); ok { + if !e.IsIncompatible() { + t.Errorf("expected to reject incompatible, got %v", e) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func TestTransportMultiplexRejectSelf(t *testing.T) { + mt := testSetupMultiplexTransport(t) + + errc := make(chan error) + + go func() { + addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + + _, err := mt.Dial(*addr, peerConfig{}) + if err != nil { + errc <- err + return + } + + close(errc) + }() + + if err := <-errc; err != nil { + if e, ok := err.(ErrRejected); ok { + if !e.IsSelf() { + t.Errorf("expected to reject self, got: %v", e) + } + } else { + t.Errorf("expected ErrRejected, got %v", err) + } + } else { + t.Errorf("expected connection failure") + } + + _, err := mt.Accept(peerConfig{}) + if err, ok := err.(ErrRejected); ok { + if !err.IsSelf() { + t.Errorf("expected to reject self, got: %v", err) + } + } else { + t.Errorf("expected ErrRejected, got %v", nil) + } +} + +func TestTransportConnDuplicateIPFilter(t *testing.T) { + filter := ConnDuplicateIPFilter() + + if err := filter(nil, &testTransportConn{}, nil); err != nil { + t.Fatal(err) + } + + var ( + c = &testTransportConn{} + cs = NewConnSet() + ) + + cs.Set(c, []net.IP{ + {10, 0, 10, 1}, + {10, 0, 10, 2}, + {10, 0, 10, 3}, + }) + + if err := filter(cs, c, []net.IP{ + {10, 0, 10, 2}, + }); err == nil { + t.Errorf("expected Peer to be rejected as duplicate") + } +} + +func TestTransportHandshake(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + var ( + peerPV = ed25519.GenPrivKey() + peerNodeInfo = testNodeInfo(PubKeyToID(peerPV.PubKey()), defaultNodeName) + ) + + go func() { + c, err := net.Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Error(err) + return + } + + go func(c net.Conn) { + _, err := protoio.NewDelimitedWriter(c).WriteMsg(peerNodeInfo.(DefaultNodeInfo).ToProto()) + if err != nil { + t.Error(err) + } + }(c) + go func(c net.Conn) { + var ( + // ni DefaultNodeInfo + pbni tmp2p.DefaultNodeInfo + ) + + protoReader := protoio.NewDelimitedReader(c, MaxNodeInfoSize()) + _, err := protoReader.ReadMsg(&pbni) + if err != nil { + t.Error(err) + } + + _, err = DefaultNodeInfoFromToProto(&pbni) + if err != nil { + t.Error(err) + } + }(c) + }() + + c, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + + ni, err := handshake(c, 20*time.Millisecond, emptyNodeInfo()) + if err != nil { + t.Fatal(err) + } + + if have, want := ni, peerNodeInfo; !reflect.DeepEqual(have, want) { + t.Errorf("have %v, want %v", have, want) + } +} + +func TestTransportAddChannel(t *testing.T) { + mt := newMultiplexTransport( + emptyNodeInfo(), + NodeKey{ + PrivKey: ed25519.GenPrivKey(), + }, + ) + testChannel := byte(0x01) + + mt.AddChannel(testChannel) + if !mt.nodeInfo.(DefaultNodeInfo).HasChannel(testChannel) { + t.Errorf("missing added channel %v. Got %v", testChannel, mt.nodeInfo.(DefaultNodeInfo).Channels) + } +} + +// create listener +func testSetupMultiplexTransport(t *testing.T) *MultiplexTransport { + var ( + pv = ed25519.GenPrivKey() + id = PubKeyToID(pv.PubKey()) + mt = newMultiplexTransport( + testNodeInfo( + id, "transport", + ), + NodeKey{ + PrivKey: pv, + }, + ) + ) + + addr, err := NewNetAddressString(IDAddressString(id, "127.0.0.1:0")) + if err != nil { + t.Fatal(err) + } + + if err := mt.Listen(*addr); err != nil { + t.Fatal(err) + } + + // give the listener some time to get ready + time.Sleep(20 * time.Millisecond) + + return mt +} + +type testTransportAddr struct{} + +func (a *testTransportAddr) Network() string { return "tcp" } +func (a *testTransportAddr) String() string { return "test.local:1234" } + +type testTransportConn struct{} + +func (c *testTransportConn) Close() error { + return fmt.Errorf("close() not implemented") +} + +func (c *testTransportConn) LocalAddr() net.Addr { + return &testTransportAddr{} +} + +func (c *testTransportConn) RemoteAddr() net.Addr { + return &testTransportAddr{} +} + +func (c *testTransportConn) Read(_ []byte) (int, error) { + return -1, fmt.Errorf("read() not implemented") +} + +func (c *testTransportConn) SetDeadline(_ time.Time) error { + return fmt.Errorf("setDeadline() not implemented") +} + +func (c *testTransportConn) SetReadDeadline(_ time.Time) error { + return fmt.Errorf("setReadDeadline() not implemented") +} + +func (c *testTransportConn) SetWriteDeadline(_ time.Time) error { + return fmt.Errorf("setWriteDeadline() not implemented") +} + +func (c *testTransportConn) Write(_ []byte) (int, error) { + return -1, fmt.Errorf("write() not implemented") +} diff --git a/p2p/types.go b/p2p/types.go new file mode 100644 index 0000000..f8f76ce --- /dev/null +++ b/p2p/types.go @@ -0,0 +1,41 @@ +package p2p + +import ( + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/p2p/conn" + tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p" +) + +type ChannelDescriptor = conn.ChannelDescriptor +type ConnectionStatus = conn.ConnectionStatus + +// Envelope contains a message with sender routing info. +type Envelope struct { + Src Peer // sender (empty if outbound) + Message proto.Message // message payload + ChannelID byte +} + +// Unwrapper is a Protobuf message that can contain a variety of inner messages +// (e.g. via oneof fields). If a Channel's message type implements Unwrapper, the +// p2p layer will automatically unwrap inbound messages so that reactors do not have to do this themselves. +type Unwrapper interface { + proto.Message + + // Unwrap will unwrap the inner message contained in this message. + Unwrap() (proto.Message, error) +} + +// Wrapper is a companion type to Unwrapper. It is a Protobuf message that can contain a variety of inner messages. The p2p layer will automatically wrap outbound messages so that the reactors do not have to do it themselves. +type Wrapper interface { + proto.Message + + // Wrap will take the underlying message and wrap it in its wrapper type. + Wrap() proto.Message +} + +var ( + _ Wrapper = &tmp2p.PexRequest{} + _ Wrapper = &tmp2p.PexAddrs{} +) diff --git a/privval/doc.go b/privval/doc.go new file mode 100644 index 0000000..f98ce4c --- /dev/null +++ b/privval/doc.go @@ -0,0 +1,27 @@ +/* +Package privval provides different implementations of the types.PrivValidator. + +# FilePV + +FilePV is the simplest implementation and developer default. +It uses one file for the private key and another to store state. + +# SignerListenerEndpoint + +SignerListenerEndpoint establishes a connection to an external process, +like a Key Management Server (KMS), using a socket. +SignerListenerEndpoint listens for the external KMS process to dial in. +SignerListenerEndpoint takes a listener, which determines the type of connection +(ie. encrypted over tcp, or unencrypted over unix). + +# SignerDialerEndpoint + +SignerDialerEndpoint is a simple wrapper around a net.Conn. It's used by both IPCVal and TCPVal. + +# SignerClient + +SignerClient handles remote validator connections that provide signing services. +In production, it's recommended to wrap it with RetrySignerClient to avoid +termination in case of temporary errors. +*/ +package privval diff --git a/privval/errors.go b/privval/errors.go new file mode 100644 index 0000000..ed55620 --- /dev/null +++ b/privval/errors.go @@ -0,0 +1,35 @@ +package privval + +import ( + "errors" + "fmt" +) + +// EndpointTimeoutError occurs when endpoint times out. +type EndpointTimeoutError struct{} + +// Implement the net.Error interface. +func (e EndpointTimeoutError) Error() string { return "endpoint connection timed out" } +func (e EndpointTimeoutError) Timeout() bool { return true } +func (e EndpointTimeoutError) Temporary() bool { return true } + +// Socket errors. +var ( + ErrConnectionTimeout = EndpointTimeoutError{} + ErrNoConnection = errors.New("endpoint is not connected") + ErrReadTimeout = errors.New("endpoint read timed out") + ErrUnexpectedResponse = errors.New("empty response") + ErrWriteTimeout = errors.New("endpoint write timed out") +) + +// RemoteSignerError allows (remote) validators to include meaningful error +// descriptions in their reply. +type RemoteSignerError struct { + // TODO(ismail): create an enum of known errors + Code int + Description string +} + +func (e *RemoteSignerError) Error() string { + return fmt.Sprintf("signerEndpoint returned error #%d: %s", e.Code, e.Description) +} diff --git a/privval/file.go b/privval/file.go new file mode 100644 index 0000000..fdd066e --- /dev/null +++ b/privval/file.go @@ -0,0 +1,466 @@ +package privval + +import ( + "bytes" + "errors" + "fmt" + "os" + "time" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/libs/protoio" + "github.com/cometbft/cometbft/libs/tempfile" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +// TODO: type ? +const ( + stepNone int8 = 0 // Used to distinguish the initial state + stepPropose int8 = 1 + stepPrevote int8 = 2 + stepPrecommit int8 = 3 +) + +// A vote is either stepPrevote or stepPrecommit. +func voteToStep(vote *cmtproto.Vote) int8 { + switch vote.Type { + case cmtproto.PrevoteType: + return stepPrevote + case cmtproto.PrecommitType: + return stepPrecommit + default: + panic(fmt.Sprintf("Unknown vote type: %v", vote.Type)) + } +} + +//------------------------------------------------------------------------------- + +// FilePVKey stores the immutable part of PrivValidator. +type FilePVKey struct { + Address types.Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` + PrivKey crypto.PrivKey `json:"priv_key"` + + filePath string +} + +// Save persists the FilePVKey to its filePath. +func (pvKey FilePVKey) Save() { + outFile := pvKey.filePath + if outFile == "" { + panic("cannot save PrivValidator key: filePath not set") + } + + jsonBytes, err := cmtjson.MarshalIndent(pvKey, "", " ") + if err != nil { + panic(err) + } + + if err := tempfile.WriteFileAtomic(outFile, jsonBytes, 0600); err != nil { + panic(err) + } +} + +//------------------------------------------------------------------------------- + +// FilePVLastSignState stores the mutable part of PrivValidator. +type FilePVLastSignState struct { + Height int64 `json:"height"` + Round int32 `json:"round"` + Step int8 `json:"step"` + Signature []byte `json:"signature,omitempty"` + SignBytes cmtbytes.HexBytes `json:"signbytes,omitempty"` + + filePath string +} + +func (lss *FilePVLastSignState) reset() { + lss.Height = 0 + lss.Round = 0 + lss.Step = 0 + lss.Signature = nil + lss.SignBytes = nil +} + +// CheckHRS checks the given height, round, step (HRS) against that of the +// FilePVLastSignState. It returns an error if the arguments constitute a regression, +// or if they match but the SignBytes are empty. +// The returned boolean indicates whether the last Signature should be reused - +// it returns true if the HRS matches the arguments and the SignBytes are not empty (indicating +// we have already signed for this HRS, and can reuse the existing signature). +// It panics if the HRS matches the arguments, there's a SignBytes, but no Signature. +func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) { + + if lss.Height > height { + return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height) + } + + if lss.Height == height { + if lss.Round > round { + return false, fmt.Errorf("round regression at height %v. Got %v, last round %v", height, round, lss.Round) + } + + if lss.Round == round { + if lss.Step > step { + return false, fmt.Errorf( + "step regression at height %v round %v. Got %v, last step %v", + height, + round, + step, + lss.Step, + ) + } else if lss.Step == step { + if lss.SignBytes != nil { + if lss.Signature == nil { + panic("pv: Signature is nil but SignBytes is not!") + } + return true, nil + } + return false, errors.New("no SignBytes found") + } + } + } + return false, nil +} + +// Save persists the FilePvLastSignState to its filePath. +func (lss *FilePVLastSignState) Save() { + outFile := lss.filePath + if outFile == "" { + panic("cannot save FilePVLastSignState: filePath not set") + } + jsonBytes, err := cmtjson.MarshalIndent(lss, "", " ") + if err != nil { + panic(err) + } + err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600) + if err != nil { + panic(err) + } +} + +//------------------------------------------------------------------------------- + +// FilePV implements PrivValidator using data persisted to disk +// to prevent double signing. +// NOTE: the directories containing pv.Key.filePath and pv.LastSignState.filePath must already exist. +// It includes the LastSignature and LastSignBytes so we don't lose the signature +// if the process crashes after signing but before the resulting consensus message is processed. +type FilePV struct { + Key FilePVKey + LastSignState FilePVLastSignState +} + +// NewFilePV generates a new validator from the given key and paths. +func NewFilePV(privKey crypto.PrivKey, keyFilePath, stateFilePath string) *FilePV { + return &FilePV{ + Key: FilePVKey{ + Address: privKey.PubKey().Address(), + PubKey: privKey.PubKey(), + PrivKey: privKey, + filePath: keyFilePath, + }, + LastSignState: FilePVLastSignState{ + Step: stepNone, + filePath: stateFilePath, + }, + } +} + +// GenFilePV generates a new validator with randomly generated private key +// and sets the filePaths, but does not call Save(). +func GenFilePV(keyFilePath, stateFilePath string) *FilePV { + return NewFilePV(ed25519.GenPrivKey(), keyFilePath, stateFilePath) +} + +// LoadFilePV loads a FilePV from the filePaths. The FilePV handles double +// signing prevention by persisting data to the stateFilePath. If either file path +// does not exist, the program will exit. +func LoadFilePV(keyFilePath, stateFilePath string) *FilePV { + return loadFilePV(keyFilePath, stateFilePath, true) +} + +// LoadFilePVEmptyState loads a FilePV from the given keyFilePath, with an empty LastSignState. +// If the keyFilePath does not exist, the program will exit. +func LoadFilePVEmptyState(keyFilePath, stateFilePath string) *FilePV { + return loadFilePV(keyFilePath, stateFilePath, false) +} + +// If loadState is true, we load from the stateFilePath. Otherwise, we use an empty LastSignState. +func loadFilePV(keyFilePath, stateFilePath string, loadState bool) *FilePV { + keyJSONBytes, err := os.ReadFile(keyFilePath) + if err != nil { + cmtos.Exit(err.Error()) + } + pvKey := FilePVKey{} + err = cmtjson.Unmarshal(keyJSONBytes, &pvKey) + if err != nil { + cmtos.Exit(fmt.Sprintf("Error reading PrivValidator key from %v: %v\n", keyFilePath, err)) + } + + // overwrite pubkey and address for convenience + pvKey.PubKey = pvKey.PrivKey.PubKey() + pvKey.Address = pvKey.PubKey.Address() + pvKey.filePath = keyFilePath + + pvState := FilePVLastSignState{} + + if loadState { + stateJSONBytes, err := os.ReadFile(stateFilePath) + if err != nil { + cmtos.Exit(err.Error()) + } + err = cmtjson.Unmarshal(stateJSONBytes, &pvState) + if err != nil { + cmtos.Exit(fmt.Sprintf("Error reading PrivValidator state from %v: %v\n", stateFilePath, err)) + } + } + + pvState.filePath = stateFilePath + + return &FilePV{ + Key: pvKey, + LastSignState: pvState, + } +} + +// LoadOrGenFilePV loads a FilePV from the given filePaths +// or else generates a new one and saves it to the filePaths. +func LoadOrGenFilePV(keyFilePath, stateFilePath string) *FilePV { + var pv *FilePV + if cmtos.FileExists(keyFilePath) { + pv = LoadFilePV(keyFilePath, stateFilePath) + } else { + pv = GenFilePV(keyFilePath, stateFilePath) + pv.Save() + } + return pv +} + +// GetAddress returns the address of the validator. +// Implements PrivValidator. +func (pv *FilePV) GetAddress() types.Address { + return pv.Key.Address +} + +// GetPubKey returns the public key of the validator. +// Implements PrivValidator. +func (pv *FilePV) GetPubKey() (crypto.PubKey, error) { + return pv.Key.PubKey, nil +} + +// SignVote signs a canonical representation of the vote, along with the +// chainID. Implements PrivValidator. +func (pv *FilePV) SignVote(chainID string, vote *cmtproto.Vote) error { + if err := pv.signVote(chainID, vote); err != nil { + return fmt.Errorf("error signing vote: %v", err) + } + return nil +} + +// SignProposal signs a canonical representation of the proposal, along with +// the chainID. Implements PrivValidator. +func (pv *FilePV) SignProposal(chainID string, proposal *cmtproto.Proposal) error { + if err := pv.signProposal(chainID, proposal); err != nil { + return fmt.Errorf("error signing proposal: %v", err) + } + return nil +} + +// Save persists the FilePV to disk. +func (pv *FilePV) Save() { + pv.Key.Save() + pv.LastSignState.Save() +} + +// Reset resets all fields in the FilePV. +// NOTE: Unsafe! +func (pv *FilePV) Reset() { + pv.LastSignState.reset() + pv.Save() +} + +// String returns a string representation of the FilePV. +func (pv *FilePV) String() string { + return fmt.Sprintf( + "PrivValidator{%v LH:%v, LR:%v, LS:%v}", + pv.GetAddress(), + pv.LastSignState.Height, + pv.LastSignState.Round, + pv.LastSignState.Step, + ) +} + +//------------------------------------------------------------------------------------ + +// signVote checks if the vote is good to sign and sets the vote signature. +// It may need to set the timestamp as well if the vote is otherwise the same as +// a previously signed vote (ie. we crashed after signing but before the vote hit the WAL). +// Extension signatures are always signed for non-nil precommits (even if the data is empty). +func (pv *FilePV) signVote(chainID string, vote *cmtproto.Vote) error { + height, round, step := vote.Height, vote.Round, voteToStep(vote) + + lss := pv.LastSignState + + sameHRS, err := lss.CheckHRS(height, round, step) + if err != nil { + return err + } + + signBytes := types.VoteSignBytes(chainID, vote) + + // Vote extensions are non-deterministic, so it is possible that an + // application may have created a different extension. We therefore always + // re-sign the vote extensions of precommits. For prevotes and nil + // precommits, the extension signature will always be empty. + // Even if the signed over data is empty, we still add the signature + var extSig []byte + if vote.Type == cmtproto.PrecommitType && !types.ProtoBlockIDIsNil(&vote.BlockID) { + extSignBytes := types.VoteExtensionSignBytes(chainID, vote) + extSig, err = pv.Key.PrivKey.Sign(extSignBytes) + if err != nil { + return err + } + } else if len(vote.Extension) > 0 { + return errors.New("unexpected vote extension - extensions are only allowed in non-nil precommits") + } + + // We might crash before writing to the wal, + // causing us to try to re-sign for the same HRS. + // If signbytes are the same, use the last signature. + // If they only differ by timestamp, use last timestamp and signature + // Otherwise, return error + if sameHRS { + if bytes.Equal(signBytes, lss.SignBytes) { + vote.Signature = lss.Signature + } else if timestamp, ok := checkVotesOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok { + // Compares the canonicalized votes (i.e. without vote extensions + // or vote extension signatures). + vote.Timestamp = timestamp + vote.Signature = lss.Signature + } else { + err = fmt.Errorf("conflicting data") + } + + vote.ExtensionSignature = extSig + + return err + } + + // It passed the checks. Sign the vote + sig, err := pv.Key.PrivKey.Sign(signBytes) + if err != nil { + return err + } + pv.saveSigned(height, round, step, signBytes, sig) + vote.Signature = sig + vote.ExtensionSignature = extSig + + return nil +} + +// signProposal checks if the proposal is good to sign and sets the proposal signature. +// It may need to set the timestamp as well if the proposal is otherwise the same as +// a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL). +func (pv *FilePV) signProposal(chainID string, proposal *cmtproto.Proposal) error { + height, round, step := proposal.Height, proposal.Round, stepPropose + + lss := pv.LastSignState + + sameHRS, err := lss.CheckHRS(height, round, step) + if err != nil { + return err + } + + signBytes := types.ProposalSignBytes(chainID, proposal) + + // We might crash before writing to the wal, + // causing us to try to re-sign for the same HRS. + // If signbytes are the same, use the last signature. + // If they only differ by timestamp, use last timestamp and signature + // Otherwise, return error + if sameHRS { + if bytes.Equal(signBytes, lss.SignBytes) { + proposal.Signature = lss.Signature + } else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok { + proposal.Timestamp = timestamp + proposal.Signature = lss.Signature + } else { + err = fmt.Errorf("conflicting data") + } + return err + } + + // It passed the checks. Sign the proposal + sig, err := pv.Key.PrivKey.Sign(signBytes) + if err != nil { + return err + } + pv.saveSigned(height, round, step, signBytes, sig) + proposal.Signature = sig + return nil +} + +// Persist height/round/step and signature +func (pv *FilePV) saveSigned(height int64, round int32, step int8, + signBytes []byte, sig []byte) { + + pv.LastSignState.Height = height + pv.LastSignState.Round = round + pv.LastSignState.Step = step + pv.LastSignState.Signature = sig + pv.LastSignState.SignBytes = signBytes + pv.LastSignState.Save() +} + +//----------------------------------------------------------------------------------------- + +// Returns the timestamp from the lastSignBytes. +// Returns true if the only difference in the votes is their timestamp. +// Performs these checks on the canonical votes (excluding the vote extension +// and vote extension signatures). +func checkVotesOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) { + var lastVote, newVote cmtproto.CanonicalVote + if err := protoio.UnmarshalDelimited(lastSignBytes, &lastVote); err != nil { + panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into vote: %v", err)) + } + if err := protoio.UnmarshalDelimited(newSignBytes, &newVote); err != nil { + panic(fmt.Sprintf("signBytes cannot be unmarshalled into vote: %v", err)) + } + + lastTime := lastVote.Timestamp + // set the times to the same value and check equality + now := cmttime.Now() + lastVote.Timestamp = now + newVote.Timestamp = now + + return lastTime, proto.Equal(&newVote, &lastVote) +} + +// returns the timestamp from the lastSignBytes. +// returns true if the only difference in the proposals is their timestamp +func checkProposalsOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) { + var lastProposal, newProposal cmtproto.CanonicalProposal + if err := protoio.UnmarshalDelimited(lastSignBytes, &lastProposal); err != nil { + panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into proposal: %v", err)) + } + if err := protoio.UnmarshalDelimited(newSignBytes, &newProposal); err != nil { + panic(fmt.Sprintf("signBytes cannot be unmarshalled into proposal: %v", err)) + } + + lastTime := lastProposal.Timestamp + // set the times to the same value and check equality + now := cmttime.Now() + lastProposal.Timestamp = now + newProposal.Timestamp = now + + return lastTime, proto.Equal(&newProposal, &lastProposal) +} diff --git a/privval/file_test.go b/privval/file_test.go new file mode 100644 index 0000000..5ef3a94 --- /dev/null +++ b/privval/file_test.go @@ -0,0 +1,393 @@ +package privval + +import ( + "encoding/base64" + "fmt" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +func TestGenLoadValidator(t *testing.T) { + privVal, tempKeyFileName, tempStateFileName := newTestFilePV(t) + + height := int64(100) + privVal.LastSignState.Height = height + privVal.Save() + addr := privVal.GetAddress() + + privVal = LoadFilePV(tempKeyFileName, tempStateFileName) + assert.Equal(t, addr, privVal.GetAddress(), "expected privval addr to be the same") + assert.Equal(t, height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved") +} + +func TestResetValidator(t *testing.T) { + privVal, _, tempStateFileName := newTestFilePV(t) + emptyState := FilePVLastSignState{filePath: tempStateFileName} + + // new priv val has empty state + assert.Equal(t, privVal.LastSignState, emptyState) + + // test vote + height, round := int64(10), int32(1) + voteType := cmtproto.PrevoteType + randBytes := cmtrand.Bytes(tmhash.Size) + blockID := types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}} + vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID, nil) + err := privVal.SignVote("mychainid", vote.ToProto()) + assert.NoError(t, err, "expected no error signing vote") + + // priv val after signing is not same as empty + assert.NotEqual(t, privVal.LastSignState, emptyState) + + // priv val after AcceptNewConnection is same as empty + privVal.Reset() + assert.Equal(t, privVal.LastSignState, emptyState) +} + +func TestLoadOrGenValidator(t *testing.T) { + assert := assert.New(t) + + tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") + require.Nil(t, err) + tempStateFile, err := os.CreateTemp("", "priv_validator_state_") + require.Nil(t, err) + + tempKeyFilePath := tempKeyFile.Name() + if err := os.Remove(tempKeyFilePath); err != nil { + t.Error(err) + } + tempStateFilePath := tempStateFile.Name() + if err := os.Remove(tempStateFilePath); err != nil { + t.Error(err) + } + + privVal := LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath) + addr := privVal.GetAddress() + privVal = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath) + assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") +} + +func TestUnmarshalValidatorState(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // create some fixed values + serialized := `{ + "height": "1", + "round": 1, + "step": 1 + }` + + val := FilePVLastSignState{} + err := cmtjson.Unmarshal([]byte(serialized), &val) + require.Nil(err, "%+v", err) + + // make sure the values match + assert.EqualValues(val.Height, 1) + assert.EqualValues(val.Round, 1) + assert.EqualValues(val.Step, 1) + + // export it and make sure it is the same + out, err := cmtjson.Marshal(val) + require.Nil(err, "%+v", err) + assert.JSONEq(serialized, string(out)) +} + +func TestUnmarshalValidatorKey(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // create some fixed values + privKey := ed25519.GenPrivKey() + pubKey := privKey.PubKey() + addr := pubKey.Address() + pubBytes := pubKey.Bytes() + privBytes := privKey.Bytes() + pubB64 := base64.StdEncoding.EncodeToString(pubBytes) + privB64 := base64.StdEncoding.EncodeToString(privBytes) + + serialized := fmt.Sprintf(`{ + "address": "%s", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "%s" + }, + "priv_key": { + "type": "tendermint/PrivKeyEd25519", + "value": "%s" + } +}`, addr, pubB64, privB64) + + val := FilePVKey{} + err := cmtjson.Unmarshal([]byte(serialized), &val) + require.Nil(err, "%+v", err) + + // make sure the values match + assert.EqualValues(addr, val.Address) + assert.EqualValues(pubKey, val.PubKey) + assert.EqualValues(privKey, val.PrivKey) + + // export it and make sure it is the same + out, err := cmtjson.Marshal(val) + require.Nil(err, "%+v", err) + assert.JSONEq(serialized, string(out)) +} + +func TestSignVote(t *testing.T) { + assert := assert.New(t) + + privVal, _, _ := newTestFilePV(t) + + randbytes := cmtrand.Bytes(tmhash.Size) + randbytes2 := cmtrand.Bytes(tmhash.Size) + + block1 := types.BlockID{Hash: randbytes, + PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}} + block2 := types.BlockID{Hash: randbytes2, + PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}} + + height, round := int64(10), int32(1) + voteType := cmtproto.PrevoteType + + // sign a vote for first time + vote := newVote(privVal.Key.Address, 0, height, round, voteType, block1, nil) + v := vote.ToProto() + err := privVal.SignVote("mychainid", v) + assert.NoError(err, "expected no error signing vote") + + // try to sign the same vote again; should be fine + err = privVal.SignVote("mychainid", v) + assert.NoError(err, "expected no error on signing same vote") + + // now try some bad votes + cases := []*types.Vote{ + newVote(privVal.Key.Address, 0, height, round-1, voteType, block1, nil), // round regression + newVote(privVal.Key.Address, 0, height-1, round, voteType, block1, nil), // height regression + newVote(privVal.Key.Address, 0, height-2, round+4, voteType, block1, nil), // height regression and different round + newVote(privVal.Key.Address, 0, height, round, voteType, block2, nil), // different block + } + + for _, c := range cases { + cpb := c.ToProto() + err = privVal.SignVote("mychainid", cpb) + assert.Error(err, "expected error on signing conflicting vote") + } + + // try signing a vote with a different time stamp + sig := vote.Signature + vote.Timestamp = vote.Timestamp.Add(time.Duration(1000)) + err = privVal.SignVote("mychainid", v) + assert.NoError(err) + assert.Equal(sig, vote.Signature) +} + +func TestSignProposal(t *testing.T) { + assert := assert.New(t) + + privVal, _, _ := newTestFilePV(t) + + randbytes := cmtrand.Bytes(tmhash.Size) + randbytes2 := cmtrand.Bytes(tmhash.Size) + + block1 := types.BlockID{Hash: randbytes, + PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}} + block2 := types.BlockID{Hash: randbytes2, + PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}} + height, round := int64(10), int32(1) + + // sign a proposal for first time + proposal := newProposal(height, round, block1) + pbp := proposal.ToProto() + err := privVal.SignProposal("mychainid", pbp) + assert.NoError(err, "expected no error signing proposal") + + // try to sign the same proposal again; should be fine + err = privVal.SignProposal("mychainid", pbp) + assert.NoError(err, "expected no error on signing same proposal") + + // now try some bad Proposals + cases := []*types.Proposal{ + newProposal(height, round-1, block1), // round regression + newProposal(height-1, round, block1), // height regression + newProposal(height-2, round+4, block1), // height regression and different round + newProposal(height, round, block2), // different block + } + + for _, c := range cases { + err = privVal.SignProposal("mychainid", c.ToProto()) + assert.Error(err, "expected error on signing conflicting proposal") + } + + // try signing a proposal with a different time stamp + sig := proposal.Signature + proposal.Timestamp = proposal.Timestamp.Add(time.Duration(1000)) + err = privVal.SignProposal("mychainid", pbp) + assert.NoError(err) + assert.Equal(sig, proposal.Signature) +} + +func TestDifferByTimestamp(t *testing.T) { + tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") + require.Nil(t, err) + tempStateFile, err := os.CreateTemp("", "priv_validator_state_") + require.Nil(t, err) + + privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name()) + randbytes := cmtrand.Bytes(tmhash.Size) + block1 := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}} + height, round := int64(10), int32(1) + chainID := "mychainid" + + // test proposal + { + proposal := newProposal(height, round, block1) + pb := proposal.ToProto() + err := privVal.SignProposal(chainID, pb) + assert.NoError(t, err, "expected no error signing proposal") + signBytes := types.ProposalSignBytes(chainID, pb) + + sig := proposal.Signature + timeStamp := proposal.Timestamp + + // manipulate the timestamp. should get changed back + pb.Timestamp = pb.Timestamp.Add(time.Millisecond) + var emptySig []byte + proposal.Signature = emptySig + err = privVal.SignProposal("mychainid", pb) + assert.NoError(t, err, "expected no error on signing same proposal") + + assert.Equal(t, timeStamp, pb.Timestamp) + assert.Equal(t, signBytes, types.ProposalSignBytes(chainID, pb)) + assert.Equal(t, sig, proposal.Signature) + } + + // test vote + { + voteType := cmtproto.PrevoteType + blockID := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{}} + vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID, nil) + v := vote.ToProto() + err := privVal.SignVote("mychainid", v) + assert.NoError(t, err, "expected no error signing vote") + + signBytes := types.VoteSignBytes(chainID, v) + sig := v.Signature + extSig := v.ExtensionSignature + timeStamp := vote.Timestamp + + // manipulate the timestamp. should get changed back + v.Timestamp = v.Timestamp.Add(time.Millisecond) + var emptySig []byte + v.Signature = emptySig + v.ExtensionSignature = emptySig + err = privVal.SignVote("mychainid", v) + assert.NoError(t, err, "expected no error on signing same vote") + + assert.Equal(t, timeStamp, v.Timestamp) + assert.Equal(t, signBytes, types.VoteSignBytes(chainID, v)) + assert.Equal(t, sig, v.Signature) + assert.Equal(t, extSig, v.ExtensionSignature) + } +} + +func TestVoteExtensionsAreAlwaysSigned(t *testing.T) { + privVal, _, _ := newTestFilePV(t) + pubKey, err := privVal.GetPubKey() + assert.NoError(t, err) + + block := types.BlockID{ + Hash: cmtrand.Bytes(tmhash.Size), + PartSetHeader: types.PartSetHeader{Total: 5, Hash: cmtrand.Bytes(tmhash.Size)}, + } + + height, round := int64(10), int32(1) + voteType := cmtproto.PrecommitType + + // We initially sign this vote without an extension + vote1 := newVote(privVal.Key.Address, 0, height, round, voteType, block, nil) + vpb1 := vote1.ToProto() + + err = privVal.SignVote("mychainid", vpb1) + assert.NoError(t, err, "expected no error signing vote") + assert.NotNil(t, vpb1.ExtensionSignature) + + vesb1 := types.VoteExtensionSignBytes("mychainid", vpb1) + assert.True(t, pubKey.VerifySignature(vesb1, vpb1.ExtensionSignature)) + + // We duplicate this vote precisely, including its timestamp, but change + // its extension + vote2 := vote1.Copy() + vote2.Extension = []byte("new extension") + vpb2 := vote2.ToProto() + + err = privVal.SignVote("mychainid", vpb2) + assert.NoError(t, err, "expected no error signing same vote with manipulated vote extension") + + // We need to ensure that a valid new extension signature has been created + // that validates against the vote extension sign bytes with the new + // extension, and does not validate against the vote extension sign bytes + // with the old extension. + vesb2 := types.VoteExtensionSignBytes("mychainid", vpb2) + assert.True(t, pubKey.VerifySignature(vesb2, vpb2.ExtensionSignature)) + assert.False(t, pubKey.VerifySignature(vesb1, vpb2.ExtensionSignature)) + + // We now manipulate the timestamp of the vote with the extension, as per + // TestDifferByTimestamp + expectedTimestamp := vpb2.Timestamp + + vpb2.Timestamp = vpb2.Timestamp.Add(time.Millisecond) + vpb2.Signature = nil + vpb2.ExtensionSignature = nil + + err = privVal.SignVote("mychainid", vpb2) + assert.NoError(t, err, "expected no error signing same vote with manipulated timestamp and vote extension") + assert.Equal(t, expectedTimestamp, vpb2.Timestamp) + + vesb3 := types.VoteExtensionSignBytes("mychainid", vpb2) + assert.True(t, pubKey.VerifySignature(vesb3, vpb2.ExtensionSignature)) + assert.False(t, pubKey.VerifySignature(vesb1, vpb2.ExtensionSignature)) +} + +func newVote(addr types.Address, idx int32, height int64, round int32, + typ cmtproto.SignedMsgType, blockID types.BlockID, extension []byte) *types.Vote { + return &types.Vote{ + ValidatorAddress: addr, + ValidatorIndex: idx, + Height: height, + Round: round, + Type: typ, + Timestamp: cmttime.Now(), + BlockID: blockID, + Extension: extension, + } +} + +func newProposal(height int64, round int32, blockID types.BlockID) *types.Proposal { + return &types.Proposal{ + Height: height, + Round: round, + BlockID: blockID, + Timestamp: cmttime.Now(), + } +} + +func newTestFilePV(t *testing.T) (*FilePV, string, string) { + tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_") + require.NoError(t, err) + tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_") + require.NoError(t, err) + + privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name()) + + return privVal, tempKeyFile.Name(), tempStateFile.Name() +} diff --git a/privval/msgs.go b/privval/msgs.go new file mode 100644 index 0000000..0390a8b --- /dev/null +++ b/privval/msgs.go @@ -0,0 +1,40 @@ +package privval + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" +) + +// TODO: Add ChainIDRequest + +func mustWrapMsg(pb proto.Message) privvalproto.Message { + msg := privvalproto.Message{} + + switch pb := pb.(type) { + case *privvalproto.Message: + msg = *pb + case *privvalproto.PubKeyRequest: + msg.Sum = &privvalproto.Message_PubKeyRequest{PubKeyRequest: pb} + case *privvalproto.PubKeyResponse: + msg.Sum = &privvalproto.Message_PubKeyResponse{PubKeyResponse: pb} + case *privvalproto.SignVoteRequest: + msg.Sum = &privvalproto.Message_SignVoteRequest{SignVoteRequest: pb} + case *privvalproto.SignedVoteResponse: + msg.Sum = &privvalproto.Message_SignedVoteResponse{SignedVoteResponse: pb} + case *privvalproto.SignedProposalResponse: + msg.Sum = &privvalproto.Message_SignedProposalResponse{SignedProposalResponse: pb} + case *privvalproto.SignProposalRequest: + msg.Sum = &privvalproto.Message_SignProposalRequest{SignProposalRequest: pb} + case *privvalproto.PingRequest: + msg.Sum = &privvalproto.Message_PingRequest{PingRequest: pb} + case *privvalproto.PingResponse: + msg.Sum = &privvalproto.Message_PingResponse{PingResponse: pb} + default: + panic(fmt.Errorf("unknown message type %T", pb)) + } + + return msg +} diff --git a/privval/msgs_test.go b/privval/msgs_test.go new file mode 100644 index 0000000..301e724 --- /dev/null +++ b/privval/msgs_test.go @@ -0,0 +1,99 @@ +package privval + +import ( + "encoding/hex" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/tmhash" + cryptoproto "github.com/cometbft/cometbft/proto/tendermint/crypto" + privproto "github.com/cometbft/cometbft/proto/tendermint/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +var stamp = time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC) + +func exampleVote() *types.Vote { + return &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 3, + Round: 2, + BlockID: types.BlockID{Hash: tmhash.Sum([]byte("blockID_hash")), PartSetHeader: types.PartSetHeader{Total: 1000000, Hash: tmhash.Sum([]byte("blockID_part_set_header_hash"))}}, + Timestamp: stamp, + ValidatorAddress: crypto.AddressHash([]byte("validator_address")), + ValidatorIndex: 56789, + Extension: []byte("extension"), + } +} + +func exampleProposal() *types.Proposal { + + return &types.Proposal{ + Type: cmtproto.SignedMsgType(1), + Height: 3, + Round: 2, + Timestamp: stamp, + POLRound: 2, + Signature: []byte("it's a signature"), + BlockID: types.BlockID{ + Hash: tmhash.Sum([]byte("blockID_hash")), + PartSetHeader: types.PartSetHeader{ + Total: 1000000, + Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")), + }, + }, + } +} + +//nolint:lll // ignore line length for tests +func TestPrivvalVectors(t *testing.T) { + pk := ed25519.GenPrivKeyFromSecret([]byte("it's a secret")).PubKey() + ppk, err := cryptoenc.PubKeyToProto(pk) + require.NoError(t, err) + + // Generate a simple vote + vote := exampleVote() + votepb := vote.ToProto() + + // Generate a simple proposal + proposal := exampleProposal() + proposalpb := proposal.ToProto() + + // Create a Reuseable remote error + remoteError := &privproto.RemoteSignerError{Code: 1, Description: "it's a error"} + + testCases := []struct { + testName string + msg proto.Message + expBytes string + }{ + {"ping request", &privproto.PingRequest{}, "3a00"}, + {"ping response", &privproto.PingResponse{}, "4200"}, + {"pubKey request", &privproto.PubKeyRequest{}, "0a00"}, + {"pubKey response", &privproto.PubKeyResponse{PubKey: ppk, Error: nil}, "12240a220a20556a436f1218d30942efe798420f51dc9b6a311b929c578257457d05c5fcf230"}, + {"pubKey response with error", &privproto.PubKeyResponse{PubKey: cryptoproto.PublicKey{}, Error: remoteError}, "12140a0012100801120c697427732061206572726f72"}, + {"Vote Request", &privproto.SignVoteRequest{Vote: votepb}, "1a81010a7f080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0608f49a8ded0532146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb034a09657874656e73696f6e"}, + {"Vote Response", &privproto.SignedVoteResponse{Vote: *votepb, Error: nil}, "2281010a7f080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0608f49a8ded0532146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb034a09657874656e73696f6e"}, + {"Vote Response with error", &privproto.SignedVoteResponse{Vote: cmtproto.Vote{}, Error: remoteError}, "22250a11220212002a0b088092b8c398feffffff0112100801120c697427732061206572726f72"}, + {"Proposal Request", &privproto.SignProposalRequest{Proposal: proposalpb}, "2a700a6e08011003180220022a4a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a320608f49a8ded053a10697427732061207369676e6174757265"}, + {"Proposal Response", &privproto.SignedProposalResponse{Proposal: *proposalpb, Error: nil}, "32700a6e08011003180220022a4a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a320608f49a8ded053a10697427732061207369676e6174757265"}, + {"Proposal Response with error", &privproto.SignedProposalResponse{Proposal: cmtproto.Proposal{}, Error: remoteError}, "32250a112a021200320b088092b8c398feffffff0112100801120c697427732061206572726f72"}, + } + + for _, tc := range testCases { + tc := tc + + pm := mustWrapMsg(tc.msg) + bz, err := pm.Marshal() + require.NoError(t, err, tc.testName) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + } +} diff --git a/privval/retry_signer_client.go b/privval/retry_signer_client.go new file mode 100644 index 0000000..860169c --- /dev/null +++ b/privval/retry_signer_client.go @@ -0,0 +1,96 @@ +package privval + +import ( + "fmt" + "time" + + "github.com/cometbft/cometbft/crypto" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +// RetrySignerClient wraps SignerClient adding retry for each operation (except +// Ping) w/ a timeout. +type RetrySignerClient struct { + next *SignerClient + retries int + timeout time.Duration +} + +// NewRetrySignerClient returns RetrySignerClient. If +retries+ is 0, the +// client will be retrying each operation indefinitely. +func NewRetrySignerClient(sc *SignerClient, retries int, timeout time.Duration) *RetrySignerClient { + return &RetrySignerClient{sc, retries, timeout} +} + +var _ types.PrivValidator = (*RetrySignerClient)(nil) + +func (sc *RetrySignerClient) Close() error { + return sc.next.Close() +} + +func (sc *RetrySignerClient) IsConnected() bool { + return sc.next.IsConnected() +} + +func (sc *RetrySignerClient) WaitForConnection(maxWait time.Duration) error { + return sc.next.WaitForConnection(maxWait) +} + +//-------------------------------------------------------- +// Implement PrivValidator + +func (sc *RetrySignerClient) Ping() error { + return sc.next.Ping() +} + +func (sc *RetrySignerClient) GetPubKey() (crypto.PubKey, error) { + var ( + pk crypto.PubKey + err error + ) + for i := 0; i < sc.retries || sc.retries == 0; i++ { + pk, err = sc.next.GetPubKey() + if err == nil { + return pk, nil + } + // If remote signer errors, we don't retry. + if _, ok := err.(*RemoteSignerError); ok { + return nil, err + } + time.Sleep(sc.timeout) + } + return nil, fmt.Errorf("exhausted all attempts to get pubkey: %w", err) +} + +func (sc *RetrySignerClient) SignVote(chainID string, vote *cmtproto.Vote) error { + var err error + for i := 0; i < sc.retries || sc.retries == 0; i++ { + err = sc.next.SignVote(chainID, vote) + if err == nil { + return nil + } + // If remote signer errors, we don't retry. + if _, ok := err.(*RemoteSignerError); ok { + return err + } + time.Sleep(sc.timeout) + } + return fmt.Errorf("exhausted all attempts to sign vote: %w", err) +} + +func (sc *RetrySignerClient) SignProposal(chainID string, proposal *cmtproto.Proposal) error { + var err error + for i := 0; i < sc.retries || sc.retries == 0; i++ { + err = sc.next.SignProposal(chainID, proposal) + if err == nil { + return nil + } + // If remote signer errors, we don't retry. + if _, ok := err.(*RemoteSignerError); ok { + return err + } + time.Sleep(sc.timeout) + } + return fmt.Errorf("exhausted all attempts to sign proposal: %w", err) +} diff --git a/privval/signer_client.go b/privval/signer_client.go new file mode 100644 index 0000000..bdb9168 --- /dev/null +++ b/privval/signer_client.go @@ -0,0 +1,133 @@ +package privval + +import ( + "fmt" + "time" + + "github.com/cometbft/cometbft/crypto" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +// SignerClient implements PrivValidator. +// Handles remote validator connections that provide signing services +type SignerClient struct { + endpoint *SignerListenerEndpoint + chainID string +} + +var _ types.PrivValidator = (*SignerClient)(nil) + +// NewSignerClient returns an instance of SignerClient. +// it will start the endpoint (if not already started) +func NewSignerClient(endpoint *SignerListenerEndpoint, chainID string) (*SignerClient, error) { + if !endpoint.IsRunning() { + if err := endpoint.Start(); err != nil { + return nil, fmt.Errorf("failed to start listener endpoint: %w", err) + } + } + + return &SignerClient{endpoint: endpoint, chainID: chainID}, nil +} + +// Close closes the underlying connection +func (sc *SignerClient) Close() error { + return sc.endpoint.Close() +} + +// IsConnected indicates with the signer is connected to a remote signing service +func (sc *SignerClient) IsConnected() bool { + return sc.endpoint.IsConnected() +} + +// WaitForConnection waits maxWait for a connection or returns a timeout error +func (sc *SignerClient) WaitForConnection(maxWait time.Duration) error { + return sc.endpoint.WaitForConnection(maxWait) +} + +//-------------------------------------------------------- +// Implement PrivValidator + +// Ping sends a ping request to the remote signer +func (sc *SignerClient) Ping() error { + response, err := sc.endpoint.SendRequest(mustWrapMsg(&privvalproto.PingRequest{})) + if err != nil { + sc.endpoint.Logger.Error("SignerClient::Ping", "err", err) + return nil + } + + pb := response.GetPingResponse() + if pb == nil { + return err + } + + return nil +} + +// GetPubKey retrieves a public key from a remote signer +// returns an error if client is not able to provide the key +func (sc *SignerClient) GetPubKey() (crypto.PubKey, error) { + response, err := sc.endpoint.SendRequest(mustWrapMsg(&privvalproto.PubKeyRequest{ChainId: sc.chainID})) + if err != nil { + return nil, fmt.Errorf("send: %w", err) + } + + resp := response.GetPubKeyResponse() + if resp == nil { + return nil, ErrUnexpectedResponse + } + if resp.Error != nil { + return nil, &RemoteSignerError{Code: int(resp.Error.Code), Description: resp.Error.Description} + } + + pk, err := cryptoenc.PubKeyFromProto(resp.PubKey) + if err != nil { + return nil, err + } + + return pk, nil +} + +// SignVote requests a remote signer to sign a vote +func (sc *SignerClient) SignVote(chainID string, vote *cmtproto.Vote) error { + response, err := sc.endpoint.SendRequest(mustWrapMsg(&privvalproto.SignVoteRequest{Vote: vote, ChainId: chainID})) + if err != nil { + return err + } + + resp := response.GetSignedVoteResponse() + if resp == nil { + return ErrUnexpectedResponse + } + if resp.Error != nil { + return &RemoteSignerError{Code: int(resp.Error.Code), Description: resp.Error.Description} + } + + *vote = resp.Vote + + return nil +} + +// SignProposal requests a remote signer to sign a proposal +func (sc *SignerClient) SignProposal(chainID string, proposal *cmtproto.Proposal) error { + response, err := sc.endpoint.SendRequest(mustWrapMsg( + &privvalproto.SignProposalRequest{Proposal: proposal, ChainId: chainID}, + )) + if err != nil { + return err + } + + resp := response.GetSignedProposalResponse() + if resp == nil { + return ErrUnexpectedResponse + } + if resp.Error != nil { + return &RemoteSignerError{Code: int(resp.Error.Code), Description: resp.Error.Description} + } + + *proposal = resp.Proposal + + return nil +} diff --git a/privval/signer_client_test.go b/privval/signer_client_test.go new file mode 100644 index 0000000..7ccaef7 --- /dev/null +++ b/privval/signer_client_test.go @@ -0,0 +1,438 @@ +package privval + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cryptoproto "github.com/cometbft/cometbft/proto/tendermint/crypto" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +type signerTestCase struct { + chainID string + mockPV types.PrivValidator + signerClient *SignerClient + signerServer *SignerServer +} + +func getSignerTestCases(t *testing.T) []signerTestCase { + testCases := make([]signerTestCase, 0) + + // Get test cases for each possible dialer (DialTCP / DialUnix / etc) + for _, dtc := range getDialerTestCases(t) { + chainID := cmtrand.Str(12) + mockPV := types.NewMockPV() + + // get a pair of signer listener, signer dialer endpoints + sl, sd := getMockEndpoints(t, dtc.addr, dtc.dialer) + sc, err := NewSignerClient(sl, chainID) + require.NoError(t, err) + ss := NewSignerServer(sd, chainID, mockPV) + + err = ss.Start() + require.NoError(t, err) + + tc := signerTestCase{ + chainID: chainID, + mockPV: mockPV, + signerClient: sc, + signerServer: ss, + } + + testCases = append(testCases, tc) + } + + return testCases +} + +func TestSignerClose(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + err := tc.signerClient.Close() + assert.NoError(t, err) + + err = tc.signerServer.Stop() + assert.NoError(t, err) + } +} + +func TestSignerPing(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + err := tc.signerClient.Ping() + assert.NoError(t, err) + } +} + +func TestSignerGetPubKey(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + pubKey, err := tc.signerClient.GetPubKey() + require.NoError(t, err) + expectedPubKey, err := tc.mockPV.GetPubKey() + require.NoError(t, err) + + assert.Equal(t, expectedPubKey, pubKey) + + pubKey, err = tc.signerClient.GetPubKey() + require.NoError(t, err) + expectedpk, err := tc.mockPV.GetPubKey() + require.NoError(t, err) + expectedAddr := expectedpk.Address() + + assert.Equal(t, expectedAddr, pubKey.Address()) + } +} + +func TestSignerProposal(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + have := &types.Proposal{ + Type: cmtproto.ProposalType, + Height: 1, + Round: 2, + POLRound: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + } + want := &types.Proposal{ + Type: cmtproto.ProposalType, + Height: 1, + Round: 2, + POLRound: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + } + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + require.NoError(t, tc.mockPV.SignProposal(tc.chainID, want.ToProto())) + require.NoError(t, tc.signerClient.SignProposal(tc.chainID, have.ToProto())) + + assert.Equal(t, want.Signature, have.Signature) + } +} + +func TestSignerVote(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + valAddr := cmtrand.Bytes(crypto.AddressSize) + want := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + have := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + require.NoError(t, tc.mockPV.SignVote(tc.chainID, want.ToProto())) + require.NoError(t, tc.signerClient.SignVote(tc.chainID, have.ToProto())) + + assert.Equal(t, want.Signature, have.Signature) + } +} + +func TestSignerVoteResetDeadline(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + valAddr := cmtrand.Bytes(crypto.AddressSize) + want := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + have := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + time.Sleep(testTimeoutReadWrite2o3) + + require.NoError(t, tc.mockPV.SignVote(tc.chainID, want.ToProto())) + require.NoError(t, tc.signerClient.SignVote(tc.chainID, have.ToProto())) + assert.Equal(t, want.Signature, have.Signature) + + // TODO(jleni): Clarify what is actually being tested + + // This would exceed the deadline if it was not extended by the previous message + time.Sleep(testTimeoutReadWrite2o3) + + require.NoError(t, tc.mockPV.SignVote(tc.chainID, want.ToProto())) + require.NoError(t, tc.signerClient.SignVote(tc.chainID, have.ToProto())) + assert.Equal(t, want.Signature, have.Signature) + } +} + +func TestSignerVoteKeepAlive(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + valAddr := cmtrand.Bytes(crypto.AddressSize) + want := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + have := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + } + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + // Check that even if the client does not request a + // signature for a long time. The service is still available + + // in this particular case, we use the dialer logger to ensure that + // test messages are properly interleaved in the test logs + tc.signerServer.Logger.Debug("TEST: Forced Wait -------------------------------------------------") + time.Sleep(testTimeoutReadWrite * 3) + tc.signerServer.Logger.Debug("TEST: Forced Wait DONE---------------------------------------------") + + require.NoError(t, tc.mockPV.SignVote(tc.chainID, want.ToProto())) + require.NoError(t, tc.signerClient.SignVote(tc.chainID, have.ToProto())) + + assert.Equal(t, want.Signature, have.Signature) + } +} + +func TestSignerSignProposalErrors(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + // Replace service with a mock that always fails + tc.signerServer.privVal = types.NewErroringMockPV() + tc.mockPV = types.NewErroringMockPV() + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + proposal := &types.Proposal{ + Type: cmtproto.ProposalType, + Height: 1, + Round: 2, + POLRound: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + Signature: []byte("signature"), + } + + err := tc.signerClient.SignProposal(tc.chainID, proposal.ToProto()) + require.Equal(t, err.(*RemoteSignerError).Description, types.ErroringMockPVErr.Error()) + + err = tc.mockPV.SignProposal(tc.chainID, proposal.ToProto()) + require.Error(t, err) + + err = tc.signerClient.SignProposal(tc.chainID, proposal.ToProto()) + require.Error(t, err) + } +} + +func TestSignerSignVoteErrors(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + ts := time.Now() + hash := cmtrand.Bytes(tmhash.Size) + valAddr := cmtrand.Bytes(crypto.AddressSize) + vote := &types.Vote{ + Type: cmtproto.PrecommitType, + Height: 1, + Round: 2, + BlockID: types.BlockID{Hash: hash, PartSetHeader: types.PartSetHeader{Hash: hash, Total: 2}}, + Timestamp: ts, + ValidatorAddress: valAddr, + ValidatorIndex: 1, + Signature: []byte("signature"), + } + + // Replace signer service privval with one that always fails + tc.signerServer.privVal = types.NewErroringMockPV() + tc.mockPV = types.NewErroringMockPV() + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + err := tc.signerClient.SignVote(tc.chainID, vote.ToProto()) + require.Equal(t, err.(*RemoteSignerError).Description, types.ErroringMockPVErr.Error()) + + err = tc.mockPV.SignVote(tc.chainID, vote.ToProto()) + require.Error(t, err) + + err = tc.signerClient.SignVote(tc.chainID, vote.ToProto()) + require.Error(t, err) + } +} + +func brokenHandler(_ types.PrivValidator, request privvalproto.Message, _ string) (privvalproto.Message, error) { + var res privvalproto.Message + var err error + + switch r := request.Sum.(type) { + // This is broken and will answer most requests with a pubkey response + case *privvalproto.Message_PubKeyRequest: + res = mustWrapMsg(&privvalproto.PubKeyResponse{PubKey: cryptoproto.PublicKey{}, Error: nil}) + case *privvalproto.Message_SignVoteRequest: + res = mustWrapMsg(&privvalproto.PubKeyResponse{PubKey: cryptoproto.PublicKey{}, Error: nil}) + case *privvalproto.Message_SignProposalRequest: + res = mustWrapMsg(&privvalproto.PubKeyResponse{PubKey: cryptoproto.PublicKey{}, Error: nil}) + case *privvalproto.Message_PingRequest: + err, res = nil, mustWrapMsg(&privvalproto.PingResponse{}) + default: + err = fmt.Errorf("unknown msg: %v", r) + } + + return res, err +} + +func TestSignerUnexpectedResponse(t *testing.T) { + for _, tc := range getSignerTestCases(t) { + tc.signerServer.privVal = types.NewMockPV() + tc.mockPV = types.NewMockPV() + + tc.signerServer.SetRequestHandler(brokenHandler) + + tc := tc + t.Cleanup(func() { + if err := tc.signerServer.Stop(); err != nil { + t.Error(err) + } + }) + t.Cleanup(func() { + if err := tc.signerClient.Close(); err != nil { + t.Error(err) + } + }) + + ts := time.Now() + want := &types.Vote{Timestamp: ts, Type: cmtproto.PrecommitType} + + e := tc.signerClient.SignVote(tc.chainID, want.ToProto()) + assert.EqualError(t, e, "empty response") + } +} diff --git a/privval/signer_dialer_endpoint.go b/privval/signer_dialer_endpoint.go new file mode 100644 index 0000000..529b3d1 --- /dev/null +++ b/privval/signer_dialer_endpoint.go @@ -0,0 +1,96 @@ +package privval + +import ( + "time" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" +) + +const ( + defaultMaxDialRetries = 10 + defaultRetryWaitMilliseconds = 100 +) + +// SignerServiceEndpointOption sets an optional parameter on the SignerDialerEndpoint. +type SignerServiceEndpointOption func(*SignerDialerEndpoint) + +// SignerDialerEndpointTimeoutReadWrite sets the read and write timeout for +// connections from client processes. +func SignerDialerEndpointTimeoutReadWrite(timeout time.Duration) SignerServiceEndpointOption { + return func(ss *SignerDialerEndpoint) { ss.timeoutReadWrite = timeout } +} + +// SignerDialerEndpointConnRetries sets the amount of attempted retries to +// acceptNewConnection. +func SignerDialerEndpointConnRetries(retries int) SignerServiceEndpointOption { + return func(ss *SignerDialerEndpoint) { ss.maxConnRetries = retries } +} + +// SignerDialerEndpointRetryWaitInterval sets the retry wait interval to a +// custom value. +func SignerDialerEndpointRetryWaitInterval(interval time.Duration) SignerServiceEndpointOption { + return func(ss *SignerDialerEndpoint) { ss.retryWait = interval } +} + +// SignerDialerEndpoint dials using its dialer and responds to any signature +// requests using its privVal. +type SignerDialerEndpoint struct { + signerEndpoint + + dialer SocketDialer + + retryWait time.Duration + maxConnRetries int +} + +// NewSignerDialerEndpoint returns a SignerDialerEndpoint that will dial using the given +// dialer and respond to any signature requests over the connection +// using the given privVal. +func NewSignerDialerEndpoint( + logger log.Logger, + dialer SocketDialer, + options ...SignerServiceEndpointOption, +) *SignerDialerEndpoint { + + sd := &SignerDialerEndpoint{ + dialer: dialer, + retryWait: defaultRetryWaitMilliseconds * time.Millisecond, + maxConnRetries: defaultMaxDialRetries, + } + + sd.BaseService = *service.NewBaseService(logger, "SignerDialerEndpoint", sd) + sd.timeoutReadWrite = defaultTimeoutReadWriteSeconds * time.Second + + for _, optionFunc := range options { + optionFunc(sd) + } + + return sd +} + +func (sd *SignerDialerEndpoint) ensureConnection() error { + if sd.IsConnected() { + return nil + } + + retries := 0 + for retries < sd.maxConnRetries { + conn, err := sd.dialer() + + if err != nil { + retries++ + sd.Logger.Debug("SignerDialer: Reconnection failed", "retries", retries, "max", sd.maxConnRetries, "err", err) + // Wait between retries + time.Sleep(sd.retryWait) + } else { + sd.SetConnection(conn) + sd.Logger.Debug("SignerDialer: Connection Ready") + return nil + } + } + + sd.Logger.Debug("SignerDialer: Max retries exceeded", "retries", retries, "max", sd.maxConnRetries) + + return ErrNoConnection +} diff --git a/privval/signer_endpoint.go b/privval/signer_endpoint.go new file mode 100644 index 0000000..00e5293 --- /dev/null +++ b/privval/signer_endpoint.go @@ -0,0 +1,154 @@ +package privval + +import ( + "fmt" + "net" + "time" + + "github.com/cometbft/cometbft/libs/protoio" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" +) + +const ( + defaultTimeoutReadWriteSeconds = 5 +) + +type signerEndpoint struct { + service.BaseService + + connMtx cmtsync.Mutex + conn net.Conn + + timeoutReadWrite time.Duration +} + +// Close closes the underlying net.Conn. +func (se *signerEndpoint) Close() error { + se.DropConnection() + return nil +} + +// IsConnected indicates if there is an active connection +func (se *signerEndpoint) IsConnected() bool { + se.connMtx.Lock() + defer se.connMtx.Unlock() + return se.isConnected() +} + +// TryGetConnection retrieves a connection if it is already available +func (se *signerEndpoint) GetAvailableConnection(connectionAvailableCh chan net.Conn) bool { + se.connMtx.Lock() + defer se.connMtx.Unlock() + + // Is there a connection ready? + select { + case se.conn = <-connectionAvailableCh: + return true + default: + } + return false +} + +// TryGetConnection retrieves a connection if it is already available +func (se *signerEndpoint) WaitConnection(connectionAvailableCh chan net.Conn, maxWait time.Duration) error { + select { + case conn := <-connectionAvailableCh: + se.SetConnection(conn) + case <-time.After(maxWait): + return ErrConnectionTimeout + } + + return nil +} + +// SetConnection replaces the current connection object +func (se *signerEndpoint) SetConnection(newConnection net.Conn) { + se.connMtx.Lock() + defer se.connMtx.Unlock() + se.conn = newConnection +} + +// IsConnected indicates if there is an active connection +func (se *signerEndpoint) DropConnection() { + se.connMtx.Lock() + defer se.connMtx.Unlock() + se.dropConnection() +} + +// ReadMessage reads a message from the endpoint +func (se *signerEndpoint) ReadMessage() (msg privvalproto.Message, err error) { + se.connMtx.Lock() + defer se.connMtx.Unlock() + + if !se.isConnected() { + return msg, fmt.Errorf("endpoint is not connected: %w", ErrNoConnection) + } + // Reset read deadline + deadline := time.Now().Add(se.timeoutReadWrite) + + err = se.conn.SetReadDeadline(deadline) + if err != nil { + return + } + const maxRemoteSignerMsgSize = 1024 * 10 + protoReader := protoio.NewDelimitedReader(se.conn, maxRemoteSignerMsgSize) + _, err = protoReader.ReadMsg(&msg) + if _, ok := err.(timeoutError); ok { + if err != nil { + err = fmt.Errorf("%v: %w", err, ErrReadTimeout) + } else { + err = fmt.Errorf("empty error: %w", ErrReadTimeout) + } + + se.Logger.Debug("Dropping [read]", "obj", se) + se.dropConnection() + } + + return +} + +// WriteMessage writes a message from the endpoint +func (se *signerEndpoint) WriteMessage(msg privvalproto.Message) (err error) { + se.connMtx.Lock() + defer se.connMtx.Unlock() + + if !se.isConnected() { + return fmt.Errorf("endpoint is not connected: %w", ErrNoConnection) + } + + protoWriter := protoio.NewDelimitedWriter(se.conn) + + // Reset read deadline + deadline := time.Now().Add(se.timeoutReadWrite) + err = se.conn.SetWriteDeadline(deadline) + if err != nil { + return + } + + _, err = protoWriter.WriteMsg(&msg) + if _, ok := err.(timeoutError); ok { + if err != nil { + err = fmt.Errorf("%v: %w", err, ErrWriteTimeout) + } else { + err = fmt.Errorf("empty error: %w", ErrWriteTimeout) + } + se.dropConnection() + } + + return +} + +func (se *signerEndpoint) isConnected() bool { + return se.conn != nil +} + +func (se *signerEndpoint) dropConnection() { + if se.conn != nil { + if err := se.conn.Close(); err != nil { + se.Logger.Error("signerEndpoint::dropConnection", "err", err) + } + se.conn = nil + } +} diff --git a/privval/signer_listener_endpoint.go b/privval/signer_listener_endpoint.go new file mode 100644 index 0000000..627c26c --- /dev/null +++ b/privval/signer_listener_endpoint.go @@ -0,0 +1,231 @@ +package privval + +import ( + "fmt" + "net" + "sync/atomic" + "time" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" +) + +// SignerListenerEndpointOption sets an optional parameter on the SignerListenerEndpoint. +type SignerListenerEndpointOption func(*SignerListenerEndpoint) + +// SignerListenerEndpointTimeoutReadWrite sets the read and write timeout for +// connections from external signing processes. +// +// Default: 5s +func SignerListenerEndpointTimeoutReadWrite(timeout time.Duration) SignerListenerEndpointOption { + return func(sl *SignerListenerEndpoint) { sl.timeoutReadWrite = timeout } +} + +// SignerListenerEndpoint listens for an external process to dial in and keeps +// the connection alive by dropping and reconnecting. +// +// The process will send pings every ~3s (read/write timeout * 2/3) to keep the +// connection alive. +type SignerListenerEndpoint struct { + signerEndpoint + + listener net.Listener + connectRequestCh chan struct{} + connectionAvailableCh chan net.Conn + + timeoutAccept time.Duration + acceptFailCount atomic.Uint32 + pingTimer *time.Ticker + pingInterval time.Duration + + instanceMtx cmtsync.Mutex // Ensures instance public methods access, i.e. SendRequest +} + +// NewSignerListenerEndpoint returns an instance of SignerListenerEndpoint. +func NewSignerListenerEndpoint( + logger log.Logger, + listener net.Listener, + options ...SignerListenerEndpointOption, +) *SignerListenerEndpoint { + sl := &SignerListenerEndpoint{ + listener: listener, + timeoutAccept: defaultTimeoutAcceptSeconds * time.Second, + } + + sl.BaseService = *service.NewBaseService(logger, "SignerListenerEndpoint", sl) + sl.timeoutReadWrite = defaultTimeoutReadWriteSeconds * time.Second + + for _, optionFunc := range options { + optionFunc(sl) + } + + return sl +} + +// OnStart implements service.Service. +func (sl *SignerListenerEndpoint) OnStart() error { + sl.connectRequestCh = make(chan struct{}, 1) // Buffer of 1 to allow `serviceLoop` to re-trigger itself. + sl.connectionAvailableCh = make(chan net.Conn) + + // NOTE: ping timeout must be less than read/write timeout. + sl.pingInterval = time.Duration(sl.timeoutReadWrite.Milliseconds()*2/3) * time.Millisecond + sl.pingTimer = time.NewTicker(sl.pingInterval) + + go sl.serviceLoop() + go sl.pingLoop() + + sl.connectRequestCh <- struct{}{} + + return nil +} + +// OnStop implements service.Service +func (sl *SignerListenerEndpoint) OnStop() { + sl.instanceMtx.Lock() + defer sl.instanceMtx.Unlock() + _ = sl.Close() + + // Stop listening + if sl.listener != nil { + if err := sl.listener.Close(); err != nil { + sl.Logger.Error("Closing Listener", "err", err) + sl.listener = nil + } + } + + sl.pingTimer.Stop() +} + +// WaitForConnection waits maxWait for a connection or returns a timeout error +func (sl *SignerListenerEndpoint) WaitForConnection(maxWait time.Duration) error { + sl.instanceMtx.Lock() + defer sl.instanceMtx.Unlock() + return sl.ensureConnection(maxWait) +} + +// SendRequest ensures there is a connection, sends a request and waits for a response +func (sl *SignerListenerEndpoint) SendRequest(request privvalproto.Message) (*privvalproto.Message, error) { + sl.instanceMtx.Lock() + defer sl.instanceMtx.Unlock() + + err := sl.ensureConnection(sl.timeoutAccept) + if err != nil { + return nil, err + } + + err = sl.WriteMessage(request) + if err != nil { + return nil, err + } + + res, err := sl.ReadMessage() + if err != nil { + return nil, err + } + + // Reset pingTimer to avoid sending unnecessary pings. + sl.pingTimer.Reset(sl.pingInterval) + + return &res, nil +} + +func (sl *SignerListenerEndpoint) ensureConnection(maxWait time.Duration) error { + if sl.IsConnected() { + return nil + } + + // Is there a connection ready? then use it + if sl.GetAvailableConnection(sl.connectionAvailableCh) { + return nil + } + + // block until connected or timeout + sl.Logger.Info("SignerListener: Blocking for connection") + sl.triggerConnect() + err := sl.WaitConnection(sl.connectionAvailableCh, maxWait) + if err != nil { + return err + } + + return nil +} + +func (sl *SignerListenerEndpoint) acceptNewConnection() (net.Conn, error) { + if !sl.IsRunning() || sl.listener == nil { + return nil, fmt.Errorf("endpoint is closing") + } + + // wait for a new conn + sl.Logger.Info("SignerListener: Listening for new connection") + conn, err := sl.listener.Accept() + if err != nil { + sl.acceptFailCount.Add(1) + return nil, err + } + + sl.acceptFailCount.Store(0) + return conn, nil +} + +func (sl *SignerListenerEndpoint) triggerConnect() { + select { + case sl.connectRequestCh <- struct{}{}: + default: + } +} + +func (sl *SignerListenerEndpoint) triggerReconnect() { + sl.DropConnection() + sl.triggerConnect() +} + +func (sl *SignerListenerEndpoint) serviceLoop() { + for { + select { + case <-sl.connectRequestCh: + // On start, listen timeouts can queue a duplicate connect request to queue + // while the first request connects. Drop duplicate request. + if sl.IsConnected() { + sl.Logger.Debug("SignerListener: Connected. Drop Listen Request") + continue + } + + // Listen for remote signer + conn, err := sl.acceptNewConnection() + if err != nil { + sl.Logger.Error("SignerListener: Error accepting connection", "err", err, "failures", sl.acceptFailCount.Load()) + sl.triggerConnect() + continue + } + + // We have a good connection, wait for someone that needs one otherwise cancellation + sl.Logger.Info("SignerListener: Connected") + select { + case sl.connectionAvailableCh <- conn: + case <-sl.Quit(): + return + } + case <-sl.Quit(): + return + } + } +} + +func (sl *SignerListenerEndpoint) pingLoop() { + for { + select { + case <-sl.pingTimer.C: + { + _, err := sl.SendRequest(mustWrapMsg(&privvalproto.PingRequest{})) + if err != nil { + sl.Logger.Error("SignerListener: Ping timeout") + sl.triggerReconnect() + } + } + case <-sl.Quit(): + return + } + } +} diff --git a/privval/signer_listener_endpoint_test.go b/privval/signer_listener_endpoint_test.go new file mode 100644 index 0000000..7a0e4a2 --- /dev/null +++ b/privval/signer_listener_endpoint_test.go @@ -0,0 +1,322 @@ +package privval + +import ( + "errors" + "net" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/types" +) + +var ( + testTimeoutAccept = defaultTimeoutAcceptSeconds * time.Second + + testTimeoutReadWrite = 100 * time.Millisecond + testTimeoutReadWrite2o3 = 60 * time.Millisecond // 2/3 of the other one +) + +type dialerTestCase struct { + addr string + dialer SocketDialer +} + +// TestSignerRemoteRetryTCPOnly will test connection retry attempts over TCP. We +// don't need this for Unix sockets because the OS instantly knows the state of +// both ends of the socket connection. This basically causes the +// SignerDialerEndpoint.dialer() call inside SignerDialerEndpoint.acceptNewConnection() to return +// successfully immediately, putting an instant stop to any retry attempts. +func TestSignerRemoteRetryTCPOnly(t *testing.T) { + var ( + attemptCh = make(chan int) + retries = 10 + ) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + // Continuously Accept connection and close {attempts} times + go func(ln net.Listener, attemptCh chan<- int) { + attempts := 0 + for { + conn, err := ln.Accept() + require.NoError(t, err) + + err = conn.Close() + require.NoError(t, err) + + attempts++ + + if attempts == retries { + attemptCh <- attempts + break + } + } + }(ln, attemptCh) + + dialerEndpoint := NewSignerDialerEndpoint( + log.TestingLogger(), + DialTCPFn(ln.Addr().String(), testTimeoutReadWrite, ed25519.GenPrivKey()), + ) + SignerDialerEndpointTimeoutReadWrite(time.Millisecond)(dialerEndpoint) + SignerDialerEndpointConnRetries(retries)(dialerEndpoint) + + chainID := cmtrand.Str(12) + mockPV := types.NewMockPV() + signerServer := NewSignerServer(dialerEndpoint, chainID, mockPV) + + err = signerServer.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := signerServer.Stop(); err != nil { + t.Error(err) + } + }) + + select { + case attempts := <-attemptCh: + assert.Equal(t, retries, attempts) + case <-time.After(1500 * time.Millisecond): + t.Error("expected remote to observe connection attempts") + } +} + +func TestRetryConnToRemoteSigner(t *testing.T) { + for _, tc := range getDialerTestCases(t) { + var ( + logger = log.TestingLogger() + chainID = cmtrand.Str(12) + mockPV = types.NewMockPV() + endpointIsOpenCh = make(chan struct{}) + thisConnTimeout = testTimeoutReadWrite + listenerEndpoint = newSignerListenerEndpoint(logger, tc.addr, thisConnTimeout) + ) + + dialerEndpoint := NewSignerDialerEndpoint( + logger, + tc.dialer, + ) + SignerDialerEndpointTimeoutReadWrite(testTimeoutReadWrite)(dialerEndpoint) + SignerDialerEndpointConnRetries(10)(dialerEndpoint) + + signerServer := NewSignerServer(dialerEndpoint, chainID, mockPV) + + startListenerEndpointAsync(t, listenerEndpoint, endpointIsOpenCh) + t.Cleanup(func() { + if err := listenerEndpoint.Stop(); err != nil { + t.Error(err) + } + }) + + require.NoError(t, signerServer.Start()) + assert.True(t, signerServer.IsRunning()) + <-endpointIsOpenCh + if err := signerServer.Stop(); err != nil { + t.Error(err) + } + + dialerEndpoint2 := NewSignerDialerEndpoint( + logger, + tc.dialer, + ) + signerServer2 := NewSignerServer(dialerEndpoint2, chainID, mockPV) + + // let some pings pass + require.NoError(t, signerServer2.Start()) + assert.True(t, signerServer2.IsRunning()) + t.Cleanup(func() { + if err := signerServer2.Stop(); err != nil { + t.Error(err) + } + }) + + // give the client some time to re-establish the conn to the remote signer + // should see sth like this in the logs: + // + // E[10016-01-10|17:12:46.128] Ping err="remote signer timed out" + // I[10016-01-10|17:16:42.447] Re-created connection to remote signer impl=SocketVal + time.Sleep(testTimeoutReadWrite * 2) + } +} + +func TestDuplicateListenReject(t *testing.T) { + for _, tc := range getDialerTestCases(t) { + var ( + logger = log.TestingLogger() + chainID = cmtrand.Str(12) + mockPV = types.NewMockPV() + endpointIsOpenCh = make(chan struct{}) + thisConnTimeout = testTimeoutReadWrite + listenerEndpoint = newSignerListenerEndpoint(logger, tc.addr, thisConnTimeout) + ) + listenerEndpoint.timeoutAccept = defaultTimeoutAcceptSeconds / 2 * time.Second + + dialerEndpoint := NewSignerDialerEndpoint( + logger, + tc.dialer, + ) + SignerDialerEndpointTimeoutReadWrite(testTimeoutReadWrite)(dialerEndpoint) + SignerDialerEndpointConnRetries(10)(dialerEndpoint) + + signerServer := NewSignerServer(dialerEndpoint, chainID, mockPV) + + startListenerEndpointAsync(t, listenerEndpoint, endpointIsOpenCh) + t.Cleanup(func() { + if err := listenerEndpoint.Stop(); err != nil { + t.Error(err) + } + }) + + require.NoError(t, signerServer.Start()) + assert.True(t, signerServer.IsRunning()) + + <-endpointIsOpenCh + if err := signerServer.Stop(); err != nil { + t.Error(err) + } + + dialerEndpoint2 := NewSignerDialerEndpoint( + logger, + tc.dialer, + ) + signerServer2 := NewSignerServer(dialerEndpoint2, chainID, mockPV) + + // let some pings pass + require.NoError(t, signerServer2.Start()) + assert.True(t, signerServer2.IsRunning()) + + // wait for successful connection + for !listenerEndpoint.IsConnected() { + + } + + // simulate ensureConnection, bypass triggerConnect default drop with multiple messages + time.Sleep(100 * time.Millisecond) + listenerEndpoint.triggerConnect() + time.Sleep(100 * time.Millisecond) + listenerEndpoint.triggerConnect() + time.Sleep(100 * time.Millisecond) + listenerEndpoint.triggerConnect() + + // simulate validator node running long enough for privval listen timeout multiple times + // up to 1 timeout error is possible due to timing differences + // Run 3 times longer than timeout to generate at least 2 accept errors + time.Sleep(3 * defaultTimeoutAcceptSeconds * time.Second) + t.Cleanup(func() { + if err := signerServer2.Stop(); err != nil { + t.Error(err) + } + }) + + // after connect, there should not be more than 1 accept fail + assert.LessOrEqual(t, listenerEndpoint.acceptFailCount.Load(), uint32(1)) + + // give the client some time to re-establish the conn to the remote signer + // should see sth like this in the logs: + // + // E[10016-01-10|17:12:46.128] Ping err="remote signer timed out" + // I[10016-01-10|17:16:42.447] Re-created connection to remote signer impl=SocketVal + time.Sleep(testTimeoutReadWrite * 2) + } +} + +func newSignerListenerEndpoint(logger log.Logger, addr string, timeoutReadWrite time.Duration) *SignerListenerEndpoint { + proto, address := cmtnet.ProtocolAndAddress(addr) + + ln, err := net.Listen(proto, address) + logger.Info("SignerListener: Listening", "proto", proto, "address", address) + if err != nil { + panic(err) + } + + var listener net.Listener + + if proto == "unix" { + unixLn := NewUnixListener(ln) + UnixListenerTimeoutAccept(testTimeoutAccept)(unixLn) + UnixListenerTimeoutReadWrite(timeoutReadWrite)(unixLn) + listener = unixLn + } else { + tcpLn := NewTCPListener(ln, ed25519.GenPrivKey()) + TCPListenerTimeoutAccept(testTimeoutAccept)(tcpLn) + TCPListenerTimeoutReadWrite(timeoutReadWrite)(tcpLn) + listener = tcpLn + } + + return NewSignerListenerEndpoint( + logger, + listener, + SignerListenerEndpointTimeoutReadWrite(testTimeoutReadWrite), + ) +} + +func startListenerEndpointAsync(t *testing.T, sle *SignerListenerEndpoint, endpointIsOpenCh chan struct{}) { + go func(sle *SignerListenerEndpoint) { + require.NoError(t, sle.Start()) + assert.True(t, sle.IsRunning()) + close(endpointIsOpenCh) + }(sle) +} + +func getMockEndpoints( + t *testing.T, + addr string, + socketDialer SocketDialer, +) (*SignerListenerEndpoint, *SignerDialerEndpoint) { + + var ( + logger = log.TestingLogger() + endpointIsOpenCh = make(chan struct{}) + + dialerEndpoint = NewSignerDialerEndpoint( + logger, + socketDialer, + ) + + listenerEndpoint = newSignerListenerEndpoint(logger, addr, testTimeoutReadWrite) + ) + + SignerDialerEndpointTimeoutReadWrite(testTimeoutReadWrite)(dialerEndpoint) + SignerDialerEndpointConnRetries(1e6)(dialerEndpoint) + + startListenerEndpointAsync(t, listenerEndpoint, endpointIsOpenCh) + + require.NoError(t, dialerEndpoint.Start()) + assert.True(t, dialerEndpoint.IsRunning()) + + <-endpointIsOpenCh + + return listenerEndpoint, dialerEndpoint +} + +func TestSignerListenerEndpointServiceLoop(t *testing.T) { + listenerEndpoint := NewSignerListenerEndpoint( + log.TestingLogger(), + &testListener{initialErrs: 5}, + ) + + require.NoError(t, listenerEndpoint.Start()) + require.NoError(t, listenerEndpoint.WaitForConnection(time.Second)) +} + +type testListener struct { + net.Listener + initialErrs int +} + +func (l *testListener) Accept() (net.Conn, error) { + if l.initialErrs > 0 { + l.initialErrs-- + + return nil, errors.New("accept error") + } + + return nil, nil // Note this doesn't actually return a valid connection, it just doesn't error. +} diff --git a/privval/signer_requestHandler.go b/privval/signer_requestHandler.go new file mode 100644 index 0000000..715836a --- /dev/null +++ b/privval/signer_requestHandler.go @@ -0,0 +1,90 @@ +package privval + +import ( + "fmt" + + "github.com/cometbft/cometbft/crypto" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + cryptoproto "github.com/cometbft/cometbft/proto/tendermint/crypto" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +func DefaultValidationRequestHandler( + privVal types.PrivValidator, + req privvalproto.Message, + chainID string, +) (privvalproto.Message, error) { + var ( + res privvalproto.Message + err error + ) + + switch r := req.Sum.(type) { + case *privvalproto.Message_PubKeyRequest: + if r.PubKeyRequest.GetChainId() != chainID { + res = mustWrapMsg(&privvalproto.PubKeyResponse{ + PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{ + Code: 0, Description: "unable to provide pubkey"}}) + return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.PubKeyRequest.GetChainId(), chainID) + } + + var pubKey crypto.PubKey + pubKey, err = privVal.GetPubKey() + if err != nil { + return res, err + } + pk, err := cryptoenc.PubKeyToProto(pubKey) + if err != nil { + res = mustWrapMsg(&privvalproto.PubKeyResponse{ + PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + } else { + res = mustWrapMsg(&privvalproto.PubKeyResponse{PubKey: pk, Error: nil}) + } + + case *privvalproto.Message_SignVoteRequest: + if r.SignVoteRequest.ChainId != chainID { + res = mustWrapMsg(&privvalproto.SignedVoteResponse{ + Vote: cmtproto.Vote{}, Error: &privvalproto.RemoteSignerError{ + Code: 0, Description: "unable to sign vote"}}) + return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.SignVoteRequest.GetChainId(), chainID) + } + + vote := r.SignVoteRequest.Vote + + err = privVal.SignVote(chainID, vote) + if err != nil { + res = mustWrapMsg(&privvalproto.SignedVoteResponse{ + Vote: cmtproto.Vote{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + } else { + res = mustWrapMsg(&privvalproto.SignedVoteResponse{Vote: *vote, Error: nil}) + } + + case *privvalproto.Message_SignProposalRequest: + if r.SignProposalRequest.GetChainId() != chainID { + res = mustWrapMsg(&privvalproto.SignedProposalResponse{ + Proposal: cmtproto.Proposal{}, Error: &privvalproto.RemoteSignerError{ + Code: 0, + Description: "unable to sign proposal"}}) + return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.SignProposalRequest.GetChainId(), chainID) + } + + proposal := r.SignProposalRequest.Proposal + + err = privVal.SignProposal(chainID, proposal) + if err != nil { + res = mustWrapMsg(&privvalproto.SignedProposalResponse{ + Proposal: cmtproto.Proposal{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + } else { + res = mustWrapMsg(&privvalproto.SignedProposalResponse{Proposal: *proposal, Error: nil}) + } + case *privvalproto.Message_PingRequest: + err, res = nil, mustWrapMsg(&privvalproto.PingResponse{}) + + default: + err = fmt.Errorf("unknown msg: %v", r) + } + + return res, err +} diff --git a/privval/signer_server.go b/privval/signer_server.go new file mode 100644 index 0000000..b5335af --- /dev/null +++ b/privval/signer_server.go @@ -0,0 +1,106 @@ +package privval + +import ( + "io" + + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + privvalproto "github.com/cometbft/cometbft/proto/tendermint/privval" + "github.com/cometbft/cometbft/types" +) + +// ValidationRequestHandlerFunc handles different remoteSigner requests +type ValidationRequestHandlerFunc func( + privVal types.PrivValidator, + requestMessage privvalproto.Message, + chainID string) (privvalproto.Message, error) + +type SignerServer struct { + service.BaseService + + endpoint *SignerDialerEndpoint + chainID string + privVal types.PrivValidator + + handlerMtx cmtsync.Mutex + validationRequestHandler ValidationRequestHandlerFunc +} + +func NewSignerServer(endpoint *SignerDialerEndpoint, chainID string, privVal types.PrivValidator) *SignerServer { + ss := &SignerServer{ + endpoint: endpoint, + chainID: chainID, + privVal: privVal, + validationRequestHandler: DefaultValidationRequestHandler, + } + + ss.BaseService = *service.NewBaseService(endpoint.Logger, "SignerServer", ss) + + return ss +} + +// OnStart implements service.Service. +func (ss *SignerServer) OnStart() error { + go ss.serviceLoop() + return nil +} + +// OnStop implements service.Service. +func (ss *SignerServer) OnStop() { + ss.endpoint.Logger.Debug("SignerServer: OnStop calling Close") + _ = ss.endpoint.Close() +} + +// SetRequestHandler override the default function that is used to service requests +func (ss *SignerServer) SetRequestHandler(validationRequestHandler ValidationRequestHandlerFunc) { + ss.handlerMtx.Lock() + defer ss.handlerMtx.Unlock() + ss.validationRequestHandler = validationRequestHandler +} + +func (ss *SignerServer) servicePendingRequest() { + if !ss.IsRunning() { + return // Ignore error from closing. + } + + req, err := ss.endpoint.ReadMessage() + if err != nil { + if err != io.EOF { + ss.Logger.Error("SignerServer: HandleMessage", "err", err) + } + return + } + + var res privvalproto.Message + { + // limit the scope of the lock + ss.handlerMtx.Lock() + defer ss.handlerMtx.Unlock() + res, err = ss.validationRequestHandler(ss.privVal, req, ss.chainID) + if err != nil { + // only log the error; we'll reply with an error in res + ss.Logger.Error("SignerServer: handleMessage", "err", err) + } + } + + err = ss.endpoint.WriteMessage(res) + if err != nil { + ss.Logger.Error("SignerServer: writeMessage", "err", err) + } +} + +func (ss *SignerServer) serviceLoop() { + for { + select { + default: + err := ss.endpoint.ensureConnection() + if err != nil { + return + } + ss.servicePendingRequest() + + case <-ss.Quit(): + return + } + } +} diff --git a/privval/socket_dialers.go b/privval/socket_dialers.go new file mode 100644 index 0000000..49a67ab --- /dev/null +++ b/privval/socket_dialers.go @@ -0,0 +1,43 @@ +package privval + +import ( + "errors" + "net" + "time" + + "github.com/cometbft/cometbft/crypto" + cmtnet "github.com/cometbft/cometbft/libs/net" + p2pconn "github.com/cometbft/cometbft/p2p/conn" +) + +// Socket errors. +var ( + ErrDialRetryMax = errors.New("dialed maximum retries") +) + +// SocketDialer dials a remote address and returns a net.Conn or an error. +type SocketDialer func() (net.Conn, error) + +// DialTCPFn dials the given tcp addr, using the given timeoutReadWrite and +// privKey for the authenticated encryption handshake. +func DialTCPFn(addr string, timeoutReadWrite time.Duration, privKey crypto.PrivKey) SocketDialer { + return func() (net.Conn, error) { + conn, err := cmtnet.Connect(addr) + if err == nil { + deadline := time.Now().Add(timeoutReadWrite) + err = conn.SetDeadline(deadline) + } + if err == nil { + conn, err = p2pconn.MakeSecretConnection(conn, privKey) + } + return conn, err + } +} + +// DialUnixFn dials the given unix socket. +func DialUnixFn(addr string) SocketDialer { + return func() (net.Conn, error) { + unixAddr := &net.UnixAddr{Name: addr, Net: "unix"} + return net.DialUnix("unix", nil, unixAddr) + } +} diff --git a/privval/socket_dialers_test.go b/privval/socket_dialers_test.go new file mode 100644 index 0000000..0b0ed31 --- /dev/null +++ b/privval/socket_dialers_test.go @@ -0,0 +1,48 @@ +package privval + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" +) + +func getDialerTestCases(t *testing.T) []dialerTestCase { + tcpAddr := GetFreeLocalhostAddrPort() + unixFilePath, err := testUnixAddr() + require.NoError(t, err) + unixAddr := fmt.Sprintf("unix://%s", unixFilePath) + + return []dialerTestCase{ + { + addr: tcpAddr, + dialer: DialTCPFn(tcpAddr, testTimeoutReadWrite, ed25519.GenPrivKey()), + }, + { + addr: unixAddr, + dialer: DialUnixFn(unixFilePath), + }, + } +} + +func TestIsConnTimeoutForFundamentalTimeouts(t *testing.T) { + // Generate a networking timeout + tcpAddr := GetFreeLocalhostAddrPort() + dialer := DialTCPFn(tcpAddr, time.Millisecond, ed25519.GenPrivKey()) + _, err := dialer() + assert.Error(t, err) + assert.True(t, IsConnTimeout(err)) +} + +func TestIsConnTimeoutForWrappedConnTimeouts(t *testing.T) { + tcpAddr := GetFreeLocalhostAddrPort() + dialer := DialTCPFn(tcpAddr, time.Millisecond, ed25519.GenPrivKey()) + _, err := dialer() + assert.Error(t, err) + err = fmt.Errorf("%v: %w", err, ErrConnectionTimeout) + assert.True(t, IsConnTimeout(err)) +} diff --git a/privval/socket_listeners.go b/privval/socket_listeners.go new file mode 100644 index 0000000..1e69ce6 --- /dev/null +++ b/privval/socket_listeners.go @@ -0,0 +1,190 @@ +package privval + +import ( + "net" + "time" + + "github.com/cometbft/cometbft/crypto/ed25519" + p2pconn "github.com/cometbft/cometbft/p2p/conn" +) + +const ( + defaultTimeoutAcceptSeconds = 3 +) + +// timeoutError can be used to check if an error returned from the netp package +// was due to a timeout. +type timeoutError interface { + Timeout() bool +} + +//------------------------------------------------------------------ +// TCP Listener + +// TCPListenerOption sets an optional parameter on the tcpListener. +type TCPListenerOption func(*TCPListener) + +// TCPListenerTimeoutAccept sets the timeout for the listener. +// A zero time value disables the timeout. +func TCPListenerTimeoutAccept(timeout time.Duration) TCPListenerOption { + return func(tl *TCPListener) { tl.timeoutAccept = timeout } +} + +// TCPListenerTimeoutReadWrite sets the read and write timeout for connections +// from external signing processes. +func TCPListenerTimeoutReadWrite(timeout time.Duration) TCPListenerOption { + return func(tl *TCPListener) { tl.timeoutReadWrite = timeout } +} + +// tcpListener implements net.Listener. +var _ net.Listener = (*TCPListener)(nil) + +// TCPListener wraps a *net.TCPListener to standardize protocol timeouts +// and potentially other tuning parameters. It also returns encrypted connections. +type TCPListener struct { + *net.TCPListener + + secretConnKey ed25519.PrivKey + + timeoutAccept time.Duration + timeoutReadWrite time.Duration +} + +// NewTCPListener returns a listener that accepts authenticated encrypted connections +// using the given secretConnKey and the default timeout values. +func NewTCPListener(ln net.Listener, secretConnKey ed25519.PrivKey) *TCPListener { + return &TCPListener{ + TCPListener: ln.(*net.TCPListener), + secretConnKey: secretConnKey, + timeoutAccept: time.Second * defaultTimeoutAcceptSeconds, + timeoutReadWrite: time.Second * defaultTimeoutReadWriteSeconds, + } +} + +// Accept implements net.Listener. +func (ln *TCPListener) Accept() (net.Conn, error) { + deadline := time.Now().Add(ln.timeoutAccept) + err := ln.SetDeadline(deadline) + if err != nil { + return nil, err + } + + tc, err := ln.AcceptTCP() + if err != nil { + return nil, err + } + + // Wrap the conn in our timeout and encryption wrappers + timeoutConn := newTimeoutConn(tc, ln.timeoutReadWrite) + secretConn, err := p2pconn.MakeSecretConnection(timeoutConn, ln.secretConnKey) + if err != nil { + return nil, err + } + + return secretConn, nil +} + +//------------------------------------------------------------------ +// Unix Listener + +// unixListener implements net.Listener. +var _ net.Listener = (*UnixListener)(nil) + +type UnixListenerOption func(*UnixListener) + +// UnixListenerTimeoutAccept sets the timeout for the listener. +// A zero time value disables the timeout. +func UnixListenerTimeoutAccept(timeout time.Duration) UnixListenerOption { + return func(ul *UnixListener) { ul.timeoutAccept = timeout } +} + +// UnixListenerTimeoutReadWrite sets the read and write timeout for connections +// from external signing processes. +func UnixListenerTimeoutReadWrite(timeout time.Duration) UnixListenerOption { + return func(ul *UnixListener) { ul.timeoutReadWrite = timeout } +} + +// UnixListener wraps a *net.UnixListener to standardize protocol timeouts +// and potentially other tuning parameters. It returns unencrypted connections. +type UnixListener struct { + *net.UnixListener + + timeoutAccept time.Duration + timeoutReadWrite time.Duration +} + +// NewUnixListener returns a listener that accepts unencrypted connections +// using the default timeout values. +func NewUnixListener(ln net.Listener) *UnixListener { + return &UnixListener{ + UnixListener: ln.(*net.UnixListener), + timeoutAccept: time.Second * defaultTimeoutAcceptSeconds, + timeoutReadWrite: time.Second * defaultTimeoutReadWriteSeconds, + } +} + +// Accept implements net.Listener. +func (ln *UnixListener) Accept() (net.Conn, error) { + deadline := time.Now().Add(ln.timeoutAccept) + err := ln.SetDeadline(deadline) + if err != nil { + return nil, err + } + + tc, err := ln.AcceptUnix() + if err != nil { + return nil, err + } + + // Wrap the conn in our timeout wrapper + conn := newTimeoutConn(tc, ln.timeoutReadWrite) + + // TODO: wrap in something that authenticates + // with a MAC - https://github.com/tendermint/tendermint/issues/3099 + + return conn, nil +} + +//------------------------------------------------------------------ +// Connection + +// timeoutConn implements net.Conn. +var _ net.Conn = (*timeoutConn)(nil) + +// timeoutConn wraps a net.Conn to standardize protocol timeouts / deadline resets. +type timeoutConn struct { + net.Conn + timeout time.Duration +} + +// newTimeoutConn returns an instance of timeoutConn. +func newTimeoutConn(conn net.Conn, timeout time.Duration) *timeoutConn { + return &timeoutConn{ + conn, + timeout, + } +} + +// Read implements net.Conn. +func (c timeoutConn) Read(b []byte) (n int, err error) { + // Reset deadline + deadline := time.Now().Add(c.timeout) + err = c.SetReadDeadline(deadline) + if err != nil { + return + } + + return c.Conn.Read(b) +} + +// Write implements net.Conn. +func (c timeoutConn) Write(b []byte) (n int, err error) { + // Reset deadline + deadline := time.Now().Add(c.timeout) + err = c.SetWriteDeadline(deadline) + if err != nil { + return + } + + return c.Conn.Write(b) +} diff --git a/privval/socket_listeners_test.go b/privval/socket_listeners_test.go new file mode 100644 index 0000000..15ebc23 --- /dev/null +++ b/privval/socket_listeners_test.go @@ -0,0 +1,140 @@ +package privval + +import ( + "net" + "os" + "testing" + "time" + + "github.com/cometbft/cometbft/crypto/ed25519" +) + +//------------------------------------------- +// helper funcs + +func newPrivKey() ed25519.PrivKey { + return ed25519.GenPrivKey() +} + +//------------------------------------------- +// tests + +type listenerTestCase struct { + description string // For test reporting purposes. + listener net.Listener + dialer SocketDialer +} + +// testUnixAddr will attempt to obtain a platform-independent temporary file +// name for a Unix socket +func testUnixAddr() (string, error) { + f, err := os.CreateTemp("", "cometbft-privval-test-*") + if err != nil { + return "", err + } + addr := f.Name() + f.Close() + os.Remove(addr) + return addr, nil +} + +func tcpListenerTestCase(t *testing.T, timeoutAccept, timeoutReadWrite time.Duration) listenerTestCase { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + tcpLn := NewTCPListener(ln, newPrivKey()) + TCPListenerTimeoutAccept(timeoutAccept)(tcpLn) + TCPListenerTimeoutReadWrite(timeoutReadWrite)(tcpLn) + return listenerTestCase{ + description: "TCP", + listener: tcpLn, + dialer: DialTCPFn(ln.Addr().String(), testTimeoutReadWrite, newPrivKey()), + } +} + +func unixListenerTestCase(t *testing.T, timeoutAccept, timeoutReadWrite time.Duration) listenerTestCase { + addr, err := testUnixAddr() + if err != nil { + t.Fatal(err) + } + ln, err := net.Listen("unix", addr) + if err != nil { + t.Fatal(err) + } + + unixLn := NewUnixListener(ln) + UnixListenerTimeoutAccept(timeoutAccept)(unixLn) + UnixListenerTimeoutReadWrite(timeoutReadWrite)(unixLn) + return listenerTestCase{ + description: "Unix", + listener: unixLn, + dialer: DialUnixFn(addr), + } +} + +func listenerTestCases(t *testing.T, timeoutAccept, timeoutReadWrite time.Duration) []listenerTestCase { + return []listenerTestCase{ + tcpListenerTestCase(t, timeoutAccept, timeoutReadWrite), + unixListenerTestCase(t, timeoutAccept, timeoutReadWrite), + } +} + +func TestListenerTimeoutAccept(t *testing.T) { + for _, tc := range listenerTestCases(t, time.Millisecond, time.Second) { + _, err := tc.listener.Accept() + opErr, ok := err.(*net.OpError) + if !ok { + t.Fatalf("for %s listener, have %v, want *net.OpError", tc.description, err) + } + + if have, want := opErr.Op, "accept"; have != want { + t.Errorf("for %s listener, have %v, want %v", tc.description, have, want) + } + } +} + +func TestListenerTimeoutReadWrite(t *testing.T) { + const ( + // This needs to be long enough s.t. the Accept will definitely succeed: + timeoutAccept = time.Second + // This can be really short but in the TCP case, the accept can + // also trigger a timeoutReadWrite. Hence, we need to give it some time. + // Note: this controls how long this test actually runs. + timeoutReadWrite = 10 * time.Millisecond + ) + + for _, tc := range listenerTestCases(t, timeoutAccept, timeoutReadWrite) { + go func(dialer SocketDialer) { + conn, err := dialer() + if err != nil { + panic(err) + } + // Add a delay before closing the connection + time.Sleep(2 * timeoutReadWrite) + conn.Close() + }(tc.dialer) + + c, err := tc.listener.Accept() + if err != nil { + t.Fatal(err) + } + + // this will timeout because we don't write anything: + msg := make([]byte, 200) + _, err = c.Read(msg) + opErr, ok := err.(*net.OpError) + if !ok { + t.Fatalf("for %s listener, have %v, want *net.OpError", tc.description, err) + } + + if have, want := opErr.Op, "read"; have != want { + t.Errorf("for %s listener, have %v, want %v", tc.description, have, want) + } + + if !opErr.Timeout() { + t.Errorf("for %s listener, got unexpected error: have %v, want Timeout error", tc.description, opErr) + } + } +} diff --git a/privval/utils.go b/privval/utils.go new file mode 100644 index 0000000..58bdb42 --- /dev/null +++ b/privval/utils.go @@ -0,0 +1,62 @@ +package privval + +import ( + "errors" + "fmt" + "net" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" +) + +// IsConnTimeout returns a boolean indicating whether the error is known to +// report that a connection timeout occurred. This detects both fundamental +// network timeouts, as well as ErrConnTimeout errors. +func IsConnTimeout(err error) bool { + _, ok := errors.Unwrap(err).(timeoutError) + switch { + case errors.As(err, &EndpointTimeoutError{}): + return true + case ok: + return true + default: + return false + } +} + +// NewSignerListener creates a new SignerListenerEndpoint using the corresponding listen address +func NewSignerListener(listenAddr string, logger log.Logger) (*SignerListenerEndpoint, error) { + var listener net.Listener + + protocol, address := cmtnet.ProtocolAndAddress(listenAddr) + ln, err := net.Listen(protocol, address) + if err != nil { + return nil, err + } + switch protocol { + case "unix": + listener = NewUnixListener(ln) + case "tcp": + // TODO: persist this key so external signer can actually authenticate us + listener = NewTCPListener(ln, ed25519.GenPrivKey()) + default: + return nil, fmt.Errorf( + "wrong listen address: expected either 'tcp' or 'unix' protocols, got %s", + protocol, + ) + } + + pve := NewSignerListenerEndpoint(logger.With("module", "privval"), listener) + + return pve, nil +} + +// GetFreeLocalhostAddrPort returns a free localhost:port address +func GetFreeLocalhostAddrPort() string { + port, err := cmtnet.GetFreePort() + if err != nil { + panic(err) + } + return fmt.Sprintf("127.0.0.1:%d", port) +} diff --git a/privval/utils_test.go b/privval/utils_test.go new file mode 100644 index 0000000..4cc6f60 --- /dev/null +++ b/privval/utils_test.go @@ -0,0 +1,14 @@ +package privval + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsConnTimeoutForNonTimeoutErrors(t *testing.T) { + assert.False(t, IsConnTimeout(fmt.Errorf("max retries exceeded: %w", ErrDialRetryMax))) + assert.False(t, IsConnTimeout(errors.New("completely irrelevant error"))) +} diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 0000000..8e42504 --- /dev/null +++ b/proto/README.md @@ -0,0 +1,56 @@ + +# CometBFT v0.38.x Protocol Buffers Definitions + +This is the set of [Protobuf][protobuf] definitions of types used by various +parts of [CometBFT]: + +- The [Application Blockchain Interface][abci] (ABCI), especially in the context + of _remote_ applications. +- The P2P layer, in how CometBFT nodes interact with each other over the + network. +- In interaction with remote signers ("privval"). +- The RPC, in that the native JSON serialization of certain Protobuf types is + used when accepting and responding to RPC requests. +- The storage layer, in how data is serialized to and deserialized from on-disk + storage. + +The canonical Protobuf definitions live in the `proto` folder of the relevant +release branch of CometBFT. These definitions are published to the [Buf +registry][buf] for integrators' convenience. + +## Why does CometBFT use `tendermint` Protobuf definitions? + +This is as a result of CometBFT being a fork of [Tendermint Core][tmcore] and +wanting to provide integrators with as painless a way as possible of +transitioning from Tendermint Core to CometBFT. + +As of CometBFT v1, however, the project will transition to using and providing a +`cometbft` package of Protobuf definitions (see [\#1330]). + +## How are `tendermint` Protobuf definitions versioned? + +At present, the canonical source of Protobuf definitions for all CometBFT v0.x +releases is on each respective release branch. Each respective release's +Protobuf definitions are also, for convenience, published to a corresponding +branch in the `tendermint/tendermint` Buf repository. + +| CometBFT version | Canonical Protobufs | Buf registry | +|------------------|---------------------------------------------|-------------------------------------------| +| v0.38.x | [v0.38.x Protobuf definitions][v038-protos] | [Buf repository v0.38.x branch][v038-buf] | +| v0.37.x | [v0.37.x Protobuf definitions][v037-protos] | [Buf repository v0.37.x branch][v037-buf] | +| v0.34.x | [v0.34.x Protobuf definitions][v034-protos] | [Buf repository v0.34.x branch][v034-buf] | + +[protobuf]: https://protobuf.dev/ +[CometBFT]: https://github.com/cometbft/cometbft +[abci]: https://github.com/cometbft/cometbft/tree/main/spec/abci +[buf]: https://buf.build/tendermint/tendermint +[tmcore]: https://github.com/tendermint/tendermint +[\#1330]: https://github.com/cometbft/cometbft/issues/1330 +[v034-protos]: https://github.com/cometbft/cometbft/tree/v0.34.x/proto +[v034-buf]: https://buf.build/tendermint/tendermint/docs/v0.34.x +[v037-protos]: https://github.com/cometbft/cometbft/tree/v0.37.x/proto +[v037-buf]: https://buf.build/tendermint/tendermint/docs/v0.37.x +[v038-protos]: https://github.com/cometbft/cometbft/tree/v0.38.x/proto +[v038-buf]: https://buf.build/tendermint/tendermint/docs/v0.38.x diff --git a/proto/buf.lock b/proto/buf.lock new file mode 100644 index 0000000..2311097 --- /dev/null +++ b/proto/buf.lock @@ -0,0 +1,8 @@ +# Generated by buf. DO NOT EDIT. +version: v1 +deps: + - remote: buf.build + owner: cosmos + repository: gogo-proto + commit: 5e5b9fdd01804356895f8f79a6f1ddc1 + digest: shake256:0b85da49e2e5f9ebc4806eae058e2f56096ff3b1c59d1fb7c190413dd15f45dd456f0b69ced9059341c80795d2b6c943de15b120a9e0308b499e43e4b5fc2952 diff --git a/proto/buf.yaml b/proto/buf.yaml new file mode 100644 index 0000000..8143063 --- /dev/null +++ b/proto/buf.yaml @@ -0,0 +1,12 @@ +version: v1 +name: buf.build/tendermint/tendermint +deps: + - buf.build/cosmos/gogo-proto +breaking: + use: + - FILE +lint: + use: + - BASIC + - FILE_LOWER_SNAKE_CASE + - UNARY_RPC diff --git a/proto/tendermint/abci/types.proto b/proto/tendermint/abci/types.proto new file mode 100644 index 0000000..d0d1552 --- /dev/null +++ b/proto/tendermint/abci/types.proto @@ -0,0 +1,494 @@ +syntax = "proto3"; +package tendermint.abci; + +option go_package = "github.com/cometbft/cometbft/abci/types"; + +// For more information on gogo.proto, see: +// https://github.com/cosmos/gogoproto/blob/master/extensions.md +import "tendermint/crypto/proof.proto"; +import "tendermint/crypto/keys.proto"; +import "tendermint/types/params.proto"; +import "tendermint/types/validator.proto"; +import "google/protobuf/timestamp.proto"; +import "gogoproto/gogo.proto"; + +// NOTE: When using custom types, mind the warnings. +// https://github.com/cosmos/gogoproto/blob/master/custom_types.md#warnings-and-issues + +service ABCI { + rpc Echo(RequestEcho) returns (ResponseEcho); + rpc Flush(RequestFlush) returns (ResponseFlush); + rpc Info(RequestInfo) returns (ResponseInfo); + rpc CheckTx(RequestCheckTx) returns (ResponseCheckTx); + rpc Query(RequestQuery) returns (ResponseQuery); + rpc Commit(RequestCommit) returns (ResponseCommit); + rpc InitChain(RequestInitChain) returns (ResponseInitChain); + rpc ListSnapshots(RequestListSnapshots) returns (ResponseListSnapshots); + rpc OfferSnapshot(RequestOfferSnapshot) returns (ResponseOfferSnapshot); + rpc LoadSnapshotChunk(RequestLoadSnapshotChunk) + returns (ResponseLoadSnapshotChunk); + rpc ApplySnapshotChunk(RequestApplySnapshotChunk) + returns (ResponseApplySnapshotChunk); + rpc PrepareProposal(RequestPrepareProposal) returns (ResponsePrepareProposal); + rpc ProcessProposal(RequestProcessProposal) returns (ResponseProcessProposal); + rpc ExtendVote(RequestExtendVote) returns (ResponseExtendVote); + rpc VerifyVoteExtension(RequestVerifyVoteExtension) returns (ResponseVerifyVoteExtension); + rpc FinalizeBlock(RequestFinalizeBlock) returns (ResponseFinalizeBlock); +} + +//---------------------------------------- +// Request types + +message Request { + oneof value { + RequestEcho echo = 1; + RequestFlush flush = 2; + RequestInfo info = 3; + RequestInitChain init_chain = 5; + RequestQuery query = 6; + RequestCheckTx check_tx = 8; + RequestCommit commit = 11; + RequestListSnapshots list_snapshots = 12; + RequestOfferSnapshot offer_snapshot = 13; + RequestLoadSnapshotChunk load_snapshot_chunk = 14; + RequestApplySnapshotChunk apply_snapshot_chunk = 15; + RequestPrepareProposal prepare_proposal = 16; + RequestProcessProposal process_proposal = 17; + RequestExtendVote extend_vote = 18; + RequestVerifyVoteExtension verify_vote_extension = 19; + RequestFinalizeBlock finalize_block = 20; + } + reserved 4, 7, 9, 10; // SetOption, BeginBlock, DeliverTx, EndBlock +} + +message RequestEcho { + string message = 1; +} + +message RequestFlush {} + +message RequestInfo { + string version = 1; + uint64 block_version = 2; + uint64 p2p_version = 3; + string abci_version = 4; +} + +message RequestInitChain { + google.protobuf.Timestamp time = 1 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + string chain_id = 2; + tendermint.types.ConsensusParams consensus_params = 3; + repeated ValidatorUpdate validators = 4 [(gogoproto.nullable) = false]; + bytes app_state_bytes = 5; + int64 initial_height = 6; +} + +message RequestQuery { + bytes data = 1; + string path = 2; + int64 height = 3; + bool prove = 4; +} + +enum CheckTxType { + NEW = 0 [(gogoproto.enumvalue_customname) = "New"]; + RECHECK = 1 [(gogoproto.enumvalue_customname) = "Recheck"]; +} + +message RequestCheckTx { + bytes tx = 1; + CheckTxType type = 2; +} + +message RequestCommit {} + +// lists available snapshots +message RequestListSnapshots {} + +// offers a snapshot to the application +message RequestOfferSnapshot { + Snapshot snapshot = 1; // snapshot offered by peers + bytes app_hash = 2; // light client-verified app hash for snapshot height +} + +// loads a snapshot chunk +message RequestLoadSnapshotChunk { + uint64 height = 1; + uint32 format = 2; + uint32 chunk = 3; +} + +// Applies a snapshot chunk +message RequestApplySnapshotChunk { + uint32 index = 1; + bytes chunk = 2; + string sender = 3; +} + +message RequestPrepareProposal { + // the modified transactions cannot exceed this size. + int64 max_tx_bytes = 1; + // txs is an array of transactions that will be included in a block, + // sent to the app for possible modifications. + repeated bytes txs = 2; + ExtendedCommitInfo local_last_commit = 3 [(gogoproto.nullable) = false]; + repeated Misbehavior misbehavior = 4 [(gogoproto.nullable) = false]; + int64 height = 5; + google.protobuf.Timestamp time = 6 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes next_validators_hash = 7; + // address of the public key of the validator proposing the block. + bytes proposer_address = 8; +} + +message RequestProcessProposal { + repeated bytes txs = 1; + CommitInfo proposed_last_commit = 2 [(gogoproto.nullable) = false]; + repeated Misbehavior misbehavior = 3 [(gogoproto.nullable) = false]; + // hash is the merkle root hash of the fields of the proposed block. + bytes hash = 4; + int64 height = 5; + google.protobuf.Timestamp time = 6 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes next_validators_hash = 7; + // address of the public key of the original proposer of the block. + bytes proposer_address = 8; +} + +// Extends a vote with application-injected data +message RequestExtendVote { + // the hash of the block that this vote may be referring to + bytes hash = 1; + // the height of the extended vote + int64 height = 2; + // info of the block that this vote may be referring to + google.protobuf.Timestamp time = 3 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + repeated bytes txs = 4; + CommitInfo proposed_last_commit = 5 [(gogoproto.nullable) = false]; + repeated Misbehavior misbehavior = 6 [(gogoproto.nullable) = false]; + bytes next_validators_hash = 7; + // address of the public key of the original proposer of the block. + bytes proposer_address = 8; +} + +// Verify the vote extension +message RequestVerifyVoteExtension { + // the hash of the block that this received vote corresponds to + bytes hash = 1; + // the validator that signed the vote extension + bytes validator_address = 2; + int64 height = 3; + bytes vote_extension = 4; +} + +message RequestFinalizeBlock { + repeated bytes txs = 1; + CommitInfo decided_last_commit = 2 [(gogoproto.nullable) = false]; + repeated Misbehavior misbehavior = 3 [(gogoproto.nullable) = false]; + // hash is the merkle root hash of the fields of the decided block. + bytes hash = 4; + int64 height = 5; + google.protobuf.Timestamp time = 6 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes next_validators_hash = 7; + // proposer_address is the address of the public key of the original proposer of the block. + bytes proposer_address = 8; +} + +//---------------------------------------- +// Response types + +message Response { + oneof value { + ResponseException exception = 1; + ResponseEcho echo = 2; + ResponseFlush flush = 3; + ResponseInfo info = 4; + ResponseInitChain init_chain = 6; + ResponseQuery query = 7; + ResponseCheckTx check_tx = 9; + ResponseCommit commit = 12; + ResponseListSnapshots list_snapshots = 13; + ResponseOfferSnapshot offer_snapshot = 14; + ResponseLoadSnapshotChunk load_snapshot_chunk = 15; + ResponseApplySnapshotChunk apply_snapshot_chunk = 16; + ResponsePrepareProposal prepare_proposal = 17; + ResponseProcessProposal process_proposal = 18; + ResponseExtendVote extend_vote = 19; + ResponseVerifyVoteExtension verify_vote_extension = 20; + ResponseFinalizeBlock finalize_block = 21; + } + reserved 5, 8, 10, 11; // SetOption, BeginBlock, DeliverTx, EndBlock +} + +// nondeterministic +message ResponseException { + string error = 1; +} + +message ResponseEcho { + string message = 1; +} + +message ResponseFlush {} + +message ResponseInfo { + string data = 1; + + string version = 2; + uint64 app_version = 3; + + int64 last_block_height = 4; + bytes last_block_app_hash = 5; +} + +message ResponseInitChain { + tendermint.types.ConsensusParams consensus_params = 1; + repeated ValidatorUpdate validators = 2 [(gogoproto.nullable) = false]; + bytes app_hash = 3; +} + +message ResponseQuery { + uint32 code = 1; + // bytes data = 2; // use "value" instead. + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 index = 5; + bytes key = 6; + bytes value = 7; + tendermint.crypto.ProofOps proof_ops = 8; + int64 height = 9; + string codespace = 10; +} + +message ResponseCheckTx { + uint32 code = 1; + bytes data = 2; + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 gas_wanted = 5 [json_name = "gas_wanted"]; + int64 gas_used = 6 [json_name = "gas_used"]; + repeated Event events = 7 + [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; + string codespace = 8; + + // These reserved fields were used until v0.37 by the priority mempool (now + // removed). + reserved 9 to 11; + reserved "sender", "priority", "mempool_error"; +} + +message ResponseCommit { + reserved 1, 2; // data was previously returned here + int64 retain_height = 3; +} + +message ResponseListSnapshots { + repeated Snapshot snapshots = 1; +} + +message ResponseOfferSnapshot { + Result result = 1; + + enum Result { + UNKNOWN = 0; // Unknown result, abort all snapshot restoration + ACCEPT = 1; // Snapshot accepted, apply chunks + ABORT = 2; // Abort all snapshot restoration + REJECT = 3; // Reject this specific snapshot, try others + REJECT_FORMAT = 4; // Reject all snapshots of this format, try others + REJECT_SENDER = 5; // Reject all snapshots from the sender(s), try others + } +} + +message ResponseLoadSnapshotChunk { + bytes chunk = 1; +} + +message ResponseApplySnapshotChunk { + Result result = 1; + repeated uint32 refetch_chunks = 2; // Chunks to refetch and reapply + repeated string reject_senders = 3; // Chunk senders to reject and ban + + enum Result { + UNKNOWN = 0; // Unknown result, abort all snapshot restoration + ACCEPT = 1; // Chunk successfully accepted + ABORT = 2; // Abort all snapshot restoration + RETRY = 3; // Retry chunk (combine with refetch and reject) + RETRY_SNAPSHOT = 4; // Retry snapshot (combine with refetch and reject) + REJECT_SNAPSHOT = 5; // Reject this snapshot, try others + } +} + +message ResponsePrepareProposal { + repeated bytes txs = 1; +} + +message ResponseProcessProposal { + ProposalStatus status = 1; + + enum ProposalStatus { + UNKNOWN = 0; + ACCEPT = 1; + REJECT = 2; + } +} + +message ResponseExtendVote { + bytes vote_extension = 1; +} + +message ResponseVerifyVoteExtension { + VerifyStatus status = 1; + + enum VerifyStatus { + UNKNOWN = 0; + ACCEPT = 1; + // Rejecting the vote extension will reject the entire precommit by the sender. + // Incorrectly implementing this thus has liveness implications as it may affect + // CometBFT's ability to receive 2/3+ valid votes to finalize the block. + // Honest nodes should never be rejected. + REJECT = 2; + } +} + +message ResponseFinalizeBlock { + // set of block events emmitted as part of executing the block + repeated Event events = 1 + [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; + // the result of executing each transaction including the events + // the particular transction emitted. This should match the order + // of the transactions delivered in the block itself + repeated ExecTxResult tx_results = 2; + // a list of updates to the validator set. These will reflect the validator set at current height + 2. + repeated ValidatorUpdate validator_updates = 3 [(gogoproto.nullable) = false]; + // updates to the consensus params, if any. + tendermint.types.ConsensusParams consensus_param_updates = 4; + // app_hash is the hash of the applications' state which is used to confirm that execution of the transactions was deterministic. It is up to the application to decide which algorithm to use. + bytes app_hash = 5; +} + +//---------------------------------------- +// Misc. + +message CommitInfo { + int32 round = 1; + repeated VoteInfo votes = 2 [(gogoproto.nullable) = false]; +} + +// ExtendedCommitInfo is similar to CommitInfo except that it is only used in +// the PrepareProposal request such that CometBFT can provide vote extensions +// to the application. +message ExtendedCommitInfo { + // The round at which the block proposer decided in the previous height. + int32 round = 1; + // List of validators' addresses in the last validator set with their voting + // information, including vote extensions. + repeated ExtendedVoteInfo votes = 2 [(gogoproto.nullable) = false]; +} + +// Event allows application developers to attach additional information to +// ResponseFinalizeBlock and ResponseCheckTx. +// Later, transactions may be queried using these events. +message Event { + string type = 1; + repeated EventAttribute attributes = 2 [ + (gogoproto.nullable) = false, + (gogoproto.jsontag) = "attributes,omitempty" + ]; +} + +// EventAttribute is a single key-value pair, associated with an event. +message EventAttribute { + string key = 1; + string value = 2; + bool index = 3; // nondeterministic +} + +// ExecTxResult contains results of executing one individual transaction. +// +// * Its structure is equivalent to #ResponseDeliverTx which will be deprecated/deleted +message ExecTxResult { + uint32 code = 1; + bytes data = 2; + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 gas_wanted = 5 [json_name = "gas_wanted"]; + int64 gas_used = 6 [json_name = "gas_used"]; + repeated Event events = 7 + [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; // nondeterministic + string codespace = 8; +} + +// TxResult contains results of executing the transaction. +// +// One usage is indexing transaction results. +message TxResult { + int64 height = 1; + uint32 index = 2; + bytes tx = 3; + ExecTxResult result = 4 [(gogoproto.nullable) = false]; +} + +//---------------------------------------- +// Blockchain Types + +message Validator { + bytes address = 1; // The first 20 bytes of SHA256(public key) + // PubKey pub_key = 2 [(gogoproto.nullable)=false]; + int64 power = 3; // The voting power +} + +message ValidatorUpdate { + tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; + int64 power = 2; +} + +message VoteInfo { + Validator validator = 1 [(gogoproto.nullable) = false]; + tendermint.types.BlockIDFlag block_id_flag = 3; + + reserved 2; // signed_last_block +} + +message ExtendedVoteInfo { + // The validator that sent the vote. + Validator validator = 1 [(gogoproto.nullable) = false]; + // Non-deterministic extension provided by the sending validator's application. + bytes vote_extension = 3; + // Vote extension signature created by CometBFT + bytes extension_signature = 4; + // block_id_flag indicates whether the validator voted for a block, nil, or did not vote at all + tendermint.types.BlockIDFlag block_id_flag = 5; + + reserved 2; // signed_last_block +} + +enum MisbehaviorType { + UNKNOWN = 0; + DUPLICATE_VOTE = 1; + LIGHT_CLIENT_ATTACK = 2; +} + +message Misbehavior { + MisbehaviorType type = 1; + // The offending validator + Validator validator = 2 [(gogoproto.nullable) = false]; + // The height when the offense occurred + int64 height = 3; + // The corresponding time where the offense occurred + google.protobuf.Timestamp time = 4 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + // Total voting power of the validator set in case the ABCI application does + // not store historical validators. + // https://github.com/tendermint/tendermint/issues/4581 + int64 total_voting_power = 5; +} + +//---------------------------------------- +// State Sync Types + +message Snapshot { + uint64 height = 1; // The height at which the snapshot was taken + uint32 format = 2; // The application-specific snapshot format + uint32 chunks = 3; // Number of chunks in the snapshot + bytes hash = 4; // Arbitrary snapshot hash, equal only if identical + bytes metadata = 5; // Arbitrary application metadata +} diff --git a/proto/tendermint/blocksync/message.go b/proto/tendermint/blocksync/message.go new file mode 100644 index 0000000..f336eac --- /dev/null +++ b/proto/tendermint/blocksync/message.go @@ -0,0 +1,74 @@ +package blocksync + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/p2p" +) + +var _ p2p.Wrapper = &StatusRequest{} +var _ p2p.Wrapper = &StatusResponse{} +var _ p2p.Wrapper = &NoBlockResponse{} +var _ p2p.Wrapper = &BlockResponse{} +var _ p2p.Wrapper = &BlockRequest{} + +const ( + BlockResponseMessagePrefixSize = 4 + BlockResponseMessageFieldKeySize = 1 +) + +func (m *BlockRequest) Wrap() proto.Message { + bm := &Message{} + bm.Sum = &Message_BlockRequest{BlockRequest: m} + return bm +} + +func (m *BlockResponse) Wrap() proto.Message { + bm := &Message{} + bm.Sum = &Message_BlockResponse{BlockResponse: m} + return bm +} + +func (m *NoBlockResponse) Wrap() proto.Message { + bm := &Message{} + bm.Sum = &Message_NoBlockResponse{NoBlockResponse: m} + return bm +} + +func (m *StatusRequest) Wrap() proto.Message { + bm := &Message{} + bm.Sum = &Message_StatusRequest{StatusRequest: m} + return bm +} + +func (m *StatusResponse) Wrap() proto.Message { + bm := &Message{} + bm.Sum = &Message_StatusResponse{StatusResponse: m} + return bm +} + +// Unwrap implements the p2p Wrapper interface and unwraps a wrapped blockchain +// message. +func (m *Message) Unwrap() (proto.Message, error) { + switch msg := m.Sum.(type) { + case *Message_BlockRequest: + return m.GetBlockRequest(), nil + + case *Message_BlockResponse: + return m.GetBlockResponse(), nil + + case *Message_NoBlockResponse: + return m.GetNoBlockResponse(), nil + + case *Message_StatusRequest: + return m.GetStatusRequest(), nil + + case *Message_StatusResponse: + return m.GetStatusResponse(), nil + + default: + return nil, fmt.Errorf("unknown message: %T", msg) + } +} diff --git a/proto/tendermint/blocksync/types.pb.go b/proto/tendermint/blocksync/types.pb.go new file mode 100644 index 0000000..1164b4b --- /dev/null +++ b/proto/tendermint/blocksync/types.pb.go @@ -0,0 +1,1581 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/blocksync/types.proto + +package blocksync + +import ( + fmt "fmt" + types "github.com/cometbft/cometbft/proto/tendermint/types" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// BlockRequest requests a block for a specific height +type BlockRequest struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` +} + +func (m *BlockRequest) Reset() { *m = BlockRequest{} } +func (m *BlockRequest) String() string { return proto.CompactTextString(m) } +func (*BlockRequest) ProtoMessage() {} +func (*BlockRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{0} +} +func (m *BlockRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockRequest.Merge(m, src) +} +func (m *BlockRequest) XXX_Size() int { + return m.Size() +} +func (m *BlockRequest) XXX_DiscardUnknown() { + xxx_messageInfo_BlockRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockRequest proto.InternalMessageInfo + +func (m *BlockRequest) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +// NoBlockResponse informs the node that the peer does not have block at the requested height +type NoBlockResponse struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` +} + +func (m *NoBlockResponse) Reset() { *m = NoBlockResponse{} } +func (m *NoBlockResponse) String() string { return proto.CompactTextString(m) } +func (*NoBlockResponse) ProtoMessage() {} +func (*NoBlockResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{1} +} +func (m *NoBlockResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *NoBlockResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_NoBlockResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *NoBlockResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_NoBlockResponse.Merge(m, src) +} +func (m *NoBlockResponse) XXX_Size() int { + return m.Size() +} +func (m *NoBlockResponse) XXX_DiscardUnknown() { + xxx_messageInfo_NoBlockResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_NoBlockResponse proto.InternalMessageInfo + +func (m *NoBlockResponse) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +// BlockResponse returns block to the requested +type BlockResponse struct { + Block *types.Block `protobuf:"bytes,1,opt,name=block,proto3" json:"block,omitempty"` + ExtCommit *types.ExtendedCommit `protobuf:"bytes,2,opt,name=ext_commit,json=extCommit,proto3" json:"ext_commit,omitempty"` +} + +func (m *BlockResponse) Reset() { *m = BlockResponse{} } +func (m *BlockResponse) String() string { return proto.CompactTextString(m) } +func (*BlockResponse) ProtoMessage() {} +func (*BlockResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{2} +} +func (m *BlockResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockResponse.Merge(m, src) +} +func (m *BlockResponse) XXX_Size() int { + return m.Size() +} +func (m *BlockResponse) XXX_DiscardUnknown() { + xxx_messageInfo_BlockResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockResponse proto.InternalMessageInfo + +func (m *BlockResponse) GetBlock() *types.Block { + if m != nil { + return m.Block + } + return nil +} + +func (m *BlockResponse) GetExtCommit() *types.ExtendedCommit { + if m != nil { + return m.ExtCommit + } + return nil +} + +// StatusRequest requests the status of a peer. +type StatusRequest struct { +} + +func (m *StatusRequest) Reset() { *m = StatusRequest{} } +func (m *StatusRequest) String() string { return proto.CompactTextString(m) } +func (*StatusRequest) ProtoMessage() {} +func (*StatusRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{3} +} +func (m *StatusRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StatusRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *StatusRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_StatusRequest.Merge(m, src) +} +func (m *StatusRequest) XXX_Size() int { + return m.Size() +} +func (m *StatusRequest) XXX_DiscardUnknown() { + xxx_messageInfo_StatusRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_StatusRequest proto.InternalMessageInfo + +// StatusResponse is a peer response to inform their status. +type StatusResponse struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Base int64 `protobuf:"varint,2,opt,name=base,proto3" json:"base,omitempty"` +} + +func (m *StatusResponse) Reset() { *m = StatusResponse{} } +func (m *StatusResponse) String() string { return proto.CompactTextString(m) } +func (*StatusResponse) ProtoMessage() {} +func (*StatusResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{4} +} +func (m *StatusResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StatusResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *StatusResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_StatusResponse.Merge(m, src) +} +func (m *StatusResponse) XXX_Size() int { + return m.Size() +} +func (m *StatusResponse) XXX_DiscardUnknown() { + xxx_messageInfo_StatusResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_StatusResponse proto.InternalMessageInfo + +func (m *StatusResponse) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *StatusResponse) GetBase() int64 { + if m != nil { + return m.Base + } + return 0 +} + +type Message struct { + // Types that are valid to be assigned to Sum: + // *Message_BlockRequest + // *Message_NoBlockResponse + // *Message_BlockResponse + // *Message_StatusRequest + // *Message_StatusResponse + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_19b397c236e0fa07, []int{5} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_BlockRequest struct { + BlockRequest *BlockRequest `protobuf:"bytes,1,opt,name=block_request,json=blockRequest,proto3,oneof" json:"block_request,omitempty"` +} +type Message_NoBlockResponse struct { + NoBlockResponse *NoBlockResponse `protobuf:"bytes,2,opt,name=no_block_response,json=noBlockResponse,proto3,oneof" json:"no_block_response,omitempty"` +} +type Message_BlockResponse struct { + BlockResponse *BlockResponse `protobuf:"bytes,3,opt,name=block_response,json=blockResponse,proto3,oneof" json:"block_response,omitempty"` +} +type Message_StatusRequest struct { + StatusRequest *StatusRequest `protobuf:"bytes,4,opt,name=status_request,json=statusRequest,proto3,oneof" json:"status_request,omitempty"` +} +type Message_StatusResponse struct { + StatusResponse *StatusResponse `protobuf:"bytes,5,opt,name=status_response,json=statusResponse,proto3,oneof" json:"status_response,omitempty"` +} + +func (*Message_BlockRequest) isMessage_Sum() {} +func (*Message_NoBlockResponse) isMessage_Sum() {} +func (*Message_BlockResponse) isMessage_Sum() {} +func (*Message_StatusRequest) isMessage_Sum() {} +func (*Message_StatusResponse) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetBlockRequest() *BlockRequest { + if x, ok := m.GetSum().(*Message_BlockRequest); ok { + return x.BlockRequest + } + return nil +} + +func (m *Message) GetNoBlockResponse() *NoBlockResponse { + if x, ok := m.GetSum().(*Message_NoBlockResponse); ok { + return x.NoBlockResponse + } + return nil +} + +func (m *Message) GetBlockResponse() *BlockResponse { + if x, ok := m.GetSum().(*Message_BlockResponse); ok { + return x.BlockResponse + } + return nil +} + +func (m *Message) GetStatusRequest() *StatusRequest { + if x, ok := m.GetSum().(*Message_StatusRequest); ok { + return x.StatusRequest + } + return nil +} + +func (m *Message) GetStatusResponse() *StatusResponse { + if x, ok := m.GetSum().(*Message_StatusResponse); ok { + return x.StatusResponse + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_BlockRequest)(nil), + (*Message_NoBlockResponse)(nil), + (*Message_BlockResponse)(nil), + (*Message_StatusRequest)(nil), + (*Message_StatusResponse)(nil), + } +} + +func init() { + proto.RegisterType((*BlockRequest)(nil), "tendermint.blocksync.BlockRequest") + proto.RegisterType((*NoBlockResponse)(nil), "tendermint.blocksync.NoBlockResponse") + proto.RegisterType((*BlockResponse)(nil), "tendermint.blocksync.BlockResponse") + proto.RegisterType((*StatusRequest)(nil), "tendermint.blocksync.StatusRequest") + proto.RegisterType((*StatusResponse)(nil), "tendermint.blocksync.StatusResponse") + proto.RegisterType((*Message)(nil), "tendermint.blocksync.Message") +} + +func init() { proto.RegisterFile("tendermint/blocksync/types.proto", fileDescriptor_19b397c236e0fa07) } + +var fileDescriptor_19b397c236e0fa07 = []byte{ + // 405 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0xcd, 0x4a, 0xc3, 0x40, + 0x14, 0x85, 0x13, 0xd3, 0x56, 0xbc, 0x36, 0x0d, 0x06, 0xd1, 0x22, 0x12, 0x4a, 0xfc, 0x41, 0x17, + 0x26, 0xa0, 0x0b, 0x37, 0x82, 0x50, 0x11, 0x2a, 0xf8, 0x83, 0xe9, 0xce, 0x4d, 0xe9, 0xa4, 0x63, + 0x1b, 0x34, 0x99, 0xda, 0x99, 0x40, 0xbb, 0xf2, 0x15, 0x7c, 0x01, 0xdf, 0xc7, 0x65, 0x97, 0x2e, + 0xa5, 0x7d, 0x11, 0xe9, 0x4c, 0x9a, 0xa6, 0x31, 0x66, 0x37, 0xb9, 0x73, 0xee, 0x97, 0x73, 0xee, + 0x65, 0xa0, 0xc6, 0x70, 0xd0, 0xc1, 0x03, 0xdf, 0x0b, 0x98, 0x8d, 0x5e, 0x89, 0xfb, 0x42, 0x47, + 0x81, 0x6b, 0xb3, 0x51, 0x1f, 0x53, 0xab, 0x3f, 0x20, 0x8c, 0xe8, 0x9b, 0x0b, 0x85, 0x15, 0x2b, + 0x76, 0x76, 0x13, 0x7d, 0x5c, 0x2d, 0xba, 0x45, 0x4f, 0xc6, 0x6d, 0x82, 0x68, 0x1e, 0x42, 0xb9, + 0x3e, 0x13, 0x3b, 0xf8, 0x2d, 0xc4, 0x94, 0xe9, 0x5b, 0x50, 0xea, 0x61, 0xaf, 0xdb, 0x63, 0x55, + 0xb9, 0x26, 0x1f, 0x29, 0x4e, 0xf4, 0x65, 0x1e, 0x83, 0x76, 0x4f, 0x22, 0x25, 0xed, 0x93, 0x80, + 0xe2, 0x7f, 0xa5, 0xef, 0xa0, 0x2e, 0x0b, 0x4f, 0xa0, 0xc8, 0x0d, 0x71, 0xdd, 0xfa, 0xe9, 0xb6, + 0x95, 0x48, 0x21, 0xbc, 0x08, 0xbd, 0x50, 0xe9, 0x97, 0x00, 0x78, 0xc8, 0x5a, 0x2e, 0xf1, 0x7d, + 0x8f, 0x55, 0x57, 0x78, 0x4f, 0xed, 0x6f, 0xcf, 0xf5, 0x90, 0x97, 0x3a, 0x57, 0x5c, 0xe7, 0xac, + 0xe1, 0x21, 0x13, 0x47, 0x53, 0x03, 0xb5, 0xc9, 0xda, 0x2c, 0xa4, 0x51, 0x28, 0xf3, 0x02, 0x2a, + 0xf3, 0x42, 0xbe, 0x77, 0x5d, 0x87, 0x02, 0x6a, 0x53, 0xcc, 0xff, 0xaa, 0x38, 0xfc, 0x6c, 0x7e, + 0x2a, 0xb0, 0x7a, 0x87, 0x29, 0x6d, 0x77, 0xb1, 0x7e, 0x03, 0x2a, 0x37, 0xd9, 0x1a, 0x08, 0x74, + 0x14, 0xc9, 0xb4, 0xb2, 0x16, 0x63, 0x25, 0x27, 0xdb, 0x90, 0x9c, 0x32, 0x4a, 0x4e, 0xba, 0x09, + 0x1b, 0x01, 0x69, 0xcd, 0x69, 0xc2, 0x57, 0x94, 0xf6, 0x20, 0x1b, 0x97, 0x5a, 0x40, 0x43, 0x72, + 0xb4, 0x20, 0xb5, 0x93, 0x5b, 0xa8, 0xa4, 0x88, 0x0a, 0x27, 0xee, 0xe5, 0x1a, 0x8c, 0x79, 0x2a, + 0x4a, 0xd3, 0x28, 0x9f, 0x5b, 0x1c, 0xb7, 0x90, 0x47, 0x5b, 0x1a, 0xfa, 0x8c, 0x46, 0x93, 0x05, + 0xfd, 0x01, 0xb4, 0x98, 0x16, 0x99, 0x2b, 0x72, 0xdc, 0x7e, 0x3e, 0x2e, 0x76, 0x57, 0xa1, 0x4b, + 0x95, 0x7a, 0x11, 0x14, 0x1a, 0xfa, 0xf5, 0xc7, 0xaf, 0x89, 0x21, 0x8f, 0x27, 0x86, 0xfc, 0x33, + 0x31, 0xe4, 0x8f, 0xa9, 0x21, 0x8d, 0xa7, 0x86, 0xf4, 0x3d, 0x35, 0xa4, 0xa7, 0xf3, 0xae, 0xc7, + 0x7a, 0x21, 0xb2, 0x5c, 0xe2, 0xdb, 0x2e, 0xf1, 0x31, 0x43, 0xcf, 0x6c, 0x71, 0xe0, 0x0f, 0xc0, + 0xce, 0x7a, 0x73, 0xa8, 0xc4, 0xef, 0xce, 0x7e, 0x03, 0x00, 0x00, 0xff, 0xff, 0x56, 0x8a, 0x71, + 0xcf, 0x92, 0x03, 0x00, 0x00, +} + +func (m *BlockRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *NoBlockResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NoBlockResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NoBlockResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *BlockResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ExtCommit != nil { + { + size, err := m.ExtCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Block != nil { + { + size, err := m.Block.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *StatusRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StatusRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *StatusResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StatusResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Base != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Base)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_BlockRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_BlockRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.BlockRequest != nil { + { + size, err := m.BlockRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Message_NoBlockResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_NoBlockResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.NoBlockResponse != nil { + { + size, err := m.NoBlockResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Message_BlockResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_BlockResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.BlockResponse != nil { + { + size, err := m.BlockResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Message_StatusRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_StatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.StatusRequest != nil { + { + size, err := m.StatusRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *Message_StatusResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_StatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.StatusResponse != nil { + { + size, err := m.StatusResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + return len(dAtA) - i, nil +} +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *BlockRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + return n +} + +func (m *NoBlockResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + return n +} + +func (m *BlockResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Block != nil { + l = m.Block.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.ExtCommit != nil { + l = m.ExtCommit.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *StatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *StatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Base != 0 { + n += 1 + sovTypes(uint64(m.Base)) + } + return n +} + +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_BlockRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockRequest != nil { + l = m.BlockRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_NoBlockResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.NoBlockResponse != nil { + l = m.NoBlockResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_BlockResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockResponse != nil { + l = m.BlockResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_StatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.StatusRequest != nil { + l = m.StatusRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_StatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.StatusResponse != nil { + l = m.StatusResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *BlockRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NoBlockResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NoBlockResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NoBlockResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Block == nil { + m.Block = &types.Block{} + } + if err := m.Block.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ExtCommit == nil { + m.ExtCommit = &types.ExtendedCommit{} + } + if err := m.ExtCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StatusRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StatusRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StatusResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StatusResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StatusResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Base", wireType) + } + m.Base = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Base |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &BlockRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_BlockRequest{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NoBlockResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &NoBlockResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_NoBlockResponse{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &BlockResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_BlockResponse{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StatusRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &StatusRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_StatusRequest{v} + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StatusResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &StatusResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_StatusResponse{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/blocksync/types.proto b/proto/tendermint/blocksync/types.proto new file mode 100644 index 0000000..3e92234 --- /dev/null +++ b/proto/tendermint/blocksync/types.proto @@ -0,0 +1,43 @@ +syntax = "proto3"; +package tendermint.blocksync; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/blocksync"; + +import "tendermint/types/block.proto"; +import "tendermint/types/types.proto"; + +// BlockRequest requests a block for a specific height +message BlockRequest { + int64 height = 1; +} + +// NoBlockResponse informs the node that the peer does not have block at the requested height +message NoBlockResponse { + int64 height = 1; +} + +// BlockResponse returns block to the requested +message BlockResponse { + tendermint.types.Block block = 1; + tendermint.types.ExtendedCommit ext_commit = 2; +} + +// StatusRequest requests the status of a peer. +message StatusRequest { +} + +// StatusResponse is a peer response to inform their status. +message StatusResponse { + int64 height = 1; + int64 base = 2; +} + +message Message { + oneof sum { + BlockRequest block_request = 1; + NoBlockResponse no_block_response = 2; + BlockResponse block_response = 3; + StatusRequest status_request = 4; + StatusResponse status_response = 5; + } +} diff --git a/proto/tendermint/consensus/message.go b/proto/tendermint/consensus/message.go new file mode 100644 index 0000000..74b50ed --- /dev/null +++ b/proto/tendermint/consensus/message.go @@ -0,0 +1,110 @@ +package consensus + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/p2p" +) + +var _ p2p.Wrapper = &VoteSetBits{} +var _ p2p.Wrapper = &VoteSetMaj23{} +var _ p2p.Wrapper = &Vote{} +var _ p2p.Wrapper = &ProposalPOL{} +var _ p2p.Wrapper = &Proposal{} +var _ p2p.Wrapper = &NewValidBlock{} +var _ p2p.Wrapper = &NewRoundStep{} +var _ p2p.Wrapper = &HasVote{} +var _ p2p.Wrapper = &BlockPart{} + +func (m *VoteSetBits) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_VoteSetBits{VoteSetBits: m} + return cm + +} + +func (m *VoteSetMaj23) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_VoteSetMaj23{VoteSetMaj23: m} + return cm +} + +func (m *HasVote) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_HasVote{HasVote: m} + return cm +} + +func (m *Vote) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_Vote{Vote: m} + return cm +} + +func (m *BlockPart) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_BlockPart{BlockPart: m} + return cm +} + +func (m *ProposalPOL) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_ProposalPol{ProposalPol: m} + return cm +} + +func (m *Proposal) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_Proposal{Proposal: m} + return cm +} + +func (m *NewValidBlock) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_NewValidBlock{NewValidBlock: m} + return cm +} + +func (m *NewRoundStep) Wrap() proto.Message { + cm := &Message{} + cm.Sum = &Message_NewRoundStep{NewRoundStep: m} + return cm +} + +// Unwrap implements the p2p Wrapper interface and unwraps a wrapped consensus +// proto message. +func (m *Message) Unwrap() (proto.Message, error) { + switch msg := m.Sum.(type) { + case *Message_NewRoundStep: + return m.GetNewRoundStep(), nil + + case *Message_NewValidBlock: + return m.GetNewValidBlock(), nil + + case *Message_Proposal: + return m.GetProposal(), nil + + case *Message_ProposalPol: + return m.GetProposalPol(), nil + + case *Message_BlockPart: + return m.GetBlockPart(), nil + + case *Message_Vote: + return m.GetVote(), nil + + case *Message_HasVote: + return m.GetHasVote(), nil + + case *Message_VoteSetMaj23: + return m.GetVoteSetMaj23(), nil + + case *Message_VoteSetBits: + return m.GetVoteSetBits(), nil + + default: + return nil, fmt.Errorf("unknown message: %T", msg) + } +} diff --git a/proto/tendermint/consensus/types.pb.go b/proto/tendermint/consensus/types.pb.go new file mode 100644 index 0000000..cde1ec1 --- /dev/null +++ b/proto/tendermint/consensus/types.pb.go @@ -0,0 +1,3425 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/consensus/types.proto + +package consensus + +import ( + fmt "fmt" + bits "github.com/cometbft/cometbft/proto/tendermint/libs/bits" + types "github.com/cometbft/cometbft/proto/tendermint/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// NewRoundStep is sent for every step taken in the ConsensusState. +// For every height/round/step transition +type NewRoundStep struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Step uint32 `protobuf:"varint,3,opt,name=step,proto3" json:"step,omitempty"` + SecondsSinceStartTime int64 `protobuf:"varint,4,opt,name=seconds_since_start_time,json=secondsSinceStartTime,proto3" json:"seconds_since_start_time,omitempty"` + LastCommitRound int32 `protobuf:"varint,5,opt,name=last_commit_round,json=lastCommitRound,proto3" json:"last_commit_round,omitempty"` +} + +func (m *NewRoundStep) Reset() { *m = NewRoundStep{} } +func (m *NewRoundStep) String() string { return proto.CompactTextString(m) } +func (*NewRoundStep) ProtoMessage() {} +func (*NewRoundStep) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{0} +} +func (m *NewRoundStep) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *NewRoundStep) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_NewRoundStep.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *NewRoundStep) XXX_Merge(src proto.Message) { + xxx_messageInfo_NewRoundStep.Merge(m, src) +} +func (m *NewRoundStep) XXX_Size() int { + return m.Size() +} +func (m *NewRoundStep) XXX_DiscardUnknown() { + xxx_messageInfo_NewRoundStep.DiscardUnknown(m) +} + +var xxx_messageInfo_NewRoundStep proto.InternalMessageInfo + +func (m *NewRoundStep) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *NewRoundStep) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *NewRoundStep) GetStep() uint32 { + if m != nil { + return m.Step + } + return 0 +} + +func (m *NewRoundStep) GetSecondsSinceStartTime() int64 { + if m != nil { + return m.SecondsSinceStartTime + } + return 0 +} + +func (m *NewRoundStep) GetLastCommitRound() int32 { + if m != nil { + return m.LastCommitRound + } + return 0 +} + +// NewValidBlock is sent when a validator observes a valid block B in some round r, +// i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r. +// In case the block is also committed, then IsCommit flag is set to true. +type NewValidBlock struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + BlockPartSetHeader types.PartSetHeader `protobuf:"bytes,3,opt,name=block_part_set_header,json=blockPartSetHeader,proto3" json:"block_part_set_header"` + BlockParts *bits.BitArray `protobuf:"bytes,4,opt,name=block_parts,json=blockParts,proto3" json:"block_parts,omitempty"` + IsCommit bool `protobuf:"varint,5,opt,name=is_commit,json=isCommit,proto3" json:"is_commit,omitempty"` +} + +func (m *NewValidBlock) Reset() { *m = NewValidBlock{} } +func (m *NewValidBlock) String() string { return proto.CompactTextString(m) } +func (*NewValidBlock) ProtoMessage() {} +func (*NewValidBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{1} +} +func (m *NewValidBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *NewValidBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_NewValidBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *NewValidBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_NewValidBlock.Merge(m, src) +} +func (m *NewValidBlock) XXX_Size() int { + return m.Size() +} +func (m *NewValidBlock) XXX_DiscardUnknown() { + xxx_messageInfo_NewValidBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_NewValidBlock proto.InternalMessageInfo + +func (m *NewValidBlock) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *NewValidBlock) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *NewValidBlock) GetBlockPartSetHeader() types.PartSetHeader { + if m != nil { + return m.BlockPartSetHeader + } + return types.PartSetHeader{} +} + +func (m *NewValidBlock) GetBlockParts() *bits.BitArray { + if m != nil { + return m.BlockParts + } + return nil +} + +func (m *NewValidBlock) GetIsCommit() bool { + if m != nil { + return m.IsCommit + } + return false +} + +// Proposal is sent when a new block is proposed. +type Proposal struct { + Proposal types.Proposal `protobuf:"bytes,1,opt,name=proposal,proto3" json:"proposal"` +} + +func (m *Proposal) Reset() { *m = Proposal{} } +func (m *Proposal) String() string { return proto.CompactTextString(m) } +func (*Proposal) ProtoMessage() {} +func (*Proposal) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{2} +} +func (m *Proposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Proposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Proposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_Proposal.Merge(m, src) +} +func (m *Proposal) XXX_Size() int { + return m.Size() +} +func (m *Proposal) XXX_DiscardUnknown() { + xxx_messageInfo_Proposal.DiscardUnknown(m) +} + +var xxx_messageInfo_Proposal proto.InternalMessageInfo + +func (m *Proposal) GetProposal() types.Proposal { + if m != nil { + return m.Proposal + } + return types.Proposal{} +} + +// ProposalPOL is sent when a previous proposal is re-proposed. +type ProposalPOL struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + ProposalPolRound int32 `protobuf:"varint,2,opt,name=proposal_pol_round,json=proposalPolRound,proto3" json:"proposal_pol_round,omitempty"` + ProposalPol bits.BitArray `protobuf:"bytes,3,opt,name=proposal_pol,json=proposalPol,proto3" json:"proposal_pol"` +} + +func (m *ProposalPOL) Reset() { *m = ProposalPOL{} } +func (m *ProposalPOL) String() string { return proto.CompactTextString(m) } +func (*ProposalPOL) ProtoMessage() {} +func (*ProposalPOL) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{3} +} +func (m *ProposalPOL) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ProposalPOL) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ProposalPOL.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ProposalPOL) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProposalPOL.Merge(m, src) +} +func (m *ProposalPOL) XXX_Size() int { + return m.Size() +} +func (m *ProposalPOL) XXX_DiscardUnknown() { + xxx_messageInfo_ProposalPOL.DiscardUnknown(m) +} + +var xxx_messageInfo_ProposalPOL proto.InternalMessageInfo + +func (m *ProposalPOL) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ProposalPOL) GetProposalPolRound() int32 { + if m != nil { + return m.ProposalPolRound + } + return 0 +} + +func (m *ProposalPOL) GetProposalPol() bits.BitArray { + if m != nil { + return m.ProposalPol + } + return bits.BitArray{} +} + +// BlockPart is sent when gossipping a piece of the proposed block. +type BlockPart struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Part types.Part `protobuf:"bytes,3,opt,name=part,proto3" json:"part"` +} + +func (m *BlockPart) Reset() { *m = BlockPart{} } +func (m *BlockPart) String() string { return proto.CompactTextString(m) } +func (*BlockPart) ProtoMessage() {} +func (*BlockPart) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{4} +} +func (m *BlockPart) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockPart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockPart.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockPart) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockPart.Merge(m, src) +} +func (m *BlockPart) XXX_Size() int { + return m.Size() +} +func (m *BlockPart) XXX_DiscardUnknown() { + xxx_messageInfo_BlockPart.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockPart proto.InternalMessageInfo + +func (m *BlockPart) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *BlockPart) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *BlockPart) GetPart() types.Part { + if m != nil { + return m.Part + } + return types.Part{} +} + +// Vote is sent when voting for a proposal (or lack thereof). +type Vote struct { + Vote *types.Vote `protobuf:"bytes,1,opt,name=vote,proto3" json:"vote,omitempty"` +} + +func (m *Vote) Reset() { *m = Vote{} } +func (m *Vote) String() string { return proto.CompactTextString(m) } +func (*Vote) ProtoMessage() {} +func (*Vote) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{5} +} +func (m *Vote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Vote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Vote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Vote) XXX_Merge(src proto.Message) { + xxx_messageInfo_Vote.Merge(m, src) +} +func (m *Vote) XXX_Size() int { + return m.Size() +} +func (m *Vote) XXX_DiscardUnknown() { + xxx_messageInfo_Vote.DiscardUnknown(m) +} + +var xxx_messageInfo_Vote proto.InternalMessageInfo + +func (m *Vote) GetVote() *types.Vote { + if m != nil { + return m.Vote + } + return nil +} + +// HasVote is sent to indicate that a particular vote has been received. +type HasVote struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Type types.SignedMsgType `protobuf:"varint,3,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + Index int32 `protobuf:"varint,4,opt,name=index,proto3" json:"index,omitempty"` +} + +func (m *HasVote) Reset() { *m = HasVote{} } +func (m *HasVote) String() string { return proto.CompactTextString(m) } +func (*HasVote) ProtoMessage() {} +func (*HasVote) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{6} +} +func (m *HasVote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *HasVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_HasVote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *HasVote) XXX_Merge(src proto.Message) { + xxx_messageInfo_HasVote.Merge(m, src) +} +func (m *HasVote) XXX_Size() int { + return m.Size() +} +func (m *HasVote) XXX_DiscardUnknown() { + xxx_messageInfo_HasVote.DiscardUnknown(m) +} + +var xxx_messageInfo_HasVote proto.InternalMessageInfo + +func (m *HasVote) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *HasVote) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *HasVote) GetType() types.SignedMsgType { + if m != nil { + return m.Type + } + return types.UnknownType +} + +func (m *HasVote) GetIndex() int32 { + if m != nil { + return m.Index + } + return 0 +} + +// VoteSetMaj23 is sent to indicate that a given BlockID has seen +2/3 votes. +type VoteSetMaj23 struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Type types.SignedMsgType `protobuf:"varint,3,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + BlockID types.BlockID `protobuf:"bytes,4,opt,name=block_id,json=blockId,proto3" json:"block_id"` +} + +func (m *VoteSetMaj23) Reset() { *m = VoteSetMaj23{} } +func (m *VoteSetMaj23) String() string { return proto.CompactTextString(m) } +func (*VoteSetMaj23) ProtoMessage() {} +func (*VoteSetMaj23) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{7} +} +func (m *VoteSetMaj23) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *VoteSetMaj23) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_VoteSetMaj23.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *VoteSetMaj23) XXX_Merge(src proto.Message) { + xxx_messageInfo_VoteSetMaj23.Merge(m, src) +} +func (m *VoteSetMaj23) XXX_Size() int { + return m.Size() +} +func (m *VoteSetMaj23) XXX_DiscardUnknown() { + xxx_messageInfo_VoteSetMaj23.DiscardUnknown(m) +} + +var xxx_messageInfo_VoteSetMaj23 proto.InternalMessageInfo + +func (m *VoteSetMaj23) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *VoteSetMaj23) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *VoteSetMaj23) GetType() types.SignedMsgType { + if m != nil { + return m.Type + } + return types.UnknownType +} + +func (m *VoteSetMaj23) GetBlockID() types.BlockID { + if m != nil { + return m.BlockID + } + return types.BlockID{} +} + +// VoteSetBits is sent to communicate the bit-array of votes seen for the BlockID. +type VoteSetBits struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Type types.SignedMsgType `protobuf:"varint,3,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + BlockID types.BlockID `protobuf:"bytes,4,opt,name=block_id,json=blockId,proto3" json:"block_id"` + Votes bits.BitArray `protobuf:"bytes,5,opt,name=votes,proto3" json:"votes"` +} + +func (m *VoteSetBits) Reset() { *m = VoteSetBits{} } +func (m *VoteSetBits) String() string { return proto.CompactTextString(m) } +func (*VoteSetBits) ProtoMessage() {} +func (*VoteSetBits) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{8} +} +func (m *VoteSetBits) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *VoteSetBits) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_VoteSetBits.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *VoteSetBits) XXX_Merge(src proto.Message) { + xxx_messageInfo_VoteSetBits.Merge(m, src) +} +func (m *VoteSetBits) XXX_Size() int { + return m.Size() +} +func (m *VoteSetBits) XXX_DiscardUnknown() { + xxx_messageInfo_VoteSetBits.DiscardUnknown(m) +} + +var xxx_messageInfo_VoteSetBits proto.InternalMessageInfo + +func (m *VoteSetBits) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *VoteSetBits) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *VoteSetBits) GetType() types.SignedMsgType { + if m != nil { + return m.Type + } + return types.UnknownType +} + +func (m *VoteSetBits) GetBlockID() types.BlockID { + if m != nil { + return m.BlockID + } + return types.BlockID{} +} + +func (m *VoteSetBits) GetVotes() bits.BitArray { + if m != nil { + return m.Votes + } + return bits.BitArray{} +} + +type Message struct { + // Types that are valid to be assigned to Sum: + // *Message_NewRoundStep + // *Message_NewValidBlock + // *Message_Proposal + // *Message_ProposalPol + // *Message_BlockPart + // *Message_Vote + // *Message_HasVote + // *Message_VoteSetMaj23 + // *Message_VoteSetBits + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_81a22d2efc008981, []int{9} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_NewRoundStep struct { + NewRoundStep *NewRoundStep `protobuf:"bytes,1,opt,name=new_round_step,json=newRoundStep,proto3,oneof" json:"new_round_step,omitempty"` +} +type Message_NewValidBlock struct { + NewValidBlock *NewValidBlock `protobuf:"bytes,2,opt,name=new_valid_block,json=newValidBlock,proto3,oneof" json:"new_valid_block,omitempty"` +} +type Message_Proposal struct { + Proposal *Proposal `protobuf:"bytes,3,opt,name=proposal,proto3,oneof" json:"proposal,omitempty"` +} +type Message_ProposalPol struct { + ProposalPol *ProposalPOL `protobuf:"bytes,4,opt,name=proposal_pol,json=proposalPol,proto3,oneof" json:"proposal_pol,omitempty"` +} +type Message_BlockPart struct { + BlockPart *BlockPart `protobuf:"bytes,5,opt,name=block_part,json=blockPart,proto3,oneof" json:"block_part,omitempty"` +} +type Message_Vote struct { + Vote *Vote `protobuf:"bytes,6,opt,name=vote,proto3,oneof" json:"vote,omitempty"` +} +type Message_HasVote struct { + HasVote *HasVote `protobuf:"bytes,7,opt,name=has_vote,json=hasVote,proto3,oneof" json:"has_vote,omitempty"` +} +type Message_VoteSetMaj23 struct { + VoteSetMaj23 *VoteSetMaj23 `protobuf:"bytes,8,opt,name=vote_set_maj23,json=voteSetMaj23,proto3,oneof" json:"vote_set_maj23,omitempty"` +} +type Message_VoteSetBits struct { + VoteSetBits *VoteSetBits `protobuf:"bytes,9,opt,name=vote_set_bits,json=voteSetBits,proto3,oneof" json:"vote_set_bits,omitempty"` +} + +func (*Message_NewRoundStep) isMessage_Sum() {} +func (*Message_NewValidBlock) isMessage_Sum() {} +func (*Message_Proposal) isMessage_Sum() {} +func (*Message_ProposalPol) isMessage_Sum() {} +func (*Message_BlockPart) isMessage_Sum() {} +func (*Message_Vote) isMessage_Sum() {} +func (*Message_HasVote) isMessage_Sum() {} +func (*Message_VoteSetMaj23) isMessage_Sum() {} +func (*Message_VoteSetBits) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetNewRoundStep() *NewRoundStep { + if x, ok := m.GetSum().(*Message_NewRoundStep); ok { + return x.NewRoundStep + } + return nil +} + +func (m *Message) GetNewValidBlock() *NewValidBlock { + if x, ok := m.GetSum().(*Message_NewValidBlock); ok { + return x.NewValidBlock + } + return nil +} + +func (m *Message) GetProposal() *Proposal { + if x, ok := m.GetSum().(*Message_Proposal); ok { + return x.Proposal + } + return nil +} + +func (m *Message) GetProposalPol() *ProposalPOL { + if x, ok := m.GetSum().(*Message_ProposalPol); ok { + return x.ProposalPol + } + return nil +} + +func (m *Message) GetBlockPart() *BlockPart { + if x, ok := m.GetSum().(*Message_BlockPart); ok { + return x.BlockPart + } + return nil +} + +func (m *Message) GetVote() *Vote { + if x, ok := m.GetSum().(*Message_Vote); ok { + return x.Vote + } + return nil +} + +func (m *Message) GetHasVote() *HasVote { + if x, ok := m.GetSum().(*Message_HasVote); ok { + return x.HasVote + } + return nil +} + +func (m *Message) GetVoteSetMaj23() *VoteSetMaj23 { + if x, ok := m.GetSum().(*Message_VoteSetMaj23); ok { + return x.VoteSetMaj23 + } + return nil +} + +func (m *Message) GetVoteSetBits() *VoteSetBits { + if x, ok := m.GetSum().(*Message_VoteSetBits); ok { + return x.VoteSetBits + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_NewRoundStep)(nil), + (*Message_NewValidBlock)(nil), + (*Message_Proposal)(nil), + (*Message_ProposalPol)(nil), + (*Message_BlockPart)(nil), + (*Message_Vote)(nil), + (*Message_HasVote)(nil), + (*Message_VoteSetMaj23)(nil), + (*Message_VoteSetBits)(nil), + } +} + +func init() { + proto.RegisterType((*NewRoundStep)(nil), "tendermint.consensus.NewRoundStep") + proto.RegisterType((*NewValidBlock)(nil), "tendermint.consensus.NewValidBlock") + proto.RegisterType((*Proposal)(nil), "tendermint.consensus.Proposal") + proto.RegisterType((*ProposalPOL)(nil), "tendermint.consensus.ProposalPOL") + proto.RegisterType((*BlockPart)(nil), "tendermint.consensus.BlockPart") + proto.RegisterType((*Vote)(nil), "tendermint.consensus.Vote") + proto.RegisterType((*HasVote)(nil), "tendermint.consensus.HasVote") + proto.RegisterType((*VoteSetMaj23)(nil), "tendermint.consensus.VoteSetMaj23") + proto.RegisterType((*VoteSetBits)(nil), "tendermint.consensus.VoteSetBits") + proto.RegisterType((*Message)(nil), "tendermint.consensus.Message") +} + +func init() { proto.RegisterFile("tendermint/consensus/types.proto", fileDescriptor_81a22d2efc008981) } + +var fileDescriptor_81a22d2efc008981 = []byte{ + // 856 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x56, 0xcd, 0x8e, 0xe3, 0x44, + 0x10, 0xb6, 0x19, 0x67, 0x92, 0x94, 0x93, 0x19, 0x68, 0xcd, 0xae, 0x42, 0x80, 0x24, 0x98, 0xcb, + 0x08, 0x21, 0x07, 0x65, 0x0e, 0x2b, 0xad, 0x90, 0x00, 0xf3, 0xb3, 0xde, 0xd5, 0x66, 0x37, 0x38, + 0xab, 0x15, 0xe2, 0x62, 0x39, 0x71, 0x93, 0x34, 0x1b, 0xbb, 0x2d, 0x77, 0x27, 0xc3, 0x5c, 0x79, + 0x02, 0x1e, 0x80, 0xd7, 0x40, 0xe2, 0x11, 0xe6, 0x38, 0x47, 0x4e, 0x23, 0x94, 0x79, 0x04, 0x04, + 0x67, 0xd4, 0xed, 0x4e, 0xec, 0x30, 0x9e, 0x81, 0xb9, 0x20, 0x71, 0xeb, 0x4e, 0x55, 0x7d, 0x5d, + 0xf5, 0x55, 0xd5, 0x17, 0x43, 0x8f, 0xe3, 0x38, 0xc4, 0x69, 0x44, 0x62, 0xde, 0x9f, 0xd2, 0x98, + 0xe1, 0x98, 0x2d, 0x59, 0x9f, 0x9f, 0x25, 0x98, 0xd9, 0x49, 0x4a, 0x39, 0x45, 0x47, 0xb9, 0x87, + 0xbd, 0xf5, 0x68, 0x1f, 0xcd, 0xe8, 0x8c, 0x4a, 0x87, 0xbe, 0x38, 0x65, 0xbe, 0xed, 0xb7, 0x0b, + 0x68, 0x12, 0xa3, 0x88, 0xd4, 0x2e, 0xbe, 0xb5, 0x20, 0x13, 0xd6, 0x9f, 0x10, 0xbe, 0xe3, 0x61, + 0xfd, 0xac, 0x43, 0xe3, 0x19, 0x3e, 0xf5, 0xe8, 0x32, 0x0e, 0xc7, 0x1c, 0x27, 0xe8, 0x3e, 0xec, + 0xcf, 0x31, 0x99, 0xcd, 0x79, 0x4b, 0xef, 0xe9, 0xc7, 0x7b, 0x9e, 0xba, 0xa1, 0x23, 0xa8, 0xa4, + 0xc2, 0xa9, 0xf5, 0x5a, 0x4f, 0x3f, 0xae, 0x78, 0xd9, 0x05, 0x21, 0x30, 0x18, 0xc7, 0x49, 0x6b, + 0xaf, 0xa7, 0x1f, 0x37, 0x3d, 0x79, 0x46, 0x0f, 0xa0, 0xc5, 0xf0, 0x94, 0xc6, 0x21, 0xf3, 0x19, + 0x89, 0xa7, 0xd8, 0x67, 0x3c, 0x48, 0xb9, 0xcf, 0x49, 0x84, 0x5b, 0x86, 0xc4, 0xbc, 0xa7, 0xec, + 0x63, 0x61, 0x1e, 0x0b, 0xeb, 0x0b, 0x12, 0x61, 0xf4, 0x3e, 0xbc, 0xb1, 0x08, 0x18, 0xf7, 0xa7, + 0x34, 0x8a, 0x08, 0xf7, 0xb3, 0xe7, 0x2a, 0xf2, 0xb9, 0x43, 0x61, 0xf8, 0x4c, 0xfe, 0x2e, 0x53, + 0xb5, 0xfe, 0xd0, 0xa1, 0xf9, 0x0c, 0x9f, 0xbe, 0x0c, 0x16, 0x24, 0x74, 0x16, 0x74, 0xfa, 0xea, + 0x8e, 0x89, 0x7f, 0x0d, 0xf7, 0x26, 0x22, 0xcc, 0x4f, 0x44, 0x6e, 0x0c, 0x73, 0x7f, 0x8e, 0x83, + 0x10, 0xa7, 0xb2, 0x12, 0x73, 0xd0, 0xb5, 0x0b, 0x3d, 0xc8, 0xf8, 0x1a, 0x05, 0x29, 0x1f, 0x63, + 0xee, 0x4a, 0x37, 0xc7, 0x38, 0xbf, 0xec, 0x6a, 0x1e, 0x92, 0x18, 0x3b, 0x16, 0xf4, 0x31, 0x98, + 0x39, 0x32, 0x93, 0x15, 0x9b, 0x83, 0x4e, 0x11, 0x4f, 0x74, 0xc2, 0x16, 0x9d, 0xb0, 0x1d, 0xc2, + 0x3f, 0x4d, 0xd3, 0xe0, 0xcc, 0x83, 0x2d, 0x10, 0x43, 0x6f, 0x41, 0x9d, 0x30, 0x45, 0x82, 0x2c, + 0xbf, 0xe6, 0xd5, 0x08, 0xcb, 0x8a, 0xb7, 0x5c, 0xa8, 0x8d, 0x52, 0x9a, 0x50, 0x16, 0x2c, 0xd0, + 0x47, 0x50, 0x4b, 0xd4, 0x59, 0xd6, 0x6c, 0x0e, 0xda, 0x25, 0x69, 0x2b, 0x0f, 0x95, 0xf1, 0x36, + 0xc2, 0xfa, 0x49, 0x07, 0x73, 0x63, 0x1c, 0x3d, 0x7f, 0x7a, 0x23, 0x7f, 0x1f, 0x00, 0xda, 0xc4, + 0xf8, 0x09, 0x5d, 0xf8, 0x45, 0x32, 0x5f, 0xdf, 0x58, 0x46, 0x74, 0x21, 0xfb, 0x82, 0x1e, 0x41, + 0xa3, 0xe8, 0xad, 0xe8, 0xfc, 0x87, 0xf2, 0x55, 0x6e, 0x66, 0x01, 0xcd, 0x7a, 0x05, 0x75, 0x67, + 0xc3, 0xc9, 0x1d, 0x7b, 0xfb, 0x21, 0x18, 0x82, 0x7b, 0xf5, 0xf6, 0xfd, 0xf2, 0x56, 0xaa, 0x37, + 0xa5, 0xa7, 0x35, 0x00, 0xe3, 0x25, 0xe5, 0x62, 0x02, 0x8d, 0x15, 0xe5, 0x58, 0xb1, 0x59, 0x12, + 0x29, 0xbc, 0x3c, 0xe9, 0x63, 0xfd, 0xa0, 0x43, 0xd5, 0x0d, 0x98, 0x8c, 0xbb, 0x5b, 0x7e, 0x27, + 0x60, 0x08, 0x34, 0x99, 0xdf, 0x41, 0xd9, 0xa8, 0x8d, 0xc9, 0x2c, 0xc6, 0xe1, 0x90, 0xcd, 0x5e, + 0x9c, 0x25, 0xd8, 0x93, 0xce, 0x02, 0x8a, 0xc4, 0x21, 0xfe, 0x5e, 0x0e, 0x54, 0xc5, 0xcb, 0x2e, + 0xd6, 0x2f, 0x3a, 0x34, 0x44, 0x06, 0x63, 0xcc, 0x87, 0xc1, 0x77, 0x83, 0x93, 0xff, 0x22, 0x93, + 0x2f, 0xa0, 0x96, 0x0d, 0x38, 0x09, 0xd5, 0x74, 0xbf, 0x79, 0x3d, 0x50, 0xf6, 0xee, 0xf1, 0xe7, + 0xce, 0xa1, 0x60, 0x79, 0x7d, 0xd9, 0xad, 0xaa, 0x1f, 0xbc, 0xaa, 0x8c, 0x7d, 0x1c, 0x5a, 0xbf, + 0xeb, 0x60, 0xaa, 0xd4, 0x1d, 0xc2, 0xd9, 0xff, 0x27, 0x73, 0xf4, 0x10, 0x2a, 0x62, 0x02, 0x98, + 0x5c, 0xce, 0x7f, 0x3b, 0xdc, 0x59, 0x88, 0xf5, 0xa7, 0x01, 0xd5, 0x21, 0x66, 0x2c, 0x98, 0x61, + 0xf4, 0x04, 0x0e, 0x62, 0x7c, 0x9a, 0x2d, 0x94, 0x2f, 0x65, 0x34, 0x9b, 0x3b, 0xcb, 0x2e, 0xfb, + 0x03, 0xb0, 0x8b, 0x32, 0xed, 0x6a, 0x5e, 0x23, 0x2e, 0xca, 0xf6, 0x10, 0x0e, 0x05, 0xd6, 0x4a, + 0xe8, 0xa1, 0x2f, 0x13, 0x95, 0x7c, 0x99, 0x83, 0xf7, 0x6e, 0x04, 0xcb, 0xb5, 0xd3, 0xd5, 0xbc, + 0x66, 0xbc, 0x23, 0xa6, 0x45, 0x69, 0x29, 0x59, 0xe1, 0x1c, 0x67, 0xa3, 0x20, 0x6e, 0x41, 0x5a, + 0xd0, 0x97, 0x7f, 0x13, 0x81, 0x8c, 0xeb, 0x77, 0x6f, 0x47, 0x18, 0x3d, 0x7f, 0xea, 0xee, 0x6a, + 0x00, 0xfa, 0x04, 0x20, 0x97, 0x52, 0xc5, 0x76, 0xb7, 0x1c, 0x65, 0xab, 0x15, 0xae, 0xe6, 0xd5, + 0xb7, 0x62, 0x2a, 0xa4, 0x40, 0x2e, 0xf4, 0xfe, 0x75, 0x79, 0xcc, 0x63, 0xc5, 0x14, 0xba, 0x5a, + 0xb6, 0xd6, 0xe8, 0x21, 0xd4, 0xe6, 0x01, 0xf3, 0x65, 0x54, 0x55, 0x46, 0xbd, 0x53, 0x1e, 0xa5, + 0x76, 0xdf, 0xd5, 0xbc, 0xea, 0x5c, 0xc9, 0xc0, 0x13, 0x38, 0x10, 0x71, 0xf2, 0xef, 0x24, 0x12, + 0xeb, 0xd8, 0xaa, 0xdd, 0xd6, 0xd0, 0xe2, 0xe2, 0x8a, 0x86, 0xae, 0x8a, 0x8b, 0xfc, 0x08, 0x9a, + 0x5b, 0x2c, 0x31, 0x4f, 0xad, 0xfa, 0x6d, 0x24, 0x16, 0x16, 0x49, 0x90, 0xb8, 0xca, 0xaf, 0x4e, + 0x05, 0xf6, 0xd8, 0x32, 0x72, 0xbe, 0x3a, 0x5f, 0x77, 0xf4, 0x8b, 0x75, 0x47, 0xff, 0x6d, 0xdd, + 0xd1, 0x7f, 0xbc, 0xea, 0x68, 0x17, 0x57, 0x1d, 0xed, 0xd7, 0xab, 0x8e, 0xf6, 0xcd, 0x83, 0x19, + 0xe1, 0xf3, 0xe5, 0xc4, 0x9e, 0xd2, 0xa8, 0x3f, 0xa5, 0x11, 0xe6, 0x93, 0x6f, 0x79, 0x7e, 0xc8, + 0xbe, 0x38, 0xca, 0xbe, 0x59, 0x26, 0xfb, 0xd2, 0x76, 0xf2, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, + 0xfe, 0x06, 0x66, 0x65, 0xd2, 0x08, 0x00, 0x00, +} + +func (m *NewRoundStep) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NewRoundStep) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NewRoundStep) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.LastCommitRound != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastCommitRound)) + i-- + dAtA[i] = 0x28 + } + if m.SecondsSinceStartTime != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.SecondsSinceStartTime)) + i-- + dAtA[i] = 0x20 + } + if m.Step != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Step)) + i-- + dAtA[i] = 0x18 + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *NewValidBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NewValidBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NewValidBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.IsCommit { + i-- + if m.IsCommit { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + if m.BlockParts != nil { + { + size, err := m.BlockParts.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + { + size, err := m.BlockPartSetHeader.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Proposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Proposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Proposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ProposalPOL) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ProposalPOL) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ProposalPOL) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.ProposalPol.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.ProposalPolRound != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.ProposalPolRound)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *BlockPart) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockPart) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockPart) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Part.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Vote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Vote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Vote != nil { + { + size, err := m.Vote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *HasVote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *HasVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *HasVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x20 + } + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x18 + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *VoteSetMaj23) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VoteSetMaj23) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VoteSetMaj23) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x18 + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *VoteSetBits) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VoteSetBits) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VoteSetBits) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Votes.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x18 + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_NewRoundStep) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_NewRoundStep) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.NewRoundStep != nil { + { + size, err := m.NewRoundStep.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Message_NewValidBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_NewValidBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.NewValidBlock != nil { + { + size, err := m.NewValidBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Message_Proposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Proposal != nil { + { + size, err := m.Proposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Message_ProposalPol) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_ProposalPol) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ProposalPol != nil { + { + size, err := m.ProposalPol.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *Message_BlockPart) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_BlockPart) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.BlockPart != nil { + { + size, err := m.BlockPart.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + return len(dAtA) - i, nil +} +func (m *Message_Vote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Vote != nil { + { + size, err := m.Vote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + return len(dAtA) - i, nil +} +func (m *Message_HasVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_HasVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.HasVote != nil { + { + size, err := m.HasVote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + return len(dAtA) - i, nil +} +func (m *Message_VoteSetMaj23) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_VoteSetMaj23) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.VoteSetMaj23 != nil { + { + size, err := m.VoteSetMaj23.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + return len(dAtA) - i, nil +} +func (m *Message_VoteSetBits) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_VoteSetBits) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.VoteSetBits != nil { + { + size, err := m.VoteSetBits.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + return len(dAtA) - i, nil +} +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *NewRoundStep) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if m.Step != 0 { + n += 1 + sovTypes(uint64(m.Step)) + } + if m.SecondsSinceStartTime != 0 { + n += 1 + sovTypes(uint64(m.SecondsSinceStartTime)) + } + if m.LastCommitRound != 0 { + n += 1 + sovTypes(uint64(m.LastCommitRound)) + } + return n +} + +func (m *NewValidBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + l = m.BlockPartSetHeader.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.BlockParts != nil { + l = m.BlockParts.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.IsCommit { + n += 2 + } + return n +} + +func (m *Proposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Proposal.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *ProposalPOL) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.ProposalPolRound != 0 { + n += 1 + sovTypes(uint64(m.ProposalPolRound)) + } + l = m.ProposalPol.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *BlockPart) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + l = m.Part.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *Vote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Vote != nil { + l = m.Vote.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *HasVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + return n +} + +func (m *VoteSetMaj23) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *VoteSetBits) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.Votes.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_NewRoundStep) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.NewRoundStep != nil { + l = m.NewRoundStep.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_NewValidBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.NewValidBlock != nil { + l = m.NewValidBlock.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_Proposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Proposal != nil { + l = m.Proposal.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_ProposalPol) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ProposalPol != nil { + l = m.ProposalPol.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_BlockPart) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockPart != nil { + l = m.BlockPart.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_Vote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Vote != nil { + l = m.Vote.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_HasVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.HasVote != nil { + l = m.HasVote.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_VoteSetMaj23) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VoteSetMaj23 != nil { + l = m.VoteSetMaj23.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_VoteSetBits) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VoteSetBits != nil { + l = m.VoteSetBits.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *NewRoundStep) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NewRoundStep: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NewRoundStep: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Step", wireType) + } + m.Step = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Step |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SecondsSinceStartTime", wireType) + } + m.SecondsSinceStartTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SecondsSinceStartTime |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastCommitRound", wireType) + } + m.LastCommitRound = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastCommitRound |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NewValidBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NewValidBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NewValidBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockPartSetHeader", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockPartSetHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockParts", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BlockParts == nil { + m.BlockParts = &bits.BitArray{} + } + if err := m.BlockParts.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IsCommit", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.IsCommit = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Proposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Proposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Proposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Proposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ProposalPOL) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ProposalPOL: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ProposalPOL: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposalPolRound", wireType) + } + m.ProposalPolRound = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ProposalPolRound |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposalPol", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ProposalPol.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockPart) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockPart: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockPart: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Part", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Part.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Vote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Vote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Vote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Vote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Vote == nil { + m.Vote = &types.Vote{} + } + if err := m.Vote.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *HasVote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: HasVote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: HasVote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= types.SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VoteSetMaj23) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VoteSetMaj23: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VoteSetMaj23: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= types.SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VoteSetBits) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VoteSetBits: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VoteSetBits: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= types.SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Votes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Votes.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NewRoundStep", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &NewRoundStep{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_NewRoundStep{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NewValidBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &NewValidBlock{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_NewValidBlock{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &Proposal{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_Proposal{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposalPol", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ProposalPOL{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_ProposalPol{v} + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockPart", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &BlockPart{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_BlockPart{v} + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Vote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &Vote{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_Vote{v} + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field HasVote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &HasVote{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_HasVote{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteSetMaj23", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &VoteSetMaj23{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_VoteSetMaj23{v} + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteSetBits", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &VoteSetBits{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_VoteSetBits{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/consensus/types.proto b/proto/tendermint/consensus/types.proto new file mode 100644 index 0000000..0cd5e78 --- /dev/null +++ b/proto/tendermint/consensus/types.proto @@ -0,0 +1,92 @@ +syntax = "proto3"; +package tendermint.consensus; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/consensus"; + +import "gogoproto/gogo.proto"; +import "tendermint/types/types.proto"; +import "tendermint/libs/bits/types.proto"; + +// NewRoundStep is sent for every step taken in the ConsensusState. +// For every height/round/step transition +message NewRoundStep { + int64 height = 1; + int32 round = 2; + uint32 step = 3; + int64 seconds_since_start_time = 4; + int32 last_commit_round = 5; +} + +// NewValidBlock is sent when a validator observes a valid block B in some round r, +// i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r. +// In case the block is also committed, then IsCommit flag is set to true. +message NewValidBlock { + int64 height = 1; + int32 round = 2; + tendermint.types.PartSetHeader block_part_set_header = 3 [(gogoproto.nullable) = false]; + tendermint.libs.bits.BitArray block_parts = 4; + bool is_commit = 5; +} + +// Proposal is sent when a new block is proposed. +message Proposal { + tendermint.types.Proposal proposal = 1 [(gogoproto.nullable) = false]; +} + +// ProposalPOL is sent when a previous proposal is re-proposed. +message ProposalPOL { + int64 height = 1; + int32 proposal_pol_round = 2; + tendermint.libs.bits.BitArray proposal_pol = 3 [(gogoproto.nullable) = false]; +} + +// BlockPart is sent when gossipping a piece of the proposed block. +message BlockPart { + int64 height = 1; + int32 round = 2; + tendermint.types.Part part = 3 [(gogoproto.nullable) = false]; +} + +// Vote is sent when voting for a proposal (or lack thereof). +message Vote { + tendermint.types.Vote vote = 1; +} + +// HasVote is sent to indicate that a particular vote has been received. +message HasVote { + int64 height = 1; + int32 round = 2; + tendermint.types.SignedMsgType type = 3; + int32 index = 4; +} + +// VoteSetMaj23 is sent to indicate that a given BlockID has seen +2/3 votes. +message VoteSetMaj23 { + int64 height = 1; + int32 round = 2; + tendermint.types.SignedMsgType type = 3; + tendermint.types.BlockID block_id = 4 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; +} + +// VoteSetBits is sent to communicate the bit-array of votes seen for the BlockID. +message VoteSetBits { + int64 height = 1; + int32 round = 2; + tendermint.types.SignedMsgType type = 3; + tendermint.types.BlockID block_id = 4 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; + tendermint.libs.bits.BitArray votes = 5 [(gogoproto.nullable) = false]; +} + +message Message { + oneof sum { + NewRoundStep new_round_step = 1; + NewValidBlock new_valid_block = 2; + Proposal proposal = 3; + ProposalPOL proposal_pol = 4; + BlockPart block_part = 5; + Vote vote = 6; + HasVote has_vote = 7; + VoteSetMaj23 vote_set_maj23 = 8; + VoteSetBits vote_set_bits = 9; + } +} diff --git a/proto/tendermint/consensus/wal.pb.go b/proto/tendermint/consensus/wal.pb.go new file mode 100644 index 0000000..d51552b --- /dev/null +++ b/proto/tendermint/consensus/wal.pb.go @@ -0,0 +1,1540 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/consensus/wal.proto + +package consensus + +import ( + fmt "fmt" + types "github.com/cometbft/cometbft/proto/tendermint/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + _ "github.com/golang/protobuf/ptypes/duration" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// MsgInfo are msgs from the reactor which may update the state +type MsgInfo struct { + Msg Message `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg"` + PeerID string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` +} + +func (m *MsgInfo) Reset() { *m = MsgInfo{} } +func (m *MsgInfo) String() string { return proto.CompactTextString(m) } +func (*MsgInfo) ProtoMessage() {} +func (*MsgInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_ed0b60c2d348ab09, []int{0} +} +func (m *MsgInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgInfo.Merge(m, src) +} +func (m *MsgInfo) XXX_Size() int { + return m.Size() +} +func (m *MsgInfo) XXX_DiscardUnknown() { + xxx_messageInfo_MsgInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgInfo proto.InternalMessageInfo + +func (m *MsgInfo) GetMsg() Message { + if m != nil { + return m.Msg + } + return Message{} +} + +func (m *MsgInfo) GetPeerID() string { + if m != nil { + return m.PeerID + } + return "" +} + +// TimeoutInfo internally generated messages which may update the state +type TimeoutInfo struct { + Duration time.Duration `protobuf:"bytes,1,opt,name=duration,proto3,stdduration" json:"duration"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,3,opt,name=round,proto3" json:"round,omitempty"` + Step uint32 `protobuf:"varint,4,opt,name=step,proto3" json:"step,omitempty"` +} + +func (m *TimeoutInfo) Reset() { *m = TimeoutInfo{} } +func (m *TimeoutInfo) String() string { return proto.CompactTextString(m) } +func (*TimeoutInfo) ProtoMessage() {} +func (*TimeoutInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_ed0b60c2d348ab09, []int{1} +} +func (m *TimeoutInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TimeoutInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TimeoutInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *TimeoutInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_TimeoutInfo.Merge(m, src) +} +func (m *TimeoutInfo) XXX_Size() int { + return m.Size() +} +func (m *TimeoutInfo) XXX_DiscardUnknown() { + xxx_messageInfo_TimeoutInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_TimeoutInfo proto.InternalMessageInfo + +func (m *TimeoutInfo) GetDuration() time.Duration { + if m != nil { + return m.Duration + } + return 0 +} + +func (m *TimeoutInfo) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *TimeoutInfo) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *TimeoutInfo) GetStep() uint32 { + if m != nil { + return m.Step + } + return 0 +} + +// EndHeight marks the end of the given height inside WAL. +// @internal used by scripts/wal2json util. +type EndHeight struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` +} + +func (m *EndHeight) Reset() { *m = EndHeight{} } +func (m *EndHeight) String() string { return proto.CompactTextString(m) } +func (*EndHeight) ProtoMessage() {} +func (*EndHeight) Descriptor() ([]byte, []int) { + return fileDescriptor_ed0b60c2d348ab09, []int{2} +} +func (m *EndHeight) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EndHeight) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EndHeight.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *EndHeight) XXX_Merge(src proto.Message) { + xxx_messageInfo_EndHeight.Merge(m, src) +} +func (m *EndHeight) XXX_Size() int { + return m.Size() +} +func (m *EndHeight) XXX_DiscardUnknown() { + xxx_messageInfo_EndHeight.DiscardUnknown(m) +} + +var xxx_messageInfo_EndHeight proto.InternalMessageInfo + +func (m *EndHeight) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +type WALMessage struct { + // Types that are valid to be assigned to Sum: + // *WALMessage_EventDataRoundState + // *WALMessage_MsgInfo + // *WALMessage_TimeoutInfo + // *WALMessage_EndHeight + Sum isWALMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *WALMessage) Reset() { *m = WALMessage{} } +func (m *WALMessage) String() string { return proto.CompactTextString(m) } +func (*WALMessage) ProtoMessage() {} +func (*WALMessage) Descriptor() ([]byte, []int) { + return fileDescriptor_ed0b60c2d348ab09, []int{3} +} +func (m *WALMessage) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *WALMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_WALMessage.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *WALMessage) XXX_Merge(src proto.Message) { + xxx_messageInfo_WALMessage.Merge(m, src) +} +func (m *WALMessage) XXX_Size() int { + return m.Size() +} +func (m *WALMessage) XXX_DiscardUnknown() { + xxx_messageInfo_WALMessage.DiscardUnknown(m) +} + +var xxx_messageInfo_WALMessage proto.InternalMessageInfo + +type isWALMessage_Sum interface { + isWALMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type WALMessage_EventDataRoundState struct { + EventDataRoundState *types.EventDataRoundState `protobuf:"bytes,1,opt,name=event_data_round_state,json=eventDataRoundState,proto3,oneof" json:"event_data_round_state,omitempty"` +} +type WALMessage_MsgInfo struct { + MsgInfo *MsgInfo `protobuf:"bytes,2,opt,name=msg_info,json=msgInfo,proto3,oneof" json:"msg_info,omitempty"` +} +type WALMessage_TimeoutInfo struct { + TimeoutInfo *TimeoutInfo `protobuf:"bytes,3,opt,name=timeout_info,json=timeoutInfo,proto3,oneof" json:"timeout_info,omitempty"` +} +type WALMessage_EndHeight struct { + EndHeight *EndHeight `protobuf:"bytes,4,opt,name=end_height,json=endHeight,proto3,oneof" json:"end_height,omitempty"` +} + +func (*WALMessage_EventDataRoundState) isWALMessage_Sum() {} +func (*WALMessage_MsgInfo) isWALMessage_Sum() {} +func (*WALMessage_TimeoutInfo) isWALMessage_Sum() {} +func (*WALMessage_EndHeight) isWALMessage_Sum() {} + +func (m *WALMessage) GetSum() isWALMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *WALMessage) GetEventDataRoundState() *types.EventDataRoundState { + if x, ok := m.GetSum().(*WALMessage_EventDataRoundState); ok { + return x.EventDataRoundState + } + return nil +} + +func (m *WALMessage) GetMsgInfo() *MsgInfo { + if x, ok := m.GetSum().(*WALMessage_MsgInfo); ok { + return x.MsgInfo + } + return nil +} + +func (m *WALMessage) GetTimeoutInfo() *TimeoutInfo { + if x, ok := m.GetSum().(*WALMessage_TimeoutInfo); ok { + return x.TimeoutInfo + } + return nil +} + +func (m *WALMessage) GetEndHeight() *EndHeight { + if x, ok := m.GetSum().(*WALMessage_EndHeight); ok { + return x.EndHeight + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*WALMessage) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*WALMessage_EventDataRoundState)(nil), + (*WALMessage_MsgInfo)(nil), + (*WALMessage_TimeoutInfo)(nil), + (*WALMessage_EndHeight)(nil), + } +} + +// TimedWALMessage wraps WALMessage and adds Time for debugging purposes. +type TimedWALMessage struct { + Time time.Time `protobuf:"bytes,1,opt,name=time,proto3,stdtime" json:"time"` + Msg *WALMessage `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (m *TimedWALMessage) Reset() { *m = TimedWALMessage{} } +func (m *TimedWALMessage) String() string { return proto.CompactTextString(m) } +func (*TimedWALMessage) ProtoMessage() {} +func (*TimedWALMessage) Descriptor() ([]byte, []int) { + return fileDescriptor_ed0b60c2d348ab09, []int{4} +} +func (m *TimedWALMessage) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TimedWALMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TimedWALMessage.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *TimedWALMessage) XXX_Merge(src proto.Message) { + xxx_messageInfo_TimedWALMessage.Merge(m, src) +} +func (m *TimedWALMessage) XXX_Size() int { + return m.Size() +} +func (m *TimedWALMessage) XXX_DiscardUnknown() { + xxx_messageInfo_TimedWALMessage.DiscardUnknown(m) +} + +var xxx_messageInfo_TimedWALMessage proto.InternalMessageInfo + +func (m *TimedWALMessage) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *TimedWALMessage) GetMsg() *WALMessage { + if m != nil { + return m.Msg + } + return nil +} + +func init() { + proto.RegisterType((*MsgInfo)(nil), "tendermint.consensus.MsgInfo") + proto.RegisterType((*TimeoutInfo)(nil), "tendermint.consensus.TimeoutInfo") + proto.RegisterType((*EndHeight)(nil), "tendermint.consensus.EndHeight") + proto.RegisterType((*WALMessage)(nil), "tendermint.consensus.WALMessage") + proto.RegisterType((*TimedWALMessage)(nil), "tendermint.consensus.TimedWALMessage") +} + +func init() { proto.RegisterFile("tendermint/consensus/wal.proto", fileDescriptor_ed0b60c2d348ab09) } + +var fileDescriptor_ed0b60c2d348ab09 = []byte{ + // 543 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x53, 0xdf, 0x8a, 0xd3, 0x4e, + 0x14, 0xce, 0x6c, 0xff, 0x9f, 0xfe, 0x7e, 0x08, 0xb1, 0x2c, 0xb5, 0xb0, 0x69, 0xec, 0x22, 0xf4, + 0x2a, 0x81, 0x15, 0x51, 0xbc, 0x51, 0x4b, 0x57, 0x5a, 0x70, 0x41, 0xc7, 0x05, 0x41, 0x84, 0x90, + 0x36, 0xa7, 0x69, 0x60, 0x33, 0x53, 0x32, 0x13, 0xc5, 0x2b, 0x5f, 0xa1, 0x97, 0xbe, 0x89, 0xaf, + 0xb0, 0x97, 0x7b, 0xe9, 0xd5, 0x2a, 0xed, 0x8b, 0x48, 0x66, 0xd2, 0x36, 0xb8, 0xf1, 0x6e, 0xce, + 0x9c, 0xef, 0x9c, 0xef, 0x9c, 0xef, 0x9b, 0x01, 0x4b, 0x22, 0x0b, 0x30, 0x89, 0x23, 0x26, 0xdd, + 0x39, 0x67, 0x02, 0x99, 0x48, 0x85, 0xfb, 0xc5, 0xbf, 0x72, 0x56, 0x09, 0x97, 0xdc, 0xec, 0x1c, + 0xf2, 0xce, 0x3e, 0xdf, 0xeb, 0x84, 0x3c, 0xe4, 0x0a, 0xe0, 0x66, 0x27, 0x8d, 0xed, 0xd9, 0xa5, + 0xbd, 0xe4, 0xd7, 0x15, 0x8a, 0x1c, 0x71, 0x52, 0x40, 0xa8, 0x7b, 0x17, 0x3f, 0x23, 0x93, 0xbb, + 0xb4, 0x15, 0x72, 0x1e, 0x5e, 0xa1, 0xab, 0xa2, 0x59, 0xba, 0x70, 0x83, 0x34, 0xf1, 0x65, 0xc4, + 0x59, 0x9e, 0xef, 0xff, 0x9d, 0x97, 0x51, 0x8c, 0x42, 0xfa, 0xf1, 0x4a, 0x03, 0x06, 0x08, 0x8d, + 0x0b, 0x11, 0x4e, 0xd9, 0x82, 0x9b, 0x4f, 0xa0, 0x12, 0x8b, 0xb0, 0x4b, 0x6c, 0x32, 0x6c, 0x9f, + 0x9d, 0x38, 0x65, 0x6b, 0x38, 0x17, 0x28, 0x84, 0x1f, 0xe2, 0xa8, 0x7a, 0x7d, 0xdb, 0x37, 0x68, + 0x86, 0x37, 0x4f, 0xa1, 0xb1, 0x42, 0x4c, 0xbc, 0x28, 0xe8, 0x1e, 0xd9, 0x64, 0xd8, 0x1a, 0xc1, + 0xe6, 0xb6, 0x5f, 0x7f, 0x8b, 0x98, 0x4c, 0xc7, 0xb4, 0x9e, 0xa5, 0xa6, 0xc1, 0x60, 0x4d, 0xa0, + 0x7d, 0x19, 0xc5, 0xc8, 0x53, 0xa9, 0xb8, 0x5e, 0x40, 0x73, 0x37, 0x69, 0x4e, 0xf8, 0xc0, 0xd1, + 0xa3, 0x3a, 0xbb, 0x51, 0x9d, 0x71, 0x0e, 0x18, 0x35, 0x33, 0xb2, 0xef, 0xbf, 0xfa, 0x84, 0xee, + 0x8b, 0xcc, 0x63, 0xa8, 0x2f, 0x31, 0x0a, 0x97, 0x52, 0x91, 0x56, 0x68, 0x1e, 0x99, 0x1d, 0xa8, + 0x25, 0x3c, 0x65, 0x41, 0xb7, 0x62, 0x93, 0x61, 0x8d, 0xea, 0xc0, 0x34, 0xa1, 0x2a, 0x24, 0xae, + 0xba, 0x55, 0x9b, 0x0c, 0xff, 0xa7, 0xea, 0x3c, 0x38, 0x85, 0xd6, 0x39, 0x0b, 0x26, 0xba, 0xec, + 0xd0, 0x8e, 0x14, 0xdb, 0x0d, 0x7e, 0x1c, 0x01, 0x7c, 0x78, 0xf5, 0x26, 0x5f, 0xdb, 0xfc, 0x04, + 0xc7, 0x4a, 0x7e, 0x2f, 0xf0, 0xa5, 0xef, 0xa9, 0xde, 0x9e, 0x90, 0xbe, 0xc4, 0x7c, 0x89, 0x47, + 0x45, 0xd5, 0xb4, 0x8d, 0xe7, 0x19, 0x7e, 0xec, 0x4b, 0x9f, 0x66, 0xe8, 0xf7, 0x19, 0x78, 0x62, + 0xd0, 0xfb, 0x78, 0xf7, 0xda, 0x7c, 0x0e, 0xcd, 0x58, 0x84, 0x5e, 0xc4, 0x16, 0x5c, 0x6d, 0xf5, + 0x6f, 0x17, 0xb4, 0x63, 0x13, 0x83, 0x36, 0xe2, 0xdc, 0xbc, 0xd7, 0xf0, 0x9f, 0xd4, 0xfa, 0xea, + 0xfa, 0x8a, 0xaa, 0x7f, 0x58, 0x5e, 0x5f, 0x70, 0x62, 0x62, 0xd0, 0xb6, 0x2c, 0x18, 0xf3, 0x12, + 0x00, 0x59, 0xe0, 0xe5, 0x62, 0x54, 0x55, 0x97, 0x7e, 0x79, 0x97, 0xbd, 0x7a, 0x13, 0x83, 0xb6, + 0x70, 0x17, 0x8c, 0x6a, 0x50, 0x11, 0x69, 0x3c, 0xf8, 0x06, 0xf7, 0x32, 0x9a, 0xa0, 0xa0, 0xde, + 0x33, 0xa8, 0x66, 0x54, 0xb9, 0x56, 0xbd, 0x3b, 0x86, 0x5f, 0xee, 0xde, 0xa6, 0x76, 0x7c, 0x9d, + 0x39, 0xae, 0x2a, 0xcc, 0x33, 0xfd, 0x34, 0xb5, 0x28, 0x76, 0xf9, 0x38, 0x07, 0x22, 0xf5, 0x2e, + 0x47, 0xef, 0xae, 0x37, 0x16, 0xb9, 0xd9, 0x58, 0xe4, 0xf7, 0xc6, 0x22, 0xeb, 0xad, 0x65, 0xdc, + 0x6c, 0x2d, 0xe3, 0xe7, 0xd6, 0x32, 0x3e, 0x3e, 0x0d, 0x23, 0xb9, 0x4c, 0x67, 0xce, 0x9c, 0xc7, + 0xee, 0x9c, 0xc7, 0x28, 0x67, 0x0b, 0x79, 0x38, 0xe8, 0x4f, 0x5a, 0xf6, 0x31, 0x67, 0x75, 0x95, + 0x7b, 0xfc, 0x27, 0x00, 0x00, 0xff, 0xff, 0x0b, 0x81, 0x69, 0x90, 0x03, 0x04, 0x00, 0x00, +} + +func (m *MsgInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.PeerID) > 0 { + i -= len(m.PeerID) + copy(dAtA[i:], m.PeerID) + i = encodeVarintWal(dAtA, i, uint64(len(m.PeerID))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Msg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *TimeoutInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TimeoutInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TimeoutInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Step != 0 { + i = encodeVarintWal(dAtA, i, uint64(m.Step)) + i-- + dAtA[i] = 0x20 + } + if m.Round != 0 { + i = encodeVarintWal(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x18 + } + if m.Height != 0 { + i = encodeVarintWal(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.Duration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.Duration):]) + if err2 != nil { + return 0, err2 + } + i -= n2 + i = encodeVarintWal(dAtA, i, uint64(n2)) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *EndHeight) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EndHeight) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EndHeight) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Height != 0 { + i = encodeVarintWal(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *WALMessage) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WALMessage) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WALMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *WALMessage_EventDataRoundState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WALMessage_EventDataRoundState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.EventDataRoundState != nil { + { + size, err := m.EventDataRoundState.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *WALMessage_MsgInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WALMessage_MsgInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.MsgInfo != nil { + { + size, err := m.MsgInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *WALMessage_TimeoutInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WALMessage_TimeoutInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.TimeoutInfo != nil { + { + size, err := m.TimeoutInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *WALMessage_EndHeight) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WALMessage_EndHeight) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.EndHeight != nil { + { + size, err := m.EndHeight.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *TimedWALMessage) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TimedWALMessage) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TimedWALMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Msg != nil { + { + size, err := m.Msg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintWal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + n8, err8 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err8 != nil { + return 0, err8 + } + i -= n8 + i = encodeVarintWal(dAtA, i, uint64(n8)) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintWal(dAtA []byte, offset int, v uint64) int { + offset -= sovWal(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Msg.Size() + n += 1 + l + sovWal(uint64(l)) + l = len(m.PeerID) + if l > 0 { + n += 1 + l + sovWal(uint64(l)) + } + return n +} + +func (m *TimeoutInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.Duration) + n += 1 + l + sovWal(uint64(l)) + if m.Height != 0 { + n += 1 + sovWal(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovWal(uint64(m.Round)) + } + if m.Step != 0 { + n += 1 + sovWal(uint64(m.Step)) + } + return n +} + +func (m *EndHeight) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovWal(uint64(m.Height)) + } + return n +} + +func (m *WALMessage) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *WALMessage_EventDataRoundState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.EventDataRoundState != nil { + l = m.EventDataRoundState.Size() + n += 1 + l + sovWal(uint64(l)) + } + return n +} +func (m *WALMessage_MsgInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MsgInfo != nil { + l = m.MsgInfo.Size() + n += 1 + l + sovWal(uint64(l)) + } + return n +} +func (m *WALMessage_TimeoutInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.TimeoutInfo != nil { + l = m.TimeoutInfo.Size() + n += 1 + l + sovWal(uint64(l)) + } + return n +} +func (m *WALMessage_EndHeight) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.EndHeight != nil { + l = m.EndHeight.Size() + n += 1 + l + sovWal(uint64(l)) + } + return n +} +func (m *TimedWALMessage) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovWal(uint64(l)) + if m.Msg != nil { + l = m.Msg.Size() + n += 1 + l + sovWal(uint64(l)) + } + return n +} + +func sovWal(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozWal(x uint64) (n int) { + return sovWal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Msg.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PeerID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PeerID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipWal(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthWal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TimeoutInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TimeoutInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TimeoutInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Duration", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.Duration, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Step", wireType) + } + m.Step = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Step |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipWal(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthWal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EndHeight) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EndHeight: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EndHeight: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipWal(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthWal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WALMessage) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WALMessage: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WALMessage: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EventDataRoundState", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &types.EventDataRoundState{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &WALMessage_EventDataRoundState{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &MsgInfo{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &WALMessage_MsgInfo{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TimeoutInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &TimeoutInfo{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &WALMessage_TimeoutInfo{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EndHeight", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &EndHeight{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &WALMessage_EndHeight{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipWal(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthWal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TimedWALMessage) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TimedWALMessage: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TimedWALMessage: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowWal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthWal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthWal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Msg == nil { + m.Msg = &WALMessage{} + } + if err := m.Msg.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipWal(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthWal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipWal(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowWal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowWal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowWal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthWal + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupWal + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthWal + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthWal = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowWal = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupWal = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/consensus/wal.proto b/proto/tendermint/consensus/wal.proto new file mode 100644 index 0000000..995b66b --- /dev/null +++ b/proto/tendermint/consensus/wal.proto @@ -0,0 +1,46 @@ +syntax = "proto3"; +package tendermint.consensus; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/consensus"; + +import "gogoproto/gogo.proto"; +import "tendermint/consensus/types.proto"; +import "tendermint/types/events.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +// MsgInfo are msgs from the reactor which may update the state +message MsgInfo { + Message msg = 1 [(gogoproto.nullable) = false]; + string peer_id = 2 [(gogoproto.customname) = "PeerID"]; +} + +// TimeoutInfo internally generated messages which may update the state +message TimeoutInfo { + google.protobuf.Duration duration = 1 + [(gogoproto.nullable) = false, (gogoproto.stdduration) = true]; + int64 height = 2; + int32 round = 3; + uint32 step = 4; +} + +// EndHeight marks the end of the given height inside WAL. +// @internal used by scripts/wal2json util. +message EndHeight { + int64 height = 1; +} + +message WALMessage { + oneof sum { + tendermint.types.EventDataRoundState event_data_round_state = 1; + MsgInfo msg_info = 2; + TimeoutInfo timeout_info = 3; + EndHeight end_height = 4; + } +} + +// TimedWALMessage wraps WALMessage and adds Time for debugging purposes. +message TimedWALMessage { + google.protobuf.Timestamp time = 1 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + WALMessage msg = 2; +} diff --git a/proto/tendermint/crypto/keys.pb.go b/proto/tendermint/crypto/keys.pb.go new file mode 100644 index 0000000..34c1f9e --- /dev/null +++ b/proto/tendermint/crypto/keys.pb.go @@ -0,0 +1,656 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/crypto/keys.proto + +package crypto + +import ( + bytes "bytes" + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// PublicKey defines the keys available for use with Validators +type PublicKey struct { + // Types that are valid to be assigned to Sum: + // + // *PublicKey_Ed25519 + // *PublicKey_Secp256K1 + Sum isPublicKey_Sum `protobuf_oneof:"sum"` +} + +func (m *PublicKey) Reset() { *m = PublicKey{} } +func (m *PublicKey) String() string { return proto.CompactTextString(m) } +func (*PublicKey) ProtoMessage() {} +func (*PublicKey) Descriptor() ([]byte, []int) { + return fileDescriptor_cb048658b234868c, []int{0} +} +func (m *PublicKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PublicKey.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PublicKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_PublicKey.Merge(m, src) +} +func (m *PublicKey) XXX_Size() int { + return m.Size() +} +func (m *PublicKey) XXX_DiscardUnknown() { + xxx_messageInfo_PublicKey.DiscardUnknown(m) +} + +var xxx_messageInfo_PublicKey proto.InternalMessageInfo + +type isPublicKey_Sum interface { + isPublicKey_Sum() + Equal(interface{}) bool + MarshalTo([]byte) (int, error) + Size() int + Compare(interface{}) int +} + +type PublicKey_Ed25519 struct { + Ed25519 []byte `protobuf:"bytes,1,opt,name=ed25519,proto3,oneof" json:"ed25519,omitempty"` +} +type PublicKey_Secp256K1 struct { + Secp256K1 []byte `protobuf:"bytes,2,opt,name=secp256k1,proto3,oneof" json:"secp256k1,omitempty"` +} + +func (*PublicKey_Ed25519) isPublicKey_Sum() {} +func (*PublicKey_Secp256K1) isPublicKey_Sum() {} + +func (m *PublicKey) GetSum() isPublicKey_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *PublicKey) GetEd25519() []byte { + if x, ok := m.GetSum().(*PublicKey_Ed25519); ok { + return x.Ed25519 + } + return nil +} + +func (m *PublicKey) GetSecp256K1() []byte { + if x, ok := m.GetSum().(*PublicKey_Secp256K1); ok { + return x.Secp256K1 + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*PublicKey) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*PublicKey_Ed25519)(nil), + (*PublicKey_Secp256K1)(nil), + } +} + +func init() { + proto.RegisterType((*PublicKey)(nil), "tendermint.crypto.PublicKey") +} + +func init() { proto.RegisterFile("tendermint/crypto/keys.proto", fileDescriptor_cb048658b234868c) } + +var fileDescriptor_cb048658b234868c = []byte{ + // 204 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x4f, 0x2e, 0xaa, 0x2c, 0x28, 0xc9, 0xd7, 0xcf, 0x4e, + 0xad, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x44, 0xc8, 0xea, 0x41, 0x64, 0xa5, + 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0xb2, 0xfa, 0x20, 0x16, 0x44, 0xa1, 0x52, 0x04, 0x17, 0x67, + 0x40, 0x69, 0x52, 0x4e, 0x66, 0xb2, 0x77, 0x6a, 0xa5, 0x90, 0x14, 0x17, 0x7b, 0x6a, 0x8a, 0x91, + 0xa9, 0xa9, 0xa1, 0xa5, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x8f, 0x07, 0x43, 0x10, 0x4c, 0x40, 0x48, + 0x8e, 0x8b, 0xb3, 0x38, 0x35, 0xb9, 0xc0, 0xc8, 0xd4, 0x2c, 0xdb, 0x50, 0x82, 0x09, 0x2a, 0x8b, + 0x10, 0xb2, 0xe2, 0x78, 0xb1, 0x40, 0x9e, 0xf1, 0xc5, 0x42, 0x79, 0x46, 0x27, 0x56, 0x2e, 0xe6, + 0xe2, 0xd2, 0x5c, 0x27, 0xbf, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, + 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x32, + 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0xcf, 0x4d, 0x2d, + 0x49, 0x4a, 0x2b, 0x41, 0x30, 0x20, 0x4e, 0xc4, 0xf0, 0x5d, 0x12, 0x1b, 0x58, 0xc2, 0x18, 0x10, + 0x00, 0x00, 0xff, 0xff, 0xa3, 0xfb, 0xf7, 0x98, 0xf9, 0x00, 0x00, 0x00, +} + +func (this *PublicKey) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*PublicKey) + if !ok { + that2, ok := that.(PublicKey) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if that1.Sum == nil { + if this.Sum != nil { + return 1 + } + } else if this.Sum == nil { + return -1 + } else { + thisType := -1 + switch this.Sum.(type) { + case *PublicKey_Ed25519: + thisType = 0 + case *PublicKey_Secp256K1: + thisType = 1 + default: + panic(fmt.Sprintf("compare: unexpected type %T in oneof", this.Sum)) + } + that1Type := -1 + switch that1.Sum.(type) { + case *PublicKey_Ed25519: + that1Type = 0 + case *PublicKey_Secp256K1: + that1Type = 1 + default: + panic(fmt.Sprintf("compare: unexpected type %T in oneof", that1.Sum)) + } + if thisType == that1Type { + if c := this.Sum.Compare(that1.Sum); c != 0 { + return c + } + } else if thisType < that1Type { + return -1 + } else if thisType > that1Type { + return 1 + } + } + return 0 +} +func (this *PublicKey_Ed25519) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*PublicKey_Ed25519) + if !ok { + that2, ok := that.(PublicKey_Ed25519) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if c := bytes.Compare(this.Ed25519, that1.Ed25519); c != 0 { + return c + } + return 0 +} +func (this *PublicKey_Secp256K1) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*PublicKey_Secp256K1) + if !ok { + that2, ok := that.(PublicKey_Secp256K1) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if c := bytes.Compare(this.Secp256K1, that1.Secp256K1); c != 0 { + return c + } + return 0 +} +func (this *PublicKey) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PublicKey) + if !ok { + that2, ok := that.(PublicKey) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if that1.Sum == nil { + if this.Sum != nil { + return false + } + } else if this.Sum == nil { + return false + } else if !this.Sum.Equal(that1.Sum) { + return false + } + return true +} +func (this *PublicKey_Ed25519) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PublicKey_Ed25519) + if !ok { + that2, ok := that.(PublicKey_Ed25519) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Ed25519, that1.Ed25519) { + return false + } + return true +} +func (this *PublicKey_Secp256K1) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PublicKey_Secp256K1) + if !ok { + that2, ok := that.(PublicKey_Secp256K1) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Secp256K1, that1.Secp256K1) { + return false + } + return true +} +func (m *PublicKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PublicKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PublicKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *PublicKey_Ed25519) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PublicKey_Ed25519) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Ed25519 != nil { + i -= len(m.Ed25519) + copy(dAtA[i:], m.Ed25519) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Ed25519))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *PublicKey_Secp256K1) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PublicKey_Secp256K1) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Secp256K1 != nil { + i -= len(m.Secp256K1) + copy(dAtA[i:], m.Secp256K1) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Secp256K1))) + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func encodeVarintKeys(dAtA []byte, offset int, v uint64) int { + offset -= sovKeys(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PublicKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *PublicKey_Ed25519) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Ed25519 != nil { + l = len(m.Ed25519) + n += 1 + l + sovKeys(uint64(l)) + } + return n +} +func (m *PublicKey_Secp256K1) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Secp256K1 != nil { + l = len(m.Secp256K1) + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func sovKeys(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozKeys(x uint64) (n int) { + return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PublicKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PublicKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PublicKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Ed25519", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := make([]byte, postIndex-iNdEx) + copy(v, dAtA[iNdEx:postIndex]) + m.Sum = &PublicKey_Ed25519{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Secp256K1", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := make([]byte, postIndex-iNdEx) + copy(v, dAtA[iNdEx:postIndex]) + m.Sum = &PublicKey_Secp256K1{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipKeys(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthKeys + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupKeys + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthKeys + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupKeys = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/crypto/keys.proto b/proto/tendermint/crypto/keys.proto new file mode 100644 index 0000000..b1df6d3 --- /dev/null +++ b/proto/tendermint/crypto/keys.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; +package tendermint.crypto; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/crypto"; + +import "gogoproto/gogo.proto"; + +// PublicKey defines the keys available for use with Validators +message PublicKey { + option (gogoproto.compare) = true; + option (gogoproto.equal) = true; + + oneof sum { + bytes ed25519 = 1; + bytes secp256k1 = 2; + } +} diff --git a/proto/tendermint/crypto/proof.pb.go b/proto/tendermint/crypto/proof.pb.go new file mode 100644 index 0000000..531a025 --- /dev/null +++ b/proto/tendermint/crypto/proof.pb.go @@ -0,0 +1,1422 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/crypto/proof.proto + +package crypto + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Proof struct { + Total int64 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"` + Index int64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"` + LeafHash []byte `protobuf:"bytes,3,opt,name=leaf_hash,json=leafHash,proto3" json:"leaf_hash,omitempty"` + Aunts [][]byte `protobuf:"bytes,4,rep,name=aunts,proto3" json:"aunts,omitempty"` +} + +func (m *Proof) Reset() { *m = Proof{} } +func (m *Proof) String() string { return proto.CompactTextString(m) } +func (*Proof) ProtoMessage() {} +func (*Proof) Descriptor() ([]byte, []int) { + return fileDescriptor_6b60b6ba2ab5b856, []int{0} +} +func (m *Proof) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Proof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Proof.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Proof) XXX_Merge(src proto.Message) { + xxx_messageInfo_Proof.Merge(m, src) +} +func (m *Proof) XXX_Size() int { + return m.Size() +} +func (m *Proof) XXX_DiscardUnknown() { + xxx_messageInfo_Proof.DiscardUnknown(m) +} + +var xxx_messageInfo_Proof proto.InternalMessageInfo + +func (m *Proof) GetTotal() int64 { + if m != nil { + return m.Total + } + return 0 +} + +func (m *Proof) GetIndex() int64 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *Proof) GetLeafHash() []byte { + if m != nil { + return m.LeafHash + } + return nil +} + +func (m *Proof) GetAunts() [][]byte { + if m != nil { + return m.Aunts + } + return nil +} + +type ValueOp struct { + // Encoded in ProofOp.Key. + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // To encode in ProofOp.Data + Proof *Proof `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` +} + +func (m *ValueOp) Reset() { *m = ValueOp{} } +func (m *ValueOp) String() string { return proto.CompactTextString(m) } +func (*ValueOp) ProtoMessage() {} +func (*ValueOp) Descriptor() ([]byte, []int) { + return fileDescriptor_6b60b6ba2ab5b856, []int{1} +} +func (m *ValueOp) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValueOp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValueOp.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValueOp) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValueOp.Merge(m, src) +} +func (m *ValueOp) XXX_Size() int { + return m.Size() +} +func (m *ValueOp) XXX_DiscardUnknown() { + xxx_messageInfo_ValueOp.DiscardUnknown(m) +} + +var xxx_messageInfo_ValueOp proto.InternalMessageInfo + +func (m *ValueOp) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func (m *ValueOp) GetProof() *Proof { + if m != nil { + return m.Proof + } + return nil +} + +type DominoOp struct { + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Input string `protobuf:"bytes,2,opt,name=input,proto3" json:"input,omitempty"` + Output string `protobuf:"bytes,3,opt,name=output,proto3" json:"output,omitempty"` +} + +func (m *DominoOp) Reset() { *m = DominoOp{} } +func (m *DominoOp) String() string { return proto.CompactTextString(m) } +func (*DominoOp) ProtoMessage() {} +func (*DominoOp) Descriptor() ([]byte, []int) { + return fileDescriptor_6b60b6ba2ab5b856, []int{2} +} +func (m *DominoOp) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DominoOp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DominoOp.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DominoOp) XXX_Merge(src proto.Message) { + xxx_messageInfo_DominoOp.Merge(m, src) +} +func (m *DominoOp) XXX_Size() int { + return m.Size() +} +func (m *DominoOp) XXX_DiscardUnknown() { + xxx_messageInfo_DominoOp.DiscardUnknown(m) +} + +var xxx_messageInfo_DominoOp proto.InternalMessageInfo + +func (m *DominoOp) GetKey() string { + if m != nil { + return m.Key + } + return "" +} + +func (m *DominoOp) GetInput() string { + if m != nil { + return m.Input + } + return "" +} + +func (m *DominoOp) GetOutput() string { + if m != nil { + return m.Output + } + return "" +} + +// ProofOp defines an operation used for calculating Merkle root +// The data could be arbitrary format, providing nessecary data +// for example neighbouring node hash +type ProofOp struct { + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` +} + +func (m *ProofOp) Reset() { *m = ProofOp{} } +func (m *ProofOp) String() string { return proto.CompactTextString(m) } +func (*ProofOp) ProtoMessage() {} +func (*ProofOp) Descriptor() ([]byte, []int) { + return fileDescriptor_6b60b6ba2ab5b856, []int{3} +} +func (m *ProofOp) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ProofOp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ProofOp.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ProofOp) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProofOp.Merge(m, src) +} +func (m *ProofOp) XXX_Size() int { + return m.Size() +} +func (m *ProofOp) XXX_DiscardUnknown() { + xxx_messageInfo_ProofOp.DiscardUnknown(m) +} + +var xxx_messageInfo_ProofOp proto.InternalMessageInfo + +func (m *ProofOp) GetType() string { + if m != nil { + return m.Type + } + return "" +} + +func (m *ProofOp) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func (m *ProofOp) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +// ProofOps is Merkle proof defined by the list of ProofOps +type ProofOps struct { + Ops []ProofOp `protobuf:"bytes,1,rep,name=ops,proto3" json:"ops"` +} + +func (m *ProofOps) Reset() { *m = ProofOps{} } +func (m *ProofOps) String() string { return proto.CompactTextString(m) } +func (*ProofOps) ProtoMessage() {} +func (*ProofOps) Descriptor() ([]byte, []int) { + return fileDescriptor_6b60b6ba2ab5b856, []int{4} +} +func (m *ProofOps) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ProofOps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ProofOps.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ProofOps) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProofOps.Merge(m, src) +} +func (m *ProofOps) XXX_Size() int { + return m.Size() +} +func (m *ProofOps) XXX_DiscardUnknown() { + xxx_messageInfo_ProofOps.DiscardUnknown(m) +} + +var xxx_messageInfo_ProofOps proto.InternalMessageInfo + +func (m *ProofOps) GetOps() []ProofOp { + if m != nil { + return m.Ops + } + return nil +} + +func init() { + proto.RegisterType((*Proof)(nil), "tendermint.crypto.Proof") + proto.RegisterType((*ValueOp)(nil), "tendermint.crypto.ValueOp") + proto.RegisterType((*DominoOp)(nil), "tendermint.crypto.DominoOp") + proto.RegisterType((*ProofOp)(nil), "tendermint.crypto.ProofOp") + proto.RegisterType((*ProofOps)(nil), "tendermint.crypto.ProofOps") +} + +func init() { proto.RegisterFile("tendermint/crypto/proof.proto", fileDescriptor_6b60b6ba2ab5b856) } + +var fileDescriptor_6b60b6ba2ab5b856 = []byte{ + // 357 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0xbd, 0x6a, 0xe3, 0x40, + 0x10, 0x96, 0x2c, 0xf9, 0x6f, 0xed, 0xe2, 0x6e, 0x31, 0x87, 0xf0, 0x71, 0x3a, 0xa1, 0x4a, 0x95, + 0x04, 0x4e, 0xea, 0x14, 0x4e, 0x8a, 0x90, 0x40, 0x1c, 0x54, 0xa4, 0x48, 0x13, 0xd6, 0xf6, 0xca, + 0x12, 0xb1, 0x34, 0x8b, 0x34, 0x82, 0xf8, 0x2d, 0xf2, 0x58, 0x2e, 0x5d, 0xa6, 0x0a, 0xc1, 0x7e, + 0x91, 0xb0, 0xbb, 0x0a, 0x26, 0x98, 0x74, 0xdf, 0xcf, 0xec, 0x37, 0xdf, 0x20, 0x91, 0x7f, 0xc8, + 0x8b, 0x25, 0x2f, 0xf3, 0xac, 0xc0, 0x68, 0x51, 0x6e, 0x04, 0x42, 0x24, 0x4a, 0x80, 0x24, 0x14, + 0x25, 0x20, 0xd0, 0xdf, 0x47, 0x3b, 0xd4, 0xf6, 0x78, 0xb4, 0x82, 0x15, 0x28, 0x37, 0x92, 0x48, + 0x0f, 0xfa, 0x09, 0x69, 0xdf, 0xcb, 0x77, 0x74, 0x44, 0xda, 0x08, 0xc8, 0xd6, 0x8e, 0xe9, 0x99, + 0x81, 0x15, 0x6b, 0x22, 0xd5, 0xac, 0x58, 0xf2, 0x17, 0xa7, 0xa5, 0x55, 0x45, 0xe8, 0x5f, 0xd2, + 0x5f, 0x73, 0x96, 0x3c, 0xa5, 0xac, 0x4a, 0x1d, 0xcb, 0x33, 0x83, 0x61, 0xdc, 0x93, 0xc2, 0x35, + 0xab, 0x52, 0xf9, 0x84, 0xd5, 0x05, 0x56, 0x8e, 0xed, 0x59, 0xc1, 0x30, 0xd6, 0xc4, 0xbf, 0x25, + 0xdd, 0x07, 0xb6, 0xae, 0xf9, 0x4c, 0xd0, 0x5f, 0xc4, 0x7a, 0xe6, 0x1b, 0xb5, 0x67, 0x18, 0x4b, + 0x48, 0x43, 0xd2, 0x56, 0xe5, 0xd5, 0x96, 0xc1, 0xc4, 0x09, 0x4f, 0xda, 0x87, 0xaa, 0x64, 0xac, + 0xc7, 0xfc, 0x1b, 0xd2, 0xbb, 0x82, 0x3c, 0x2b, 0xe0, 0x7b, 0x5a, 0x5f, 0xa7, 0xa9, 0xce, 0xa2, + 0x46, 0x95, 0xd6, 0x8f, 0x35, 0xa1, 0x7f, 0x48, 0x07, 0x6a, 0x94, 0xb2, 0xa5, 0xe4, 0x86, 0xf9, + 0x97, 0xa4, 0xab, 0xb2, 0x67, 0x82, 0x52, 0x62, 0xe3, 0x46, 0xf0, 0x26, 0x4b, 0xe1, 0xaf, 0xf8, + 0xd6, 0xb1, 0x2c, 0x25, 0xf6, 0x92, 0x21, 0x6b, 0xee, 0x56, 0xd8, 0xbf, 0x20, 0xbd, 0x26, 0xa4, + 0xa2, 0x13, 0x62, 0x81, 0xa8, 0x1c, 0xd3, 0xb3, 0x82, 0xc1, 0x64, 0xfc, 0xd3, 0x29, 0x33, 0x31, + 0xb5, 0xb7, 0xef, 0xff, 0x8d, 0x58, 0x0e, 0x4f, 0xef, 0xb6, 0x7b, 0xd7, 0xdc, 0xed, 0x5d, 0xf3, + 0x63, 0xef, 0x9a, 0xaf, 0x07, 0xd7, 0xd8, 0x1d, 0x5c, 0xe3, 0xed, 0xe0, 0x1a, 0x8f, 0xe7, 0xab, + 0x0c, 0xd3, 0x7a, 0x1e, 0x2e, 0x20, 0x8f, 0x16, 0x90, 0x73, 0x9c, 0x27, 0x78, 0x04, 0xfa, 0x73, + 0x9e, 0xfc, 0x0a, 0xf3, 0x8e, 0x32, 0xce, 0x3e, 0x03, 0x00, 0x00, 0xff, 0xff, 0xa6, 0x5a, 0xb3, + 0xb6, 0x26, 0x02, 0x00, 0x00, +} + +func (m *Proof) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Proof) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Proof) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Aunts) > 0 { + for iNdEx := len(m.Aunts) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Aunts[iNdEx]) + copy(dAtA[i:], m.Aunts[iNdEx]) + i = encodeVarintProof(dAtA, i, uint64(len(m.Aunts[iNdEx]))) + i-- + dAtA[i] = 0x22 + } + } + if len(m.LeafHash) > 0 { + i -= len(m.LeafHash) + copy(dAtA[i:], m.LeafHash) + i = encodeVarintProof(dAtA, i, uint64(len(m.LeafHash))) + i-- + dAtA[i] = 0x1a + } + if m.Index != 0 { + i = encodeVarintProof(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x10 + } + if m.Total != 0 { + i = encodeVarintProof(dAtA, i, uint64(m.Total)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ValueOp) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValueOp) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValueOp) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Proof != nil { + { + size, err := m.Proof.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintProof(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintProof(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *DominoOp) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DominoOp) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DominoOp) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Output) > 0 { + i -= len(m.Output) + copy(dAtA[i:], m.Output) + i = encodeVarintProof(dAtA, i, uint64(len(m.Output))) + i-- + dAtA[i] = 0x1a + } + if len(m.Input) > 0 { + i -= len(m.Input) + copy(dAtA[i:], m.Input) + i = encodeVarintProof(dAtA, i, uint64(len(m.Input))) + i-- + dAtA[i] = 0x12 + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintProof(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ProofOp) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ProofOp) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ProofOp) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintProof(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x1a + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintProof(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0x12 + } + if len(m.Type) > 0 { + i -= len(m.Type) + copy(dAtA[i:], m.Type) + i = encodeVarintProof(dAtA, i, uint64(len(m.Type))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ProofOps) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ProofOps) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ProofOps) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Ops) > 0 { + for iNdEx := len(m.Ops) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Ops[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintProof(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintProof(dAtA []byte, offset int, v uint64) int { + offset -= sovProof(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Proof) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Total != 0 { + n += 1 + sovProof(uint64(m.Total)) + } + if m.Index != 0 { + n += 1 + sovProof(uint64(m.Index)) + } + l = len(m.LeafHash) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + if len(m.Aunts) > 0 { + for _, b := range m.Aunts { + l = len(b) + n += 1 + l + sovProof(uint64(l)) + } + } + return n +} + +func (m *ValueOp) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + if m.Proof != nil { + l = m.Proof.Size() + n += 1 + l + sovProof(uint64(l)) + } + return n +} + +func (m *DominoOp) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + l = len(m.Input) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + l = len(m.Output) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + return n +} + +func (m *ProofOp) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Type) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + l = len(m.Key) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovProof(uint64(l)) + } + return n +} + +func (m *ProofOps) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Ops) > 0 { + for _, e := range m.Ops { + l = e.Size() + n += 1 + l + sovProof(uint64(l)) + } + } + return n +} + +func sovProof(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozProof(x uint64) (n int) { + return sovProof(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Proof) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Proof: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Proof: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) + } + m.Total = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Total |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LeafHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LeafHash = append(m.LeafHash[:0], dAtA[iNdEx:postIndex]...) + if m.LeafHash == nil { + m.LeafHash = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Aunts", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Aunts = append(m.Aunts, make([]byte, postIndex-iNdEx)) + copy(m.Aunts[len(m.Aunts)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProof(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProof + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValueOp) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValueOp: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValueOp: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Proof == nil { + m.Proof = &Proof{} + } + if err := m.Proof.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProof(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProof + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DominoOp) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DominoOp: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DominoOp: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Input = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Output", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Output = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProof(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProof + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ProofOp) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ProofOp: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ProofOp: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Type = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProof(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProof + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ProofOps) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ProofOps: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ProofOps: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Ops", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProof + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProof + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProof + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Ops = append(m.Ops, ProofOp{}) + if err := m.Ops[len(m.Ops)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProof(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProof + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipProof(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProof + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProof + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProof + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthProof + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupProof + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthProof + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthProof = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowProof = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupProof = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/crypto/proof.proto b/proto/tendermint/crypto/proof.proto new file mode 100644 index 0000000..f7234ba --- /dev/null +++ b/proto/tendermint/crypto/proof.proto @@ -0,0 +1,41 @@ +syntax = "proto3"; +package tendermint.crypto; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/crypto"; + +import "gogoproto/gogo.proto"; + +message Proof { + int64 total = 1; + int64 index = 2; + bytes leaf_hash = 3; + repeated bytes aunts = 4; +} + +message ValueOp { + // Encoded in ProofOp.Key. + bytes key = 1; + + // To encode in ProofOp.Data + Proof proof = 2; +} + +message DominoOp { + string key = 1; + string input = 2; + string output = 3; +} + +// ProofOp defines an operation used for calculating Merkle root +// The data could be arbitrary format, providing nessecary data +// for example neighbouring node hash +message ProofOp { + string type = 1; + bytes key = 2; + bytes data = 3; +} + +// ProofOps is Merkle proof defined by the list of ProofOps +message ProofOps { + repeated ProofOp ops = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/tendermint/libs/bits/types.pb.go b/proto/tendermint/libs/bits/types.pb.go new file mode 100644 index 0000000..a30c37d --- /dev/null +++ b/proto/tendermint/libs/bits/types.pb.go @@ -0,0 +1,408 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/libs/bits/types.proto + +package bits + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type BitArray struct { + Bits int64 `protobuf:"varint,1,opt,name=bits,proto3" json:"bits,omitempty"` + Elems []uint64 `protobuf:"varint,2,rep,packed,name=elems,proto3" json:"elems,omitempty"` +} + +func (m *BitArray) Reset() { *m = BitArray{} } +func (m *BitArray) String() string { return proto.CompactTextString(m) } +func (*BitArray) ProtoMessage() {} +func (*BitArray) Descriptor() ([]byte, []int) { + return fileDescriptor_e91ab2672920d7d4, []int{0} +} +func (m *BitArray) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BitArray) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BitArray.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BitArray) XXX_Merge(src proto.Message) { + xxx_messageInfo_BitArray.Merge(m, src) +} +func (m *BitArray) XXX_Size() int { + return m.Size() +} +func (m *BitArray) XXX_DiscardUnknown() { + xxx_messageInfo_BitArray.DiscardUnknown(m) +} + +var xxx_messageInfo_BitArray proto.InternalMessageInfo + +func (m *BitArray) GetBits() int64 { + if m != nil { + return m.Bits + } + return 0 +} + +func (m *BitArray) GetElems() []uint64 { + if m != nil { + return m.Elems + } + return nil +} + +func init() { + proto.RegisterType((*BitArray)(nil), "tendermint.libs.bits.BitArray") +} + +func init() { proto.RegisterFile("tendermint/libs/bits/types.proto", fileDescriptor_e91ab2672920d7d4) } + +var fileDescriptor_e91ab2672920d7d4 = []byte{ + // 173 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x28, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0xcf, 0xc9, 0x4c, 0x2a, 0xd6, 0x4f, 0xca, 0x2c, 0x29, + 0xd6, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x41, 0xa8, + 0xd0, 0x03, 0xa9, 0xd0, 0x03, 0xa9, 0x50, 0x32, 0xe1, 0xe2, 0x70, 0xca, 0x2c, 0x71, 0x2c, 0x2a, + 0x4a, 0xac, 0x14, 0x12, 0xe2, 0x62, 0x01, 0x89, 0x49, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0x81, + 0xd9, 0x42, 0x22, 0x5c, 0xac, 0xa9, 0x39, 0xa9, 0xb9, 0xc5, 0x12, 0x4c, 0x0a, 0xcc, 0x1a, 0x2c, + 0x41, 0x10, 0x8e, 0x53, 0xe0, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, + 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x99, + 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x27, 0xe7, 0xe7, 0xa6, 0x96, + 0x24, 0xa5, 0x95, 0x20, 0x18, 0x60, 0x97, 0xe8, 0x63, 0x73, 0x6a, 0x12, 0x1b, 0x58, 0xce, 0x18, + 0x10, 0x00, 0x00, 0xff, 0xff, 0x09, 0xfd, 0x78, 0xed, 0xc9, 0x00, 0x00, 0x00, +} + +func (m *BitArray) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BitArray) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BitArray) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Elems) > 0 { + dAtA2 := make([]byte, len(m.Elems)*10) + var j1 int + for _, num := range m.Elems { + for num >= 1<<7 { + dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) + num >>= 7 + j1++ + } + dAtA2[j1] = uint8(num) + j1++ + } + i -= j1 + copy(dAtA[i:], dAtA2[:j1]) + i = encodeVarintTypes(dAtA, i, uint64(j1)) + i-- + dAtA[i] = 0x12 + } + if m.Bits != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Bits)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *BitArray) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Bits != 0 { + n += 1 + sovTypes(uint64(m.Bits)) + } + if len(m.Elems) > 0 { + l = 0 + for _, e := range m.Elems { + l += sovTypes(uint64(e)) + } + n += 1 + sovTypes(uint64(l)) + l + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *BitArray) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BitArray: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BitArray: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Bits", wireType) + } + m.Bits = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Bits |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType == 0 { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Elems = append(m.Elems, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ + } + } + elementCount = count + if elementCount != 0 && len(m.Elems) == 0 { + m.Elems = make([]uint64, 0, elementCount) + } + for iNdEx < postIndex { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Elems = append(m.Elems, v) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field Elems", wireType) + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/libs/bits/types.proto b/proto/tendermint/libs/bits/types.proto new file mode 100644 index 0000000..7d3588d --- /dev/null +++ b/proto/tendermint/libs/bits/types.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; +package tendermint.libs.bits; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/libs/bits"; + +message BitArray { + int64 bits = 1; + repeated uint64 elems = 2; +} diff --git a/proto/tendermint/mempool/message.go b/proto/tendermint/mempool/message.go new file mode 100644 index 0000000..59f1335 --- /dev/null +++ b/proto/tendermint/mempool/message.go @@ -0,0 +1,31 @@ +package mempool + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/p2p" +) + +var _ p2p.Wrapper = &Txs{} +var _ p2p.Unwrapper = &Message{} + +// Wrap implements the p2p Wrapper interface and wraps a mempool message. +func (m *Txs) Wrap() proto.Message { + mm := &Message{} + mm.Sum = &Message_Txs{Txs: m} + return mm +} + +// Unwrap implements the p2p Wrapper interface and unwraps a wrapped mempool +// message. +func (m *Message) Unwrap() (proto.Message, error) { + switch msg := m.Sum.(type) { + case *Message_Txs: + return m.GetTxs(), nil + + default: + return nil, fmt.Errorf("unknown message: %T", msg) + } +} diff --git a/proto/tendermint/mempool/types.pb.go b/proto/tendermint/mempool/types.pb.go new file mode 100644 index 0000000..782260d --- /dev/null +++ b/proto/tendermint/mempool/types.pb.go @@ -0,0 +1,557 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/mempool/types.proto + +package mempool + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Txs struct { + Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` +} + +func (m *Txs) Reset() { *m = Txs{} } +func (m *Txs) String() string { return proto.CompactTextString(m) } +func (*Txs) ProtoMessage() {} +func (*Txs) Descriptor() ([]byte, []int) { + return fileDescriptor_2af51926fdbcbc05, []int{0} +} +func (m *Txs) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Txs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Txs.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Txs) XXX_Merge(src proto.Message) { + xxx_messageInfo_Txs.Merge(m, src) +} +func (m *Txs) XXX_Size() int { + return m.Size() +} +func (m *Txs) XXX_DiscardUnknown() { + xxx_messageInfo_Txs.DiscardUnknown(m) +} + +var xxx_messageInfo_Txs proto.InternalMessageInfo + +func (m *Txs) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +type Message struct { + // Types that are valid to be assigned to Sum: + // + // *Message_Txs + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_2af51926fdbcbc05, []int{1} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_Txs struct { + Txs *Txs `protobuf:"bytes,1,opt,name=txs,proto3,oneof" json:"txs,omitempty"` +} + +func (*Message_Txs) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetTxs() *Txs { + if x, ok := m.GetSum().(*Message_Txs); ok { + return x.Txs + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_Txs)(nil), + } +} + +func init() { + proto.RegisterType((*Txs)(nil), "tendermint.mempool.Txs") + proto.RegisterType((*Message)(nil), "tendermint.mempool.Message") +} + +func init() { proto.RegisterFile("tendermint/mempool/types.proto", fileDescriptor_2af51926fdbcbc05) } + +var fileDescriptor_2af51926fdbcbc05 = []byte{ + // 184 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0xcf, 0x4d, 0xcd, 0x2d, 0xc8, 0xcf, 0xcf, 0xd1, 0x2f, + 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x42, 0xc8, 0xeb, 0x41, + 0xe5, 0x95, 0xc4, 0xb9, 0x98, 0x43, 0x2a, 0x8a, 0x85, 0x04, 0xb8, 0x98, 0x4b, 0x2a, 0x8a, 0x25, + 0x18, 0x15, 0x98, 0x35, 0x78, 0x82, 0x40, 0x4c, 0x25, 0x5b, 0x2e, 0x76, 0xdf, 0xd4, 0xe2, 0xe2, + 0xc4, 0xf4, 0x54, 0x21, 0x6d, 0x98, 0x24, 0xa3, 0x06, 0xb7, 0x91, 0xb8, 0x1e, 0xa6, 0x29, 0x7a, + 0x21, 0x15, 0xc5, 0x1e, 0x0c, 0x60, 0x7d, 0x4e, 0xac, 0x5c, 0xcc, 0xc5, 0xa5, 0xb9, 0x4e, 0xfe, + 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, + 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x9a, 0x9e, 0x59, 0x92, 0x51, + 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, 0x9c, 0x9f, 0x9b, 0x5a, 0x92, 0x94, 0x56, 0x82, 0x60, + 0x80, 0x5d, 0xaa, 0x8f, 0xe9, 0x91, 0x24, 0x36, 0xb0, 0x8c, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, + 0x53, 0xc3, 0xc4, 0x0a, 0xe5, 0x00, 0x00, 0x00, +} + +func (m *Txs) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Txs) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Txs) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_Txs) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_Txs) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.Txs != nil { + { + size, err := m.Txs.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Txs) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_Txs) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Txs != nil { + l = m.Txs.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Txs) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Txs: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Txs: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &Txs{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_Txs{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/mempool/types.proto b/proto/tendermint/mempool/types.proto new file mode 100644 index 0000000..be07aee --- /dev/null +++ b/proto/tendermint/mempool/types.proto @@ -0,0 +1,14 @@ +syntax = "proto3"; +package tendermint.mempool; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/mempool"; + +message Txs { + repeated bytes txs = 1; +} + +message Message { + oneof sum { + Txs txs = 1; + } +} diff --git a/proto/tendermint/p2p/conn.pb.go b/proto/tendermint/p2p/conn.pb.go new file mode 100644 index 0000000..0de067a --- /dev/null +++ b/proto/tendermint/p2p/conn.pb.go @@ -0,0 +1,1270 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/p2p/conn.proto + +package p2p + +import ( + fmt "fmt" + crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type PacketPing struct { +} + +func (m *PacketPing) Reset() { *m = PacketPing{} } +func (m *PacketPing) String() string { return proto.CompactTextString(m) } +func (*PacketPing) ProtoMessage() {} +func (*PacketPing) Descriptor() ([]byte, []int) { + return fileDescriptor_22474b5527c8fa9f, []int{0} +} +func (m *PacketPing) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PacketPing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PacketPing.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PacketPing) XXX_Merge(src proto.Message) { + xxx_messageInfo_PacketPing.Merge(m, src) +} +func (m *PacketPing) XXX_Size() int { + return m.Size() +} +func (m *PacketPing) XXX_DiscardUnknown() { + xxx_messageInfo_PacketPing.DiscardUnknown(m) +} + +var xxx_messageInfo_PacketPing proto.InternalMessageInfo + +type PacketPong struct { +} + +func (m *PacketPong) Reset() { *m = PacketPong{} } +func (m *PacketPong) String() string { return proto.CompactTextString(m) } +func (*PacketPong) ProtoMessage() {} +func (*PacketPong) Descriptor() ([]byte, []int) { + return fileDescriptor_22474b5527c8fa9f, []int{1} +} +func (m *PacketPong) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PacketPong) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PacketPong.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PacketPong) XXX_Merge(src proto.Message) { + xxx_messageInfo_PacketPong.Merge(m, src) +} +func (m *PacketPong) XXX_Size() int { + return m.Size() +} +func (m *PacketPong) XXX_DiscardUnknown() { + xxx_messageInfo_PacketPong.DiscardUnknown(m) +} + +var xxx_messageInfo_PacketPong proto.InternalMessageInfo + +type PacketMsg struct { + ChannelID int32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + EOF bool `protobuf:"varint,2,opt,name=eof,proto3" json:"eof,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` +} + +func (m *PacketMsg) Reset() { *m = PacketMsg{} } +func (m *PacketMsg) String() string { return proto.CompactTextString(m) } +func (*PacketMsg) ProtoMessage() {} +func (*PacketMsg) Descriptor() ([]byte, []int) { + return fileDescriptor_22474b5527c8fa9f, []int{2} +} +func (m *PacketMsg) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PacketMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PacketMsg.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PacketMsg) XXX_Merge(src proto.Message) { + xxx_messageInfo_PacketMsg.Merge(m, src) +} +func (m *PacketMsg) XXX_Size() int { + return m.Size() +} +func (m *PacketMsg) XXX_DiscardUnknown() { + xxx_messageInfo_PacketMsg.DiscardUnknown(m) +} + +var xxx_messageInfo_PacketMsg proto.InternalMessageInfo + +func (m *PacketMsg) GetChannelID() int32 { + if m != nil { + return m.ChannelID + } + return 0 +} + +func (m *PacketMsg) GetEOF() bool { + if m != nil { + return m.EOF + } + return false +} + +func (m *PacketMsg) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +type Packet struct { + // Types that are valid to be assigned to Sum: + // + // *Packet_PacketPing + // *Packet_PacketPong + // *Packet_PacketMsg + Sum isPacket_Sum `protobuf_oneof:"sum"` +} + +func (m *Packet) Reset() { *m = Packet{} } +func (m *Packet) String() string { return proto.CompactTextString(m) } +func (*Packet) ProtoMessage() {} +func (*Packet) Descriptor() ([]byte, []int) { + return fileDescriptor_22474b5527c8fa9f, []int{3} +} +func (m *Packet) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Packet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Packet.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Packet) XXX_Merge(src proto.Message) { + xxx_messageInfo_Packet.Merge(m, src) +} +func (m *Packet) XXX_Size() int { + return m.Size() +} +func (m *Packet) XXX_DiscardUnknown() { + xxx_messageInfo_Packet.DiscardUnknown(m) +} + +var xxx_messageInfo_Packet proto.InternalMessageInfo + +type isPacket_Sum interface { + isPacket_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Packet_PacketPing struct { + PacketPing *PacketPing `protobuf:"bytes,1,opt,name=packet_ping,json=packetPing,proto3,oneof" json:"packet_ping,omitempty"` +} +type Packet_PacketPong struct { + PacketPong *PacketPong `protobuf:"bytes,2,opt,name=packet_pong,json=packetPong,proto3,oneof" json:"packet_pong,omitempty"` +} +type Packet_PacketMsg struct { + PacketMsg *PacketMsg `protobuf:"bytes,3,opt,name=packet_msg,json=packetMsg,proto3,oneof" json:"packet_msg,omitempty"` +} + +func (*Packet_PacketPing) isPacket_Sum() {} +func (*Packet_PacketPong) isPacket_Sum() {} +func (*Packet_PacketMsg) isPacket_Sum() {} + +func (m *Packet) GetSum() isPacket_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Packet) GetPacketPing() *PacketPing { + if x, ok := m.GetSum().(*Packet_PacketPing); ok { + return x.PacketPing + } + return nil +} + +func (m *Packet) GetPacketPong() *PacketPong { + if x, ok := m.GetSum().(*Packet_PacketPong); ok { + return x.PacketPong + } + return nil +} + +func (m *Packet) GetPacketMsg() *PacketMsg { + if x, ok := m.GetSum().(*Packet_PacketMsg); ok { + return x.PacketMsg + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Packet) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Packet_PacketPing)(nil), + (*Packet_PacketPong)(nil), + (*Packet_PacketMsg)(nil), + } +} + +type AuthSigMessage struct { + PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` + Sig []byte `protobuf:"bytes,2,opt,name=sig,proto3" json:"sig,omitempty"` +} + +func (m *AuthSigMessage) Reset() { *m = AuthSigMessage{} } +func (m *AuthSigMessage) String() string { return proto.CompactTextString(m) } +func (*AuthSigMessage) ProtoMessage() {} +func (*AuthSigMessage) Descriptor() ([]byte, []int) { + return fileDescriptor_22474b5527c8fa9f, []int{4} +} +func (m *AuthSigMessage) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AuthSigMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AuthSigMessage.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AuthSigMessage) XXX_Merge(src proto.Message) { + xxx_messageInfo_AuthSigMessage.Merge(m, src) +} +func (m *AuthSigMessage) XXX_Size() int { + return m.Size() +} +func (m *AuthSigMessage) XXX_DiscardUnknown() { + xxx_messageInfo_AuthSigMessage.DiscardUnknown(m) +} + +var xxx_messageInfo_AuthSigMessage proto.InternalMessageInfo + +func (m *AuthSigMessage) GetPubKey() crypto.PublicKey { + if m != nil { + return m.PubKey + } + return crypto.PublicKey{} +} + +func (m *AuthSigMessage) GetSig() []byte { + if m != nil { + return m.Sig + } + return nil +} + +func init() { + proto.RegisterType((*PacketPing)(nil), "tendermint.p2p.PacketPing") + proto.RegisterType((*PacketPong)(nil), "tendermint.p2p.PacketPong") + proto.RegisterType((*PacketMsg)(nil), "tendermint.p2p.PacketMsg") + proto.RegisterType((*Packet)(nil), "tendermint.p2p.Packet") + proto.RegisterType((*AuthSigMessage)(nil), "tendermint.p2p.AuthSigMessage") +} + +func init() { proto.RegisterFile("tendermint/p2p/conn.proto", fileDescriptor_22474b5527c8fa9f) } + +var fileDescriptor_22474b5527c8fa9f = []byte{ + // 397 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0x4d, 0x8f, 0xd3, 0x30, + 0x10, 0x8d, 0xc9, 0x6e, 0x97, 0x4e, 0xcb, 0x0a, 0x59, 0x1c, 0xda, 0x6a, 0x95, 0x56, 0x3d, 0xf5, + 0x80, 0x12, 0x11, 0x6e, 0x20, 0x0e, 0x84, 0x0f, 0xb1, 0xaa, 0x2a, 0xaa, 0x70, 0xe3, 0x12, 0xe5, + 0xc3, 0xeb, 0x58, 0xdd, 0xd8, 0x56, 0xed, 0x1c, 0xf2, 0x2f, 0xf8, 0x59, 0xcb, 0xad, 0x47, 0x4e, + 0x15, 0x4a, 0xff, 0x08, 0x4a, 0x5c, 0x68, 0x2a, 0xb1, 0xb7, 0xf7, 0x66, 0xfc, 0x66, 0xde, 0x93, + 0x07, 0xc6, 0x9a, 0xf0, 0x8c, 0x6c, 0x0b, 0xc6, 0xb5, 0x27, 0x7d, 0xe9, 0xa5, 0x82, 0x73, 0x57, + 0x6e, 0x85, 0x16, 0xf8, 0xfa, 0xd4, 0x72, 0xa5, 0x2f, 0x27, 0x2f, 0xa8, 0xa0, 0xa2, 0x6d, 0x79, + 0x0d, 0x32, 0xaf, 0x26, 0x37, 0x9d, 0x01, 0xe9, 0xb6, 0x92, 0x5a, 0x78, 0x1b, 0x52, 0x29, 0xd3, + 0x9d, 0x0f, 0x01, 0xd6, 0x71, 0xba, 0x21, 0x7a, 0xcd, 0x38, 0xed, 0x30, 0xc1, 0xe9, 0x3c, 0x87, + 0xbe, 0x61, 0x2b, 0x45, 0xf1, 0x4b, 0x80, 0x34, 0x8f, 0x39, 0x27, 0xf7, 0x11, 0xcb, 0x46, 0x68, + 0x86, 0x16, 0x97, 0xc1, 0xb3, 0x7a, 0x3f, 0xed, 0x7f, 0x30, 0xd5, 0xdb, 0x8f, 0x61, 0xff, 0xf8, + 0xe0, 0x36, 0xc3, 0x63, 0xb0, 0x89, 0xb8, 0x1b, 0x3d, 0x99, 0xa1, 0xc5, 0xd3, 0xe0, 0xaa, 0xde, + 0x4f, 0xed, 0x4f, 0x5f, 0x3f, 0x87, 0x4d, 0x0d, 0x63, 0xb8, 0xc8, 0x62, 0x1d, 0x8f, 0xec, 0x19, + 0x5a, 0x0c, 0xc3, 0x16, 0xcf, 0x7f, 0x22, 0xe8, 0x99, 0x55, 0xf8, 0x1d, 0x0c, 0x64, 0x8b, 0x22, + 0xc9, 0x38, 0x6d, 0x17, 0x0d, 0xfc, 0x89, 0x7b, 0x1e, 0xd5, 0x3d, 0x79, 0xfe, 0x62, 0x85, 0x20, + 0xff, 0xb1, 0xae, 0x5c, 0x70, 0xda, 0x1a, 0x78, 0x5c, 0x2e, 0xce, 0xe4, 0x82, 0x53, 0xfc, 0x06, + 0x8e, 0x2c, 0x2a, 0x14, 0x6d, 0x2d, 0x0e, 0xfc, 0xf1, 0xff, 0xd5, 0x2b, 0xd5, 0x88, 0xfb, 0xf2, + 0x2f, 0x09, 0x2e, 0xc1, 0x56, 0x65, 0x31, 0x8f, 0xe0, 0xfa, 0x7d, 0xa9, 0xf3, 0x6f, 0x8c, 0xae, + 0x88, 0x52, 0x31, 0x25, 0xf8, 0x2d, 0x5c, 0xc9, 0x32, 0x89, 0x36, 0xa4, 0x3a, 0xc6, 0xb9, 0xe9, + 0x4e, 0x34, 0x7f, 0xe2, 0xae, 0xcb, 0xe4, 0x9e, 0xa5, 0x4b, 0x52, 0x05, 0x17, 0x0f, 0xfb, 0xa9, + 0x15, 0xf6, 0x64, 0x99, 0x2c, 0x49, 0x85, 0x9f, 0x83, 0xad, 0x98, 0x09, 0x32, 0x0c, 0x1b, 0x18, + 0x2c, 0x1f, 0x6a, 0x07, 0xed, 0x6a, 0x07, 0xfd, 0xae, 0x1d, 0xf4, 0xe3, 0xe0, 0x58, 0xbb, 0x83, + 0x63, 0xfd, 0x3a, 0x38, 0xd6, 0xf7, 0x57, 0x94, 0xe9, 0xbc, 0x4c, 0xdc, 0x54, 0x14, 0x5e, 0x2a, + 0x0a, 0xa2, 0x93, 0x3b, 0x7d, 0x02, 0xe6, 0x32, 0xce, 0xcf, 0x29, 0xe9, 0xb5, 0xd5, 0xd7, 0x7f, + 0x02, 0x00, 0x00, 0xff, 0xff, 0xa9, 0xf9, 0x75, 0xae, 0x67, 0x02, 0x00, 0x00, +} + +func (m *PacketPing) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PacketPing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PacketPing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *PacketPong) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PacketPong) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PacketPong) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *PacketMsg) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PacketMsg) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PacketMsg) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintConn(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x1a + } + if m.EOF { + i-- + if m.EOF { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x10 + } + if m.ChannelID != 0 { + i = encodeVarintConn(dAtA, i, uint64(m.ChannelID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Packet) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Packet) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Packet) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Packet_PacketPing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Packet_PacketPing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PacketPing != nil { + { + size, err := m.PacketPing.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConn(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Packet_PacketPong) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Packet_PacketPong) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PacketPong != nil { + { + size, err := m.PacketPong.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConn(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Packet_PacketMsg) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Packet_PacketMsg) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PacketMsg != nil { + { + size, err := m.PacketMsg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConn(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *AuthSigMessage) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AuthSigMessage) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AuthSigMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Sig) > 0 { + i -= len(m.Sig) + copy(dAtA[i:], m.Sig) + i = encodeVarintConn(dAtA, i, uint64(len(m.Sig))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConn(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintConn(dAtA []byte, offset int, v uint64) int { + offset -= sovConn(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PacketPing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *PacketPong) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *PacketMsg) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChannelID != 0 { + n += 1 + sovConn(uint64(m.ChannelID)) + } + if m.EOF { + n += 2 + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovConn(uint64(l)) + } + return n +} + +func (m *Packet) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Packet_PacketPing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PacketPing != nil { + l = m.PacketPing.Size() + n += 1 + l + sovConn(uint64(l)) + } + return n +} +func (m *Packet_PacketPong) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PacketPong != nil { + l = m.PacketPong.Size() + n += 1 + l + sovConn(uint64(l)) + } + return n +} +func (m *Packet_PacketMsg) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PacketMsg != nil { + l = m.PacketMsg.Size() + n += 1 + l + sovConn(uint64(l)) + } + return n +} +func (m *AuthSigMessage) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.PubKey.Size() + n += 1 + l + sovConn(uint64(l)) + l = len(m.Sig) + if l > 0 { + n += 1 + l + sovConn(uint64(l)) + } + return n +} + +func sovConn(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozConn(x uint64) (n int) { + return sovConn(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PacketPing) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PacketPing: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PacketPing: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipConn(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConn + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PacketPong) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PacketPong: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PacketPong: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipConn(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConn + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PacketMsg) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PacketMsg: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PacketMsg: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelID", wireType) + } + m.ChannelID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelID |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field EOF", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.EOF = bool(v != 0) + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConn(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConn + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Packet) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Packet: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Packet: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PacketPing", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PacketPing{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Packet_PacketPing{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PacketPong", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PacketPong{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Packet_PacketPong{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PacketMsg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PacketMsg{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Packet_PacketMsg{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConn(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConn + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AuthSigMessage) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AuthSigMessage: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AuthSigMessage: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sig", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthConn + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthConn + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sig = append(m.Sig[:0], dAtA[iNdEx:postIndex]...) + if m.Sig == nil { + m.Sig = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConn(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConn + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipConn(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConn + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConn + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConn + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthConn + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupConn + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthConn + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthConn = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowConn = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupConn = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/p2p/conn.proto b/proto/tendermint/p2p/conn.proto new file mode 100644 index 0000000..106a746 --- /dev/null +++ b/proto/tendermint/p2p/conn.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; +package tendermint.p2p; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/p2p"; + +import "gogoproto/gogo.proto"; +import "tendermint/crypto/keys.proto"; + +message PacketPing {} + +message PacketPong {} + +message PacketMsg { + int32 channel_id = 1 [(gogoproto.customname) = "ChannelID"]; + bool eof = 2 [(gogoproto.customname) = "EOF"]; + bytes data = 3; +} + +message Packet { + oneof sum { + PacketPing packet_ping = 1; + PacketPong packet_pong = 2; + PacketMsg packet_msg = 3; + } +} + +message AuthSigMessage { + tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; + bytes sig = 2; +} diff --git a/proto/tendermint/p2p/pex.go b/proto/tendermint/p2p/pex.go new file mode 100644 index 0000000..5202a4c --- /dev/null +++ b/proto/tendermint/p2p/pex.go @@ -0,0 +1,32 @@ +package p2p + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" +) + +func (m *PexAddrs) Wrap() proto.Message { + pm := &Message{} + pm.Sum = &Message_PexAddrs{PexAddrs: m} + return pm +} + +func (m *PexRequest) Wrap() proto.Message { + pm := &Message{} + pm.Sum = &Message_PexRequest{PexRequest: m} + return pm +} + +// Unwrap implements the p2p Wrapper interface and unwraps a wrapped PEX +// message. +func (m *Message) Unwrap() (proto.Message, error) { + switch msg := m.Sum.(type) { + case *Message_PexRequest: + return msg.PexRequest, nil + case *Message_PexAddrs: + return msg.PexAddrs, nil + default: + return nil, fmt.Errorf("unknown pex message: %T", msg) + } +} diff --git a/proto/tendermint/p2p/pex.pb.go b/proto/tendermint/p2p/pex.pb.go new file mode 100644 index 0000000..39e18c8 --- /dev/null +++ b/proto/tendermint/p2p/pex.pb.go @@ -0,0 +1,770 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/p2p/pex.proto + +package p2p + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type PexRequest struct { +} + +func (m *PexRequest) Reset() { *m = PexRequest{} } +func (m *PexRequest) String() string { return proto.CompactTextString(m) } +func (*PexRequest) ProtoMessage() {} +func (*PexRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_81c2f011fd13be57, []int{0} +} +func (m *PexRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PexRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PexRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PexRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_PexRequest.Merge(m, src) +} +func (m *PexRequest) XXX_Size() int { + return m.Size() +} +func (m *PexRequest) XXX_DiscardUnknown() { + xxx_messageInfo_PexRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_PexRequest proto.InternalMessageInfo + +type PexAddrs struct { + Addrs []NetAddress `protobuf:"bytes,1,rep,name=addrs,proto3" json:"addrs"` +} + +func (m *PexAddrs) Reset() { *m = PexAddrs{} } +func (m *PexAddrs) String() string { return proto.CompactTextString(m) } +func (*PexAddrs) ProtoMessage() {} +func (*PexAddrs) Descriptor() ([]byte, []int) { + return fileDescriptor_81c2f011fd13be57, []int{1} +} +func (m *PexAddrs) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PexAddrs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PexAddrs.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PexAddrs) XXX_Merge(src proto.Message) { + xxx_messageInfo_PexAddrs.Merge(m, src) +} +func (m *PexAddrs) XXX_Size() int { + return m.Size() +} +func (m *PexAddrs) XXX_DiscardUnknown() { + xxx_messageInfo_PexAddrs.DiscardUnknown(m) +} + +var xxx_messageInfo_PexAddrs proto.InternalMessageInfo + +func (m *PexAddrs) GetAddrs() []NetAddress { + if m != nil { + return m.Addrs + } + return nil +} + +type Message struct { + // Types that are valid to be assigned to Sum: + // *Message_PexRequest + // *Message_PexAddrs + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_81c2f011fd13be57, []int{2} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_PexRequest struct { + PexRequest *PexRequest `protobuf:"bytes,1,opt,name=pex_request,json=pexRequest,proto3,oneof" json:"pex_request,omitempty"` +} +type Message_PexAddrs struct { + PexAddrs *PexAddrs `protobuf:"bytes,2,opt,name=pex_addrs,json=pexAddrs,proto3,oneof" json:"pex_addrs,omitempty"` +} + +func (*Message_PexRequest) isMessage_Sum() {} +func (*Message_PexAddrs) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetPexRequest() *PexRequest { + if x, ok := m.GetSum().(*Message_PexRequest); ok { + return x.PexRequest + } + return nil +} + +func (m *Message) GetPexAddrs() *PexAddrs { + if x, ok := m.GetSum().(*Message_PexAddrs); ok { + return x.PexAddrs + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_PexRequest)(nil), + (*Message_PexAddrs)(nil), + } +} + +func init() { + proto.RegisterType((*PexRequest)(nil), "tendermint.p2p.PexRequest") + proto.RegisterType((*PexAddrs)(nil), "tendermint.p2p.PexAddrs") + proto.RegisterType((*Message)(nil), "tendermint.p2p.Message") +} + +func init() { proto.RegisterFile("tendermint/p2p/pex.proto", fileDescriptor_81c2f011fd13be57) } + +var fileDescriptor_81c2f011fd13be57 = []byte{ + // 273 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x28, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x30, 0x2a, 0xd0, 0x2f, 0x48, 0xad, 0xd0, 0x2b, + 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x43, 0xc8, 0xe8, 0x15, 0x18, 0x15, 0x48, 0x49, 0xa1, 0xa9, + 0x2c, 0xa9, 0x2c, 0x48, 0x2d, 0x86, 0xa8, 0x95, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x33, 0xf5, + 0x41, 0x2c, 0x88, 0xa8, 0x12, 0x0f, 0x17, 0x57, 0x40, 0x6a, 0x45, 0x50, 0x6a, 0x61, 0x69, 0x6a, + 0x71, 0x89, 0x92, 0x13, 0x17, 0x47, 0x40, 0x6a, 0x85, 0x63, 0x4a, 0x4a, 0x51, 0xb1, 0x90, 0x19, + 0x17, 0x6b, 0x22, 0x88, 0x21, 0xc1, 0xa8, 0xc0, 0xac, 0xc1, 0x6d, 0x24, 0xa5, 0x87, 0x6a, 0x97, + 0x9e, 0x5f, 0x6a, 0x09, 0x48, 0x61, 0x6a, 0x71, 0xb1, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, + 0x10, 0xe5, 0x4a, 0x1d, 0x8c, 0x5c, 0xec, 0xbe, 0xa9, 0xc5, 0xc5, 0x89, 0xe9, 0xa9, 0x42, 0xb6, + 0x5c, 0xdc, 0x05, 0xa9, 0x15, 0xf1, 0x45, 0x10, 0xe3, 0x25, 0x18, 0x15, 0x18, 0xb1, 0x99, 0x84, + 0x70, 0x80, 0x07, 0x43, 0x10, 0x57, 0x01, 0x9c, 0x27, 0x64, 0xce, 0xc5, 0x09, 0xd2, 0x0e, 0x71, + 0x06, 0x13, 0x58, 0xb3, 0x04, 0x16, 0xcd, 0x60, 0xf7, 0x7a, 0x30, 0x04, 0x71, 0x14, 0x40, 0xd9, + 0x4e, 0xac, 0x5c, 0xcc, 0xc5, 0xa5, 0xb9, 0x4e, 0xde, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, + 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, + 0x2c, 0xc7, 0x10, 0x65, 0x98, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, + 0x9c, 0x9f, 0x9b, 0x5a, 0x92, 0x94, 0x56, 0x82, 0x60, 0x40, 0x42, 0x09, 0x35, 0x2c, 0x93, 0xd8, + 0xc0, 0xa2, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x02, 0xad, 0x52, 0xe1, 0x8e, 0x01, 0x00, + 0x00, +} + +func (m *PexRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PexRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PexRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *PexAddrs) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PexAddrs) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PexAddrs) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Addrs) > 0 { + for iNdEx := len(m.Addrs) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Addrs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPex(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_PexRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PexRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PexRequest != nil { + { + size, err := m.PexRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPex(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Message_PexAddrs) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PexAddrs) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PexAddrs != nil { + { + size, err := m.PexAddrs.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPex(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func encodeVarintPex(dAtA []byte, offset int, v uint64) int { + offset -= sovPex(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PexRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *PexAddrs) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Addrs) > 0 { + for _, e := range m.Addrs { + l = e.Size() + n += 1 + l + sovPex(uint64(l)) + } + } + return n +} + +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_PexRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PexRequest != nil { + l = m.PexRequest.Size() + n += 1 + l + sovPex(uint64(l)) + } + return n +} +func (m *Message_PexAddrs) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PexAddrs != nil { + l = m.PexAddrs.Size() + n += 1 + l + sovPex(uint64(l)) + } + return n +} + +func sovPex(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPex(x uint64) (n int) { + return sovPex(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PexRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PexRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PexRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipPex(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPex + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PexAddrs) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PexAddrs: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PexAddrs: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Addrs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPex + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPex + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Addrs = append(m.Addrs, NetAddress{}) + if err := m.Addrs[len(m.Addrs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPex(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPex + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PexRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPex + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPex + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PexRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PexRequest{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PexAddrs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPex + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPex + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPex + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PexAddrs{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PexAddrs{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPex(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPex + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPex(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPex + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPex + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPex + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthPex + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPex + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPex + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPex = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPex = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPex = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/p2p/pex.proto b/proto/tendermint/p2p/pex.proto new file mode 100644 index 0000000..6cada37 --- /dev/null +++ b/proto/tendermint/p2p/pex.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; +package tendermint.p2p; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/p2p"; + +import "tendermint/p2p/types.proto"; +import "gogoproto/gogo.proto"; + +message PexRequest {} + +message PexAddrs { + repeated NetAddress addrs = 1 [(gogoproto.nullable) = false]; +} + +message Message { + oneof sum { + PexRequest pex_request = 1; + PexAddrs pex_addrs = 2; + } +} diff --git a/proto/tendermint/p2p/types.pb.go b/proto/tendermint/p2p/types.pb.go new file mode 100644 index 0000000..0eb5aa9 --- /dev/null +++ b/proto/tendermint/p2p/types.pb.go @@ -0,0 +1,1400 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/p2p/types.proto + +package p2p + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type NetAddress struct { + ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + IP string `protobuf:"bytes,2,opt,name=ip,proto3" json:"ip,omitempty"` + Port uint32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` +} + +func (m *NetAddress) Reset() { *m = NetAddress{} } +func (m *NetAddress) String() string { return proto.CompactTextString(m) } +func (*NetAddress) ProtoMessage() {} +func (*NetAddress) Descriptor() ([]byte, []int) { + return fileDescriptor_c8a29e659aeca578, []int{0} +} +func (m *NetAddress) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *NetAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_NetAddress.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *NetAddress) XXX_Merge(src proto.Message) { + xxx_messageInfo_NetAddress.Merge(m, src) +} +func (m *NetAddress) XXX_Size() int { + return m.Size() +} +func (m *NetAddress) XXX_DiscardUnknown() { + xxx_messageInfo_NetAddress.DiscardUnknown(m) +} + +var xxx_messageInfo_NetAddress proto.InternalMessageInfo + +func (m *NetAddress) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *NetAddress) GetIP() string { + if m != nil { + return m.IP + } + return "" +} + +func (m *NetAddress) GetPort() uint32 { + if m != nil { + return m.Port + } + return 0 +} + +type ProtocolVersion struct { + P2P uint64 `protobuf:"varint,1,opt,name=p2p,proto3" json:"p2p,omitempty"` + Block uint64 `protobuf:"varint,2,opt,name=block,proto3" json:"block,omitempty"` + App uint64 `protobuf:"varint,3,opt,name=app,proto3" json:"app,omitempty"` +} + +func (m *ProtocolVersion) Reset() { *m = ProtocolVersion{} } +func (m *ProtocolVersion) String() string { return proto.CompactTextString(m) } +func (*ProtocolVersion) ProtoMessage() {} +func (*ProtocolVersion) Descriptor() ([]byte, []int) { + return fileDescriptor_c8a29e659aeca578, []int{1} +} +func (m *ProtocolVersion) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ProtocolVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ProtocolVersion.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ProtocolVersion) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProtocolVersion.Merge(m, src) +} +func (m *ProtocolVersion) XXX_Size() int { + return m.Size() +} +func (m *ProtocolVersion) XXX_DiscardUnknown() { + xxx_messageInfo_ProtocolVersion.DiscardUnknown(m) +} + +var xxx_messageInfo_ProtocolVersion proto.InternalMessageInfo + +func (m *ProtocolVersion) GetP2P() uint64 { + if m != nil { + return m.P2P + } + return 0 +} + +func (m *ProtocolVersion) GetBlock() uint64 { + if m != nil { + return m.Block + } + return 0 +} + +func (m *ProtocolVersion) GetApp() uint64 { + if m != nil { + return m.App + } + return 0 +} + +type DefaultNodeInfo struct { + ProtocolVersion ProtocolVersion `protobuf:"bytes,1,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version"` + DefaultNodeID string `protobuf:"bytes,2,opt,name=default_node_id,json=defaultNodeId,proto3" json:"default_node_id,omitempty"` + ListenAddr string `protobuf:"bytes,3,opt,name=listen_addr,json=listenAddr,proto3" json:"listen_addr,omitempty"` + Network string `protobuf:"bytes,4,opt,name=network,proto3" json:"network,omitempty"` + Version string `protobuf:"bytes,5,opt,name=version,proto3" json:"version,omitempty"` + Channels []byte `protobuf:"bytes,6,opt,name=channels,proto3" json:"channels,omitempty"` + Moniker string `protobuf:"bytes,7,opt,name=moniker,proto3" json:"moniker,omitempty"` + Other DefaultNodeInfoOther `protobuf:"bytes,8,opt,name=other,proto3" json:"other"` +} + +func (m *DefaultNodeInfo) Reset() { *m = DefaultNodeInfo{} } +func (m *DefaultNodeInfo) String() string { return proto.CompactTextString(m) } +func (*DefaultNodeInfo) ProtoMessage() {} +func (*DefaultNodeInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_c8a29e659aeca578, []int{2} +} +func (m *DefaultNodeInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DefaultNodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DefaultNodeInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DefaultNodeInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_DefaultNodeInfo.Merge(m, src) +} +func (m *DefaultNodeInfo) XXX_Size() int { + return m.Size() +} +func (m *DefaultNodeInfo) XXX_DiscardUnknown() { + xxx_messageInfo_DefaultNodeInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_DefaultNodeInfo proto.InternalMessageInfo + +func (m *DefaultNodeInfo) GetProtocolVersion() ProtocolVersion { + if m != nil { + return m.ProtocolVersion + } + return ProtocolVersion{} +} + +func (m *DefaultNodeInfo) GetDefaultNodeID() string { + if m != nil { + return m.DefaultNodeID + } + return "" +} + +func (m *DefaultNodeInfo) GetListenAddr() string { + if m != nil { + return m.ListenAddr + } + return "" +} + +func (m *DefaultNodeInfo) GetNetwork() string { + if m != nil { + return m.Network + } + return "" +} + +func (m *DefaultNodeInfo) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *DefaultNodeInfo) GetChannels() []byte { + if m != nil { + return m.Channels + } + return nil +} + +func (m *DefaultNodeInfo) GetMoniker() string { + if m != nil { + return m.Moniker + } + return "" +} + +func (m *DefaultNodeInfo) GetOther() DefaultNodeInfoOther { + if m != nil { + return m.Other + } + return DefaultNodeInfoOther{} +} + +type DefaultNodeInfoOther struct { + TxIndex string `protobuf:"bytes,1,opt,name=tx_index,json=txIndex,proto3" json:"tx_index,omitempty"` + RPCAddress string `protobuf:"bytes,2,opt,name=rpc_address,json=rpcAddress,proto3" json:"rpc_address,omitempty"` +} + +func (m *DefaultNodeInfoOther) Reset() { *m = DefaultNodeInfoOther{} } +func (m *DefaultNodeInfoOther) String() string { return proto.CompactTextString(m) } +func (*DefaultNodeInfoOther) ProtoMessage() {} +func (*DefaultNodeInfoOther) Descriptor() ([]byte, []int) { + return fileDescriptor_c8a29e659aeca578, []int{3} +} +func (m *DefaultNodeInfoOther) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DefaultNodeInfoOther) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DefaultNodeInfoOther.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DefaultNodeInfoOther) XXX_Merge(src proto.Message) { + xxx_messageInfo_DefaultNodeInfoOther.Merge(m, src) +} +func (m *DefaultNodeInfoOther) XXX_Size() int { + return m.Size() +} +func (m *DefaultNodeInfoOther) XXX_DiscardUnknown() { + xxx_messageInfo_DefaultNodeInfoOther.DiscardUnknown(m) +} + +var xxx_messageInfo_DefaultNodeInfoOther proto.InternalMessageInfo + +func (m *DefaultNodeInfoOther) GetTxIndex() string { + if m != nil { + return m.TxIndex + } + return "" +} + +func (m *DefaultNodeInfoOther) GetRPCAddress() string { + if m != nil { + return m.RPCAddress + } + return "" +} + +func init() { + proto.RegisterType((*NetAddress)(nil), "tendermint.p2p.NetAddress") + proto.RegisterType((*ProtocolVersion)(nil), "tendermint.p2p.ProtocolVersion") + proto.RegisterType((*DefaultNodeInfo)(nil), "tendermint.p2p.DefaultNodeInfo") + proto.RegisterType((*DefaultNodeInfoOther)(nil), "tendermint.p2p.DefaultNodeInfoOther") +} + +func init() { proto.RegisterFile("tendermint/p2p/types.proto", fileDescriptor_c8a29e659aeca578) } + +var fileDescriptor_c8a29e659aeca578 = []byte{ + // 483 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x52, 0x3d, 0x8f, 0xda, 0x40, + 0x10, 0xc5, 0xc6, 0x7c, 0xdc, 0x10, 0x8e, 0xcb, 0x0a, 0x45, 0x3e, 0x0a, 0x1b, 0xa1, 0x14, 0x54, + 0xa0, 0x90, 0x2a, 0x5d, 0x42, 0x68, 0x50, 0xa4, 0x8b, 0xb5, 0x8a, 0x52, 0xa4, 0x41, 0xe0, 0x5d, + 0x60, 0x85, 0xd9, 0x5d, 0xad, 0xf7, 0x12, 0xf2, 0x2f, 0xf2, 0xb3, 0xae, 0xbc, 0x32, 0x95, 0x15, + 0x99, 0x32, 0x7f, 0x22, 0xf2, 0xae, 0x2f, 0xc7, 0xa1, 0xeb, 0xe6, 0xcd, 0x9b, 0x99, 0x37, 0xf3, + 0x34, 0xd0, 0xd3, 0x94, 0x13, 0xaa, 0xf6, 0x8c, 0xeb, 0xb1, 0x9c, 0xc8, 0xb1, 0xfe, 0x29, 0x69, + 0x3a, 0x92, 0x4a, 0x68, 0x81, 0x2e, 0x1f, 0xb9, 0x91, 0x9c, 0xc8, 0x5e, 0x77, 0x23, 0x36, 0xc2, + 0x50, 0xe3, 0x22, 0xb2, 0x55, 0x83, 0x08, 0xe0, 0x86, 0xea, 0x0f, 0x84, 0x28, 0x9a, 0xa6, 0xe8, + 0x15, 0xb8, 0x8c, 0xf8, 0x4e, 0xdf, 0x19, 0x5e, 0x4c, 0xeb, 0x79, 0x16, 0xba, 0xf3, 0x19, 0x76, + 0x19, 0x31, 0x79, 0xe9, 0xbb, 0x27, 0xf9, 0x08, 0xbb, 0x4c, 0x22, 0x04, 0x9e, 0x14, 0x4a, 0xfb, + 0xd5, 0xbe, 0x33, 0x6c, 0x63, 0x13, 0x0f, 0xbe, 0x40, 0x27, 0x2a, 0x46, 0xc7, 0x22, 0xf9, 0x4a, + 0x55, 0xca, 0x04, 0x47, 0xd7, 0x50, 0x95, 0x13, 0x69, 0xe6, 0x7a, 0xd3, 0x46, 0x9e, 0x85, 0xd5, + 0x68, 0x12, 0xe1, 0x22, 0x87, 0xba, 0x50, 0x5b, 0x25, 0x22, 0xde, 0x99, 0xe1, 0x1e, 0xb6, 0x00, + 0x5d, 0x41, 0x75, 0x29, 0xa5, 0x19, 0xeb, 0xe1, 0x22, 0x1c, 0xfc, 0x75, 0xa1, 0x33, 0xa3, 0xeb, + 0xe5, 0x6d, 0xa2, 0x6f, 0x04, 0xa1, 0x73, 0xbe, 0x16, 0x28, 0x82, 0x2b, 0x59, 0x2a, 0x2d, 0xbe, + 0x5b, 0x29, 0xa3, 0xd1, 0x9a, 0x84, 0xa3, 0xa7, 0xc7, 0x8f, 0xce, 0x36, 0x9a, 0x7a, 0x77, 0x59, + 0x58, 0xc1, 0x1d, 0x79, 0xb6, 0xe8, 0x3b, 0xe8, 0x10, 0x2b, 0xb2, 0xe0, 0x82, 0xd0, 0x05, 0x23, + 0xe5, 0xd1, 0x2f, 0xf3, 0x2c, 0x6c, 0x9f, 0xea, 0xcf, 0x70, 0x9b, 0x9c, 0x40, 0x82, 0x42, 0x68, + 0x25, 0x2c, 0xd5, 0x94, 0x2f, 0x96, 0x84, 0x28, 0xb3, 0xfa, 0x05, 0x06, 0x9b, 0x2a, 0xec, 0x45, + 0x3e, 0x34, 0x38, 0xd5, 0x3f, 0x84, 0xda, 0xf9, 0x9e, 0x21, 0x1f, 0x60, 0xc1, 0x3c, 0xac, 0x5f, + 0xb3, 0x4c, 0x09, 0x51, 0x0f, 0x9a, 0xf1, 0x76, 0xc9, 0x39, 0x4d, 0x52, 0xbf, 0xde, 0x77, 0x86, + 0x2f, 0xf0, 0x7f, 0x5c, 0x74, 0xed, 0x05, 0x67, 0x3b, 0xaa, 0xfc, 0x86, 0xed, 0x2a, 0x21, 0x7a, + 0x0f, 0x35, 0xa1, 0xb7, 0x54, 0xf9, 0x4d, 0x63, 0xc6, 0xeb, 0x73, 0x33, 0xce, 0x7c, 0xfc, 0x5c, + 0xd4, 0x96, 0x8e, 0xd8, 0xc6, 0xc1, 0x0a, 0xba, 0xcf, 0x15, 0xa1, 0x6b, 0x68, 0xea, 0xc3, 0x82, + 0x71, 0x42, 0x0f, 0xf6, 0x4b, 0x70, 0x43, 0x1f, 0xe6, 0x05, 0x44, 0x63, 0x68, 0x29, 0x19, 0x9b, + 0xe3, 0x69, 0x9a, 0x96, 0xb6, 0x5d, 0xe6, 0x59, 0x08, 0x38, 0xfa, 0x58, 0xfe, 0x17, 0x06, 0x25, + 0xe3, 0x32, 0x9e, 0x7e, 0xba, 0xcb, 0x03, 0xe7, 0x3e, 0x0f, 0x9c, 0x3f, 0x79, 0xe0, 0xfc, 0x3a, + 0x06, 0x95, 0xfb, 0x63, 0x50, 0xf9, 0x7d, 0x0c, 0x2a, 0xdf, 0xde, 0x6c, 0x98, 0xde, 0xde, 0xae, + 0x46, 0xb1, 0xd8, 0x8f, 0x63, 0xb1, 0xa7, 0x7a, 0xb5, 0xd6, 0x8f, 0x81, 0x7d, 0xe1, 0xa7, 0x8f, + 0xbf, 0xaa, 0x9b, 0xec, 0xdb, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xae, 0xdb, 0x56, 0x6d, 0x11, + 0x03, 0x00, 0x00, +} + +func (m *NetAddress) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NetAddress) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NetAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Port != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Port)) + i-- + dAtA[i] = 0x18 + } + if len(m.IP) > 0 { + i -= len(m.IP) + copy(dAtA[i:], m.IP) + i = encodeVarintTypes(dAtA, i, uint64(len(m.IP))) + i-- + dAtA[i] = 0x12 + } + if len(m.ID) > 0 { + i -= len(m.ID) + copy(dAtA[i:], m.ID) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ID))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ProtocolVersion) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ProtocolVersion) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ProtocolVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.App != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.App)) + i-- + dAtA[i] = 0x18 + } + if m.Block != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Block)) + i-- + dAtA[i] = 0x10 + } + if m.P2P != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.P2P)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *DefaultNodeInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DefaultNodeInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DefaultNodeInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Other.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + if len(m.Moniker) > 0 { + i -= len(m.Moniker) + copy(dAtA[i:], m.Moniker) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Moniker))) + i-- + dAtA[i] = 0x3a + } + if len(m.Channels) > 0 { + i -= len(m.Channels) + copy(dAtA[i:], m.Channels) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Channels))) + i-- + dAtA[i] = 0x32 + } + if len(m.Version) > 0 { + i -= len(m.Version) + copy(dAtA[i:], m.Version) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Version))) + i-- + dAtA[i] = 0x2a + } + if len(m.Network) > 0 { + i -= len(m.Network) + copy(dAtA[i:], m.Network) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Network))) + i-- + dAtA[i] = 0x22 + } + if len(m.ListenAddr) > 0 { + i -= len(m.ListenAddr) + copy(dAtA[i:], m.ListenAddr) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ListenAddr))) + i-- + dAtA[i] = 0x1a + } + if len(m.DefaultNodeID) > 0 { + i -= len(m.DefaultNodeID) + copy(dAtA[i:], m.DefaultNodeID) + i = encodeVarintTypes(dAtA, i, uint64(len(m.DefaultNodeID))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.ProtocolVersion.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *DefaultNodeInfoOther) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DefaultNodeInfoOther) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DefaultNodeInfoOther) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.RPCAddress) > 0 { + i -= len(m.RPCAddress) + copy(dAtA[i:], m.RPCAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.RPCAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.TxIndex) > 0 { + i -= len(m.TxIndex) + copy(dAtA[i:], m.TxIndex) + i = encodeVarintTypes(dAtA, i, uint64(len(m.TxIndex))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *NetAddress) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ID) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.IP) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Port != 0 { + n += 1 + sovTypes(uint64(m.Port)) + } + return n +} + +func (m *ProtocolVersion) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.P2P != 0 { + n += 1 + sovTypes(uint64(m.P2P)) + } + if m.Block != 0 { + n += 1 + sovTypes(uint64(m.Block)) + } + if m.App != 0 { + n += 1 + sovTypes(uint64(m.App)) + } + return n +} + +func (m *DefaultNodeInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ProtocolVersion.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.DefaultNodeID) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ListenAddr) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Network) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Version) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Channels) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Moniker) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.Other.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *DefaultNodeInfoOther) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.TxIndex) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.RPCAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *NetAddress) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NetAddress: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NetAddress: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field IP", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.IP = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Port", wireType) + } + m.Port = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Port |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ProtocolVersion) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ProtocolVersion: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ProtocolVersion: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field P2P", wireType) + } + m.P2P = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.P2P |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType) + } + m.Block = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Block |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field App", wireType) + } + m.App = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.App |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DefaultNodeInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DefaultNodeInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DefaultNodeInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProtocolVersion", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ProtocolVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultNodeID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DefaultNodeID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListenAddr", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ListenAddr = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Network = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Channels", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Channels = append(m.Channels[:0], dAtA[iNdEx:postIndex]...) + if m.Channels == nil { + m.Channels = []byte{} + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Moniker", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Moniker = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Other", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Other.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DefaultNodeInfoOther) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DefaultNodeInfoOther: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DefaultNodeInfoOther: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxIndex", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TxIndex = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RPCAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RPCAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/p2p/types.proto b/proto/tendermint/p2p/types.proto new file mode 100644 index 0000000..fecf7a8 --- /dev/null +++ b/proto/tendermint/p2p/types.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; +package tendermint.p2p; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/p2p"; + +import "gogoproto/gogo.proto"; + +message NetAddress { + string id = 1 [(gogoproto.customname) = "ID"]; + string ip = 2 [(gogoproto.customname) = "IP"]; + uint32 port = 3; +} + +message ProtocolVersion { + uint64 p2p = 1 [(gogoproto.customname) = "P2P"]; + uint64 block = 2; + uint64 app = 3; +} + +message DefaultNodeInfo { + ProtocolVersion protocol_version = 1 [(gogoproto.nullable) = false]; + string default_node_id = 2 [(gogoproto.customname) = "DefaultNodeID"]; + string listen_addr = 3; + string network = 4; + string version = 5; + bytes channels = 6; + string moniker = 7; + DefaultNodeInfoOther other = 8 [(gogoproto.nullable) = false]; +} + +message DefaultNodeInfoOther { + string tx_index = 1; + string rpc_address = 2 [(gogoproto.customname) = "RPCAddress"]; +} diff --git a/proto/tendermint/privval/types.pb.go b/proto/tendermint/privval/types.pb.go new file mode 100644 index 0000000..b39d513 --- /dev/null +++ b/proto/tendermint/privval/types.pb.go @@ -0,0 +1,2803 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/privval/types.proto + +package privval + +import ( + fmt "fmt" + crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + types "github.com/cometbft/cometbft/proto/tendermint/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Errors int32 + +const ( + Errors_ERRORS_UNKNOWN Errors = 0 + Errors_ERRORS_UNEXPECTED_RESPONSE Errors = 1 + Errors_ERRORS_NO_CONNECTION Errors = 2 + Errors_ERRORS_CONNECTION_TIMEOUT Errors = 3 + Errors_ERRORS_READ_TIMEOUT Errors = 4 + Errors_ERRORS_WRITE_TIMEOUT Errors = 5 +) + +var Errors_name = map[int32]string{ + 0: "ERRORS_UNKNOWN", + 1: "ERRORS_UNEXPECTED_RESPONSE", + 2: "ERRORS_NO_CONNECTION", + 3: "ERRORS_CONNECTION_TIMEOUT", + 4: "ERRORS_READ_TIMEOUT", + 5: "ERRORS_WRITE_TIMEOUT", +} + +var Errors_value = map[string]int32{ + "ERRORS_UNKNOWN": 0, + "ERRORS_UNEXPECTED_RESPONSE": 1, + "ERRORS_NO_CONNECTION": 2, + "ERRORS_CONNECTION_TIMEOUT": 3, + "ERRORS_READ_TIMEOUT": 4, + "ERRORS_WRITE_TIMEOUT": 5, +} + +func (x Errors) String() string { + return proto.EnumName(Errors_name, int32(x)) +} + +func (Errors) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{0} +} + +type RemoteSignerError struct { + Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` +} + +func (m *RemoteSignerError) Reset() { *m = RemoteSignerError{} } +func (m *RemoteSignerError) String() string { return proto.CompactTextString(m) } +func (*RemoteSignerError) ProtoMessage() {} +func (*RemoteSignerError) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{0} +} +func (m *RemoteSignerError) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RemoteSignerError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RemoteSignerError.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RemoteSignerError) XXX_Merge(src proto.Message) { + xxx_messageInfo_RemoteSignerError.Merge(m, src) +} +func (m *RemoteSignerError) XXX_Size() int { + return m.Size() +} +func (m *RemoteSignerError) XXX_DiscardUnknown() { + xxx_messageInfo_RemoteSignerError.DiscardUnknown(m) +} + +var xxx_messageInfo_RemoteSignerError proto.InternalMessageInfo + +func (m *RemoteSignerError) GetCode() int32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *RemoteSignerError) GetDescription() string { + if m != nil { + return m.Description + } + return "" +} + +// PubKeyRequest requests the consensus public key from the remote signer. +type PubKeyRequest struct { + ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *PubKeyRequest) Reset() { *m = PubKeyRequest{} } +func (m *PubKeyRequest) String() string { return proto.CompactTextString(m) } +func (*PubKeyRequest) ProtoMessage() {} +func (*PubKeyRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{1} +} +func (m *PubKeyRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PubKeyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PubKeyRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PubKeyRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_PubKeyRequest.Merge(m, src) +} +func (m *PubKeyRequest) XXX_Size() int { + return m.Size() +} +func (m *PubKeyRequest) XXX_DiscardUnknown() { + xxx_messageInfo_PubKeyRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_PubKeyRequest proto.InternalMessageInfo + +func (m *PubKeyRequest) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +// PubKeyResponse is a response message containing the public key. +type PubKeyResponse struct { + PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` + Error *RemoteSignerError `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` +} + +func (m *PubKeyResponse) Reset() { *m = PubKeyResponse{} } +func (m *PubKeyResponse) String() string { return proto.CompactTextString(m) } +func (*PubKeyResponse) ProtoMessage() {} +func (*PubKeyResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{2} +} +func (m *PubKeyResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PubKeyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PubKeyResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PubKeyResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_PubKeyResponse.Merge(m, src) +} +func (m *PubKeyResponse) XXX_Size() int { + return m.Size() +} +func (m *PubKeyResponse) XXX_DiscardUnknown() { + xxx_messageInfo_PubKeyResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_PubKeyResponse proto.InternalMessageInfo + +func (m *PubKeyResponse) GetPubKey() crypto.PublicKey { + if m != nil { + return m.PubKey + } + return crypto.PublicKey{} +} + +func (m *PubKeyResponse) GetError() *RemoteSignerError { + if m != nil { + return m.Error + } + return nil +} + +// SignVoteRequest is a request to sign a vote +type SignVoteRequest struct { + Vote *types.Vote `protobuf:"bytes,1,opt,name=vote,proto3" json:"vote,omitempty"` + ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *SignVoteRequest) Reset() { *m = SignVoteRequest{} } +func (m *SignVoteRequest) String() string { return proto.CompactTextString(m) } +func (*SignVoteRequest) ProtoMessage() {} +func (*SignVoteRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{3} +} +func (m *SignVoteRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignVoteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignVoteRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SignVoteRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignVoteRequest.Merge(m, src) +} +func (m *SignVoteRequest) XXX_Size() int { + return m.Size() +} +func (m *SignVoteRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SignVoteRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SignVoteRequest proto.InternalMessageInfo + +func (m *SignVoteRequest) GetVote() *types.Vote { + if m != nil { + return m.Vote + } + return nil +} + +func (m *SignVoteRequest) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +// SignedVoteResponse is a response containing a signed vote or an error +type SignedVoteResponse struct { + Vote types.Vote `protobuf:"bytes,1,opt,name=vote,proto3" json:"vote"` + Error *RemoteSignerError `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` +} + +func (m *SignedVoteResponse) Reset() { *m = SignedVoteResponse{} } +func (m *SignedVoteResponse) String() string { return proto.CompactTextString(m) } +func (*SignedVoteResponse) ProtoMessage() {} +func (*SignedVoteResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{4} +} +func (m *SignedVoteResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignedVoteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignedVoteResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SignedVoteResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignedVoteResponse.Merge(m, src) +} +func (m *SignedVoteResponse) XXX_Size() int { + return m.Size() +} +func (m *SignedVoteResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SignedVoteResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SignedVoteResponse proto.InternalMessageInfo + +func (m *SignedVoteResponse) GetVote() types.Vote { + if m != nil { + return m.Vote + } + return types.Vote{} +} + +func (m *SignedVoteResponse) GetError() *RemoteSignerError { + if m != nil { + return m.Error + } + return nil +} + +// SignProposalRequest is a request to sign a proposal +type SignProposalRequest struct { + Proposal *types.Proposal `protobuf:"bytes,1,opt,name=proposal,proto3" json:"proposal,omitempty"` + ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *SignProposalRequest) Reset() { *m = SignProposalRequest{} } +func (m *SignProposalRequest) String() string { return proto.CompactTextString(m) } +func (*SignProposalRequest) ProtoMessage() {} +func (*SignProposalRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{5} +} +func (m *SignProposalRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignProposalRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignProposalRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SignProposalRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignProposalRequest.Merge(m, src) +} +func (m *SignProposalRequest) XXX_Size() int { + return m.Size() +} +func (m *SignProposalRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SignProposalRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SignProposalRequest proto.InternalMessageInfo + +func (m *SignProposalRequest) GetProposal() *types.Proposal { + if m != nil { + return m.Proposal + } + return nil +} + +func (m *SignProposalRequest) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +// SignedProposalResponse is response containing a signed proposal or an error +type SignedProposalResponse struct { + Proposal types.Proposal `protobuf:"bytes,1,opt,name=proposal,proto3" json:"proposal"` + Error *RemoteSignerError `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` +} + +func (m *SignedProposalResponse) Reset() { *m = SignedProposalResponse{} } +func (m *SignedProposalResponse) String() string { return proto.CompactTextString(m) } +func (*SignedProposalResponse) ProtoMessage() {} +func (*SignedProposalResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{6} +} +func (m *SignedProposalResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignedProposalResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignedProposalResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SignedProposalResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignedProposalResponse.Merge(m, src) +} +func (m *SignedProposalResponse) XXX_Size() int { + return m.Size() +} +func (m *SignedProposalResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SignedProposalResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SignedProposalResponse proto.InternalMessageInfo + +func (m *SignedProposalResponse) GetProposal() types.Proposal { + if m != nil { + return m.Proposal + } + return types.Proposal{} +} + +func (m *SignedProposalResponse) GetError() *RemoteSignerError { + if m != nil { + return m.Error + } + return nil +} + +// PingRequest is a request to confirm that the connection is alive. +type PingRequest struct { +} + +func (m *PingRequest) Reset() { *m = PingRequest{} } +func (m *PingRequest) String() string { return proto.CompactTextString(m) } +func (*PingRequest) ProtoMessage() {} +func (*PingRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{7} +} +func (m *PingRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PingRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PingRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PingRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_PingRequest.Merge(m, src) +} +func (m *PingRequest) XXX_Size() int { + return m.Size() +} +func (m *PingRequest) XXX_DiscardUnknown() { + xxx_messageInfo_PingRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_PingRequest proto.InternalMessageInfo + +// PingResponse is a response to confirm that the connection is alive. +type PingResponse struct { +} + +func (m *PingResponse) Reset() { *m = PingResponse{} } +func (m *PingResponse) String() string { return proto.CompactTextString(m) } +func (*PingResponse) ProtoMessage() {} +func (*PingResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{8} +} +func (m *PingResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PingResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PingResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PingResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_PingResponse.Merge(m, src) +} +func (m *PingResponse) XXX_Size() int { + return m.Size() +} +func (m *PingResponse) XXX_DiscardUnknown() { + xxx_messageInfo_PingResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_PingResponse proto.InternalMessageInfo + +type Message struct { + // Types that are valid to be assigned to Sum: + // *Message_PubKeyRequest + // *Message_PubKeyResponse + // *Message_SignVoteRequest + // *Message_SignedVoteResponse + // *Message_SignProposalRequest + // *Message_SignedProposalResponse + // *Message_PingRequest + // *Message_PingResponse + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_cb4e437a5328cf9c, []int{9} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_PubKeyRequest struct { + PubKeyRequest *PubKeyRequest `protobuf:"bytes,1,opt,name=pub_key_request,json=pubKeyRequest,proto3,oneof" json:"pub_key_request,omitempty"` +} +type Message_PubKeyResponse struct { + PubKeyResponse *PubKeyResponse `protobuf:"bytes,2,opt,name=pub_key_response,json=pubKeyResponse,proto3,oneof" json:"pub_key_response,omitempty"` +} +type Message_SignVoteRequest struct { + SignVoteRequest *SignVoteRequest `protobuf:"bytes,3,opt,name=sign_vote_request,json=signVoteRequest,proto3,oneof" json:"sign_vote_request,omitempty"` +} +type Message_SignedVoteResponse struct { + SignedVoteResponse *SignedVoteResponse `protobuf:"bytes,4,opt,name=signed_vote_response,json=signedVoteResponse,proto3,oneof" json:"signed_vote_response,omitempty"` +} +type Message_SignProposalRequest struct { + SignProposalRequest *SignProposalRequest `protobuf:"bytes,5,opt,name=sign_proposal_request,json=signProposalRequest,proto3,oneof" json:"sign_proposal_request,omitempty"` +} +type Message_SignedProposalResponse struct { + SignedProposalResponse *SignedProposalResponse `protobuf:"bytes,6,opt,name=signed_proposal_response,json=signedProposalResponse,proto3,oneof" json:"signed_proposal_response,omitempty"` +} +type Message_PingRequest struct { + PingRequest *PingRequest `protobuf:"bytes,7,opt,name=ping_request,json=pingRequest,proto3,oneof" json:"ping_request,omitempty"` +} +type Message_PingResponse struct { + PingResponse *PingResponse `protobuf:"bytes,8,opt,name=ping_response,json=pingResponse,proto3,oneof" json:"ping_response,omitempty"` +} + +func (*Message_PubKeyRequest) isMessage_Sum() {} +func (*Message_PubKeyResponse) isMessage_Sum() {} +func (*Message_SignVoteRequest) isMessage_Sum() {} +func (*Message_SignedVoteResponse) isMessage_Sum() {} +func (*Message_SignProposalRequest) isMessage_Sum() {} +func (*Message_SignedProposalResponse) isMessage_Sum() {} +func (*Message_PingRequest) isMessage_Sum() {} +func (*Message_PingResponse) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetPubKeyRequest() *PubKeyRequest { + if x, ok := m.GetSum().(*Message_PubKeyRequest); ok { + return x.PubKeyRequest + } + return nil +} + +func (m *Message) GetPubKeyResponse() *PubKeyResponse { + if x, ok := m.GetSum().(*Message_PubKeyResponse); ok { + return x.PubKeyResponse + } + return nil +} + +func (m *Message) GetSignVoteRequest() *SignVoteRequest { + if x, ok := m.GetSum().(*Message_SignVoteRequest); ok { + return x.SignVoteRequest + } + return nil +} + +func (m *Message) GetSignedVoteResponse() *SignedVoteResponse { + if x, ok := m.GetSum().(*Message_SignedVoteResponse); ok { + return x.SignedVoteResponse + } + return nil +} + +func (m *Message) GetSignProposalRequest() *SignProposalRequest { + if x, ok := m.GetSum().(*Message_SignProposalRequest); ok { + return x.SignProposalRequest + } + return nil +} + +func (m *Message) GetSignedProposalResponse() *SignedProposalResponse { + if x, ok := m.GetSum().(*Message_SignedProposalResponse); ok { + return x.SignedProposalResponse + } + return nil +} + +func (m *Message) GetPingRequest() *PingRequest { + if x, ok := m.GetSum().(*Message_PingRequest); ok { + return x.PingRequest + } + return nil +} + +func (m *Message) GetPingResponse() *PingResponse { + if x, ok := m.GetSum().(*Message_PingResponse); ok { + return x.PingResponse + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_PubKeyRequest)(nil), + (*Message_PubKeyResponse)(nil), + (*Message_SignVoteRequest)(nil), + (*Message_SignedVoteResponse)(nil), + (*Message_SignProposalRequest)(nil), + (*Message_SignedProposalResponse)(nil), + (*Message_PingRequest)(nil), + (*Message_PingResponse)(nil), + } +} + +func init() { + proto.RegisterEnum("tendermint.privval.Errors", Errors_name, Errors_value) + proto.RegisterType((*RemoteSignerError)(nil), "tendermint.privval.RemoteSignerError") + proto.RegisterType((*PubKeyRequest)(nil), "tendermint.privval.PubKeyRequest") + proto.RegisterType((*PubKeyResponse)(nil), "tendermint.privval.PubKeyResponse") + proto.RegisterType((*SignVoteRequest)(nil), "tendermint.privval.SignVoteRequest") + proto.RegisterType((*SignedVoteResponse)(nil), "tendermint.privval.SignedVoteResponse") + proto.RegisterType((*SignProposalRequest)(nil), "tendermint.privval.SignProposalRequest") + proto.RegisterType((*SignedProposalResponse)(nil), "tendermint.privval.SignedProposalResponse") + proto.RegisterType((*PingRequest)(nil), "tendermint.privval.PingRequest") + proto.RegisterType((*PingResponse)(nil), "tendermint.privval.PingResponse") + proto.RegisterType((*Message)(nil), "tendermint.privval.Message") +} + +func init() { proto.RegisterFile("tendermint/privval/types.proto", fileDescriptor_cb4e437a5328cf9c) } + +var fileDescriptor_cb4e437a5328cf9c = []byte{ + // 756 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0x4d, 0x4f, 0xe3, 0x46, + 0x18, 0xb6, 0x21, 0x1f, 0xf0, 0x86, 0x84, 0x30, 0x50, 0x1a, 0x22, 0x6a, 0xd2, 0x54, 0x6d, 0x51, + 0x0e, 0x49, 0x45, 0xd5, 0x5e, 0xe8, 0xa5, 0x80, 0xd5, 0x44, 0x11, 0x76, 0x3a, 0x09, 0x05, 0x21, + 0x55, 0x56, 0x3e, 0x06, 0x63, 0x41, 0x3c, 0x5e, 0x8f, 0x83, 0x94, 0xf3, 0xde, 0xf6, 0xb4, 0xd2, + 0xfe, 0x89, 0x3d, 0xef, 0xaf, 0xe0, 0xc8, 0x71, 0x4f, 0xab, 0x15, 0xfc, 0x91, 0x55, 0xc6, 0x13, + 0xdb, 0xf9, 0x42, 0xbb, 0xe2, 0x36, 0xf3, 0xbe, 0xef, 0x3c, 0x1f, 0x33, 0x8f, 0x65, 0x50, 0x3c, + 0x62, 0xf7, 0x88, 0xdb, 0xb7, 0x6c, 0xaf, 0xe2, 0xb8, 0xd6, 0xdd, 0x5d, 0xfb, 0xb6, 0xe2, 0x0d, + 0x1d, 0xc2, 0xca, 0x8e, 0x4b, 0x3d, 0x8a, 0x50, 0xd8, 0x2f, 0x8b, 0x7e, 0x7e, 0x37, 0x72, 0xa6, + 0xeb, 0x0e, 0x1d, 0x8f, 0x56, 0x6e, 0xc8, 0x50, 0x9c, 0x98, 0xe8, 0x72, 0xa4, 0x28, 0x5e, 0x7e, + 0xcb, 0xa4, 0x26, 0xe5, 0xcb, 0xca, 0x68, 0xe5, 0x57, 0x8b, 0x35, 0xd8, 0xc0, 0xa4, 0x4f, 0x3d, + 0xd2, 0xb4, 0x4c, 0x9b, 0xb8, 0xaa, 0xeb, 0x52, 0x17, 0x21, 0x88, 0x75, 0x69, 0x8f, 0xe4, 0xe4, + 0x82, 0xbc, 0x1f, 0xc7, 0x7c, 0x8d, 0x0a, 0x90, 0xea, 0x11, 0xd6, 0x75, 0x2d, 0xc7, 0xb3, 0xa8, + 0x9d, 0x5b, 0x2a, 0xc8, 0xfb, 0xab, 0x38, 0x5a, 0x2a, 0x96, 0x20, 0xdd, 0x18, 0x74, 0xea, 0x64, + 0x88, 0xc9, 0xab, 0x01, 0x61, 0x1e, 0xda, 0x81, 0x95, 0xee, 0x75, 0xdb, 0xb2, 0x0d, 0xab, 0xc7, + 0xa1, 0x56, 0x71, 0x92, 0xef, 0x6b, 0xbd, 0xe2, 0x1b, 0x19, 0x32, 0xe3, 0x61, 0xe6, 0x50, 0x9b, + 0x11, 0x74, 0x08, 0x49, 0x67, 0xd0, 0x31, 0x6e, 0xc8, 0x90, 0x0f, 0xa7, 0x0e, 0x76, 0xcb, 0x91, + 0x1b, 0xf0, 0xdd, 0x96, 0x1b, 0x83, 0xce, 0xad, 0xd5, 0xad, 0x93, 0xe1, 0x51, 0xec, 0xfe, 0xd3, + 0x9e, 0x84, 0x13, 0x0e, 0x07, 0x41, 0x87, 0x10, 0x27, 0x23, 0xe9, 0x5c, 0x57, 0xea, 0xe0, 0xe7, + 0xf2, 0xec, 0xe5, 0x95, 0x67, 0x7c, 0x62, 0xff, 0x4c, 0xf1, 0x02, 0xd6, 0x47, 0xd5, 0xff, 0xa8, + 0x47, 0xc6, 0xd2, 0x4b, 0x10, 0xbb, 0xa3, 0x1e, 0x11, 0x4a, 0xb6, 0xa3, 0x70, 0xfe, 0x9d, 0xf2, + 0x61, 0x3e, 0x33, 0x61, 0x73, 0x69, 0xd2, 0xe6, 0x6b, 0x19, 0x10, 0x27, 0xec, 0xf9, 0xe0, 0xc2, + 0xea, 0x6f, 0x5f, 0x83, 0x2e, 0x1c, 0xfa, 0x1c, 0x2f, 0xf2, 0x77, 0x0d, 0x9b, 0xa3, 0x6a, 0xc3, + 0xa5, 0x0e, 0x65, 0xed, 0xdb, 0xb1, 0xc7, 0x3f, 0x61, 0xc5, 0x11, 0x25, 0xa1, 0x24, 0x3f, 0xab, + 0x24, 0x38, 0x14, 0xcc, 0x3e, 0xe7, 0xf7, 0x9d, 0x0c, 0xdb, 0xbe, 0xdf, 0x90, 0x4c, 0x78, 0xfe, + 0xeb, 0x5b, 0xd8, 0x84, 0xf7, 0x90, 0xf3, 0x45, 0xfe, 0xd3, 0x90, 0x6a, 0x58, 0xb6, 0x29, 0x7c, + 0x17, 0x33, 0xb0, 0xe6, 0x6f, 0x7d, 0x65, 0xc5, 0x0f, 0x71, 0x48, 0x9e, 0x12, 0xc6, 0xda, 0x26, + 0x41, 0x75, 0x58, 0x17, 0x21, 0x34, 0x5c, 0x7f, 0x5c, 0x88, 0xfd, 0x71, 0x1e, 0xe3, 0x44, 0xdc, + 0xab, 0x12, 0x4e, 0x3b, 0x13, 0xf9, 0xd7, 0x20, 0x1b, 0x82, 0xf9, 0x64, 0x42, 0x7f, 0xf1, 0x39, + 0x34, 0x7f, 0xb2, 0x2a, 0xe1, 0x8c, 0x33, 0xf9, 0x85, 0xfc, 0x0b, 0x1b, 0xcc, 0x32, 0x6d, 0x63, + 0x94, 0x88, 0x40, 0xde, 0x32, 0x07, 0xfc, 0x69, 0x1e, 0xe0, 0x54, 0xa8, 0xab, 0x12, 0x5e, 0x67, + 0x53, 0x39, 0xbf, 0x84, 0x2d, 0xc6, 0xdf, 0x6b, 0x0c, 0x2a, 0x64, 0xc6, 0x38, 0xea, 0x2f, 0x8b, + 0x50, 0x27, 0xf3, 0x5c, 0x95, 0x30, 0x62, 0xb3, 0x29, 0xff, 0x1f, 0xbe, 0xe3, 0x72, 0xc7, 0x8f, + 0x18, 0x48, 0x8e, 0x73, 0xf0, 0x5f, 0x17, 0x81, 0x4f, 0xe5, 0xb4, 0x2a, 0xe1, 0x4d, 0x36, 0x27, + 0xbe, 0x57, 0x90, 0x13, 0xd2, 0x23, 0x04, 0x42, 0x7e, 0x82, 0x33, 0x94, 0x16, 0xcb, 0x9f, 0x8e, + 0x67, 0x55, 0xc2, 0xdb, 0x6c, 0x7e, 0x70, 0x4f, 0x60, 0xcd, 0xb1, 0x6c, 0x33, 0x50, 0x9f, 0xe4, + 0xd8, 0x7b, 0x73, 0x5f, 0x30, 0x4c, 0x59, 0x55, 0xc2, 0x29, 0x27, 0xdc, 0xa2, 0x7f, 0x20, 0x2d, + 0x50, 0x84, 0xc4, 0x15, 0x0e, 0x53, 0x58, 0x0c, 0x13, 0x08, 0x5b, 0x73, 0x22, 0xfb, 0xa3, 0x38, + 0x2c, 0xb3, 0x41, 0xbf, 0xf4, 0x5e, 0x86, 0x04, 0x0f, 0x39, 0x43, 0x08, 0x32, 0x2a, 0xc6, 0x3a, + 0x6e, 0x1a, 0x67, 0x5a, 0x5d, 0xd3, 0xcf, 0xb5, 0xac, 0x84, 0x14, 0xc8, 0x07, 0x35, 0xf5, 0xa2, + 0xa1, 0x1e, 0xb7, 0xd4, 0x13, 0x03, 0xab, 0xcd, 0x86, 0xae, 0x35, 0xd5, 0xac, 0x8c, 0x72, 0xb0, + 0x25, 0xfa, 0x9a, 0x6e, 0x1c, 0xeb, 0x9a, 0xa6, 0x1e, 0xb7, 0x6a, 0xba, 0x96, 0x5d, 0x42, 0x3f, + 0xc0, 0x8e, 0xe8, 0x84, 0x65, 0xa3, 0x55, 0x3b, 0x55, 0xf5, 0xb3, 0x56, 0x76, 0x19, 0x7d, 0x0f, + 0x9b, 0xa2, 0x8d, 0xd5, 0xbf, 0x4f, 0x82, 0x46, 0x2c, 0x82, 0x78, 0x8e, 0x6b, 0x2d, 0x35, 0xe8, + 0xc4, 0x8f, 0xf4, 0xfb, 0x47, 0x45, 0x7e, 0x78, 0x54, 0xe4, 0xcf, 0x8f, 0x8a, 0xfc, 0xf6, 0x49, + 0x91, 0x1e, 0x9e, 0x14, 0xe9, 0xe3, 0x93, 0x22, 0x5d, 0xfe, 0x61, 0x5a, 0xde, 0xf5, 0xa0, 0x53, + 0xee, 0xd2, 0x7e, 0xa5, 0x4b, 0xfb, 0xc4, 0xeb, 0x5c, 0x79, 0xe1, 0xc2, 0xff, 0x57, 0xcd, 0xfe, + 0x25, 0x3b, 0x09, 0xde, 0xf9, 0xfd, 0x4b, 0x00, 0x00, 0x00, 0xff, 0xff, 0xda, 0x9f, 0x99, 0x3e, + 0x42, 0x07, 0x00, 0x00, +} + +func (m *RemoteSignerError) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RemoteSignerError) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RemoteSignerError) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if m.Code != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *PubKeyRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PubKeyRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PubKeyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PubKeyResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PubKeyResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PubKeyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Error != nil { + { + size, err := m.Error.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *SignVoteRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignVoteRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignVoteRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x12 + } + if m.Vote != nil { + { + size, err := m.Vote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *SignedVoteResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignedVoteResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignedVoteResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Error != nil { + { + size, err := m.Error.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Vote.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *SignProposalRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignProposalRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignProposalRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x12 + } + if m.Proposal != nil { + { + size, err := m.Proposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *SignedProposalResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignedProposalResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignedProposalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Error != nil { + { + size, err := m.Error.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Proposal.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PingRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PingRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PingRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *PingResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PingResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PingResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_PubKeyRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PubKeyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PubKeyRequest != nil { + { + size, err := m.PubKeyRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Message_PubKeyResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PubKeyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PubKeyResponse != nil { + { + size, err := m.PubKeyResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Message_SignVoteRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SignVoteRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SignVoteRequest != nil { + { + size, err := m.SignVoteRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Message_SignedVoteResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SignedVoteResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SignedVoteResponse != nil { + { + size, err := m.SignedVoteResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *Message_SignProposalRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SignProposalRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SignProposalRequest != nil { + { + size, err := m.SignProposalRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + return len(dAtA) - i, nil +} +func (m *Message_SignedProposalResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SignedProposalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SignedProposalResponse != nil { + { + size, err := m.SignedProposalResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + return len(dAtA) - i, nil +} +func (m *Message_PingRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PingRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PingRequest != nil { + { + size, err := m.PingRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + return len(dAtA) - i, nil +} +func (m *Message_PingResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_PingResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.PingResponse != nil { + { + size, err := m.PingResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + return len(dAtA) - i, nil +} +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *RemoteSignerError) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Code != 0 { + n += 1 + sovTypes(uint64(m.Code)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *PubKeyRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *PubKeyResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.PubKey.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Error != nil { + l = m.Error.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *SignVoteRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Vote != nil { + l = m.Vote.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *SignedVoteResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Vote.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Error != nil { + l = m.Error.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *SignProposalRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Proposal != nil { + l = m.Proposal.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *SignedProposalResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Proposal.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Error != nil { + l = m.Error.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *PingRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *PingResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_PubKeyRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PubKeyRequest != nil { + l = m.PubKeyRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_PubKeyResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PubKeyResponse != nil { + l = m.PubKeyResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_SignVoteRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SignVoteRequest != nil { + l = m.SignVoteRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_SignedVoteResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SignedVoteResponse != nil { + l = m.SignedVoteResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_SignProposalRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SignProposalRequest != nil { + l = m.SignProposalRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_SignedProposalResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SignedProposalResponse != nil { + l = m.SignedProposalResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_PingRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PingRequest != nil { + l = m.PingRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_PingResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PingResponse != nil { + l = m.PingResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *RemoteSignerError) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RemoteSignerError: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RemoteSignerError: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PubKeyRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PubKeyRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubKeyRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PubKeyResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PubKeyResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubKeyResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Error == nil { + m.Error = &RemoteSignerError{} + } + if err := m.Error.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignVoteRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignVoteRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignVoteRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Vote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Vote == nil { + m.Vote = &types.Vote{} + } + if err := m.Vote.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignedVoteResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignedVoteResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignedVoteResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Vote", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Vote.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Error == nil { + m.Error = &RemoteSignerError{} + } + if err := m.Error.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignProposalRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignProposalRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignProposalRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Proposal == nil { + m.Proposal = &types.Proposal{} + } + if err := m.Proposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignedProposalResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignedProposalResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignedProposalResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proposal", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Proposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Error == nil { + m.Error = &RemoteSignerError{} + } + if err := m.Error.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PingRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PingRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PingRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PingResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PingResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PingResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKeyRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PubKeyRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PubKeyRequest{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKeyResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PubKeyResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PubKeyResponse{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignVoteRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SignVoteRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SignVoteRequest{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignedVoteResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SignedVoteResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SignedVoteResponse{v} + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignProposalRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SignProposalRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SignProposalRequest{v} + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignedProposalResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SignedProposalResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SignedProposalResponse{v} + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PingRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PingRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PingRequest{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PingResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &PingResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_PingResponse{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/privval/types.proto b/proto/tendermint/privval/types.proto new file mode 100644 index 0000000..d73e437 --- /dev/null +++ b/proto/tendermint/privval/types.proto @@ -0,0 +1,76 @@ +syntax = "proto3"; +package tendermint.privval; + +import "tendermint/crypto/keys.proto"; +import "tendermint/types/types.proto"; +import "gogoproto/gogo.proto"; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/privval"; + +enum Errors { + ERRORS_UNKNOWN = 0; + ERRORS_UNEXPECTED_RESPONSE = 1; + ERRORS_NO_CONNECTION = 2; + ERRORS_CONNECTION_TIMEOUT = 3; + ERRORS_READ_TIMEOUT = 4; + ERRORS_WRITE_TIMEOUT = 5; +} + +message RemoteSignerError { + int32 code = 1; + string description = 2; +} + +// PubKeyRequest requests the consensus public key from the remote signer. +message PubKeyRequest { + string chain_id = 1; +} + +// PubKeyResponse is a response message containing the public key. +message PubKeyResponse { + tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; + RemoteSignerError error = 2; +} + +// SignVoteRequest is a request to sign a vote +message SignVoteRequest { + tendermint.types.Vote vote = 1; + string chain_id = 2; +} + +// SignedVoteResponse is a response containing a signed vote or an error +message SignedVoteResponse { + tendermint.types.Vote vote = 1 [(gogoproto.nullable) = false]; + RemoteSignerError error = 2; +} + +// SignProposalRequest is a request to sign a proposal +message SignProposalRequest { + tendermint.types.Proposal proposal = 1; + string chain_id = 2; +} + +// SignedProposalResponse is response containing a signed proposal or an error +message SignedProposalResponse { + tendermint.types.Proposal proposal = 1 [(gogoproto.nullable) = false]; + RemoteSignerError error = 2; +} + +// PingRequest is a request to confirm that the connection is alive. +message PingRequest {} + +// PingResponse is a response to confirm that the connection is alive. +message PingResponse {} + +message Message { + oneof sum { + PubKeyRequest pub_key_request = 1; + PubKeyResponse pub_key_response = 2; + SignVoteRequest sign_vote_request = 3; + SignedVoteResponse signed_vote_response = 4; + SignProposalRequest sign_proposal_request = 5; + SignedProposalResponse signed_proposal_response = 6; + PingRequest ping_request = 7; + PingResponse ping_response = 8; + } +} diff --git a/proto/tendermint/rpc/grpc/types.pb.go b/proto/tendermint/rpc/grpc/types.pb.go new file mode 100644 index 0000000..ee2010a --- /dev/null +++ b/proto/tendermint/rpc/grpc/types.pb.go @@ -0,0 +1,927 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/rpc/grpc/types.proto + +package coregrpc + +import ( + context "context" + fmt "fmt" + types "github.com/cometbft/cometbft/abci/types" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type RequestPing struct { +} + +func (m *RequestPing) Reset() { *m = RequestPing{} } +func (m *RequestPing) String() string { return proto.CompactTextString(m) } +func (*RequestPing) ProtoMessage() {} +func (*RequestPing) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{0} +} +func (m *RequestPing) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestPing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestPing.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestPing) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestPing.Merge(m, src) +} +func (m *RequestPing) XXX_Size() int { + return m.Size() +} +func (m *RequestPing) XXX_DiscardUnknown() { + xxx_messageInfo_RequestPing.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestPing proto.InternalMessageInfo + +type RequestBroadcastTx struct { + Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` +} + +func (m *RequestBroadcastTx) Reset() { *m = RequestBroadcastTx{} } +func (m *RequestBroadcastTx) String() string { return proto.CompactTextString(m) } +func (*RequestBroadcastTx) ProtoMessage() {} +func (*RequestBroadcastTx) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{1} +} +func (m *RequestBroadcastTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestBroadcastTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestBroadcastTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestBroadcastTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestBroadcastTx.Merge(m, src) +} +func (m *RequestBroadcastTx) XXX_Size() int { + return m.Size() +} +func (m *RequestBroadcastTx) XXX_DiscardUnknown() { + xxx_messageInfo_RequestBroadcastTx.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestBroadcastTx proto.InternalMessageInfo + +func (m *RequestBroadcastTx) GetTx() []byte { + if m != nil { + return m.Tx + } + return nil +} + +type ResponsePing struct { +} + +func (m *ResponsePing) Reset() { *m = ResponsePing{} } +func (m *ResponsePing) String() string { return proto.CompactTextString(m) } +func (*ResponsePing) ProtoMessage() {} +func (*ResponsePing) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{2} +} +func (m *ResponsePing) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponsePing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponsePing.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponsePing) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponsePing.Merge(m, src) +} +func (m *ResponsePing) XXX_Size() int { + return m.Size() +} +func (m *ResponsePing) XXX_DiscardUnknown() { + xxx_messageInfo_ResponsePing.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponsePing proto.InternalMessageInfo + +type ResponseBroadcastTx struct { + CheckTx *types.ResponseCheckTx `protobuf:"bytes,1,opt,name=check_tx,json=checkTx,proto3" json:"check_tx,omitempty"` + TxResult *types.ExecTxResult `protobuf:"bytes,2,opt,name=tx_result,json=txResult,proto3" json:"tx_result,omitempty"` +} + +func (m *ResponseBroadcastTx) Reset() { *m = ResponseBroadcastTx{} } +func (m *ResponseBroadcastTx) String() string { return proto.CompactTextString(m) } +func (*ResponseBroadcastTx) ProtoMessage() {} +func (*ResponseBroadcastTx) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{3} +} +func (m *ResponseBroadcastTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseBroadcastTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseBroadcastTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseBroadcastTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseBroadcastTx.Merge(m, src) +} +func (m *ResponseBroadcastTx) XXX_Size() int { + return m.Size() +} +func (m *ResponseBroadcastTx) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseBroadcastTx.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseBroadcastTx proto.InternalMessageInfo + +func (m *ResponseBroadcastTx) GetCheckTx() *types.ResponseCheckTx { + if m != nil { + return m.CheckTx + } + return nil +} + +func (m *ResponseBroadcastTx) GetTxResult() *types.ExecTxResult { + if m != nil { + return m.TxResult + } + return nil +} + +func init() { + proto.RegisterType((*RequestPing)(nil), "tendermint.rpc.grpc.RequestPing") + proto.RegisterType((*RequestBroadcastTx)(nil), "tendermint.rpc.grpc.RequestBroadcastTx") + proto.RegisterType((*ResponsePing)(nil), "tendermint.rpc.grpc.ResponsePing") + proto.RegisterType((*ResponseBroadcastTx)(nil), "tendermint.rpc.grpc.ResponseBroadcastTx") +} + +func init() { proto.RegisterFile("tendermint/rpc/grpc/types.proto", fileDescriptor_0ffff5682c662b95) } + +var fileDescriptor_0ffff5682c662b95 = []byte{ + // 324 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x31, 0x4f, 0x02, 0x31, + 0x14, 0xc7, 0x29, 0x31, 0x8a, 0x05, 0x19, 0xca, 0x42, 0x30, 0x9e, 0x48, 0x4c, 0x64, 0x2a, 0x09, + 0x6e, 0x32, 0x89, 0x31, 0xd1, 0xb8, 0x90, 0x86, 0xc9, 0x05, 0xb9, 0xf2, 0x84, 0x8b, 0x72, 0x3d, + 0xdb, 0x47, 0x52, 0xbf, 0x84, 0xf1, 0x0b, 0xb9, 0x3b, 0x32, 0x3a, 0x1a, 0xf8, 0x22, 0xa6, 0x27, + 0x27, 0x35, 0x46, 0x96, 0xe6, 0xdf, 0xe6, 0xff, 0x7b, 0xfd, 0xbf, 0xd7, 0xd2, 0x43, 0x84, 0x78, + 0x04, 0x7a, 0x1a, 0xc5, 0xd8, 0xd2, 0x89, 0x6c, 0x8d, 0xdd, 0x82, 0xcf, 0x09, 0x18, 0x9e, 0x68, + 0x85, 0x8a, 0x55, 0xd6, 0x06, 0xae, 0x13, 0xc9, 0x9d, 0xa1, 0xb6, 0xef, 0x51, 0xc3, 0x50, 0x46, + 0x3e, 0xd1, 0xd8, 0xa3, 0x45, 0x01, 0x4f, 0x33, 0x30, 0xd8, 0x8b, 0xe2, 0x71, 0xe3, 0x98, 0xb2, + 0xd5, 0xb6, 0xab, 0xd5, 0x70, 0x24, 0x87, 0x06, 0xfb, 0x96, 0x95, 0x69, 0x1e, 0x6d, 0x95, 0xd4, + 0x49, 0xb3, 0x24, 0xf2, 0x68, 0x1b, 0x65, 0x5a, 0x12, 0x60, 0x12, 0x15, 0x1b, 0x48, 0xa9, 0x17, + 0x42, 0x2b, 0xd9, 0x81, 0xcf, 0x75, 0x68, 0x41, 0x4e, 0x40, 0x3e, 0x0c, 0x56, 0x74, 0xb1, 0x5d, + 0xe7, 0x5e, 0x42, 0x17, 0x86, 0x67, 0xdc, 0x85, 0x33, 0xf6, 0xad, 0xd8, 0x91, 0xdf, 0x82, 0x9d, + 0xd1, 0x5d, 0xb4, 0x03, 0x0d, 0x66, 0xf6, 0x88, 0xd5, 0x7c, 0x4a, 0x1f, 0xfc, 0xa1, 0x2f, 0x2d, + 0xc8, 0xbe, 0x15, 0xa9, 0x49, 0x14, 0x70, 0xa5, 0xda, 0x6f, 0x84, 0x96, 0x7e, 0x82, 0x9c, 0xf7, + 0xae, 0xd9, 0x0d, 0xdd, 0x72, 0x49, 0xd9, 0xaf, 0xfb, 0xb3, 0x09, 0x71, 0x6f, 0x02, 0xb5, 0xa3, + 0x7f, 0x1c, 0xeb, 0x76, 0xd9, 0x1d, 0x2d, 0xfa, 0x5d, 0x9e, 0x6c, 0xaa, 0xe9, 0x19, 0x6b, 0xcd, + 0x8d, 0xa5, 0x3d, 0x67, 0xf7, 0xea, 0x7d, 0x11, 0x90, 0xf9, 0x22, 0x20, 0x9f, 0x8b, 0x80, 0xbc, + 0x2e, 0x83, 0xdc, 0x7c, 0x19, 0xe4, 0x3e, 0x96, 0x41, 0xee, 0x96, 0x8f, 0x23, 0x9c, 0xcc, 0x42, + 0x2e, 0xd5, 0xb4, 0x25, 0xd5, 0x14, 0x30, 0xbc, 0xc7, 0xb5, 0xc8, 0x3e, 0x45, 0x47, 0x2a, 0x0d, + 0x4e, 0x84, 0xdb, 0xe9, 0x33, 0x9f, 0x7e, 0x05, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xca, 0xdb, 0xe7, + 0x3b, 0x02, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// BroadcastAPIClient is the client API for BroadcastAPI service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type BroadcastAPIClient interface { + Ping(ctx context.Context, in *RequestPing, opts ...grpc.CallOption) (*ResponsePing, error) + BroadcastTx(ctx context.Context, in *RequestBroadcastTx, opts ...grpc.CallOption) (*ResponseBroadcastTx, error) +} + +type broadcastAPIClient struct { + cc grpc1.ClientConn +} + +func NewBroadcastAPIClient(cc grpc1.ClientConn) BroadcastAPIClient { + return &broadcastAPIClient{cc} +} + +func (c *broadcastAPIClient) Ping(ctx context.Context, in *RequestPing, opts ...grpc.CallOption) (*ResponsePing, error) { + out := new(ResponsePing) + err := c.cc.Invoke(ctx, "/tendermint.rpc.grpc.BroadcastAPI/Ping", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *broadcastAPIClient) BroadcastTx(ctx context.Context, in *RequestBroadcastTx, opts ...grpc.CallOption) (*ResponseBroadcastTx, error) { + out := new(ResponseBroadcastTx) + err := c.cc.Invoke(ctx, "/tendermint.rpc.grpc.BroadcastAPI/BroadcastTx", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// BroadcastAPIServer is the server API for BroadcastAPI service. +type BroadcastAPIServer interface { + Ping(context.Context, *RequestPing) (*ResponsePing, error) + BroadcastTx(context.Context, *RequestBroadcastTx) (*ResponseBroadcastTx, error) +} + +// UnimplementedBroadcastAPIServer can be embedded to have forward compatible implementations. +type UnimplementedBroadcastAPIServer struct { +} + +func (*UnimplementedBroadcastAPIServer) Ping(ctx context.Context, req *RequestPing) (*ResponsePing, error) { + return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented") +} +func (*UnimplementedBroadcastAPIServer) BroadcastTx(ctx context.Context, req *RequestBroadcastTx) (*ResponseBroadcastTx, error) { + return nil, status.Errorf(codes.Unimplemented, "method BroadcastTx not implemented") +} + +func RegisterBroadcastAPIServer(s grpc1.Server, srv BroadcastAPIServer) { + s.RegisterService(&_BroadcastAPI_serviceDesc, srv) +} + +func _BroadcastAPI_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestPing) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(BroadcastAPIServer).Ping(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.rpc.grpc.BroadcastAPI/Ping", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(BroadcastAPIServer).Ping(ctx, req.(*RequestPing)) + } + return interceptor(ctx, in, info, handler) +} + +func _BroadcastAPI_BroadcastTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestBroadcastTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(BroadcastAPIServer).BroadcastTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.rpc.grpc.BroadcastAPI/BroadcastTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(BroadcastAPIServer).BroadcastTx(ctx, req.(*RequestBroadcastTx)) + } + return interceptor(ctx, in, info, handler) +} + +var BroadcastAPI_serviceDesc = _BroadcastAPI_serviceDesc +var _BroadcastAPI_serviceDesc = grpc.ServiceDesc{ + ServiceName: "tendermint.rpc.grpc.BroadcastAPI", + HandlerType: (*BroadcastAPIServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Ping", + Handler: _BroadcastAPI_Ping_Handler, + }, + { + MethodName: "BroadcastTx", + Handler: _BroadcastAPI_BroadcastTx_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "tendermint/rpc/grpc/types.proto", +} + +func (m *RequestPing) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestPing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestPing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *RequestBroadcastTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestBroadcastTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestBroadcastTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Tx) > 0 { + i -= len(m.Tx) + copy(dAtA[i:], m.Tx) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponsePing) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponsePing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponsePing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *ResponseBroadcastTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseBroadcastTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseBroadcastTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TxResult != nil { + { + size, err := m.TxResult.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.CheckTx != nil { + { + size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *RequestPing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *RequestBroadcastTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Tx) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponsePing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *ResponseBroadcastTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CheckTx != nil { + l = m.CheckTx.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.TxResult != nil { + l = m.TxResult.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *RequestPing) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestPing: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestPing: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestBroadcastTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestBroadcastTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestBroadcastTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...) + if m.Tx == nil { + m.Tx = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponsePing) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponsePing: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponsePing: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseBroadcastTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseBroadcastTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseBroadcastTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CheckTx == nil { + m.CheckTx = &types.ResponseCheckTx{} + } + if err := m.CheckTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxResult", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.TxResult == nil { + m.TxResult = &types.ExecTxResult{} + } + if err := m.TxResult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/rpc/grpc/types.proto b/proto/tendermint/rpc/grpc/types.proto new file mode 100644 index 0000000..bea7eec --- /dev/null +++ b/proto/tendermint/rpc/grpc/types.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; +package tendermint.rpc.grpc; +option go_package = "github.com/cometbft/cometbft/rpc/grpc;coregrpc"; + +import "tendermint/abci/types.proto"; + +//---------------------------------------- +// Request types + +message RequestPing {} + +message RequestBroadcastTx { + bytes tx = 1; +} + +//---------------------------------------- +// Response types + +message ResponsePing {} + +message ResponseBroadcastTx { + tendermint.abci.ResponseCheckTx check_tx = 1; + tendermint.abci.ExecTxResult tx_result = 2; +} + +//---------------------------------------- +// Service Definition + +// BroadcastAPI +// +// Deprecated: This API will be superseded by a more comprehensive gRPC-based +// broadcast API, and is scheduled for removal after v0.38. +service BroadcastAPI { + rpc Ping(RequestPing) returns (ResponsePing); + rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx); +} diff --git a/proto/tendermint/state/types.pb.go b/proto/tendermint/state/types.pb.go new file mode 100644 index 0000000..3d326f2 --- /dev/null +++ b/proto/tendermint/state/types.pb.go @@ -0,0 +1,2732 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/state/types.proto + +package state + +import ( + fmt "fmt" + types "github.com/cometbft/cometbft/abci/types" + types1 "github.com/cometbft/cometbft/proto/tendermint/types" + version "github.com/cometbft/cometbft/proto/tendermint/version" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// LegacyABCIResponses retains the responses +// of the legacy ABCI calls during block processing. +// Note ReponseDeliverTx is renamed to ExecTxResult but they are semantically the same +// Kept for backwards compatibility for versions prior to v0.38 +type LegacyABCIResponses struct { + DeliverTxs []*types.ExecTxResult `protobuf:"bytes,1,rep,name=deliver_txs,json=deliverTxs,proto3" json:"deliver_txs,omitempty"` + EndBlock *ResponseEndBlock `protobuf:"bytes,2,opt,name=end_block,json=endBlock,proto3" json:"end_block,omitempty"` + BeginBlock *ResponseBeginBlock `protobuf:"bytes,3,opt,name=begin_block,json=beginBlock,proto3" json:"begin_block,omitempty"` +} + +func (m *LegacyABCIResponses) Reset() { *m = LegacyABCIResponses{} } +func (m *LegacyABCIResponses) String() string { return proto.CompactTextString(m) } +func (*LegacyABCIResponses) ProtoMessage() {} +func (*LegacyABCIResponses) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{0} +} +func (m *LegacyABCIResponses) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *LegacyABCIResponses) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_LegacyABCIResponses.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *LegacyABCIResponses) XXX_Merge(src proto.Message) { + xxx_messageInfo_LegacyABCIResponses.Merge(m, src) +} +func (m *LegacyABCIResponses) XXX_Size() int { + return m.Size() +} +func (m *LegacyABCIResponses) XXX_DiscardUnknown() { + xxx_messageInfo_LegacyABCIResponses.DiscardUnknown(m) +} + +var xxx_messageInfo_LegacyABCIResponses proto.InternalMessageInfo + +func (m *LegacyABCIResponses) GetDeliverTxs() []*types.ExecTxResult { + if m != nil { + return m.DeliverTxs + } + return nil +} + +func (m *LegacyABCIResponses) GetEndBlock() *ResponseEndBlock { + if m != nil { + return m.EndBlock + } + return nil +} + +func (m *LegacyABCIResponses) GetBeginBlock() *ResponseBeginBlock { + if m != nil { + return m.BeginBlock + } + return nil +} + +// ResponseBeginBlock is kept for backwards compatibility for versions prior to v0.38 +type ResponseBeginBlock struct { + Events []types.Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` +} + +func (m *ResponseBeginBlock) Reset() { *m = ResponseBeginBlock{} } +func (m *ResponseBeginBlock) String() string { return proto.CompactTextString(m) } +func (*ResponseBeginBlock) ProtoMessage() {} +func (*ResponseBeginBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{1} +} +func (m *ResponseBeginBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseBeginBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseBeginBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseBeginBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseBeginBlock.Merge(m, src) +} +func (m *ResponseBeginBlock) XXX_Size() int { + return m.Size() +} +func (m *ResponseBeginBlock) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseBeginBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseBeginBlock proto.InternalMessageInfo + +func (m *ResponseBeginBlock) GetEvents() []types.Event { + if m != nil { + return m.Events + } + return nil +} + +// ResponseEndBlock is kept for backwards compatibility for versions prior to v0.38 +type ResponseEndBlock struct { + ValidatorUpdates []types.ValidatorUpdate `protobuf:"bytes,1,rep,name=validator_updates,json=validatorUpdates,proto3" json:"validator_updates"` + ConsensusParamUpdates *types1.ConsensusParams `protobuf:"bytes,2,opt,name=consensus_param_updates,json=consensusParamUpdates,proto3" json:"consensus_param_updates,omitempty"` + Events []types.Event `protobuf:"bytes,3,rep,name=events,proto3" json:"events,omitempty"` +} + +func (m *ResponseEndBlock) Reset() { *m = ResponseEndBlock{} } +func (m *ResponseEndBlock) String() string { return proto.CompactTextString(m) } +func (*ResponseEndBlock) ProtoMessage() {} +func (*ResponseEndBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{2} +} +func (m *ResponseEndBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseEndBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseEndBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseEndBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseEndBlock.Merge(m, src) +} +func (m *ResponseEndBlock) XXX_Size() int { + return m.Size() +} +func (m *ResponseEndBlock) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseEndBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseEndBlock proto.InternalMessageInfo + +func (m *ResponseEndBlock) GetValidatorUpdates() []types.ValidatorUpdate { + if m != nil { + return m.ValidatorUpdates + } + return nil +} + +func (m *ResponseEndBlock) GetConsensusParamUpdates() *types1.ConsensusParams { + if m != nil { + return m.ConsensusParamUpdates + } + return nil +} + +func (m *ResponseEndBlock) GetEvents() []types.Event { + if m != nil { + return m.Events + } + return nil +} + +// ValidatorsInfo represents the latest validator set, or the last height it changed +type ValidatorsInfo struct { + ValidatorSet *types1.ValidatorSet `protobuf:"bytes,1,opt,name=validator_set,json=validatorSet,proto3" json:"validator_set,omitempty"` + LastHeightChanged int64 `protobuf:"varint,2,opt,name=last_height_changed,json=lastHeightChanged,proto3" json:"last_height_changed,omitempty"` +} + +func (m *ValidatorsInfo) Reset() { *m = ValidatorsInfo{} } +func (m *ValidatorsInfo) String() string { return proto.CompactTextString(m) } +func (*ValidatorsInfo) ProtoMessage() {} +func (*ValidatorsInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{3} +} +func (m *ValidatorsInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValidatorsInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValidatorsInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValidatorsInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValidatorsInfo.Merge(m, src) +} +func (m *ValidatorsInfo) XXX_Size() int { + return m.Size() +} +func (m *ValidatorsInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ValidatorsInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ValidatorsInfo proto.InternalMessageInfo + +func (m *ValidatorsInfo) GetValidatorSet() *types1.ValidatorSet { + if m != nil { + return m.ValidatorSet + } + return nil +} + +func (m *ValidatorsInfo) GetLastHeightChanged() int64 { + if m != nil { + return m.LastHeightChanged + } + return 0 +} + +// ConsensusParamsInfo represents the latest consensus params, or the last height it changed +type ConsensusParamsInfo struct { + ConsensusParams types1.ConsensusParams `protobuf:"bytes,1,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params"` + LastHeightChanged int64 `protobuf:"varint,2,opt,name=last_height_changed,json=lastHeightChanged,proto3" json:"last_height_changed,omitempty"` +} + +func (m *ConsensusParamsInfo) Reset() { *m = ConsensusParamsInfo{} } +func (m *ConsensusParamsInfo) String() string { return proto.CompactTextString(m) } +func (*ConsensusParamsInfo) ProtoMessage() {} +func (*ConsensusParamsInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{4} +} +func (m *ConsensusParamsInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConsensusParamsInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ConsensusParamsInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ConsensusParamsInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConsensusParamsInfo.Merge(m, src) +} +func (m *ConsensusParamsInfo) XXX_Size() int { + return m.Size() +} +func (m *ConsensusParamsInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ConsensusParamsInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ConsensusParamsInfo proto.InternalMessageInfo + +func (m *ConsensusParamsInfo) GetConsensusParams() types1.ConsensusParams { + if m != nil { + return m.ConsensusParams + } + return types1.ConsensusParams{} +} + +func (m *ConsensusParamsInfo) GetLastHeightChanged() int64 { + if m != nil { + return m.LastHeightChanged + } + return 0 +} + +type ABCIResponsesInfo struct { + LegacyAbciResponses *LegacyABCIResponses `protobuf:"bytes,1,opt,name=legacy_abci_responses,json=legacyAbciResponses,proto3" json:"legacy_abci_responses,omitempty"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + ResponseFinalizeBlock *types.ResponseFinalizeBlock `protobuf:"bytes,3,opt,name=response_finalize_block,json=responseFinalizeBlock,proto3" json:"response_finalize_block,omitempty"` +} + +func (m *ABCIResponsesInfo) Reset() { *m = ABCIResponsesInfo{} } +func (m *ABCIResponsesInfo) String() string { return proto.CompactTextString(m) } +func (*ABCIResponsesInfo) ProtoMessage() {} +func (*ABCIResponsesInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{5} +} +func (m *ABCIResponsesInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ABCIResponsesInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ABCIResponsesInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ABCIResponsesInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ABCIResponsesInfo.Merge(m, src) +} +func (m *ABCIResponsesInfo) XXX_Size() int { + return m.Size() +} +func (m *ABCIResponsesInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ABCIResponsesInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ABCIResponsesInfo proto.InternalMessageInfo + +func (m *ABCIResponsesInfo) GetLegacyAbciResponses() *LegacyABCIResponses { + if m != nil { + return m.LegacyAbciResponses + } + return nil +} + +func (m *ABCIResponsesInfo) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ABCIResponsesInfo) GetResponseFinalizeBlock() *types.ResponseFinalizeBlock { + if m != nil { + return m.ResponseFinalizeBlock + } + return nil +} + +type Version struct { + Consensus version.Consensus `protobuf:"bytes,1,opt,name=consensus,proto3" json:"consensus"` + Software string `protobuf:"bytes,2,opt,name=software,proto3" json:"software,omitempty"` +} + +func (m *Version) Reset() { *m = Version{} } +func (m *Version) String() string { return proto.CompactTextString(m) } +func (*Version) ProtoMessage() {} +func (*Version) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{6} +} +func (m *Version) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Version) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Version.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Version) XXX_Merge(src proto.Message) { + xxx_messageInfo_Version.Merge(m, src) +} +func (m *Version) XXX_Size() int { + return m.Size() +} +func (m *Version) XXX_DiscardUnknown() { + xxx_messageInfo_Version.DiscardUnknown(m) +} + +var xxx_messageInfo_Version proto.InternalMessageInfo + +func (m *Version) GetConsensus() version.Consensus { + if m != nil { + return m.Consensus + } + return version.Consensus{} +} + +func (m *Version) GetSoftware() string { + if m != nil { + return m.Software + } + return "" +} + +type State struct { + Version Version `protobuf:"bytes,1,opt,name=version,proto3" json:"version"` + // immutable + ChainID string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + InitialHeight int64 `protobuf:"varint,14,opt,name=initial_height,json=initialHeight,proto3" json:"initial_height,omitempty"` + // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist) + LastBlockHeight int64 `protobuf:"varint,3,opt,name=last_block_height,json=lastBlockHeight,proto3" json:"last_block_height,omitempty"` + LastBlockID types1.BlockID `protobuf:"bytes,4,opt,name=last_block_id,json=lastBlockId,proto3" json:"last_block_id"` + LastBlockTime time.Time `protobuf:"bytes,5,opt,name=last_block_time,json=lastBlockTime,proto3,stdtime" json:"last_block_time"` + // LastValidators is used to validate block.LastCommit. + // Validators are persisted to the database separately every time they change, + // so we can query for historical validator sets. + // Note that if s.LastBlockHeight causes a valset change, + // we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1 + 1 + // Extra +1 due to nextValSet delay. + NextValidators *types1.ValidatorSet `protobuf:"bytes,6,opt,name=next_validators,json=nextValidators,proto3" json:"next_validators,omitempty"` + Validators *types1.ValidatorSet `protobuf:"bytes,7,opt,name=validators,proto3" json:"validators,omitempty"` + LastValidators *types1.ValidatorSet `protobuf:"bytes,8,opt,name=last_validators,json=lastValidators,proto3" json:"last_validators,omitempty"` + LastHeightValidatorsChanged int64 `protobuf:"varint,9,opt,name=last_height_validators_changed,json=lastHeightValidatorsChanged,proto3" json:"last_height_validators_changed,omitempty"` + // Consensus parameters used for validating blocks. + // Changes returned by EndBlock and updated after Commit. + ConsensusParams types1.ConsensusParams `protobuf:"bytes,10,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params"` + LastHeightConsensusParamsChanged int64 `protobuf:"varint,11,opt,name=last_height_consensus_params_changed,json=lastHeightConsensusParamsChanged,proto3" json:"last_height_consensus_params_changed,omitempty"` + // Merkle root of the results from executing prev block + LastResultsHash []byte `protobuf:"bytes,12,opt,name=last_results_hash,json=lastResultsHash,proto3" json:"last_results_hash,omitempty"` + // the latest AppHash we've received from calling abci.Commit() + AppHash []byte `protobuf:"bytes,13,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` +} + +func (m *State) Reset() { *m = State{} } +func (m *State) String() string { return proto.CompactTextString(m) } +func (*State) ProtoMessage() {} +func (*State) Descriptor() ([]byte, []int) { + return fileDescriptor_ccfacf933f22bf93, []int{7} +} +func (m *State) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *State) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_State.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *State) XXX_Merge(src proto.Message) { + xxx_messageInfo_State.Merge(m, src) +} +func (m *State) XXX_Size() int { + return m.Size() +} +func (m *State) XXX_DiscardUnknown() { + xxx_messageInfo_State.DiscardUnknown(m) +} + +var xxx_messageInfo_State proto.InternalMessageInfo + +func (m *State) GetVersion() Version { + if m != nil { + return m.Version + } + return Version{} +} + +func (m *State) GetChainID() string { + if m != nil { + return m.ChainID + } + return "" +} + +func (m *State) GetInitialHeight() int64 { + if m != nil { + return m.InitialHeight + } + return 0 +} + +func (m *State) GetLastBlockHeight() int64 { + if m != nil { + return m.LastBlockHeight + } + return 0 +} + +func (m *State) GetLastBlockID() types1.BlockID { + if m != nil { + return m.LastBlockID + } + return types1.BlockID{} +} + +func (m *State) GetLastBlockTime() time.Time { + if m != nil { + return m.LastBlockTime + } + return time.Time{} +} + +func (m *State) GetNextValidators() *types1.ValidatorSet { + if m != nil { + return m.NextValidators + } + return nil +} + +func (m *State) GetValidators() *types1.ValidatorSet { + if m != nil { + return m.Validators + } + return nil +} + +func (m *State) GetLastValidators() *types1.ValidatorSet { + if m != nil { + return m.LastValidators + } + return nil +} + +func (m *State) GetLastHeightValidatorsChanged() int64 { + if m != nil { + return m.LastHeightValidatorsChanged + } + return 0 +} + +func (m *State) GetConsensusParams() types1.ConsensusParams { + if m != nil { + return m.ConsensusParams + } + return types1.ConsensusParams{} +} + +func (m *State) GetLastHeightConsensusParamsChanged() int64 { + if m != nil { + return m.LastHeightConsensusParamsChanged + } + return 0 +} + +func (m *State) GetLastResultsHash() []byte { + if m != nil { + return m.LastResultsHash + } + return nil +} + +func (m *State) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +func init() { + proto.RegisterType((*LegacyABCIResponses)(nil), "tendermint.state.LegacyABCIResponses") + proto.RegisterType((*ResponseBeginBlock)(nil), "tendermint.state.ResponseBeginBlock") + proto.RegisterType((*ResponseEndBlock)(nil), "tendermint.state.ResponseEndBlock") + proto.RegisterType((*ValidatorsInfo)(nil), "tendermint.state.ValidatorsInfo") + proto.RegisterType((*ConsensusParamsInfo)(nil), "tendermint.state.ConsensusParamsInfo") + proto.RegisterType((*ABCIResponsesInfo)(nil), "tendermint.state.ABCIResponsesInfo") + proto.RegisterType((*Version)(nil), "tendermint.state.Version") + proto.RegisterType((*State)(nil), "tendermint.state.State") +} + +func init() { proto.RegisterFile("tendermint/state/types.proto", fileDescriptor_ccfacf933f22bf93) } + +var fileDescriptor_ccfacf933f22bf93 = []byte{ + // 963 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x4b, 0x6f, 0xdb, 0x46, + 0x17, 0x35, 0xe3, 0x44, 0x8f, 0x2b, 0xcb, 0x96, 0x47, 0x9f, 0x13, 0x45, 0xf9, 0x22, 0xa9, 0x42, + 0x12, 0x18, 0x45, 0x41, 0x01, 0xc9, 0xaa, 0x9b, 0x14, 0x96, 0xec, 0xd6, 0x02, 0xdc, 0xa2, 0xa0, + 0xdd, 0x00, 0xe9, 0x22, 0xc4, 0x88, 0x1c, 0x49, 0x83, 0x4a, 0x24, 0xc1, 0x19, 0xa9, 0x72, 0xf7, + 0xdd, 0x75, 0x91, 0x6d, 0xff, 0x51, 0x96, 0x59, 0x76, 0x53, 0xb7, 0x95, 0x81, 0x2e, 0xfa, 0x2b, + 0x8a, 0x79, 0xf0, 0x25, 0xba, 0xa8, 0x8b, 0xec, 0xc8, 0xb9, 0xe7, 0x9e, 0x7b, 0xee, 0x99, 0xb9, + 0x43, 0xc2, 0xff, 0x39, 0xf1, 0x5c, 0x12, 0xce, 0xa9, 0xc7, 0x7b, 0x8c, 0x63, 0x4e, 0x7a, 0xfc, + 0x32, 0x20, 0xcc, 0x0c, 0x42, 0x9f, 0xfb, 0xa8, 0x96, 0x44, 0x4d, 0x19, 0x6d, 0xfe, 0x6f, 0xe2, + 0x4f, 0x7c, 0x19, 0xec, 0x89, 0x27, 0x85, 0x6b, 0x3e, 0x4a, 0xb1, 0xe0, 0x91, 0x43, 0xd3, 0x24, + 0xcd, 0x74, 0x09, 0xb9, 0x9e, 0x89, 0x76, 0x72, 0xd1, 0x25, 0x9e, 0x51, 0x17, 0x73, 0x3f, 0xd4, + 0x88, 0xc7, 0x39, 0x44, 0x80, 0x43, 0x3c, 0x8f, 0x08, 0x5a, 0xa9, 0xf0, 0x92, 0x84, 0x8c, 0xfa, + 0x5e, 0xa6, 0x40, 0x7b, 0xe2, 0xfb, 0x93, 0x19, 0xe9, 0xc9, 0xb7, 0xd1, 0x62, 0xdc, 0xe3, 0x74, + 0x4e, 0x18, 0xc7, 0xf3, 0x40, 0x01, 0xba, 0xbf, 0x1a, 0x50, 0x3f, 0x23, 0x13, 0xec, 0x5c, 0x1e, + 0xf5, 0x07, 0x43, 0x8b, 0xb0, 0xc0, 0xf7, 0x18, 0x61, 0xe8, 0x25, 0x54, 0x5c, 0x32, 0xa3, 0x4b, + 0x12, 0xda, 0x7c, 0xc5, 0x1a, 0x46, 0x67, 0xfb, 0xb0, 0xf2, 0xfc, 0xb1, 0x99, 0xb2, 0x44, 0xb4, + 0x6a, 0x9e, 0xac, 0x88, 0x73, 0xb1, 0xb2, 0x08, 0x5b, 0xcc, 0xb8, 0x05, 0x3a, 0xe3, 0x62, 0xc5, + 0xd0, 0x67, 0x50, 0x26, 0x9e, 0x6b, 0x8f, 0x66, 0xbe, 0xf3, 0x5d, 0xe3, 0x4e, 0xc7, 0x38, 0xac, + 0x3c, 0xef, 0x9a, 0x9b, 0x86, 0x9a, 0x51, 0xbd, 0x13, 0xcf, 0xed, 0x0b, 0xa4, 0x55, 0x22, 0xfa, + 0x09, 0x9d, 0x40, 0x65, 0x44, 0x26, 0xd4, 0xd3, 0x14, 0xdb, 0x92, 0xe2, 0xc9, 0x3f, 0x53, 0xf4, + 0x05, 0x58, 0x91, 0xc0, 0x28, 0x7e, 0xee, 0xbe, 0x01, 0x94, 0x47, 0xa0, 0x53, 0x28, 0x90, 0x25, + 0xf1, 0x78, 0xd4, 0xd8, 0xfd, 0x7c, 0x63, 0x22, 0xdc, 0x6f, 0xbc, 0xbb, 0x6a, 0x6f, 0xfd, 0x75, + 0xd5, 0xae, 0x29, 0xf4, 0x27, 0xfe, 0x9c, 0x72, 0x32, 0x0f, 0xf8, 0xa5, 0xa5, 0xf3, 0xbb, 0x3f, + 0xdd, 0x81, 0xda, 0x66, 0x17, 0xe8, 0x1c, 0xf6, 0xe3, 0x7d, 0xb4, 0x17, 0x81, 0x8b, 0x39, 0x89, + 0x2a, 0x75, 0x72, 0x95, 0x5e, 0x45, 0xc8, 0x6f, 0x24, 0xb0, 0x7f, 0x57, 0xd4, 0xb4, 0x6a, 0xcb, + 0xec, 0x32, 0x43, 0xaf, 0xe1, 0x81, 0x23, 0xaa, 0x78, 0x6c, 0xc1, 0x6c, 0x79, 0x08, 0x62, 0x6a, + 0xe5, 0xef, 0x47, 0x69, 0x6a, 0x75, 0x08, 0x06, 0x51, 0xc2, 0xd7, 0xf2, 0xd0, 0x58, 0x07, 0x4e, + 0x66, 0x21, 0xa2, 0x4e, 0xec, 0xd8, 0xfe, 0x40, 0x3b, 0x7e, 0x34, 0x60, 0x37, 0x6e, 0x88, 0x0d, + 0xbd, 0xb1, 0x8f, 0x06, 0x50, 0x4d, 0xcc, 0x60, 0x84, 0x37, 0x0c, 0xa9, 0xb6, 0x95, 0x57, 0x1b, + 0x27, 0x9e, 0x13, 0x6e, 0xed, 0x2c, 0x53, 0x6f, 0xc8, 0x84, 0xfa, 0x0c, 0x33, 0x6e, 0x4f, 0x09, + 0x9d, 0x4c, 0xb9, 0xed, 0x4c, 0xb1, 0x37, 0x21, 0xae, 0x6c, 0x7c, 0xdb, 0xda, 0x17, 0xa1, 0x53, + 0x19, 0x19, 0xa8, 0x40, 0xf7, 0x67, 0x03, 0xea, 0x1b, 0xcd, 0x4b, 0x31, 0x16, 0xd4, 0x36, 0x4c, + 0x64, 0x5a, 0xcf, 0xbf, 0xbb, 0xa7, 0x77, 0x66, 0x2f, 0xeb, 0x21, 0xfb, 0xcf, 0xda, 0xfe, 0x34, + 0x60, 0x3f, 0x33, 0x6c, 0x52, 0xd9, 0x6b, 0x38, 0x98, 0xc9, 0x39, 0xb4, 0x85, 0xe1, 0x76, 0x18, + 0x05, 0xb5, 0xbc, 0xa7, 0xf9, 0x93, 0x7f, 0xc3, 0xd8, 0x5a, 0x75, 0xc5, 0x71, 0x34, 0x72, 0x68, + 0x32, 0xcb, 0xf7, 0xa1, 0xa0, 0xb4, 0x69, 0x4d, 0xfa, 0x0d, 0xbd, 0x81, 0x07, 0x51, 0x19, 0x7b, + 0x4c, 0x3d, 0x3c, 0xa3, 0x3f, 0x90, 0xcc, 0xb8, 0x3d, 0xcb, 0x9d, 0x83, 0x88, 0xf4, 0x73, 0x0d, + 0x57, 0x03, 0x77, 0x10, 0xde, 0xb4, 0xdc, 0x9d, 0x42, 0xf1, 0x95, 0xba, 0x93, 0xd0, 0x11, 0x94, + 0x63, 0xdb, 0x74, 0x47, 0x99, 0xcb, 0x44, 0xdf, 0x5d, 0x89, 0xe5, 0xda, 0xec, 0x24, 0x0b, 0x35, + 0xa1, 0xc4, 0xfc, 0x31, 0xff, 0x1e, 0x87, 0x44, 0xf6, 0x51, 0xb6, 0xe2, 0xf7, 0xee, 0x1f, 0x05, + 0xb8, 0x77, 0x2e, 0x4c, 0x41, 0x9f, 0x42, 0x51, 0x73, 0xe9, 0x32, 0x0f, 0xf3, 0xc6, 0x69, 0x51, + 0xba, 0x44, 0x84, 0x47, 0xcf, 0xa0, 0xe4, 0x4c, 0x31, 0xf5, 0x6c, 0xaa, 0x36, 0xaf, 0xdc, 0xaf, + 0xac, 0xaf, 0xda, 0xc5, 0x81, 0x58, 0x1b, 0x1e, 0x5b, 0x45, 0x19, 0x1c, 0xba, 0xe8, 0x29, 0xec, + 0x52, 0x8f, 0x72, 0x8a, 0x67, 0x7a, 0xcb, 0x1b, 0xbb, 0xd2, 0xd6, 0xaa, 0x5e, 0x55, 0xbb, 0x8d, + 0x3e, 0x06, 0xb9, 0xf7, 0xca, 0xd0, 0x08, 0xb9, 0x2d, 0x91, 0x7b, 0x22, 0x20, 0x3d, 0xd2, 0x58, + 0x0b, 0xaa, 0x29, 0x2c, 0x75, 0x1b, 0x77, 0xf3, 0xda, 0xd5, 0x99, 0x94, 0x59, 0xc3, 0xe3, 0x7e, + 0x5d, 0x68, 0x5f, 0x5f, 0xb5, 0x2b, 0x67, 0x11, 0xd5, 0xf0, 0xd8, 0xaa, 0xc4, 0xbc, 0x43, 0x17, + 0x9d, 0xc1, 0x5e, 0x8a, 0x53, 0xdc, 0xfb, 0x8d, 0x7b, 0x92, 0xb5, 0x69, 0xaa, 0x8f, 0x82, 0x19, + 0x7d, 0x14, 0xcc, 0x8b, 0xe8, 0xa3, 0xd0, 0x2f, 0x09, 0xda, 0xb7, 0xbf, 0xb5, 0x0d, 0xab, 0x1a, + 0x73, 0x89, 0x28, 0xfa, 0x02, 0xf6, 0x3c, 0xb2, 0xe2, 0x76, 0x3c, 0x95, 0xac, 0x51, 0xb8, 0xd5, + 0x1c, 0xef, 0x8a, 0xb4, 0xe4, 0x4a, 0x40, 0x2f, 0x01, 0x52, 0x1c, 0xc5, 0x5b, 0x71, 0xa4, 0x32, + 0x84, 0x10, 0xd9, 0x56, 0x8a, 0xa4, 0x74, 0x3b, 0x21, 0x22, 0x2d, 0x25, 0x64, 0x00, 0xad, 0xf4, + 0xd8, 0x26, 0x7c, 0xf1, 0x04, 0x97, 0xe5, 0x66, 0x3d, 0x4a, 0x26, 0x38, 0xc9, 0xd6, 0xb3, 0x7c, + 0xe3, 0x7d, 0x02, 0x1f, 0x78, 0x9f, 0x7c, 0x05, 0x4f, 0x32, 0xf7, 0xc9, 0x06, 0x7f, 0x2c, 0xaf, + 0x22, 0xe5, 0x75, 0x52, 0x17, 0x4c, 0x96, 0x28, 0xd2, 0x18, 0x1d, 0xc4, 0x50, 0x7e, 0xa5, 0x99, + 0x3d, 0xc5, 0x6c, 0xda, 0xd8, 0xe9, 0x18, 0x87, 0x3b, 0xea, 0x20, 0xaa, 0xaf, 0x37, 0x3b, 0xc5, + 0x6c, 0x8a, 0x1e, 0x42, 0x09, 0x07, 0x81, 0x82, 0x54, 0x25, 0xa4, 0x88, 0x83, 0x40, 0x84, 0xfa, + 0x5f, 0xbe, 0x5b, 0xb7, 0x8c, 0xf7, 0xeb, 0x96, 0xf1, 0xfb, 0xba, 0x65, 0xbc, 0xbd, 0x6e, 0x6d, + 0xbd, 0xbf, 0x6e, 0x6d, 0xfd, 0x72, 0xdd, 0xda, 0xfa, 0xf6, 0xc5, 0x84, 0xf2, 0xe9, 0x62, 0x64, + 0x3a, 0xfe, 0xbc, 0xe7, 0xf8, 0x73, 0xc2, 0x47, 0x63, 0x9e, 0x3c, 0xa8, 0xff, 0xa5, 0xcd, 0x3f, + 0xad, 0x51, 0x41, 0xae, 0xbf, 0xf8, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xec, 0x26, 0xcf, 0x93, 0x84, + 0x09, 0x00, 0x00, +} + +func (m *LegacyABCIResponses) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *LegacyABCIResponses) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *LegacyABCIResponses) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.BeginBlock != nil { + { + size, err := m.BeginBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.EndBlock != nil { + { + size, err := m.EndBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.DeliverTxs) > 0 { + for iNdEx := len(m.DeliverTxs) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DeliverTxs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ResponseBeginBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseBeginBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseBeginBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ResponseEndBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseEndBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseEndBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.ConsensusParamUpdates != nil { + { + size, err := m.ConsensusParamUpdates.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.ValidatorUpdates) > 0 { + for iNdEx := len(m.ValidatorUpdates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ValidatorUpdates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ValidatorsInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorsInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValidatorsInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.LastHeightChanged != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastHeightChanged)) + i-- + dAtA[i] = 0x10 + } + if m.ValidatorSet != nil { + { + size, err := m.ValidatorSet.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ConsensusParamsInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ConsensusParamsInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsensusParamsInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.LastHeightChanged != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastHeightChanged)) + i-- + dAtA[i] = 0x10 + } + { + size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ABCIResponsesInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ABCIResponsesInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ABCIResponsesInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResponseFinalizeBlock != nil { + { + size, err := m.ResponseFinalizeBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if m.LegacyAbciResponses != nil { + { + size, err := m.LegacyAbciResponses.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Version) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Version) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Version) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Software) > 0 { + i -= len(m.Software) + copy(dAtA[i:], m.Software) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Software))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Consensus.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *State) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *State) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *State) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.InitialHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.InitialHeight)) + i-- + dAtA[i] = 0x70 + } + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x6a + } + if len(m.LastResultsHash) > 0 { + i -= len(m.LastResultsHash) + copy(dAtA[i:], m.LastResultsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LastResultsHash))) + i-- + dAtA[i] = 0x62 + } + if m.LastHeightConsensusParamsChanged != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastHeightConsensusParamsChanged)) + i-- + dAtA[i] = 0x58 + } + { + size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + if m.LastHeightValidatorsChanged != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastHeightValidatorsChanged)) + i-- + dAtA[i] = 0x48 + } + if m.LastValidators != nil { + { + size, err := m.LastValidators.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + if m.Validators != nil { + { + size, err := m.Validators.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + if m.NextValidators != nil { + { + size, err := m.NextValidators.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + n13, err13 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.LastBlockTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastBlockTime):]) + if err13 != nil { + return 0, err13 + } + i -= n13 + i = encodeVarintTypes(dAtA, i, uint64(n13)) + i-- + dAtA[i] = 0x2a + { + size, err := m.LastBlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.LastBlockHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastBlockHeight)) + i-- + dAtA[i] = 0x18 + } + if len(m.ChainID) > 0 { + i -= len(m.ChainID) + copy(dAtA[i:], m.ChainID) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainID))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Version.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *LegacyABCIResponses) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.DeliverTxs) > 0 { + for _, e := range m.DeliverTxs { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if m.EndBlock != nil { + l = m.EndBlock.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.BeginBlock != nil { + l = m.BeginBlock.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponseBeginBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ResponseEndBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ValidatorUpdates) > 0 { + for _, e := range m.ValidatorUpdates { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if m.ConsensusParamUpdates != nil { + l = m.ConsensusParamUpdates.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ValidatorsInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ValidatorSet != nil { + l = m.ValidatorSet.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.LastHeightChanged != 0 { + n += 1 + sovTypes(uint64(m.LastHeightChanged)) + } + return n +} + +func (m *ConsensusParamsInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ConsensusParams.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.LastHeightChanged != 0 { + n += 1 + sovTypes(uint64(m.LastHeightChanged)) + } + return n +} + +func (m *ABCIResponsesInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.LegacyAbciResponses != nil { + l = m.LegacyAbciResponses.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.ResponseFinalizeBlock != nil { + l = m.ResponseFinalizeBlock.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Version) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Consensus.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.Software) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *State) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Version.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.ChainID) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.LastBlockHeight != 0 { + n += 1 + sovTypes(uint64(m.LastBlockHeight)) + } + l = m.LastBlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastBlockTime) + n += 1 + l + sovTypes(uint64(l)) + if m.NextValidators != nil { + l = m.NextValidators.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.Validators != nil { + l = m.Validators.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.LastValidators != nil { + l = m.LastValidators.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.LastHeightValidatorsChanged != 0 { + n += 1 + sovTypes(uint64(m.LastHeightValidatorsChanged)) + } + l = m.ConsensusParams.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.LastHeightConsensusParamsChanged != 0 { + n += 1 + sovTypes(uint64(m.LastHeightConsensusParamsChanged)) + } + l = len(m.LastResultsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.InitialHeight != 0 { + n += 1 + sovTypes(uint64(m.InitialHeight)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *LegacyABCIResponses) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: LegacyABCIResponses: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: LegacyABCIResponses: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeliverTxs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DeliverTxs = append(m.DeliverTxs, &types.ExecTxResult{}) + if err := m.DeliverTxs[len(m.DeliverTxs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EndBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.EndBlock == nil { + m.EndBlock = &ResponseEndBlock{} + } + if err := m.EndBlock.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BeginBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BeginBlock == nil { + m.BeginBlock = &ResponseBeginBlock{} + } + if err := m.BeginBlock.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseBeginBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseBeginBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseBeginBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, types.Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseEndBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseEndBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseEndBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorUpdates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorUpdates = append(m.ValidatorUpdates, types.ValidatorUpdate{}) + if err := m.ValidatorUpdates[len(m.ValidatorUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParamUpdates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ConsensusParamUpdates == nil { + m.ConsensusParamUpdates = &types1.ConsensusParams{} + } + if err := m.ConsensusParamUpdates.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, types.Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorsInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorsInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorsInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSet", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ValidatorSet == nil { + m.ValidatorSet = &types1.ValidatorSet{} + } + if err := m.ValidatorSet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastHeightChanged", wireType) + } + m.LastHeightChanged = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastHeightChanged |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ConsensusParamsInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ConsensusParamsInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsensusParamsInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastHeightChanged", wireType) + } + m.LastHeightChanged = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastHeightChanged |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ABCIResponsesInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ABCIResponsesInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ABCIResponsesInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LegacyAbciResponses", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.LegacyAbciResponses == nil { + m.LegacyAbciResponses = &LegacyABCIResponses{} + } + if err := m.LegacyAbciResponses.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResponseFinalizeBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ResponseFinalizeBlock == nil { + m.ResponseFinalizeBlock = &types.ResponseFinalizeBlock{} + } + if err := m.ResponseFinalizeBlock.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Version) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Version: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Version: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Consensus", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Consensus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Software", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Software = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *State) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: State: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: State: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockHeight", wireType) + } + m.LastBlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastBlockHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastBlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.LastBlockTime, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NextValidators == nil { + m.NextValidators = &types1.ValidatorSet{} + } + if err := m.NextValidators.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Validators == nil { + m.Validators = &types1.ValidatorSet{} + } + if err := m.Validators.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastValidators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.LastValidators == nil { + m.LastValidators = &types1.ValidatorSet{} + } + if err := m.LastValidators.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastHeightValidatorsChanged", wireType) + } + m.LastHeightValidatorsChanged = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastHeightValidatorsChanged |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 11: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastHeightConsensusParamsChanged", wireType) + } + m.LastHeightConsensusParamsChanged = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastHeightConsensusParamsChanged |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastResultsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LastResultsHash = append(m.LastResultsHash[:0], dAtA[iNdEx:postIndex]...) + if m.LastResultsHash == nil { + m.LastResultsHash = []byte{} + } + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + case 14: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field InitialHeight", wireType) + } + m.InitialHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.InitialHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/state/types.proto b/proto/tendermint/state/types.proto new file mode 100644 index 0000000..f8baff2 --- /dev/null +++ b/proto/tendermint/state/types.proto @@ -0,0 +1,96 @@ +syntax = "proto3"; +package tendermint.state; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/state"; + +import "gogoproto/gogo.proto"; +import "tendermint/abci/types.proto"; +import "tendermint/types/types.proto"; +import "tendermint/types/validator.proto"; +import "tendermint/types/params.proto"; +import "tendermint/version/types.proto"; +import "google/protobuf/timestamp.proto"; + +// LegacyABCIResponses retains the responses +// of the legacy ABCI calls during block processing. +// Note ReponseDeliverTx is renamed to ExecTxResult but they are semantically the same +// Kept for backwards compatibility for versions prior to v0.38 +message LegacyABCIResponses { + repeated tendermint.abci.ExecTxResult deliver_txs = 1; + ResponseEndBlock end_block = 2; + ResponseBeginBlock begin_block = 3; +} + +// ResponseBeginBlock is kept for backwards compatibility for versions prior to v0.38 +message ResponseBeginBlock { + repeated tendermint.abci.Event events = 1 + [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; +} + +// ResponseEndBlock is kept for backwards compatibility for versions prior to v0.38 +message ResponseEndBlock { + repeated tendermint.abci.ValidatorUpdate validator_updates = 1 [(gogoproto.nullable) = false]; + tendermint.types.ConsensusParams consensus_param_updates = 2; + repeated tendermint.abci.Event events = 3 + [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; +} + +// ValidatorsInfo represents the latest validator set, or the last height it changed +message ValidatorsInfo { + tendermint.types.ValidatorSet validator_set = 1; + int64 last_height_changed = 2; +} + +// ConsensusParamsInfo represents the latest consensus params, or the last height it changed +message ConsensusParamsInfo { + tendermint.types.ConsensusParams consensus_params = 1 [(gogoproto.nullable) = false]; + int64 last_height_changed = 2; +} + +message ABCIResponsesInfo { + LegacyABCIResponses legacy_abci_responses = 1; + int64 height = 2; + abci.ResponseFinalizeBlock response_finalize_block = 3; +} + +message Version { + tendermint.version.Consensus consensus = 1 [(gogoproto.nullable) = false]; + string software = 2; +} + +message State { + Version version = 1 [(gogoproto.nullable) = false]; + + // immutable + string chain_id = 2 [(gogoproto.customname) = "ChainID"]; + int64 initial_height = 14; + + // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist) + int64 last_block_height = 3; + tendermint.types.BlockID last_block_id = 4 + [(gogoproto.nullable) = false, (gogoproto.customname) = "LastBlockID"]; + google.protobuf.Timestamp last_block_time = 5 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + + // LastValidators is used to validate block.LastCommit. + // Validators are persisted to the database separately every time they change, + // so we can query for historical validator sets. + // Note that if s.LastBlockHeight causes a valset change, + // we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1 + 1 + // Extra +1 due to nextValSet delay. + tendermint.types.ValidatorSet next_validators = 6; + tendermint.types.ValidatorSet validators = 7; + tendermint.types.ValidatorSet last_validators = 8; + int64 last_height_validators_changed = 9; + + // Consensus parameters used for validating blocks. + // Changes returned by EndBlock and updated after Commit. + tendermint.types.ConsensusParams consensus_params = 10 [(gogoproto.nullable) = false]; + int64 last_height_consensus_params_changed = 11; + + // Merkle root of the results from executing prev block + bytes last_results_hash = 12; + + // the latest AppHash we've received from calling abci.Commit() + bytes app_hash = 13; +} diff --git a/proto/tendermint/statesync/message.go b/proto/tendermint/statesync/message.go new file mode 100644 index 0000000..63d6d18 --- /dev/null +++ b/proto/tendermint/statesync/message.go @@ -0,0 +1,59 @@ +package statesync + +import ( + "fmt" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cometbft/cometbft/p2p" +) + +var _ p2p.Wrapper = &ChunkRequest{} +var _ p2p.Wrapper = &ChunkResponse{} +var _ p2p.Wrapper = &SnapshotsRequest{} +var _ p2p.Wrapper = &SnapshotsResponse{} + +func (m *SnapshotsResponse) Wrap() proto.Message { + sm := &Message{} + sm.Sum = &Message_SnapshotsResponse{SnapshotsResponse: m} + return sm +} + +func (m *SnapshotsRequest) Wrap() proto.Message { + sm := &Message{} + sm.Sum = &Message_SnapshotsRequest{SnapshotsRequest: m} + return sm +} + +func (m *ChunkResponse) Wrap() proto.Message { + sm := &Message{} + sm.Sum = &Message_ChunkResponse{ChunkResponse: m} + return sm +} + +func (m *ChunkRequest) Wrap() proto.Message { + sm := &Message{} + sm.Sum = &Message_ChunkRequest{ChunkRequest: m} + return sm +} + +// Unwrap implements the p2p Wrapper interface and unwraps a wrapped state sync +// proto message. +func (m *Message) Unwrap() (proto.Message, error) { + switch msg := m.Sum.(type) { + case *Message_ChunkRequest: + return m.GetChunkRequest(), nil + + case *Message_ChunkResponse: + return m.GetChunkResponse(), nil + + case *Message_SnapshotsRequest: + return m.GetSnapshotsRequest(), nil + + case *Message_SnapshotsResponse: + return m.GetSnapshotsResponse(), nil + + default: + return nil, fmt.Errorf("unknown message: %T", msg) + } +} diff --git a/proto/tendermint/statesync/types.pb.go b/proto/tendermint/statesync/types.pb.go new file mode 100644 index 0000000..1a9ed12 --- /dev/null +++ b/proto/tendermint/statesync/types.pb.go @@ -0,0 +1,1629 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/statesync/types.proto + +package statesync + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Message struct { + // Types that are valid to be assigned to Sum: + // + // *Message_SnapshotsRequest + // *Message_SnapshotsResponse + // *Message_ChunkRequest + // *Message_ChunkResponse + Sum isMessage_Sum `protobuf_oneof:"sum"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} +func (*Message) Descriptor() ([]byte, []int) { + return fileDescriptor_a1c2869546ca7914, []int{0} +} +func (m *Message) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Message.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) +} +func (m *Message) XXX_Size() int { + return m.Size() +} +func (m *Message) XXX_DiscardUnknown() { + xxx_messageInfo_Message.DiscardUnknown(m) +} + +var xxx_messageInfo_Message proto.InternalMessageInfo + +type isMessage_Sum interface { + isMessage_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Message_SnapshotsRequest struct { + SnapshotsRequest *SnapshotsRequest `protobuf:"bytes,1,opt,name=snapshots_request,json=snapshotsRequest,proto3,oneof" json:"snapshots_request,omitempty"` +} +type Message_SnapshotsResponse struct { + SnapshotsResponse *SnapshotsResponse `protobuf:"bytes,2,opt,name=snapshots_response,json=snapshotsResponse,proto3,oneof" json:"snapshots_response,omitempty"` +} +type Message_ChunkRequest struct { + ChunkRequest *ChunkRequest `protobuf:"bytes,3,opt,name=chunk_request,json=chunkRequest,proto3,oneof" json:"chunk_request,omitempty"` +} +type Message_ChunkResponse struct { + ChunkResponse *ChunkResponse `protobuf:"bytes,4,opt,name=chunk_response,json=chunkResponse,proto3,oneof" json:"chunk_response,omitempty"` +} + +func (*Message_SnapshotsRequest) isMessage_Sum() {} +func (*Message_SnapshotsResponse) isMessage_Sum() {} +func (*Message_ChunkRequest) isMessage_Sum() {} +func (*Message_ChunkResponse) isMessage_Sum() {} + +func (m *Message) GetSum() isMessage_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Message) GetSnapshotsRequest() *SnapshotsRequest { + if x, ok := m.GetSum().(*Message_SnapshotsRequest); ok { + return x.SnapshotsRequest + } + return nil +} + +func (m *Message) GetSnapshotsResponse() *SnapshotsResponse { + if x, ok := m.GetSum().(*Message_SnapshotsResponse); ok { + return x.SnapshotsResponse + } + return nil +} + +func (m *Message) GetChunkRequest() *ChunkRequest { + if x, ok := m.GetSum().(*Message_ChunkRequest); ok { + return x.ChunkRequest + } + return nil +} + +func (m *Message) GetChunkResponse() *ChunkResponse { + if x, ok := m.GetSum().(*Message_ChunkResponse); ok { + return x.ChunkResponse + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Message) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Message_SnapshotsRequest)(nil), + (*Message_SnapshotsResponse)(nil), + (*Message_ChunkRequest)(nil), + (*Message_ChunkResponse)(nil), + } +} + +type SnapshotsRequest struct { +} + +func (m *SnapshotsRequest) Reset() { *m = SnapshotsRequest{} } +func (m *SnapshotsRequest) String() string { return proto.CompactTextString(m) } +func (*SnapshotsRequest) ProtoMessage() {} +func (*SnapshotsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_a1c2869546ca7914, []int{1} +} +func (m *SnapshotsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SnapshotsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SnapshotsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SnapshotsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SnapshotsRequest.Merge(m, src) +} +func (m *SnapshotsRequest) XXX_Size() int { + return m.Size() +} +func (m *SnapshotsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SnapshotsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SnapshotsRequest proto.InternalMessageInfo + +type SnapshotsResponse struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"` + Chunks uint32 `protobuf:"varint,3,opt,name=chunks,proto3" json:"chunks,omitempty"` + Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"` + Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"` +} + +func (m *SnapshotsResponse) Reset() { *m = SnapshotsResponse{} } +func (m *SnapshotsResponse) String() string { return proto.CompactTextString(m) } +func (*SnapshotsResponse) ProtoMessage() {} +func (*SnapshotsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_a1c2869546ca7914, []int{2} +} +func (m *SnapshotsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SnapshotsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SnapshotsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SnapshotsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SnapshotsResponse.Merge(m, src) +} +func (m *SnapshotsResponse) XXX_Size() int { + return m.Size() +} +func (m *SnapshotsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SnapshotsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SnapshotsResponse proto.InternalMessageInfo + +func (m *SnapshotsResponse) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *SnapshotsResponse) GetFormat() uint32 { + if m != nil { + return m.Format + } + return 0 +} + +func (m *SnapshotsResponse) GetChunks() uint32 { + if m != nil { + return m.Chunks + } + return 0 +} + +func (m *SnapshotsResponse) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *SnapshotsResponse) GetMetadata() []byte { + if m != nil { + return m.Metadata + } + return nil +} + +type ChunkRequest struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"` + Index uint32 `protobuf:"varint,3,opt,name=index,proto3" json:"index,omitempty"` +} + +func (m *ChunkRequest) Reset() { *m = ChunkRequest{} } +func (m *ChunkRequest) String() string { return proto.CompactTextString(m) } +func (*ChunkRequest) ProtoMessage() {} +func (*ChunkRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_a1c2869546ca7914, []int{3} +} +func (m *ChunkRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ChunkRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ChunkRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ChunkRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_ChunkRequest.Merge(m, src) +} +func (m *ChunkRequest) XXX_Size() int { + return m.Size() +} +func (m *ChunkRequest) XXX_DiscardUnknown() { + xxx_messageInfo_ChunkRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_ChunkRequest proto.InternalMessageInfo + +func (m *ChunkRequest) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ChunkRequest) GetFormat() uint32 { + if m != nil { + return m.Format + } + return 0 +} + +func (m *ChunkRequest) GetIndex() uint32 { + if m != nil { + return m.Index + } + return 0 +} + +type ChunkResponse struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"` + Index uint32 `protobuf:"varint,3,opt,name=index,proto3" json:"index,omitempty"` + Chunk []byte `protobuf:"bytes,4,opt,name=chunk,proto3" json:"chunk,omitempty"` + Missing bool `protobuf:"varint,5,opt,name=missing,proto3" json:"missing,omitempty"` +} + +func (m *ChunkResponse) Reset() { *m = ChunkResponse{} } +func (m *ChunkResponse) String() string { return proto.CompactTextString(m) } +func (*ChunkResponse) ProtoMessage() {} +func (*ChunkResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_a1c2869546ca7914, []int{4} +} +func (m *ChunkResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ChunkResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ChunkResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ChunkResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ChunkResponse.Merge(m, src) +} +func (m *ChunkResponse) XXX_Size() int { + return m.Size() +} +func (m *ChunkResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ChunkResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ChunkResponse proto.InternalMessageInfo + +func (m *ChunkResponse) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ChunkResponse) GetFormat() uint32 { + if m != nil { + return m.Format + } + return 0 +} + +func (m *ChunkResponse) GetIndex() uint32 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *ChunkResponse) GetChunk() []byte { + if m != nil { + return m.Chunk + } + return nil +} + +func (m *ChunkResponse) GetMissing() bool { + if m != nil { + return m.Missing + } + return false +} + +func init() { + proto.RegisterType((*Message)(nil), "tendermint.statesync.Message") + proto.RegisterType((*SnapshotsRequest)(nil), "tendermint.statesync.SnapshotsRequest") + proto.RegisterType((*SnapshotsResponse)(nil), "tendermint.statesync.SnapshotsResponse") + proto.RegisterType((*ChunkRequest)(nil), "tendermint.statesync.ChunkRequest") + proto.RegisterType((*ChunkResponse)(nil), "tendermint.statesync.ChunkResponse") +} + +func init() { proto.RegisterFile("tendermint/statesync/types.proto", fileDescriptor_a1c2869546ca7914) } + +var fileDescriptor_a1c2869546ca7914 = []byte{ + // 397 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0x3f, 0x6b, 0xdb, 0x40, + 0x1c, 0x95, 0xfc, 0x9f, 0x5f, 0xad, 0x62, 0x1f, 0xa6, 0x88, 0x0e, 0xc2, 0xa8, 0xd0, 0x76, 0x92, + 0xa0, 0x1d, 0xba, 0xbb, 0x8b, 0x0b, 0xed, 0xd0, 0x6b, 0x03, 0x21, 0x4b, 0x38, 0xcb, 0x67, 0x49, + 0x04, 0x9d, 0x14, 0xfd, 0x4e, 0x10, 0x7f, 0x80, 0x4c, 0x59, 0xf2, 0xb1, 0x32, 0x7a, 0x0c, 0x99, + 0x82, 0xfd, 0x45, 0x82, 0x4e, 0xb2, 0xac, 0x38, 0x26, 0x21, 0x90, 0xed, 0xde, 0xd3, 0xd3, 0xbb, + 0xf7, 0x1e, 0x1c, 0x8c, 0x25, 0x17, 0x73, 0x9e, 0x46, 0xa1, 0x90, 0x2e, 0x4a, 0x26, 0x39, 0x2e, + 0x85, 0xe7, 0xca, 0x65, 0xc2, 0xd1, 0x49, 0xd2, 0x58, 0xc6, 0x64, 0xb4, 0x53, 0x38, 0x95, 0xc2, + 0xbe, 0x6b, 0x40, 0xf7, 0x0f, 0x47, 0x64, 0x3e, 0x27, 0x47, 0x30, 0x44, 0xc1, 0x12, 0x0c, 0x62, + 0x89, 0xa7, 0x29, 0x3f, 0xcf, 0x38, 0x4a, 0x53, 0x1f, 0xeb, 0x5f, 0xdf, 0x7d, 0xfb, 0xec, 0x1c, + 0xfa, 0xdb, 0xf9, 0xb7, 0x95, 0xd3, 0x42, 0x3d, 0xd5, 0xe8, 0x00, 0xf7, 0x38, 0x72, 0x0c, 0xa4, + 0x6e, 0x8b, 0x49, 0x2c, 0x90, 0x9b, 0x0d, 0xe5, 0xfb, 0xe5, 0x45, 0xdf, 0x42, 0x3e, 0xd5, 0xe8, + 0x10, 0xf7, 0x49, 0xf2, 0x0b, 0x0c, 0x2f, 0xc8, 0xc4, 0x59, 0x15, 0xb6, 0xa9, 0x4c, 0xed, 0xc3, + 0xa6, 0x3f, 0x73, 0xe9, 0x2e, 0x68, 0xdf, 0xab, 0x61, 0xf2, 0x1b, 0xde, 0x6f, 0xad, 0xca, 0x80, + 0x2d, 0xe5, 0xf5, 0xe9, 0x59, 0xaf, 0x2a, 0x9c, 0xe1, 0xd5, 0x89, 0x49, 0x1b, 0x9a, 0x98, 0x45, + 0x36, 0x81, 0xc1, 0xfe, 0x42, 0xf6, 0x95, 0x0e, 0xc3, 0x27, 0xf5, 0xc8, 0x07, 0xe8, 0x04, 0x3c, + 0xf4, 0x83, 0x62, 0xef, 0x16, 0x2d, 0x51, 0xce, 0x2f, 0xe2, 0x34, 0x62, 0x52, 0xed, 0x65, 0xd0, + 0x12, 0xe5, 0xbc, 0xba, 0x11, 0x55, 0x65, 0x83, 0x96, 0x88, 0x10, 0x68, 0x05, 0x0c, 0x03, 0x15, + 0xbe, 0x4f, 0xd5, 0x99, 0x7c, 0x84, 0x5e, 0xc4, 0x25, 0x9b, 0x33, 0xc9, 0xcc, 0xb6, 0xe2, 0x2b, + 0x6c, 0xff, 0x87, 0x7e, 0x7d, 0x96, 0x57, 0xe7, 0x18, 0x41, 0x3b, 0x14, 0x73, 0x7e, 0x51, 0xc6, + 0x28, 0x80, 0x7d, 0xa9, 0x83, 0xf1, 0x68, 0xa1, 0xb7, 0xf1, 0xcd, 0x59, 0xd5, 0xb3, 0xac, 0x57, + 0x00, 0x62, 0x42, 0x37, 0x0a, 0x11, 0x43, 0xe1, 0xab, 0x7a, 0x3d, 0xba, 0x85, 0x93, 0xbf, 0x37, + 0x6b, 0x4b, 0x5f, 0xad, 0x2d, 0xfd, 0x7e, 0x6d, 0xe9, 0xd7, 0x1b, 0x4b, 0x5b, 0x6d, 0x2c, 0xed, + 0x76, 0x63, 0x69, 0x27, 0x3f, 0xfc, 0x50, 0x06, 0xd9, 0xcc, 0xf1, 0xe2, 0xc8, 0xf5, 0xe2, 0x88, + 0xcb, 0xd9, 0x42, 0xee, 0x0e, 0xea, 0xc1, 0xb8, 0x87, 0x5e, 0xd4, 0xac, 0xa3, 0xbe, 0x7d, 0x7f, + 0x08, 0x00, 0x00, 0xff, 0xff, 0x04, 0xbe, 0xb0, 0x90, 0x70, 0x03, 0x00, 0x00, +} + +func (m *Message) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Message) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Message_SnapshotsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SnapshotsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SnapshotsRequest != nil { + { + size, err := m.SnapshotsRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Message_SnapshotsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_SnapshotsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.SnapshotsResponse != nil { + { + size, err := m.SnapshotsResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *Message_ChunkRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_ChunkRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ChunkRequest != nil { + { + size, err := m.ChunkRequest.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} +func (m *Message_ChunkResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Message_ChunkResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.ChunkResponse != nil { + { + size, err := m.ChunkResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + return len(dAtA) - i, nil +} +func (m *SnapshotsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SnapshotsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SnapshotsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *SnapshotsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SnapshotsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SnapshotsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Metadata) > 0 { + i -= len(m.Metadata) + copy(dAtA[i:], m.Metadata) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Metadata))) + i-- + dAtA[i] = 0x2a + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x22 + } + if m.Chunks != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Chunks)) + i-- + dAtA[i] = 0x18 + } + if m.Format != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Format)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ChunkRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ChunkRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ChunkRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x18 + } + if m.Format != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Format)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ChunkResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ChunkResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ChunkResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Missing { + i-- + if m.Missing { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + if len(m.Chunk) > 0 { + i -= len(m.Chunk) + copy(dAtA[i:], m.Chunk) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Chunk))) + i-- + dAtA[i] = 0x22 + } + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x18 + } + if m.Format != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Format)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Message) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Message_SnapshotsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SnapshotsRequest != nil { + l = m.SnapshotsRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_SnapshotsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SnapshotsResponse != nil { + l = m.SnapshotsResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_ChunkRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChunkRequest != nil { + l = m.ChunkRequest.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *Message_ChunkResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChunkResponse != nil { + l = m.ChunkResponse.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} +func (m *SnapshotsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *SnapshotsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Format != 0 { + n += 1 + sovTypes(uint64(m.Format)) + } + if m.Chunks != 0 { + n += 1 + sovTypes(uint64(m.Chunks)) + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Metadata) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ChunkRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Format != 0 { + n += 1 + sovTypes(uint64(m.Format)) + } + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + return n +} + +func (m *ChunkResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Format != 0 { + n += 1 + sovTypes(uint64(m.Format)) + } + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + l = len(m.Chunk) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Missing { + n += 2 + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Message) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Message: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SnapshotsRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SnapshotsRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SnapshotsRequest{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SnapshotsResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &SnapshotsResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_SnapshotsResponse{v} + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChunkRequest", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ChunkRequest{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_ChunkRequest{v} + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChunkResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &ChunkResponse{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Message_ChunkResponse{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SnapshotsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SnapshotsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SnapshotsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SnapshotsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SnapshotsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SnapshotsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType) + } + m.Format = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Format |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunks", wireType) + } + m.Chunks = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Chunks |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Metadata = append(m.Metadata[:0], dAtA[iNdEx:postIndex]...) + if m.Metadata == nil { + m.Metadata = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ChunkRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ChunkRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ChunkRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType) + } + m.Format = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Format |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ChunkResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ChunkResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ChunkResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType) + } + m.Format = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Format |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Chunk = append(m.Chunk[:0], dAtA[iNdEx:postIndex]...) + if m.Chunk == nil { + m.Chunk = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Missing", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Missing = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/statesync/types.proto b/proto/tendermint/statesync/types.proto new file mode 100644 index 0000000..5e68440 --- /dev/null +++ b/proto/tendermint/statesync/types.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; +package tendermint.statesync; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/statesync"; + +message Message { + oneof sum { + SnapshotsRequest snapshots_request = 1; + SnapshotsResponse snapshots_response = 2; + ChunkRequest chunk_request = 3; + ChunkResponse chunk_response = 4; + } +} + +message SnapshotsRequest {} + +message SnapshotsResponse { + uint64 height = 1; + uint32 format = 2; + uint32 chunks = 3; + bytes hash = 4; + bytes metadata = 5; +} + +message ChunkRequest { + uint64 height = 1; + uint32 format = 2; + uint32 index = 3; +} + +message ChunkResponse { + uint64 height = 1; + uint32 format = 2; + uint32 index = 3; + bytes chunk = 4; + bool missing = 5; +} diff --git a/proto/tendermint/store/types.pb.go b/proto/tendermint/store/types.pb.go new file mode 100644 index 0000000..08d72b3 --- /dev/null +++ b/proto/tendermint/store/types.pb.go @@ -0,0 +1,334 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/store/types.proto + +package store + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type BlockStoreState struct { + Base int64 `protobuf:"varint,1,opt,name=base,proto3" json:"base,omitempty"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` +} + +func (m *BlockStoreState) Reset() { *m = BlockStoreState{} } +func (m *BlockStoreState) String() string { return proto.CompactTextString(m) } +func (*BlockStoreState) ProtoMessage() {} +func (*BlockStoreState) Descriptor() ([]byte, []int) { + return fileDescriptor_ff9e53a0a74267f7, []int{0} +} +func (m *BlockStoreState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockStoreState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockStoreState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockStoreState) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockStoreState.Merge(m, src) +} +func (m *BlockStoreState) XXX_Size() int { + return m.Size() +} +func (m *BlockStoreState) XXX_DiscardUnknown() { + xxx_messageInfo_BlockStoreState.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockStoreState proto.InternalMessageInfo + +func (m *BlockStoreState) GetBase() int64 { + if m != nil { + return m.Base + } + return 0 +} + +func (m *BlockStoreState) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func init() { + proto.RegisterType((*BlockStoreState)(nil), "tendermint.store.BlockStoreState") +} + +func init() { proto.RegisterFile("tendermint/store/types.proto", fileDescriptor_ff9e53a0a74267f7) } + +var fileDescriptor_ff9e53a0a74267f7 = []byte{ + // 171 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x2e, 0xc9, 0x2f, 0x4a, 0xd5, 0x2f, 0xa9, 0x2c, + 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0xc8, 0xea, 0x81, 0x65, 0x95, + 0x6c, 0xb9, 0xf8, 0x9d, 0x72, 0xf2, 0x93, 0xb3, 0x83, 0x41, 0xbc, 0xe0, 0x92, 0xc4, 0x92, 0x54, + 0x21, 0x21, 0x2e, 0x96, 0xa4, 0xc4, 0xe2, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xe6, 0x20, 0x30, + 0x5b, 0x48, 0x8c, 0x8b, 0x2d, 0x23, 0x35, 0x33, 0x3d, 0xa3, 0x44, 0x82, 0x09, 0x2c, 0x0a, 0xe5, + 0x39, 0xf9, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, + 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x71, 0x7a, 0x66, + 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x72, 0x7e, 0x6e, 0x6a, 0x49, 0x52, 0x5a, + 0x09, 0x82, 0x01, 0x76, 0x8e, 0x3e, 0xba, 0x5b, 0x93, 0xd8, 0xc0, 0xe2, 0xc6, 0x80, 0x00, 0x00, + 0x00, 0xff, 0xff, 0xb7, 0x2b, 0x34, 0x2a, 0xc6, 0x00, 0x00, 0x00, +} + +func (m *BlockStoreState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockStoreState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockStoreState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if m.Base != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Base)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *BlockStoreState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Base != 0 { + n += 1 + sovTypes(uint64(m.Base)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *BlockStoreState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockStoreState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockStoreState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Base", wireType) + } + m.Base = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Base |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/store/types.proto b/proto/tendermint/store/types.proto new file mode 100644 index 0000000..1c9a8b6 --- /dev/null +++ b/proto/tendermint/store/types.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; +package tendermint.store; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/store"; + +message BlockStoreState { + int64 base = 1; + int64 height = 2; +} diff --git a/proto/tendermint/types/block.pb.go b/proto/tendermint/types/block.pb.go new file mode 100644 index 0000000..2ca6742 --- /dev/null +++ b/proto/tendermint/types/block.pb.go @@ -0,0 +1,490 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/block.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Block struct { + Header Header `protobuf:"bytes,1,opt,name=header,proto3" json:"header"` + Data Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` + Evidence EvidenceList `protobuf:"bytes,3,opt,name=evidence,proto3" json:"evidence"` + LastCommit *Commit `protobuf:"bytes,4,opt,name=last_commit,json=lastCommit,proto3" json:"last_commit,omitempty"` +} + +func (m *Block) Reset() { *m = Block{} } +func (m *Block) String() string { return proto.CompactTextString(m) } +func (*Block) ProtoMessage() {} +func (*Block) Descriptor() ([]byte, []int) { + return fileDescriptor_70840e82f4357ab1, []int{0} +} +func (m *Block) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Block) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Block.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Block) XXX_Merge(src proto.Message) { + xxx_messageInfo_Block.Merge(m, src) +} +func (m *Block) XXX_Size() int { + return m.Size() +} +func (m *Block) XXX_DiscardUnknown() { + xxx_messageInfo_Block.DiscardUnknown(m) +} + +var xxx_messageInfo_Block proto.InternalMessageInfo + +func (m *Block) GetHeader() Header { + if m != nil { + return m.Header + } + return Header{} +} + +func (m *Block) GetData() Data { + if m != nil { + return m.Data + } + return Data{} +} + +func (m *Block) GetEvidence() EvidenceList { + if m != nil { + return m.Evidence + } + return EvidenceList{} +} + +func (m *Block) GetLastCommit() *Commit { + if m != nil { + return m.LastCommit + } + return nil +} + +func init() { + proto.RegisterType((*Block)(nil), "tendermint.types.Block") +} + +func init() { proto.RegisterFile("tendermint/types/block.proto", fileDescriptor_70840e82f4357ab1) } + +var fileDescriptor_70840e82f4357ab1 = []byte{ + // 272 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0xca, 0xc9, + 0x4f, 0xce, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0xc8, 0xea, 0x81, 0x65, 0xa5, + 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x92, 0xfa, 0x20, 0x16, 0x44, 0x9d, 0x14, 0xa6, 0x29, 0x60, + 0x12, 0x2a, 0x2b, 0x8f, 0x21, 0x9b, 0x5a, 0x96, 0x99, 0x92, 0x9a, 0x97, 0x9c, 0x0a, 0x51, 0xa0, + 0xf4, 0x8e, 0x91, 0x8b, 0xd5, 0x09, 0x64, 0xad, 0x90, 0x19, 0x17, 0x5b, 0x46, 0x6a, 0x62, 0x4a, + 0x6a, 0x91, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x84, 0x1e, 0xba, 0x0b, 0xf4, 0x3c, 0xc0, + 0xf2, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0x55, 0x0b, 0x19, 0x70, 0xb1, 0xa4, 0x24, + 0x96, 0x24, 0x4a, 0x30, 0x81, 0x75, 0x89, 0x61, 0xea, 0x72, 0x49, 0x2c, 0x49, 0x84, 0xea, 0x01, + 0xab, 0x14, 0x72, 0xe0, 0xe2, 0x80, 0xb9, 0x42, 0x82, 0x19, 0xac, 0x4b, 0x0e, 0x53, 0x97, 0x2b, + 0x54, 0x85, 0x4f, 0x66, 0x71, 0x09, 0x54, 0x37, 0x5c, 0x97, 0x90, 0x25, 0x17, 0x77, 0x4e, 0x62, + 0x71, 0x49, 0x7c, 0x72, 0x7e, 0x6e, 0x6e, 0x66, 0x89, 0x04, 0x0b, 0x2e, 0x07, 0x3b, 0x83, 0xe5, + 0x83, 0xb8, 0x40, 0x8a, 0x21, 0x6c, 0x27, 0xdf, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, + 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, + 0x63, 0x88, 0x32, 0x4e, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, + 0xcf, 0x4d, 0x2d, 0x49, 0x4a, 0x2b, 0x41, 0x30, 0x20, 0x01, 0x8f, 0x1e, 0x9c, 0x49, 0x6c, 0x60, + 0x71, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x15, 0xdf, 0xde, 0x0a, 0xcd, 0x01, 0x00, 0x00, +} + +func (m *Block) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Block) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Block) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.LastCommit != nil { + { + size, err := m.LastCommit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintBlock(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + { + size, err := m.Evidence.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintBlock(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintBlock(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintBlock(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintBlock(dAtA []byte, offset int, v uint64) int { + offset -= sovBlock(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Block) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Header.Size() + n += 1 + l + sovBlock(uint64(l)) + l = m.Data.Size() + n += 1 + l + sovBlock(uint64(l)) + l = m.Evidence.Size() + n += 1 + l + sovBlock(uint64(l)) + if m.LastCommit != nil { + l = m.LastCommit.Size() + n += 1 + l + sovBlock(uint64(l)) + } + return n +} + +func sovBlock(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozBlock(x uint64) (n int) { + return sovBlock(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Block) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBlock + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Block: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Block: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBlock + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthBlock + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthBlock + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBlock + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthBlock + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthBlock + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Evidence", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBlock + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthBlock + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthBlock + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Evidence.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastCommit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBlock + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthBlock + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthBlock + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.LastCommit == nil { + m.LastCommit = &Commit{} + } + if err := m.LastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipBlock(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthBlock + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipBlock(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBlock + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBlock + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBlock + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthBlock + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupBlock + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthBlock + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthBlock = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowBlock = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupBlock = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/block.proto b/proto/tendermint/types/block.proto new file mode 100644 index 0000000..03b8827 --- /dev/null +++ b/proto/tendermint/types/block.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "tendermint/types/types.proto"; +import "tendermint/types/evidence.proto"; + +message Block { + Header header = 1 [(gogoproto.nullable) = false]; + Data data = 2 [(gogoproto.nullable) = false]; + tendermint.types.EvidenceList evidence = 3 [(gogoproto.nullable) = false]; + Commit last_commit = 4; +} diff --git a/proto/tendermint/types/canonical.pb.go b/proto/tendermint/types/canonical.pb.go new file mode 100644 index 0000000..57bddef --- /dev/null +++ b/proto/tendermint/types/canonical.pb.go @@ -0,0 +1,1659 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/canonical.proto + +package types + +import ( + encoding_binary "encoding/binary" + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type CanonicalBlockID struct { + Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + PartSetHeader CanonicalPartSetHeader `protobuf:"bytes,2,opt,name=part_set_header,json=partSetHeader,proto3" json:"part_set_header"` +} + +func (m *CanonicalBlockID) Reset() { *m = CanonicalBlockID{} } +func (m *CanonicalBlockID) String() string { return proto.CompactTextString(m) } +func (*CanonicalBlockID) ProtoMessage() {} +func (*CanonicalBlockID) Descriptor() ([]byte, []int) { + return fileDescriptor_8d1a1a84ff7267ed, []int{0} +} +func (m *CanonicalBlockID) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CanonicalBlockID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CanonicalBlockID.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CanonicalBlockID) XXX_Merge(src proto.Message) { + xxx_messageInfo_CanonicalBlockID.Merge(m, src) +} +func (m *CanonicalBlockID) XXX_Size() int { + return m.Size() +} +func (m *CanonicalBlockID) XXX_DiscardUnknown() { + xxx_messageInfo_CanonicalBlockID.DiscardUnknown(m) +} + +var xxx_messageInfo_CanonicalBlockID proto.InternalMessageInfo + +func (m *CanonicalBlockID) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *CanonicalBlockID) GetPartSetHeader() CanonicalPartSetHeader { + if m != nil { + return m.PartSetHeader + } + return CanonicalPartSetHeader{} +} + +type CanonicalPartSetHeader struct { + Total uint32 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"` + Hash []byte `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"` +} + +func (m *CanonicalPartSetHeader) Reset() { *m = CanonicalPartSetHeader{} } +func (m *CanonicalPartSetHeader) String() string { return proto.CompactTextString(m) } +func (*CanonicalPartSetHeader) ProtoMessage() {} +func (*CanonicalPartSetHeader) Descriptor() ([]byte, []int) { + return fileDescriptor_8d1a1a84ff7267ed, []int{1} +} +func (m *CanonicalPartSetHeader) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CanonicalPartSetHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CanonicalPartSetHeader.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CanonicalPartSetHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_CanonicalPartSetHeader.Merge(m, src) +} +func (m *CanonicalPartSetHeader) XXX_Size() int { + return m.Size() +} +func (m *CanonicalPartSetHeader) XXX_DiscardUnknown() { + xxx_messageInfo_CanonicalPartSetHeader.DiscardUnknown(m) +} + +var xxx_messageInfo_CanonicalPartSetHeader proto.InternalMessageInfo + +func (m *CanonicalPartSetHeader) GetTotal() uint32 { + if m != nil { + return m.Total + } + return 0 +} + +func (m *CanonicalPartSetHeader) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +type CanonicalProposal struct { + Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + Height int64 `protobuf:"fixed64,2,opt,name=height,proto3" json:"height,omitempty"` + Round int64 `protobuf:"fixed64,3,opt,name=round,proto3" json:"round,omitempty"` + POLRound int64 `protobuf:"varint,4,opt,name=pol_round,json=polRound,proto3" json:"pol_round,omitempty"` + BlockID *CanonicalBlockID `protobuf:"bytes,5,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` + Timestamp time.Time `protobuf:"bytes,6,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + ChainID string `protobuf:"bytes,7,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *CanonicalProposal) Reset() { *m = CanonicalProposal{} } +func (m *CanonicalProposal) String() string { return proto.CompactTextString(m) } +func (*CanonicalProposal) ProtoMessage() {} +func (*CanonicalProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_8d1a1a84ff7267ed, []int{2} +} +func (m *CanonicalProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CanonicalProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CanonicalProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CanonicalProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_CanonicalProposal.Merge(m, src) +} +func (m *CanonicalProposal) XXX_Size() int { + return m.Size() +} +func (m *CanonicalProposal) XXX_DiscardUnknown() { + xxx_messageInfo_CanonicalProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_CanonicalProposal proto.InternalMessageInfo + +func (m *CanonicalProposal) GetType() SignedMsgType { + if m != nil { + return m.Type + } + return UnknownType +} + +func (m *CanonicalProposal) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *CanonicalProposal) GetRound() int64 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *CanonicalProposal) GetPOLRound() int64 { + if m != nil { + return m.POLRound + } + return 0 +} + +func (m *CanonicalProposal) GetBlockID() *CanonicalBlockID { + if m != nil { + return m.BlockID + } + return nil +} + +func (m *CanonicalProposal) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *CanonicalProposal) GetChainID() string { + if m != nil { + return m.ChainID + } + return "" +} + +type CanonicalVote struct { + Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + Height int64 `protobuf:"fixed64,2,opt,name=height,proto3" json:"height,omitempty"` + Round int64 `protobuf:"fixed64,3,opt,name=round,proto3" json:"round,omitempty"` + BlockID *CanonicalBlockID `protobuf:"bytes,4,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` + Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + ChainID string `protobuf:"bytes,6,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *CanonicalVote) Reset() { *m = CanonicalVote{} } +func (m *CanonicalVote) String() string { return proto.CompactTextString(m) } +func (*CanonicalVote) ProtoMessage() {} +func (*CanonicalVote) Descriptor() ([]byte, []int) { + return fileDescriptor_8d1a1a84ff7267ed, []int{3} +} +func (m *CanonicalVote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CanonicalVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CanonicalVote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CanonicalVote) XXX_Merge(src proto.Message) { + xxx_messageInfo_CanonicalVote.Merge(m, src) +} +func (m *CanonicalVote) XXX_Size() int { + return m.Size() +} +func (m *CanonicalVote) XXX_DiscardUnknown() { + xxx_messageInfo_CanonicalVote.DiscardUnknown(m) +} + +var xxx_messageInfo_CanonicalVote proto.InternalMessageInfo + +func (m *CanonicalVote) GetType() SignedMsgType { + if m != nil { + return m.Type + } + return UnknownType +} + +func (m *CanonicalVote) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *CanonicalVote) GetRound() int64 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *CanonicalVote) GetBlockID() *CanonicalBlockID { + if m != nil { + return m.BlockID + } + return nil +} + +func (m *CanonicalVote) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *CanonicalVote) GetChainID() string { + if m != nil { + return m.ChainID + } + return "" +} + +// CanonicalVoteExtension provides us a way to serialize a vote extension from +// a particular validator such that we can sign over those serialized bytes. +type CanonicalVoteExtension struct { + Extension []byte `protobuf:"bytes,1,opt,name=extension,proto3" json:"extension,omitempty"` + Height int64 `protobuf:"fixed64,2,opt,name=height,proto3" json:"height,omitempty"` + Round int64 `protobuf:"fixed64,3,opt,name=round,proto3" json:"round,omitempty"` + ChainId string `protobuf:"bytes,4,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` +} + +func (m *CanonicalVoteExtension) Reset() { *m = CanonicalVoteExtension{} } +func (m *CanonicalVoteExtension) String() string { return proto.CompactTextString(m) } +func (*CanonicalVoteExtension) ProtoMessage() {} +func (*CanonicalVoteExtension) Descriptor() ([]byte, []int) { + return fileDescriptor_8d1a1a84ff7267ed, []int{4} +} +func (m *CanonicalVoteExtension) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CanonicalVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CanonicalVoteExtension.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CanonicalVoteExtension) XXX_Merge(src proto.Message) { + xxx_messageInfo_CanonicalVoteExtension.Merge(m, src) +} +func (m *CanonicalVoteExtension) XXX_Size() int { + return m.Size() +} +func (m *CanonicalVoteExtension) XXX_DiscardUnknown() { + xxx_messageInfo_CanonicalVoteExtension.DiscardUnknown(m) +} + +var xxx_messageInfo_CanonicalVoteExtension proto.InternalMessageInfo + +func (m *CanonicalVoteExtension) GetExtension() []byte { + if m != nil { + return m.Extension + } + return nil +} + +func (m *CanonicalVoteExtension) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *CanonicalVoteExtension) GetRound() int64 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *CanonicalVoteExtension) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +func init() { + proto.RegisterType((*CanonicalBlockID)(nil), "tendermint.types.CanonicalBlockID") + proto.RegisterType((*CanonicalPartSetHeader)(nil), "tendermint.types.CanonicalPartSetHeader") + proto.RegisterType((*CanonicalProposal)(nil), "tendermint.types.CanonicalProposal") + proto.RegisterType((*CanonicalVote)(nil), "tendermint.types.CanonicalVote") + proto.RegisterType((*CanonicalVoteExtension)(nil), "tendermint.types.CanonicalVoteExtension") +} + +func init() { proto.RegisterFile("tendermint/types/canonical.proto", fileDescriptor_8d1a1a84ff7267ed) } + +var fileDescriptor_8d1a1a84ff7267ed = []byte{ + // 525 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0xc1, 0x6e, 0x9b, 0x40, + 0x10, 0x35, 0x0e, 0xb6, 0x61, 0x13, 0xb7, 0xee, 0x2a, 0x8a, 0xa8, 0x15, 0x01, 0xe2, 0x50, 0xd1, + 0x0b, 0x48, 0xf1, 0x1f, 0x90, 0x56, 0xaa, 0xab, 0x46, 0x8d, 0x48, 0x94, 0x43, 0x2f, 0xd6, 0x02, + 0x1b, 0x40, 0x05, 0x16, 0xc1, 0x5a, 0x6a, 0x2e, 0xed, 0x2f, 0xe4, 0x3b, 0xfa, 0x25, 0x39, 0xe6, + 0xd8, 0x5e, 0xdc, 0x0a, 0xff, 0x48, 0xb5, 0x0b, 0x06, 0x2b, 0xa9, 0x2c, 0x55, 0xad, 0x7a, 0x41, + 0x33, 0x6f, 0xde, 0xce, 0x3c, 0xbd, 0x61, 0x17, 0xe8, 0x14, 0x67, 0x01, 0x2e, 0xd2, 0x38, 0xa3, + 0x36, 0xbd, 0xc9, 0x71, 0x69, 0xfb, 0x28, 0x23, 0x59, 0xec, 0xa3, 0xc4, 0xca, 0x0b, 0x42, 0x09, + 0x9c, 0x74, 0x0c, 0x8b, 0x33, 0xa6, 0x87, 0x21, 0x09, 0x09, 0x2f, 0xda, 0x2c, 0xaa, 0x79, 0xd3, + 0xe3, 0x47, 0x9d, 0xf8, 0xb7, 0xa9, 0x6a, 0x21, 0x21, 0x61, 0x82, 0x6d, 0x9e, 0x79, 0xcb, 0x6b, + 0x9b, 0xc6, 0x29, 0x2e, 0x29, 0x4a, 0xf3, 0x9a, 0x60, 0x7c, 0x06, 0x93, 0xd3, 0xcd, 0x64, 0x27, + 0x21, 0xfe, 0xc7, 0xf9, 0x2b, 0x08, 0x81, 0x18, 0xa1, 0x32, 0x52, 0x04, 0x5d, 0x30, 0x0f, 0x5c, + 0x1e, 0xc3, 0x2b, 0xf0, 0x34, 0x47, 0x05, 0x5d, 0x94, 0x98, 0x2e, 0x22, 0x8c, 0x02, 0x5c, 0x28, + 0x7d, 0x5d, 0x30, 0xf7, 0x4f, 0x4c, 0xeb, 0xa1, 0x50, 0xab, 0x6d, 0x78, 0x8e, 0x0a, 0x7a, 0x81, + 0xe9, 0x1b, 0xce, 0x77, 0xc4, 0xbb, 0x95, 0xd6, 0x73, 0xc7, 0xf9, 0x36, 0x68, 0x38, 0xe0, 0xe8, + 0xf7, 0x74, 0x78, 0x08, 0x06, 0x94, 0x50, 0x94, 0x70, 0x19, 0x63, 0xb7, 0x4e, 0x5a, 0x6d, 0xfd, + 0x4e, 0x9b, 0xf1, 0xbd, 0x0f, 0x9e, 0x75, 0x4d, 0x0a, 0x92, 0x93, 0x12, 0x25, 0x70, 0x06, 0x44, + 0x26, 0x87, 0x1f, 0x7f, 0x72, 0xa2, 0x3d, 0x96, 0x79, 0x11, 0x87, 0x19, 0x0e, 0xce, 0xca, 0xf0, + 0xf2, 0x26, 0xc7, 0x2e, 0x27, 0xc3, 0x23, 0x30, 0x8c, 0x70, 0x1c, 0x46, 0x94, 0x0f, 0x98, 0xb8, + 0x4d, 0xc6, 0xc4, 0x14, 0x64, 0x99, 0x05, 0xca, 0x1e, 0x87, 0xeb, 0x04, 0xbe, 0x04, 0x72, 0x4e, + 0x92, 0x45, 0x5d, 0x11, 0x75, 0xc1, 0xdc, 0x73, 0x0e, 0xaa, 0x95, 0x26, 0x9d, 0xbf, 0x7f, 0xe7, + 0x32, 0xcc, 0x95, 0x72, 0x92, 0xf0, 0x08, 0xbe, 0x05, 0x92, 0xc7, 0xec, 0x5d, 0xc4, 0x81, 0x32, + 0xe0, 0xc6, 0x19, 0x3b, 0x8c, 0x6b, 0x36, 0xe1, 0xec, 0x57, 0x2b, 0x6d, 0xd4, 0x24, 0xee, 0x88, + 0x37, 0x98, 0x07, 0xd0, 0x01, 0x72, 0xbb, 0x46, 0x65, 0xc8, 0x9b, 0x4d, 0xad, 0x7a, 0xd1, 0xd6, + 0x66, 0xd1, 0xd6, 0xe5, 0x86, 0xe1, 0x48, 0xcc, 0xf7, 0xdb, 0x1f, 0x9a, 0xe0, 0x76, 0xc7, 0xe0, + 0x0b, 0x20, 0xf9, 0x11, 0x8a, 0x33, 0xa6, 0x67, 0xa4, 0x0b, 0xa6, 0x5c, 0xcf, 0x3a, 0x65, 0x18, + 0x9b, 0xc5, 0x8b, 0xf3, 0xc0, 0xf8, 0xda, 0x07, 0xe3, 0x56, 0xd6, 0x15, 0xa1, 0xf8, 0x7f, 0xf8, + 0xba, 0x6d, 0x96, 0xf8, 0x2f, 0xcd, 0x1a, 0xfc, 0xbd, 0x59, 0xc3, 0x1d, 0x66, 0x7d, 0xd9, 0xfa, + 0x99, 0x99, 0x57, 0xaf, 0x3f, 0x51, 0x9c, 0x95, 0x31, 0xc9, 0xe0, 0x31, 0x90, 0xf1, 0x26, 0x69, + 0xee, 0x55, 0x07, 0xfc, 0xa1, 0x3b, 0xcf, 0xb7, 0xd4, 0x30, 0x77, 0xe4, 0x56, 0x80, 0x73, 0x76, + 0x57, 0xa9, 0xc2, 0x7d, 0xa5, 0x0a, 0x3f, 0x2b, 0x55, 0xb8, 0x5d, 0xab, 0xbd, 0xfb, 0xb5, 0xda, + 0xfb, 0xb6, 0x56, 0x7b, 0x1f, 0x66, 0x61, 0x4c, 0xa3, 0xa5, 0x67, 0xf9, 0x24, 0xb5, 0x7d, 0x92, + 0x62, 0xea, 0x5d, 0xd3, 0x2e, 0xa8, 0x5f, 0x95, 0x87, 0x2f, 0x89, 0x37, 0xe4, 0xf8, 0xec, 0x57, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xe6, 0x22, 0x5b, 0x0b, 0xae, 0x04, 0x00, 0x00, +} + +func (m *CanonicalBlockID) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CanonicalBlockID) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CanonicalBlockID) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.PartSetHeader.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintCanonical(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *CanonicalPartSetHeader) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CanonicalPartSetHeader) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CanonicalPartSetHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x12 + } + if m.Total != 0 { + i = encodeVarintCanonical(dAtA, i, uint64(m.Total)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *CanonicalProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CanonicalProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CanonicalProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainID) > 0 { + i -= len(m.ChainID) + copy(dAtA[i:], m.ChainID) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.ChainID))) + i-- + dAtA[i] = 0x3a + } + n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err2 != nil { + return 0, err2 + } + i -= n2 + i = encodeVarintCanonical(dAtA, i, uint64(n2)) + i-- + dAtA[i] = 0x32 + if m.BlockID != nil { + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintCanonical(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if m.POLRound != 0 { + i = encodeVarintCanonical(dAtA, i, uint64(m.POLRound)) + i-- + dAtA[i] = 0x20 + } + if m.Round != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Round)) + i-- + dAtA[i] = 0x19 + } + if m.Height != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Height)) + i-- + dAtA[i] = 0x11 + } + if m.Type != 0 { + i = encodeVarintCanonical(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *CanonicalVote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CanonicalVote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CanonicalVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainID) > 0 { + i -= len(m.ChainID) + copy(dAtA[i:], m.ChainID) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.ChainID))) + i-- + dAtA[i] = 0x32 + } + n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err4 != nil { + return 0, err4 + } + i -= n4 + i = encodeVarintCanonical(dAtA, i, uint64(n4)) + i-- + dAtA[i] = 0x2a + if m.BlockID != nil { + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintCanonical(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.Round != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Round)) + i-- + dAtA[i] = 0x19 + } + if m.Height != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Height)) + i-- + dAtA[i] = 0x11 + } + if m.Type != 0 { + i = encodeVarintCanonical(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *CanonicalVoteExtension) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CanonicalVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CanonicalVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x22 + } + if m.Round != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Round)) + i-- + dAtA[i] = 0x19 + } + if m.Height != 0 { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.Height)) + i-- + dAtA[i] = 0x11 + } + if len(m.Extension) > 0 { + i -= len(m.Extension) + copy(dAtA[i:], m.Extension) + i = encodeVarintCanonical(dAtA, i, uint64(len(m.Extension))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintCanonical(dAtA []byte, offset int, v uint64) int { + offset -= sovCanonical(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *CanonicalBlockID) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + l = m.PartSetHeader.Size() + n += 1 + l + sovCanonical(uint64(l)) + return n +} + +func (m *CanonicalPartSetHeader) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Total != 0 { + n += 1 + sovCanonical(uint64(m.Total)) + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + return n +} + +func (m *CanonicalProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovCanonical(uint64(m.Type)) + } + if m.Height != 0 { + n += 9 + } + if m.Round != 0 { + n += 9 + } + if m.POLRound != 0 { + n += 1 + sovCanonical(uint64(m.POLRound)) + } + if m.BlockID != nil { + l = m.BlockID.Size() + n += 1 + l + sovCanonical(uint64(l)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovCanonical(uint64(l)) + l = len(m.ChainID) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + return n +} + +func (m *CanonicalVote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovCanonical(uint64(m.Type)) + } + if m.Height != 0 { + n += 9 + } + if m.Round != 0 { + n += 9 + } + if m.BlockID != nil { + l = m.BlockID.Size() + n += 1 + l + sovCanonical(uint64(l)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovCanonical(uint64(l)) + l = len(m.ChainID) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + return n +} + +func (m *CanonicalVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Extension) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + if m.Height != 0 { + n += 9 + } + if m.Round != 0 { + n += 9 + } + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovCanonical(uint64(l)) + } + return n +} + +func sovCanonical(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozCanonical(x uint64) (n int) { + return sovCanonical(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *CanonicalBlockID) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CanonicalBlockID: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CanonicalBlockID: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartSetHeader", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PartSetHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCanonical(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCanonical + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CanonicalPartSetHeader) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CanonicalPartSetHeader: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CanonicalPartSetHeader: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) + } + m.Total = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Total |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCanonical(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCanonical + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CanonicalProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CanonicalProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CanonicalProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Height = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 3: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Round = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field POLRound", wireType) + } + m.POLRound = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.POLRound |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BlockID == nil { + m.BlockID = &CanonicalBlockID{} + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCanonical(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCanonical + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CanonicalVote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CanonicalVote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CanonicalVote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Height = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 3: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Round = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BlockID == nil { + m.BlockID = &CanonicalBlockID{} + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCanonical(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCanonical + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CanonicalVoteExtension) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CanonicalVoteExtension: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CanonicalVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Extension = append(m.Extension[:0], dAtA[iNdEx:postIndex]...) + if m.Extension == nil { + m.Extension = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Height = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 3: + if wireType != 1 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF + } + m.Round = int64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCanonical + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthCanonical + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCanonical + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCanonical(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCanonical + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipCanonical(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCanonical + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCanonical + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCanonical + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthCanonical + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupCanonical + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthCanonical + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthCanonical = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowCanonical = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupCanonical = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/canonical.proto b/proto/tendermint/types/canonical.proto new file mode 100644 index 0000000..59ffb9a --- /dev/null +++ b/proto/tendermint/types/canonical.proto @@ -0,0 +1,46 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "tendermint/types/types.proto"; +import "google/protobuf/timestamp.proto"; + +message CanonicalBlockID { + bytes hash = 1; + CanonicalPartSetHeader part_set_header = 2 [(gogoproto.nullable) = false]; +} + +message CanonicalPartSetHeader { + uint32 total = 1; + bytes hash = 2; +} + +message CanonicalProposal { + SignedMsgType type = 1; // type alias for byte + sfixed64 height = 2; // canonicalization requires fixed size encoding here + sfixed64 round = 3; // canonicalization requires fixed size encoding here + int64 pol_round = 4 [(gogoproto.customname) = "POLRound"]; + CanonicalBlockID block_id = 5 [(gogoproto.customname) = "BlockID"]; + google.protobuf.Timestamp timestamp = 6 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + string chain_id = 7 [(gogoproto.customname) = "ChainID"]; +} + +message CanonicalVote { + SignedMsgType type = 1; // type alias for byte + sfixed64 height = 2; // canonicalization requires fixed size encoding here + sfixed64 round = 3; // canonicalization requires fixed size encoding here + CanonicalBlockID block_id = 4 [(gogoproto.customname) = "BlockID"]; + google.protobuf.Timestamp timestamp = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + string chain_id = 6 [(gogoproto.customname) = "ChainID"]; +} + +// CanonicalVoteExtension provides us a way to serialize a vote extension from +// a particular validator such that we can sign over those serialized bytes. +message CanonicalVoteExtension { + bytes extension = 1; + sfixed64 height = 2; + sfixed64 round = 3; + string chain_id = 4; +} diff --git a/proto/tendermint/types/events.pb.go b/proto/tendermint/types/events.pb.go new file mode 100644 index 0000000..d5498e0 --- /dev/null +++ b/proto/tendermint/types/events.pb.go @@ -0,0 +1,387 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/events.proto + +package types + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type EventDataRoundState struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + Step string `protobuf:"bytes,3,opt,name=step,proto3" json:"step,omitempty"` +} + +func (m *EventDataRoundState) Reset() { *m = EventDataRoundState{} } +func (m *EventDataRoundState) String() string { return proto.CompactTextString(m) } +func (*EventDataRoundState) ProtoMessage() {} +func (*EventDataRoundState) Descriptor() ([]byte, []int) { + return fileDescriptor_72cfafd446dedf7c, []int{0} +} +func (m *EventDataRoundState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EventDataRoundState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EventDataRoundState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *EventDataRoundState) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventDataRoundState.Merge(m, src) +} +func (m *EventDataRoundState) XXX_Size() int { + return m.Size() +} +func (m *EventDataRoundState) XXX_DiscardUnknown() { + xxx_messageInfo_EventDataRoundState.DiscardUnknown(m) +} + +var xxx_messageInfo_EventDataRoundState proto.InternalMessageInfo + +func (m *EventDataRoundState) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *EventDataRoundState) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *EventDataRoundState) GetStep() string { + if m != nil { + return m.Step + } + return "" +} + +func init() { + proto.RegisterType((*EventDataRoundState)(nil), "tendermint.types.EventDataRoundState") +} + +func init() { proto.RegisterFile("tendermint/types/events.proto", fileDescriptor_72cfafd446dedf7c) } + +var fileDescriptor_72cfafd446dedf7c = []byte{ + // 195 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x2d, 0x4b, + 0xcd, 0x2b, 0x29, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x48, 0xeb, 0x81, 0xa5, + 0x95, 0xc2, 0xb9, 0x84, 0x5d, 0x41, 0x2a, 0x5c, 0x12, 0x4b, 0x12, 0x83, 0xf2, 0x4b, 0xf3, 0x52, + 0x82, 0x4b, 0x12, 0x4b, 0x52, 0x85, 0xc4, 0xb8, 0xd8, 0x32, 0x52, 0x33, 0xd3, 0x33, 0x4a, 0x24, + 0x18, 0x15, 0x18, 0x35, 0x98, 0x83, 0xa0, 0x3c, 0x21, 0x11, 0x2e, 0xd6, 0x22, 0x90, 0x2a, 0x09, + 0x26, 0x05, 0x46, 0x0d, 0xd6, 0x20, 0x08, 0x47, 0x48, 0x88, 0x8b, 0xa5, 0xb8, 0x24, 0xb5, 0x40, + 0x82, 0x59, 0x81, 0x51, 0x83, 0x33, 0x08, 0xcc, 0x76, 0xf2, 0x3d, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, + 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, + 0xc6, 0x63, 0x39, 0x86, 0x28, 0xe3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, + 0xfd, 0xe4, 0xfc, 0xdc, 0xd4, 0x92, 0xa4, 0xb4, 0x12, 0x04, 0x03, 0xec, 0x50, 0x7d, 0x74, 0x6f, + 0x24, 0xb1, 0x81, 0xc5, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa8, 0xb3, 0x7f, 0x37, 0xe1, + 0x00, 0x00, 0x00, +} + +func (m *EventDataRoundState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EventDataRoundState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EventDataRoundState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Step) > 0 { + i -= len(m.Step) + copy(dAtA[i:], m.Step) + i = encodeVarintEvents(dAtA, i, uint64(len(m.Step))) + i-- + dAtA[i] = 0x1a + } + if m.Round != 0 { + i = encodeVarintEvents(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintEvents(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintEvents(dAtA []byte, offset int, v uint64) int { + offset -= sovEvents(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *EventDataRoundState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovEvents(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovEvents(uint64(m.Round)) + } + l = len(m.Step) + if l > 0 { + n += 1 + l + sovEvents(uint64(l)) + } + return n +} + +func sovEvents(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozEvents(x uint64) (n int) { + return sovEvents(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *EventDataRoundState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EventDataRoundState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EventDataRoundState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Step", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthEvents + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvents + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Step = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvents(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipEvents(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthEvents + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupEvents + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthEvents + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthEvents = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowEvents = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupEvents = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/events.proto b/proto/tendermint/types/events.proto new file mode 100644 index 0000000..a4cba08 --- /dev/null +++ b/proto/tendermint/types/events.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +message EventDataRoundState { + int64 height = 1; + int32 round = 2; + string step = 3; +} diff --git a/proto/tendermint/types/evidence.pb.go b/proto/tendermint/types/evidence.pb.go new file mode 100644 index 0000000..53f0e37 --- /dev/null +++ b/proto/tendermint/types/evidence.pb.go @@ -0,0 +1,1394 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/evidence.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Evidence struct { + // Types that are valid to be assigned to Sum: + // *Evidence_DuplicateVoteEvidence + // *Evidence_LightClientAttackEvidence + Sum isEvidence_Sum `protobuf_oneof:"sum"` +} + +func (m *Evidence) Reset() { *m = Evidence{} } +func (m *Evidence) String() string { return proto.CompactTextString(m) } +func (*Evidence) ProtoMessage() {} +func (*Evidence) Descriptor() ([]byte, []int) { + return fileDescriptor_6825fabc78e0a168, []int{0} +} +func (m *Evidence) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Evidence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Evidence.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Evidence) XXX_Merge(src proto.Message) { + xxx_messageInfo_Evidence.Merge(m, src) +} +func (m *Evidence) XXX_Size() int { + return m.Size() +} +func (m *Evidence) XXX_DiscardUnknown() { + xxx_messageInfo_Evidence.DiscardUnknown(m) +} + +var xxx_messageInfo_Evidence proto.InternalMessageInfo + +type isEvidence_Sum interface { + isEvidence_Sum() + MarshalTo([]byte) (int, error) + Size() int +} + +type Evidence_DuplicateVoteEvidence struct { + DuplicateVoteEvidence *DuplicateVoteEvidence `protobuf:"bytes,1,opt,name=duplicate_vote_evidence,json=duplicateVoteEvidence,proto3,oneof" json:"duplicate_vote_evidence,omitempty"` +} +type Evidence_LightClientAttackEvidence struct { + LightClientAttackEvidence *LightClientAttackEvidence `protobuf:"bytes,2,opt,name=light_client_attack_evidence,json=lightClientAttackEvidence,proto3,oneof" json:"light_client_attack_evidence,omitempty"` +} + +func (*Evidence_DuplicateVoteEvidence) isEvidence_Sum() {} +func (*Evidence_LightClientAttackEvidence) isEvidence_Sum() {} + +func (m *Evidence) GetSum() isEvidence_Sum { + if m != nil { + return m.Sum + } + return nil +} + +func (m *Evidence) GetDuplicateVoteEvidence() *DuplicateVoteEvidence { + if x, ok := m.GetSum().(*Evidence_DuplicateVoteEvidence); ok { + return x.DuplicateVoteEvidence + } + return nil +} + +func (m *Evidence) GetLightClientAttackEvidence() *LightClientAttackEvidence { + if x, ok := m.GetSum().(*Evidence_LightClientAttackEvidence); ok { + return x.LightClientAttackEvidence + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*Evidence) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*Evidence_DuplicateVoteEvidence)(nil), + (*Evidence_LightClientAttackEvidence)(nil), + } +} + +// DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes. +type DuplicateVoteEvidence struct { + VoteA *Vote `protobuf:"bytes,1,opt,name=vote_a,json=voteA,proto3" json:"vote_a,omitempty"` + VoteB *Vote `protobuf:"bytes,2,opt,name=vote_b,json=voteB,proto3" json:"vote_b,omitempty"` + TotalVotingPower int64 `protobuf:"varint,3,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` + ValidatorPower int64 `protobuf:"varint,4,opt,name=validator_power,json=validatorPower,proto3" json:"validator_power,omitempty"` + Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"` +} + +func (m *DuplicateVoteEvidence) Reset() { *m = DuplicateVoteEvidence{} } +func (m *DuplicateVoteEvidence) String() string { return proto.CompactTextString(m) } +func (*DuplicateVoteEvidence) ProtoMessage() {} +func (*DuplicateVoteEvidence) Descriptor() ([]byte, []int) { + return fileDescriptor_6825fabc78e0a168, []int{1} +} +func (m *DuplicateVoteEvidence) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DuplicateVoteEvidence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DuplicateVoteEvidence.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DuplicateVoteEvidence) XXX_Merge(src proto.Message) { + xxx_messageInfo_DuplicateVoteEvidence.Merge(m, src) +} +func (m *DuplicateVoteEvidence) XXX_Size() int { + return m.Size() +} +func (m *DuplicateVoteEvidence) XXX_DiscardUnknown() { + xxx_messageInfo_DuplicateVoteEvidence.DiscardUnknown(m) +} + +var xxx_messageInfo_DuplicateVoteEvidence proto.InternalMessageInfo + +func (m *DuplicateVoteEvidence) GetVoteA() *Vote { + if m != nil { + return m.VoteA + } + return nil +} + +func (m *DuplicateVoteEvidence) GetVoteB() *Vote { + if m != nil { + return m.VoteB + } + return nil +} + +func (m *DuplicateVoteEvidence) GetTotalVotingPower() int64 { + if m != nil { + return m.TotalVotingPower + } + return 0 +} + +func (m *DuplicateVoteEvidence) GetValidatorPower() int64 { + if m != nil { + return m.ValidatorPower + } + return 0 +} + +func (m *DuplicateVoteEvidence) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +// LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client. +type LightClientAttackEvidence struct { + ConflictingBlock *LightBlock `protobuf:"bytes,1,opt,name=conflicting_block,json=conflictingBlock,proto3" json:"conflicting_block,omitempty"` + CommonHeight int64 `protobuf:"varint,2,opt,name=common_height,json=commonHeight,proto3" json:"common_height,omitempty"` + ByzantineValidators []*Validator `protobuf:"bytes,3,rep,name=byzantine_validators,json=byzantineValidators,proto3" json:"byzantine_validators,omitempty"` + TotalVotingPower int64 `protobuf:"varint,4,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` + Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"` +} + +func (m *LightClientAttackEvidence) Reset() { *m = LightClientAttackEvidence{} } +func (m *LightClientAttackEvidence) String() string { return proto.CompactTextString(m) } +func (*LightClientAttackEvidence) ProtoMessage() {} +func (*LightClientAttackEvidence) Descriptor() ([]byte, []int) { + return fileDescriptor_6825fabc78e0a168, []int{2} +} +func (m *LightClientAttackEvidence) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *LightClientAttackEvidence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_LightClientAttackEvidence.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *LightClientAttackEvidence) XXX_Merge(src proto.Message) { + xxx_messageInfo_LightClientAttackEvidence.Merge(m, src) +} +func (m *LightClientAttackEvidence) XXX_Size() int { + return m.Size() +} +func (m *LightClientAttackEvidence) XXX_DiscardUnknown() { + xxx_messageInfo_LightClientAttackEvidence.DiscardUnknown(m) +} + +var xxx_messageInfo_LightClientAttackEvidence proto.InternalMessageInfo + +func (m *LightClientAttackEvidence) GetConflictingBlock() *LightBlock { + if m != nil { + return m.ConflictingBlock + } + return nil +} + +func (m *LightClientAttackEvidence) GetCommonHeight() int64 { + if m != nil { + return m.CommonHeight + } + return 0 +} + +func (m *LightClientAttackEvidence) GetByzantineValidators() []*Validator { + if m != nil { + return m.ByzantineValidators + } + return nil +} + +func (m *LightClientAttackEvidence) GetTotalVotingPower() int64 { + if m != nil { + return m.TotalVotingPower + } + return 0 +} + +func (m *LightClientAttackEvidence) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +type EvidenceList struct { + Evidence []Evidence `protobuf:"bytes,1,rep,name=evidence,proto3" json:"evidence"` +} + +func (m *EvidenceList) Reset() { *m = EvidenceList{} } +func (m *EvidenceList) String() string { return proto.CompactTextString(m) } +func (*EvidenceList) ProtoMessage() {} +func (*EvidenceList) Descriptor() ([]byte, []int) { + return fileDescriptor_6825fabc78e0a168, []int{3} +} +func (m *EvidenceList) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EvidenceList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EvidenceList.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *EvidenceList) XXX_Merge(src proto.Message) { + xxx_messageInfo_EvidenceList.Merge(m, src) +} +func (m *EvidenceList) XXX_Size() int { + return m.Size() +} +func (m *EvidenceList) XXX_DiscardUnknown() { + xxx_messageInfo_EvidenceList.DiscardUnknown(m) +} + +var xxx_messageInfo_EvidenceList proto.InternalMessageInfo + +func (m *EvidenceList) GetEvidence() []Evidence { + if m != nil { + return m.Evidence + } + return nil +} + +func init() { + proto.RegisterType((*Evidence)(nil), "tendermint.types.Evidence") + proto.RegisterType((*DuplicateVoteEvidence)(nil), "tendermint.types.DuplicateVoteEvidence") + proto.RegisterType((*LightClientAttackEvidence)(nil), "tendermint.types.LightClientAttackEvidence") + proto.RegisterType((*EvidenceList)(nil), "tendermint.types.EvidenceList") +} + +func init() { proto.RegisterFile("tendermint/types/evidence.proto", fileDescriptor_6825fabc78e0a168) } + +var fileDescriptor_6825fabc78e0a168 = []byte{ + // 533 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x94, 0xcf, 0x6e, 0xd3, 0x40, + 0x10, 0xc6, 0xe3, 0x38, 0xa9, 0xc2, 0xb6, 0x40, 0x58, 0x5a, 0x48, 0x43, 0xe4, 0x44, 0xe1, 0xd0, + 0x48, 0x80, 0x2d, 0xb5, 0x57, 0x2e, 0x35, 0x20, 0x15, 0x29, 0x20, 0x64, 0xa1, 0x1e, 0xb8, 0x58, + 0xeb, 0xcd, 0xc6, 0x59, 0xd5, 0xde, 0x8d, 0xe2, 0x49, 0x50, 0x79, 0x8a, 0x3c, 0x56, 0x2f, 0x48, + 0x3d, 0x72, 0x02, 0x94, 0xf0, 0x20, 0xc8, 0xeb, 0x3f, 0x89, 0xea, 0x98, 0x13, 0x97, 0xc8, 0x99, + 0xf9, 0x7d, 0x3b, 0x33, 0x9f, 0x67, 0x8d, 0xba, 0xc0, 0xc4, 0x88, 0xcd, 0x42, 0x2e, 0xc0, 0x82, + 0xeb, 0x29, 0x8b, 0x2c, 0xb6, 0xe0, 0x23, 0x26, 0x28, 0x33, 0xa7, 0x33, 0x09, 0x12, 0x37, 0x37, + 0x80, 0xa9, 0x80, 0xf6, 0xa1, 0x2f, 0x7d, 0xa9, 0x92, 0x56, 0xfc, 0x94, 0x70, 0xed, 0xae, 0x2f, + 0xa5, 0x1f, 0x30, 0x4b, 0xfd, 0xf3, 0xe6, 0x63, 0x0b, 0x78, 0xc8, 0x22, 0x20, 0xe1, 0x34, 0x05, + 0x3a, 0x85, 0x4a, 0xea, 0x37, 0xcd, 0xf6, 0x0a, 0xd9, 0x05, 0x09, 0xf8, 0x88, 0x80, 0x9c, 0x25, + 0x44, 0xff, 0x8f, 0x86, 0x1a, 0xef, 0xd2, 0xde, 0x30, 0x41, 0x4f, 0x47, 0xf3, 0x69, 0xc0, 0x29, + 0x01, 0xe6, 0x2e, 0x24, 0x30, 0x37, 0x6b, 0xbb, 0xa5, 0xf5, 0xb4, 0xc1, 0xfe, 0xe9, 0x89, 0x79, + 0xb7, 0x6f, 0xf3, 0x6d, 0x26, 0xb8, 0x94, 0xc0, 0xb2, 0x93, 0x2e, 0x2a, 0xce, 0xd1, 0x68, 0x57, + 0x02, 0x0b, 0xd4, 0x09, 0xb8, 0x3f, 0x01, 0x97, 0x06, 0x9c, 0x09, 0x70, 0x09, 0x00, 0xa1, 0x57, + 0x9b, 0x3a, 0x55, 0x55, 0xe7, 0x45, 0xb1, 0xce, 0x30, 0x56, 0xbd, 0x51, 0xa2, 0x73, 0xa5, 0xd9, + 0xaa, 0x75, 0x1c, 0x94, 0x25, 0xed, 0x3a, 0xd2, 0xa3, 0x79, 0xd8, 0x5f, 0x56, 0xd1, 0xd1, 0xce, + 0x4e, 0xf1, 0x2b, 0xb4, 0xa7, 0x26, 0x25, 0xe9, 0x88, 0x4f, 0x8a, 0xa5, 0x63, 0xde, 0xa9, 0xc7, + 0xd4, 0x79, 0x8e, 0x7b, 0x69, 0xa7, 0xff, 0xc4, 0x6d, 0xfc, 0x12, 0x61, 0x90, 0x40, 0x82, 0xd8, + 0x4d, 0x2e, 0x7c, 0x77, 0x2a, 0xbf, 0xb2, 0x59, 0x4b, 0xef, 0x69, 0x03, 0xdd, 0x69, 0xaa, 0xcc, + 0xa5, 0x4a, 0x7c, 0x8a, 0xe3, 0xf8, 0x04, 0x3d, 0xcc, 0xdf, 0x4f, 0x8a, 0xd6, 0x14, 0xfa, 0x20, + 0x0f, 0x27, 0xa0, 0x8d, 0xee, 0xe5, 0x8b, 0xd0, 0xaa, 0xab, 0x46, 0xda, 0x66, 0xb2, 0x2a, 0x66, + 0xb6, 0x2a, 0xe6, 0xe7, 0x8c, 0xb0, 0x1b, 0x37, 0x3f, 0xbb, 0x95, 0xe5, 0xaf, 0xae, 0xe6, 0x6c, + 0x64, 0xfd, 0xef, 0x55, 0x74, 0x5c, 0x6a, 0x2a, 0x7e, 0x8f, 0x1e, 0x51, 0x29, 0xc6, 0x01, 0xa7, + 0xaa, 0x6f, 0x2f, 0x90, 0xf4, 0x2a, 0x75, 0xa8, 0x53, 0xf2, 0x72, 0xec, 0x98, 0x71, 0x9a, 0x5b, + 0x32, 0x15, 0xc1, 0xcf, 0xd1, 0x7d, 0x2a, 0xc3, 0x50, 0x0a, 0x77, 0xc2, 0x62, 0x4e, 0x39, 0xa7, + 0x3b, 0x07, 0x49, 0xf0, 0x42, 0xc5, 0xf0, 0x47, 0x74, 0xe8, 0x5d, 0x7f, 0x23, 0x02, 0xb8, 0x60, + 0x6e, 0x3e, 0x6d, 0xd4, 0xd2, 0x7b, 0xfa, 0x60, 0xff, 0xf4, 0xd9, 0x0e, 0x97, 0x33, 0xc6, 0x79, + 0x9c, 0x0b, 0xf3, 0x58, 0x54, 0x62, 0x7c, 0xad, 0xc4, 0xf8, 0xff, 0xe1, 0xe7, 0x10, 0x1d, 0x64, + 0xee, 0x0d, 0x79, 0x04, 0xf8, 0x35, 0x6a, 0x6c, 0xdd, 0x1e, 0x5d, 0x1d, 0x59, 0x98, 0x22, 0xdf, + 0xd3, 0x5a, 0x7c, 0xa4, 0x93, 0x2b, 0xec, 0x0f, 0x37, 0x2b, 0x43, 0xbb, 0x5d, 0x19, 0xda, 0xef, + 0x95, 0xa1, 0x2d, 0xd7, 0x46, 0xe5, 0x76, 0x6d, 0x54, 0x7e, 0xac, 0x8d, 0xca, 0x97, 0x33, 0x9f, + 0xc3, 0x64, 0xee, 0x99, 0x54, 0x86, 0x16, 0x95, 0x21, 0x03, 0x6f, 0x0c, 0x9b, 0x87, 0xe4, 0x0b, + 0x72, 0xf7, 0xda, 0x7b, 0x7b, 0x2a, 0x7e, 0xf6, 0x37, 0x00, 0x00, 0xff, 0xff, 0xab, 0xbe, 0xb8, + 0x21, 0x99, 0x04, 0x00, 0x00, +} + +func (m *Evidence) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Evidence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Evidence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sum != nil { + { + size := m.Sum.Size() + i -= size + if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + } + } + return len(dAtA) - i, nil +} + +func (m *Evidence_DuplicateVoteEvidence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Evidence_DuplicateVoteEvidence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.DuplicateVoteEvidence != nil { + { + size, err := m.DuplicateVoteEvidence.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} +func (m *Evidence_LightClientAttackEvidence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Evidence_LightClientAttackEvidence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.LightClientAttackEvidence != nil { + { + size, err := m.LightClientAttackEvidence.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + return len(dAtA) - i, nil +} +func (m *DuplicateVoteEvidence) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DuplicateVoteEvidence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DuplicateVoteEvidence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err3 != nil { + return 0, err3 + } + i -= n3 + i = encodeVarintEvidence(dAtA, i, uint64(n3)) + i-- + dAtA[i] = 0x2a + if m.ValidatorPower != 0 { + i = encodeVarintEvidence(dAtA, i, uint64(m.ValidatorPower)) + i-- + dAtA[i] = 0x20 + } + if m.TotalVotingPower != 0 { + i = encodeVarintEvidence(dAtA, i, uint64(m.TotalVotingPower)) + i-- + dAtA[i] = 0x18 + } + if m.VoteB != nil { + { + size, err := m.VoteB.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.VoteA != nil { + { + size, err := m.VoteA.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *LightClientAttackEvidence) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *LightClientAttackEvidence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *LightClientAttackEvidence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err6 != nil { + return 0, err6 + } + i -= n6 + i = encodeVarintEvidence(dAtA, i, uint64(n6)) + i-- + dAtA[i] = 0x2a + if m.TotalVotingPower != 0 { + i = encodeVarintEvidence(dAtA, i, uint64(m.TotalVotingPower)) + i-- + dAtA[i] = 0x20 + } + if len(m.ByzantineValidators) > 0 { + for iNdEx := len(m.ByzantineValidators) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ByzantineValidators[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.CommonHeight != 0 { + i = encodeVarintEvidence(dAtA, i, uint64(m.CommonHeight)) + i-- + dAtA[i] = 0x10 + } + if m.ConflictingBlock != nil { + { + size, err := m.ConflictingBlock.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *EvidenceList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EvidenceList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EvidenceList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Evidence) > 0 { + for iNdEx := len(m.Evidence) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Evidence[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintEvidence(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintEvidence(dAtA []byte, offset int, v uint64) int { + offset -= sovEvidence(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Evidence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sum != nil { + n += m.Sum.Size() + } + return n +} + +func (m *Evidence_DuplicateVoteEvidence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.DuplicateVoteEvidence != nil { + l = m.DuplicateVoteEvidence.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + return n +} +func (m *Evidence_LightClientAttackEvidence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.LightClientAttackEvidence != nil { + l = m.LightClientAttackEvidence.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + return n +} +func (m *DuplicateVoteEvidence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VoteA != nil { + l = m.VoteA.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + if m.VoteB != nil { + l = m.VoteB.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + if m.TotalVotingPower != 0 { + n += 1 + sovEvidence(uint64(m.TotalVotingPower)) + } + if m.ValidatorPower != 0 { + n += 1 + sovEvidence(uint64(m.ValidatorPower)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovEvidence(uint64(l)) + return n +} + +func (m *LightClientAttackEvidence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ConflictingBlock != nil { + l = m.ConflictingBlock.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + if m.CommonHeight != 0 { + n += 1 + sovEvidence(uint64(m.CommonHeight)) + } + if len(m.ByzantineValidators) > 0 { + for _, e := range m.ByzantineValidators { + l = e.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + } + if m.TotalVotingPower != 0 { + n += 1 + sovEvidence(uint64(m.TotalVotingPower)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovEvidence(uint64(l)) + return n +} + +func (m *EvidenceList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Evidence) > 0 { + for _, e := range m.Evidence { + l = e.Size() + n += 1 + l + sovEvidence(uint64(l)) + } + } + return n +} + +func sovEvidence(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozEvidence(x uint64) (n int) { + return sovEvidence(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Evidence) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Evidence: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Evidence: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DuplicateVoteEvidence", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &DuplicateVoteEvidence{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Evidence_DuplicateVoteEvidence{v} + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LightClientAttackEvidence", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &LightClientAttackEvidence{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &Evidence_LightClientAttackEvidence{v} + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvidence(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvidence + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DuplicateVoteEvidence) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DuplicateVoteEvidence: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DuplicateVoteEvidence: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteA", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.VoteA == nil { + m.VoteA = &Vote{} + } + if err := m.VoteA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteB", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.VoteB == nil { + m.VoteB = &Vote{} + } + if err := m.VoteB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType) + } + m.TotalVotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TotalVotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorPower", wireType) + } + m.ValidatorPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvidence(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvidence + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *LightClientAttackEvidence) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: LightClientAttackEvidence: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: LightClientAttackEvidence: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConflictingBlock", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ConflictingBlock == nil { + m.ConflictingBlock = &LightBlock{} + } + if err := m.ConflictingBlock.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CommonHeight", wireType) + } + m.CommonHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CommonHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ByzantineValidators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ByzantineValidators = append(m.ByzantineValidators, &Validator{}) + if err := m.ByzantineValidators[len(m.ByzantineValidators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType) + } + m.TotalVotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TotalVotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvidence(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvidence + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EvidenceList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvidenceList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvidenceList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Evidence", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvidence + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthEvidence + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthEvidence + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Evidence = append(m.Evidence, Evidence{}) + if err := m.Evidence[len(m.Evidence)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvidence(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvidence + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipEvidence(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvidence + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvidence + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowEvidence + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthEvidence + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupEvidence + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthEvidence + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthEvidence = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowEvidence = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupEvidence = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/evidence.proto b/proto/tendermint/types/evidence.proto new file mode 100644 index 0000000..cad717d --- /dev/null +++ b/proto/tendermint/types/evidence.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "google/protobuf/timestamp.proto"; +import "tendermint/types/types.proto"; +import "tendermint/types/validator.proto"; + +message Evidence { + oneof sum { + DuplicateVoteEvidence duplicate_vote_evidence = 1; + LightClientAttackEvidence light_client_attack_evidence = 2; + } +} + +// DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes. +message DuplicateVoteEvidence { + tendermint.types.Vote vote_a = 1; + tendermint.types.Vote vote_b = 2; + int64 total_voting_power = 3; + int64 validator_power = 4; + google.protobuf.Timestamp timestamp = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; +} + +// LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client. +message LightClientAttackEvidence { + tendermint.types.LightBlock conflicting_block = 1; + int64 common_height = 2; + repeated tendermint.types.Validator byzantine_validators = 3; + int64 total_voting_power = 4; + google.protobuf.Timestamp timestamp = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; +} + +message EvidenceList { + repeated Evidence evidence = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/tendermint/types/params.pb.go b/proto/tendermint/types/params.pb.go new file mode 100644 index 0000000..bcceb02 --- /dev/null +++ b/proto/tendermint/types/params.pb.go @@ -0,0 +1,2019 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/params.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + _ "github.com/golang/protobuf/ptypes/duration" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// ConsensusParams contains consensus critical parameters that determine the +// validity of blocks. +type ConsensusParams struct { + Block *BlockParams `protobuf:"bytes,1,opt,name=block,proto3" json:"block,omitempty"` + Evidence *EvidenceParams `protobuf:"bytes,2,opt,name=evidence,proto3" json:"evidence,omitempty"` + Validator *ValidatorParams `protobuf:"bytes,3,opt,name=validator,proto3" json:"validator,omitempty"` + Version *VersionParams `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` + Abci *ABCIParams `protobuf:"bytes,5,opt,name=abci,proto3" json:"abci,omitempty"` +} + +func (m *ConsensusParams) Reset() { *m = ConsensusParams{} } +func (m *ConsensusParams) String() string { return proto.CompactTextString(m) } +func (*ConsensusParams) ProtoMessage() {} +func (*ConsensusParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{0} +} +func (m *ConsensusParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConsensusParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ConsensusParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ConsensusParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConsensusParams.Merge(m, src) +} +func (m *ConsensusParams) XXX_Size() int { + return m.Size() +} +func (m *ConsensusParams) XXX_DiscardUnknown() { + xxx_messageInfo_ConsensusParams.DiscardUnknown(m) +} + +var xxx_messageInfo_ConsensusParams proto.InternalMessageInfo + +func (m *ConsensusParams) GetBlock() *BlockParams { + if m != nil { + return m.Block + } + return nil +} + +func (m *ConsensusParams) GetEvidence() *EvidenceParams { + if m != nil { + return m.Evidence + } + return nil +} + +func (m *ConsensusParams) GetValidator() *ValidatorParams { + if m != nil { + return m.Validator + } + return nil +} + +func (m *ConsensusParams) GetVersion() *VersionParams { + if m != nil { + return m.Version + } + return nil +} + +func (m *ConsensusParams) GetAbci() *ABCIParams { + if m != nil { + return m.Abci + } + return nil +} + +// BlockParams contains limits on the block size. +type BlockParams struct { + // Max block size, in bytes. + // Note: must be greater than 0 + MaxBytes int64 `protobuf:"varint,1,opt,name=max_bytes,json=maxBytes,proto3" json:"max_bytes,omitempty"` + // Max gas per block. + // Note: must be greater or equal to -1 + MaxGas int64 `protobuf:"varint,2,opt,name=max_gas,json=maxGas,proto3" json:"max_gas,omitempty"` +} + +func (m *BlockParams) Reset() { *m = BlockParams{} } +func (m *BlockParams) String() string { return proto.CompactTextString(m) } +func (*BlockParams) ProtoMessage() {} +func (*BlockParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{1} +} +func (m *BlockParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockParams.Merge(m, src) +} +func (m *BlockParams) XXX_Size() int { + return m.Size() +} +func (m *BlockParams) XXX_DiscardUnknown() { + xxx_messageInfo_BlockParams.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockParams proto.InternalMessageInfo + +func (m *BlockParams) GetMaxBytes() int64 { + if m != nil { + return m.MaxBytes + } + return 0 +} + +func (m *BlockParams) GetMaxGas() int64 { + if m != nil { + return m.MaxGas + } + return 0 +} + +// EvidenceParams determine how we handle evidence of malfeasance. +type EvidenceParams struct { + // Max age of evidence, in blocks. + // + // The basic formula for calculating this is: MaxAgeDuration / {average block + // time}. + MaxAgeNumBlocks int64 `protobuf:"varint,1,opt,name=max_age_num_blocks,json=maxAgeNumBlocks,proto3" json:"max_age_num_blocks,omitempty"` + // Max age of evidence, in time. + // + // It should correspond with an app's "unbonding period" or other similar + // mechanism for handling [Nothing-At-Stake + // attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). + MaxAgeDuration time.Duration `protobuf:"bytes,2,opt,name=max_age_duration,json=maxAgeDuration,proto3,stdduration" json:"max_age_duration"` + // This sets the maximum size of total evidence in bytes that can be committed in a single block. + // and should fall comfortably under the max block bytes. + // Default is 1048576 or 1MB + MaxBytes int64 `protobuf:"varint,3,opt,name=max_bytes,json=maxBytes,proto3" json:"max_bytes,omitempty"` +} + +func (m *EvidenceParams) Reset() { *m = EvidenceParams{} } +func (m *EvidenceParams) String() string { return proto.CompactTextString(m) } +func (*EvidenceParams) ProtoMessage() {} +func (*EvidenceParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{2} +} +func (m *EvidenceParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EvidenceParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EvidenceParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *EvidenceParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_EvidenceParams.Merge(m, src) +} +func (m *EvidenceParams) XXX_Size() int { + return m.Size() +} +func (m *EvidenceParams) XXX_DiscardUnknown() { + xxx_messageInfo_EvidenceParams.DiscardUnknown(m) +} + +var xxx_messageInfo_EvidenceParams proto.InternalMessageInfo + +func (m *EvidenceParams) GetMaxAgeNumBlocks() int64 { + if m != nil { + return m.MaxAgeNumBlocks + } + return 0 +} + +func (m *EvidenceParams) GetMaxAgeDuration() time.Duration { + if m != nil { + return m.MaxAgeDuration + } + return 0 +} + +func (m *EvidenceParams) GetMaxBytes() int64 { + if m != nil { + return m.MaxBytes + } + return 0 +} + +// ValidatorParams restrict the public key types validators can use. +// NOTE: uses ABCI pubkey naming, not Amino names. +type ValidatorParams struct { + PubKeyTypes []string `protobuf:"bytes,1,rep,name=pub_key_types,json=pubKeyTypes,proto3" json:"pub_key_types,omitempty"` +} + +func (m *ValidatorParams) Reset() { *m = ValidatorParams{} } +func (m *ValidatorParams) String() string { return proto.CompactTextString(m) } +func (*ValidatorParams) ProtoMessage() {} +func (*ValidatorParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{3} +} +func (m *ValidatorParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValidatorParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValidatorParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValidatorParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValidatorParams.Merge(m, src) +} +func (m *ValidatorParams) XXX_Size() int { + return m.Size() +} +func (m *ValidatorParams) XXX_DiscardUnknown() { + xxx_messageInfo_ValidatorParams.DiscardUnknown(m) +} + +var xxx_messageInfo_ValidatorParams proto.InternalMessageInfo + +func (m *ValidatorParams) GetPubKeyTypes() []string { + if m != nil { + return m.PubKeyTypes + } + return nil +} + +// VersionParams contains the ABCI application version. +type VersionParams struct { + App uint64 `protobuf:"varint,1,opt,name=app,proto3" json:"app,omitempty"` +} + +func (m *VersionParams) Reset() { *m = VersionParams{} } +func (m *VersionParams) String() string { return proto.CompactTextString(m) } +func (*VersionParams) ProtoMessage() {} +func (*VersionParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{4} +} +func (m *VersionParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *VersionParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_VersionParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *VersionParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_VersionParams.Merge(m, src) +} +func (m *VersionParams) XXX_Size() int { + return m.Size() +} +func (m *VersionParams) XXX_DiscardUnknown() { + xxx_messageInfo_VersionParams.DiscardUnknown(m) +} + +var xxx_messageInfo_VersionParams proto.InternalMessageInfo + +func (m *VersionParams) GetApp() uint64 { + if m != nil { + return m.App + } + return 0 +} + +// HashedParams is a subset of ConsensusParams. +// +// It is hashed into the Header.ConsensusHash. +type HashedParams struct { + BlockMaxBytes int64 `protobuf:"varint,1,opt,name=block_max_bytes,json=blockMaxBytes,proto3" json:"block_max_bytes,omitempty"` + BlockMaxGas int64 `protobuf:"varint,2,opt,name=block_max_gas,json=blockMaxGas,proto3" json:"block_max_gas,omitempty"` +} + +func (m *HashedParams) Reset() { *m = HashedParams{} } +func (m *HashedParams) String() string { return proto.CompactTextString(m) } +func (*HashedParams) ProtoMessage() {} +func (*HashedParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{5} +} +func (m *HashedParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *HashedParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_HashedParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *HashedParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_HashedParams.Merge(m, src) +} +func (m *HashedParams) XXX_Size() int { + return m.Size() +} +func (m *HashedParams) XXX_DiscardUnknown() { + xxx_messageInfo_HashedParams.DiscardUnknown(m) +} + +var xxx_messageInfo_HashedParams proto.InternalMessageInfo + +func (m *HashedParams) GetBlockMaxBytes() int64 { + if m != nil { + return m.BlockMaxBytes + } + return 0 +} + +func (m *HashedParams) GetBlockMaxGas() int64 { + if m != nil { + return m.BlockMaxGas + } + return 0 +} + +// ABCIParams configure functionality specific to the Application Blockchain Interface. +type ABCIParams struct { + // vote_extensions_enable_height configures the first height during which + // vote extensions will be enabled. During this specified height, and for all + // subsequent heights, precommit messages that do not contain valid extension data + // will be considered invalid. Prior to this height, vote extensions will not + // be used or accepted by validators on the network. + // + // Once enabled, vote extensions will be created by the application in ExtendVote, + // passed to the application for validation in VerifyVoteExtension and given + // to the application to use when proposing a block during PrepareProposal. + VoteExtensionsEnableHeight int64 `protobuf:"varint,1,opt,name=vote_extensions_enable_height,json=voteExtensionsEnableHeight,proto3" json:"vote_extensions_enable_height,omitempty"` +} + +func (m *ABCIParams) Reset() { *m = ABCIParams{} } +func (m *ABCIParams) String() string { return proto.CompactTextString(m) } +func (*ABCIParams) ProtoMessage() {} +func (*ABCIParams) Descriptor() ([]byte, []int) { + return fileDescriptor_e12598271a686f57, []int{6} +} +func (m *ABCIParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ABCIParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ABCIParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ABCIParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_ABCIParams.Merge(m, src) +} +func (m *ABCIParams) XXX_Size() int { + return m.Size() +} +func (m *ABCIParams) XXX_DiscardUnknown() { + xxx_messageInfo_ABCIParams.DiscardUnknown(m) +} + +var xxx_messageInfo_ABCIParams proto.InternalMessageInfo + +func (m *ABCIParams) GetVoteExtensionsEnableHeight() int64 { + if m != nil { + return m.VoteExtensionsEnableHeight + } + return 0 +} + +func init() { + proto.RegisterType((*ConsensusParams)(nil), "tendermint.types.ConsensusParams") + proto.RegisterType((*BlockParams)(nil), "tendermint.types.BlockParams") + proto.RegisterType((*EvidenceParams)(nil), "tendermint.types.EvidenceParams") + proto.RegisterType((*ValidatorParams)(nil), "tendermint.types.ValidatorParams") + proto.RegisterType((*VersionParams)(nil), "tendermint.types.VersionParams") + proto.RegisterType((*HashedParams)(nil), "tendermint.types.HashedParams") + proto.RegisterType((*ABCIParams)(nil), "tendermint.types.ABCIParams") +} + +func init() { proto.RegisterFile("tendermint/types/params.proto", fileDescriptor_e12598271a686f57) } + +var fileDescriptor_e12598271a686f57 = []byte{ + // 576 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x93, 0x3f, 0x6f, 0xd3, 0x4e, + 0x18, 0xc7, 0x73, 0x75, 0xda, 0xa6, 0x4f, 0x7e, 0x69, 0xa2, 0xd3, 0x4f, 0xc2, 0x14, 0xe2, 0x04, + 0x0f, 0xa8, 0x52, 0x25, 0x1b, 0x91, 0x09, 0x84, 0x54, 0x25, 0x25, 0x6a, 0x0b, 0x2a, 0x7f, 0x2c, + 0xc4, 0xd0, 0xc5, 0x3a, 0x27, 0x57, 0xc7, 0x6a, 0xec, 0xb3, 0x7c, 0xe7, 0x28, 0x79, 0x17, 0x8c, + 0x8c, 0x1d, 0x61, 0x65, 0xe2, 0x25, 0x74, 0xec, 0xc8, 0x04, 0x28, 0x59, 0x78, 0x19, 0xc8, 0x67, + 0xbb, 0x6e, 0x12, 0xb6, 0xbb, 0x7b, 0x3e, 0x9f, 0xfb, 0xf3, 0x7d, 0x74, 0xd0, 0x14, 0x34, 0x18, + 0xd2, 0xc8, 0xf7, 0x02, 0x61, 0x8a, 0x59, 0x48, 0xb9, 0x19, 0x92, 0x88, 0xf8, 0xdc, 0x08, 0x23, + 0x26, 0x18, 0x6e, 0x14, 0x65, 0x43, 0x96, 0xf7, 0xfe, 0x77, 0x99, 0xcb, 0x64, 0xd1, 0x4c, 0x46, + 0x29, 0xb7, 0xa7, 0xb9, 0x8c, 0xb9, 0x63, 0x6a, 0xca, 0x99, 0x13, 0x5f, 0x98, 0xc3, 0x38, 0x22, + 0xc2, 0x63, 0x41, 0x5a, 0xd7, 0xbf, 0x6d, 0x40, 0xfd, 0x88, 0x05, 0x9c, 0x06, 0x3c, 0xe6, 0xef, + 0xe4, 0x09, 0xb8, 0x03, 0x9b, 0xce, 0x98, 0x0d, 0x2e, 0x55, 0xd4, 0x46, 0xfb, 0xd5, 0xa7, 0x4d, + 0x63, 0xf5, 0x2c, 0xa3, 0x97, 0x94, 0x53, 0xda, 0x4a, 0x59, 0xfc, 0x02, 0x2a, 0x74, 0xe2, 0x0d, + 0x69, 0x30, 0xa0, 0xea, 0x86, 0xf4, 0xda, 0xeb, 0x5e, 0x3f, 0x23, 0x32, 0xf5, 0xd6, 0xc0, 0x87, + 0xb0, 0x33, 0x21, 0x63, 0x6f, 0x48, 0x04, 0x8b, 0x54, 0x45, 0xea, 0x8f, 0xd6, 0xf5, 0x8f, 0x39, + 0x92, 0xf9, 0x85, 0x83, 0x9f, 0xc1, 0xf6, 0x84, 0x46, 0xdc, 0x63, 0x81, 0x5a, 0x96, 0x7a, 0xeb, + 0x1f, 0x7a, 0x0a, 0x64, 0x72, 0xce, 0xe3, 0x27, 0x50, 0x26, 0xce, 0xc0, 0x53, 0x37, 0xa5, 0xf7, + 0x70, 0xdd, 0xeb, 0xf6, 0x8e, 0x4e, 0x33, 0x49, 0x92, 0xfa, 0x29, 0x54, 0xef, 0x24, 0x80, 0x1f, + 0xc0, 0x8e, 0x4f, 0xa6, 0xb6, 0x33, 0x13, 0x94, 0xcb, 0xcc, 0x14, 0xab, 0xe2, 0x93, 0x69, 0x2f, + 0x99, 0xe3, 0x7b, 0xb0, 0x9d, 0x14, 0x5d, 0xc2, 0x65, 0x2c, 0x8a, 0xb5, 0xe5, 0x93, 0xe9, 0x31, + 0xe1, 0xaf, 0xca, 0x15, 0xa5, 0x51, 0xd6, 0xbf, 0x22, 0xd8, 0x5d, 0x4e, 0x05, 0x1f, 0x00, 0x4e, + 0x0c, 0xe2, 0x52, 0x3b, 0x88, 0x7d, 0x5b, 0xc6, 0x9b, 0xef, 0x5b, 0xf7, 0xc9, 0xb4, 0xeb, 0xd2, + 0x37, 0xb1, 0x2f, 0x2f, 0xc0, 0xf1, 0x19, 0x34, 0x72, 0x38, 0xef, 0x6c, 0x16, 0xff, 0x7d, 0x23, + 0x6d, 0xbd, 0x91, 0xb7, 0xde, 0x78, 0x99, 0x01, 0xbd, 0xca, 0xf5, 0xcf, 0x56, 0xe9, 0xf3, 0xaf, + 0x16, 0xb2, 0x76, 0xd3, 0xfd, 0xf2, 0xca, 0xf2, 0x53, 0x94, 0xe5, 0xa7, 0xe8, 0x87, 0x50, 0x5f, + 0xe9, 0x00, 0xd6, 0xa1, 0x16, 0xc6, 0x8e, 0x7d, 0x49, 0x67, 0xb6, 0xcc, 0x4a, 0x45, 0x6d, 0x65, + 0x7f, 0xc7, 0xaa, 0x86, 0xb1, 0xf3, 0x9a, 0xce, 0x3e, 0x24, 0x4b, 0xcf, 0x2b, 0xdf, 0xaf, 0x5a, + 0xe8, 0xcf, 0x55, 0x0b, 0xe9, 0x07, 0x50, 0x5b, 0xea, 0x01, 0x6e, 0x80, 0x42, 0xc2, 0x50, 0xbe, + 0xad, 0x6c, 0x25, 0xc3, 0x3b, 0xf0, 0x39, 0xfc, 0x77, 0x42, 0xf8, 0x88, 0x0e, 0x33, 0xf6, 0x31, + 0xd4, 0x65, 0x14, 0xf6, 0x6a, 0xd6, 0x35, 0xb9, 0x7c, 0x96, 0x07, 0xae, 0x43, 0xad, 0xe0, 0x8a, + 0xd8, 0xab, 0x39, 0x75, 0x4c, 0xb8, 0xfe, 0x16, 0xa0, 0x68, 0x2a, 0xee, 0x42, 0x73, 0xc2, 0x04, + 0xb5, 0xe9, 0x54, 0xd0, 0x20, 0xb9, 0x1d, 0xb7, 0x69, 0x40, 0x9c, 0x31, 0xb5, 0x47, 0xd4, 0x73, + 0x47, 0x22, 0x3b, 0x67, 0x2f, 0x81, 0xfa, 0xb7, 0x4c, 0x5f, 0x22, 0x27, 0x92, 0xe8, 0xbd, 0xff, + 0x32, 0xd7, 0xd0, 0xf5, 0x5c, 0x43, 0x37, 0x73, 0x0d, 0xfd, 0x9e, 0x6b, 0xe8, 0xd3, 0x42, 0x2b, + 0xdd, 0x2c, 0xb4, 0xd2, 0x8f, 0x85, 0x56, 0x3a, 0xef, 0xb8, 0x9e, 0x18, 0xc5, 0x8e, 0x31, 0x60, + 0xbe, 0x39, 0x60, 0x3e, 0x15, 0xce, 0x85, 0x28, 0x06, 0xe9, 0x9f, 0x5d, 0xfd, 0xee, 0xce, 0x96, + 0x5c, 0xef, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xb9, 0xe8, 0xce, 0x9a, 0x09, 0x04, 0x00, 0x00, +} + +func (this *ConsensusParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ConsensusParams) + if !ok { + that2, ok := that.(ConsensusParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !this.Block.Equal(that1.Block) { + return false + } + if !this.Evidence.Equal(that1.Evidence) { + return false + } + if !this.Validator.Equal(that1.Validator) { + return false + } + if !this.Version.Equal(that1.Version) { + return false + } + if !this.Abci.Equal(that1.Abci) { + return false + } + return true +} +func (this *BlockParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*BlockParams) + if !ok { + that2, ok := that.(BlockParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.MaxBytes != that1.MaxBytes { + return false + } + if this.MaxGas != that1.MaxGas { + return false + } + return true +} +func (this *EvidenceParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*EvidenceParams) + if !ok { + that2, ok := that.(EvidenceParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.MaxAgeNumBlocks != that1.MaxAgeNumBlocks { + return false + } + if this.MaxAgeDuration != that1.MaxAgeDuration { + return false + } + if this.MaxBytes != that1.MaxBytes { + return false + } + return true +} +func (this *ValidatorParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ValidatorParams) + if !ok { + that2, ok := that.(ValidatorParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.PubKeyTypes) != len(that1.PubKeyTypes) { + return false + } + for i := range this.PubKeyTypes { + if this.PubKeyTypes[i] != that1.PubKeyTypes[i] { + return false + } + } + return true +} +func (this *VersionParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*VersionParams) + if !ok { + that2, ok := that.(VersionParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.App != that1.App { + return false + } + return true +} +func (this *HashedParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*HashedParams) + if !ok { + that2, ok := that.(HashedParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.BlockMaxBytes != that1.BlockMaxBytes { + return false + } + if this.BlockMaxGas != that1.BlockMaxGas { + return false + } + return true +} +func (this *ABCIParams) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ABCIParams) + if !ok { + that2, ok := that.(ABCIParams) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.VoteExtensionsEnableHeight != that1.VoteExtensionsEnableHeight { + return false + } + return true +} +func (m *ConsensusParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ConsensusParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsensusParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Abci != nil { + { + size, err := m.Abci.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if m.Version != nil { + { + size, err := m.Version.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.Validator != nil { + { + size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.Evidence != nil { + { + size, err := m.Evidence.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Block != nil { + { + size, err := m.Block.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *BlockParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MaxGas != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxGas)) + i-- + dAtA[i] = 0x10 + } + if m.MaxBytes != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxBytes)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *EvidenceParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EvidenceParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EvidenceParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MaxBytes != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxBytes)) + i-- + dAtA[i] = 0x18 + } + n6, err6 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.MaxAgeDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAgeDuration):]) + if err6 != nil { + return 0, err6 + } + i -= n6 + i = encodeVarintParams(dAtA, i, uint64(n6)) + i-- + dAtA[i] = 0x12 + if m.MaxAgeNumBlocks != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxAgeNumBlocks)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ValidatorParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValidatorParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.PubKeyTypes) > 0 { + for iNdEx := len(m.PubKeyTypes) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.PubKeyTypes[iNdEx]) + copy(dAtA[i:], m.PubKeyTypes[iNdEx]) + i = encodeVarintParams(dAtA, i, uint64(len(m.PubKeyTypes[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *VersionParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VersionParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VersionParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.App != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.App)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *HashedParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *HashedParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *HashedParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.BlockMaxGas != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.BlockMaxGas)) + i-- + dAtA[i] = 0x10 + } + if m.BlockMaxBytes != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.BlockMaxBytes)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ABCIParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ABCIParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ABCIParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.VoteExtensionsEnableHeight != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.VoteExtensionsEnableHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func NewPopulatedValidatorParams(r randyParams, easy bool) *ValidatorParams { + this := &ValidatorParams{} + v1 := r.Intn(10) + this.PubKeyTypes = make([]string, v1) + for i := 0; i < v1; i++ { + this.PubKeyTypes[i] = string(randStringParams(r)) + } + if !easy && r.Intn(10) != 0 { + } + return this +} + +func NewPopulatedVersionParams(r randyParams, easy bool) *VersionParams { + this := &VersionParams{} + this.App = uint64(uint64(r.Uint32())) + if !easy && r.Intn(10) != 0 { + } + return this +} + +type randyParams interface { + Float32() float32 + Float64() float64 + Int63() int64 + Int31() int32 + Uint32() uint32 + Intn(n int) int +} + +func randUTF8RuneParams(r randyParams) rune { + ru := r.Intn(62) + if ru < 10 { + return rune(ru + 48) + } else if ru < 36 { + return rune(ru + 55) + } + return rune(ru + 61) +} +func randStringParams(r randyParams) string { + v2 := r.Intn(100) + tmps := make([]rune, v2) + for i := 0; i < v2; i++ { + tmps[i] = randUTF8RuneParams(r) + } + return string(tmps) +} +func randUnrecognizedParams(r randyParams, maxFieldNumber int) (dAtA []byte) { + l := r.Intn(5) + for i := 0; i < l; i++ { + wire := r.Intn(4) + if wire == 3 { + wire = 5 + } + fieldNumber := maxFieldNumber + r.Intn(100) + dAtA = randFieldParams(dAtA, r, fieldNumber, wire) + } + return dAtA +} +func randFieldParams(dAtA []byte, r randyParams, fieldNumber int, wire int) []byte { + key := uint32(fieldNumber)<<3 | uint32(wire) + switch wire { + case 0: + dAtA = encodeVarintPopulateParams(dAtA, uint64(key)) + v3 := r.Int63() + if r.Intn(2) == 0 { + v3 *= -1 + } + dAtA = encodeVarintPopulateParams(dAtA, uint64(v3)) + case 1: + dAtA = encodeVarintPopulateParams(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + case 2: + dAtA = encodeVarintPopulateParams(dAtA, uint64(key)) + ll := r.Intn(100) + dAtA = encodeVarintPopulateParams(dAtA, uint64(ll)) + for j := 0; j < ll; j++ { + dAtA = append(dAtA, byte(r.Intn(256))) + } + default: + dAtA = encodeVarintPopulateParams(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + } + return dAtA +} +func encodeVarintPopulateParams(dAtA []byte, v uint64) []byte { + for v >= 1<<7 { + dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) + v >>= 7 + } + dAtA = append(dAtA, uint8(v)) + return dAtA +} +func (m *ConsensusParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Block != nil { + l = m.Block.Size() + n += 1 + l + sovParams(uint64(l)) + } + if m.Evidence != nil { + l = m.Evidence.Size() + n += 1 + l + sovParams(uint64(l)) + } + if m.Validator != nil { + l = m.Validator.Size() + n += 1 + l + sovParams(uint64(l)) + } + if m.Version != nil { + l = m.Version.Size() + n += 1 + l + sovParams(uint64(l)) + } + if m.Abci != nil { + l = m.Abci.Size() + n += 1 + l + sovParams(uint64(l)) + } + return n +} + +func (m *BlockParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MaxBytes != 0 { + n += 1 + sovParams(uint64(m.MaxBytes)) + } + if m.MaxGas != 0 { + n += 1 + sovParams(uint64(m.MaxGas)) + } + return n +} + +func (m *EvidenceParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MaxAgeNumBlocks != 0 { + n += 1 + sovParams(uint64(m.MaxAgeNumBlocks)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAgeDuration) + n += 1 + l + sovParams(uint64(l)) + if m.MaxBytes != 0 { + n += 1 + sovParams(uint64(m.MaxBytes)) + } + return n +} + +func (m *ValidatorParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.PubKeyTypes) > 0 { + for _, s := range m.PubKeyTypes { + l = len(s) + n += 1 + l + sovParams(uint64(l)) + } + } + return n +} + +func (m *VersionParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.App != 0 { + n += 1 + sovParams(uint64(m.App)) + } + return n +} + +func (m *HashedParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockMaxBytes != 0 { + n += 1 + sovParams(uint64(m.BlockMaxBytes)) + } + if m.BlockMaxGas != 0 { + n += 1 + sovParams(uint64(m.BlockMaxGas)) + } + return n +} + +func (m *ABCIParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VoteExtensionsEnableHeight != 0 { + n += 1 + sovParams(uint64(m.VoteExtensionsEnableHeight)) + } + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ConsensusParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ConsensusParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsensusParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Block == nil { + m.Block = &BlockParams{} + } + if err := m.Block.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Evidence", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Evidence == nil { + m.Evidence = &EvidenceParams{} + } + if err := m.Evidence.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Validator == nil { + m.Validator = &ValidatorParams{} + } + if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Version == nil { + m.Version = &VersionParams{} + } + if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Abci", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Abci == nil { + m.Abci = &ABCIParams{} + } + if err := m.Abci.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxBytes", wireType) + } + m.MaxBytes = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxBytes |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxGas", wireType) + } + m.MaxGas = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxGas |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EvidenceParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvidenceParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvidenceParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxAgeNumBlocks", wireType) + } + m.MaxAgeNumBlocks = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxAgeNumBlocks |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxAgeDuration", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.MaxAgeDuration, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxBytes", wireType) + } + m.MaxBytes = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxBytes |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKeyTypes", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PubKeyTypes = append(m.PubKeyTypes, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VersionParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VersionParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VersionParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field App", wireType) + } + m.App = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.App |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *HashedParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: HashedParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: HashedParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockMaxBytes", wireType) + } + m.BlockMaxBytes = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockMaxBytes |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockMaxGas", wireType) + } + m.BlockMaxGas = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockMaxGas |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ABCIParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ABCIParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ABCIParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VoteExtensionsEnableHeight", wireType) + } + m.VoteExtensionsEnableHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.VoteExtensionsEnableHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/params.proto b/proto/tendermint/types/params.proto new file mode 100644 index 0000000..7bcfb13 --- /dev/null +++ b/proto/tendermint/types/params.proto @@ -0,0 +1,92 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "google/protobuf/duration.proto"; + +option (gogoproto.equal_all) = true; + +// ConsensusParams contains consensus critical parameters that determine the +// validity of blocks. +message ConsensusParams { + BlockParams block = 1; + EvidenceParams evidence = 2; + ValidatorParams validator = 3; + VersionParams version = 4; + ABCIParams abci = 5; +} + +// BlockParams contains limits on the block size. +message BlockParams { + // Max block size, in bytes. + // Note: must be greater than 0 + int64 max_bytes = 1; + // Max gas per block. + // Note: must be greater or equal to -1 + int64 max_gas = 2; + + reserved 3; // was TimeIotaMs see https://github.com/tendermint/tendermint/pull/5792 +} + +// EvidenceParams determine how we handle evidence of malfeasance. +message EvidenceParams { + // Max age of evidence, in blocks. + // + // The basic formula for calculating this is: MaxAgeDuration / {average block + // time}. + int64 max_age_num_blocks = 1; + + // Max age of evidence, in time. + // + // It should correspond with an app's "unbonding period" or other similar + // mechanism for handling [Nothing-At-Stake + // attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). + google.protobuf.Duration max_age_duration = 2 + [(gogoproto.nullable) = false, (gogoproto.stdduration) = true]; + + // This sets the maximum size of total evidence in bytes that can be committed in a single block. + // and should fall comfortably under the max block bytes. + // Default is 1048576 or 1MB + int64 max_bytes = 3; +} + +// ValidatorParams restrict the public key types validators can use. +// NOTE: uses ABCI pubkey naming, not Amino names. +message ValidatorParams { + option (gogoproto.populate) = true; + option (gogoproto.equal) = true; + + repeated string pub_key_types = 1; +} + +// VersionParams contains the ABCI application version. +message VersionParams { + option (gogoproto.populate) = true; + option (gogoproto.equal) = true; + + uint64 app = 1; +} + +// HashedParams is a subset of ConsensusParams. +// +// It is hashed into the Header.ConsensusHash. +message HashedParams { + int64 block_max_bytes = 1; + int64 block_max_gas = 2; +} + +// ABCIParams configure functionality specific to the Application Blockchain Interface. +message ABCIParams { + // vote_extensions_enable_height configures the first height during which + // vote extensions will be enabled. During this specified height, and for all + // subsequent heights, precommit messages that do not contain valid extension data + // will be considered invalid. Prior to this height, vote extensions will not + // be used or accepted by validators on the network. + // + // Once enabled, vote extensions will be created by the application in ExtendVote, + // passed to the application for validation in VerifyVoteExtension and given + // to the application to use when proposing a block during PrepareProposal. + int64 vote_extensions_enable_height = 1; +} diff --git a/proto/tendermint/types/types.pb.go b/proto/tendermint/types/types.pb.go new file mode 100644 index 0000000..6edc737 --- /dev/null +++ b/proto/tendermint/types/types.pb.go @@ -0,0 +1,5377 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/types.proto + +package types + +import ( + fmt "fmt" + crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + version "github.com/cometbft/cometbft/proto/tendermint/version" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "github.com/cosmos/gogoproto/types" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// SignedMsgType is a type of signed message in the consensus. +type SignedMsgType int32 + +const ( + UnknownType SignedMsgType = 0 + // Votes + PrevoteType SignedMsgType = 1 + PrecommitType SignedMsgType = 2 + // Proposals + ProposalType SignedMsgType = 32 +) + +var SignedMsgType_name = map[int32]string{ + 0: "SIGNED_MSG_TYPE_UNKNOWN", + 1: "SIGNED_MSG_TYPE_PREVOTE", + 2: "SIGNED_MSG_TYPE_PRECOMMIT", + 32: "SIGNED_MSG_TYPE_PROPOSAL", +} + +var SignedMsgType_value = map[string]int32{ + "SIGNED_MSG_TYPE_UNKNOWN": 0, + "SIGNED_MSG_TYPE_PREVOTE": 1, + "SIGNED_MSG_TYPE_PRECOMMIT": 2, + "SIGNED_MSG_TYPE_PROPOSAL": 32, +} + +func (x SignedMsgType) String() string { + return proto.EnumName(SignedMsgType_name, int32(x)) +} + +func (SignedMsgType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{0} +} + +// PartsetHeader +type PartSetHeader struct { + Total uint32 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"` + Hash []byte `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"` +} + +func (m *PartSetHeader) Reset() { *m = PartSetHeader{} } +func (m *PartSetHeader) String() string { return proto.CompactTextString(m) } +func (*PartSetHeader) ProtoMessage() {} +func (*PartSetHeader) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{0} +} +func (m *PartSetHeader) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PartSetHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PartSetHeader.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PartSetHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_PartSetHeader.Merge(m, src) +} +func (m *PartSetHeader) XXX_Size() int { + return m.Size() +} +func (m *PartSetHeader) XXX_DiscardUnknown() { + xxx_messageInfo_PartSetHeader.DiscardUnknown(m) +} + +var xxx_messageInfo_PartSetHeader proto.InternalMessageInfo + +func (m *PartSetHeader) GetTotal() uint32 { + if m != nil { + return m.Total + } + return 0 +} + +func (m *PartSetHeader) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +type Part struct { + Index uint32 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"` + Bytes []byte `protobuf:"bytes,2,opt,name=bytes,proto3" json:"bytes,omitempty"` + Proof crypto.Proof `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof"` +} + +func (m *Part) Reset() { *m = Part{} } +func (m *Part) String() string { return proto.CompactTextString(m) } +func (*Part) ProtoMessage() {} +func (*Part) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{1} +} +func (m *Part) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Part) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Part.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Part) XXX_Merge(src proto.Message) { + xxx_messageInfo_Part.Merge(m, src) +} +func (m *Part) XXX_Size() int { + return m.Size() +} +func (m *Part) XXX_DiscardUnknown() { + xxx_messageInfo_Part.DiscardUnknown(m) +} + +var xxx_messageInfo_Part proto.InternalMessageInfo + +func (m *Part) GetIndex() uint32 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *Part) GetBytes() []byte { + if m != nil { + return m.Bytes + } + return nil +} + +func (m *Part) GetProof() crypto.Proof { + if m != nil { + return m.Proof + } + return crypto.Proof{} +} + +// BlockID +type BlockID struct { + Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + PartSetHeader PartSetHeader `protobuf:"bytes,2,opt,name=part_set_header,json=partSetHeader,proto3" json:"part_set_header"` +} + +func (m *BlockID) Reset() { *m = BlockID{} } +func (m *BlockID) String() string { return proto.CompactTextString(m) } +func (*BlockID) ProtoMessage() {} +func (*BlockID) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{2} +} +func (m *BlockID) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockID.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockID) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockID.Merge(m, src) +} +func (m *BlockID) XXX_Size() int { + return m.Size() +} +func (m *BlockID) XXX_DiscardUnknown() { + xxx_messageInfo_BlockID.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockID proto.InternalMessageInfo + +func (m *BlockID) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *BlockID) GetPartSetHeader() PartSetHeader { + if m != nil { + return m.PartSetHeader + } + return PartSetHeader{} +} + +// Header defines the structure of a block header. +type Header struct { + // basic block info + Version version.Consensus `protobuf:"bytes,1,opt,name=version,proto3" json:"version"` + ChainID string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"` + // prev block info + LastBlockId BlockID `protobuf:"bytes,5,opt,name=last_block_id,json=lastBlockId,proto3" json:"last_block_id"` + // hashes of block data + LastCommitHash []byte `protobuf:"bytes,6,opt,name=last_commit_hash,json=lastCommitHash,proto3" json:"last_commit_hash,omitempty"` + DataHash []byte `protobuf:"bytes,7,opt,name=data_hash,json=dataHash,proto3" json:"data_hash,omitempty"` + // hashes from the app output from the prev block + ValidatorsHash []byte `protobuf:"bytes,8,opt,name=validators_hash,json=validatorsHash,proto3" json:"validators_hash,omitempty"` + NextValidatorsHash []byte `protobuf:"bytes,9,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"` + ConsensusHash []byte `protobuf:"bytes,10,opt,name=consensus_hash,json=consensusHash,proto3" json:"consensus_hash,omitempty"` + AppHash []byte `protobuf:"bytes,11,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` + LastResultsHash []byte `protobuf:"bytes,12,opt,name=last_results_hash,json=lastResultsHash,proto3" json:"last_results_hash,omitempty"` + // consensus info + EvidenceHash []byte `protobuf:"bytes,13,opt,name=evidence_hash,json=evidenceHash,proto3" json:"evidence_hash,omitempty"` + ProposerAddress []byte `protobuf:"bytes,14,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` +} + +func (m *Header) Reset() { *m = Header{} } +func (m *Header) String() string { return proto.CompactTextString(m) } +func (*Header) ProtoMessage() {} +func (*Header) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{3} +} +func (m *Header) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Header.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Header) XXX_Merge(src proto.Message) { + xxx_messageInfo_Header.Merge(m, src) +} +func (m *Header) XXX_Size() int { + return m.Size() +} +func (m *Header) XXX_DiscardUnknown() { + xxx_messageInfo_Header.DiscardUnknown(m) +} + +var xxx_messageInfo_Header proto.InternalMessageInfo + +func (m *Header) GetVersion() version.Consensus { + if m != nil { + return m.Version + } + return version.Consensus{} +} + +func (m *Header) GetChainID() string { + if m != nil { + return m.ChainID + } + return "" +} + +func (m *Header) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Header) GetTime() time.Time { + if m != nil { + return m.Time + } + return time.Time{} +} + +func (m *Header) GetLastBlockId() BlockID { + if m != nil { + return m.LastBlockId + } + return BlockID{} +} + +func (m *Header) GetLastCommitHash() []byte { + if m != nil { + return m.LastCommitHash + } + return nil +} + +func (m *Header) GetDataHash() []byte { + if m != nil { + return m.DataHash + } + return nil +} + +func (m *Header) GetValidatorsHash() []byte { + if m != nil { + return m.ValidatorsHash + } + return nil +} + +func (m *Header) GetNextValidatorsHash() []byte { + if m != nil { + return m.NextValidatorsHash + } + return nil +} + +func (m *Header) GetConsensusHash() []byte { + if m != nil { + return m.ConsensusHash + } + return nil +} + +func (m *Header) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +func (m *Header) GetLastResultsHash() []byte { + if m != nil { + return m.LastResultsHash + } + return nil +} + +func (m *Header) GetEvidenceHash() []byte { + if m != nil { + return m.EvidenceHash + } + return nil +} + +func (m *Header) GetProposerAddress() []byte { + if m != nil { + return m.ProposerAddress + } + return nil +} + +// Data contains the set of transactions included in the block +type Data struct { + // Txs that will be applied by state @ block.Height+1. + // NOTE: not all txs here are valid. We're just agreeing on the order first. + // This means that block.AppHash does not include these txs. + Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` +} + +func (m *Data) Reset() { *m = Data{} } +func (m *Data) String() string { return proto.CompactTextString(m) } +func (*Data) ProtoMessage() {} +func (*Data) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{4} +} +func (m *Data) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Data) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Data.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Data) XXX_Merge(src proto.Message) { + xxx_messageInfo_Data.Merge(m, src) +} +func (m *Data) XXX_Size() int { + return m.Size() +} +func (m *Data) XXX_DiscardUnknown() { + xxx_messageInfo_Data.DiscardUnknown(m) +} + +var xxx_messageInfo_Data proto.InternalMessageInfo + +func (m *Data) GetTxs() [][]byte { + if m != nil { + return m.Txs + } + return nil +} + +// Vote represents a prevote or precommit vote from validators for +// consensus. +type Vote struct { + Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,3,opt,name=round,proto3" json:"round,omitempty"` + BlockID BlockID `protobuf:"bytes,4,opt,name=block_id,json=blockId,proto3" json:"block_id"` + Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + ValidatorAddress []byte `protobuf:"bytes,6,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + ValidatorIndex int32 `protobuf:"varint,7,opt,name=validator_index,json=validatorIndex,proto3" json:"validator_index,omitempty"` + // Vote signature by the validator if they participated in consensus for the + // associated block. + Signature []byte `protobuf:"bytes,8,opt,name=signature,proto3" json:"signature,omitempty"` + // Vote extension provided by the application. Only valid for precommit + // messages. + Extension []byte `protobuf:"bytes,9,opt,name=extension,proto3" json:"extension,omitempty"` + // Vote extension signature by the validator if they participated in + // consensus for the associated block. + // Only valid for precommit messages. + ExtensionSignature []byte `protobuf:"bytes,10,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"` +} + +func (m *Vote) Reset() { *m = Vote{} } +func (m *Vote) String() string { return proto.CompactTextString(m) } +func (*Vote) ProtoMessage() {} +func (*Vote) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{5} +} +func (m *Vote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Vote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Vote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Vote) XXX_Merge(src proto.Message) { + xxx_messageInfo_Vote.Merge(m, src) +} +func (m *Vote) XXX_Size() int { + return m.Size() +} +func (m *Vote) XXX_DiscardUnknown() { + xxx_messageInfo_Vote.DiscardUnknown(m) +} + +var xxx_messageInfo_Vote proto.InternalMessageInfo + +func (m *Vote) GetType() SignedMsgType { + if m != nil { + return m.Type + } + return UnknownType +} + +func (m *Vote) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Vote) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *Vote) GetBlockID() BlockID { + if m != nil { + return m.BlockID + } + return BlockID{} +} + +func (m *Vote) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *Vote) GetValidatorAddress() []byte { + if m != nil { + return m.ValidatorAddress + } + return nil +} + +func (m *Vote) GetValidatorIndex() int32 { + if m != nil { + return m.ValidatorIndex + } + return 0 +} + +func (m *Vote) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +func (m *Vote) GetExtension() []byte { + if m != nil { + return m.Extension + } + return nil +} + +func (m *Vote) GetExtensionSignature() []byte { + if m != nil { + return m.ExtensionSignature + } + return nil +} + +// Commit contains the evidence that a block was committed by a set of validators. +type Commit struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + BlockID BlockID `protobuf:"bytes,3,opt,name=block_id,json=blockId,proto3" json:"block_id"` + Signatures []CommitSig `protobuf:"bytes,4,rep,name=signatures,proto3" json:"signatures"` +} + +func (m *Commit) Reset() { *m = Commit{} } +func (m *Commit) String() string { return proto.CompactTextString(m) } +func (*Commit) ProtoMessage() {} +func (*Commit) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{6} +} +func (m *Commit) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Commit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Commit.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Commit) XXX_Merge(src proto.Message) { + xxx_messageInfo_Commit.Merge(m, src) +} +func (m *Commit) XXX_Size() int { + return m.Size() +} +func (m *Commit) XXX_DiscardUnknown() { + xxx_messageInfo_Commit.DiscardUnknown(m) +} + +var xxx_messageInfo_Commit proto.InternalMessageInfo + +func (m *Commit) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Commit) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *Commit) GetBlockID() BlockID { + if m != nil { + return m.BlockID + } + return BlockID{} +} + +func (m *Commit) GetSignatures() []CommitSig { + if m != nil { + return m.Signatures + } + return nil +} + +// CommitSig is a part of the Vote included in a Commit. +type CommitSig struct { + BlockIdFlag BlockIDFlag `protobuf:"varint,1,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"` + ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"` +} + +func (m *CommitSig) Reset() { *m = CommitSig{} } +func (m *CommitSig) String() string { return proto.CompactTextString(m) } +func (*CommitSig) ProtoMessage() {} +func (*CommitSig) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{7} +} +func (m *CommitSig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CommitSig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CommitSig.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CommitSig) XXX_Merge(src proto.Message) { + xxx_messageInfo_CommitSig.Merge(m, src) +} +func (m *CommitSig) XXX_Size() int { + return m.Size() +} +func (m *CommitSig) XXX_DiscardUnknown() { + xxx_messageInfo_CommitSig.DiscardUnknown(m) +} + +var xxx_messageInfo_CommitSig proto.InternalMessageInfo + +func (m *CommitSig) GetBlockIdFlag() BlockIDFlag { + if m != nil { + return m.BlockIdFlag + } + return BlockIDFlagUnknown +} + +func (m *CommitSig) GetValidatorAddress() []byte { + if m != nil { + return m.ValidatorAddress + } + return nil +} + +func (m *CommitSig) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *CommitSig) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +type ExtendedCommit struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` + BlockID BlockID `protobuf:"bytes,3,opt,name=block_id,json=blockId,proto3" json:"block_id"` + ExtendedSignatures []ExtendedCommitSig `protobuf:"bytes,4,rep,name=extended_signatures,json=extendedSignatures,proto3" json:"extended_signatures"` +} + +func (m *ExtendedCommit) Reset() { *m = ExtendedCommit{} } +func (m *ExtendedCommit) String() string { return proto.CompactTextString(m) } +func (*ExtendedCommit) ProtoMessage() {} +func (*ExtendedCommit) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{8} +} +func (m *ExtendedCommit) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ExtendedCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ExtendedCommit.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ExtendedCommit) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtendedCommit.Merge(m, src) +} +func (m *ExtendedCommit) XXX_Size() int { + return m.Size() +} +func (m *ExtendedCommit) XXX_DiscardUnknown() { + xxx_messageInfo_ExtendedCommit.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtendedCommit proto.InternalMessageInfo + +func (m *ExtendedCommit) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ExtendedCommit) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *ExtendedCommit) GetBlockID() BlockID { + if m != nil { + return m.BlockID + } + return BlockID{} +} + +func (m *ExtendedCommit) GetExtendedSignatures() []ExtendedCommitSig { + if m != nil { + return m.ExtendedSignatures + } + return nil +} + +// ExtendedCommitSig retains all the same fields as CommitSig but adds vote +// extension-related fields. We use two signatures to ensure backwards compatibility. +// That is the digest of the original signature is still the same in prior versions +type ExtendedCommitSig struct { + BlockIdFlag BlockIDFlag `protobuf:"varint,1,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"` + ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"` + // Vote extension data + Extension []byte `protobuf:"bytes,5,opt,name=extension,proto3" json:"extension,omitempty"` + // Vote extension signature + ExtensionSignature []byte `protobuf:"bytes,6,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"` +} + +func (m *ExtendedCommitSig) Reset() { *m = ExtendedCommitSig{} } +func (m *ExtendedCommitSig) String() string { return proto.CompactTextString(m) } +func (*ExtendedCommitSig) ProtoMessage() {} +func (*ExtendedCommitSig) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{9} +} +func (m *ExtendedCommitSig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ExtendedCommitSig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ExtendedCommitSig.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ExtendedCommitSig) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtendedCommitSig.Merge(m, src) +} +func (m *ExtendedCommitSig) XXX_Size() int { + return m.Size() +} +func (m *ExtendedCommitSig) XXX_DiscardUnknown() { + xxx_messageInfo_ExtendedCommitSig.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtendedCommitSig proto.InternalMessageInfo + +func (m *ExtendedCommitSig) GetBlockIdFlag() BlockIDFlag { + if m != nil { + return m.BlockIdFlag + } + return BlockIDFlagUnknown +} + +func (m *ExtendedCommitSig) GetValidatorAddress() []byte { + if m != nil { + return m.ValidatorAddress + } + return nil +} + +func (m *ExtendedCommitSig) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *ExtendedCommitSig) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +func (m *ExtendedCommitSig) GetExtension() []byte { + if m != nil { + return m.Extension + } + return nil +} + +func (m *ExtendedCommitSig) GetExtensionSignature() []byte { + if m != nil { + return m.ExtensionSignature + } + return nil +} + +type Proposal struct { + Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + Round int32 `protobuf:"varint,3,opt,name=round,proto3" json:"round,omitempty"` + PolRound int32 `protobuf:"varint,4,opt,name=pol_round,json=polRound,proto3" json:"pol_round,omitempty"` + BlockID BlockID `protobuf:"bytes,5,opt,name=block_id,json=blockId,proto3" json:"block_id"` + Timestamp time.Time `protobuf:"bytes,6,opt,name=timestamp,proto3,stdtime" json:"timestamp"` + Signature []byte `protobuf:"bytes,7,opt,name=signature,proto3" json:"signature,omitempty"` +} + +func (m *Proposal) Reset() { *m = Proposal{} } +func (m *Proposal) String() string { return proto.CompactTextString(m) } +func (*Proposal) ProtoMessage() {} +func (*Proposal) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{10} +} +func (m *Proposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Proposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Proposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_Proposal.Merge(m, src) +} +func (m *Proposal) XXX_Size() int { + return m.Size() +} +func (m *Proposal) XXX_DiscardUnknown() { + xxx_messageInfo_Proposal.DiscardUnknown(m) +} + +var xxx_messageInfo_Proposal proto.InternalMessageInfo + +func (m *Proposal) GetType() SignedMsgType { + if m != nil { + return m.Type + } + return UnknownType +} + +func (m *Proposal) GetHeight() int64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Proposal) GetRound() int32 { + if m != nil { + return m.Round + } + return 0 +} + +func (m *Proposal) GetPolRound() int32 { + if m != nil { + return m.PolRound + } + return 0 +} + +func (m *Proposal) GetBlockID() BlockID { + if m != nil { + return m.BlockID + } + return BlockID{} +} + +func (m *Proposal) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + +func (m *Proposal) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +type SignedHeader struct { + Header *Header `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` + Commit *Commit `protobuf:"bytes,2,opt,name=commit,proto3" json:"commit,omitempty"` +} + +func (m *SignedHeader) Reset() { *m = SignedHeader{} } +func (m *SignedHeader) String() string { return proto.CompactTextString(m) } +func (*SignedHeader) ProtoMessage() {} +func (*SignedHeader) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{11} +} +func (m *SignedHeader) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignedHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignedHeader.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SignedHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignedHeader.Merge(m, src) +} +func (m *SignedHeader) XXX_Size() int { + return m.Size() +} +func (m *SignedHeader) XXX_DiscardUnknown() { + xxx_messageInfo_SignedHeader.DiscardUnknown(m) +} + +var xxx_messageInfo_SignedHeader proto.InternalMessageInfo + +func (m *SignedHeader) GetHeader() *Header { + if m != nil { + return m.Header + } + return nil +} + +func (m *SignedHeader) GetCommit() *Commit { + if m != nil { + return m.Commit + } + return nil +} + +type LightBlock struct { + SignedHeader *SignedHeader `protobuf:"bytes,1,opt,name=signed_header,json=signedHeader,proto3" json:"signed_header,omitempty"` + ValidatorSet *ValidatorSet `protobuf:"bytes,2,opt,name=validator_set,json=validatorSet,proto3" json:"validator_set,omitempty"` +} + +func (m *LightBlock) Reset() { *m = LightBlock{} } +func (m *LightBlock) String() string { return proto.CompactTextString(m) } +func (*LightBlock) ProtoMessage() {} +func (*LightBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{12} +} +func (m *LightBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *LightBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_LightBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *LightBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_LightBlock.Merge(m, src) +} +func (m *LightBlock) XXX_Size() int { + return m.Size() +} +func (m *LightBlock) XXX_DiscardUnknown() { + xxx_messageInfo_LightBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_LightBlock proto.InternalMessageInfo + +func (m *LightBlock) GetSignedHeader() *SignedHeader { + if m != nil { + return m.SignedHeader + } + return nil +} + +func (m *LightBlock) GetValidatorSet() *ValidatorSet { + if m != nil { + return m.ValidatorSet + } + return nil +} + +type BlockMeta struct { + BlockID BlockID `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id"` + BlockSize int64 `protobuf:"varint,2,opt,name=block_size,json=blockSize,proto3" json:"block_size,omitempty"` + Header Header `protobuf:"bytes,3,opt,name=header,proto3" json:"header"` + NumTxs int64 `protobuf:"varint,4,opt,name=num_txs,json=numTxs,proto3" json:"num_txs,omitempty"` +} + +func (m *BlockMeta) Reset() { *m = BlockMeta{} } +func (m *BlockMeta) String() string { return proto.CompactTextString(m) } +func (*BlockMeta) ProtoMessage() {} +func (*BlockMeta) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{13} +} +func (m *BlockMeta) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BlockMeta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BlockMeta.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *BlockMeta) XXX_Merge(src proto.Message) { + xxx_messageInfo_BlockMeta.Merge(m, src) +} +func (m *BlockMeta) XXX_Size() int { + return m.Size() +} +func (m *BlockMeta) XXX_DiscardUnknown() { + xxx_messageInfo_BlockMeta.DiscardUnknown(m) +} + +var xxx_messageInfo_BlockMeta proto.InternalMessageInfo + +func (m *BlockMeta) GetBlockID() BlockID { + if m != nil { + return m.BlockID + } + return BlockID{} +} + +func (m *BlockMeta) GetBlockSize() int64 { + if m != nil { + return m.BlockSize + } + return 0 +} + +func (m *BlockMeta) GetHeader() Header { + if m != nil { + return m.Header + } + return Header{} +} + +func (m *BlockMeta) GetNumTxs() int64 { + if m != nil { + return m.NumTxs + } + return 0 +} + +// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree. +type TxProof struct { + RootHash []byte `protobuf:"bytes,1,opt,name=root_hash,json=rootHash,proto3" json:"root_hash,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` + Proof *crypto.Proof `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof,omitempty"` +} + +func (m *TxProof) Reset() { *m = TxProof{} } +func (m *TxProof) String() string { return proto.CompactTextString(m) } +func (*TxProof) ProtoMessage() {} +func (*TxProof) Descriptor() ([]byte, []int) { + return fileDescriptor_d3a6e55e2345de56, []int{14} +} +func (m *TxProof) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TxProof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TxProof.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *TxProof) XXX_Merge(src proto.Message) { + xxx_messageInfo_TxProof.Merge(m, src) +} +func (m *TxProof) XXX_Size() int { + return m.Size() +} +func (m *TxProof) XXX_DiscardUnknown() { + xxx_messageInfo_TxProof.DiscardUnknown(m) +} + +var xxx_messageInfo_TxProof proto.InternalMessageInfo + +func (m *TxProof) GetRootHash() []byte { + if m != nil { + return m.RootHash + } + return nil +} + +func (m *TxProof) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *TxProof) GetProof() *crypto.Proof { + if m != nil { + return m.Proof + } + return nil +} + +func init() { + proto.RegisterEnum("tendermint.types.SignedMsgType", SignedMsgType_name, SignedMsgType_value) + proto.RegisterType((*PartSetHeader)(nil), "tendermint.types.PartSetHeader") + proto.RegisterType((*Part)(nil), "tendermint.types.Part") + proto.RegisterType((*BlockID)(nil), "tendermint.types.BlockID") + proto.RegisterType((*Header)(nil), "tendermint.types.Header") + proto.RegisterType((*Data)(nil), "tendermint.types.Data") + proto.RegisterType((*Vote)(nil), "tendermint.types.Vote") + proto.RegisterType((*Commit)(nil), "tendermint.types.Commit") + proto.RegisterType((*CommitSig)(nil), "tendermint.types.CommitSig") + proto.RegisterType((*ExtendedCommit)(nil), "tendermint.types.ExtendedCommit") + proto.RegisterType((*ExtendedCommitSig)(nil), "tendermint.types.ExtendedCommitSig") + proto.RegisterType((*Proposal)(nil), "tendermint.types.Proposal") + proto.RegisterType((*SignedHeader)(nil), "tendermint.types.SignedHeader") + proto.RegisterType((*LightBlock)(nil), "tendermint.types.LightBlock") + proto.RegisterType((*BlockMeta)(nil), "tendermint.types.BlockMeta") + proto.RegisterType((*TxProof)(nil), "tendermint.types.TxProof") +} + +func init() { proto.RegisterFile("tendermint/types/types.proto", fileDescriptor_d3a6e55e2345de56) } + +var fileDescriptor_d3a6e55e2345de56 = []byte{ + // 1310 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x57, 0xcf, 0x6f, 0x1b, 0x45, + 0x14, 0xce, 0xda, 0xeb, 0x5f, 0xcf, 0x76, 0xe2, 0x2c, 0x11, 0x75, 0xdd, 0xc6, 0xb1, 0x5c, 0x01, + 0xa1, 0xa0, 0x4d, 0x95, 0x22, 0x04, 0x07, 0x0e, 0xf9, 0x45, 0x1b, 0x51, 0x27, 0xd6, 0xda, 0x2d, + 0xa2, 0x97, 0xd5, 0xda, 0x3b, 0xb1, 0x97, 0xda, 0x3b, 0xab, 0xdd, 0x71, 0x70, 0xfa, 0x17, 0xa0, + 0x9e, 0x7a, 0xe2, 0xd6, 0x13, 0x1c, 0xb8, 0x83, 0xc4, 0x15, 0x71, 0xea, 0xb1, 0x37, 0xb8, 0x50, + 0x20, 0x95, 0xf8, 0x3b, 0xd0, 0xbc, 0x99, 0xdd, 0xb5, 0xe3, 0x18, 0xaa, 0xa8, 0x02, 0x89, 0x8b, + 0xb5, 0xf3, 0xde, 0xf7, 0xde, 0xbc, 0x79, 0xdf, 0x37, 0xa3, 0x67, 0xb8, 0xca, 0x88, 0x6b, 0x13, + 0x7f, 0xe8, 0xb8, 0x6c, 0x83, 0x9d, 0x78, 0x24, 0x10, 0xbf, 0xba, 0xe7, 0x53, 0x46, 0xb5, 0x52, + 0xec, 0xd5, 0xd1, 0x5e, 0x59, 0xe9, 0xd1, 0x1e, 0x45, 0xe7, 0x06, 0xff, 0x12, 0xb8, 0xca, 0x5a, + 0x8f, 0xd2, 0xde, 0x80, 0x6c, 0xe0, 0xaa, 0x33, 0x3a, 0xda, 0x60, 0xce, 0x90, 0x04, 0xcc, 0x1a, + 0x7a, 0x12, 0xb0, 0x3a, 0xb1, 0x4d, 0xd7, 0x3f, 0xf1, 0x18, 0xe5, 0x58, 0x7a, 0x24, 0xdd, 0xd5, + 0x09, 0xf7, 0x31, 0xf1, 0x03, 0x87, 0xba, 0x93, 0x75, 0x54, 0x6a, 0x33, 0x55, 0x1e, 0x5b, 0x03, + 0xc7, 0xb6, 0x18, 0xf5, 0x05, 0xa2, 0xfe, 0x21, 0x14, 0x9b, 0x96, 0xcf, 0x5a, 0x84, 0xdd, 0x26, + 0x96, 0x4d, 0x7c, 0x6d, 0x05, 0x52, 0x8c, 0x32, 0x6b, 0x50, 0x56, 0x6a, 0xca, 0x7a, 0xd1, 0x10, + 0x0b, 0x4d, 0x03, 0xb5, 0x6f, 0x05, 0xfd, 0x72, 0xa2, 0xa6, 0xac, 0x17, 0x0c, 0xfc, 0xae, 0xf7, + 0x41, 0xe5, 0xa1, 0x3c, 0xc2, 0x71, 0x6d, 0x32, 0x0e, 0x23, 0x70, 0xc1, 0xad, 0x9d, 0x13, 0x46, + 0x02, 0x19, 0x22, 0x16, 0xda, 0x7b, 0x90, 0xc2, 0xfa, 0xcb, 0xc9, 0x9a, 0xb2, 0x9e, 0xdf, 0x2c, + 0xeb, 0x13, 0x8d, 0x12, 0xe7, 0xd3, 0x9b, 0xdc, 0xbf, 0xad, 0x3e, 0x7d, 0xbe, 0xb6, 0x60, 0x08, + 0x70, 0x7d, 0x00, 0x99, 0xed, 0x01, 0xed, 0x3e, 0xd8, 0xdf, 0x8d, 0x0a, 0x51, 0xe2, 0x42, 0xb4, + 0x06, 0x2c, 0x79, 0x96, 0xcf, 0xcc, 0x80, 0x30, 0xb3, 0x8f, 0xa7, 0xc0, 0x4d, 0xf3, 0x9b, 0x6b, + 0xfa, 0x59, 0x1e, 0xf4, 0xa9, 0xc3, 0xca, 0x5d, 0x8a, 0xde, 0xa4, 0xb1, 0xfe, 0xa7, 0x0a, 0x69, + 0xd9, 0x8c, 0x8f, 0x20, 0x23, 0xdb, 0x8a, 0x1b, 0xe6, 0x37, 0x57, 0x27, 0x33, 0x4a, 0x97, 0xbe, + 0x43, 0xdd, 0x80, 0xb8, 0xc1, 0x28, 0x90, 0xf9, 0xc2, 0x18, 0xed, 0x4d, 0xc8, 0x76, 0xfb, 0x96, + 0xe3, 0x9a, 0x8e, 0x8d, 0x15, 0xe5, 0xb6, 0xf3, 0xa7, 0xcf, 0xd7, 0x32, 0x3b, 0xdc, 0xb6, 0xbf, + 0x6b, 0x64, 0xd0, 0xb9, 0x6f, 0x6b, 0xaf, 0x43, 0xba, 0x4f, 0x9c, 0x5e, 0x9f, 0x61, 0x5b, 0x92, + 0x86, 0x5c, 0x69, 0x1f, 0x80, 0xca, 0x05, 0x51, 0x56, 0x71, 0xef, 0x8a, 0x2e, 0xd4, 0xa2, 0x87, + 0x6a, 0xd1, 0xdb, 0xa1, 0x5a, 0xb6, 0xb3, 0x7c, 0xe3, 0xc7, 0xbf, 0xad, 0x29, 0x06, 0x46, 0x68, + 0x3b, 0x50, 0x1c, 0x58, 0x01, 0x33, 0x3b, 0xbc, 0x6d, 0x7c, 0xfb, 0x14, 0xa6, 0xb8, 0x3c, 0xdb, + 0x10, 0xd9, 0x58, 0x59, 0x7a, 0x9e, 0x47, 0x09, 0x93, 0xad, 0xad, 0x43, 0x09, 0x93, 0x74, 0xe9, + 0x70, 0xe8, 0x30, 0x13, 0xfb, 0x9e, 0xc6, 0xbe, 0x2f, 0x72, 0xfb, 0x0e, 0x9a, 0x6f, 0x73, 0x06, + 0xae, 0x40, 0xce, 0xb6, 0x98, 0x25, 0x20, 0x19, 0x84, 0x64, 0xb9, 0x01, 0x9d, 0x6f, 0xc1, 0x52, + 0xa4, 0xba, 0x40, 0x40, 0xb2, 0x22, 0x4b, 0x6c, 0x46, 0xe0, 0x0d, 0x58, 0x71, 0xc9, 0x98, 0x99, + 0x67, 0xd1, 0x39, 0x44, 0x6b, 0xdc, 0x77, 0x6f, 0x3a, 0xe2, 0x0d, 0x58, 0xec, 0x86, 0xcd, 0x17, + 0x58, 0x40, 0x6c, 0x31, 0xb2, 0x22, 0xec, 0x32, 0x64, 0x2d, 0xcf, 0x13, 0x80, 0x3c, 0x02, 0x32, + 0x96, 0xe7, 0xa1, 0xeb, 0x3a, 0x2c, 0xe3, 0x19, 0x7d, 0x12, 0x8c, 0x06, 0x4c, 0x26, 0x29, 0x20, + 0x66, 0x89, 0x3b, 0x0c, 0x61, 0x47, 0xec, 0x35, 0x28, 0x92, 0x63, 0xc7, 0x26, 0x6e, 0x97, 0x08, + 0x5c, 0x11, 0x71, 0x85, 0xd0, 0x88, 0xa0, 0xb7, 0xa1, 0xe4, 0xf9, 0xd4, 0xa3, 0x01, 0xf1, 0x4d, + 0xcb, 0xb6, 0x7d, 0x12, 0x04, 0xe5, 0x45, 0x91, 0x2f, 0xb4, 0x6f, 0x09, 0x73, 0xbd, 0x0c, 0xea, + 0xae, 0xc5, 0x2c, 0xad, 0x04, 0x49, 0x36, 0x0e, 0xca, 0x4a, 0x2d, 0xb9, 0x5e, 0x30, 0xf8, 0x67, + 0xfd, 0x87, 0x24, 0xa8, 0xf7, 0x28, 0x23, 0xda, 0x4d, 0x50, 0x39, 0x4d, 0xa8, 0xbe, 0xc5, 0xf3, + 0xf4, 0xdc, 0x72, 0x7a, 0x2e, 0xb1, 0x1b, 0x41, 0xaf, 0x7d, 0xe2, 0x11, 0x03, 0xc1, 0x13, 0x72, + 0x4a, 0x4c, 0xc9, 0x69, 0x05, 0x52, 0x3e, 0x1d, 0xb9, 0x36, 0xaa, 0x2c, 0x65, 0x88, 0x85, 0xb6, + 0x07, 0xd9, 0x48, 0x25, 0xea, 0x3f, 0xa9, 0x64, 0x89, 0xab, 0x84, 0x6b, 0x58, 0x1a, 0x8c, 0x4c, + 0x47, 0x8a, 0x65, 0x1b, 0x72, 0xd1, 0xe3, 0x25, 0xd5, 0xf6, 0x72, 0x82, 0x8d, 0xc3, 0xb4, 0x77, + 0x60, 0x39, 0xe2, 0x3e, 0x6a, 0x9e, 0x50, 0x5c, 0x29, 0x72, 0xc8, 0xee, 0x4d, 0xc9, 0xca, 0x14, + 0x0f, 0x50, 0x06, 0xcf, 0x15, 0xcb, 0x6a, 0x1f, 0x5f, 0xa2, 0xab, 0x90, 0x0b, 0x9c, 0x9e, 0x6b, + 0xb1, 0x91, 0x4f, 0xa4, 0xf2, 0x62, 0x03, 0xf7, 0x92, 0x31, 0x23, 0x2e, 0x5e, 0x72, 0xa1, 0xb4, + 0xd8, 0xa0, 0x6d, 0xc0, 0x6b, 0xd1, 0xc2, 0x8c, 0xb3, 0x08, 0x95, 0x69, 0x91, 0xab, 0x15, 0x7a, + 0xea, 0x3f, 0x2a, 0x90, 0x16, 0x17, 0x63, 0x82, 0x06, 0xe5, 0x7c, 0x1a, 0x12, 0xf3, 0x68, 0x48, + 0x5e, 0x9c, 0x86, 0x2d, 0x80, 0xa8, 0xcc, 0xa0, 0xac, 0xd6, 0x92, 0xeb, 0xf9, 0xcd, 0x2b, 0xb3, + 0x89, 0x44, 0x89, 0x2d, 0xa7, 0x27, 0xef, 0xfd, 0x44, 0x50, 0xfd, 0x57, 0x05, 0x72, 0x91, 0x5f, + 0xdb, 0x82, 0x62, 0x58, 0x97, 0x79, 0x34, 0xb0, 0x7a, 0x52, 0x8a, 0xab, 0x73, 0x8b, 0xfb, 0x78, + 0x60, 0xf5, 0x8c, 0xbc, 0xac, 0x87, 0x2f, 0xce, 0xa7, 0x35, 0x31, 0x87, 0xd6, 0x29, 0x1d, 0x25, + 0x2f, 0xa6, 0xa3, 0x29, 0xc6, 0xd5, 0x33, 0x8c, 0xd7, 0xff, 0x50, 0x60, 0x71, 0x6f, 0x8c, 0xe5, + 0xdb, 0xff, 0x25, 0x55, 0xf7, 0xa5, 0xb6, 0x6c, 0x62, 0x9b, 0x33, 0x9c, 0x5d, 0x9b, 0xcd, 0x38, + 0x5d, 0x73, 0xcc, 0x9d, 0x16, 0x66, 0x69, 0xc5, 0x1c, 0x7e, 0x9f, 0x80, 0xe5, 0x19, 0xfc, 0xff, + 0x8f, 0xcb, 0xe9, 0xdb, 0x9b, 0x7a, 0xc9, 0xdb, 0x9b, 0x9e, 0x7b, 0x7b, 0xbf, 0x4b, 0x40, 0xb6, + 0x89, 0xaf, 0xb4, 0x35, 0xf8, 0x37, 0xde, 0xde, 0x2b, 0x90, 0xf3, 0xe8, 0xc0, 0x14, 0x1e, 0x15, + 0x3d, 0x59, 0x8f, 0x0e, 0x8c, 0x19, 0x99, 0xa5, 0x5e, 0xd1, 0xc3, 0x9c, 0x7e, 0x05, 0x24, 0x64, + 0xce, 0x5e, 0x28, 0x1f, 0x0a, 0xa2, 0x15, 0x72, 0x6a, 0xba, 0xc1, 0x7b, 0x80, 0x63, 0x98, 0x32, + 0x3b, 0xe5, 0x89, 0xb2, 0x05, 0xd2, 0x90, 0x38, 0x1e, 0x21, 0x86, 0x0c, 0x39, 0xb8, 0x95, 0xe7, + 0xbd, 0x58, 0x86, 0xc4, 0xd5, 0xbf, 0x52, 0x00, 0xee, 0xf0, 0xce, 0xe2, 0x79, 0xf9, 0xbc, 0x13, + 0x60, 0x09, 0xe6, 0xd4, 0xce, 0xd5, 0x79, 0xa4, 0xc9, 0xfd, 0x0b, 0xc1, 0x64, 0xdd, 0x3b, 0x50, + 0x8c, 0xb5, 0x1d, 0x90, 0xb0, 0x98, 0x73, 0x92, 0x44, 0x63, 0x48, 0x8b, 0x30, 0xa3, 0x70, 0x3c, + 0xb1, 0xaa, 0xff, 0xa4, 0x40, 0x0e, 0x6b, 0x6a, 0x10, 0x66, 0x4d, 0x71, 0xa8, 0x5c, 0x9c, 0xc3, + 0x55, 0x00, 0x91, 0x26, 0x70, 0x1e, 0x12, 0xa9, 0xac, 0x1c, 0x5a, 0x5a, 0xce, 0x43, 0xa2, 0xbd, + 0x1f, 0x35, 0x3c, 0xf9, 0xf7, 0x0d, 0x97, 0x2f, 0x46, 0xd8, 0xf6, 0x4b, 0x90, 0x71, 0x47, 0x43, + 0x93, 0x0f, 0x1f, 0xaa, 0x50, 0xab, 0x3b, 0x1a, 0xb6, 0xc7, 0x41, 0xfd, 0x73, 0xc8, 0xb4, 0xc7, + 0x38, 0x88, 0x73, 0x89, 0xfa, 0x94, 0xca, 0xe9, 0x4f, 0x4c, 0xdd, 0x59, 0x6e, 0xc0, 0x61, 0x47, + 0x03, 0x95, 0x8f, 0x79, 0xe1, 0xdf, 0x02, 0xfe, 0xad, 0xe9, 0x2f, 0x39, 0xe2, 0xcb, 0xe1, 0xfe, + 0xfa, 0xcf, 0x0a, 0x14, 0xa7, 0x6e, 0x92, 0xf6, 0x2e, 0x5c, 0x6a, 0xed, 0xdf, 0x3a, 0xd8, 0xdb, + 0x35, 0x1b, 0xad, 0x5b, 0x66, 0xfb, 0xb3, 0xe6, 0x9e, 0x79, 0xf7, 0xe0, 0x93, 0x83, 0xc3, 0x4f, + 0x0f, 0x4a, 0x0b, 0x95, 0xa5, 0x47, 0x4f, 0x6a, 0xf9, 0xbb, 0xee, 0x03, 0x97, 0x7e, 0xe1, 0xce, + 0x43, 0x37, 0x8d, 0xbd, 0x7b, 0x87, 0xed, 0xbd, 0x92, 0x22, 0xd0, 0x4d, 0x9f, 0x1c, 0x53, 0x46, + 0x10, 0x7d, 0x03, 0x2e, 0x9f, 0x83, 0xde, 0x39, 0x6c, 0x34, 0xf6, 0xdb, 0xa5, 0x44, 0x65, 0xf9, + 0xd1, 0x93, 0x5a, 0xb1, 0xe9, 0x13, 0xa1, 0x32, 0x8c, 0xd0, 0xa1, 0x3c, 0x1b, 0x71, 0xd8, 0x3c, + 0x6c, 0x6d, 0xdd, 0x29, 0xd5, 0x2a, 0xa5, 0x47, 0x4f, 0x6a, 0x85, 0xf0, 0xc9, 0xe0, 0xf8, 0x4a, + 0xf6, 0xcb, 0xaf, 0xab, 0x0b, 0xdf, 0x7e, 0x53, 0x55, 0xb6, 0x1b, 0x4f, 0x4f, 0xab, 0xca, 0xb3, + 0xd3, 0xaa, 0xf2, 0xfb, 0x69, 0x55, 0x79, 0xfc, 0xa2, 0xba, 0xf0, 0xec, 0x45, 0x75, 0xe1, 0x97, + 0x17, 0xd5, 0x85, 0xfb, 0x37, 0x7b, 0x0e, 0xeb, 0x8f, 0x3a, 0x7a, 0x97, 0x0e, 0x37, 0xba, 0x74, + 0x48, 0x58, 0xe7, 0x88, 0xc5, 0x1f, 0xe2, 0x6f, 0xe2, 0xd9, 0xbf, 0x6e, 0x9d, 0x34, 0xda, 0x6f, + 0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0x8c, 0xb6, 0xa1, 0x4e, 0x7b, 0x0e, 0x00, 0x00, +} + +func (m *PartSetHeader) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PartSetHeader) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PartSetHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0x12 + } + if m.Total != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Total)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Part) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Part) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Part) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Proof.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if len(m.Bytes) > 0 { + i -= len(m.Bytes) + copy(dAtA[i:], m.Bytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Bytes))) + i-- + dAtA[i] = 0x12 + } + if m.Index != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *BlockID) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockID) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockID) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.PartSetHeader.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Header) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Header) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Header) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ProposerAddress) > 0 { + i -= len(m.ProposerAddress) + copy(dAtA[i:], m.ProposerAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress))) + i-- + dAtA[i] = 0x72 + } + if len(m.EvidenceHash) > 0 { + i -= len(m.EvidenceHash) + copy(dAtA[i:], m.EvidenceHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.EvidenceHash))) + i-- + dAtA[i] = 0x6a + } + if len(m.LastResultsHash) > 0 { + i -= len(m.LastResultsHash) + copy(dAtA[i:], m.LastResultsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LastResultsHash))) + i-- + dAtA[i] = 0x62 + } + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x5a + } + if len(m.ConsensusHash) > 0 { + i -= len(m.ConsensusHash) + copy(dAtA[i:], m.ConsensusHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ConsensusHash))) + i-- + dAtA[i] = 0x52 + } + if len(m.NextValidatorsHash) > 0 { + i -= len(m.NextValidatorsHash) + copy(dAtA[i:], m.NextValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash))) + i-- + dAtA[i] = 0x4a + } + if len(m.ValidatorsHash) > 0 { + i -= len(m.ValidatorsHash) + copy(dAtA[i:], m.ValidatorsHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorsHash))) + i-- + dAtA[i] = 0x42 + } + if len(m.DataHash) > 0 { + i -= len(m.DataHash) + copy(dAtA[i:], m.DataHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.DataHash))) + i-- + dAtA[i] = 0x3a + } + if len(m.LastCommitHash) > 0 { + i -= len(m.LastCommitHash) + copy(dAtA[i:], m.LastCommitHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LastCommitHash))) + i-- + dAtA[i] = 0x32 + } + { + size, err := m.LastBlockId.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):]) + if err4 != nil { + return 0, err4 + } + i -= n4 + i = encodeVarintTypes(dAtA, i, uint64(n4)) + i-- + dAtA[i] = 0x22 + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x18 + } + if len(m.ChainID) > 0 { + i -= len(m.ChainID) + copy(dAtA[i:], m.ChainID) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainID))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Version.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Data) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Data) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Data) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Txs) > 0 { + for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Txs[iNdEx]) + copy(dAtA[i:], m.Txs[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Vote) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Vote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ExtensionSignature) > 0 { + i -= len(m.ExtensionSignature) + copy(dAtA[i:], m.ExtensionSignature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature))) + i-- + dAtA[i] = 0x52 + } + if len(m.Extension) > 0 { + i -= len(m.Extension) + copy(dAtA[i:], m.Extension) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Extension))) + i-- + dAtA[i] = 0x4a + } + if len(m.Signature) > 0 { + i -= len(m.Signature) + copy(dAtA[i:], m.Signature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature))) + i-- + dAtA[i] = 0x42 + } + if m.ValidatorIndex != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.ValidatorIndex)) + i-- + dAtA[i] = 0x38 + } + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0x32 + } + n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err6 != nil { + return 0, err6 + } + i -= n6 + i = encodeVarintTypes(dAtA, i, uint64(n6)) + i-- + dAtA[i] = 0x2a + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x18 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Commit) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Commit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signatures) > 0 { + for iNdEx := len(m.Signatures) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Signatures[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *CommitSig) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CommitSig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CommitSig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signature) > 0 { + i -= len(m.Signature) + copy(dAtA[i:], m.Signature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature))) + i-- + dAtA[i] = 0x22 + } + n9, err9 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err9 != nil { + return 0, err9 + } + i -= n9 + i = encodeVarintTypes(dAtA, i, uint64(n9)) + i-- + dAtA[i] = 0x1a + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0x12 + } + if m.BlockIdFlag != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ExtendedCommit) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExtendedCommit) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ExtendedCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ExtendedSignatures) > 0 { + for iNdEx := len(m.ExtendedSignatures) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ExtendedSignatures[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x10 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ExtendedCommitSig) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExtendedCommitSig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ExtendedCommitSig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ExtensionSignature) > 0 { + i -= len(m.ExtensionSignature) + copy(dAtA[i:], m.ExtensionSignature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature))) + i-- + dAtA[i] = 0x32 + } + if len(m.Extension) > 0 { + i -= len(m.Extension) + copy(dAtA[i:], m.Extension) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Extension))) + i-- + dAtA[i] = 0x2a + } + if len(m.Signature) > 0 { + i -= len(m.Signature) + copy(dAtA[i:], m.Signature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature))) + i-- + dAtA[i] = 0x22 + } + n11, err11 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err11 != nil { + return 0, err11 + } + i -= n11 + i = encodeVarintTypes(dAtA, i, uint64(n11)) + i-- + dAtA[i] = 0x1a + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0x12 + } + if m.BlockIdFlag != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Proposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Proposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signature) > 0 { + i -= len(m.Signature) + copy(dAtA[i:], m.Signature) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature))) + i-- + dAtA[i] = 0x3a + } + n12, err12 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err12 != nil { + return 0, err12 + } + i -= n12 + i = encodeVarintTypes(dAtA, i, uint64(n12)) + i-- + dAtA[i] = 0x32 + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + if m.PolRound != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.PolRound)) + i-- + dAtA[i] = 0x20 + } + if m.Round != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Round)) + i-- + dAtA[i] = 0x18 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if m.Type != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *SignedHeader) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignedHeader) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignedHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Commit != nil { + { + size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Header != nil { + { + size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *LightBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *LightBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *LightBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ValidatorSet != nil { + { + size, err := m.ValidatorSet.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.SignedHeader != nil { + { + size, err := m.SignedHeader.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *BlockMeta) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockMeta) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BlockMeta) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.NumTxs != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.NumTxs)) + i-- + dAtA[i] = 0x20 + } + { + size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.BlockSize != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockSize)) + i-- + dAtA[i] = 0x10 + } + { + size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *TxProof) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxProof) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TxProof) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Proof != nil { + { + size, err := m.Proof.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x12 + } + if len(m.RootHash) > 0 { + i -= len(m.RootHash) + copy(dAtA[i:], m.RootHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.RootHash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PartSetHeader) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Total != 0 { + n += 1 + sovTypes(uint64(m.Total)) + } + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Part) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Index != 0 { + n += 1 + sovTypes(uint64(m.Index)) + } + l = len(m.Bytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.Proof.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *BlockID) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.PartSetHeader.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *Header) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Version.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.ChainID) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time) + n += 1 + l + sovTypes(uint64(l)) + l = m.LastBlockId.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.LastCommitHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.DataHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.NextValidatorsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ConsensusHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.LastResultsHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.EvidenceHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ProposerAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Data) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Txs) > 0 { + for _, b := range m.Txs { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *Vote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.ValidatorIndex != 0 { + n += 1 + sovTypes(uint64(m.ValidatorIndex)) + } + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Extension) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ExtensionSignature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Commit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.Signatures) > 0 { + for _, e := range m.Signatures { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *CommitSig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockIdFlag != 0 { + n += 1 + sovTypes(uint64(m.BlockIdFlag)) + } + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ExtendedCommit) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + if len(m.ExtendedSignatures) > 0 { + for _, e := range m.ExtendedSignatures { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ExtendedCommitSig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockIdFlag != 0 { + n += 1 + sovTypes(uint64(m.BlockIdFlag)) + } + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Extension) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ExtensionSignature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Proposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovTypes(uint64(m.Type)) + } + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + if m.Round != 0 { + n += 1 + sovTypes(uint64(m.Round)) + } + if m.PolRound != 0 { + n += 1 + sovTypes(uint64(m.PolRound)) + } + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovTypes(uint64(l)) + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *SignedHeader) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Header != nil { + l = m.Header.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.Commit != nil { + l = m.Commit.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *LightBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SignedHeader != nil { + l = m.SignedHeader.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.ValidatorSet != nil { + l = m.ValidatorSet.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *BlockMeta) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.BlockID.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.BlockSize != 0 { + n += 1 + sovTypes(uint64(m.BlockSize)) + } + l = m.Header.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.NumTxs != 0 { + n += 1 + sovTypes(uint64(m.NumTxs)) + } + return n +} + +func (m *TxProof) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.RootHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Proof != nil { + l = m.Proof.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PartSetHeader) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PartSetHeader: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PartSetHeader: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) + } + m.Total = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Total |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Part) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Part: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Part: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Bytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Bytes = append(m.Bytes[:0], dAtA[iNdEx:postIndex]...) + if m.Bytes == nil { + m.Bytes = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Proof.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockID) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockID: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockID: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) + if m.Hash == nil { + m.Hash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartSetHeader", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PartSetHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Header) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Header: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Header: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlockId", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastBlockId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastCommitHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LastCommitHash = append(m.LastCommitHash[:0], dAtA[iNdEx:postIndex]...) + if m.LastCommitHash == nil { + m.LastCommitHash = []byte{} + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...) + if m.DataHash == nil { + m.DataHash = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorsHash = append(m.ValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorsHash == nil { + m.ValidatorsHash = []byte{} + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) + if m.NextValidatorsHash == nil { + m.NextValidatorsHash = []byte{} + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsensusHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ConsensusHash = append(m.ConsensusHash[:0], dAtA[iNdEx:postIndex]...) + if m.ConsensusHash == nil { + m.ConsensusHash = []byte{} + } + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastResultsHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LastResultsHash = append(m.LastResultsHash[:0], dAtA[iNdEx:postIndex]...) + if m.LastResultsHash == nil { + m.LastResultsHash = []byte{} + } + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EvidenceHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.EvidenceHash = append(m.EvidenceHash[:0], dAtA[iNdEx:postIndex]...) + if m.EvidenceHash == nil { + m.EvidenceHash = []byte{} + } + iNdEx = postIndex + case 14: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ProposerAddress == nil { + m.ProposerAddress = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Data) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Data: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Data: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx)) + copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Vote) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Vote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Vote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorAddress == nil { + m.ValidatorAddress = []byte{} + } + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorIndex", wireType) + } + m.ValidatorIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorIndex |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Extension = append(m.Extension[:0], dAtA[iNdEx:postIndex]...) + if m.Extension == nil { + m.Extension = []byte{} + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...) + if m.ExtensionSignature == nil { + m.ExtensionSignature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Commit) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Commit: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Commit: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signatures = append(m.Signatures, CommitSig{}) + if err := m.Signatures[len(m.Signatures)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CommitSig) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CommitSig: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CommitSig: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType) + } + m.BlockIdFlag = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockIdFlag |= BlockIDFlag(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorAddress == nil { + m.ValidatorAddress = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExtendedCommit) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExtendedCommit: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExtendedCommit: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtendedSignatures", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ExtendedSignatures = append(m.ExtendedSignatures, ExtendedCommitSig{}) + if err := m.ExtendedSignatures[len(m.ExtendedSignatures)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExtendedCommitSig) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExtendedCommitSig: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExtendedCommitSig: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType) + } + m.BlockIdFlag = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockIdFlag |= BlockIDFlag(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorAddress == nil { + m.ValidatorAddress = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Extension = append(m.Extension[:0], dAtA[iNdEx:postIndex]...) + if m.Extension == nil { + m.Extension = []byte{} + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...) + if m.ExtensionSignature == nil { + m.ExtensionSignature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Proposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Proposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Proposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= SignedMsgType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType) + } + m.Round = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Round |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PolRound", wireType) + } + m.PolRound = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PolRound |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignedHeader) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignedHeader: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignedHeader: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Header == nil { + m.Header = &Header{} + } + if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Commit == nil { + m.Commit = &Commit{} + } + if err := m.Commit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *LightBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: LightBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: LightBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignedHeader", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SignedHeader == nil { + m.SignedHeader = &SignedHeader{} + } + if err := m.SignedHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSet", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ValidatorSet == nil { + m.ValidatorSet = &ValidatorSet{} + } + if err := m.ValidatorSet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockMeta) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockMeta: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockMeta: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockSize", wireType) + } + m.BlockSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockSize |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NumTxs", wireType) + } + m.NumTxs = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.NumTxs |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxProof) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxProof: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxProof: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RootHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RootHash = append(m.RootHash[:0], dAtA[iNdEx:postIndex]...) + if m.RootHash == nil { + m.RootHash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Proof == nil { + m.Proof = &crypto.Proof{} + } + if err := m.Proof.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/types.proto b/proto/tendermint/types/types.proto new file mode 100644 index 0000000..147641b --- /dev/null +++ b/proto/tendermint/types/types.proto @@ -0,0 +1,178 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "google/protobuf/timestamp.proto"; +import "tendermint/crypto/proof.proto"; +import "tendermint/version/types.proto"; +import "tendermint/types/validator.proto"; + +// SignedMsgType is a type of signed message in the consensus. +enum SignedMsgType { + option (gogoproto.goproto_enum_stringer) = true; + option (gogoproto.goproto_enum_prefix) = false; + + SIGNED_MSG_TYPE_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "UnknownType"]; + // Votes + SIGNED_MSG_TYPE_PREVOTE = 1 [(gogoproto.enumvalue_customname) = "PrevoteType"]; + SIGNED_MSG_TYPE_PRECOMMIT = 2 [(gogoproto.enumvalue_customname) = "PrecommitType"]; + + // Proposals + SIGNED_MSG_TYPE_PROPOSAL = 32 [(gogoproto.enumvalue_customname) = "ProposalType"]; +} + +// PartsetHeader +message PartSetHeader { + uint32 total = 1; + bytes hash = 2; +} + +message Part { + uint32 index = 1; + bytes bytes = 2; + tendermint.crypto.Proof proof = 3 [(gogoproto.nullable) = false]; +} + +// BlockID +message BlockID { + bytes hash = 1; + PartSetHeader part_set_header = 2 [(gogoproto.nullable) = false]; +} + +// -------------------------------- + +// Header defines the structure of a block header. +message Header { + // basic block info + tendermint.version.Consensus version = 1 [(gogoproto.nullable) = false]; + string chain_id = 2 [(gogoproto.customname) = "ChainID"]; + int64 height = 3; + google.protobuf.Timestamp time = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + + // prev block info + BlockID last_block_id = 5 [(gogoproto.nullable) = false]; + + // hashes of block data + bytes last_commit_hash = 6; // commit from validators from the last block + bytes data_hash = 7; // transactions + + // hashes from the app output from the prev block + bytes validators_hash = 8; // validators for the current block + bytes next_validators_hash = 9; // validators for the next block + bytes consensus_hash = 10; // consensus params for current block + bytes app_hash = 11; // state after txs from the previous block + bytes last_results_hash = 12; // root hash of all results from the txs from the previous block + + // consensus info + bytes evidence_hash = 13; // evidence included in the block + bytes proposer_address = 14; // original proposer of the block +} + +// Data contains the set of transactions included in the block +message Data { + // Txs that will be applied by state @ block.Height+1. + // NOTE: not all txs here are valid. We're just agreeing on the order first. + // This means that block.AppHash does not include these txs. + repeated bytes txs = 1; +} + +// Vote represents a prevote or precommit vote from validators for +// consensus. +message Vote { + SignedMsgType type = 1; + int64 height = 2; + int32 round = 3; + BlockID block_id = 4 + [(gogoproto.nullable) = false, (gogoproto.customname) = "BlockID"]; // zero if vote is nil. + google.protobuf.Timestamp timestamp = 5 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes validator_address = 6; + int32 validator_index = 7; + // Vote signature by the validator if they participated in consensus for the + // associated block. + bytes signature = 8; + // Vote extension provided by the application. Only valid for precommit + // messages. + bytes extension = 9; + // Vote extension signature by the validator if they participated in + // consensus for the associated block. + // Only valid for precommit messages. + bytes extension_signature = 10; +} + +// Commit contains the evidence that a block was committed by a set of validators. +message Commit { + int64 height = 1; + int32 round = 2; + BlockID block_id = 3 [(gogoproto.nullable) = false, (gogoproto.customname) = "BlockID"]; + repeated CommitSig signatures = 4 [(gogoproto.nullable) = false]; +} + +// CommitSig is a part of the Vote included in a Commit. +message CommitSig { + tendermint.types.BlockIDFlag block_id_flag = 1; + bytes validator_address = 2; + google.protobuf.Timestamp timestamp = 3 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes signature = 4; +} + +message ExtendedCommit { + int64 height = 1; + int32 round = 2; + BlockID block_id = 3 + [(gogoproto.nullable) = false, (gogoproto.customname) = "BlockID"]; + repeated ExtendedCommitSig extended_signatures = 4 [(gogoproto.nullable) = false]; +} + +// ExtendedCommitSig retains all the same fields as CommitSig but adds vote +// extension-related fields. We use two signatures to ensure backwards compatibility. +// That is the digest of the original signature is still the same in prior versions +message ExtendedCommitSig { + tendermint.types.BlockIDFlag block_id_flag = 1; + bytes validator_address = 2; + google.protobuf.Timestamp timestamp = 3 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes signature = 4; + // Vote extension data + bytes extension = 5; + // Vote extension signature + bytes extension_signature = 6; +} + +message Proposal { + SignedMsgType type = 1; + int64 height = 2; + int32 round = 3; + int32 pol_round = 4; + BlockID block_id = 5 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; + google.protobuf.Timestamp timestamp = 6 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + bytes signature = 7; +} + +message SignedHeader { + Header header = 1; + Commit commit = 2; +} + +message LightBlock { + SignedHeader signed_header = 1; + tendermint.types.ValidatorSet validator_set = 2; +} + +message BlockMeta { + BlockID block_id = 1 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; + int64 block_size = 2; + Header header = 3 [(gogoproto.nullable) = false]; + int64 num_txs = 4; +} + +// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree. +message TxProof { + bytes root_hash = 1; + bytes data = 2; + tendermint.crypto.Proof proof = 3; +} diff --git a/proto/tendermint/types/validator.pb.go b/proto/tendermint/types/validator.pb.go new file mode 100644 index 0000000..66fa228 --- /dev/null +++ b/proto/tendermint/types/validator.pb.go @@ -0,0 +1,986 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/types/validator.proto + +package types + +import ( + fmt "fmt" + crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// BlockIdFlag indicates which BlockID the signature is for +type BlockIDFlag int32 + +const ( + BlockIDFlagUnknown BlockIDFlag = 0 + BlockIDFlagAbsent BlockIDFlag = 1 + BlockIDFlagCommit BlockIDFlag = 2 + BlockIDFlagNil BlockIDFlag = 3 +) + +var BlockIDFlag_name = map[int32]string{ + 0: "BLOCK_ID_FLAG_UNKNOWN", + 1: "BLOCK_ID_FLAG_ABSENT", + 2: "BLOCK_ID_FLAG_COMMIT", + 3: "BLOCK_ID_FLAG_NIL", +} + +var BlockIDFlag_value = map[string]int32{ + "BLOCK_ID_FLAG_UNKNOWN": 0, + "BLOCK_ID_FLAG_ABSENT": 1, + "BLOCK_ID_FLAG_COMMIT": 2, + "BLOCK_ID_FLAG_NIL": 3, +} + +func (x BlockIDFlag) String() string { + return proto.EnumName(BlockIDFlag_name, int32(x)) +} + +func (BlockIDFlag) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_4e92274df03d3088, []int{0} +} + +type ValidatorSet struct { + Validators []*Validator `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` + Proposer *Validator `protobuf:"bytes,2,opt,name=proposer,proto3" json:"proposer,omitempty"` + TotalVotingPower int64 `protobuf:"varint,3,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` +} + +func (m *ValidatorSet) Reset() { *m = ValidatorSet{} } +func (m *ValidatorSet) String() string { return proto.CompactTextString(m) } +func (*ValidatorSet) ProtoMessage() {} +func (*ValidatorSet) Descriptor() ([]byte, []int) { + return fileDescriptor_4e92274df03d3088, []int{0} +} +func (m *ValidatorSet) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValidatorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValidatorSet.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValidatorSet) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValidatorSet.Merge(m, src) +} +func (m *ValidatorSet) XXX_Size() int { + return m.Size() +} +func (m *ValidatorSet) XXX_DiscardUnknown() { + xxx_messageInfo_ValidatorSet.DiscardUnknown(m) +} + +var xxx_messageInfo_ValidatorSet proto.InternalMessageInfo + +func (m *ValidatorSet) GetValidators() []*Validator { + if m != nil { + return m.Validators + } + return nil +} + +func (m *ValidatorSet) GetProposer() *Validator { + if m != nil { + return m.Proposer + } + return nil +} + +func (m *ValidatorSet) GetTotalVotingPower() int64 { + if m != nil { + return m.TotalVotingPower + } + return 0 +} + +type Validator struct { + Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + PubKey crypto.PublicKey `protobuf:"bytes,2,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` + VotingPower int64 `protobuf:"varint,3,opt,name=voting_power,json=votingPower,proto3" json:"voting_power,omitempty"` + ProposerPriority int64 `protobuf:"varint,4,opt,name=proposer_priority,json=proposerPriority,proto3" json:"proposer_priority,omitempty"` +} + +func (m *Validator) Reset() { *m = Validator{} } +func (m *Validator) String() string { return proto.CompactTextString(m) } +func (*Validator) ProtoMessage() {} +func (*Validator) Descriptor() ([]byte, []int) { + return fileDescriptor_4e92274df03d3088, []int{1} +} +func (m *Validator) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Validator) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Validator.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Validator) XXX_Merge(src proto.Message) { + xxx_messageInfo_Validator.Merge(m, src) +} +func (m *Validator) XXX_Size() int { + return m.Size() +} +func (m *Validator) XXX_DiscardUnknown() { + xxx_messageInfo_Validator.DiscardUnknown(m) +} + +var xxx_messageInfo_Validator proto.InternalMessageInfo + +func (m *Validator) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + +func (m *Validator) GetPubKey() crypto.PublicKey { + if m != nil { + return m.PubKey + } + return crypto.PublicKey{} +} + +func (m *Validator) GetVotingPower() int64 { + if m != nil { + return m.VotingPower + } + return 0 +} + +func (m *Validator) GetProposerPriority() int64 { + if m != nil { + return m.ProposerPriority + } + return 0 +} + +type SimpleValidator struct { + PubKey *crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key,omitempty"` + VotingPower int64 `protobuf:"varint,2,opt,name=voting_power,json=votingPower,proto3" json:"voting_power,omitempty"` +} + +func (m *SimpleValidator) Reset() { *m = SimpleValidator{} } +func (m *SimpleValidator) String() string { return proto.CompactTextString(m) } +func (*SimpleValidator) ProtoMessage() {} +func (*SimpleValidator) Descriptor() ([]byte, []int) { + return fileDescriptor_4e92274df03d3088, []int{2} +} +func (m *SimpleValidator) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SimpleValidator) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SimpleValidator.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SimpleValidator) XXX_Merge(src proto.Message) { + xxx_messageInfo_SimpleValidator.Merge(m, src) +} +func (m *SimpleValidator) XXX_Size() int { + return m.Size() +} +func (m *SimpleValidator) XXX_DiscardUnknown() { + xxx_messageInfo_SimpleValidator.DiscardUnknown(m) +} + +var xxx_messageInfo_SimpleValidator proto.InternalMessageInfo + +func (m *SimpleValidator) GetPubKey() *crypto.PublicKey { + if m != nil { + return m.PubKey + } + return nil +} + +func (m *SimpleValidator) GetVotingPower() int64 { + if m != nil { + return m.VotingPower + } + return 0 +} + +func init() { + proto.RegisterEnum("tendermint.types.BlockIDFlag", BlockIDFlag_name, BlockIDFlag_value) + proto.RegisterType((*ValidatorSet)(nil), "tendermint.types.ValidatorSet") + proto.RegisterType((*Validator)(nil), "tendermint.types.Validator") + proto.RegisterType((*SimpleValidator)(nil), "tendermint.types.SimpleValidator") +} + +func init() { proto.RegisterFile("tendermint/types/validator.proto", fileDescriptor_4e92274df03d3088) } + +var fileDescriptor_4e92274df03d3088 = []byte{ + // 502 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x93, 0xcd, 0x6e, 0xd3, 0x40, + 0x14, 0x85, 0x3d, 0x4d, 0xd5, 0x96, 0x49, 0x04, 0xce, 0xa8, 0x45, 0x91, 0xa9, 0x8c, 0xe9, 0x2a, + 0xfc, 0xc8, 0x16, 0x54, 0x88, 0x45, 0x57, 0x49, 0x4a, 0x51, 0x94, 0xc4, 0x89, 0x92, 0xb6, 0x48, + 0x6c, 0xac, 0x38, 0x19, 0xcc, 0xc8, 0x3f, 0x33, 0x1a, 0x4f, 0x52, 0xf9, 0x0d, 0x50, 0x56, 0xbc, + 0x40, 0x56, 0xb0, 0x60, 0xcd, 0x53, 0x74, 0xd9, 0x1d, 0xac, 0x10, 0x4a, 0x5e, 0x04, 0xc5, 0x6e, + 0x62, 0xb7, 0x01, 0x75, 0x77, 0x7d, 0xcf, 0x39, 0xf7, 0x7e, 0x1e, 0xe9, 0x42, 0x4d, 0xe0, 0x60, + 0x88, 0xb9, 0x4f, 0x02, 0x61, 0x88, 0x88, 0xe1, 0xd0, 0x18, 0xf7, 0x3d, 0x32, 0xec, 0x0b, 0xca, + 0x75, 0xc6, 0xa9, 0xa0, 0x48, 0x4e, 0x1d, 0x7a, 0xec, 0x50, 0x76, 0x1d, 0xea, 0xd0, 0x58, 0x34, + 0x16, 0x55, 0xe2, 0x53, 0xf6, 0x33, 0x93, 0x06, 0x3c, 0x62, 0x82, 0x1a, 0x2e, 0x8e, 0xc2, 0x44, + 0x3d, 0xf8, 0x01, 0x60, 0xe1, 0x7c, 0x39, 0xb9, 0x87, 0x05, 0x3a, 0x82, 0x70, 0xb5, 0x29, 0x2c, + 0x01, 0x2d, 0x57, 0xce, 0xbf, 0x7a, 0xa4, 0xdf, 0xde, 0xa5, 0xaf, 0x32, 0xdd, 0x8c, 0x1d, 0xbd, + 0x81, 0x3b, 0x8c, 0x53, 0x46, 0x43, 0xcc, 0x4b, 0x1b, 0x1a, 0xb8, 0x2b, 0xba, 0x32, 0xa3, 0x17, + 0x10, 0x09, 0x2a, 0xfa, 0x9e, 0x35, 0xa6, 0x82, 0x04, 0x8e, 0xc5, 0xe8, 0x05, 0xe6, 0xa5, 0x9c, + 0x06, 0xca, 0xb9, 0xae, 0x1c, 0x2b, 0xe7, 0xb1, 0xd0, 0x59, 0xf4, 0x17, 0xd0, 0xf7, 0x56, 0x53, + 0x50, 0x09, 0x6e, 0xf7, 0x87, 0x43, 0x8e, 0xc3, 0x05, 0x2e, 0x28, 0x17, 0xba, 0xcb, 0x4f, 0x74, + 0x04, 0xb7, 0xd9, 0xc8, 0xb6, 0x5c, 0x1c, 0x5d, 0xd3, 0xec, 0x67, 0x69, 0x92, 0xc7, 0xd0, 0x3b, + 0x23, 0xdb, 0x23, 0x83, 0x06, 0x8e, 0xaa, 0x9b, 0x97, 0xbf, 0x1f, 0x4b, 0xdd, 0x2d, 0x36, 0xb2, + 0x1b, 0x38, 0x42, 0x4f, 0x60, 0xe1, 0x1f, 0x30, 0xf9, 0x71, 0xca, 0x81, 0x9e, 0xc3, 0xe2, 0xf2, + 0x0f, 0x2c, 0xc6, 0x09, 0xe5, 0x44, 0x44, 0xa5, 0xcd, 0x04, 0x7a, 0x29, 0x74, 0xae, 0xfb, 0x07, + 0x2e, 0x7c, 0xd0, 0x23, 0x3e, 0xf3, 0x70, 0x4a, 0xfe, 0x3a, 0xe5, 0x03, 0x77, 0xf3, 0xfd, 0x97, + 0x6c, 0x63, 0x8d, 0xec, 0xd9, 0x4f, 0x00, 0xf3, 0x55, 0x8f, 0x0e, 0xdc, 0xfa, 0xf1, 0x89, 0xd7, + 0x77, 0xd0, 0x4b, 0xb8, 0x57, 0x6d, 0xb6, 0x6b, 0x0d, 0xab, 0x7e, 0x6c, 0x9d, 0x34, 0x2b, 0xef, + 0xac, 0x33, 0xb3, 0x61, 0xb6, 0xdf, 0x9b, 0xb2, 0xa4, 0x3c, 0x9c, 0x4c, 0x35, 0x94, 0xf1, 0x9e, + 0x05, 0x6e, 0x40, 0x2f, 0x02, 0x64, 0xc0, 0xdd, 0x9b, 0x91, 0x4a, 0xb5, 0xf7, 0xd6, 0x3c, 0x95, + 0x81, 0xb2, 0x37, 0x99, 0x6a, 0xc5, 0x4c, 0xa2, 0x62, 0x87, 0x38, 0x10, 0xeb, 0x81, 0x5a, 0xbb, + 0xd5, 0xaa, 0x9f, 0xca, 0x1b, 0x6b, 0x81, 0x1a, 0xf5, 0x7d, 0x22, 0xd0, 0x53, 0x58, 0xbc, 0x19, + 0x30, 0xeb, 0x4d, 0x39, 0xa7, 0xa0, 0xc9, 0x54, 0xbb, 0x9f, 0x71, 0x9b, 0xc4, 0x53, 0x76, 0x3e, + 0x7f, 0x55, 0xa5, 0xef, 0xdf, 0x54, 0x50, 0x6d, 0x5d, 0xce, 0x54, 0x70, 0x35, 0x53, 0xc1, 0x9f, + 0x99, 0x0a, 0xbe, 0xcc, 0x55, 0xe9, 0x6a, 0xae, 0x4a, 0xbf, 0xe6, 0xaa, 0xf4, 0xe1, 0xd0, 0x21, + 0xe2, 0xd3, 0xc8, 0xd6, 0x07, 0xd4, 0x37, 0x06, 0xd4, 0xc7, 0xc2, 0xfe, 0x28, 0xd2, 0x22, 0xb9, + 0x8b, 0xdb, 0x57, 0x65, 0x6f, 0xc5, 0xfd, 0xc3, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbb, 0x8c, + 0xe3, 0x20, 0x70, 0x03, 0x00, 0x00, +} + +func (m *ValidatorSet) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorSet) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValidatorSet) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TotalVotingPower != 0 { + i = encodeVarintValidator(dAtA, i, uint64(m.TotalVotingPower)) + i-- + dAtA[i] = 0x18 + } + if m.Proposer != nil { + { + size, err := m.Proposer.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintValidator(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Validators) > 0 { + for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintValidator(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Validator) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Validator) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Validator) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ProposerPriority != 0 { + i = encodeVarintValidator(dAtA, i, uint64(m.ProposerPriority)) + i-- + dAtA[i] = 0x20 + } + if m.VotingPower != 0 { + i = encodeVarintValidator(dAtA, i, uint64(m.VotingPower)) + i-- + dAtA[i] = 0x18 + } + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintValidator(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintValidator(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *SimpleValidator) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SimpleValidator) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SimpleValidator) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.VotingPower != 0 { + i = encodeVarintValidator(dAtA, i, uint64(m.VotingPower)) + i-- + dAtA[i] = 0x10 + } + if m.PubKey != nil { + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintValidator(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintValidator(dAtA []byte, offset int, v uint64) int { + offset -= sovValidator(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *ValidatorSet) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Validators) > 0 { + for _, e := range m.Validators { + l = e.Size() + n += 1 + l + sovValidator(uint64(l)) + } + } + if m.Proposer != nil { + l = m.Proposer.Size() + n += 1 + l + sovValidator(uint64(l)) + } + if m.TotalVotingPower != 0 { + n += 1 + sovValidator(uint64(m.TotalVotingPower)) + } + return n +} + +func (m *Validator) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovValidator(uint64(l)) + } + l = m.PubKey.Size() + n += 1 + l + sovValidator(uint64(l)) + if m.VotingPower != 0 { + n += 1 + sovValidator(uint64(m.VotingPower)) + } + if m.ProposerPriority != 0 { + n += 1 + sovValidator(uint64(m.ProposerPriority)) + } + return n +} + +func (m *SimpleValidator) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PubKey != nil { + l = m.PubKey.Size() + n += 1 + l + sovValidator(uint64(l)) + } + if m.VotingPower != 0 { + n += 1 + sovValidator(uint64(m.VotingPower)) + } + return n +} + +func sovValidator(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozValidator(x uint64) (n int) { + return sovValidator(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ValidatorSet) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorSet: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorSet: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthValidator + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validators = append(m.Validators, &Validator{}) + if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Proposer", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthValidator + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Proposer == nil { + m.Proposer = &Validator{} + } + if err := m.Proposer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType) + } + m.TotalVotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TotalVotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipValidator(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthValidator + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Validator) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Validator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Validator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthValidator + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthValidator + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingPower", wireType) + } + m.VotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.VotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ProposerPriority", wireType) + } + m.ProposerPriority = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ProposerPriority |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipValidator(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthValidator + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SimpleValidator) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SimpleValidator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SimpleValidator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthValidator + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PubKey == nil { + m.PubKey = &crypto.PublicKey{} + } + if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingPower", wireType) + } + m.VotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.VotingPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipValidator(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthValidator + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipValidator(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthValidator + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupValidator + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthValidator + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthValidator = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowValidator = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupValidator = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/types/validator.proto b/proto/tendermint/types/validator.proto new file mode 100644 index 0000000..a006cdd --- /dev/null +++ b/proto/tendermint/types/validator.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; +package tendermint.types; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/types"; + +import "gogoproto/gogo.proto"; +import "tendermint/crypto/keys.proto"; + +// BlockIdFlag indicates which BlockID the signature is for +enum BlockIDFlag { + option (gogoproto.goproto_enum_stringer) = true; + option (gogoproto.goproto_enum_prefix) = false; + + BLOCK_ID_FLAG_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "BlockIDFlagUnknown"]; // indicates an error condition + BLOCK_ID_FLAG_ABSENT = 1 [(gogoproto.enumvalue_customname) = "BlockIDFlagAbsent"]; // the vote was not received + BLOCK_ID_FLAG_COMMIT = 2 [(gogoproto.enumvalue_customname) = "BlockIDFlagCommit"]; // voted for the block that received the majority + BLOCK_ID_FLAG_NIL = 3 [(gogoproto.enumvalue_customname) = "BlockIDFlagNil"]; // voted for nil +} + + +message ValidatorSet { + repeated Validator validators = 1; + Validator proposer = 2; + int64 total_voting_power = 3; +} + +message Validator { + bytes address = 1; + tendermint.crypto.PublicKey pub_key = 2 [(gogoproto.nullable) = false]; + int64 voting_power = 3; + int64 proposer_priority = 4; +} + +message SimpleValidator { + tendermint.crypto.PublicKey pub_key = 1; + int64 voting_power = 2; +} diff --git a/proto/tendermint/version/types.pb.go b/proto/tendermint/version/types.pb.go new file mode 100644 index 0000000..2c04246 --- /dev/null +++ b/proto/tendermint/version/types.pb.go @@ -0,0 +1,576 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/version/types.proto + +package version + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// App includes the protocol and software version for the application. +// This information is included in ResponseInfo. The App.Protocol can be +// updated in ResponseEndBlock. +type App struct { + Protocol uint64 `protobuf:"varint,1,opt,name=protocol,proto3" json:"protocol,omitempty"` + Software string `protobuf:"bytes,2,opt,name=software,proto3" json:"software,omitempty"` +} + +func (m *App) Reset() { *m = App{} } +func (m *App) String() string { return proto.CompactTextString(m) } +func (*App) ProtoMessage() {} +func (*App) Descriptor() ([]byte, []int) { + return fileDescriptor_f9b42966edc5edad, []int{0} +} +func (m *App) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *App) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_App.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *App) XXX_Merge(src proto.Message) { + xxx_messageInfo_App.Merge(m, src) +} +func (m *App) XXX_Size() int { + return m.Size() +} +func (m *App) XXX_DiscardUnknown() { + xxx_messageInfo_App.DiscardUnknown(m) +} + +var xxx_messageInfo_App proto.InternalMessageInfo + +func (m *App) GetProtocol() uint64 { + if m != nil { + return m.Protocol + } + return 0 +} + +func (m *App) GetSoftware() string { + if m != nil { + return m.Software + } + return "" +} + +// Consensus captures the consensus rules for processing a block in the blockchain, +// including all blockchain data structures and the rules of the application's +// state transition machine. +type Consensus struct { + Block uint64 `protobuf:"varint,1,opt,name=block,proto3" json:"block,omitempty"` + App uint64 `protobuf:"varint,2,opt,name=app,proto3" json:"app,omitempty"` +} + +func (m *Consensus) Reset() { *m = Consensus{} } +func (m *Consensus) String() string { return proto.CompactTextString(m) } +func (*Consensus) ProtoMessage() {} +func (*Consensus) Descriptor() ([]byte, []int) { + return fileDescriptor_f9b42966edc5edad, []int{1} +} +func (m *Consensus) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Consensus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Consensus.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Consensus) XXX_Merge(src proto.Message) { + xxx_messageInfo_Consensus.Merge(m, src) +} +func (m *Consensus) XXX_Size() int { + return m.Size() +} +func (m *Consensus) XXX_DiscardUnknown() { + xxx_messageInfo_Consensus.DiscardUnknown(m) +} + +var xxx_messageInfo_Consensus proto.InternalMessageInfo + +func (m *Consensus) GetBlock() uint64 { + if m != nil { + return m.Block + } + return 0 +} + +func (m *Consensus) GetApp() uint64 { + if m != nil { + return m.App + } + return 0 +} + +func init() { + proto.RegisterType((*App)(nil), "tendermint.version.App") + proto.RegisterType((*Consensus)(nil), "tendermint.version.Consensus") +} + +func init() { proto.RegisterFile("tendermint/version/types.proto", fileDescriptor_f9b42966edc5edad) } + +var fileDescriptor_f9b42966edc5edad = []byte{ + // 223 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x49, 0xcd, 0x4b, + 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x4b, 0x2d, 0x2a, 0xce, 0xcc, 0xcf, 0xd3, 0x2f, + 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x42, 0xc8, 0xeb, 0x41, + 0xe5, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0xd2, 0xfa, 0x20, 0x16, 0x44, 0xa5, 0x92, 0x2d, + 0x17, 0xb3, 0x63, 0x41, 0x81, 0x90, 0x14, 0x17, 0x07, 0x98, 0x9f, 0x9c, 0x9f, 0x23, 0xc1, 0xa8, + 0xc0, 0xa8, 0xc1, 0x12, 0x04, 0xe7, 0x83, 0xe4, 0x8a, 0xf3, 0xd3, 0x4a, 0xca, 0x13, 0x8b, 0x52, + 0x25, 0x98, 0x14, 0x18, 0x35, 0x38, 0x83, 0xe0, 0x7c, 0x25, 0x4b, 0x2e, 0x4e, 0xe7, 0xfc, 0xbc, + 0xe2, 0xd4, 0xbc, 0xe2, 0xd2, 0x62, 0x21, 0x11, 0x2e, 0xd6, 0xa4, 0x9c, 0xfc, 0xe4, 0x6c, 0xa8, + 0x09, 0x10, 0x8e, 0x90, 0x00, 0x17, 0x73, 0x62, 0x41, 0x01, 0x58, 0x27, 0x4b, 0x10, 0x88, 0x69, + 0xc5, 0xf2, 0x62, 0x81, 0x3c, 0xa3, 0x93, 0xff, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, + 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, + 0x31, 0x44, 0x99, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x27, 0xe7, + 0xe7, 0xa6, 0x96, 0x24, 0xa5, 0x95, 0x20, 0x18, 0x10, 0x2f, 0x60, 0x06, 0x40, 0x12, 0x1b, 0x58, + 0xc6, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x1a, 0xc7, 0x18, 0x2b, 0x1d, 0x01, 0x00, 0x00, +} + +func (this *Consensus) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Consensus) + if !ok { + that2, ok := that.(Consensus) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Block != that1.Block { + return false + } + if this.App != that1.App { + return false + } + return true +} +func (m *App) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *App) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *App) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Software) > 0 { + i -= len(m.Software) + copy(dAtA[i:], m.Software) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Software))) + i-- + dAtA[i] = 0x12 + } + if m.Protocol != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Protocol)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Consensus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Consensus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Consensus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.App != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.App)) + i-- + dAtA[i] = 0x10 + } + if m.Block != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Block)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *App) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Protocol != 0 { + n += 1 + sovTypes(uint64(m.Protocol)) + } + l = len(m.Software) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Consensus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Block != 0 { + n += 1 + sovTypes(uint64(m.Block)) + } + if m.App != 0 { + n += 1 + sovTypes(uint64(m.App)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *App) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: App: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: App: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType) + } + m.Protocol = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Protocol |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Software", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Software = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Consensus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Consensus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Consensus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType) + } + m.Block = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Block |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field App", wireType) + } + m.App = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.App |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/proto/tendermint/version/types.proto b/proto/tendermint/version/types.proto new file mode 100644 index 0000000..77cdd42 --- /dev/null +++ b/proto/tendermint/version/types.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package tendermint.version; + +option go_package = "github.com/cometbft/cometbft/proto/tendermint/version"; + +import "gogoproto/gogo.proto"; + +// App includes the protocol and software version for the application. +// This information is included in ResponseInfo. The App.Protocol can be +// updated in ResponseEndBlock. +message App { + uint64 protocol = 1; + string software = 2; +} + +// Consensus captures the consensus rules for processing a block in the blockchain, +// including all blockchain data structures and the rules of the application's +// state transition machine. +message Consensus { + option (gogoproto.equal) = true; + + uint64 block = 1; + uint64 app = 2; +} diff --git a/proxy/app_conn.go b/proxy/app_conn.go new file mode 100644 index 0000000..9f6c723 --- /dev/null +++ b/proxy/app_conn.go @@ -0,0 +1,230 @@ +package proxy + +import ( + "context" + "time" + + "github.com/go-kit/kit/metrics" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/types" +) + +//go:generate ../scripts/mockery_generate.sh AppConnConsensus|AppConnMempool|AppConnQuery|AppConnSnapshot + +//---------------------------------------------------------------------------------------- +// Enforce which abci msgs can be sent on a connection at the type level + +type AppConnConsensus interface { + Error() error + InitChain(context.Context, *types.RequestInitChain) (*types.ResponseInitChain, error) + PrepareProposal(context.Context, *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) + ProcessProposal(context.Context, *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) + ExtendVote(context.Context, *types.RequestExtendVote) (*types.ResponseExtendVote, error) + VerifyVoteExtension(context.Context, *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) + FinalizeBlock(context.Context, *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) + Commit(context.Context) (*types.ResponseCommit, error) +} + +type AppConnMempool interface { + SetResponseCallback(abcicli.Callback) + Error() error + + CheckTx(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error) + CheckTxAsync(context.Context, *types.RequestCheckTx) (*abcicli.ReqRes, error) + Flush(context.Context) error +} + +type AppConnQuery interface { + Error() error + + Echo(context.Context, string) (*types.ResponseEcho, error) + Info(context.Context, *types.RequestInfo) (*types.ResponseInfo, error) + Query(context.Context, *types.RequestQuery) (*types.ResponseQuery, error) +} + +type AppConnSnapshot interface { + Error() error + + ListSnapshots(context.Context, *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) + OfferSnapshot(context.Context, *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) + LoadSnapshotChunk(context.Context, *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) + ApplySnapshotChunk(context.Context, *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) +} + +//----------------------------------------------------------------------------------------- +// Implements AppConnConsensus (subset of abcicli.Client) + +type appConnConsensus struct { + metrics *Metrics + appConn abcicli.Client +} + +var _ AppConnConsensus = (*appConnConsensus)(nil) + +func NewAppConnConsensus(appConn abcicli.Client, metrics *Metrics) AppConnConsensus { + return &appConnConsensus{ + metrics: metrics, + appConn: appConn, + } +} + +func (app *appConnConsensus) Error() error { + return app.appConn.Error() +} + +func (app *appConnConsensus) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "init_chain", "type", "sync"))() + return app.appConn.InitChain(ctx, req) +} + +func (app *appConnConsensus) PrepareProposal(ctx context.Context, + req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "prepare_proposal", "type", "sync"))() + return app.appConn.PrepareProposal(ctx, req) +} + +func (app *appConnConsensus) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "process_proposal", "type", "sync"))() + return app.appConn.ProcessProposal(ctx, req) +} + +func (app *appConnConsensus) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "extend_vote", "type", "sync"))() + return app.appConn.ExtendVote(ctx, req) +} + +func (app *appConnConsensus) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "verify_vote_extension", "type", "sync"))() + return app.appConn.VerifyVoteExtension(ctx, req) +} + +func (app *appConnConsensus) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "finalize_block", "type", "sync"))() + return app.appConn.FinalizeBlock(ctx, req) +} + +func (app *appConnConsensus) Commit(ctx context.Context) (*types.ResponseCommit, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "commit", "type", "sync"))() + return app.appConn.Commit(ctx, &types.RequestCommit{}) +} + +//------------------------------------------------ +// Implements AppConnMempool (subset of abcicli.Client) + +type appConnMempool struct { + metrics *Metrics + appConn abcicli.Client +} + +func NewAppConnMempool(appConn abcicli.Client, metrics *Metrics) AppConnMempool { + return &appConnMempool{ + metrics: metrics, + appConn: appConn, + } +} + +func (app *appConnMempool) SetResponseCallback(cb abcicli.Callback) { + app.appConn.SetResponseCallback(cb) +} + +func (app *appConnMempool) Error() error { + return app.appConn.Error() +} + +func (app *appConnMempool) Flush(ctx context.Context) error { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "flush", "type", "sync"))() + return app.appConn.Flush(ctx) +} + +func (app *appConnMempool) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "check_tx", "type", "sync"))() + return app.appConn.CheckTx(ctx, req) +} + +func (app *appConnMempool) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*abcicli.ReqRes, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "check_tx", "type", "async"))() + return app.appConn.CheckTxAsync(ctx, req) +} + +//------------------------------------------------ +// Implements AppConnQuery (subset of abcicli.Client) + +type appConnQuery struct { + metrics *Metrics + appConn abcicli.Client +} + +func NewAppConnQuery(appConn abcicli.Client, metrics *Metrics) AppConnQuery { + return &appConnQuery{ + metrics: metrics, + appConn: appConn, + } +} + +func (app *appConnQuery) Error() error { + return app.appConn.Error() +} + +func (app *appConnQuery) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "echo", "type", "sync"))() + return app.appConn.Echo(ctx, msg) +} + +func (app *appConnQuery) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "info", "type", "sync"))() + return app.appConn.Info(ctx, req) +} + +func (app *appConnQuery) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "query", "type", "sync"))() + return app.appConn.Query(ctx, req) +} + +//------------------------------------------------ +// Implements AppConnSnapshot (subset of abcicli.Client) + +type appConnSnapshot struct { + metrics *Metrics + appConn abcicli.Client +} + +func NewAppConnSnapshot(appConn abcicli.Client, metrics *Metrics) AppConnSnapshot { + return &appConnSnapshot{ + metrics: metrics, + appConn: appConn, + } +} + +func (app *appConnSnapshot) Error() error { + return app.appConn.Error() +} + +func (app *appConnSnapshot) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "list_snapshots", "type", "sync"))() + return app.appConn.ListSnapshots(ctx, req) +} + +func (app *appConnSnapshot) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "offer_snapshot", "type", "sync"))() + return app.appConn.OfferSnapshot(ctx, req) +} + +func (app *appConnSnapshot) LoadSnapshotChunk(ctx context.Context, req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "load_snapshot_chunk", "type", "sync"))() + return app.appConn.LoadSnapshotChunk(ctx, req) +} + +func (app *appConnSnapshot) ApplySnapshotChunk(ctx context.Context, req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "apply_snapshot_chunk", "type", "sync"))() + return app.appConn.ApplySnapshotChunk(ctx, req) +} + +// addTimeSample returns a function that, when called, adds an observation to m. +// The observation added to m is the number of seconds ellapsed since addTimeSample +// was initially called. addTimeSample is meant to be called in a defer to calculate +// the amount of time a function takes to complete. +func addTimeSample(m metrics.Histogram) func() { + start := time.Now() + return func() { m.Observe(time.Since(start).Seconds()) } +} diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go new file mode 100644 index 0000000..aa6dcf3 --- /dev/null +++ b/proxy/app_conn_test.go @@ -0,0 +1,99 @@ +package proxy + +import ( + "context" + "fmt" + "testing" + + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/abci/server" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +var SOCKET = "socket" + +func TestEcho(t *testing.T) { + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmtrand.Str(6)) + clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) + + // Start server + s := server.NewSocketServer(sockPath, kvstore.NewInMemoryApplication()) + s.SetLogger(log.TestingLogger().With("module", "abci-server")) + if err := s.Start(); err != nil { + t.Fatalf("Error starting socket server: %v", err.Error()) + } + t.Cleanup(func() { + if err := s.Stop(); err != nil { + t.Error(err) + } + }) + + // Start client + cli, err := clientCreator.NewABCIClient() + if err != nil { + t.Fatalf("Error creating ABCI client: %v", err.Error()) + } + cli.SetLogger(log.TestingLogger().With("module", "abci-client")) + if err := cli.Start(); err != nil { + t.Fatalf("Error starting ABCI client: %v", err.Error()) + } + + proxy := NewAppConnMempool(cli, NopMetrics()) + t.Log("Connected") + + for i := 0; i < 1000; i++ { + _, err = proxy.CheckTx(context.Background(), &abci.RequestCheckTx{Tx: []byte(fmt.Sprintf("echo-%v", i))}) + if err != nil { + t.Fatal(err) + } + } + if err := proxy.Flush(context.Background()); err != nil { + t.Error(err) + } +} + +func BenchmarkEcho(b *testing.B) { + b.StopTimer() // Initialize + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmtrand.Str(6)) + clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) + + // Start server + s := server.NewSocketServer(sockPath, kvstore.NewInMemoryApplication()) + s.SetLogger(log.TestingLogger().With("module", "abci-server")) + if err := s.Start(); err != nil { + b.Fatalf("Error starting socket server: %v", err.Error()) + } + b.Cleanup(func() { + if err := s.Stop(); err != nil { + b.Error(err) + } + }) + + // Start client + cli, err := clientCreator.NewABCIClient() + if err != nil { + b.Fatalf("Error creating ABCI client: %v", err.Error()) + } + cli.SetLogger(log.TestingLogger().With("module", "abci-client")) + if err := cli.Start(); err != nil { + b.Fatalf("Error starting ABCI client: %v", err.Error()) + } + + proxy := NewAppConnMempool(cli, NopMetrics()) + b.Log("Connected") + b.StartTimer() // Start benchmarking tests + + for i := 0; i < b.N; i++ { + _, err = proxy.CheckTx(context.Background(), &abci.RequestCheckTx{Tx: []byte("hello")}) + if err != nil { + b.Error(err) + } + } + if err := proxy.Flush(context.Background()); err != nil { + b.Error(err) + } + + b.StopTimer() +} diff --git a/proxy/client.go b/proxy/client.go new file mode 100644 index 0000000..f461a1d --- /dev/null +++ b/proxy/client.go @@ -0,0 +1,138 @@ +package proxy + +import ( + "fmt" + + abcicli "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/abci/types" + cmtsync "github.com/cometbft/cometbft/libs/sync" + e2e "github.com/cometbft/cometbft/test/e2e/app" +) + +//go:generate ../scripts/mockery_generate.sh ClientCreator + +// ClientCreator creates new ABCI clients. +type ClientCreator interface { + // NewABCIClient returns a new ABCI client. + NewABCIClient() (abcicli.Client, error) +} + +//---------------------------------------------------- +// local proxy uses a mutex on an in-proc app + +type localClientCreator struct { + mtx *cmtsync.Mutex + app types.Application +} + +// NewLocalClientCreator returns a [ClientCreator] for the given app, which +// will be running locally. +// +// Maintains a single mutex over all new clients created with NewABCIClient. For +// a local client creator that uses a single mutex per new client, rather use +// [NewConnSyncLocalClientCreator]. +func NewLocalClientCreator(app types.Application) ClientCreator { + return &localClientCreator{ + mtx: new(cmtsync.Mutex), + app: app, + } +} + +func (l *localClientCreator) NewABCIClient() (abcicli.Client, error) { + return abcicli.NewLocalClient(l.mtx, l.app), nil +} + +//---------------------------------------------------- +// local proxy creates a new mutex for each client + +type connSyncLocalClientCreator struct { + app types.Application +} + +// NewConnSyncLocalClientCreator returns a local [ClientCreator] for the given +// app. +// +// Unlike [NewLocalClientCreator], this is a "connection-synchronized" local +// client creator, meaning each call to NewABCIClient returns an ABCI client +// that maintains its own mutex over the application (i.e. it is +// per-"connection" synchronized). +func NewConnSyncLocalClientCreator(app types.Application) ClientCreator { + return &connSyncLocalClientCreator{ + app: app, + } +} + +func (c *connSyncLocalClientCreator) NewABCIClient() (abcicli.Client, error) { + // Specifying nil for the mutex causes each instance to create its own + // mutex. + return abcicli.NewLocalClient(nil, c.app), nil +} + +//--------------------------------------------------------------- +// remote proxy opens new connections to an external app process + +type remoteClientCreator struct { + addr string + transport string + mustConnect bool +} + +// NewRemoteClientCreator returns a ClientCreator for the given address (e.g. +// "192.168.0.1") and transport (e.g. "tcp"). Set mustConnect to true if you +// want the client to connect before reporting success. +func NewRemoteClientCreator(addr, transport string, mustConnect bool) ClientCreator { + return &remoteClientCreator{ + addr: addr, + transport: transport, + mustConnect: mustConnect, + } +} + +func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) { + remoteApp, err := abcicli.NewClient(r.addr, r.transport, r.mustConnect) + if err != nil { + return nil, fmt.Errorf("failed to connect to proxy: %w", err) + } + + return remoteApp, nil +} + +// DefaultClientCreator returns a default [ClientCreator], which will create a +// local client if addr is one of "kvstore", "persistent_kvstore", "e2e", +// "noop". +// +// Otherwise a remote client will be created. +// +// Each of "kvstore", "persistent_kvstore" and "e2e" also currently have an +// "_connsync" variant (i.e. "kvstore_connsync", etc.), which attempts to +// replicate the same concurrency model as the remote client. +func DefaultClientCreator(addr, transport, dbDir string) ClientCreator { + switch addr { + case "kvstore": + return NewLocalClientCreator(kvstore.NewInMemoryApplication()) + case "kvstore_connsync": + return NewConnSyncLocalClientCreator(kvstore.NewInMemoryApplication()) + case "persistent_kvstore": + return NewLocalClientCreator(kvstore.NewPersistentApplication(dbDir)) + case "persistent_kvstore_connsync": + return NewConnSyncLocalClientCreator(kvstore.NewPersistentApplication(dbDir)) + case "e2e": + app, err := e2e.NewApplication(e2e.DefaultConfig(dbDir)) + if err != nil { + panic(err) + } + return NewLocalClientCreator(app) + case "e2e_connsync": + app, err := e2e.NewApplication(e2e.DefaultConfig(dbDir)) + if err != nil { + panic(err) + } + return NewConnSyncLocalClientCreator(app) + case "noop": + return NewLocalClientCreator(types.NewBaseApplication()) + default: + mustConnect := false // loop retrying + return NewRemoteClientCreator(addr, transport, mustConnect) + } +} diff --git a/proxy/metrics.gen.go b/proxy/metrics.gen.go new file mode 100644 index 0000000..47113a3 --- /dev/null +++ b/proxy/metrics.gen.go @@ -0,0 +1,32 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package proxy + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + MethodTimingSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "method_timing_seconds", + Help: "Timing for each ABCI method.", + + Buckets: []float64{.0001, .0004, .002, .009, .02, .1, .65, 2, 6, 25}, + }, append(labels, "method", "type")).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + MethodTimingSeconds: discard.NewHistogram(), + } +} diff --git a/proxy/metrics.go b/proxy/metrics.go new file mode 100644 index 0000000..68b8e9b --- /dev/null +++ b/proxy/metrics.go @@ -0,0 +1,19 @@ +package proxy + +import ( + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "abci_connection" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains the prometheus metrics exposed by the proxy package. +type Metrics struct { + // Timing for each ABCI method. + MethodTimingSeconds metrics.Histogram `metrics_bucketsizes:".0001,.0004,.002,.009,.02,.1,.65,2,6,25" metrics_labels:"method, type"` +} diff --git a/proxy/mocks/app_conn_consensus.go b/proxy/mocks/app_conn_consensus.go new file mode 100644 index 0000000..d69e1a2 --- /dev/null +++ b/proxy/mocks/app_conn_consensus.go @@ -0,0 +1,258 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/abci/types" +) + +// AppConnConsensus is an autogenerated mock type for the AppConnConsensus type +type AppConnConsensus struct { + mock.Mock +} + +// Commit provides a mock function with given fields: _a0 +func (_m *AppConnConsensus) Commit(_a0 context.Context) (*types.ResponseCommit, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Commit") + } + + var r0 *types.ResponseCommit + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*types.ResponseCommit, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(context.Context) *types.ResponseCommit); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCommit) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Error provides a mock function with no fields +func (_m *AppConnConsensus) Error() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Error") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ExtendVote provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) ExtendVote(_a0 context.Context, _a1 *types.RequestExtendVote) (*types.ResponseExtendVote, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ExtendVote") + } + + var r0 *types.ResponseExtendVote + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) (*types.ResponseExtendVote, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestExtendVote) *types.ResponseExtendVote); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseExtendVote) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestExtendVote) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FinalizeBlock provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) FinalizeBlock(_a0 context.Context, _a1 *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for FinalizeBlock") + } + + var r0 *types.ResponseFinalizeBlock + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestFinalizeBlock) *types.ResponseFinalizeBlock); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseFinalizeBlock) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestFinalizeBlock) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// InitChain provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) InitChain(_a0 context.Context, _a1 *types.RequestInitChain) (*types.ResponseInitChain, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for InitChain") + } + + var r0 *types.ResponseInitChain + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) (*types.ResponseInitChain, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInitChain) *types.ResponseInitChain); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInitChain) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInitChain) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PrepareProposal provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) PrepareProposal(_a0 context.Context, _a1 *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for PrepareProposal") + } + + var r0 *types.ResponsePrepareProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestPrepareProposal) *types.ResponsePrepareProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponsePrepareProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestPrepareProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ProcessProposal provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) ProcessProposal(_a0 context.Context, _a1 *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ProcessProposal") + } + + var r0 *types.ResponseProcessProposal + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) (*types.ResponseProcessProposal, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestProcessProposal) *types.ResponseProcessProposal); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseProcessProposal) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestProcessProposal) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 +func (_m *AppConnConsensus) VerifyVoteExtension(_a0 context.Context, _a1 *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for VerifyVoteExtension") + } + + var r0 *types.ResponseVerifyVoteExtension + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestVerifyVoteExtension) *types.ResponseVerifyVoteExtension); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseVerifyVoteExtension) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestVerifyVoteExtension) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewAppConnConsensus creates a new instance of AppConnConsensus. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAppConnConsensus(t interface { + mock.TestingT + Cleanup(func()) +}) *AppConnConsensus { + mock := &AppConnConsensus{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/proxy/mocks/app_conn_mempool.go b/proxy/mocks/app_conn_mempool.go new file mode 100644 index 0000000..922bb19 --- /dev/null +++ b/proxy/mocks/app_conn_mempool.go @@ -0,0 +1,133 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + abcicli "github.com/cometbft/cometbft/abci/client" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/abci/types" +) + +// AppConnMempool is an autogenerated mock type for the AppConnMempool type +type AppConnMempool struct { + mock.Mock +} + +// CheckTx provides a mock function with given fields: _a0, _a1 +func (_m *AppConnMempool) CheckTx(_a0 context.Context, _a1 *types.RequestCheckTx) (*types.ResponseCheckTx, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for CheckTx") + } + + var r0 *types.ResponseCheckTx + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) *types.ResponseCheckTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseCheckTx) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCheckTx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckTxAsync provides a mock function with given fields: _a0, _a1 +func (_m *AppConnMempool) CheckTxAsync(_a0 context.Context, _a1 *types.RequestCheckTx) (*abcicli.ReqRes, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for CheckTxAsync") + } + + var r0 *abcicli.ReqRes + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) (*abcicli.ReqRes, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestCheckTx) *abcicli.ReqRes); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*abcicli.ReqRes) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestCheckTx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Error provides a mock function with no fields +func (_m *AppConnMempool) Error() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Error") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Flush provides a mock function with given fields: _a0 +func (_m *AppConnMempool) Flush(_a0 context.Context) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Flush") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SetResponseCallback provides a mock function with given fields: _a0 +func (_m *AppConnMempool) SetResponseCallback(_a0 abcicli.Callback) { + _m.Called(_a0) +} + +// NewAppConnMempool creates a new instance of AppConnMempool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAppConnMempool(t interface { + mock.TestingT + Cleanup(func()) +}) *AppConnMempool { + mock := &AppConnMempool{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/proxy/mocks/app_conn_query.go b/proxy/mocks/app_conn_query.go new file mode 100644 index 0000000..bd71e52 --- /dev/null +++ b/proxy/mocks/app_conn_query.go @@ -0,0 +1,138 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/abci/types" +) + +// AppConnQuery is an autogenerated mock type for the AppConnQuery type +type AppConnQuery struct { + mock.Mock +} + +// Echo provides a mock function with given fields: _a0, _a1 +func (_m *AppConnQuery) Echo(_a0 context.Context, _a1 string) (*types.ResponseEcho, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Echo") + } + + var r0 *types.ResponseEcho + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string) (*types.ResponseEcho, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, string) *types.ResponseEcho); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseEcho) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Error provides a mock function with no fields +func (_m *AppConnQuery) Error() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Error") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Info provides a mock function with given fields: _a0, _a1 +func (_m *AppConnQuery) Info(_a0 context.Context, _a1 *types.RequestInfo) (*types.ResponseInfo, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Info") + } + + var r0 *types.ResponseInfo + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) (*types.ResponseInfo, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestInfo) *types.ResponseInfo); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseInfo) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestInfo) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Query provides a mock function with given fields: _a0, _a1 +func (_m *AppConnQuery) Query(_a0 context.Context, _a1 *types.RequestQuery) (*types.ResponseQuery, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for Query") + } + + var r0 *types.ResponseQuery + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) (*types.ResponseQuery, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestQuery) *types.ResponseQuery); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseQuery) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestQuery) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewAppConnQuery creates a new instance of AppConnQuery. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAppConnQuery(t interface { + mock.TestingT + Cleanup(func()) +}) *AppConnQuery { + mock := &AppConnQuery{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/proxy/mocks/app_conn_snapshot.go b/proxy/mocks/app_conn_snapshot.go new file mode 100644 index 0000000..8b667b5 --- /dev/null +++ b/proxy/mocks/app_conn_snapshot.go @@ -0,0 +1,168 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/abci/types" +) + +// AppConnSnapshot is an autogenerated mock type for the AppConnSnapshot type +type AppConnSnapshot struct { + mock.Mock +} + +// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *AppConnSnapshot) ApplySnapshotChunk(_a0 context.Context, _a1 *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ApplySnapshotChunk") + } + + var r0 *types.ResponseApplySnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestApplySnapshotChunk) *types.ResponseApplySnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseApplySnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestApplySnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Error provides a mock function with no fields +func (_m *AppConnSnapshot) Error() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Error") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ListSnapshots provides a mock function with given fields: _a0, _a1 +func (_m *AppConnSnapshot) ListSnapshots(_a0 context.Context, _a1 *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for ListSnapshots") + } + + var r0 *types.ResponseListSnapshots + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) (*types.ResponseListSnapshots, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestListSnapshots) *types.ResponseListSnapshots); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseListSnapshots) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestListSnapshots) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 +func (_m *AppConnSnapshot) LoadSnapshotChunk(_a0 context.Context, _a1 *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for LoadSnapshotChunk") + } + + var r0 *types.ResponseLoadSnapshotChunk + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestLoadSnapshotChunk) *types.ResponseLoadSnapshotChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseLoadSnapshotChunk) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestLoadSnapshotChunk) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OfferSnapshot provides a mock function with given fields: _a0, _a1 +func (_m *AppConnSnapshot) OfferSnapshot(_a0 context.Context, _a1 *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for OfferSnapshot") + } + + var r0 *types.ResponseOfferSnapshot + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(context.Context, *types.RequestOfferSnapshot) *types.ResponseOfferSnapshot); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ResponseOfferSnapshot) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *types.RequestOfferSnapshot) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewAppConnSnapshot creates a new instance of AppConnSnapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAppConnSnapshot(t interface { + mock.TestingT + Cleanup(func()) +}) *AppConnSnapshot { + mock := &AppConnSnapshot{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/proxy/mocks/client_creator.go b/proxy/mocks/client_creator.go new file mode 100644 index 0000000..a9ee49c --- /dev/null +++ b/proxy/mocks/client_creator.go @@ -0,0 +1,57 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + abcicli "github.com/cometbft/cometbft/abci/client" + mock "github.com/stretchr/testify/mock" +) + +// ClientCreator is an autogenerated mock type for the ClientCreator type +type ClientCreator struct { + mock.Mock +} + +// NewABCIClient provides a mock function with no fields +func (_m *ClientCreator) NewABCIClient() (abcicli.Client, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for NewABCIClient") + } + + var r0 abcicli.Client + var r1 error + if rf, ok := ret.Get(0).(func() (abcicli.Client, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() abcicli.Client); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(abcicli.Client) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewClientCreator creates a new instance of ClientCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClientCreator(t interface { + mock.TestingT + Cleanup(func()) +}) *ClientCreator { + mock := &ClientCreator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go new file mode 100644 index 0000000..b241c53 --- /dev/null +++ b/proxy/multi_app_conn.go @@ -0,0 +1,193 @@ +package proxy + +import ( + "fmt" + + abcicli "github.com/cometbft/cometbft/abci/client" + cmtlog "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + "github.com/cometbft/cometbft/libs/service" +) + +const ( + connConsensus = "consensus" + connMempool = "mempool" + connQuery = "query" + connSnapshot = "snapshot" +) + +// AppConns is the CometBFT's interface to the application that consists of +// multiple connections. +type AppConns interface { + service.Service + + // Mempool connection + Mempool() AppConnMempool + // Consensus connection + Consensus() AppConnConsensus + // Query connection + Query() AppConnQuery + // Snapshot connection + Snapshot() AppConnSnapshot +} + +// NewAppConns calls NewMultiAppConn. +func NewAppConns(clientCreator ClientCreator, metrics *Metrics) AppConns { + return NewMultiAppConn(clientCreator, metrics) +} + +// multiAppConn implements AppConns. +// +// A multiAppConn is made of a few appConns and manages their underlying abci +// clients. +// TODO: on app restart, clients must reboot together +type multiAppConn struct { + service.BaseService + + metrics *Metrics + consensusConn AppConnConsensus + mempoolConn AppConnMempool + queryConn AppConnQuery + snapshotConn AppConnSnapshot + + consensusConnClient abcicli.Client + mempoolConnClient abcicli.Client + queryConnClient abcicli.Client + snapshotConnClient abcicli.Client + + clientCreator ClientCreator +} + +// NewMultiAppConn makes all necessary abci connections to the application. +func NewMultiAppConn(clientCreator ClientCreator, metrics *Metrics) AppConns { + multiAppConn := &multiAppConn{ + metrics: metrics, + clientCreator: clientCreator, + } + multiAppConn.BaseService = *service.NewBaseService(nil, "multiAppConn", multiAppConn) + return multiAppConn +} + +func (app *multiAppConn) Mempool() AppConnMempool { + return app.mempoolConn +} + +func (app *multiAppConn) Consensus() AppConnConsensus { + return app.consensusConn +} + +func (app *multiAppConn) Query() AppConnQuery { + return app.queryConn +} + +func (app *multiAppConn) Snapshot() AppConnSnapshot { + return app.snapshotConn +} + +func (app *multiAppConn) OnStart() error { + c, err := app.abciClientFor(connQuery) + if err != nil { + return err + } + app.queryConnClient = c + app.queryConn = NewAppConnQuery(c, app.metrics) + + c, err = app.abciClientFor(connSnapshot) + if err != nil { + app.stopAllClients() + return err + } + app.snapshotConnClient = c + app.snapshotConn = NewAppConnSnapshot(c, app.metrics) + + c, err = app.abciClientFor(connMempool) + if err != nil { + app.stopAllClients() + return err + } + app.mempoolConnClient = c + app.mempoolConn = NewAppConnMempool(c, app.metrics) + + c, err = app.abciClientFor(connConsensus) + if err != nil { + app.stopAllClients() + return err + } + app.consensusConnClient = c + app.consensusConn = NewAppConnConsensus(c, app.metrics) + + // Kill CometBFT if the ABCI application crashes. + go app.killTMOnClientError() + + return nil +} + +func (app *multiAppConn) OnStop() { + app.stopAllClients() +} + +func (app *multiAppConn) killTMOnClientError() { + killFn := func(conn string, err error, logger cmtlog.Logger) { + logger.Error( + fmt.Sprintf("%s connection terminated. Did the application crash? Please restart CometBFT", conn), + "err", err) + killErr := cmtos.Kill() + if killErr != nil { + logger.Error("Failed to kill this process - please do so manually", "err", killErr) + } + } + + select { + case <-app.consensusConnClient.Quit(): + if err := app.consensusConnClient.Error(); err != nil { + killFn(connConsensus, err, app.Logger) + } + case <-app.mempoolConnClient.Quit(): + if err := app.mempoolConnClient.Error(); err != nil { + killFn(connMempool, err, app.Logger) + } + case <-app.queryConnClient.Quit(): + if err := app.queryConnClient.Error(); err != nil { + killFn(connQuery, err, app.Logger) + } + case <-app.snapshotConnClient.Quit(): + if err := app.snapshotConnClient.Error(); err != nil { + killFn(connSnapshot, err, app.Logger) + } + } +} + +func (app *multiAppConn) stopAllClients() { + if app.consensusConnClient != nil { + if err := app.consensusConnClient.Stop(); err != nil { + app.Logger.Error("error while stopping consensus client", "error", err) + } + } + if app.mempoolConnClient != nil { + if err := app.mempoolConnClient.Stop(); err != nil { + app.Logger.Error("error while stopping mempool client", "error", err) + } + } + if app.queryConnClient != nil { + if err := app.queryConnClient.Stop(); err != nil { + app.Logger.Error("error while stopping query client", "error", err) + } + } + if app.snapshotConnClient != nil { + if err := app.snapshotConnClient.Stop(); err != nil { + app.Logger.Error("error while stopping snapshot client", "error", err) + } + } +} + +func (app *multiAppConn) abciClientFor(conn string) (abcicli.Client, error) { + c, err := app.clientCreator.NewABCIClient() + if err != nil { + return nil, fmt.Errorf("error creating ABCI client (%s connection): %w", conn, err) + } + c.SetLogger(app.Logger.With("module", "abci-client", "connection", conn)) + if err := c.Start(); err != nil { + return nil, fmt.Errorf("error starting ABCI client (%s connection): %w", conn, err) + } + return c, nil +} diff --git a/proxy/multi_app_conn_test.go b/proxy/multi_app_conn_test.go new file mode 100644 index 0000000..bf99557 --- /dev/null +++ b/proxy/multi_app_conn_test.go @@ -0,0 +1,89 @@ +package proxy + +import ( + "errors" + "os" + "os/signal" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + abcimocks "github.com/cometbft/cometbft/abci/client/mocks" + "github.com/cometbft/cometbft/proxy/mocks" +) + +func TestAppConns_Start_Stop(t *testing.T) { + quitCh := make(<-chan struct{}) + + clientCreatorMock := &mocks.ClientCreator{} + + clientMock := &abcimocks.Client{} + clientMock.On("SetLogger", mock.Anything).Return().Times(4) + clientMock.On("Start").Return(nil).Times(4) + clientMock.On("Stop").Return(nil).Times(4) + clientMock.On("Quit").Return(quitCh).Times(4) + + clientCreatorMock.On("NewABCIClient").Return(clientMock, nil).Times(4) + + appConns := NewAppConns(clientCreatorMock, NopMetrics()) + + err := appConns.Start() + require.NoError(t, err) + + time.Sleep(100 * time.Millisecond) + + err = appConns.Stop() + require.NoError(t, err) + + clientMock.AssertExpectations(t) +} + +// Upon failure, we call cmtos.Kill +func TestAppConns_Failure(t *testing.T) { + ok := make(chan struct{}) + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGTERM) + go func() { + for range c { + close(ok) + } + }() + + quitCh := make(chan struct{}) + var recvQuitCh <-chan struct{} = quitCh + + clientCreatorMock := &mocks.ClientCreator{} + + clientMock := &abcimocks.Client{} + clientMock.On("SetLogger", mock.Anything).Return() + clientMock.On("Start").Return(nil) + clientMock.On("Stop").Return(nil) + + clientMock.On("Quit").Return(recvQuitCh) + clientMock.On("Error").Return(errors.New("EOF")).Once() + + clientCreatorMock.On("NewABCIClient").Return(clientMock, nil) + + appConns := NewAppConns(clientCreatorMock, NopMetrics()) + + err := appConns.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := appConns.Stop(); err != nil { + t.Error(err) + } + }) + + // simulate failure + close(quitCh) + + select { + case <-ok: + t.Log("SIGTERM successfully received") + case <-time.After(5 * time.Second): + t.Fatal("expected process to receive SIGTERM signal") + } +} diff --git a/proxy/version.go b/proxy/version.go new file mode 100644 index 0000000..1dd0fdb --- /dev/null +++ b/proxy/version.go @@ -0,0 +1,16 @@ +package proxy + +import ( + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/version" +) + +// RequestInfo contains all the information for sending +// the abci.RequestInfo message during handshake with the app. +// It contains only compile-time version information. +var RequestInfo = &abci.RequestInfo{ + Version: version.TMCoreSemVer, + BlockVersion: version.BlockProtocol, + P2PVersion: version.P2PProtocol, + AbciVersion: version.ABCIVersion, +} diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go new file mode 100644 index 0000000..8f32242 --- /dev/null +++ b/rpc/client/event_test.go @@ -0,0 +1,175 @@ +package client_test + +import ( + "context" + "fmt" + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/rpc/client" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/types" +) + +var waitForEventTimeout = 8 * time.Second + +// MakeTxKV returns a text transaction, allong with expected key, value pair +func MakeTxKV() ([]byte, []byte, []byte) { + k := []byte(cmtrand.Str(8)) + v := []byte(cmtrand.Str(8)) + return k, v, append(k, append([]byte("="), v...)...) +} + +func TestHeaderEvents(t *testing.T) { + for i, c := range GetClients() { + i, c := i, c + t.Run(reflect.TypeOf(c).String(), func(t *testing.T) { + // start for this test it if it wasn't already running + if !c.IsRunning() { + // if so, then we start it, listen, and stop it. + err := c.Start() + require.Nil(t, err, "%d: %+v", i, err) + t.Cleanup(func() { + if err := c.Stop(); err != nil { + t.Error(err) + } + }) + } + + evtTyp := types.EventNewBlockHeader + evt, err := client.WaitForOneEvent(c, evtTyp, waitForEventTimeout) + require.Nil(t, err, "%d: %+v", i, err) + _, ok := evt.(types.EventDataNewBlockHeader) + require.True(t, ok, "%d: %#v", i, evt) + // TODO: more checks... + }) + } +} + +// subscribe to new blocks and make sure height increments by 1 +func TestBlockEvents(t *testing.T) { + for _, c := range GetClients() { + c := c + t.Run(reflect.TypeOf(c).String(), func(t *testing.T) { + + // start for this test it if it wasn't already running + if !c.IsRunning() { + // if so, then we start it, listen, and stop it. + err := c.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := c.Stop(); err != nil { + t.Error(err) + } + }) + } + + const subscriber = "TestBlockEvents" + + eventCh, err := c.Subscribe(context.Background(), subscriber, types.QueryForEvent(types.EventNewBlock).String()) + require.NoError(t, err) + t.Cleanup(func() { + if err := c.UnsubscribeAll(context.Background(), subscriber); err != nil { + t.Error(err) + } + }) + + var firstBlockHeight int64 + for i := int64(0); i < 3; i++ { + event := <-eventCh + blockEvent, ok := event.Data.(types.EventDataNewBlock) + require.True(t, ok) + + block := blockEvent.Block + + if firstBlockHeight == 0 { + firstBlockHeight = block.Height + } + + require.Equal(t, firstBlockHeight+i, block.Height) + } + }) + } +} + +func TestTxEventsSentWithBroadcastTxAsync(t *testing.T) { testTxEventsSent(t, "async") } +func TestTxEventsSentWithBroadcastTxSync(t *testing.T) { testTxEventsSent(t, "sync") } + +func testTxEventsSent(t *testing.T, broadcastMethod string) { + for _, c := range GetClients() { + c := c + t.Run(reflect.TypeOf(c).String(), func(t *testing.T) { + + // start for this test it if it wasn't already running + if !c.IsRunning() { + // if so, then we start it, listen, and stop it. + err := c.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := c.Stop(); err != nil { + t.Error(err) + } + }) + } + + // make the tx + _, _, tx := MakeTxKV() + + // send + go func() { + var ( + txres *ctypes.ResultBroadcastTx + err error + ctx = context.Background() + ) + switch broadcastMethod { + case "async": + txres, err = c.BroadcastTxAsync(ctx, tx) + case "sync": + txres, err = c.BroadcastTxSync(ctx, tx) + default: + panic(fmt.Sprintf("Unknown broadcastMethod %s", broadcastMethod)) + } + if assert.NoError(t, err) { + assert.Equal(t, txres.Code, abci.CodeTypeOK) + } + }() + + // and wait for confirmation + evt, err := client.WaitForOneEvent(c, types.EventTx, waitForEventTimeout) + require.Nil(t, err) + + // and make sure it has the proper info + txe, ok := evt.(types.EventDataTx) + require.True(t, ok) + + // make sure this is the proper tx + require.EqualValues(t, tx, txe.Tx) + require.True(t, txe.Result.IsOK()) + }) + } +} + +func TestHTTPReturnsErrorIfClientIsNotRunning(t *testing.T) { + c := getHTTPClient() + + // on Subscribe + _, err := c.Subscribe(context.Background(), "TestHeaderEvents", + types.QueryForEvent(types.EventNewBlockHeader).String()) + assert.Error(t, err) + + // on Unsubscribe + err = c.Unsubscribe(context.Background(), "TestHeaderEvents", + types.QueryForEvent(types.EventNewBlockHeader).String()) + assert.Error(t, err) + + // on UnsubscribeAll + err = c.UnsubscribeAll(context.Background(), "TestHeaderEvents") + assert.Error(t, err) +} diff --git a/rpc/client/evidence_test.go b/rpc/client/evidence_test.go new file mode 100644 index 0000000..0a99b04 --- /dev/null +++ b/rpc/client/evidence_test.go @@ -0,0 +1,167 @@ +package client_test + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/rpc/client" + rpctest "github.com/cometbft/cometbft/rpc/test" + "github.com/cometbft/cometbft/types" +) + +// For some reason the empty node used in tests has a time of +// 2018-10-10 08:20:13.695936996 +0000 UTC +// this is because the test genesis time is set here +// so in order to validate evidence we need evidence to be the same time +var defaultTestTime = time.Date(2018, 10, 10, 8, 20, 13, 695936996, time.UTC) + +func newEvidence(t *testing.T, val *privval.FilePV, + vote *types.Vote, vote2 *types.Vote, + chainID string) *types.DuplicateVoteEvidence { + + var err error + + v := vote.ToProto() + v2 := vote2.ToProto() + + vote.Signature, err = val.Key.PrivKey.Sign(types.VoteSignBytes(chainID, v)) + require.NoError(t, err) + + vote2.Signature, err = val.Key.PrivKey.Sign(types.VoteSignBytes(chainID, v2)) + require.NoError(t, err) + + validator := types.NewValidator(val.Key.PubKey, 10) + valSet := types.NewValidatorSet([]*types.Validator{validator}) + + ev, err := types.NewDuplicateVoteEvidence(vote, vote2, defaultTestTime, valSet) + require.NoError(t, err) + return ev +} + +func makeEvidences( + t *testing.T, + val *privval.FilePV, + chainID string, +) (correct *types.DuplicateVoteEvidence, fakes []*types.DuplicateVoteEvidence) { + vote := types.Vote{ + ValidatorAddress: val.Key.Address, + ValidatorIndex: 0, + Height: 1, + Round: 0, + Type: cmtproto.PrevoteType, + Timestamp: defaultTestTime, + BlockID: types.BlockID{ + Hash: tmhash.Sum(cmtrand.Bytes(tmhash.Size)), + PartSetHeader: types.PartSetHeader{ + Total: 1000, + Hash: tmhash.Sum([]byte("partset")), + }, + }, + } + + vote2 := vote + vote2.BlockID.Hash = tmhash.Sum([]byte("blockhash2")) + correct = newEvidence(t, val, &vote, &vote2, chainID) + + fakes = make([]*types.DuplicateVoteEvidence, 0) + + // different address + { + v := vote2 + v.ValidatorAddress = []byte("some_address") + fakes = append(fakes, newEvidence(t, val, &vote, &v, chainID)) + } + + // different height + { + v := vote2 + v.Height = vote.Height + 1 + fakes = append(fakes, newEvidence(t, val, &vote, &v, chainID)) + } + + // different round + { + v := vote2 + v.Round = vote.Round + 1 + fakes = append(fakes, newEvidence(t, val, &vote, &v, chainID)) + } + + // different type + { + v := vote2 + v.Type = cmtproto.PrecommitType + fakes = append(fakes, newEvidence(t, val, &vote, &v, chainID)) + } + + // exactly same vote + { + v := vote + fakes = append(fakes, newEvidence(t, val, &vote, &v, chainID)) + } + + return correct, fakes +} + +func TestBroadcastEvidence_DuplicateVoteEvidence(t *testing.T) { + var ( + config = rpctest.GetConfig() + chainID = test.DefaultTestChainID + pv = privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + ) + + for i, c := range GetClients() { + correct, fakes := makeEvidences(t, pv, chainID) + t.Logf("client %d", i) + + result, err := c.BroadcastEvidence(context.Background(), correct) + require.NoError(t, err, "BroadcastEvidence(%s) failed", correct) + assert.Equal(t, correct.Hash(), result.Hash, "expected result hash to match evidence hash") + + status, err := c.Status(context.Background()) + require.NoError(t, err) + err = client.WaitForHeight(c, status.SyncInfo.LatestBlockHeight+2, nil) + require.NoError(t, err) + + ed25519pub := pv.Key.PubKey.(ed25519.PubKey) + rawpub := ed25519pub.Bytes() + result2, err := c.ABCIQuery(context.Background(), "/val", rawpub) + require.NoError(t, err) + qres := result2.Response + require.True(t, qres.IsOK()) + + var v abci.ValidatorUpdate + err = abci.ReadMessage(bytes.NewReader(qres.Value), &v) + require.NoError(t, err, "Error reading query result, value %v", qres.Value) + + pk, err := cryptoenc.PubKeyFromProto(v.PubKey) + require.NoError(t, err) + + require.EqualValues(t, rawpub, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value)) + require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value)) + + for _, fake := range fakes { + _, err := c.BroadcastEvidence(context.Background(), fake) + require.Error(t, err, "BroadcastEvidence(%s) succeeded, but the evidence was fake", fake) + } + } +} + +func TestBroadcastEmptyEvidence(t *testing.T) { + for _, c := range GetClients() { + _, err := c.BroadcastEvidence(context.Background(), nil) + assert.Error(t, err) + } +} diff --git a/rpc/client/examples_test.go b/rpc/client/examples_test.go new file mode 100644 index 0000000..2cf7de2 --- /dev/null +++ b/rpc/client/examples_test.go @@ -0,0 +1,191 @@ +package client_test + +import ( + "bytes" + "context" + "fmt" + "log" + "strings" + + "github.com/cometbft/cometbft/abci/example/kvstore" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/rpc/jsonrpc/types" + rpctest "github.com/cometbft/cometbft/rpc/test" +) + +func ExampleHTTP_simple() { + // Start a CometBFT node (and kvstore) in the background to test against + app := kvstore.NewInMemoryApplication() + node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig) + defer rpctest.StopTendermint(node) + + // Create our RPC client + rpcAddr := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.New(rpcAddr, "/websocket") + if err != nil { + log.Fatal(err) //nolint:gocritic + } + + // Create a transaction + k := []byte("name") + v := []byte("satoshi") + tx := append(k, append([]byte("="), v...)...) + + // Broadcast the transaction and wait for it to commit (rather use + // c.BroadcastTxSync though in production). + bres, err := c.BroadcastTxCommit(context.Background(), tx) + if err != nil { + log.Fatal(err) + } + if bres.CheckTx.IsErr() || bres.TxResult.IsErr() { + log.Fatal("BroadcastTxCommit transaction failed") + } + + // Now try to fetch the value for the key + qres, err := c.ABCIQuery(context.Background(), "/key", k) + if err != nil { + log.Fatal(err) + } + if qres.Response.IsErr() { + log.Fatal("ABCIQuery failed") + } + if !bytes.Equal(qres.Response.Key, k) { + log.Fatal("returned key does not match queried key") + } + if !bytes.Equal(qres.Response.Value, v) { + log.Fatal("returned value does not match sent value") + } + + fmt.Println("Sent tx :", string(tx)) + fmt.Println("Queried for :", string(qres.Response.Key)) + fmt.Println("Got value :", string(qres.Response.Value)) + + // Output: + // Sent tx : name=satoshi + // Queried for : name + // Got value : satoshi +} + +func ExampleHTTP_batching() { + // Start a CometBFT node (and kvstore) in the background to test against + app := kvstore.NewInMemoryApplication() + node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig) + + // Create our RPC client + rpcAddr := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.New(rpcAddr, "/websocket") + if err != nil { + log.Fatal(err) + } + + defer rpctest.StopTendermint(node) + + // Create our two transactions + k1 := []byte("firstName") + v1 := []byte("satoshi") + tx1 := append(k1, append([]byte("="), v1...)...) + + k2 := []byte("lastName") + v2 := []byte("nakamoto") + tx2 := append(k2, append([]byte("="), v2...)...) + + txs := [][]byte{tx1, tx2} + + // Create a new batch + batch := c.NewBatch() + + // Queue up our transactions + for _, tx := range txs { + // Broadcast the transaction and wait for it to commit (rather use + // c.BroadcastTxSync though in production). + if _, err := batch.BroadcastTxCommit(context.Background(), tx); err != nil { + log.Fatal(err) //nolint:gocritic + } + } + + // Send the batch of 2 transactions + if _, err := batch.Send(context.Background()); err != nil { + log.Fatal(err) + } + + // Now let's query for the original results as a batch + keys := [][]byte{k1, k2} + for _, key := range keys { + if _, err := batch.ABCIQuery(context.Background(), "/key", key); err != nil { + log.Fatal(err) + } + } + + // Send the 2 queries and keep the results + results, err := batch.Send(context.Background()) + if err != nil { + log.Fatal(err) + } + + // Each result in the returned list is the deserialized result of each + // respective ABCIQuery response + for _, result := range results { + qr, ok := result.(*ctypes.ResultABCIQuery) + if !ok { + log.Fatal("invalid result type from ABCIQuery request") + } + fmt.Println(string(qr.Response.Key), "=", string(qr.Response.Value)) + } + + // Output: + // firstName = satoshi + // lastName = nakamoto +} + +// Test the maximum batch request size middleware. +func ExampleHTTP_maxBatchSize() { + // Start a CometBFT node (and kvstore) in the background to test against + app := kvstore.NewInMemoryApplication() + node := rpctest.StartTendermint(app, rpctest.RecreateConfig, rpctest.SuppressStdout, rpctest.MaxReqBatchSize) + + // Change the max_request_batch_size + node.Config().RPC.MaxRequestBatchSize = 2 + + // Create our RPC client + rpcAddr := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.New(rpcAddr, "/websocket") + if err != nil { + log.Fatal(err) + } + + defer rpctest.StopTendermint(node) + + // Create a new batch + batch := c.NewBatch() + + for i := 1; i <= 5; i++ { + if _, err := batch.Health(context.Background()); err != nil { + log.Fatal(err) + } + } + + // Send the requests + results, err := batch.Send(context.Background()) + if err != nil { + log.Fatal(err) + } + + // Each result in the returned list is the deserialized result of each + // respective status response + for _, result := range results { + rpcError, ok := result.(*types.RPCError) + if !ok { + log.Fatal("invalid result type") + } + if !strings.Contains(rpcError.Data, "batch request exceeds maximum") { + fmt.Println("Error message does not contain 'Max Request Batch Exceeded'") + } else { + // The max request batch size rpcError has been returned + fmt.Println("Max Request Batch Exceeded") + } + } + + // Output: + // Max Request Batch Exceeded +} diff --git a/rpc/client/helpers.go b/rpc/client/helpers.go new file mode 100644 index 0000000..b2bca31 --- /dev/null +++ b/rpc/client/helpers.go @@ -0,0 +1,83 @@ +package client + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/types" +) + +// Waiter is informed of current height, decided whether to quit early +type Waiter func(delta int64) (abort error) + +// DefaultWaitStrategy is the standard backoff algorithm, +// but you can plug in another one +func DefaultWaitStrategy(delta int64) (abort error) { + if delta > 10 { + return fmt.Errorf("waiting for %d blocks... aborting", delta) + } else if delta > 0 { + // estimate of wait time.... + // wait half a second for the next block (in progress) + // plus one second for every full block + delay := time.Duration(delta-1)*time.Second + 500*time.Millisecond + time.Sleep(delay) + } + return nil +} + +// Wait for height will poll status at reasonable intervals until +// the block at the given height is available. +// +// If waiter is nil, we use DefaultWaitStrategy, but you can also +// provide your own implementation +func WaitForHeight(c StatusClient, h int64, waiter Waiter) error { + if waiter == nil { + waiter = DefaultWaitStrategy + } + delta := int64(1) + for delta > 0 { + s, err := c.Status(context.Background()) + if err != nil { + return err + } + delta = h - s.SyncInfo.LatestBlockHeight + // wait for the time, or abort early + if err := waiter(delta); err != nil { + return err + } + } + + return nil +} + +// WaitForOneEvent subscribes to a websocket event for the given +// event time and returns upon receiving it one time, or +// when the timeout duration has expired. +// +// This handles subscribing and unsubscribing under the hood +func WaitForOneEvent(c EventsClient, evtTyp string, timeout time.Duration) (types.TMEventData, error) { + const subscriber = "helpers" + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + // register for the next event of this type + eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(evtTyp).String()) + if err != nil { + return nil, fmt.Errorf("failed to subscribe: %w", err) + } + // make sure to unregister after the test is over + defer func() { + if deferErr := c.UnsubscribeAll(ctx, subscriber); deferErr != nil { + panic(deferErr) + } + }() + + select { + case event := <-eventCh: + return event.Data, nil + case <-ctx.Done(): + return nil, errors.New("timed out waiting for event") + } +} diff --git a/rpc/client/helpers_test.go b/rpc/client/helpers_test.go new file mode 100644 index 0000000..8b698f3 --- /dev/null +++ b/rpc/client/helpers_test.go @@ -0,0 +1,77 @@ +package client_test + +import ( + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/rpc/client" + "github.com/cometbft/cometbft/rpc/client/mock" + ctypes "github.com/cometbft/cometbft/rpc/core/types" +) + +func TestWaitForHeight(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // test with error result - immediate failure + m := &mock.StatusMock{ + Call: mock.Call{ + Error: errors.New("bye"), + }, + } + r := mock.NewStatusRecorder(m) + + // connection failure always leads to error + err := client.WaitForHeight(r, 8, nil) + require.NotNil(err) + require.Equal("bye", err.Error()) + // we called status once to check + require.Equal(1, len(r.Calls)) + + // now set current block height to 10 + m.Call = mock.Call{ + Response: &ctypes.ResultStatus{SyncInfo: ctypes.SyncInfo{LatestBlockHeight: 10}}, + } + + // we will not wait for more than 10 blocks + err = client.WaitForHeight(r, 40, nil) + require.NotNil(err) + require.True(strings.Contains(err.Error(), "aborting")) + // we called status once more to check + require.Equal(2, len(r.Calls)) + + // waiting for the past returns immediately + err = client.WaitForHeight(r, 5, nil) + require.Nil(err) + // we called status once more to check + require.Equal(3, len(r.Calls)) + + // since we can't update in a background goroutine (test --race) + // we use the callback to update the status height + myWaiter := func(delta int64) error { + // update the height for the next call + m.Response = &ctypes.ResultStatus{SyncInfo: ctypes.SyncInfo{LatestBlockHeight: 15}} + return client.DefaultWaitStrategy(delta) + } + + // we wait for a few blocks + err = client.WaitForHeight(r, 12, myWaiter) + require.Nil(err) + // we called status once to check + require.Equal(5, len(r.Calls)) + + pre := r.Calls[3] + require.Nil(pre.Error) + prer, ok := pre.Response.(*ctypes.ResultStatus) + require.True(ok) + assert.Equal(int64(10), prer.SyncInfo.LatestBlockHeight) + + post := r.Calls[4] + require.Nil(post.Error) + postr, ok := post.Response.(*ctypes.ResultStatus) + require.True(ok) + assert.Equal(int64(15), postr.SyncInfo.LatestBlockHeight) +} diff --git a/rpc/client/http/http.go b/rpc/client/http/http.go new file mode 100644 index 0000000..7cd746d --- /dev/null +++ b/rpc/client/http/http.go @@ -0,0 +1,790 @@ +package http + +import ( + "context" + "errors" + "net/http" + "strings" + "time" + + "github.com/cometbft/cometbft/libs/bytes" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/service" + cmtsync "github.com/cometbft/cometbft/libs/sync" + rpcclient "github.com/cometbft/cometbft/rpc/client" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + jsonrpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + "github.com/cometbft/cometbft/types" +) + +/* +HTTP is a Client implementation that communicates with a CometBFT node over +JSON RPC and WebSockets. + +This is the main implementation you probably want to use in production code. +There are other implementations when calling the CometBFT node in-process +(Local), or when you want to mock out the server for test code (mock). + +You can subscribe for any event published by CometBFT using Subscribe method. +Note delivery is best-effort. If you don't read events fast enough or network is +slow, CometBFT might cancel the subscription. The client will attempt to +resubscribe (you don't need to do anything). It will keep trying every second +indefinitely until successful. + +Request batching is available for JSON RPC requests over HTTP, which conforms to +the JSON RPC specification (https://www.jsonrpc.org/specification#batch). See +the example for more details. + +Example: + + c, err := New("http://192.168.1.10:26657", "/websocket") + if err != nil { + // handle error + } + + // call Start/Stop if you're subscribing to events + err = c.Start() + if err != nil { + // handle error + } + defer c.Stop() + + res, err := c.Status() + if err != nil { + // handle error + } + + // handle result +*/ +type HTTP struct { + remote string + rpc *jsonrpcclient.Client + + *baseRPCClient + *WSEvents +} + +// BatchHTTP provides the same interface as `HTTP`, but allows for batching of +// requests (as per https://www.jsonrpc.org/specification#batch). Do not +// instantiate directly - rather use the HTTP.NewBatch() method to create an +// instance of this struct. +// +// Batching of HTTP requests is thread-safe in the sense that multiple +// goroutines can each create their own batches and send them using the same +// HTTP client. Multiple goroutines could also enqueue transactions in a single +// batch, but ordering of transactions in the batch cannot be guaranteed in such +// an example. +type BatchHTTP struct { + rpcBatch *jsonrpcclient.RequestBatch + *baseRPCClient +} + +// rpcClient is an internal interface to which our RPC clients (batch and +// non-batch) must conform. Acts as an additional code-level sanity check to +// make sure the implementations stay coherent. +type rpcClient interface { + rpcclient.ABCIClient + rpcclient.HistoryClient + rpcclient.NetworkClient + rpcclient.SignClient + rpcclient.StatusClient +} + +// baseRPCClient implements the basic RPC method logic without the actual +// underlying RPC call functionality, which is provided by `caller`. +type baseRPCClient struct { + caller jsonrpcclient.Caller +} + +var ( + _ rpcClient = (*HTTP)(nil) + _ rpcClient = (*BatchHTTP)(nil) + _ rpcClient = (*baseRPCClient)(nil) +) + +//----------------------------------------------------------------------------- +// HTTP + +// New takes a remote endpoint in the form ://: and +// the websocket path (which always seems to be "/websocket") +// An error is returned on invalid remote. The function panics when remote is nil. +func New(remote, wsEndpoint string) (*HTTP, error) { + httpClient, err := jsonrpcclient.DefaultHTTPClient(remote) + if err != nil { + return nil, err + } + return NewWithClient(remote, wsEndpoint, httpClient) +} + +// Create timeout enabled http client +func NewWithTimeout(remote, wsEndpoint string, timeout uint) (*HTTP, error) { + httpClient, err := jsonrpcclient.DefaultHTTPClient(remote) + if err != nil { + return nil, err + } + httpClient.Timeout = time.Duration(timeout) * time.Second + return NewWithClient(remote, wsEndpoint, httpClient) +} + +// NewWithClient allows for setting a custom http client (See New). +// An error is returned on invalid remote. The function panics when remote is nil. +func NewWithClient(remote, wsEndpoint string, client *http.Client) (*HTTP, error) { + if client == nil { + panic("nil http.Client provided") + } + + rc, err := jsonrpcclient.NewWithHTTPClient(remote, client) + if err != nil { + return nil, err + } + + wsEvents, err := newWSEvents(remote, wsEndpoint) + if err != nil { + return nil, err + } + + httpClient := &HTTP{ + rpc: rc, + remote: remote, + baseRPCClient: &baseRPCClient{caller: rc}, + WSEvents: wsEvents, + } + + return httpClient, nil +} + +var _ rpcclient.Client = (*HTTP)(nil) + +// SetLogger sets a logger. +func (c *HTTP) SetLogger(l log.Logger) { + c.WSEvents.SetLogger(l) +} + +// Remote returns the remote network address in a string form. +func (c *HTTP) Remote() string { + return c.remote +} + +// NewBatch creates a new batch client for this HTTP client. +func (c *HTTP) NewBatch() *BatchHTTP { + rpcBatch := c.rpc.NewRequestBatch() + return &BatchHTTP{ + rpcBatch: rpcBatch, + baseRPCClient: &baseRPCClient{ + caller: rpcBatch, + }, + } +} + +//----------------------------------------------------------------------------- +// BatchHTTP + +// Send is a convenience function for an HTTP batch that will trigger the +// compilation of the batched requests and send them off using the client as a +// single request. On success, this returns a list of the deserialized results +// from each request in the sent batch. +func (b *BatchHTTP) Send(ctx context.Context) ([]interface{}, error) { + return b.rpcBatch.Send(ctx) +} + +// Clear will empty out this batch of requests and return the number of requests +// that were cleared out. +func (b *BatchHTTP) Clear() int { + return b.rpcBatch.Clear() +} + +// Count returns the number of enqueued requests waiting to be sent. +func (b *BatchHTTP) Count() int { + return b.rpcBatch.Count() +} + +//----------------------------------------------------------------------------- +// baseRPCClient + +func (c *baseRPCClient) Status(ctx context.Context) (*ctypes.ResultStatus, error) { + result := new(ctypes.ResultStatus) + _, err := c.caller.Call(ctx, "status", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *baseRPCClient) ABCIInfo(ctx context.Context) (*ctypes.ResultABCIInfo, error) { + result := new(ctypes.ResultABCIInfo) + _, err := c.caller.Call(ctx, "abci_info", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *baseRPCClient) ABCIQuery( + ctx context.Context, + path string, + data bytes.HexBytes, +) (*ctypes.ResultABCIQuery, error) { + return c.ABCIQueryWithOptions(ctx, path, data, rpcclient.DefaultABCIQueryOptions) +} + +func (c *baseRPCClient) ABCIQueryWithOptions( + ctx context.Context, + path string, + data bytes.HexBytes, + opts rpcclient.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { + result := new(ctypes.ResultABCIQuery) + _, err := c.caller.Call(ctx, "abci_query", + map[string]interface{}{"path": path, "data": data, "height": opts.Height, "prove": opts.Prove}, + result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *baseRPCClient) BroadcastTxCommit( + ctx context.Context, + tx types.Tx, +) (*ctypes.ResultBroadcastTxCommit, error) { + result := new(ctypes.ResultBroadcastTxCommit) + _, err := c.caller.Call(ctx, "broadcast_tx_commit", map[string]interface{}{"tx": tx}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) BroadcastTxAsync( + ctx context.Context, + tx types.Tx, +) (*ctypes.ResultBroadcastTx, error) { + return c.broadcastTX(ctx, "broadcast_tx_async", tx) +} + +func (c *baseRPCClient) BroadcastTxSync( + ctx context.Context, + tx types.Tx, +) (*ctypes.ResultBroadcastTx, error) { + return c.broadcastTX(ctx, "broadcast_tx_sync", tx) +} + +func (c *baseRPCClient) broadcastTX( + ctx context.Context, + route string, + tx types.Tx, +) (*ctypes.ResultBroadcastTx, error) { + result := new(ctypes.ResultBroadcastTx) + _, err := c.caller.Call(ctx, route, map[string]interface{}{"tx": tx}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) UnconfirmedTxs( + ctx context.Context, + limit *int, +) (*ctypes.ResultUnconfirmedTxs, error) { + result := new(ctypes.ResultUnconfirmedTxs) + params := make(map[string]interface{}) + if limit != nil { + params["limit"] = limit + } + _, err := c.caller.Call(ctx, "unconfirmed_txs", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) NumUnconfirmedTxs(ctx context.Context) (*ctypes.ResultUnconfirmedTxs, error) { + result := new(ctypes.ResultUnconfirmedTxs) + _, err := c.caller.Call(ctx, "num_unconfirmed_txs", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) CheckTx(ctx context.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) { + result := new(ctypes.ResultCheckTx) + _, err := c.caller.Call(ctx, "check_tx", map[string]interface{}{"tx": tx}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) NetInfo(ctx context.Context) (*ctypes.ResultNetInfo, error) { + result := new(ctypes.ResultNetInfo) + _, err := c.caller.Call(ctx, "net_info", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) DumpConsensusState(ctx context.Context) (*ctypes.ResultDumpConsensusState, error) { + result := new(ctypes.ResultDumpConsensusState) + _, err := c.caller.Call(ctx, "dump_consensus_state", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) ConsensusState(ctx context.Context) (*ctypes.ResultConsensusState, error) { + result := new(ctypes.ResultConsensusState) + _, err := c.caller.Call(ctx, "consensus_state", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) ConsensusParams( + ctx context.Context, + height *int64, +) (*ctypes.ResultConsensusParams, error) { + result := new(ctypes.ResultConsensusParams) + params := make(map[string]interface{}) + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "consensus_params", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Health(ctx context.Context) (*ctypes.ResultHealth, error) { + result := new(ctypes.ResultHealth) + _, err := c.caller.Call(ctx, "health", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) BlockchainInfo( + ctx context.Context, + minHeight, + maxHeight int64, +) (*ctypes.ResultBlockchainInfo, error) { + result := new(ctypes.ResultBlockchainInfo) + _, err := c.caller.Call(ctx, "blockchain", + map[string]interface{}{"minHeight": minHeight, "maxHeight": maxHeight}, + result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Genesis(ctx context.Context) (*ctypes.ResultGenesis, error) { + result := new(ctypes.ResultGenesis) + _, err := c.caller.Call(ctx, "genesis", map[string]interface{}{}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) GenesisChunked(ctx context.Context, id uint) (*ctypes.ResultGenesisChunk, error) { + result := new(ctypes.ResultGenesisChunk) + _, err := c.caller.Call(ctx, "genesis_chunked", map[string]interface{}{"chunk": id}, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Block(ctx context.Context, height *int64) (*ctypes.ResultBlock, error) { + result := new(ctypes.ResultBlock) + params := make(map[string]interface{}) + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "block", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) BlockByHash(ctx context.Context, hash []byte) (*ctypes.ResultBlock, error) { + result := new(ctypes.ResultBlock) + params := map[string]interface{}{ + "hash": hash, + } + _, err := c.caller.Call(ctx, "block_by_hash", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) BlockResults( + ctx context.Context, + height *int64, +) (*ctypes.ResultBlockResults, error) { + result := new(ctypes.ResultBlockResults) + params := make(map[string]interface{}) + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "block_results", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Header(ctx context.Context, height *int64) (*ctypes.ResultHeader, error) { + result := new(ctypes.ResultHeader) + params := make(map[string]interface{}) + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "header", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) HeaderByHash(ctx context.Context, hash bytes.HexBytes) (*ctypes.ResultHeader, error) { + result := new(ctypes.ResultHeader) + params := map[string]interface{}{ + "hash": hash, + } + _, err := c.caller.Call(ctx, "header_by_hash", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Commit(ctx context.Context, height *int64) (*ctypes.ResultCommit, error) { + result := new(ctypes.ResultCommit) + params := make(map[string]interface{}) + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "commit", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) Tx(ctx context.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) { + result := new(ctypes.ResultTx) + params := map[string]interface{}{ + "hash": hash, + "prove": prove, + } + _, err := c.caller.Call(ctx, "tx", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) TxSearch( + ctx context.Context, + query string, + prove bool, + page, + perPage *int, + orderBy string, +) (*ctypes.ResultTxSearch, error) { + result := new(ctypes.ResultTxSearch) + params := map[string]interface{}{ + "query": query, + "prove": prove, + "order_by": orderBy, + } + + if page != nil { + params["page"] = page + } + if perPage != nil { + params["per_page"] = perPage + } + + _, err := c.caller.Call(ctx, "tx_search", params, result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *baseRPCClient) BlockSearch( + ctx context.Context, + query string, + page, perPage *int, + orderBy string, +) (*ctypes.ResultBlockSearch, error) { + result := new(ctypes.ResultBlockSearch) + params := map[string]interface{}{ + "query": query, + "order_by": orderBy, + } + + if page != nil { + params["page"] = page + } + if perPage != nil { + params["per_page"] = perPage + } + + _, err := c.caller.Call(ctx, "block_search", params, result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *baseRPCClient) Validators( + ctx context.Context, + height *int64, + page, + perPage *int, +) (*ctypes.ResultValidators, error) { + result := new(ctypes.ResultValidators) + params := make(map[string]interface{}) + if page != nil { + params["page"] = page + } + if perPage != nil { + params["per_page"] = perPage + } + if height != nil { + params["height"] = height + } + _, err := c.caller.Call(ctx, "validators", params, result) + if err != nil { + return nil, err + } + return result, nil +} + +func (c *baseRPCClient) BroadcastEvidence( + ctx context.Context, + ev types.Evidence, +) (*ctypes.ResultBroadcastEvidence, error) { + result := new(ctypes.ResultBroadcastEvidence) + _, err := c.caller.Call(ctx, "broadcast_evidence", map[string]interface{}{"evidence": ev}, result) + if err != nil { + return nil, err + } + return result, nil +} + +//----------------------------------------------------------------------------- +// WSEvents + +var errNotRunning = errors.New("client is not running. Use .Start() method to start") + +// WSEvents is a wrapper around WSClient, which implements EventsClient. +type WSEvents struct { + service.BaseService + remote string + endpoint string + ws *jsonrpcclient.WSClient + + mtx cmtsync.RWMutex + subscriptions map[string]chan ctypes.ResultEvent // query -> chan +} + +func newWSEvents(remote, endpoint string) (*WSEvents, error) { + w := &WSEvents{ + endpoint: endpoint, + remote: remote, + subscriptions: make(map[string]chan ctypes.ResultEvent), + } + w.BaseService = *service.NewBaseService(nil, "WSEvents", w) + + var err error + w.ws, err = jsonrpcclient.NewWS(w.remote, w.endpoint, jsonrpcclient.OnReconnect(func() { + // resubscribe immediately + w.redoSubscriptionsAfter(0 * time.Second) + })) + if err != nil { + return nil, err + } + w.ws.SetLogger(w.Logger) + + return w, nil +} + +// OnStart implements service.Service by starting WSClient and event loop. +func (w *WSEvents) OnStart() error { + if err := w.ws.Start(); err != nil { + return err + } + + go w.eventListener() + + return nil +} + +// OnStop implements service.Service by stopping WSClient. +func (w *WSEvents) OnStop() { + if err := w.ws.Stop(); err != nil { + w.Logger.Error("Can't stop ws client", "err", err) + } +} + +// Subscribe implements EventsClient by using WSClient to subscribe given +// subscriber to query. By default, returns a channel with cap=1. Error is +// returned if it fails to subscribe. +// +// Channel is never closed to prevent clients from seeing an erroneous event. +// +// It returns an error if WSEvents is not running. +func (w *WSEvents) Subscribe(ctx context.Context, _, query string, + outCapacity ...int, +) (out <-chan ctypes.ResultEvent, err error) { + if !w.IsRunning() { + return nil, errNotRunning + } + + if err := w.ws.Subscribe(ctx, query); err != nil { + return nil, err + } + + outCap := 1 + if len(outCapacity) > 0 { + outCap = outCapacity[0] + } + + outc := make(chan ctypes.ResultEvent, outCap) + w.mtx.Lock() + // subscriber param is ignored because CometBFT will override it with + // remote IP anyway. + w.subscriptions[query] = outc + w.mtx.Unlock() + + return outc, nil +} + +// Unsubscribe implements EventsClient by using WSClient to unsubscribe given +// subscriber from query. +// +// It returns an error if WSEvents is not running. +func (w *WSEvents) Unsubscribe(ctx context.Context, _, query string) error { + if !w.IsRunning() { + return errNotRunning + } + + if err := w.ws.Unsubscribe(ctx, query); err != nil { + return err + } + + w.mtx.Lock() + _, ok := w.subscriptions[query] + if ok { + delete(w.subscriptions, query) + } + w.mtx.Unlock() + + return nil +} + +// UnsubscribeAll implements EventsClient by using WSClient to unsubscribe +// given subscriber from all the queries. +// +// It returns an error if WSEvents is not running. +func (w *WSEvents) UnsubscribeAll(ctx context.Context, _ string) error { + if !w.IsRunning() { + return errNotRunning + } + + if err := w.ws.UnsubscribeAll(ctx); err != nil { + return err + } + + w.mtx.Lock() + w.subscriptions = make(map[string]chan ctypes.ResultEvent) + w.mtx.Unlock() + + return nil +} + +// After being reconnected, it is necessary to redo subscription to server +// otherwise no data will be automatically received. +func (w *WSEvents) redoSubscriptionsAfter(d time.Duration) { + time.Sleep(d) + + w.mtx.RLock() + defer w.mtx.RUnlock() + for q := range w.subscriptions { + err := w.ws.Subscribe(context.Background(), q) + if err != nil { + w.Logger.Error("Failed to resubscribe", "err", err) + } + } +} + +func isErrAlreadySubscribed(err error) bool { + return strings.Contains(err.Error(), cmtpubsub.ErrAlreadySubscribed.Error()) +} + +func (w *WSEvents) eventListener() { + for { + select { + case resp, ok := <-w.ws.ResponsesCh: + if !ok { + return + } + + if resp.Error != nil { + w.Logger.Error("WS error", "err", resp.Error.Error()) + // Error can be ErrAlreadySubscribed or max client (subscriptions per + // client) reached or CometBFT exited. + // We can ignore ErrAlreadySubscribed, but need to retry in other + // cases. + if !isErrAlreadySubscribed(resp.Error) { + // Resubscribe after 1 second to give CometBFT time to restart (if + // crashed). + w.redoSubscriptionsAfter(1 * time.Second) + } + continue + } + + result := new(ctypes.ResultEvent) + err := cmtjson.Unmarshal(resp.Result, result) + if err != nil { + w.Logger.Error("failed to unmarshal response", "err", err) + continue + } + + w.mtx.RLock() + if out, ok := w.subscriptions[result.Query]; ok { + if cap(out) == 0 { + out <- *result + } else { + select { + case out <- *result: + default: + w.Logger.Error("wanted to publish ResultEvent, but out channel is full", "result", result, "query", result.Query) + } + } + } + w.mtx.RUnlock() + case <-w.Quit(): + return + } + } +} diff --git a/rpc/client/interface.go b/rpc/client/interface.go new file mode 100644 index 0000000..398e774 --- /dev/null +++ b/rpc/client/interface.go @@ -0,0 +1,154 @@ +package client + +/* +The client package provides a general purpose interface (Client) for connecting +to a CometBFT node, as well as higher-level functionality. + +The main implementation for production code is client.HTTP, which +connects via http to the jsonrpc interface of the CometBFT node. + +For connecting to a node running in the same process (eg. when +compiling the abci app in the same process), you can use the client.Local +implementation. + +For mocking out server responses during testing to see behavior for +arbitrary return values, use the mock package. + +In addition to the Client interface, which should be used externally +for maximum flexibility and testability, and two implementations, +this package also provides helper functions that work on any Client +implementation. +*/ + +import ( + "context" + + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/service" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/types" +) + +// Client wraps most important rpc calls a client would make if you want to +// listen for events, test if it also implements events.EventSwitch. +type Client interface { + service.Service + ABCIClient + EventsClient + HistoryClient + NetworkClient + SignClient + StatusClient + EvidenceClient + MempoolClient +} + +// ABCIClient groups together the functionality that principally affects the +// ABCI app. +// +// In many cases this will be all we want, so we can accept an interface which +// is easier to mock. +type ABCIClient interface { + // Reading from abci app + ABCIInfo(context.Context) (*ctypes.ResultABCIInfo, error) + ABCIQuery(ctx context.Context, path string, data bytes.HexBytes) (*ctypes.ResultABCIQuery, error) + ABCIQueryWithOptions(ctx context.Context, path string, data bytes.HexBytes, + opts ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) + + // Writing to abci app + BroadcastTxCommit(context.Context, types.Tx) (*ctypes.ResultBroadcastTxCommit, error) + BroadcastTxAsync(context.Context, types.Tx) (*ctypes.ResultBroadcastTx, error) + BroadcastTxSync(context.Context, types.Tx) (*ctypes.ResultBroadcastTx, error) +} + +// SignClient groups together the functionality needed to get valid signatures +// and prove anything about the chain. +type SignClient interface { + Block(ctx context.Context, height *int64) (*ctypes.ResultBlock, error) + BlockByHash(ctx context.Context, hash []byte) (*ctypes.ResultBlock, error) + BlockResults(ctx context.Context, height *int64) (*ctypes.ResultBlockResults, error) + Header(ctx context.Context, height *int64) (*ctypes.ResultHeader, error) + HeaderByHash(ctx context.Context, hash bytes.HexBytes) (*ctypes.ResultHeader, error) + Commit(ctx context.Context, height *int64) (*ctypes.ResultCommit, error) + Validators(ctx context.Context, height *int64, page, perPage *int) (*ctypes.ResultValidators, error) + Tx(ctx context.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) + + // TxSearch defines a method to search for a paginated set of transactions by + // transaction event search criteria. + TxSearch( + ctx context.Context, + query string, + prove bool, + page, perPage *int, + orderBy string, + ) (*ctypes.ResultTxSearch, error) + + // BlockSearch defines a method to search for a paginated set of blocks based + // from FinalizeBlock event search criteria. + BlockSearch( + ctx context.Context, + query string, + page, perPage *int, + orderBy string, + ) (*ctypes.ResultBlockSearch, error) +} + +// HistoryClient provides access to data from genesis to now in large chunks. +type HistoryClient interface { + Genesis(context.Context) (*ctypes.ResultGenesis, error) + GenesisChunked(context.Context, uint) (*ctypes.ResultGenesisChunk, error) + BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) +} + +// StatusClient provides access to general chain info. +type StatusClient interface { + Status(context.Context) (*ctypes.ResultStatus, error) +} + +// NetworkClient is general info about the network state. May not be needed +// usually. +type NetworkClient interface { + NetInfo(context.Context) (*ctypes.ResultNetInfo, error) + DumpConsensusState(context.Context) (*ctypes.ResultDumpConsensusState, error) + ConsensusState(context.Context) (*ctypes.ResultConsensusState, error) + ConsensusParams(ctx context.Context, height *int64) (*ctypes.ResultConsensusParams, error) + Health(context.Context) (*ctypes.ResultHealth, error) +} + +// EventsClient is reactive, you can subscribe to any message, given the proper +// string. see cometbft/types/events.go +type EventsClient interface { + // Subscribe subscribes given subscriber to query. Returns a channel with + // cap=1 onto which events are published. An error is returned if it fails to + // subscribe. outCapacity can be used optionally to set capacity for the + // channel. Channel is never closed to prevent accidental reads. + // + // ctx cannot be used to unsubscribe. To unsubscribe, use either Unsubscribe + // or UnsubscribeAll. + Subscribe(ctx context.Context, subscriber, query string, outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) + // Unsubscribe unsubscribes given subscriber from query. + Unsubscribe(ctx context.Context, subscriber, query string) error + // UnsubscribeAll unsubscribes given subscriber from all the queries. + UnsubscribeAll(ctx context.Context, subscriber string) error +} + +// MempoolClient shows us data about current mempool state. +type MempoolClient interface { + UnconfirmedTxs(ctx context.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) + NumUnconfirmedTxs(context.Context) (*ctypes.ResultUnconfirmedTxs, error) + CheckTx(context.Context, types.Tx) (*ctypes.ResultCheckTx, error) +} + +// EvidenceClient is used for submitting an evidence of the malicious +// behavior. +type EvidenceClient interface { + BroadcastEvidence(context.Context, types.Evidence) (*ctypes.ResultBroadcastEvidence, error) +} + +// RemoteClient is a Client, which can also return the remote network address. +type RemoteClient interface { + Client + + // Remote returns the remote network address in a string form. + Remote() string +} diff --git a/rpc/client/local/local.go b/rpc/client/local/local.go new file mode 100644 index 0000000..f1289c1 --- /dev/null +++ b/rpc/client/local/local.go @@ -0,0 +1,310 @@ +package local + +import ( + "context" + "fmt" + "time" + + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" + nm "github.com/cometbft/cometbft/node" + rpcclient "github.com/cometbft/cometbft/rpc/client" + "github.com/cometbft/cometbft/rpc/core" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +/* +Local is a Client implementation that directly executes the rpc +functions on a given node, without going through HTTP or GRPC. + +This implementation is useful for: + +* Running tests against a node in-process without the overhead +of going through an http server +* Communication between an ABCI app and CometBFT when they +are compiled in process. + +For real clients, you probably want to use client.HTTP. For more +powerful control during testing, you probably want the "client/mock" package. + +You can subscribe for any event published by CometBFT using Subscribe method. +Note delivery is best-effort. If you don't read events fast enough, CometBFT +might cancel the subscription. The client will attempt to resubscribe (you +don't need to do anything). It will keep trying indefinitely with exponential +backoff (10ms -> 20ms -> 40ms) until successful. +*/ +type Local struct { + *types.EventBus + Logger log.Logger + ctx *rpctypes.Context + env *core.Environment +} + +// NewLocal configures a client that calls the Node directly. +func New(node *nm.Node) *Local { + env, err := node.ConfigureRPC() + if err != nil { + node.Logger.Error("Error configuring RPC", "err", err) + } + return &Local{ + EventBus: node.EventBus(), + Logger: log.NewNopLogger(), + ctx: &rpctypes.Context{}, + env: env, + } +} + +var _ rpcclient.Client = (*Local)(nil) + +// SetLogger allows to set a logger on the client. +func (c *Local) SetLogger(l log.Logger) { + c.Logger = l +} + +func (c *Local) Status(context.Context) (*ctypes.ResultStatus, error) { + return c.env.Status(c.ctx) +} + +func (c *Local) ABCIInfo(context.Context) (*ctypes.ResultABCIInfo, error) { + return c.env.ABCIInfo(c.ctx) +} + +func (c *Local) ABCIQuery(ctx context.Context, path string, data bytes.HexBytes) (*ctypes.ResultABCIQuery, error) { + return c.ABCIQueryWithOptions(ctx, path, data, rpcclient.DefaultABCIQueryOptions) +} + +func (c *Local) ABCIQueryWithOptions( + _ context.Context, + path string, + data bytes.HexBytes, + opts rpcclient.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { + return c.env.ABCIQuery(c.ctx, path, data, opts.Height, opts.Prove) +} + +func (c *Local) BroadcastTxCommit(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { + return c.env.BroadcastTxCommit(c.ctx, tx) +} + +func (c *Local) BroadcastTxAsync(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.env.BroadcastTxAsync(c.ctx, tx) +} + +func (c *Local) BroadcastTxSync(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.env.BroadcastTxSync(c.ctx, tx) +} + +func (c *Local) UnconfirmedTxs(_ context.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) { + return c.env.UnconfirmedTxs(c.ctx, limit) +} + +func (c *Local) NumUnconfirmedTxs(context.Context) (*ctypes.ResultUnconfirmedTxs, error) { + return c.env.NumUnconfirmedTxs(c.ctx) +} + +func (c *Local) CheckTx(_ context.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) { + return c.env.CheckTx(c.ctx, tx) +} + +func (c *Local) NetInfo(context.Context) (*ctypes.ResultNetInfo, error) { + return c.env.NetInfo(c.ctx) +} + +func (c *Local) DumpConsensusState(context.Context) (*ctypes.ResultDumpConsensusState, error) { + return c.env.DumpConsensusState(c.ctx) +} + +func (c *Local) ConsensusState(context.Context) (*ctypes.ResultConsensusState, error) { + return c.env.GetConsensusState(c.ctx) +} + +func (c *Local) ConsensusParams(_ context.Context, height *int64) (*ctypes.ResultConsensusParams, error) { + return c.env.ConsensusParams(c.ctx, height) +} + +func (c *Local) Health(context.Context) (*ctypes.ResultHealth, error) { + return c.env.Health(c.ctx) +} + +func (c *Local) DialSeeds(_ context.Context, seeds []string) (*ctypes.ResultDialSeeds, error) { + return c.env.UnsafeDialSeeds(c.ctx, seeds) +} + +func (c *Local) DialPeers( + _ context.Context, + peers []string, + persistent, + unconditional, + private bool, +) (*ctypes.ResultDialPeers, error) { + return c.env.UnsafeDialPeers(c.ctx, peers, persistent, unconditional, private) +} + +func (c *Local) BlockchainInfo(_ context.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) { + return c.env.BlockchainInfo(c.ctx, minHeight, maxHeight) +} + +func (c *Local) Genesis(context.Context) (*ctypes.ResultGenesis, error) { + return c.env.Genesis(c.ctx) +} + +func (c *Local) GenesisChunked(_ context.Context, id uint) (*ctypes.ResultGenesisChunk, error) { + return c.env.GenesisChunked(c.ctx, id) +} + +func (c *Local) Block(_ context.Context, height *int64) (*ctypes.ResultBlock, error) { + return c.env.Block(c.ctx, height) +} + +func (c *Local) BlockByHash(_ context.Context, hash []byte) (*ctypes.ResultBlock, error) { + return c.env.BlockByHash(c.ctx, hash) +} + +func (c *Local) BlockResults(_ context.Context, height *int64) (*ctypes.ResultBlockResults, error) { + return c.env.BlockResults(c.ctx, height) +} + +func (c *Local) Header(_ context.Context, height *int64) (*ctypes.ResultHeader, error) { + return c.env.Header(c.ctx, height) +} + +func (c *Local) HeaderByHash(_ context.Context, hash bytes.HexBytes) (*ctypes.ResultHeader, error) { + return c.env.HeaderByHash(c.ctx, hash) +} + +func (c *Local) Commit(_ context.Context, height *int64) (*ctypes.ResultCommit, error) { + return c.env.Commit(c.ctx, height) +} + +func (c *Local) Validators(_ context.Context, height *int64, page, perPage *int) (*ctypes.ResultValidators, error) { + return c.env.Validators(c.ctx, height, page, perPage) +} + +func (c *Local) Tx(_ context.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) { + return c.env.Tx(c.ctx, hash, prove) +} + +func (c *Local) TxSearch( + _ context.Context, + query string, + prove bool, + page, + perPage *int, + orderBy string, +) (*ctypes.ResultTxSearch, error) { + return c.env.TxSearch(c.ctx, query, prove, page, perPage, orderBy) +} + +func (c *Local) BlockSearch( + _ context.Context, + query string, + page, perPage *int, + orderBy string, +) (*ctypes.ResultBlockSearch, error) { + return c.env.BlockSearch(c.ctx, query, page, perPage, orderBy) +} + +func (c *Local) BroadcastEvidence(_ context.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { + return c.env.BroadcastEvidence(c.ctx, ev) +} + +func (c *Local) Subscribe( + ctx context.Context, + subscriber, + query string, + outCapacity ...int, +) (out <-chan ctypes.ResultEvent, err error) { + q, err := cmtquery.New(query) + if err != nil { + return nil, fmt.Errorf("failed to parse query: %w", err) + } + + outCap := 1 + if len(outCapacity) > 0 { + outCap = outCapacity[0] + } + + var sub types.Subscription + if outCap > 0 { + sub, err = c.EventBus.Subscribe(ctx, subscriber, q, outCap) + } else { + sub, err = c.SubscribeUnbuffered(ctx, subscriber, q) + } + if err != nil { + return nil, fmt.Errorf("failed to subscribe: %w", err) + } + + outc := make(chan ctypes.ResultEvent, outCap) + go c.eventsRoutine(sub, subscriber, q, outc) + + return outc, nil +} + +func (c *Local) eventsRoutine( + sub types.Subscription, + subscriber string, + q cmtpubsub.Query, + outc chan<- ctypes.ResultEvent, +) { + for { + select { + case msg := <-sub.Out(): + result := ctypes.ResultEvent{Query: q.String(), Data: msg.Data(), Events: msg.Events()} + if cap(outc) == 0 { + outc <- result + } else { + select { + case outc <- result: + default: + c.Logger.Error("wanted to publish ResultEvent, but out channel is full", "result", result, "query", result.Query) + } + } + case <-sub.Canceled(): + if sub.Err() == cmtpubsub.ErrUnsubscribed { + return + } + + c.Logger.Error("subscription was canceled, resubscribing...", "err", sub.Err(), "query", q.String()) + sub = c.resubscribe(subscriber, q) + if sub == nil { // client was stopped + return + } + case <-c.Quit(): + return + } + } +} + +// Try to resubscribe with exponential backoff. +func (c *Local) resubscribe(subscriber string, q cmtpubsub.Query) types.Subscription { + attempts := 0 + for { + if !c.IsRunning() { + return nil + } + + sub, err := c.EventBus.Subscribe(context.Background(), subscriber, q) + if err == nil { + return sub + } + + attempts++ + time.Sleep((10 << uint(attempts)) * time.Millisecond) // 10ms -> 20ms -> 40ms + } +} + +func (c *Local) Unsubscribe(ctx context.Context, subscriber, query string) error { + q, err := cmtquery.New(query) + if err != nil { + return fmt.Errorf("failed to parse query: %w", err) + } + return c.EventBus.Unsubscribe(ctx, subscriber, q) +} + +func (c *Local) UnsubscribeAll(ctx context.Context, subscriber string) error { + return c.EventBus.UnsubscribeAll(ctx, subscriber) +} diff --git a/rpc/client/main_test.go b/rpc/client/main_test.go new file mode 100644 index 0000000..636d800 --- /dev/null +++ b/rpc/client/main_test.go @@ -0,0 +1,32 @@ +package client_test + +import ( + "os" + "testing" + + "github.com/cometbft/cometbft/abci/example/kvstore" + nm "github.com/cometbft/cometbft/node" + rpctest "github.com/cometbft/cometbft/rpc/test" +) + +var node *nm.Node + +func TestMain(m *testing.M) { + // start a CometBFT node (and kvstore) in the background to test against + dir, err := os.MkdirTemp("/tmp", "rpc-client-test") + if err != nil { + panic(err) + } + + app := kvstore.NewPersistentApplication(dir) + // If testing block event generation + // app.SetGenBlockEvents() // needs to be called here (see TestBlockSearch in rpc_test.go) + node = rpctest.StartTendermint(app) + + code := m.Run() + + // and shut down proper at the end + rpctest.StopTendermint(node) + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/rpc/client/mock/client.go b/rpc/client/mock/client.go new file mode 100644 index 0000000..1aca785 --- /dev/null +++ b/rpc/client/mock/client.go @@ -0,0 +1,183 @@ +package mock + +/* +package mock returns a Client implementation that +accepts various (mock) implementations of the various methods. + +This implementation is useful for using in tests, when you don't +need a real server, but want a high-level of control about +the server response you want to mock (eg. error handling), +or if you just want to record the calls to verify in your tests. + +For real clients, you probably want the "http" package. If you +want to directly call a CometBFT node in process, you can use the +"local" package. +*/ + +import ( + "context" + "reflect" + + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/rpc/client" + "github.com/cometbft/cometbft/rpc/core" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +// Client wraps arbitrary implementations of the various interfaces. +type Client struct { + client.ABCIClient + client.SignClient + client.HistoryClient + client.StatusClient + client.EventsClient + client.EvidenceClient + client.MempoolClient + service.Service + + env *core.Environment +} + +func New() Client { + return Client{ + env: &core.Environment{}, + } +} + +var _ client.Client = Client{} + +// Call is used by recorders to save a call and response. +// It can also be used to configure mock responses. +type Call struct { + Name string + Args interface{} + Response interface{} + Error error +} + +// GetResponse will generate the apporiate response for us, when +// using the Call struct to configure a Mock handler. +// +// When configuring a response, if only one of Response or Error is +// set then that will always be returned. If both are set, then +// we return Response if the Args match the set args, Error otherwise. +func (c Call) GetResponse(args interface{}) (interface{}, error) { + // handle the case with no response + if c.Response == nil { + if c.Error == nil { + panic("Misconfigured call, you must set either Response or Error") + } + return nil, c.Error + } + // response without error + if c.Error == nil { + return c.Response, nil + } + // have both, we must check args.... + if reflect.DeepEqual(args, c.Args) { + return c.Response, nil + } + return nil, c.Error +} + +func (c Client) Status(context.Context) (*ctypes.ResultStatus, error) { + return c.env.Status(&rpctypes.Context{}) +} + +func (c Client) ABCIInfo(context.Context) (*ctypes.ResultABCIInfo, error) { + return c.env.ABCIInfo(&rpctypes.Context{}) +} + +func (c Client) ABCIQuery(ctx context.Context, path string, data bytes.HexBytes) (*ctypes.ResultABCIQuery, error) { + return c.ABCIQueryWithOptions(ctx, path, data, client.DefaultABCIQueryOptions) +} + +func (c Client) ABCIQueryWithOptions( + _ context.Context, + path string, + data bytes.HexBytes, + opts client.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { + return c.env.ABCIQuery(&rpctypes.Context{}, path, data, opts.Height, opts.Prove) +} + +func (c Client) BroadcastTxCommit(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { + return c.env.BroadcastTxCommit(&rpctypes.Context{}, tx) +} + +func (c Client) BroadcastTxAsync(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.env.BroadcastTxAsync(&rpctypes.Context{}, tx) +} + +func (c Client) BroadcastTxSync(_ context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + return c.env.BroadcastTxSync(&rpctypes.Context{}, tx) +} + +func (c Client) CheckTx(_ context.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) { + return c.env.CheckTx(&rpctypes.Context{}, tx) +} + +func (c Client) NetInfo(_ context.Context) (*ctypes.ResultNetInfo, error) { + return c.env.NetInfo(&rpctypes.Context{}) +} + +func (c Client) ConsensusState(_ context.Context) (*ctypes.ResultConsensusState, error) { + return c.env.GetConsensusState(&rpctypes.Context{}) +} + +func (c Client) DumpConsensusState(_ context.Context) (*ctypes.ResultDumpConsensusState, error) { + return c.env.DumpConsensusState(&rpctypes.Context{}) +} + +func (c Client) ConsensusParams(_ context.Context, height *int64) (*ctypes.ResultConsensusParams, error) { + return c.env.ConsensusParams(&rpctypes.Context{}, height) +} + +func (c Client) Health(_ context.Context) (*ctypes.ResultHealth, error) { + return c.env.Health(&rpctypes.Context{}) +} + +func (c Client) DialSeeds(_ context.Context, seeds []string) (*ctypes.ResultDialSeeds, error) { + return c.env.UnsafeDialSeeds(&rpctypes.Context{}, seeds) +} + +func (c Client) DialPeers( + _ context.Context, + peers []string, + persistent, + unconditional, + private bool, +) (*ctypes.ResultDialPeers, error) { + return c.env.UnsafeDialPeers(&rpctypes.Context{}, peers, persistent, unconditional, private) +} + +func (c Client) BlockchainInfo(_ context.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) { + return c.env.BlockchainInfo(&rpctypes.Context{}, minHeight, maxHeight) +} + +func (c Client) Genesis(context.Context) (*ctypes.ResultGenesis, error) { + return c.env.Genesis(&rpctypes.Context{}) +} + +func (c Client) Block(_ context.Context, height *int64) (*ctypes.ResultBlock, error) { + return c.env.Block(&rpctypes.Context{}, height) +} + +func (c Client) BlockByHash(_ context.Context, hash []byte) (*ctypes.ResultBlock, error) { + return c.env.BlockByHash(&rpctypes.Context{}, hash) +} + +func (c Client) Commit(_ context.Context, height *int64) (*ctypes.ResultCommit, error) { + return c.env.Commit(&rpctypes.Context{}, height) +} + +func (c Client) Validators(_ context.Context, height *int64, page, perPage *int) (*ctypes.ResultValidators, error) { + return c.env.Validators(&rpctypes.Context{}, height, page, perPage) +} + +func (c Client) BroadcastEvidence(_ context.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { + return c.env.BroadcastEvidence(&rpctypes.Context{}, ev) +} diff --git a/rpc/client/mock/status.go b/rpc/client/mock/status.go new file mode 100644 index 0000000..95fdcc3 --- /dev/null +++ b/rpc/client/mock/status.go @@ -0,0 +1,54 @@ +package mock + +import ( + "context" + + "github.com/cometbft/cometbft/rpc/client" + ctypes "github.com/cometbft/cometbft/rpc/core/types" +) + +// StatusMock returns the result specified by the Call +type StatusMock struct { + Call +} + +var ( + _ client.StatusClient = (*StatusMock)(nil) + _ client.StatusClient = (*StatusRecorder)(nil) +) + +func (m *StatusMock) Status(context.Context) (*ctypes.ResultStatus, error) { + res, err := m.GetResponse(nil) + if err != nil { + return nil, err + } + return res.(*ctypes.ResultStatus), nil +} + +// StatusRecorder can wrap another type (StatusMock, full client) +// and record the status calls +type StatusRecorder struct { + Client client.StatusClient + Calls []Call +} + +func NewStatusRecorder(client client.StatusClient) *StatusRecorder { + return &StatusRecorder{ + Client: client, + Calls: []Call{}, + } +} + +func (r *StatusRecorder) addCall(call Call) { + r.Calls = append(r.Calls, call) +} + +func (r *StatusRecorder) Status(ctx context.Context) (*ctypes.ResultStatus, error) { + res, err := r.Client.Status(ctx) + r.addCall(Call{ + Name: "status", + Response: res, + Error: err, + }) + return res, err +} diff --git a/rpc/client/mock/status_test.go b/rpc/client/mock/status_test.go new file mode 100644 index 0000000..9ee3cf6 --- /dev/null +++ b/rpc/client/mock/status_test.go @@ -0,0 +1,49 @@ +package mock_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/rpc/client/mock" + ctypes "github.com/cometbft/cometbft/rpc/core/types" +) + +func TestStatus(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + m := &mock.StatusMock{ + Call: mock.Call{ + Response: &ctypes.ResultStatus{ + SyncInfo: ctypes.SyncInfo{ + LatestBlockHash: bytes.HexBytes("block"), + LatestAppHash: bytes.HexBytes("app"), + LatestBlockHeight: 10, + }, + }}, + } + + r := mock.NewStatusRecorder(m) + require.Equal(0, len(r.Calls)) + + // make sure response works proper + status, err := r.Status(context.Background()) + require.Nil(err, "%+v", err) + assert.EqualValues("block", status.SyncInfo.LatestBlockHash) + assert.EqualValues(10, status.SyncInfo.LatestBlockHeight) + + // make sure recorder works properly + require.Equal(1, len(r.Calls)) + rs := r.Calls[0] + assert.Equal("status", rs.Name) + assert.Nil(rs.Args) + assert.Nil(rs.Error) + require.NotNil(rs.Response) + st, ok := rs.Response.(*ctypes.ResultStatus) + require.True(ok) + assert.EqualValues("block", st.SyncInfo.LatestBlockHash) + assert.EqualValues(10, st.SyncInfo.LatestBlockHeight) +} diff --git a/rpc/client/mocks/client.go b/rpc/client/mocks/client.go new file mode 100644 index 0000000..1b99ee9 --- /dev/null +++ b/rpc/client/mocks/client.go @@ -0,0 +1,872 @@ +// Code generated by mockery 2.7.4. DO NOT EDIT. + +package mocks + +import ( + bytes "github.com/cometbft/cometbft/libs/bytes" + client "github.com/cometbft/cometbft/rpc/client" + + context "context" + + coretypes "github.com/cometbft/cometbft/rpc/core/types" + + log "github.com/cometbft/cometbft/libs/log" + + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/types" +) + +// Client is an autogenerated mock type for the Client type +type Client struct { + mock.Mock +} + +// ABCIInfo provides a mock function with given fields: _a0 +func (_m *Client) ABCIInfo(_a0 context.Context) (*coretypes.ResultABCIInfo, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultABCIInfo + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultABCIInfo); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultABCIInfo) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ABCIQuery provides a mock function with given fields: ctx, path, data +func (_m *Client) ABCIQuery(ctx context.Context, path string, data bytes.HexBytes) (*coretypes.ResultABCIQuery, error) { + ret := _m.Called(ctx, path, data) + + var r0 *coretypes.ResultABCIQuery + if rf, ok := ret.Get(0).(func(context.Context, string, bytes.HexBytes) *coretypes.ResultABCIQuery); ok { + r0 = rf(ctx, path, data) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultABCIQuery) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, string, bytes.HexBytes) error); ok { + r1 = rf(ctx, path, data) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ABCIQueryWithOptions provides a mock function with given fields: ctx, path, data, opts +func (_m *Client) ABCIQueryWithOptions(ctx context.Context, path string, data bytes.HexBytes, opts client.ABCIQueryOptions) (*coretypes.ResultABCIQuery, error) { + ret := _m.Called(ctx, path, data, opts) + + var r0 *coretypes.ResultABCIQuery + if rf, ok := ret.Get(0).(func(context.Context, string, bytes.HexBytes, client.ABCIQueryOptions) *coretypes.ResultABCIQuery); ok { + r0 = rf(ctx, path, data, opts) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultABCIQuery) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, string, bytes.HexBytes, client.ABCIQueryOptions) error); ok { + r1 = rf(ctx, path, data, opts) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Block provides a mock function with given fields: ctx, height +func (_m *Client) Block(ctx context.Context, height *int64) (*coretypes.ResultBlock, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultBlock + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultBlock); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBlock) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BlockByHash provides a mock function with given fields: ctx, hash +func (_m *Client) BlockByHash(ctx context.Context, hash []byte) (*coretypes.ResultBlock, error) { + ret := _m.Called(ctx, hash) + + var r0 *coretypes.ResultBlock + if rf, ok := ret.Get(0).(func(context.Context, []byte) *coretypes.ResultBlock); ok { + r0 = rf(ctx, hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBlock) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, []byte) error); ok { + r1 = rf(ctx, hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BlockResults provides a mock function with given fields: ctx, height +func (_m *Client) BlockResults(ctx context.Context, height *int64) (*coretypes.ResultBlockResults, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultBlockResults + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultBlockResults); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBlockResults) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BlockSearch provides a mock function with given fields: ctx, query, page, perPage, orderBy +func (_m *Client) BlockSearch(ctx context.Context, query string, page *int, perPage *int, orderBy string) (*coretypes.ResultBlockSearch, error) { + ret := _m.Called(ctx, query, page, perPage, orderBy) + + var r0 *coretypes.ResultBlockSearch + if rf, ok := ret.Get(0).(func(context.Context, string, *int, *int, string) *coretypes.ResultBlockSearch); ok { + r0 = rf(ctx, query, page, perPage, orderBy) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBlockSearch) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, string, *int, *int, string) error); ok { + r1 = rf(ctx, query, page, perPage, orderBy) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BlockchainInfo provides a mock function with given fields: ctx, minHeight, maxHeight +func (_m *Client) BlockchainInfo(ctx context.Context, minHeight int64, maxHeight int64) (*coretypes.ResultBlockchainInfo, error) { + ret := _m.Called(ctx, minHeight, maxHeight) + + var r0 *coretypes.ResultBlockchainInfo + if rf, ok := ret.Get(0).(func(context.Context, int64, int64) *coretypes.ResultBlockchainInfo); ok { + r0 = rf(ctx, minHeight, maxHeight) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBlockchainInfo) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, int64, int64) error); ok { + r1 = rf(ctx, minHeight, maxHeight) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BroadcastEvidence provides a mock function with given fields: _a0, _a1 +func (_m *Client) BroadcastEvidence(_a0 context.Context, _a1 types.Evidence) (*coretypes.ResultBroadcastEvidence, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultBroadcastEvidence + if rf, ok := ret.Get(0).(func(context.Context, types.Evidence) *coretypes.ResultBroadcastEvidence); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBroadcastEvidence) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, types.Evidence) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BroadcastTxAsync provides a mock function with given fields: _a0, _a1 +func (_m *Client) BroadcastTxAsync(_a0 context.Context, _a1 types.Tx) (*coretypes.ResultBroadcastTx, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultBroadcastTx + if rf, ok := ret.Get(0).(func(context.Context, types.Tx) *coretypes.ResultBroadcastTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBroadcastTx) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, types.Tx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BroadcastTxCommit provides a mock function with given fields: _a0, _a1 +func (_m *Client) BroadcastTxCommit(_a0 context.Context, _a1 types.Tx) (*coretypes.ResultBroadcastTxCommit, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultBroadcastTxCommit + if rf, ok := ret.Get(0).(func(context.Context, types.Tx) *coretypes.ResultBroadcastTxCommit); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBroadcastTxCommit) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, types.Tx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BroadcastTxSync provides a mock function with given fields: _a0, _a1 +func (_m *Client) BroadcastTxSync(_a0 context.Context, _a1 types.Tx) (*coretypes.ResultBroadcastTx, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultBroadcastTx + if rf, ok := ret.Get(0).(func(context.Context, types.Tx) *coretypes.ResultBroadcastTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultBroadcastTx) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, types.Tx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckTx provides a mock function with given fields: _a0, _a1 +func (_m *Client) CheckTx(_a0 context.Context, _a1 types.Tx) (*coretypes.ResultCheckTx, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultCheckTx + if rf, ok := ret.Get(0).(func(context.Context, types.Tx) *coretypes.ResultCheckTx); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultCheckTx) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, types.Tx) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Commit provides a mock function with given fields: ctx, height +func (_m *Client) Commit(ctx context.Context, height *int64) (*coretypes.ResultCommit, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultCommit + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultCommit); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultCommit) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ConsensusParams provides a mock function with given fields: ctx, height +func (_m *Client) ConsensusParams(ctx context.Context, height *int64) (*coretypes.ResultConsensusParams, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultConsensusParams + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultConsensusParams); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultConsensusParams) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ConsensusState provides a mock function with given fields: _a0 +func (_m *Client) ConsensusState(_a0 context.Context) (*coretypes.ResultConsensusState, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultConsensusState + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultConsensusState); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultConsensusState) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// DumpConsensusState provides a mock function with given fields: _a0 +func (_m *Client) DumpConsensusState(_a0 context.Context) (*coretypes.ResultDumpConsensusState, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultDumpConsensusState + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultDumpConsensusState); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultDumpConsensusState) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Genesis provides a mock function with given fields: _a0 +func (_m *Client) Genesis(_a0 context.Context) (*coretypes.ResultGenesis, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultGenesis + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultGenesis); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultGenesis) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GenesisChunked provides a mock function with given fields: _a0, _a1 +func (_m *Client) GenesisChunked(_a0 context.Context, _a1 uint) (*coretypes.ResultGenesisChunk, error) { + ret := _m.Called(_a0, _a1) + + var r0 *coretypes.ResultGenesisChunk + if rf, ok := ret.Get(0).(func(context.Context, uint) *coretypes.ResultGenesisChunk); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultGenesisChunk) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, uint) error); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Header provides a mock function with given fields: ctx, height +func (_m *Client) Header(ctx context.Context, height *int64) (*coretypes.ResultHeader, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultHeader + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultHeader); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultHeader) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// HeaderByHash provides a mock function with given fields: ctx, hash +func (_m *Client) HeaderByHash(ctx context.Context, hash bytes.HexBytes) (*coretypes.ResultHeader, error) { + ret := _m.Called(ctx, hash) + + var r0 *coretypes.ResultHeader + if rf, ok := ret.Get(0).(func(context.Context, bytes.HexBytes) *coretypes.ResultHeader); ok { + r0 = rf(ctx, hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultHeader) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, bytes.HexBytes) error); ok { + r1 = rf(ctx, hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Health provides a mock function with given fields: _a0 +func (_m *Client) Health(_a0 context.Context) (*coretypes.ResultHealth, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultHealth + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultHealth); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultHealth) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// IsRunning provides a mock function with given fields: +func (_m *Client) IsRunning() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// NetInfo provides a mock function with given fields: _a0 +func (_m *Client) NetInfo(_a0 context.Context) (*coretypes.ResultNetInfo, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultNetInfo + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultNetInfo); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultNetInfo) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NumUnconfirmedTxs provides a mock function with given fields: _a0 +func (_m *Client) NumUnconfirmedTxs(_a0 context.Context) (*coretypes.ResultUnconfirmedTxs, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultUnconfirmedTxs + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultUnconfirmedTxs); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultUnconfirmedTxs) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OnReset provides a mock function with given fields: +func (_m *Client) OnReset() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStart provides a mock function with given fields: +func (_m *Client) OnStart() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OnStop provides a mock function with given fields: +func (_m *Client) OnStop() { + _m.Called() +} + +// Quit provides a mock function with given fields: +func (_m *Client) Quit() <-chan struct{} { + ret := _m.Called() + + var r0 <-chan struct{} + if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan struct{}) + } + } + + return r0 +} + +// Reset provides a mock function with given fields: +func (_m *Client) Reset() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SetLogger provides a mock function with given fields: _a0 +func (_m *Client) SetLogger(_a0 log.Logger) { + _m.Called(_a0) +} + +// Start provides a mock function with given fields: +func (_m *Client) Start() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Status provides a mock function with given fields: _a0 +func (_m *Client) Status(_a0 context.Context) (*coretypes.ResultStatus, error) { + ret := _m.Called(_a0) + + var r0 *coretypes.ResultStatus + if rf, ok := ret.Get(0).(func(context.Context) *coretypes.ResultStatus); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultStatus) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Stop provides a mock function with given fields: +func (_m *Client) Stop() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// String provides a mock function with given fields: +func (_m *Client) String() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Subscribe provides a mock function with given fields: ctx, subscriber, query, outCapacity +func (_m *Client) Subscribe(ctx context.Context, subscriber string, query string, outCapacity ...int) (<-chan coretypes.ResultEvent, error) { + _va := make([]interface{}, len(outCapacity)) + for _i := range outCapacity { + _va[_i] = outCapacity[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, subscriber, query) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 <-chan coretypes.ResultEvent + if rf, ok := ret.Get(0).(func(context.Context, string, string, ...int) <-chan coretypes.ResultEvent); ok { + r0 = rf(ctx, subscriber, query, outCapacity...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan coretypes.ResultEvent) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, string, string, ...int) error); ok { + r1 = rf(ctx, subscriber, query, outCapacity...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Tx provides a mock function with given fields: ctx, hash, prove +func (_m *Client) Tx(ctx context.Context, hash []byte, prove bool) (*coretypes.ResultTx, error) { + ret := _m.Called(ctx, hash, prove) + + var r0 *coretypes.ResultTx + if rf, ok := ret.Get(0).(func(context.Context, []byte, bool) *coretypes.ResultTx); ok { + r0 = rf(ctx, hash, prove) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultTx) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, []byte, bool) error); ok { + r1 = rf(ctx, hash, prove) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// TxSearch provides a mock function with given fields: ctx, query, prove, page, perPage, orderBy +func (_m *Client) TxSearch(ctx context.Context, query string, prove bool, page *int, perPage *int, orderBy string) (*coretypes.ResultTxSearch, error) { + ret := _m.Called(ctx, query, prove, page, perPage, orderBy) + + var r0 *coretypes.ResultTxSearch + if rf, ok := ret.Get(0).(func(context.Context, string, bool, *int, *int, string) *coretypes.ResultTxSearch); ok { + r0 = rf(ctx, query, prove, page, perPage, orderBy) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultTxSearch) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, string, bool, *int, *int, string) error); ok { + r1 = rf(ctx, query, prove, page, perPage, orderBy) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// UnconfirmedTxs provides a mock function with given fields: ctx, limit +func (_m *Client) UnconfirmedTxs(ctx context.Context, limit *int) (*coretypes.ResultUnconfirmedTxs, error) { + ret := _m.Called(ctx, limit) + + var r0 *coretypes.ResultUnconfirmedTxs + if rf, ok := ret.Get(0).(func(context.Context, *int) *coretypes.ResultUnconfirmedTxs); ok { + r0 = rf(ctx, limit) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultUnconfirmedTxs) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int) error); ok { + r1 = rf(ctx, limit) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Unsubscribe provides a mock function with given fields: ctx, subscriber, query +func (_m *Client) Unsubscribe(ctx context.Context, subscriber string, query string) error { + ret := _m.Called(ctx, subscriber, query) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string, string) error); ok { + r0 = rf(ctx, subscriber, query) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UnsubscribeAll provides a mock function with given fields: ctx, subscriber +func (_m *Client) UnsubscribeAll(ctx context.Context, subscriber string) error { + ret := _m.Called(ctx, subscriber) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { + r0 = rf(ctx, subscriber) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Validators provides a mock function with given fields: ctx, height, page, perPage +func (_m *Client) Validators(ctx context.Context, height *int64, page *int, perPage *int) (*coretypes.ResultValidators, error) { + ret := _m.Called(ctx, height, page, perPage) + + var r0 *coretypes.ResultValidators + if rf, ok := ret.Get(0).(func(context.Context, *int64, *int, *int) *coretypes.ResultValidators); ok { + r0 = rf(ctx, height, page, perPage) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultValidators) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64, *int, *int) error); ok { + r1 = rf(ctx, height, page, perPage) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go new file mode 100644 index 0000000..6551189 --- /dev/null +++ b/rpc/client/rpc_test.go @@ -0,0 +1,764 @@ +package client_test + +import ( + "context" + "encoding/base64" + "fmt" + "math" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + cmtmath "github.com/cometbft/cometbft/libs/math" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + rpclocal "github.com/cometbft/cometbft/rpc/client/local" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + rpctest "github.com/cometbft/cometbft/rpc/test" + "github.com/cometbft/cometbft/types" +) + +var ( + ctx = context.Background() +) + +func getHTTPClient() *rpchttp.HTTP { + rpcAddr := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.New(rpcAddr, "/websocket") + if err != nil { + panic(err) + } + c.SetLogger(log.TestingLogger()) + return c +} + +func getHTTPClientWithTimeout(timeout uint) *rpchttp.HTTP { + rpcAddr := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.NewWithTimeout(rpcAddr, "/websocket", timeout) + if err != nil { + panic(err) + } + c.SetLogger(log.TestingLogger()) + return c +} + +func getLocalClient() *rpclocal.Local { + return rpclocal.New(node) +} + +// GetClients returns a slice of clients for table-driven tests +func GetClients() []client.Client { + return []client.Client{ + getHTTPClient(), + getLocalClient(), + } +} + +func TestNilCustomHTTPClient(t *testing.T) { + require.Panics(t, func() { + _, _ = rpchttp.NewWithClient("http://example.com", "/websocket", nil) + }) + require.Panics(t, func() { + _, _ = rpcclient.NewWithHTTPClient("http://example.com", nil) + }) +} + +func TestCustomHTTPClient(t *testing.T) { + remote := rpctest.GetConfig().RPC.ListenAddress + c, err := rpchttp.NewWithClient(remote, "/websocket", http.DefaultClient) + require.Nil(t, err) + status, err := c.Status(context.Background()) + require.NoError(t, err) + require.NotNil(t, status) +} + +func TestCorsEnabled(t *testing.T) { + origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0] + remote := strings.ReplaceAll(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http") + + req, err := http.NewRequest("GET", remote, nil) + require.Nil(t, err, "%+v", err) + req.Header.Set("Origin", origin) + c := &http.Client{} + resp, err := c.Do(req) + require.Nil(t, err, "%+v", err) + defer resp.Body.Close() + + assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin) +} + +// Make sure status is correct (we connect properly) +func TestStatus(t *testing.T) { + for i, c := range GetClients() { + moniker := rpctest.GetConfig().Moniker + status, err := c.Status(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + assert.Equal(t, moniker, status.NodeInfo.Moniker) + } +} + +// Make sure info is correct (we connect properly) +func TestInfo(t *testing.T) { + for i, c := range GetClients() { + // status, err := c.Status() + // require.Nil(t, err, "%+v", err) + info, err := c.ABCIInfo(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + // TODO: this is not correct - fix merkleeyes! + // assert.EqualValues(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight) + assert.True(t, strings.Contains(info.Response.Data, "size")) + } +} + +func TestNetInfo(t *testing.T) { + for i, c := range GetClients() { + nc, ok := c.(client.NetworkClient) + require.True(t, ok, "%d", i) + netinfo, err := nc.NetInfo(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + assert.True(t, netinfo.Listening) + assert.Equal(t, 0, len(netinfo.Peers)) + } +} + +func TestDumpConsensusState(t *testing.T) { + for i, c := range GetClients() { + // FIXME: fix server so it doesn't panic on invalid input + nc, ok := c.(client.NetworkClient) + require.True(t, ok, "%d", i) + cons, err := nc.DumpConsensusState(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + assert.NotEmpty(t, cons.RoundState) + assert.Empty(t, cons.Peers) + } +} + +func TestConsensusState(t *testing.T) { + for i, c := range GetClients() { + // FIXME: fix server so it doesn't panic on invalid input + nc, ok := c.(client.NetworkClient) + require.True(t, ok, "%d", i) + cons, err := nc.ConsensusState(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + assert.NotEmpty(t, cons.RoundState) + } +} + +func TestHealth(t *testing.T) { + for i, c := range GetClients() { + nc, ok := c.(client.NetworkClient) + require.True(t, ok, "%d", i) + _, err := nc.Health(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + } +} + +func TestGenesisAndValidators(t *testing.T) { + for i, c := range GetClients() { + + // make sure this is the right genesis file + gen, err := c.Genesis(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + // get the genesis validator + require.Equal(t, 1, len(gen.Genesis.Validators)) + gval := gen.Genesis.Validators[0] + + // get the current validators + h := int64(1) + vals, err := c.Validators(context.Background(), &h, nil, nil) + require.Nil(t, err, "%d: %+v", i, err) + require.Equal(t, 1, len(vals.Validators)) + require.Equal(t, 1, vals.Count) + require.Equal(t, 1, vals.Total) + val := vals.Validators[0] + + // make sure the current set is also the genesis set + assert.Equal(t, gval.Power, val.VotingPower) + assert.Equal(t, gval.PubKey, val.PubKey) + } +} + +func TestGenesisChunked(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + for _, c := range GetClients() { + first, err := c.GenesisChunked(ctx, 0) + require.NoError(t, err) + + decoded := make([]string, 0, first.TotalChunks) + for i := 0; i < first.TotalChunks; i++ { + chunk, err := c.GenesisChunked(ctx, uint(i)) + require.NoError(t, err) + data, err := base64.StdEncoding.DecodeString(chunk.Data) + require.NoError(t, err) + decoded = append(decoded, string(data)) + + } + doc := []byte(strings.Join(decoded, "")) + + var out types.GenesisDoc + require.NoError(t, cmtjson.Unmarshal(doc, &out), + "first: %+v, doc: %s", first, string(doc)) + } +} + +func TestABCIQuery(t *testing.T) { + for i, c := range GetClients() { + // write something + k, v, tx := MakeTxKV() + bres, err := c.BroadcastTxCommit(context.Background(), tx) + require.Nil(t, err, "%d: %+v", i, err) + apph := bres.Height + 1 // this is where the tx will be applied to the state + + // wait before querying + err = client.WaitForHeight(c, apph, nil) + require.NoError(t, err) + res, err := c.ABCIQuery(context.Background(), "/key", k) + qres := res.Response + if assert.Nil(t, err) && assert.True(t, qres.IsOK()) { + assert.EqualValues(t, v, qres.Value) + } + } +} + +// Make some app checks +func TestAppCalls(t *testing.T) { + assert, require := assert.New(t), require.New(t) + for i, c := range GetClients() { + + // get an offset of height to avoid racing and guessing + s, err := c.Status(context.Background()) + require.NoError(err) + // sh is start height or status height + sh := s.SyncInfo.LatestBlockHeight + + // look for the future + h := sh + 20 + _, err = c.Block(context.Background(), &h) + require.Error(err) // no block yet + + // write something + k, v, tx := MakeTxKV() + bres, err := c.BroadcastTxCommit(context.Background(), tx) + require.NoError(err) + require.True(bres.TxResult.IsOK()) + txh := bres.Height + apph := txh + 1 // this is where the tx will be applied to the state + + // wait before querying + err = client.WaitForHeight(c, apph, nil) + require.NoError(err) + + _qres, err := c.ABCIQueryWithOptions(context.Background(), "/key", k, client.ABCIQueryOptions{Prove: false}) + require.NoError(err) + qres := _qres.Response + if assert.True(qres.IsOK()) { + assert.Equal(k, qres.Key) + assert.EqualValues(v, qres.Value) + } + + // make sure we can lookup the tx with proof + ptx, err := c.Tx(context.Background(), bres.Hash, true) + require.NoError(err) + assert.EqualValues(txh, ptx.Height) + assert.EqualValues(tx, ptx.Tx) + + // and we can even check the block is added + block, err := c.Block(context.Background(), &apph) + require.NoError(err) + appHash := block.Block.AppHash + assert.True(len(appHash) > 0) + assert.EqualValues(apph, block.Block.Height) + + blockByHash, err := c.BlockByHash(context.Background(), block.BlockID.Hash) + require.NoError(err) + require.Equal(block, blockByHash) + + // check that the header matches the block hash + header, err := c.Header(context.Background(), &apph) + require.NoError(err) + require.Equal(block.Block.Header, *header.Header) + + headerByHash, err := c.HeaderByHash(context.Background(), block.BlockID.Hash) + require.NoError(err) + require.Equal(header, headerByHash) + + // now check the results + blockResults, err := c.BlockResults(context.Background(), &txh) + require.Nil(err, "%d: %+v", i, err) + assert.Equal(txh, blockResults.Height) + if assert.Equal(1, len(blockResults.TxsResults)) { + // check success code + assert.EqualValues(0, blockResults.TxsResults[0].Code) + } + + // check blockchain info, now that we know there is info + info, err := c.BlockchainInfo(context.Background(), apph, apph) + require.NoError(err) + assert.True(info.LastHeight >= apph) + if assert.Equal(1, len(info.BlockMetas)) { + lastMeta := info.BlockMetas[0] + assert.EqualValues(apph, lastMeta.Header.Height) + blockData := block.Block + assert.Equal(blockData.AppHash, lastMeta.Header.AppHash) + assert.Equal(block.BlockID, lastMeta.BlockID) + } + + // and get the corresponding commit with the same apphash + commit, err := c.Commit(context.Background(), &apph) + require.NoError(err) + cappHash := commit.AppHash + assert.Equal(appHash, cappHash) + assert.NotNil(commit.Commit) + + // compare the commits (note Commit(2) has commit from Block(3)) + h = apph - 1 + commit2, err := c.Commit(context.Background(), &h) + require.NoError(err) + assert.Equal(block.Block.LastCommitHash, commit2.Commit.Hash()) + + // and we got a proof that works! + _pres, err := c.ABCIQueryWithOptions(context.Background(), "/key", k, client.ABCIQueryOptions{Prove: true}) + require.NoError(err) + pres := _pres.Response + assert.True(pres.IsOK()) + + // XXX Test proof + } +} + +func TestBroadcastTxSync(t *testing.T) { + require := require.New(t) + + // TODO (melekes): use mempool which is set on RPC rather than getting it from node + mempool := node.Mempool() + initMempoolSize := mempool.Size() + + for i, c := range GetClients() { + _, _, tx := MakeTxKV() + bres, err := c.BroadcastTxSync(context.Background(), tx) + require.Nil(err, "%d: %+v", i, err) + require.Equal(bres.Code, abci.CodeTypeOK) // FIXME + + require.Equal(initMempoolSize+1, mempool.Size()) + + txs := mempool.ReapMaxTxs(len(tx)) + require.EqualValues(tx, txs[0]) + mempool.Flush() + } +} + +func TestBroadcastTxCommit(t *testing.T) { + require := require.New(t) + + mempool := node.Mempool() + for i, c := range GetClients() { + _, _, tx := MakeTxKV() + bres, err := c.BroadcastTxCommit(context.Background(), tx) + require.Nil(err, "%d: %+v", i, err) + require.True(bres.CheckTx.IsOK()) + require.True(bres.TxResult.IsOK()) + + require.Equal(0, mempool.Size()) + } +} + +func TestUnconfirmedTxs(t *testing.T) { + _, _, tx := MakeTxKV() + + ch := make(chan *abci.ResponseCheckTx, 1) + mempool := node.Mempool() + err := mempool.CheckTx(tx, func(resp *abci.ResponseCheckTx) { ch <- resp }, mempl.TxInfo{}) + require.NoError(t, err) + + // wait for tx to arrive in mempoool. + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Error("Timed out waiting for CheckTx callback") + } + + for _, c := range GetClients() { + mc := c.(client.MempoolClient) + limit := 1 + res, err := mc.UnconfirmedTxs(context.Background(), &limit) + require.NoError(t, err) + + assert.Equal(t, 1, res.Count) + assert.Equal(t, 1, res.Total) + assert.Equal(t, mempool.SizeBytes(), res.TotalBytes) + assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs)) + } + + mempool.Flush() +} + +func TestNumUnconfirmedTxs(t *testing.T) { + _, _, tx := MakeTxKV() + + ch := make(chan *abci.ResponseCheckTx, 1) + mempool := node.Mempool() + err := mempool.CheckTx(tx, func(resp *abci.ResponseCheckTx) { ch <- resp }, mempl.TxInfo{}) + require.NoError(t, err) + + // wait for tx to arrive in mempoool. + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Error("Timed out waiting for CheckTx callback") + } + + mempoolSize := mempool.Size() + for i, c := range GetClients() { + mc, ok := c.(client.MempoolClient) + require.True(t, ok, "%d", i) + res, err := mc.NumUnconfirmedTxs(context.Background()) + require.Nil(t, err, "%d: %+v", i, err) + + assert.Equal(t, mempoolSize, res.Count) + assert.Equal(t, mempoolSize, res.Total) + assert.Equal(t, mempool.SizeBytes(), res.TotalBytes) + } + + mempool.Flush() +} + +func TestCheckTx(t *testing.T) { + mempool := node.Mempool() + + for _, c := range GetClients() { + _, _, tx := MakeTxKV() + + res, err := c.CheckTx(context.Background(), tx) + require.NoError(t, err) + assert.Equal(t, abci.CodeTypeOK, res.Code) + + assert.Equal(t, 0, mempool.Size(), "mempool must be empty") + } +} + +func TestTx(t *testing.T) { + // first we broadcast a tx + c := getHTTPClient() + _, _, tx := MakeTxKV() + bres, err := c.BroadcastTxCommit(context.Background(), tx) + require.Nil(t, err, "%+v", err) + + txHeight := bres.Height + txHash := bres.Hash + + anotherTxHash := types.Tx("a different tx").Hash() + + cases := []struct { + valid bool + prove bool + hash []byte + }{ + // only valid if correct hash provided + {true, false, txHash}, + {true, true, txHash}, + {false, false, anotherTxHash}, + {false, true, anotherTxHash}, + {false, false, nil}, + {false, true, nil}, + } + + for i, c := range GetClients() { + for j, tc := range cases { + t.Logf("client %d, case %d", i, j) + + // now we query for the tx. + // since there's only one tx, we know index=0. + ptx, err := c.Tx(context.Background(), tc.hash, tc.prove) + + if !tc.valid { + require.NotNil(t, err) + } else { + require.Nil(t, err, "%+v", err) + assert.EqualValues(t, txHeight, ptx.Height) + assert.EqualValues(t, tx, ptx.Tx) + assert.Zero(t, ptx.Index) + assert.True(t, ptx.TxResult.IsOK()) + assert.EqualValues(t, txHash, ptx.Hash) + + // time to verify the proof + proof := ptx.Proof + if tc.prove && assert.EqualValues(t, tx, proof.Data) { + assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash)) + } + } + } + } +} + +func TestTxSearchWithTimeout(t *testing.T) { + // Get a client with a time-out of 10 secs. + timeoutClient := getHTTPClientWithTimeout(10) + + _, _, tx := MakeTxKV() + _, err := timeoutClient.BroadcastTxCommit(context.Background(), tx) + require.NoError(t, err) + + // query using a compositeKey (see kvstore application) + result, err := timeoutClient.TxSearch(context.Background(), "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc") + require.Nil(t, err) + require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") +} + +// This test does nothing if we do not call app.SetGenBlockEvents() within main_test.go +// It will nevertheless pass as there are no events being generated. +func TestBlockSearch(t *testing.T) { + c := getHTTPClient() + + // first we broadcast a few txs + for i := 0; i < 10; i++ { + _, _, tx := MakeTxKV() + + _, err := c.BroadcastTxCommit(context.Background(), tx) + require.NoError(t, err) + } + require.NoError(t, client.WaitForHeight(c, 5, nil)) + result, err := c.BlockSearch(context.Background(), "begin_event.foo = 100", nil, nil, "asc") + require.NoError(t, err) + blockCount := len(result.Blocks) + // if we generate block events within the test (by uncommenting + // the code in line main_test.go:L23) then we expect len(result.Blocks) + // to be at least 5 + // require.GreaterOrEqual(t, blockCount, 5) + + // otherwise it is 0 + require.Equal(t, blockCount, 0) + +} +func TestTxSearch(t *testing.T) { + c := getHTTPClient() + + // first we broadcast a few txs + for i := 0; i < 10; i++ { + _, _, tx := MakeTxKV() + _, err := c.BroadcastTxCommit(context.Background(), tx) + require.NoError(t, err) + } + + // since we're not using an isolated test server, we'll have lingering transactions + // from other tests as well + result, err := c.TxSearch(context.Background(), "tx.height >= 0", true, nil, nil, "asc") + require.NoError(t, err) + txCount := len(result.Txs) + + // pick out the last tx to have something to search for in tests + find := result.Txs[len(result.Txs)-1] + anotherTxHash := types.Tx("a different tx").Hash() + + for _, c := range GetClients() { + + // now we query for the tx. + result, err := c.TxSearch(context.Background(), fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc") + require.Nil(t, err) + require.Len(t, result.Txs, 1) + require.Equal(t, find.Hash, result.Txs[0].Hash) + + ptx := result.Txs[0] + assert.EqualValues(t, find.Height, ptx.Height) + assert.EqualValues(t, find.Tx, ptx.Tx) + assert.Zero(t, ptx.Index) + assert.True(t, ptx.TxResult.IsOK()) + assert.EqualValues(t, find.Hash, ptx.Hash) + + // time to verify the proof + if assert.EqualValues(t, find.Tx, ptx.Proof.Data) { + assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash)) + } + + // query by height + result, err = c.TxSearch(context.Background(), fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc") + require.Nil(t, err) + require.Len(t, result.Txs, 1) + + // query for non existing tx + result, err = c.TxSearch(context.Background(), fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc") + require.Nil(t, err) + require.Len(t, result.Txs, 0) + + // query using a compositeKey (see kvstore application) + result, err = c.TxSearch(context.Background(), "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc") + require.Nil(t, err) + require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") + + // query using an index key + result, err = c.TxSearch(context.Background(), "app.index_key='index is working'", false, nil, nil, "asc") + require.Nil(t, err) + require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") + + // query using an noindex key + result, err = c.TxSearch(context.Background(), "app.noindex_key='index is working'", false, nil, nil, "asc") + require.Nil(t, err) + require.Equal(t, len(result.Txs), 0, "expected a lot of transactions") + + // query using a compositeKey (see kvstore application) and height + result, err = c.TxSearch(context.Background(), + "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc") + require.Nil(t, err) + require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") + + // query a non existing tx with page 1 and txsPerPage 1 + perPage := 1 + result, err = c.TxSearch(context.Background(), "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc") + require.Nil(t, err) + require.Len(t, result.Txs, 0) + + // check sorting + result, err = c.TxSearch(context.Background(), "tx.height >= 1", false, nil, nil, "asc") + require.Nil(t, err) + for k := 0; k < len(result.Txs)-1; k++ { + require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) + require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index) + } + + result, err = c.TxSearch(context.Background(), "tx.height >= 1", false, nil, nil, "desc") + require.Nil(t, err) + for k := 0; k < len(result.Txs)-1; k++ { + require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) + require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index) + } + // check pagination + perPage = 3 + var ( + seen = map[int64]bool{} + maxHeight int64 + pages = int(math.Ceil(float64(txCount) / float64(perPage))) + ) + + totalTx := 0 + for page := 1; page <= pages; page++ { + page := page + result, err := c.TxSearch(context.Background(), "tx.height >= 1", true, &page, &perPage, "asc") + require.NoError(t, err) + if page < pages { + require.Len(t, result.Txs, perPage) + } else { + require.LessOrEqual(t, len(result.Txs), perPage) + } + totalTx = totalTx + len(result.Txs) + for _, tx := range result.Txs { + require.False(t, seen[tx.Height], + "Found duplicate height %v in page %v", tx.Height, page) + require.Greater(t, tx.Height, maxHeight, + "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page) + seen[tx.Height] = true + maxHeight = tx.Height + } + } + require.Equal(t, txCount, totalTx) + require.Len(t, seen, txCount) + } +} + +func TestBatchedJSONRPCCalls(t *testing.T) { + c := getHTTPClient() + testBatchedJSONRPCCalls(t, c) +} + +func testBatchedJSONRPCCalls(t *testing.T, c *rpchttp.HTTP) { + k1, v1, tx1 := MakeTxKV() + k2, v2, tx2 := MakeTxKV() + + batch := c.NewBatch() + r1, err := batch.BroadcastTxCommit(context.Background(), tx1) + require.NoError(t, err) + r2, err := batch.BroadcastTxCommit(context.Background(), tx2) + require.NoError(t, err) + require.Equal(t, 2, batch.Count()) + bresults, err := batch.Send(ctx) + require.NoError(t, err) + require.Len(t, bresults, 2) + require.Equal(t, 0, batch.Count()) + + bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit) + require.True(t, ok) + require.Equal(t, *bresult1, *r1) + bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit) + require.True(t, ok) + require.Equal(t, *bresult2, *r2) + apph := cmtmath.MaxInt64(bresult1.Height, bresult2.Height) + 1 + + err = client.WaitForHeight(c, apph, nil) + require.NoError(t, err) + + q1, err := batch.ABCIQuery(context.Background(), "/key", k1) + require.NoError(t, err) + q2, err := batch.ABCIQuery(context.Background(), "/key", k2) + require.NoError(t, err) + require.Equal(t, 2, batch.Count()) + qresults, err := batch.Send(ctx) + require.NoError(t, err) + require.Len(t, qresults, 2) + require.Equal(t, 0, batch.Count()) + + qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery) + require.True(t, ok) + require.Equal(t, *qresult1, *q1) + qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery) + require.True(t, ok) + require.Equal(t, *qresult2, *q2) + + require.Equal(t, qresult1.Response.Key, k1) + require.Equal(t, qresult2.Response.Key, k2) + require.Equal(t, qresult1.Response.Value, v1) + require.Equal(t, qresult2.Response.Value, v2) +} + +func TestBatchedJSONRPCCallsCancellation(t *testing.T) { + c := getHTTPClient() + _, _, tx1 := MakeTxKV() + _, _, tx2 := MakeTxKV() + + batch := c.NewBatch() + _, err := batch.BroadcastTxCommit(context.Background(), tx1) + require.NoError(t, err) + _, err = batch.BroadcastTxCommit(context.Background(), tx2) + require.NoError(t, err) + // we should have 2 requests waiting + require.Equal(t, 2, batch.Count()) + // we want to make sure we cleared 2 pending requests + require.Equal(t, 2, batch.Clear()) + // now there should be no batched requests + require.Equal(t, 0, batch.Count()) +} + +func TestSendingEmptyRequestBatch(t *testing.T) { + c := getHTTPClient() + batch := c.NewBatch() + _, err := batch.Send(ctx) + require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error") +} + +func TestClearingEmptyRequestBatch(t *testing.T) { + c := getHTTPClient() + batch := c.NewBatch() + require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result") +} + +func TestConcurrentJSONRPCBatching(t *testing.T) { + var wg sync.WaitGroup + c := getHTTPClient() + for i := 0; i < 50; i++ { + wg.Add(1) + go func() { + defer wg.Done() + testBatchedJSONRPCCalls(t, c) + }() + } + wg.Wait() +} diff --git a/rpc/client/types.go b/rpc/client/types.go new file mode 100644 index 0000000..aa21afc --- /dev/null +++ b/rpc/client/types.go @@ -0,0 +1,11 @@ +package client + +// ABCIQueryOptions can be used to provide options for ABCIQuery call other +// than the DefaultABCIQueryOptions. +type ABCIQueryOptions struct { + Height int64 + Prove bool +} + +// DefaultABCIQueryOptions are latest height (0) and prove false. +var DefaultABCIQueryOptions = ABCIQueryOptions{Height: 0, Prove: false} diff --git a/rpc/core/CONTRIBUTING.md b/rpc/core/CONTRIBUTING.md new file mode 100644 index 0000000..ab2aaae --- /dev/null +++ b/rpc/core/CONTRIBUTING.md @@ -0,0 +1,4 @@ +# Openapi docs + +Do not forget to update ../openapi/openapi.yaml if making changes to any +endpoint. diff --git a/rpc/core/README.md b/rpc/core/README.md new file mode 100644 index 0000000..f725135 --- /dev/null +++ b/rpc/core/README.md @@ -0,0 +1,18 @@ +# CometBFT RPC + +## Pagination + +Requests that return multiple items will be paginated to 30 items by default. +You can specify further pages with the ?page parameter. You can also set a +custom page size up to 100 with the ?per_page parameter. + +## Subscribing to events + +The user can subscribe to events emitted by CometBFT, using `/subscribe`. If +the maximum number of clients is reached or the client has too many +subscriptions, an error will be returned. The subscription timeout is 5 sec. +Each subscription has a buffer to accommodate short bursts of events or some +slowness in clients. If the buffer gets full, the subscription will be canceled +("client is not pulling messages fast enough"). If CometBFT exits, all +subscriptions are canceled ("CometBFT exited"). The user can unsubscribe +using either `/unsubscribe` or `/unsubscribe_all`. diff --git a/rpc/core/abci.go b/rpc/core/abci.go new file mode 100644 index 0000000..315b51e --- /dev/null +++ b/rpc/core/abci.go @@ -0,0 +1,44 @@ +package core + +import ( + "context" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/proxy" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// ABCIQuery queries the application for some information. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/ABCI/abci_query +func (env *Environment) ABCIQuery( + _ *rpctypes.Context, + path string, + data bytes.HexBytes, + height int64, + prove bool, +) (*ctypes.ResultABCIQuery, error) { + resQuery, err := env.ProxyAppQuery.Query(context.TODO(), &abci.RequestQuery{ + Path: path, + Data: data, + Height: height, + Prove: prove, + }) + if err != nil { + return nil, err + } + + return &ctypes.ResultABCIQuery{Response: *resQuery}, nil +} + +// ABCIInfo gets some info about the application. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/ABCI/abci_info +func (env *Environment) ABCIInfo(_ *rpctypes.Context) (*ctypes.ResultABCIInfo, error) { + resInfo, err := env.ProxyAppQuery.Info(context.TODO(), proxy.RequestInfo) + if err != nil { + return nil, err + } + + return &ctypes.ResultABCIInfo{Response: *resInfo}, nil +} diff --git a/rpc/core/blocks.go b/rpc/core/blocks.go new file mode 100644 index 0000000..bb77af6 --- /dev/null +++ b/rpc/core/blocks.go @@ -0,0 +1,268 @@ +package core + +import ( + "errors" + "fmt" + "sort" + + "github.com/cometbft/cometbft/libs/bytes" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + blockidxnull "github.com/cometbft/cometbft/state/indexer/block/null" + "github.com/cometbft/cometbft/types" +) + +// BlockchainInfo gets block headers for minHeight <= height <= maxHeight. +// +// If maxHeight does not yet exist, blocks up to the current height will be +// returned. If minHeight does not exist (due to pruning), earliest existing +// height will be used. +// +// At most 20 items will be returned. Block headers are returned in descending +// order (highest first). +// +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/blockchain +func (env *Environment) BlockchainInfo( + _ *rpctypes.Context, + minHeight, maxHeight int64, +) (*ctypes.ResultBlockchainInfo, error) { + const limit int64 = 20 + var err error + minHeight, maxHeight, err = filterMinMax( + env.BlockStore.Base(), + env.BlockStore.Height(), + minHeight, + maxHeight, + limit) + if err != nil { + return nil, err + } + env.Logger.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight) + + blockMetas := []*types.BlockMeta{} + for height := maxHeight; height >= minHeight; height-- { + blockMeta := env.BlockStore.LoadBlockMeta(height) + blockMetas = append(blockMetas, blockMeta) + } + + return &ctypes.ResultBlockchainInfo{ + LastHeight: env.BlockStore.Height(), + BlockMetas: blockMetas, + }, nil +} + +// error if either min or max are negative or min > max +// if 0, use blockstore base for min, latest block height for max +// enforce limit. +func filterMinMax(base, height, min, max, limit int64) (int64, int64, error) { + // filter negatives + if min < 0 || max < 0 { + return min, max, fmt.Errorf("heights must be non-negative") + } + + // adjust for default values + if min == 0 { + min = 1 + } + if max == 0 { + max = height + } + + // limit max to the height + max = cmtmath.MinInt64(height, max) + + // limit min to the base + min = cmtmath.MaxInt64(base, min) + + // limit min to within `limit` of max + // so the total number of blocks returned will be `limit` + min = cmtmath.MaxInt64(min, max-limit+1) + + if min > max { + return min, max, fmt.Errorf("min height %d can't be greater than max height %d", min, max) + } + return min, max, nil +} + +// Header gets block header at a given height. +// If no height is provided, it will fetch the latest header. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/header +func (env *Environment) Header(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultHeader, error) { + height, err := env.getHeight(env.BlockStore.Height(), heightPtr) + if err != nil { + return nil, err + } + + blockMeta := env.BlockStore.LoadBlockMeta(height) + if blockMeta == nil { + return &ctypes.ResultHeader{}, nil + } + + return &ctypes.ResultHeader{Header: &blockMeta.Header}, nil +} + +// HeaderByHash gets header by hash. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/header_by_hash +func (env *Environment) HeaderByHash(_ *rpctypes.Context, hash bytes.HexBytes) (*ctypes.ResultHeader, error) { + // N.B. The hash parameter is HexBytes so that the reflective parameter + // decoding logic in the HTTP service will correctly translate from JSON. + // See https://github.com/tendermint/tendermint/issues/6802 for context. + + blockMeta := env.BlockStore.LoadBlockMetaByHash(hash) + if blockMeta == nil { + return &ctypes.ResultHeader{}, nil + } + + return &ctypes.ResultHeader{Header: &blockMeta.Header}, nil +} + +// Block gets block at a given height. +// If no height is provided, it will fetch the latest block. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block +func (env *Environment) Block(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlock, error) { + height, err := env.getHeight(env.BlockStore.Height(), heightPtr) + if err != nil { + return nil, err + } + + block := env.BlockStore.LoadBlock(height) + blockMeta := env.BlockStore.LoadBlockMeta(height) + if blockMeta == nil { + return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: block}, nil + } + return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil +} + +// BlockByHash gets block by hash. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block_by_hash +func (env *Environment) BlockByHash(_ *rpctypes.Context, hash []byte) (*ctypes.ResultBlock, error) { + block := env.BlockStore.LoadBlockByHash(hash) + if block == nil { + return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil + } + // If block is not nil, then blockMeta can't be nil. + blockMeta := env.BlockStore.LoadBlockMeta(block.Height) + return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil +} + +// Commit gets block commit at a given height. +// If no height is provided, it will fetch the commit for the latest block. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/commit +func (env *Environment) Commit(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultCommit, error) { + height, err := env.getHeight(env.BlockStore.Height(), heightPtr) + if err != nil { + return nil, err + } + + blockMeta := env.BlockStore.LoadBlockMeta(height) + if blockMeta == nil { + return nil, nil + } + header := blockMeta.Header + + // If the next block has not been committed yet, + // use a non-canonical commit + if height == env.BlockStore.Height() { + commit := env.BlockStore.LoadSeenCommit(height) + return ctypes.NewResultCommit(&header, commit, false), nil + } + + // Return the canonical commit (comes from the block at height+1) + commit := env.BlockStore.LoadBlockCommit(height) + return ctypes.NewResultCommit(&header, commit, true), nil +} + +// BlockResults gets ABCIResults at a given height. +// If no height is provided, it will fetch results for the latest block. +// +// Results are for the height of the block containing the txs. +// Thus response.results.deliver_tx[5] is the results of executing +// getBlock(h).Txs[5] +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block_results +func (env *Environment) BlockResults(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlockResults, error) { + height, err := env.getHeight(env.BlockStore.Height(), heightPtr) + if err != nil { + return nil, err + } + + results, err := env.StateStore.LoadFinalizeBlockResponse(height) + if err != nil { + env.Logger.Error("failed to LoadFinalizeBlockResponse", "err", err) + return nil, err + } + + return &ctypes.ResultBlockResults{ + Height: height, + TxsResults: results.TxResults, + FinalizeBlockEvents: results.Events, + ValidatorUpdates: results.ValidatorUpdates, + ConsensusParamUpdates: results.ConsensusParamUpdates, + AppHash: results.AppHash, + }, nil +} + +// BlockSearch searches for a paginated set of blocks matching +// FinalizeBlock event search criteria. +func (env *Environment) BlockSearch( + ctx *rpctypes.Context, + query string, + pagePtr, perPagePtr *int, + orderBy string, +) (*ctypes.ResultBlockSearch, error) { + // skip if block indexing is disabled + if _, ok := env.BlockIndexer.(*blockidxnull.BlockerIndexer); ok { + return nil, errors.New("block indexing is disabled") + } + + q, err := cmtquery.New(query) + if err != nil { + return nil, err + } + + results, err := env.BlockIndexer.Search(ctx.Context(), q) + if err != nil { + return nil, err + } + + // sort results (must be done before pagination) + switch orderBy { + case "desc", "": + sort.Slice(results, func(i, j int) bool { return results[i] > results[j] }) + + case "asc": + sort.Slice(results, func(i, j int) bool { return results[i] < results[j] }) + + default: + return nil, errors.New("expected order_by to be either `asc` or `desc` or empty") + } + + // paginate results + totalCount := len(results) + perPage := env.validatePerPage(perPagePtr) + + page, err := validatePage(pagePtr, perPage, totalCount) + if err != nil { + return nil, err + } + + skipCount := validateSkipCount(page, perPage) + pageSize := cmtmath.MinInt(perPage, totalCount-skipCount) + + apiResults := make([]*ctypes.ResultBlock, 0, pageSize) + for i := skipCount; i < skipCount+pageSize; i++ { + block := env.BlockStore.LoadBlock(results[i]) + if block != nil { + blockMeta := env.BlockStore.LoadBlockMeta(block.Height) + if blockMeta != nil { + apiResults = append(apiResults, &ctypes.ResultBlock{ + Block: block, + BlockID: blockMeta.BlockID, + }) + } + } + } + + return &ctypes.ResultBlockSearch{Blocks: apiResults, TotalCount: totalCount}, nil +} diff --git a/rpc/core/blocks_test.go b/rpc/core/blocks_test.go new file mode 100644 index 0000000..054a8bb --- /dev/null +++ b/rpc/core/blocks_test.go @@ -0,0 +1,118 @@ +package core + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/mocks" +) + +func TestBlockchainInfo(t *testing.T) { + cases := []struct { + min, max int64 + base, height int64 + limit int64 + resultLength int64 + wantErr bool + }{ + // min > max + {0, 0, 0, 0, 10, 0, true}, // min set to 1 + {0, 1, 0, 0, 10, 0, true}, // max set to height (0) + {0, 0, 0, 1, 10, 1, false}, // max set to height (1) + {2, 0, 0, 1, 10, 0, true}, // max set to height (1) + {2, 1, 0, 5, 10, 0, true}, + + // negative + {1, 10, 0, 14, 10, 10, false}, // control + {-1, 10, 0, 14, 10, 0, true}, + {1, -10, 0, 14, 10, 0, true}, + {-9223372036854775808, -9223372036854775788, 0, 100, 20, 0, true}, + + // check base + {1, 1, 1, 1, 1, 1, false}, + {2, 5, 3, 5, 5, 3, false}, + + // check limit and height + {1, 1, 0, 1, 10, 1, false}, + {1, 1, 0, 5, 10, 1, false}, + {2, 2, 0, 5, 10, 1, false}, + {1, 2, 0, 5, 10, 2, false}, + {1, 5, 0, 1, 10, 1, false}, + {1, 5, 0, 10, 10, 5, false}, + {1, 15, 0, 10, 10, 10, false}, + {1, 15, 0, 15, 10, 10, false}, + {1, 15, 0, 15, 20, 15, false}, + {1, 20, 0, 15, 20, 15, false}, + {1, 20, 0, 20, 20, 20, false}, + } + + for i, c := range cases { + caseString := fmt.Sprintf("test %d failed", i) + min, max, err := filterMinMax(c.base, c.height, c.min, c.max, c.limit) + if c.wantErr { + require.Error(t, err, caseString) + } else { + require.NoError(t, err, caseString) + require.Equal(t, 1+max-min, c.resultLength, caseString) + } + } +} + +func TestBlockResults(t *testing.T) { + results := &abci.ResponseFinalizeBlock{ + TxResults: []*abci.ExecTxResult{ + {Code: 0, Data: []byte{0x01}, Log: "ok"}, + {Code: 0, Data: []byte{0x02}, Log: "ok"}, + {Code: 1, Log: "not ok"}, + }, + AppHash: make([]byte, 1), + } + + env := &Environment{} + env.StateStore = sm.NewStore(dbm.NewMemDB(), sm.StoreOptions{ + DiscardABCIResponses: false, + }) + err := env.StateStore.SaveFinalizeBlockResponse(100, results) + require.NoError(t, err) + mockstore := &mocks.BlockStore{} + mockstore.On("Height").Return(int64(100)) + mockstore.On("Base").Return(int64(1)) + env.BlockStore = mockstore + + testCases := []struct { + height int64 + wantErr bool + wantRes *ctypes.ResultBlockResults + }{ + {-1, true, nil}, + {0, true, nil}, + {101, true, nil}, + {100, false, &ctypes.ResultBlockResults{ + Height: 100, + TxsResults: results.TxResults, + FinalizeBlockEvents: results.Events, + ValidatorUpdates: results.ValidatorUpdates, + ConsensusParamUpdates: results.ConsensusParamUpdates, + AppHash: make([]byte, 1), + }}, + } + + for _, tc := range testCases { + res, err := env.BlockResults(&rpctypes.Context{}, &tc.height) + if tc.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.Equal(t, tc.wantRes, res) + } + } +} diff --git a/rpc/core/consensus.go b/rpc/core/consensus.go new file mode 100644 index 0000000..5c16422 --- /dev/null +++ b/rpc/core/consensus.go @@ -0,0 +1,118 @@ +package core + +import ( + cm "github.com/cometbft/cometbft/consensus" + cmtmath "github.com/cometbft/cometbft/libs/math" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +// Validators gets the validator set at the given block height. +// +// If no height is provided, it will fetch the latest validator set. Note the +// validators are sorted by their voting power - this is the canonical order +// for the validators in the set as used in computing their Merkle root. +// +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/validators +func (env *Environment) Validators( + _ *rpctypes.Context, + heightPtr *int64, + pagePtr, perPagePtr *int, +) (*ctypes.ResultValidators, error) { + // The latest validator that we know is the NextValidator of the last block. + height, err := env.getHeight(env.latestUncommittedHeight(), heightPtr) + if err != nil { + return nil, err + } + + validators, err := env.StateStore.LoadValidators(height) + if err != nil { + return nil, err + } + + totalCount := len(validators.Validators) + perPage := env.validatePerPage(perPagePtr) + page, err := validatePage(pagePtr, perPage, totalCount) + if err != nil { + return nil, err + } + + skipCount := validateSkipCount(page, perPage) + + v := validators.Validators[skipCount : skipCount+cmtmath.MinInt(perPage, totalCount-skipCount)] + + return &ctypes.ResultValidators{ + BlockHeight: height, + Validators: v, + Count: len(v), + Total: totalCount, + }, nil +} + +// DumpConsensusState dumps consensus state. +// UNSTABLE +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/dump_consensus_state +func (env *Environment) DumpConsensusState(*rpctypes.Context) (*ctypes.ResultDumpConsensusState, error) { + // Get Peer consensus states. + peers := env.P2PPeers.Peers().List() + peerStates := make([]ctypes.PeerStateInfo, len(peers)) + for i, peer := range peers { + peerState, ok := peer.Get(types.PeerStateKey).(*cm.PeerState) + if !ok { // peer does not have a state yet + continue + } + peerStateJSON, err := peerState.MarshalJSON() + if err != nil { + return nil, err + } + peerStates[i] = ctypes.PeerStateInfo{ + // Peer basic info. + NodeAddress: peer.SocketAddr().String(), + // Peer consensus state. + PeerState: peerStateJSON, + } + } + // Get self round state. + roundState, err := env.ConsensusState.GetRoundStateJSON() + if err != nil { + return nil, err + } + return &ctypes.ResultDumpConsensusState{ + RoundState: roundState, + Peers: peerStates, + }, nil +} + +// ConsensusState returns a concise summary of the consensus state. +// UNSTABLE +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/consensus_state +func (env *Environment) GetConsensusState(*rpctypes.Context) (*ctypes.ResultConsensusState, error) { + // Get self round state. + bz, err := env.ConsensusState.GetRoundStateSimpleJSON() + return &ctypes.ResultConsensusState{RoundState: bz}, err +} + +// ConsensusParams gets the consensus parameters at the given block height. +// If no height is provided, it will fetch the latest consensus params. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/consensus_params +func (env *Environment) ConsensusParams( + _ *rpctypes.Context, + heightPtr *int64, +) (*ctypes.ResultConsensusParams, error) { + // The latest consensus params that we know is the consensus params after the + // last block. + height, err := env.getHeight(env.latestUncommittedHeight(), heightPtr) + if err != nil { + return nil, err + } + + consensusParams, err := env.StateStore.LoadConsensusParams(height) + if err != nil { + return nil, err + } + return &ctypes.ResultConsensusParams{ + BlockHeight: height, + ConsensusParams: consensusParams, + }, nil +} diff --git a/rpc/core/dev.go b/rpc/core/dev.go new file mode 100644 index 0000000..55dfe42 --- /dev/null +++ b/rpc/core/dev.go @@ -0,0 +1,12 @@ +package core + +import ( + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// UnsafeFlushMempool removes all transactions from the mempool. +func (env *Environment) UnsafeFlushMempool(*rpctypes.Context) (*ctypes.ResultUnsafeFlushMempool, error) { + env.Mempool.Flush() + return &ctypes.ResultUnsafeFlushMempool{}, nil +} diff --git a/rpc/core/doc.go b/rpc/core/doc.go new file mode 100644 index 0000000..2c177c8 --- /dev/null +++ b/rpc/core/doc.go @@ -0,0 +1,45 @@ +/* +Package core defines the CometBFT RPC endpoints. + +CometBFT ships with its own JSONRPC library - +https://github.com/cometbft/cometbft/tree/v0.38.x/rpc/jsonrpc. + +## Get the list + +An HTTP Get request to the root RPC endpoint shows a list of available endpoints. + +```bash +curl 'localhost:26657' +``` + +> Response: + +```plain +Available endpoints: +/abci_info +/dump_consensus_state +/genesis +/net_info +/num_unconfirmed_txs +/status +/health +/unconfirmed_txs +/unsafe_flush_mempool +/validators + +Endpoints that require arguments: +/abci_query?path=_&data=_&prove=_ +/block?height=_ +/blockchain?minHeight=_&maxHeight=_ +/broadcast_tx_async?tx=_ +/broadcast_tx_commit?tx=_ +/broadcast_tx_sync?tx=_ +/commit?height=_ +/dial_seeds?seeds=_ +/dial_persistent_peers?persistent_peers=_ +/subscribe?event=_ +/tx?hash=_&prove=_ +/unsubscribe?event=_ +``` +*/ +package core diff --git a/rpc/core/doc_template.txt b/rpc/core/doc_template.txt new file mode 100644 index 0000000..5827be3 --- /dev/null +++ b/rpc/core/doc_template.txt @@ -0,0 +1,8 @@ +{{with .PDoc}} +{{comment_md .Doc}} +{{example_html $ ""}} + +{{range .Funcs}}{{$name_html := html .Name}}## [{{$name_html}}]({{posLink_url $ .Decl}}) +{{comment_md .Doc}}{{end}} +{{end}} +--- diff --git a/rpc/core/env.go b/rpc/core/env.go new file mode 100644 index 0000000..9f17495 --- /dev/null +++ b/rpc/core/env.go @@ -0,0 +1,199 @@ +package core + +import ( + "encoding/base64" + "fmt" + "time" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/types" +) + +const ( + // see README + defaultPerPage = 30 + maxPerPage = 100 + + // SubscribeTimeout is the maximum time we wait to subscribe for an event. + // must be less than the server's write timeout (see rpcserver.DefaultConfig) + SubscribeTimeout = 5 * time.Second + + // genesisChunkSize is the maximum size, in bytes, of each + // chunk in the genesis structure for the chunked API + genesisChunkSize = 16 * 1024 * 1024 // 16 +) + +//---------------------------------------------- +// These interfaces are used by RPC and must be thread safe + +type Consensus interface { + GetState() sm.State + GetValidators() (int64, []*types.Validator) + GetLastHeight() int64 + GetRoundStateJSON() ([]byte, error) + GetRoundStateSimpleJSON() ([]byte, error) +} + +type transport interface { + Listeners() []string + IsListening() bool + NodeInfo() p2p.NodeInfo +} + +type peers interface { + AddPersistentPeers([]string) error + AddUnconditionalPeerIDs([]string) error + AddPrivatePeerIDs([]string) error + DialPeersAsync([]string) error + Peers() p2p.IPeerSet +} + +type consensusReactor interface { + WaitSync() bool +} + +// ---------------------------------------------- +// Environment contains objects and interfaces used by the RPC. It is expected +// to be setup once during startup. +type Environment struct { + // external, thread safe interfaces + ProxyAppQuery proxy.AppConnQuery + ProxyAppMempool proxy.AppConnMempool + + // interfaces defined in types and above + StateStore sm.Store + BlockStore sm.BlockStore + EvidencePool sm.EvidencePool + ConsensusState Consensus + ConsensusReactor consensusReactor + P2PPeers peers + P2PTransport transport + + // objects + PubKey crypto.PubKey + GenDoc *types.GenesisDoc // cache the genesis structure + TxIndexer txindex.TxIndexer + BlockIndexer indexer.BlockIndexer + EventBus *types.EventBus // thread safe + Mempool mempl.Mempool + + Logger log.Logger + + Config cfg.RPCConfig + + // cache of chunked genesis data. + genChunks []string +} + +//---------------------------------------------- + +func validatePage(pagePtr *int, perPage, totalCount int) (int, error) { + if perPage < 1 { + panic(fmt.Sprintf("zero or negative perPage: %d", perPage)) + } + + if pagePtr == nil { // no page parameter + return 1, nil + } + + pages := ((totalCount - 1) / perPage) + 1 + if pages == 0 { + pages = 1 // one page (even if it's empty) + } + page := *pagePtr + if page <= 0 || page > pages { + return 1, fmt.Errorf("page should be within [1, %d] range, given %d", pages, page) + } + + return page, nil +} + +func (env *Environment) validatePerPage(perPagePtr *int) int { + if perPagePtr == nil { // no per_page parameter + return defaultPerPage + } + + perPage := *perPagePtr + if perPage < 1 { + return defaultPerPage + } else if perPage > maxPerPage { + return maxPerPage + } + return perPage +} + +// InitGenesisChunks configures the environment and should be called on service +// startup. +func (env *Environment) InitGenesisChunks() error { + if env.genChunks != nil { + return nil + } + + if env.GenDoc == nil { + return nil + } + + data, err := cmtjson.Marshal(env.GenDoc) + if err != nil { + return err + } + + for i := 0; i < len(data); i += genesisChunkSize { + end := i + genesisChunkSize + + if end > len(data) { + end = len(data) + } + + env.genChunks = append(env.genChunks, base64.StdEncoding.EncodeToString(data[i:end])) + } + + return nil +} + +func validateSkipCount(page, perPage int) int { + skipCount := (page - 1) * perPage + if skipCount < 0 { + return 0 + } + + return skipCount +} + +// latestHeight can be either latest committed or uncommitted (+1) height. +func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) { + if heightPtr != nil { + height := *heightPtr + if height <= 0 { + return 0, fmt.Errorf("height must be greater than 0, but got %d", height) + } + if height > latestHeight { + return 0, fmt.Errorf("height %d must be less than or equal to the current blockchain height %d", + height, latestHeight) + } + base := env.BlockStore.Base() + if height < base { + return 0, fmt.Errorf("height %d is not available, lowest height is %d", + height, base) + } + return height, nil + } + return latestHeight, nil +} + +func (env *Environment) latestUncommittedHeight() int64 { + nodeIsSyncing := env.ConsensusReactor.WaitSync() + if nodeIsSyncing { + return env.BlockStore.Height() + } + return env.BlockStore.Height() + 1 +} diff --git a/rpc/core/env_test.go b/rpc/core/env_test.go new file mode 100644 index 0000000..1155700 --- /dev/null +++ b/rpc/core/env_test.go @@ -0,0 +1,82 @@ +package core + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestPaginationPage(t *testing.T) { + cases := []struct { + totalCount int + perPage int + page int + newPage int + expErr bool + }{ + {0, 10, 1, 1, false}, + + {0, 10, 0, 1, false}, + {0, 10, 1, 1, false}, + {0, 10, 2, 0, true}, + + {5, 10, -1, 0, true}, + {5, 10, 0, 1, false}, + {5, 10, 1, 1, false}, + {5, 10, 2, 0, true}, + {5, 10, 2, 0, true}, + + {5, 5, 1, 1, false}, + {5, 5, 2, 0, true}, + {5, 5, 3, 0, true}, + + {5, 3, 2, 2, false}, + {5, 3, 3, 0, true}, + + {5, 2, 2, 2, false}, + {5, 2, 3, 3, false}, + {5, 2, 4, 0, true}, + } + + for _, c := range cases { + p, err := validatePage(&c.page, c.perPage, c.totalCount) + if c.expErr { + assert.Error(t, err) + continue + } + + assert.Equal(t, c.newPage, p, fmt.Sprintf("%v", c)) + } + + // nil case + p, err := validatePage(nil, 1, 1) + if assert.NoError(t, err) { + assert.Equal(t, 1, p) + } +} + +func TestPaginationPerPage(t *testing.T) { + cases := []struct { + totalCount int + perPage int + newPerPage int + }{ + {5, 0, defaultPerPage}, + {5, 1, 1}, + {5, 2, 2}, + {5, defaultPerPage, defaultPerPage}, + {5, maxPerPage - 1, maxPerPage - 1}, + {5, maxPerPage, maxPerPage}, + {5, maxPerPage + 1, maxPerPage}, + } + env := &Environment{} + for _, c := range cases { + p := env.validatePerPage(&c.perPage) + assert.Equal(t, c.newPerPage, p, fmt.Sprintf("%v", c)) + } + + // nil case + p := env.validatePerPage(nil) + assert.Equal(t, defaultPerPage, p) +} diff --git a/rpc/core/events.go b/rpc/core/events.go new file mode 100644 index 0000000..99bba61 --- /dev/null +++ b/rpc/core/events.go @@ -0,0 +1,130 @@ +package core + +import ( + "context" + "errors" + "fmt" + "time" + + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +const ( + // maxQueryLength is the maximum length of a query string that will be + // accepted. This is just a safety check to avoid outlandish queries. + maxQueryLength = 512 +) + +// Subscribe for events via WebSocket. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Websocket/subscribe +func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, error) { + addr := ctx.RemoteAddr() + + if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients { + return nil, fmt.Errorf("max_subscription_clients %d reached", env.Config.MaxSubscriptionClients) + } else if env.EventBus.NumClientSubscriptions(addr) >= env.Config.MaxSubscriptionsPerClient { + return nil, fmt.Errorf("max_subscriptions_per_client %d reached", env.Config.MaxSubscriptionsPerClient) + } else if len(query) > maxQueryLength { + return nil, errors.New("maximum query length exceeded") + } + + env.Logger.Info("Subscribe to query", "remote", addr, "query", query) + + q, err := cmtquery.New(query) + if err != nil { + return nil, fmt.Errorf("failed to parse query: %w", err) + } + + subCtx, cancel := context.WithTimeout(ctx.Context(), SubscribeTimeout) + defer cancel() + + sub, err := env.EventBus.Subscribe(subCtx, addr, q, env.Config.SubscriptionBufferSize) + if err != nil { + return nil, err + } + + closeIfSlow := env.Config.CloseOnSlowClient + + // Capture the current ID, since it can change in the future. + subscriptionID := ctx.JSONReq.ID + go func() { + for { + select { + case msg := <-sub.Out(): + var ( + resultEvent = &ctypes.ResultEvent{Query: query, Data: msg.Data(), Events: msg.Events()} + resp = rpctypes.NewRPCSuccessResponse(subscriptionID, resultEvent) + ) + writeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := ctx.WSConn.WriteRPCResponse(writeCtx, resp); err != nil { + env.Logger.Info("Can't write response (slow client)", + "to", addr, "subscriptionID", subscriptionID, "err", err) + + if closeIfSlow { + var ( + err = errors.New("subscription was canceled (reason: slow client)") + resp = rpctypes.RPCServerError(subscriptionID, err) + ) + if !ctx.WSConn.TryWriteRPCResponse(resp) { + env.Logger.Info("Can't write response (slow client)", + "to", addr, "subscriptionID", subscriptionID, "err", err) + } + return + } + } + case <-sub.Canceled(): + if sub.Err() != cmtpubsub.ErrUnsubscribed { + var reason string + if sub.Err() == nil { + reason = "CometBFT exited" + } else { + reason = sub.Err().Error() + } + var ( + err = fmt.Errorf("subscription was canceled (reason: %s)", reason) + resp = rpctypes.RPCServerError(subscriptionID, err) + ) + if !ctx.WSConn.TryWriteRPCResponse(resp) { + env.Logger.Info("Can't write response (slow client)", + "to", addr, "subscriptionID", subscriptionID, "err", err) + } + } + return + } + } + }() + + return &ctypes.ResultSubscribe{}, nil +} + +// Unsubscribe from events via WebSocket. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Websocket/unsubscribe +func (env *Environment) Unsubscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultUnsubscribe, error) { + addr := ctx.RemoteAddr() + env.Logger.Info("Unsubscribe from query", "remote", addr, "query", query) + q, err := cmtquery.New(query) + if err != nil { + return nil, fmt.Errorf("failed to parse query: %w", err) + } + err = env.EventBus.Unsubscribe(context.Background(), addr, q) + if err != nil { + return nil, err + } + return &ctypes.ResultUnsubscribe{}, nil +} + +// UnsubscribeAll from all events via WebSocket. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Websocket/unsubscribe_all +func (env *Environment) UnsubscribeAll(ctx *rpctypes.Context) (*ctypes.ResultUnsubscribe, error) { + addr := ctx.RemoteAddr() + env.Logger.Info("Unsubscribe from all", "remote", addr) + err := env.EventBus.UnsubscribeAll(context.Background(), addr) + if err != nil { + return nil, err + } + return &ctypes.ResultUnsubscribe{}, nil +} diff --git a/rpc/core/evidence.go b/rpc/core/evidence.go new file mode 100644 index 0000000..b7aa20c --- /dev/null +++ b/rpc/core/evidence.go @@ -0,0 +1,30 @@ +package core + +import ( + "errors" + "fmt" + + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +// BroadcastEvidence broadcasts evidence of the misbehavior. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Evidence/broadcast_evidence +func (env *Environment) BroadcastEvidence( + _ *rpctypes.Context, + ev types.Evidence, +) (*ctypes.ResultBroadcastEvidence, error) { + if ev == nil { + return nil, errors.New("no evidence was provided") + } + + if err := ev.ValidateBasic(); err != nil { + return nil, fmt.Errorf("evidence.ValidateBasic failed: %w", err) + } + + if err := env.EvidencePool.AddEvidence(ev); err != nil { + return nil, fmt.Errorf("failed to add evidence: %w", err) + } + return &ctypes.ResultBroadcastEvidence{Hash: ev.Hash()}, nil +} diff --git a/rpc/core/health.go b/rpc/core/health.go new file mode 100644 index 0000000..c347d06 --- /dev/null +++ b/rpc/core/health.go @@ -0,0 +1,13 @@ +package core + +import ( + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// Health gets node health. Returns empty result (200 OK) on success, no +// response - in case of an error. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/health +func (env *Environment) Health(*rpctypes.Context) (*ctypes.ResultHealth, error) { + return &ctypes.ResultHealth{}, nil +} diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go new file mode 100644 index 0000000..3112dbe --- /dev/null +++ b/rpc/core/mempool.go @@ -0,0 +1,181 @@ +package core + +import ( + "context" + "errors" + "fmt" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + mempl "github.com/cometbft/cometbft/mempool" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------------------------------- +// NOTE: tx should be signed, but this is only checked at the app level (not by CometBFT!) + +// BroadcastTxAsync returns right away, with no response. Does not wait for +// CheckTx nor transaction results. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_async +func (env *Environment) BroadcastTxAsync(_ *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + err := env.Mempool.CheckTx(tx, nil, mempl.TxInfo{}) + if err != nil { + return nil, err + } + return &ctypes.ResultBroadcastTx{Hash: tx.Hash()}, nil +} + +// BroadcastTxSync returns with the response from CheckTx. Does not wait for +// the transaction result. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_sync +func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + resCh := make(chan *abci.ResponseCheckTx, 1) + err := env.Mempool.CheckTx(tx, func(res *abci.ResponseCheckTx) { + select { + case <-ctx.Context().Done(): + case resCh <- res: + } + }, mempl.TxInfo{}) + if err != nil { + return nil, err + } + + select { + case <-ctx.Context().Done(): + return nil, fmt.Errorf("broadcast confirmation not received: %w", ctx.Context().Err()) + case res := <-resCh: + return &ctypes.ResultBroadcastTx{ + Code: res.Code, + Data: res.Data, + Log: res.Log, + Codespace: res.Codespace, + Hash: tx.Hash(), + }, nil + } +} + +// BroadcastTxCommit returns with the responses from CheckTx and ExecTxResult. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_commit +func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { + subscriber := ctx.RemoteAddr() + + if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients { + return nil, fmt.Errorf("max_subscription_clients %d reached", env.Config.MaxSubscriptionClients) + } else if env.EventBus.NumClientSubscriptions(subscriber) >= env.Config.MaxSubscriptionsPerClient { + return nil, fmt.Errorf("max_subscriptions_per_client %d reached", env.Config.MaxSubscriptionsPerClient) + } + + // Subscribe to tx being committed in block. + subCtx, cancel := context.WithTimeout(ctx.Context(), SubscribeTimeout) + defer cancel() + q := types.EventQueryTxFor(tx) + txSub, err := env.EventBus.Subscribe(subCtx, subscriber, q) + if err != nil { + err = fmt.Errorf("failed to subscribe to tx: %w", err) + env.Logger.Error("Error on broadcast_tx_commit", "err", err) + return nil, err + } + defer func() { + if err := env.EventBus.Unsubscribe(context.Background(), subscriber, q); err != nil { + env.Logger.Error("Error unsubscribing from eventBus", "err", err) + } + }() + + // Broadcast tx and wait for CheckTx result + checkTxResCh := make(chan *abci.ResponseCheckTx, 1) + err = env.Mempool.CheckTx(tx, func(res *abci.ResponseCheckTx) { + select { + case <-ctx.Context().Done(): + case checkTxResCh <- res: + } + }, mempl.TxInfo{}) + if err != nil { + env.Logger.Error("Error on broadcastTxCommit", "err", err) + return nil, fmt.Errorf("error on broadcastTxCommit: %v", err) + } + select { + case <-ctx.Context().Done(): + return nil, fmt.Errorf("broadcast confirmation not received: %w", ctx.Context().Err()) + case checkTxRes := <-checkTxResCh: + if checkTxRes.Code != abci.CodeTypeOK { + return &ctypes.ResultBroadcastTxCommit{ + CheckTx: *checkTxRes, + TxResult: abci.ExecTxResult{}, + Hash: tx.Hash(), + }, nil + } + + // Wait for the tx to be included in a block or timeout. + select { + case msg := <-txSub.Out(): // The tx was included in a block. + txResultEvent := msg.Data().(types.EventDataTx) + return &ctypes.ResultBroadcastTxCommit{ + CheckTx: *checkTxRes, + TxResult: txResultEvent.Result, + Hash: tx.Hash(), + Height: txResultEvent.Height, + }, nil + case <-txSub.Canceled(): + var reason string + if txSub.Err() == nil { + reason = "CometBFT exited" + } else { + reason = txSub.Err().Error() + } + err = fmt.Errorf("txSub was canceled (reason: %s)", reason) + env.Logger.Error("Error on broadcastTxCommit", "err", err) + return &ctypes.ResultBroadcastTxCommit{ + CheckTx: *checkTxRes, + TxResult: abci.ExecTxResult{}, + Hash: tx.Hash(), + }, err + case <-time.After(env.Config.TimeoutBroadcastTxCommit): + err = errors.New("timed out waiting for tx to be included in a block") + env.Logger.Error("Error on broadcastTxCommit", "err", err) + return &ctypes.ResultBroadcastTxCommit{ + CheckTx: *checkTxRes, + TxResult: abci.ExecTxResult{}, + Hash: tx.Hash(), + }, err + } + } +} + +// UnconfirmedTxs gets unconfirmed transactions (maximum ?limit entries) +// including their number. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/unconfirmed_txs +func (env *Environment) UnconfirmedTxs(_ *rpctypes.Context, limitPtr *int) (*ctypes.ResultUnconfirmedTxs, error) { + // reuse per_page validator + limit := env.validatePerPage(limitPtr) + + txs := env.Mempool.ReapMaxTxs(limit) + return &ctypes.ResultUnconfirmedTxs{ + Count: len(txs), + Total: env.Mempool.Size(), + TotalBytes: env.Mempool.SizeBytes(), + Txs: txs, + }, nil +} + +// NumUnconfirmedTxs gets number of unconfirmed transactions. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/num_unconfirmed_txs +func (env *Environment) NumUnconfirmedTxs(*rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, error) { + return &ctypes.ResultUnconfirmedTxs{ + Count: env.Mempool.Size(), + Total: env.Mempool.Size(), + TotalBytes: env.Mempool.SizeBytes(), + }, nil +} + +// CheckTx checks the transaction without executing it. The transaction won't +// be added to the mempool either. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/check_tx +func (env *Environment) CheckTx(_ *rpctypes.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) { + res, err := env.ProxyAppMempool.CheckTx(context.TODO(), &abci.RequestCheckTx{Tx: tx}) + if err != nil { + return nil, err + } + return &ctypes.ResultCheckTx{ResponseCheckTx: *res}, nil +} diff --git a/rpc/core/net.go b/rpc/core/net.go new file mode 100644 index 0000000..77c6a56 --- /dev/null +++ b/rpc/core/net.go @@ -0,0 +1,142 @@ +package core + +import ( + "errors" + "fmt" + "strings" + + "github.com/cometbft/cometbft/p2p" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// NetInfo returns network info. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/net_info +func (env *Environment) NetInfo(*rpctypes.Context) (*ctypes.ResultNetInfo, error) { + peersList := env.P2PPeers.Peers().List() + peers := make([]ctypes.Peer, 0, len(peersList)) + for _, peer := range peersList { + nodeInfo, ok := peer.NodeInfo().(p2p.DefaultNodeInfo) + if !ok { + return nil, fmt.Errorf("peer.NodeInfo() is not DefaultNodeInfo") + } + peers = append(peers, ctypes.Peer{ + NodeInfo: nodeInfo, + IsOutbound: peer.IsOutbound(), + ConnectionStatus: peer.Status(), + RemoteIP: peer.RemoteIP().String(), + }) + } + // TODO: Should we include PersistentPeers and Seeds in here? + // PRO: useful info + // CON: privacy + return &ctypes.ResultNetInfo{ + Listening: env.P2PTransport.IsListening(), + Listeners: env.P2PTransport.Listeners(), + NPeers: len(peers), + Peers: peers, + }, nil +} + +// UnsafeDialSeeds dials the given seeds (comma-separated id@IP:PORT). +func (env *Environment) UnsafeDialSeeds(_ *rpctypes.Context, seeds []string) (*ctypes.ResultDialSeeds, error) { + if len(seeds) == 0 { + return &ctypes.ResultDialSeeds{}, errors.New("no seeds provided") + } + env.Logger.Info("DialSeeds", "seeds", seeds) + if err := env.P2PPeers.DialPeersAsync(seeds); err != nil { + return &ctypes.ResultDialSeeds{}, err + } + return &ctypes.ResultDialSeeds{Log: "Dialing seeds in progress. See /net_info for details"}, nil +} + +// UnsafeDialPeers dials the given peers (comma-separated id@IP:PORT), +// optionally making them persistent. +func (env *Environment) UnsafeDialPeers( + _ *rpctypes.Context, + peers []string, + persistent, unconditional, private bool, +) (*ctypes.ResultDialPeers, error) { + if len(peers) == 0 { + return &ctypes.ResultDialPeers{}, errors.New("no peers provided") + } + + ids, err := getIDs(peers) + if err != nil { + return &ctypes.ResultDialPeers{}, err + } + + env.Logger.Info("DialPeers", "peers", peers, "persistent", + persistent, "unconditional", unconditional, "private", private) + + if persistent { + if err := env.P2PPeers.AddPersistentPeers(peers); err != nil { + return &ctypes.ResultDialPeers{}, err + } + } + + if private { + if err := env.P2PPeers.AddPrivatePeerIDs(ids); err != nil { + return &ctypes.ResultDialPeers{}, err + } + } + + if unconditional { + if err := env.P2PPeers.AddUnconditionalPeerIDs(ids); err != nil { + return &ctypes.ResultDialPeers{}, err + } + } + + if err := env.P2PPeers.DialPeersAsync(peers); err != nil { + return &ctypes.ResultDialPeers{}, err + } + + return &ctypes.ResultDialPeers{Log: "Dialing peers in progress. See /net_info for details"}, nil +} + +// Genesis returns genesis file. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/genesis +func (env *Environment) Genesis(*rpctypes.Context) (*ctypes.ResultGenesis, error) { + if len(env.genChunks) > 1 { + return nil, errors.New("genesis response is large, please use the genesis_chunked API instead") + } + + return &ctypes.ResultGenesis{Genesis: env.GenDoc}, nil +} + +func (env *Environment) GenesisChunked(_ *rpctypes.Context, chunk uint) (*ctypes.ResultGenesisChunk, error) { + if env.genChunks == nil { + return nil, fmt.Errorf("service configuration error, genesis chunks are not initialized") + } + + if len(env.genChunks) == 0 { + return nil, fmt.Errorf("service configuration error, there are no chunks") + } + + id := int(chunk) + + if id > len(env.genChunks)-1 { + return nil, fmt.Errorf("there are %d chunks, %d is invalid", len(env.genChunks)-1, id) + } + + return &ctypes.ResultGenesisChunk{ + TotalChunks: len(env.genChunks), + ChunkNumber: id, + Data: env.genChunks[id], + }, nil +} + +func getIDs(peers []string) ([]string, error) { + ids := make([]string, 0, len(peers)) + + for _, peer := range peers { + + spl := strings.Split(peer, "@") + if len(spl) != 2 { + return nil, p2p.ErrNetAddressNoID{Addr: peer} + } + ids = append(ids, spl[0]) + + } + return ids, nil +} diff --git a/rpc/core/net_test.go b/rpc/core/net_test.go new file mode 100644 index 0000000..66f93ee --- /dev/null +++ b/rpc/core/net_test.go @@ -0,0 +1,89 @@ +package core + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func TestUnsafeDialSeeds(t *testing.T) { + sw := p2p.MakeSwitch(cfg.DefaultP2PConfig(), 1, + func(n int, sw *p2p.Switch) *p2p.Switch { return sw }) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + env := &Environment{} + env.Logger = log.TestingLogger() + env.P2PPeers = sw + + testCases := []struct { + seeds []string + isErr bool + }{ + {[]string{}, true}, + {[]string{"d51fb70907db1c6c2d5237e78379b25cf1a37ab4@127.0.0.1:41198"}, false}, + {[]string{"127.0.0.1:41198"}, true}, + } + + for _, tc := range testCases { + res, err := env.UnsafeDialSeeds(&rpctypes.Context{}, tc.seeds) + if tc.isErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.NotNil(t, res) + } + } +} + +func TestUnsafeDialPeers(t *testing.T) { + sw := p2p.MakeSwitch(cfg.DefaultP2PConfig(), 1, + func(n int, sw *p2p.Switch) *p2p.Switch { return sw }) + sw.SetAddrBook(&p2p.AddrBookMock{ + Addrs: make(map[string]struct{}), + OurAddrs: make(map[string]struct{}), + PrivateAddrs: make(map[string]struct{}), + }) + err := sw.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := sw.Stop(); err != nil { + t.Error(err) + } + }) + + env := &Environment{} + env.Logger = log.TestingLogger() + env.P2PPeers = sw + + testCases := []struct { + peers []string + persistence, unconditional, private bool + isErr bool + }{ + {[]string{}, false, false, false, true}, + {[]string{"d51fb70907db1c6c2d5237e78379b25cf1a37ab4@127.0.0.1:41198"}, true, true, true, false}, + {[]string{"127.0.0.1:41198"}, true, true, false, true}, + } + + for _, tc := range testCases { + res, err := env.UnsafeDialPeers(&rpctypes.Context{}, tc.peers, tc.persistence, tc.unconditional, tc.private) + if tc.isErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.NotNil(t, res) + } + } +} diff --git a/rpc/core/routes.go b/rpc/core/routes.go new file mode 100644 index 0000000..7aa57bc --- /dev/null +++ b/rpc/core/routes.go @@ -0,0 +1,63 @@ +package core + +import ( + rpc "github.com/cometbft/cometbft/rpc/jsonrpc/server" +) + +// TODO: better system than "unsafe" prefix + +type RoutesMap map[string]*rpc.RPCFunc + +// Routes is a map of available routes. +func (env *Environment) GetRoutes() RoutesMap { + return RoutesMap{ + // subscribe/unsubscribe are reserved for websocket events. + "subscribe": rpc.NewWSRPCFunc(env.Subscribe, "query"), + "unsubscribe": rpc.NewWSRPCFunc(env.Unsubscribe, "query"), + "unsubscribe_all": rpc.NewWSRPCFunc(env.UnsubscribeAll, ""), + + // info AP + "health": rpc.NewRPCFunc(env.Health, ""), + "status": rpc.NewRPCFunc(env.Status, ""), + "net_info": rpc.NewRPCFunc(env.NetInfo, ""), + "blockchain": rpc.NewRPCFunc(env.BlockchainInfo, "minHeight,maxHeight", rpc.Cacheable()), + "genesis": rpc.NewRPCFunc(env.Genesis, "", rpc.Cacheable()), + "genesis_chunked": rpc.NewRPCFunc(env.GenesisChunked, "chunk", rpc.Cacheable()), + "block": rpc.NewRPCFunc(env.Block, "height", rpc.Cacheable("height")), + "block_by_hash": rpc.NewRPCFunc(env.BlockByHash, "hash", rpc.Cacheable()), + "block_results": rpc.NewRPCFunc(env.BlockResults, "height", rpc.Cacheable("height")), + "commit": rpc.NewRPCFunc(env.Commit, "height", rpc.Cacheable("height")), + "header": rpc.NewRPCFunc(env.Header, "height", rpc.Cacheable("height")), + "header_by_hash": rpc.NewRPCFunc(env.HeaderByHash, "hash", rpc.Cacheable()), + "check_tx": rpc.NewRPCFunc(env.CheckTx, "tx"), + "tx": rpc.NewRPCFunc(env.Tx, "hash,prove", rpc.Cacheable()), + "tx_search": rpc.NewRPCFunc(env.TxSearch, "query,prove,page,per_page,order_by"), + "block_search": rpc.NewRPCFunc(env.BlockSearch, "query,page,per_page,order_by"), + "validators": rpc.NewRPCFunc(env.Validators, "height,page,per_page", rpc.Cacheable("height")), + "dump_consensus_state": rpc.NewRPCFunc(env.DumpConsensusState, ""), + "consensus_state": rpc.NewRPCFunc(env.GetConsensusState, ""), + "consensus_params": rpc.NewRPCFunc(env.ConsensusParams, "height", rpc.Cacheable("height")), + "unconfirmed_txs": rpc.NewRPCFunc(env.UnconfirmedTxs, "limit"), + "num_unconfirmed_txs": rpc.NewRPCFunc(env.NumUnconfirmedTxs, ""), + + // tx broadcast API + "broadcast_tx_commit": rpc.NewRPCFunc(env.BroadcastTxCommit, "tx"), + "broadcast_tx_sync": rpc.NewRPCFunc(env.BroadcastTxSync, "tx"), + "broadcast_tx_async": rpc.NewRPCFunc(env.BroadcastTxAsync, "tx"), + + // abci API + "abci_query": rpc.NewRPCFunc(env.ABCIQuery, "path,data,height,prove"), + "abci_info": rpc.NewRPCFunc(env.ABCIInfo, "", rpc.Cacheable()), + + // evidence API + "broadcast_evidence": rpc.NewRPCFunc(env.BroadcastEvidence, "evidence"), + } +} + +// AddUnsafeRoutes adds unsafe routes. +func (env *Environment) AddUnsafeRoutes(routes RoutesMap) { + // control API + routes["dial_seeds"] = rpc.NewRPCFunc(env.UnsafeDialSeeds, "seeds") + routes["dial_peers"] = rpc.NewRPCFunc(env.UnsafeDialPeers, "peers,persistent,unconditional,private") + routes["unsafe_flush_mempool"] = rpc.NewRPCFunc(env.UnsafeFlushMempool, "") +} diff --git a/rpc/core/status.go b/rpc/core/status.go new file mode 100644 index 0000000..e4737f5 --- /dev/null +++ b/rpc/core/status.go @@ -0,0 +1,85 @@ +package core + +import ( + "time" + + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/p2p" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/types" +) + +// Status returns CometBFT status including node info, pubkey, latest block +// hash, app hash, block height and time. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/status +func (env *Environment) Status(*rpctypes.Context) (*ctypes.ResultStatus, error) { + var ( + earliestBlockHeight int64 + earliestBlockHash cmtbytes.HexBytes + earliestAppHash cmtbytes.HexBytes + earliestBlockTimeNano int64 + ) + + if earliestBlockMeta := env.BlockStore.LoadBaseMeta(); earliestBlockMeta != nil { + earliestBlockHeight = earliestBlockMeta.Header.Height + earliestAppHash = earliestBlockMeta.Header.AppHash + earliestBlockHash = earliestBlockMeta.BlockID.Hash + earliestBlockTimeNano = earliestBlockMeta.Header.Time.UnixNano() + } + + var ( + latestBlockHash cmtbytes.HexBytes + latestAppHash cmtbytes.HexBytes + latestBlockTimeNano int64 + + latestHeight = env.BlockStore.Height() + ) + + if latestHeight != 0 { + if latestBlockMeta := env.BlockStore.LoadBlockMeta(latestHeight); latestBlockMeta != nil { + latestBlockHash = latestBlockMeta.BlockID.Hash + latestAppHash = latestBlockMeta.Header.AppHash + latestBlockTimeNano = latestBlockMeta.Header.Time.UnixNano() + } + } + + // Return the very last voting power, not the voting power of this validator + // during the last block. + var votingPower int64 + if val := env.validatorAtHeight(env.latestUncommittedHeight()); val != nil { + votingPower = val.VotingPower + } + + result := &ctypes.ResultStatus{ + NodeInfo: env.P2PTransport.NodeInfo().(p2p.DefaultNodeInfo), + SyncInfo: ctypes.SyncInfo{ + LatestBlockHash: latestBlockHash, + LatestAppHash: latestAppHash, + LatestBlockHeight: latestHeight, + LatestBlockTime: time.Unix(0, latestBlockTimeNano), + EarliestBlockHash: earliestBlockHash, + EarliestAppHash: earliestAppHash, + EarliestBlockHeight: earliestBlockHeight, + EarliestBlockTime: time.Unix(0, earliestBlockTimeNano), + CatchingUp: env.ConsensusReactor.WaitSync(), + }, + ValidatorInfo: ctypes.ValidatorInfo{ + Address: env.PubKey.Address(), + PubKey: env.PubKey, + VotingPower: votingPower, + }, + } + + return result, nil +} + +func (env *Environment) validatorAtHeight(h int64) *types.Validator { + valsWithH, err := env.StateStore.LoadValidators(h) + if err != nil { + return nil + } + privValAddress := env.PubKey.Address() + _, val := valsWithH.GetByAddress(privValAddress) + return val +} diff --git a/rpc/core/tx.go b/rpc/core/tx.go new file mode 100644 index 0000000..5abd0dd --- /dev/null +++ b/rpc/core/tx.go @@ -0,0 +1,135 @@ +package core + +import ( + "errors" + "fmt" + "sort" + + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/cometbft/cometbft/state/txindex/null" + "github.com/cometbft/cometbft/types" +) + +// Tx allows you to query the transaction results. `nil` could mean the +// transaction is in the mempool, invalidated, or was not sent in the first +// place. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/tx +func (env *Environment) Tx(_ *rpctypes.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) { + // if index is disabled, return error + if _, ok := env.TxIndexer.(*null.TxIndex); ok { + return nil, fmt.Errorf("transaction indexing is disabled") + } + + r, err := env.TxIndexer.Get(hash) + if err != nil { + return nil, err + } + + if r == nil { + return nil, fmt.Errorf("tx (%X) not found", hash) + } + + var proof types.TxProof + if prove { + block := env.BlockStore.LoadBlock(r.Height) + if block != nil { + proof = block.Txs.Proof(int(r.Index)) + } + } + + return &ctypes.ResultTx{ + Hash: hash, + Height: r.Height, + Index: r.Index, + TxResult: r.Result, + Tx: r.Tx, + Proof: proof, + }, nil +} + +// TxSearch allows you to query for multiple transactions results. It returns a +// list of transactions (maximum ?per_page entries) and the total count. +// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/tx_search +func (env *Environment) TxSearch( + ctx *rpctypes.Context, + query string, + prove bool, + pagePtr, perPagePtr *int, + orderBy string, +) (*ctypes.ResultTxSearch, error) { + // if index is disabled, return error + if _, ok := env.TxIndexer.(*null.TxIndex); ok { + return nil, errors.New("transaction indexing is disabled") + } else if len(query) > maxQueryLength { + return nil, errors.New("maximum query length exceeded") + } + + q, err := cmtquery.New(query) + if err != nil { + return nil, err + } + + results, err := env.TxIndexer.Search(ctx.Context(), q) + if err != nil { + return nil, err + } + + // sort results (must be done before pagination) + switch orderBy { + case "desc": + sort.Slice(results, func(i, j int) bool { + if results[i].Height == results[j].Height { + return results[i].Index > results[j].Index + } + return results[i].Height > results[j].Height + }) + case "asc", "": + sort.Slice(results, func(i, j int) bool { + if results[i].Height == results[j].Height { + return results[i].Index < results[j].Index + } + return results[i].Height < results[j].Height + }) + default: + return nil, errors.New("expected order_by to be either `asc` or `desc` or empty") + } + + // paginate results + totalCount := len(results) + perPage := env.validatePerPage(perPagePtr) + + page, err := validatePage(pagePtr, perPage, totalCount) + if err != nil { + return nil, err + } + + skipCount := validateSkipCount(page, perPage) + pageSize := cmtmath.MinInt(perPage, totalCount-skipCount) + + apiResults := make([]*ctypes.ResultTx, 0, pageSize) + for i := skipCount; i < skipCount+pageSize; i++ { + r := results[i] + + var proof types.TxProof + if prove { + block := env.BlockStore.LoadBlock(r.Height) + if block != nil { + proof = block.Txs.Proof(int(r.Index)) + } + } + + apiResults = append(apiResults, &ctypes.ResultTx{ + Hash: types.Tx(r.Tx).Hash(), + Height: r.Height, + Index: r.Index, + TxResult: r.Result, + Tx: r.Tx, + Proof: proof, + }) + } + + return &ctypes.ResultTxSearch{Txs: apiResults, TotalCount: totalCount}, nil +} diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go new file mode 100644 index 0000000..19c3c2d --- /dev/null +++ b/rpc/core/types/responses.go @@ -0,0 +1,256 @@ +package coretypes + +import ( + "encoding/json" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/p2p" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +// List of blocks +type ResultBlockchainInfo struct { + LastHeight int64 `json:"last_height"` + BlockMetas []*types.BlockMeta `json:"block_metas"` +} + +// Genesis file +type ResultGenesis struct { + Genesis *types.GenesisDoc `json:"genesis"` +} + +// ResultGenesisChunk is the output format for the chunked/paginated +// interface. These chunks are produced by converting the genesis +// document to JSON and then splitting the resulting payload into +// 16 megabyte blocks and then base64 encoding each block. +type ResultGenesisChunk struct { + ChunkNumber int `json:"chunk"` + TotalChunks int `json:"total"` + Data string `json:"data"` +} + +// Single block (with meta) +type ResultBlock struct { + BlockID types.BlockID `json:"block_id"` + Block *types.Block `json:"block"` +} + +// ResultHeader represents the response for a Header RPC Client query +type ResultHeader struct { + Header *types.Header `json:"header"` +} + +// Commit and Header +type ResultCommit struct { + types.SignedHeader `json:"signed_header"` + CanonicalCommit bool `json:"canonical"` +} + +// ABCI results from a block +type ResultBlockResults struct { + Height int64 `json:"height"` + TxsResults []*abci.ExecTxResult `json:"txs_results"` + FinalizeBlockEvents []abci.Event `json:"finalize_block_events"` + ValidatorUpdates []abci.ValidatorUpdate `json:"validator_updates"` + ConsensusParamUpdates *cmtproto.ConsensusParams `json:"consensus_param_updates"` + AppHash []byte `json:"app_hash"` +} + +// NewResultCommit is a helper to initialize the ResultCommit with +// the embedded struct +func NewResultCommit(header *types.Header, commit *types.Commit, + canonical bool) *ResultCommit { + + return &ResultCommit{ + SignedHeader: types.SignedHeader{ + Header: header, + Commit: commit, + }, + CanonicalCommit: canonical, + } +} + +// Info about the node's syncing state +type SyncInfo struct { + LatestBlockHash bytes.HexBytes `json:"latest_block_hash"` + LatestAppHash bytes.HexBytes `json:"latest_app_hash"` + LatestBlockHeight int64 `json:"latest_block_height"` + LatestBlockTime time.Time `json:"latest_block_time"` + + EarliestBlockHash bytes.HexBytes `json:"earliest_block_hash"` + EarliestAppHash bytes.HexBytes `json:"earliest_app_hash"` + EarliestBlockHeight int64 `json:"earliest_block_height"` + EarliestBlockTime time.Time `json:"earliest_block_time"` + + CatchingUp bool `json:"catching_up"` +} + +// Info about the node's validator +type ValidatorInfo struct { + Address bytes.HexBytes `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` + VotingPower int64 `json:"voting_power"` +} + +// Node Status +type ResultStatus struct { + NodeInfo p2p.DefaultNodeInfo `json:"node_info"` + SyncInfo SyncInfo `json:"sync_info"` + ValidatorInfo ValidatorInfo `json:"validator_info"` +} + +// Is TxIndexing enabled +func (s *ResultStatus) TxIndexEnabled() bool { + if s == nil { + return false + } + return s.NodeInfo.Other.TxIndex == "on" +} + +// Info about peer connections +type ResultNetInfo struct { + Listening bool `json:"listening"` + Listeners []string `json:"listeners"` + NPeers int `json:"n_peers"` + Peers []Peer `json:"peers"` +} + +// Log from dialing seeds +type ResultDialSeeds struct { + Log string `json:"log"` +} + +// Log from dialing peers +type ResultDialPeers struct { + Log string `json:"log"` +} + +// A peer +type Peer struct { + NodeInfo p2p.DefaultNodeInfo `json:"node_info"` + IsOutbound bool `json:"is_outbound"` + ConnectionStatus p2p.ConnectionStatus `json:"connection_status"` + RemoteIP string `json:"remote_ip"` +} + +// Validators for a height. +type ResultValidators struct { + BlockHeight int64 `json:"block_height"` + Validators []*types.Validator `json:"validators"` + // Count of actual validators in this result + Count int `json:"count"` + // Total number of validators + Total int `json:"total"` +} + +// ConsensusParams for given height +type ResultConsensusParams struct { + BlockHeight int64 `json:"block_height"` + ConsensusParams types.ConsensusParams `json:"consensus_params"` +} + +// Info about the consensus state. +// UNSTABLE +type ResultDumpConsensusState struct { + RoundState json.RawMessage `json:"round_state"` + Peers []PeerStateInfo `json:"peers"` +} + +// UNSTABLE +type PeerStateInfo struct { + NodeAddress string `json:"node_address"` + PeerState json.RawMessage `json:"peer_state"` +} + +// UNSTABLE +type ResultConsensusState struct { + RoundState json.RawMessage `json:"round_state"` +} + +// CheckTx result +type ResultBroadcastTx struct { + Code uint32 `json:"code"` + Data bytes.HexBytes `json:"data"` + Log string `json:"log"` + Codespace string `json:"codespace"` + + Hash bytes.HexBytes `json:"hash"` +} + +// CheckTx and ExecTx results +type ResultBroadcastTxCommit struct { + CheckTx abci.ResponseCheckTx `json:"check_tx"` + TxResult abci.ExecTxResult `json:"tx_result"` + Hash bytes.HexBytes `json:"hash"` + Height int64 `json:"height"` +} + +// ResultCheckTx wraps abci.ResponseCheckTx. +type ResultCheckTx struct { + abci.ResponseCheckTx +} + +// Result of querying for a tx +type ResultTx struct { + Hash bytes.HexBytes `json:"hash"` + Height int64 `json:"height"` + Index uint32 `json:"index"` + TxResult abci.ExecTxResult `json:"tx_result"` + Tx types.Tx `json:"tx"` + Proof types.TxProof `json:"proof,omitempty"` +} + +// Result of searching for txs +type ResultTxSearch struct { + Txs []*ResultTx `json:"txs"` + TotalCount int `json:"total_count"` +} + +// ResultBlockSearch defines the RPC response type for a block search by events. +type ResultBlockSearch struct { + Blocks []*ResultBlock `json:"blocks"` + TotalCount int `json:"total_count"` +} + +// List of mempool txs +type ResultUnconfirmedTxs struct { + Count int `json:"n_txs"` + Total int `json:"total"` + TotalBytes int64 `json:"total_bytes"` + Txs []types.Tx `json:"txs"` +} + +// Info abci msg +type ResultABCIInfo struct { + Response abci.ResponseInfo `json:"response"` +} + +// Query abci msg +type ResultABCIQuery struct { + Response abci.ResponseQuery `json:"response"` +} + +// Result of broadcasting evidence +type ResultBroadcastEvidence struct { + Hash []byte `json:"hash"` +} + +// empty results +type ( + ResultUnsafeFlushMempool struct{} + ResultUnsafeProfile struct{} + ResultSubscribe struct{} + ResultUnsubscribe struct{} + ResultHealth struct{} +) + +// Event data from a subscription +type ResultEvent struct { + Query string `json:"query"` + Data types.TMEventData `json:"data"` + Events map[string][]string `json:"events"` +} diff --git a/rpc/core/types/responses_test.go b/rpc/core/types/responses_test.go new file mode 100644 index 0000000..d247e51 --- /dev/null +++ b/rpc/core/types/responses_test.go @@ -0,0 +1,35 @@ +package coretypes + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/p2p" +) + +func TestStatusIndexer(t *testing.T) { + var status *ResultStatus + assert.False(t, status.TxIndexEnabled()) + + status = &ResultStatus{} + assert.False(t, status.TxIndexEnabled()) + + status.NodeInfo = p2p.DefaultNodeInfo{} + assert.False(t, status.TxIndexEnabled()) + + cases := []struct { + expected bool + other p2p.DefaultNodeInfoOther + }{ + {false, p2p.DefaultNodeInfoOther{}}, + {false, p2p.DefaultNodeInfoOther{TxIndex: "aa"}}, + {false, p2p.DefaultNodeInfoOther{TxIndex: "off"}}, + {true, p2p.DefaultNodeInfoOther{TxIndex: "on"}}, + } + + for _, tc := range cases { + status.NodeInfo.Other = tc.other + assert.Equal(t, tc.expected, status.TxIndexEnabled()) + } +} diff --git a/rpc/grpc/api.go b/rpc/grpc/api.go new file mode 100644 index 0000000..ed5545e --- /dev/null +++ b/rpc/grpc/api.go @@ -0,0 +1,40 @@ +package coregrpc + +import ( + "context" + + abci "github.com/cometbft/cometbft/abci/types" + core "github.com/cometbft/cometbft/rpc/core" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +type broadcastAPI struct { + env *core.Environment +} + +func (bapi *broadcastAPI) Ping(context.Context, *RequestPing) (*ResponsePing, error) { + // kvstore so we can check if the server is up + return &ResponsePing{}, nil +} + +func (bapi *broadcastAPI) BroadcastTx(_ context.Context, req *RequestBroadcastTx) (*ResponseBroadcastTx, error) { + // NOTE: there's no way to get client's remote address + // see https://stackoverflow.com/questions/33684570/session-and-remote-ip-address-in-grpc-go + res, err := bapi.env.BroadcastTxCommit(&rpctypes.Context{}, req.Tx) + if err != nil { + return nil, err + } + + return &ResponseBroadcastTx{ + CheckTx: &abci.ResponseCheckTx{ + Code: res.CheckTx.Code, + Data: res.CheckTx.Data, + Log: res.CheckTx.Log, + }, + TxResult: &abci.ExecTxResult{ + Code: res.TxResult.Code, + Data: res.TxResult.Data, + Log: res.TxResult.Log, + }, + }, nil +} diff --git a/rpc/grpc/client_server.go b/rpc/grpc/client_server.go new file mode 100644 index 0000000..89cdf92 --- /dev/null +++ b/rpc/grpc/client_server.go @@ -0,0 +1,45 @@ +package coregrpc + +import ( + "net" + + "golang.org/x/net/context" + "google.golang.org/grpc" + + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/rpc/core" +) + +// Config is an gRPC server configuration. +// +// Deprecated: A new gRPC API will be introduced after v0.38. +type Config struct { + MaxOpenConnections int +} + +// StartGRPCServer starts a new gRPC BroadcastAPIServer using the given +// net.Listener. +// NOTE: This function blocks - you may want to call it in a go-routine. +// +// Deprecated: A new gRPC API will be introduced after v0.38. +func StartGRPCServer(env *core.Environment, ln net.Listener) error { + grpcServer := grpc.NewServer() + RegisterBroadcastAPIServer(grpcServer, &broadcastAPI{env: env}) + return grpcServer.Serve(ln) +} + +// StartGRPCClient dials the gRPC server using protoAddr and returns a new +// BroadcastAPIClient. +// +// Deprecated: A new gRPC API will be introduced after v0.38. +func StartGRPCClient(protoAddr string) BroadcastAPIClient { + conn, err := grpc.Dial(protoAddr, grpc.WithInsecure(), grpc.WithContextDialer(dialerFunc)) + if err != nil { + panic(err) + } + return NewBroadcastAPIClient(conn) +} + +func dialerFunc(_ context.Context, addr string) (net.Conn, error) { + return cmtnet.Connect(addr) +} diff --git a/rpc/grpc/grpc_test.go b/rpc/grpc/grpc_test.go new file mode 100644 index 0000000..b354158 --- /dev/null +++ b/rpc/grpc/grpc_test.go @@ -0,0 +1,35 @@ +package coregrpc_test + +import ( + "context" + "os" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/abci/example/kvstore" + core_grpc "github.com/cometbft/cometbft/rpc/grpc" + rpctest "github.com/cometbft/cometbft/rpc/test" +) + +func TestMain(m *testing.M) { + // start a CometBFT node in the background to test against + app := kvstore.NewInMemoryApplication() + node := rpctest.StartTendermint(app) + + code := m.Run() + + // and shut down proper at the end + rpctest.StopTendermint(node) + os.Exit(code) +} + +func TestBroadcastTx(t *testing.T) { + res, err := rpctest.GetGRPCClient().BroadcastTx( + context.Background(), + &core_grpc.RequestBroadcastTx{Tx: kvstore.NewTx("hello", "world")}, + ) + require.NoError(t, err) + require.EqualValues(t, 0, res.CheckTx.Code) + require.EqualValues(t, 0, res.TxResult.Code) +} diff --git a/rpc/grpc/types.pb.go b/rpc/grpc/types.pb.go new file mode 100644 index 0000000..ee2010a --- /dev/null +++ b/rpc/grpc/types.pb.go @@ -0,0 +1,927 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint/rpc/grpc/types.proto + +package coregrpc + +import ( + context "context" + fmt "fmt" + types "github.com/cometbft/cometbft/abci/types" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type RequestPing struct { +} + +func (m *RequestPing) Reset() { *m = RequestPing{} } +func (m *RequestPing) String() string { return proto.CompactTextString(m) } +func (*RequestPing) ProtoMessage() {} +func (*RequestPing) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{0} +} +func (m *RequestPing) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestPing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestPing.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestPing) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestPing.Merge(m, src) +} +func (m *RequestPing) XXX_Size() int { + return m.Size() +} +func (m *RequestPing) XXX_DiscardUnknown() { + xxx_messageInfo_RequestPing.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestPing proto.InternalMessageInfo + +type RequestBroadcastTx struct { + Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` +} + +func (m *RequestBroadcastTx) Reset() { *m = RequestBroadcastTx{} } +func (m *RequestBroadcastTx) String() string { return proto.CompactTextString(m) } +func (*RequestBroadcastTx) ProtoMessage() {} +func (*RequestBroadcastTx) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{1} +} +func (m *RequestBroadcastTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RequestBroadcastTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_RequestBroadcastTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *RequestBroadcastTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_RequestBroadcastTx.Merge(m, src) +} +func (m *RequestBroadcastTx) XXX_Size() int { + return m.Size() +} +func (m *RequestBroadcastTx) XXX_DiscardUnknown() { + xxx_messageInfo_RequestBroadcastTx.DiscardUnknown(m) +} + +var xxx_messageInfo_RequestBroadcastTx proto.InternalMessageInfo + +func (m *RequestBroadcastTx) GetTx() []byte { + if m != nil { + return m.Tx + } + return nil +} + +type ResponsePing struct { +} + +func (m *ResponsePing) Reset() { *m = ResponsePing{} } +func (m *ResponsePing) String() string { return proto.CompactTextString(m) } +func (*ResponsePing) ProtoMessage() {} +func (*ResponsePing) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{2} +} +func (m *ResponsePing) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponsePing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponsePing.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponsePing) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponsePing.Merge(m, src) +} +func (m *ResponsePing) XXX_Size() int { + return m.Size() +} +func (m *ResponsePing) XXX_DiscardUnknown() { + xxx_messageInfo_ResponsePing.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponsePing proto.InternalMessageInfo + +type ResponseBroadcastTx struct { + CheckTx *types.ResponseCheckTx `protobuf:"bytes,1,opt,name=check_tx,json=checkTx,proto3" json:"check_tx,omitempty"` + TxResult *types.ExecTxResult `protobuf:"bytes,2,opt,name=tx_result,json=txResult,proto3" json:"tx_result,omitempty"` +} + +func (m *ResponseBroadcastTx) Reset() { *m = ResponseBroadcastTx{} } +func (m *ResponseBroadcastTx) String() string { return proto.CompactTextString(m) } +func (*ResponseBroadcastTx) ProtoMessage() {} +func (*ResponseBroadcastTx) Descriptor() ([]byte, []int) { + return fileDescriptor_0ffff5682c662b95, []int{3} +} +func (m *ResponseBroadcastTx) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResponseBroadcastTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResponseBroadcastTx.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ResponseBroadcastTx) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResponseBroadcastTx.Merge(m, src) +} +func (m *ResponseBroadcastTx) XXX_Size() int { + return m.Size() +} +func (m *ResponseBroadcastTx) XXX_DiscardUnknown() { + xxx_messageInfo_ResponseBroadcastTx.DiscardUnknown(m) +} + +var xxx_messageInfo_ResponseBroadcastTx proto.InternalMessageInfo + +func (m *ResponseBroadcastTx) GetCheckTx() *types.ResponseCheckTx { + if m != nil { + return m.CheckTx + } + return nil +} + +func (m *ResponseBroadcastTx) GetTxResult() *types.ExecTxResult { + if m != nil { + return m.TxResult + } + return nil +} + +func init() { + proto.RegisterType((*RequestPing)(nil), "tendermint.rpc.grpc.RequestPing") + proto.RegisterType((*RequestBroadcastTx)(nil), "tendermint.rpc.grpc.RequestBroadcastTx") + proto.RegisterType((*ResponsePing)(nil), "tendermint.rpc.grpc.ResponsePing") + proto.RegisterType((*ResponseBroadcastTx)(nil), "tendermint.rpc.grpc.ResponseBroadcastTx") +} + +func init() { proto.RegisterFile("tendermint/rpc/grpc/types.proto", fileDescriptor_0ffff5682c662b95) } + +var fileDescriptor_0ffff5682c662b95 = []byte{ + // 324 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x31, 0x4f, 0x02, 0x31, + 0x14, 0xc7, 0x29, 0x31, 0x8a, 0x05, 0x19, 0xca, 0x42, 0x30, 0x9e, 0x48, 0x4c, 0x64, 0x2a, 0x09, + 0x6e, 0x32, 0x89, 0x31, 0xd1, 0xb8, 0x90, 0x86, 0xc9, 0x05, 0xb9, 0xf2, 0x84, 0x8b, 0x72, 0x3d, + 0xdb, 0x47, 0x52, 0xbf, 0x84, 0xf1, 0x0b, 0xb9, 0x3b, 0x32, 0x3a, 0x1a, 0xf8, 0x22, 0xa6, 0x27, + 0x27, 0x35, 0x46, 0x96, 0xe6, 0xdf, 0xe6, 0xff, 0x7b, 0xfd, 0xbf, 0xd7, 0xd2, 0x43, 0x84, 0x78, + 0x04, 0x7a, 0x1a, 0xc5, 0xd8, 0xd2, 0x89, 0x6c, 0x8d, 0xdd, 0x82, 0xcf, 0x09, 0x18, 0x9e, 0x68, + 0x85, 0x8a, 0x55, 0xd6, 0x06, 0xae, 0x13, 0xc9, 0x9d, 0xa1, 0xb6, 0xef, 0x51, 0xc3, 0x50, 0x46, + 0x3e, 0xd1, 0xd8, 0xa3, 0x45, 0x01, 0x4f, 0x33, 0x30, 0xd8, 0x8b, 0xe2, 0x71, 0xe3, 0x98, 0xb2, + 0xd5, 0xb6, 0xab, 0xd5, 0x70, 0x24, 0x87, 0x06, 0xfb, 0x96, 0x95, 0x69, 0x1e, 0x6d, 0x95, 0xd4, + 0x49, 0xb3, 0x24, 0xf2, 0x68, 0x1b, 0x65, 0x5a, 0x12, 0x60, 0x12, 0x15, 0x1b, 0x48, 0xa9, 0x17, + 0x42, 0x2b, 0xd9, 0x81, 0xcf, 0x75, 0x68, 0x41, 0x4e, 0x40, 0x3e, 0x0c, 0x56, 0x74, 0xb1, 0x5d, + 0xe7, 0x5e, 0x42, 0x17, 0x86, 0x67, 0xdc, 0x85, 0x33, 0xf6, 0xad, 0xd8, 0x91, 0xdf, 0x82, 0x9d, + 0xd1, 0x5d, 0xb4, 0x03, 0x0d, 0x66, 0xf6, 0x88, 0xd5, 0x7c, 0x4a, 0x1f, 0xfc, 0xa1, 0x2f, 0x2d, + 0xc8, 0xbe, 0x15, 0xa9, 0x49, 0x14, 0x70, 0xa5, 0xda, 0x6f, 0x84, 0x96, 0x7e, 0x82, 0x9c, 0xf7, + 0xae, 0xd9, 0x0d, 0xdd, 0x72, 0x49, 0xd9, 0xaf, 0xfb, 0xb3, 0x09, 0x71, 0x6f, 0x02, 0xb5, 0xa3, + 0x7f, 0x1c, 0xeb, 0x76, 0xd9, 0x1d, 0x2d, 0xfa, 0x5d, 0x9e, 0x6c, 0xaa, 0xe9, 0x19, 0x6b, 0xcd, + 0x8d, 0xa5, 0x3d, 0x67, 0xf7, 0xea, 0x7d, 0x11, 0x90, 0xf9, 0x22, 0x20, 0x9f, 0x8b, 0x80, 0xbc, + 0x2e, 0x83, 0xdc, 0x7c, 0x19, 0xe4, 0x3e, 0x96, 0x41, 0xee, 0x96, 0x8f, 0x23, 0x9c, 0xcc, 0x42, + 0x2e, 0xd5, 0xb4, 0x25, 0xd5, 0x14, 0x30, 0xbc, 0xc7, 0xb5, 0xc8, 0x3e, 0x45, 0x47, 0x2a, 0x0d, + 0x4e, 0x84, 0xdb, 0xe9, 0x33, 0x9f, 0x7e, 0x05, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xca, 0xdb, 0xe7, + 0x3b, 0x02, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// BroadcastAPIClient is the client API for BroadcastAPI service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type BroadcastAPIClient interface { + Ping(ctx context.Context, in *RequestPing, opts ...grpc.CallOption) (*ResponsePing, error) + BroadcastTx(ctx context.Context, in *RequestBroadcastTx, opts ...grpc.CallOption) (*ResponseBroadcastTx, error) +} + +type broadcastAPIClient struct { + cc grpc1.ClientConn +} + +func NewBroadcastAPIClient(cc grpc1.ClientConn) BroadcastAPIClient { + return &broadcastAPIClient{cc} +} + +func (c *broadcastAPIClient) Ping(ctx context.Context, in *RequestPing, opts ...grpc.CallOption) (*ResponsePing, error) { + out := new(ResponsePing) + err := c.cc.Invoke(ctx, "/tendermint.rpc.grpc.BroadcastAPI/Ping", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *broadcastAPIClient) BroadcastTx(ctx context.Context, in *RequestBroadcastTx, opts ...grpc.CallOption) (*ResponseBroadcastTx, error) { + out := new(ResponseBroadcastTx) + err := c.cc.Invoke(ctx, "/tendermint.rpc.grpc.BroadcastAPI/BroadcastTx", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// BroadcastAPIServer is the server API for BroadcastAPI service. +type BroadcastAPIServer interface { + Ping(context.Context, *RequestPing) (*ResponsePing, error) + BroadcastTx(context.Context, *RequestBroadcastTx) (*ResponseBroadcastTx, error) +} + +// UnimplementedBroadcastAPIServer can be embedded to have forward compatible implementations. +type UnimplementedBroadcastAPIServer struct { +} + +func (*UnimplementedBroadcastAPIServer) Ping(ctx context.Context, req *RequestPing) (*ResponsePing, error) { + return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented") +} +func (*UnimplementedBroadcastAPIServer) BroadcastTx(ctx context.Context, req *RequestBroadcastTx) (*ResponseBroadcastTx, error) { + return nil, status.Errorf(codes.Unimplemented, "method BroadcastTx not implemented") +} + +func RegisterBroadcastAPIServer(s grpc1.Server, srv BroadcastAPIServer) { + s.RegisterService(&_BroadcastAPI_serviceDesc, srv) +} + +func _BroadcastAPI_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestPing) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(BroadcastAPIServer).Ping(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.rpc.grpc.BroadcastAPI/Ping", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(BroadcastAPIServer).Ping(ctx, req.(*RequestPing)) + } + return interceptor(ctx, in, info, handler) +} + +func _BroadcastAPI_BroadcastTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestBroadcastTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(BroadcastAPIServer).BroadcastTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/tendermint.rpc.grpc.BroadcastAPI/BroadcastTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(BroadcastAPIServer).BroadcastTx(ctx, req.(*RequestBroadcastTx)) + } + return interceptor(ctx, in, info, handler) +} + +var BroadcastAPI_serviceDesc = _BroadcastAPI_serviceDesc +var _BroadcastAPI_serviceDesc = grpc.ServiceDesc{ + ServiceName: "tendermint.rpc.grpc.BroadcastAPI", + HandlerType: (*BroadcastAPIServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Ping", + Handler: _BroadcastAPI_Ping_Handler, + }, + { + MethodName: "BroadcastTx", + Handler: _BroadcastAPI_BroadcastTx_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "tendermint/rpc/grpc/types.proto", +} + +func (m *RequestPing) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestPing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestPing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *RequestBroadcastTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RequestBroadcastTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RequestBroadcastTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Tx) > 0 { + i -= len(m.Tx) + copy(dAtA[i:], m.Tx) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResponsePing) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponsePing) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponsePing) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *ResponseBroadcastTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResponseBroadcastTx) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResponseBroadcastTx) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TxResult != nil { + { + size, err := m.TxResult.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.CheckTx != nil { + { + size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *RequestPing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *RequestBroadcastTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Tx) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ResponsePing) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *ResponseBroadcastTx) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CheckTx != nil { + l = m.CheckTx.Size() + n += 1 + l + sovTypes(uint64(l)) + } + if m.TxResult != nil { + l = m.TxResult.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *RequestPing) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestPing: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestPing: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RequestBroadcastTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RequestBroadcastTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RequestBroadcastTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...) + if m.Tx == nil { + m.Tx = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponsePing) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponsePing: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponsePing: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResponseBroadcastTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResponseBroadcastTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResponseBroadcastTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CheckTx == nil { + m.CheckTx = &types.ResponseCheckTx{} + } + if err := m.CheckTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxResult", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.TxResult == nil { + m.TxResult = &types.ExecTxResult{} + } + if err := m.TxResult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/rpc/jsonrpc/client/args_test.go b/rpc/jsonrpc/client/args_test.go new file mode 100644 index 0000000..659391a --- /dev/null +++ b/rpc/jsonrpc/client/args_test.go @@ -0,0 +1,39 @@ +package client + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type Tx []byte + +type Foo struct { + Bar int + Baz string +} + +func TestArgToJSON(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + cases := []struct { + input interface{} + expected string + }{ + {[]byte("1234"), "0x31323334"}, + {Tx("654"), "0x363534"}, + {Foo{7, "hello"}, `{"Bar":"7","Baz":"hello"}`}, + } + + for i, tc := range cases { + args := map[string]interface{}{"data": tc.input} + err := argsToJSON(args) + require.Nil(err, "%d: %+v", i, err) + require.Equal(1, len(args), "%d", i) + data, ok := args["data"].(string) + require.True(ok, "%d: %#v", i, args["data"]) + assert.Equal(tc.expected, data, "%d", i) + } +} diff --git a/rpc/jsonrpc/client/decode.go b/rpc/jsonrpc/client/decode.go new file mode 100644 index 0000000..f38df3f --- /dev/null +++ b/rpc/jsonrpc/client/decode.go @@ -0,0 +1,154 @@ +package client + +import ( + "encoding/json" + "errors" + "fmt" + + cmtjson "github.com/cometbft/cometbft/libs/json" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func unmarshalResponseBytes( + responseBytes []byte, + expectedID types.JSONRPCIntID, + result interface{}, +) (interface{}, error) { + + // Read response. If rpc/core/types is imported, the result will unmarshal + // into the correct type. + response := &types.RPCResponse{} + if err := json.Unmarshal(responseBytes, response); err != nil { + return nil, fmt.Errorf("error unmarshalling: %w", err) + } + + if response.Error != nil { + return nil, response.Error + } + + if err := validateAndVerifyID(response, expectedID); err != nil { + return nil, fmt.Errorf("wrong ID: %w", err) + } + + // Unmarshal the RawMessage into the result. + if err := cmtjson.Unmarshal(response.Result, result); err != nil { + return nil, fmt.Errorf("error unmarshalling result: %w", err) + } + + return result, nil +} + +// Separate the unmarshalling actions using different functions to improve readability and maintainability. +func unmarshalIndividualResponse(responseBytes []byte) (types.RPCResponse, error) { + var singleResponse types.RPCResponse + err := json.Unmarshal(responseBytes, &singleResponse) + return singleResponse, err +} + +func unmarshalMultipleResponses(responseBytes []byte) ([]types.RPCResponse, error) { + var responses []types.RPCResponse + err := json.Unmarshal(responseBytes, &responses) + return responses, err +} + +func unmarshalResponseBytesArray( + responseBytes []byte, + expectedIDs []types.JSONRPCIntID, + results []interface{}, +) ([]interface{}, error) { + + var ( + responses []types.RPCResponse + ) + + // Try to unmarshal as multiple responses + responses, err := unmarshalMultipleResponses(responseBytes) + // if err == nil it could unmarshal in multiple responses + if err == nil { + // No response error checking here as there may be a mixture of successful + // and unsuccessful responses. + + if len(results) != len(responses) { + return nil, fmt.Errorf( + "expected %d result objects into which to inject responses, but got %d", + len(responses), + len(results), + ) + } + + // Intersect IDs from responses with expectedIDs. + ids := make([]types.JSONRPCIntID, len(responses)) + var ok bool + for i, resp := range responses { + ids[i], ok = resp.ID.(types.JSONRPCIntID) + if !ok { + return nil, fmt.Errorf("expected JSONRPCIntID, got %T", resp.ID) + } + } + if err := validateResponseIDs(ids, expectedIDs); err != nil { + return nil, fmt.Errorf("wrong IDs: %w", err) + } + + for i := 0; i < len(responses); i++ { + if err := cmtjson.Unmarshal(responses[i].Result, results[i]); err != nil { + return nil, fmt.Errorf("error unmarshalling #%d result: %w", i, err) + } + } + + return results, nil + } + // check if it's a single response that should be an error + singleResponse, err := unmarshalIndividualResponse(responseBytes) + if err != nil { + // Here, an error means that even single response unmarshalling failed, + // so return the error. + return nil, fmt.Errorf("error unmarshalling: %w", err) + } + singleResult := make([]any, 0) + if singleResponse.Error != nil { + singleResult = append(singleResult, singleResponse.Error) + } else { + singleResult = append(singleResult, singleResponse.Result) + } + return singleResult, nil +} + +func validateResponseIDs(ids, expectedIDs []types.JSONRPCIntID) error { + m := make(map[types.JSONRPCIntID]bool, len(expectedIDs)) + for _, expectedID := range expectedIDs { + m[expectedID] = true + } + + for i, id := range ids { + if m[id] { + delete(m, id) + } else { + return fmt.Errorf("unsolicited ID #%d: %v", i, id) + } + } + + return nil +} + +// From the JSON-RPC 2.0 spec: +// id: It MUST be the same as the value of the id member in the Request Object. +func validateAndVerifyID(res *types.RPCResponse, expectedID types.JSONRPCIntID) error { + if err := validateResponseID(res.ID); err != nil { + return err + } + if expectedID != res.ID.(types.JSONRPCIntID) { // validateResponseID ensured res.ID has the right type + return fmt.Errorf("response ID (%d) does not match request ID (%d)", res.ID, expectedID) + } + return nil +} + +func validateResponseID(id interface{}) error { + if id == nil { + return errors.New("no ID") + } + _, ok := id.(types.JSONRPCIntID) + if !ok { + return fmt.Errorf("expected JSONRPCIntID, but got: %T", id) + } + return nil +} diff --git a/rpc/jsonrpc/client/encode.go b/rpc/jsonrpc/client/encode.go new file mode 100644 index 0000000..e313842 --- /dev/null +++ b/rpc/jsonrpc/client/encode.go @@ -0,0 +1,46 @@ +package client + +import ( + "fmt" + "net/url" + "reflect" + + cmtjson "github.com/cometbft/cometbft/libs/json" +) + +func argsToURLValues(args map[string]interface{}) (url.Values, error) { + values := make(url.Values) + if len(args) == 0 { + return values, nil + } + + err := argsToJSON(args) + if err != nil { + return nil, err + } + + for key, val := range args { + values.Set(key, val.(string)) + } + + return values, nil +} + +func argsToJSON(args map[string]interface{}) error { + for k, v := range args { + rt := reflect.TypeOf(v) + isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8 + if isByteSlice { + bytes := reflect.ValueOf(v).Bytes() + args[k] = fmt.Sprintf("0x%X", bytes) + continue + } + + data, err := cmtjson.Marshal(v) + if err != nil { + return err + } + args[k] = string(data) + } + return nil +} diff --git a/rpc/jsonrpc/client/http_json_client.go b/rpc/jsonrpc/client/http_json_client.go new file mode 100644 index 0000000..a40663b --- /dev/null +++ b/rpc/jsonrpc/client/http_json_client.go @@ -0,0 +1,435 @@ +package client + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "regexp" + "strings" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +const ( + protoHTTP = "http" + protoHTTPS = "https" + protoWSS = "wss" + protoWS = "ws" + protoTCP = "tcp" + protoUNIX = "unix" +) + +var endsWithPortPattern = regexp.MustCompile(`:[0-9]+$`) + +//------------------------------------------------------------- + +// Parsed URL structure +type parsedURL struct { + url.URL + + isUnixSocket bool +} + +// Parse URL and set defaults +func newParsedURL(remoteAddr string) (*parsedURL, error) { + u, err := url.Parse(remoteAddr) + if err != nil { + return nil, err + } + + // default to tcp if nothing specified + if u.Scheme == "" { + u.Scheme = protoTCP + } + + pu := &parsedURL{ + URL: *u, + isUnixSocket: false, + } + + if u.Scheme == protoUNIX { + pu.isUnixSocket = true + } + + return pu, nil +} + +// Change protocol to HTTP for unknown protocols and TCP protocol - useful for RPC connections +func (u *parsedURL) SetDefaultSchemeHTTP() { + // protocol to use for http operations, to support both http and https + switch u.Scheme { + case protoHTTP, protoHTTPS, protoWS, protoWSS: + // known protocols not changed + default: + // default to http for unknown protocols (ex. tcp) + u.Scheme = protoHTTP + } +} + +// Get full address without the protocol - useful for Dialer connections +func (u parsedURL) GetHostWithPath() string { + // Remove protocol, userinfo and # fragment, assume opaque is empty + return u.Host + u.EscapedPath() +} + +// Get a trimmed address - useful for WS connections +func (u parsedURL) GetTrimmedHostWithPath() string { + // if it's not an unix socket we return the normal URL + if !u.isUnixSocket { + return u.GetHostWithPath() + } + // if it's a unix socket we replace the host slashes with a period + // this is because otherwise the http.Client would think that the + // domain is invalid. + return strings.ReplaceAll(u.GetHostWithPath(), "/", ".") +} + +// GetDialAddress returns the endpoint to dial for the parsed URL +func (u parsedURL) GetDialAddress() string { + // if it's not a unix socket we return the host with port, example: localhost:443 + if !u.isUnixSocket { + hasPort := endsWithPortPattern.MatchString(u.Host) + if !hasPort { + // http and ws default to port 80, https and wss default to port 443 + // https://www.rfc-editor.org/rfc/rfc9110#section-4.2 + // https://www.rfc-editor.org/rfc/rfc6455.html#section-3 + switch u.Scheme { + case protoHTTP, protoWS: + return u.Host + `:80` + case protoHTTPS, protoWSS: + return u.Host + `:443` + } + } + return u.Host + } + // otherwise we return the path of the unix socket, ex /tmp/socket + return u.GetHostWithPath() +} + +// Get a trimmed address with protocol - useful as address in RPC connections +func (u parsedURL) GetTrimmedURL() string { + return u.Scheme + "://" + u.GetTrimmedHostWithPath() +} + +//------------------------------------------------------------- + +// HTTPClient is a common interface for JSON-RPC HTTP clients. +type HTTPClient interface { + // Call calls the given method with the params and returns a result. + Call(ctx context.Context, method string, params map[string]interface{}, result interface{}) (interface{}, error) +} + +// Caller implementers can facilitate calling the JSON-RPC endpoint. +type Caller interface { + Call(ctx context.Context, method string, params map[string]interface{}, result interface{}) (interface{}, error) +} + +//------------------------------------------------------------- + +// Client is a JSON-RPC client, which sends POST HTTP requests to the +// remote server. +// +// Client is safe for concurrent use by multiple goroutines. +type Client struct { + address string + username string + password string + + client *http.Client + + mtx cmtsync.Mutex + nextReqID int +} + +var _ HTTPClient = (*Client)(nil) + +// Both Client and RequestBatch can facilitate calls to the JSON +// RPC endpoint. +var _ Caller = (*Client)(nil) +var _ Caller = (*RequestBatch)(nil) + +var _ fmt.Stringer = (*Client)(nil) + +// New returns a Client pointed at the given address. +// An error is returned on invalid remote. The function panics when remote is nil. +func New(remote string) (*Client, error) { + httpClient, err := DefaultHTTPClient(remote) + if err != nil { + return nil, err + } + return NewWithHTTPClient(remote, httpClient) +} + +// NewWithHTTPClient returns a Client pointed at the given +// address using a custom http client. An error is returned on invalid remote. +// The function panics when remote is nil. +func NewWithHTTPClient(remote string, client *http.Client) (*Client, error) { + if client == nil { + panic("nil http.Client provided") + } + + parsedURL, err := newParsedURL(remote) + if err != nil { + return nil, fmt.Errorf("invalid remote %s: %s", remote, err) + } + + parsedURL.SetDefaultSchemeHTTP() + + address := parsedURL.GetTrimmedURL() + username := parsedURL.User.Username() + password, _ := parsedURL.User.Password() + + rpcClient := &Client{ + address: address, + username: username, + password: password, + client: client, + } + + return rpcClient, nil +} + +// Call issues a POST HTTP request. Requests are JSON encoded. Content-Type: +// application/json. +func (c *Client) Call( + ctx context.Context, + method string, + params map[string]interface{}, + result interface{}, +) (interface{}, error) { + id := c.nextRequestID() + + request, err := types.MapToRequest(id, method, params) + if err != nil { + return nil, fmt.Errorf("failed to encode params: %w", err) + } + + requestBytes, err := json.Marshal(request) + if err != nil { + return nil, fmt.Errorf("failed to marshal request: %w", err) + } + + requestBuf := bytes.NewBuffer(requestBytes) + httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, c.address, requestBuf) + if err != nil { + return nil, fmt.Errorf("request failed: %w", err) + } + + httpRequest.Header.Set("Content-Type", "application/json") + + if c.username != "" || c.password != "" { + httpRequest.SetBasicAuth(c.username, c.password) + } + + httpResponse, err := c.client.Do(httpRequest) + if err != nil { + return nil, fmt.Errorf("post failed: %w", err) + } + defer httpResponse.Body.Close() + + responseBytes, err := io.ReadAll(httpResponse.Body) + if err != nil { + return nil, fmt.Errorf("%s. Failed to read response body: %w", getHTTPRespErrPrefix(httpResponse), err) + } + + res, err := unmarshalResponseBytes(responseBytes, id, result) + if err != nil { + return nil, fmt.Errorf("%s. %w", getHTTPRespErrPrefix(httpResponse), err) + } + return res, nil +} + +func getHTTPRespErrPrefix(resp *http.Response) string { + return fmt.Sprintf("error in json rpc client, with http response metadata: (Status: %s, Protocol %s)", resp.Status, resp.Proto) +} + +func (c *Client) String() string { + return fmt.Sprintf("&Client{user=%v, addr=%v, client=%v, nextReqID=%v}", c.username, c.address, c.client, c.nextReqID) +} + +// NewRequestBatch starts a batch of requests for this client. +func (c *Client) NewRequestBatch() *RequestBatch { + return &RequestBatch{ + requests: make([]*jsonRPCBufferedRequest, 0), + client: c, + } +} + +func (c *Client) sendBatch(ctx context.Context, requests []*jsonRPCBufferedRequest) ([]interface{}, error) { + reqs := make([]types.RPCRequest, 0, len(requests)) + results := make([]interface{}, 0, len(requests)) + for _, req := range requests { + reqs = append(reqs, req.request) + results = append(results, req.result) + } + + // serialize the array of requests into a single JSON object + requestBytes, err := json.Marshal(reqs) + if err != nil { + return nil, fmt.Errorf("json marshal: %w", err) + } + + httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, c.address, bytes.NewBuffer(requestBytes)) + if err != nil { + return nil, fmt.Errorf("new request: %w", err) + } + + httpRequest.Header.Set("Content-Type", "application/json") + + if c.username != "" || c.password != "" { + httpRequest.SetBasicAuth(c.username, c.password) + } + + httpResponse, err := c.client.Do(httpRequest) + if err != nil { + return nil, fmt.Errorf("post: %w", err) + } + + defer httpResponse.Body.Close() + + responseBytes, err := io.ReadAll(httpResponse.Body) + if err != nil { + return nil, fmt.Errorf("read response body: %w", err) + } + + // collect ids to check responses IDs in unmarshalResponseBytesArray + ids := make([]types.JSONRPCIntID, len(requests)) + for i, req := range requests { + ids[i] = req.request.ID.(types.JSONRPCIntID) + } + + return unmarshalResponseBytesArray(responseBytes, ids, results) +} + +func (c *Client) nextRequestID() types.JSONRPCIntID { + c.mtx.Lock() + id := c.nextReqID + c.nextReqID++ + c.mtx.Unlock() + return types.JSONRPCIntID(id) +} + +//------------------------------------------------------------------------------------ + +// jsonRPCBufferedRequest encapsulates a single buffered request, as well as its +// anticipated response structure. +type jsonRPCBufferedRequest struct { + request types.RPCRequest + result interface{} // The result will be deserialized into this object. +} + +// RequestBatch allows us to buffer multiple request/response structures +// into a single batch request. Note that this batch acts like a FIFO queue, and +// is thread-safe. +type RequestBatch struct { + client *Client + + mtx cmtsync.Mutex + requests []*jsonRPCBufferedRequest +} + +// Count returns the number of enqueued requests waiting to be sent. +func (b *RequestBatch) Count() int { + b.mtx.Lock() + defer b.mtx.Unlock() + return len(b.requests) +} + +func (b *RequestBatch) enqueue(req *jsonRPCBufferedRequest) { + b.mtx.Lock() + defer b.mtx.Unlock() + b.requests = append(b.requests, req) +} + +// Clear empties out the request batch. +func (b *RequestBatch) Clear() int { + b.mtx.Lock() + defer b.mtx.Unlock() + return b.clear() +} + +func (b *RequestBatch) clear() int { + count := len(b.requests) + b.requests = make([]*jsonRPCBufferedRequest, 0) + return count +} + +// Send will attempt to send the current batch of enqueued requests, and then +// will clear out the requests once done. On success, this returns the +// deserialized list of results from each of the enqueued requests. +func (b *RequestBatch) Send(ctx context.Context) ([]interface{}, error) { + b.mtx.Lock() + defer func() { + b.clear() + b.mtx.Unlock() + }() + return b.client.sendBatch(ctx, b.requests) +} + +// Call enqueues a request to call the given RPC method with the specified +// parameters, in the same way that the `Client.Call` function would. +func (b *RequestBatch) Call( + _ context.Context, + method string, + params map[string]interface{}, + result interface{}, +) (interface{}, error) { + id := b.client.nextRequestID() + request, err := types.MapToRequest(id, method, params) + if err != nil { + return nil, err + } + b.enqueue(&jsonRPCBufferedRequest{request: request, result: result}) + return result, nil +} + +//------------------------------------------------------------- + +func makeHTTPDialer(remoteAddr string) (func(string, string) (net.Conn, error), error) { + u, err := newParsedURL(remoteAddr) + if err != nil { + return nil, err + } + + protocol := u.Scheme + + // accept http(s) as an alias for tcp + switch protocol { + case protoHTTP, protoHTTPS: + protocol = protoTCP + } + + dialFn := func(proto, addr string) (net.Conn, error) { + return net.Dial(protocol, u.GetDialAddress()) + } + + return dialFn, nil +} + +// DefaultHTTPClient is used to create an http client with some default parameters. +// We overwrite the http.Client.Dial so we can do http over tcp or unix. +// remoteAddr should be fully featured (eg. with tcp:// or unix://). +// An error will be returned in case of invalid remoteAddr. +func DefaultHTTPClient(remoteAddr string) (*http.Client, error) { + dialFn, err := makeHTTPDialer(remoteAddr) + if err != nil { + return nil, err + } + + client := &http.Client{ + Transport: &http.Transport{ + // Set to true to prevent GZIP-bomb DoS attacks + DisableCompression: true, + Dial: dialFn, + Proxy: http.ProxyFromEnvironment, + }, + } + + return client, nil +} diff --git a/rpc/jsonrpc/client/http_json_client_test.go b/rpc/jsonrpc/client/http_json_client_test.go new file mode 100644 index 0000000..f66a9dd --- /dev/null +++ b/rpc/jsonrpc/client/http_json_client_test.go @@ -0,0 +1,100 @@ +package client + +import ( + "io" + "log" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestHTTPClientMakeHTTPDialer(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("Hi!\n")) + }) + ts := httptest.NewServer(handler) + defer ts.Close() + + tsTLS := httptest.NewTLSServer(handler) + defer tsTLS.Close() + // This silences a TLS handshake error, caused by the dialer just immediately + // disconnecting, which we can just ignore. + tsTLS.Config.ErrorLog = log.New(io.Discard, "", 0) + + for _, testURL := range []string{ts.URL, tsTLS.URL} { + u, err := newParsedURL(testURL) + require.NoError(t, err) + dialFn, err := makeHTTPDialer(testURL) + require.Nil(t, err) + + addr, err := dialFn(u.Scheme, u.GetHostWithPath()) + require.NoError(t, err) + require.NotNil(t, addr) + } +} + +func Test_parsedURL(t *testing.T) { + type test struct { + url string + expectedURL string + expectedHostWithPath string + expectedDialAddress string + } + + tests := map[string]test{ + "unix endpoint": { + url: "unix:///tmp/test", + expectedURL: "unix://.tmp.test", + expectedHostWithPath: "/tmp/test", + expectedDialAddress: "/tmp/test", + }, + + "http endpoint": { + url: "http://example.com", + expectedURL: "http://example.com", + expectedHostWithPath: "example.com", + expectedDialAddress: "example.com:80", + }, + + "http endpoint with port": { + url: "http://example.com:8080", + expectedURL: "http://example.com:8080", + expectedHostWithPath: "example.com:8080", + expectedDialAddress: "example.com:8080", + }, + + "https endpoint": { + url: "https://example.com", + expectedURL: "https://example.com", + expectedHostWithPath: "example.com", + expectedDialAddress: "example.com:443", + }, + + "https endpoint with port": { + url: "https://example.com:8080", + expectedURL: "https://example.com:8080", + expectedHostWithPath: "example.com:8080", + expectedDialAddress: "example.com:8080", + }, + + "https path routed endpoint": { + url: "https://example.com:8080/rpc", + expectedURL: "https://example.com:8080/rpc", + expectedHostWithPath: "example.com:8080/rpc", + expectedDialAddress: "example.com:8080", + }, + } + + for name, tt := range tests { + tt := tt // suppressing linter + t.Run(name, func(t *testing.T) { + parsed, err := newParsedURL(tt.url) + require.NoError(t, err) + require.Equal(t, tt.expectedDialAddress, parsed.GetDialAddress()) + require.Equal(t, tt.expectedURL, parsed.GetTrimmedURL()) + require.Equal(t, tt.expectedHostWithPath, parsed.GetHostWithPath()) + }) + } +} diff --git a/rpc/jsonrpc/client/http_uri_client.go b/rpc/jsonrpc/client/http_uri_client.go new file mode 100644 index 0000000..89bdcf3 --- /dev/null +++ b/rpc/jsonrpc/client/http_uri_client.go @@ -0,0 +1,85 @@ +package client + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +const ( + // URIClientRequestID in a request ID used by URIClient + URIClientRequestID = types.JSONRPCIntID(-1) +) + +// URIClient is a JSON-RPC client, which sends POST form HTTP requests to the +// remote server. +// +// URIClient is safe for concurrent use by multiple goroutines. +type URIClient struct { + address string + client *http.Client +} + +var _ HTTPClient = (*URIClient)(nil) + +// NewURI returns a new client. +// An error is returned on invalid remote. +// The function panics when remote is nil. +func NewURI(remote string) (*URIClient, error) { + parsedURL, err := newParsedURL(remote) + if err != nil { + return nil, err + } + + httpClient, err := DefaultHTTPClient(remote) + if err != nil { + return nil, err + } + + parsedURL.SetDefaultSchemeHTTP() + + uriClient := &URIClient{ + address: parsedURL.GetTrimmedURL(), + client: httpClient, + } + + return uriClient, nil +} + +// Call issues a POST form HTTP request. +func (c *URIClient) Call(ctx context.Context, method string, + params map[string]interface{}, result interface{}) (interface{}, error) { + + values, err := argsToURLValues(params) + if err != nil { + return nil, fmt.Errorf("failed to encode params: %w", err) + } + + req, err := http.NewRequestWithContext( + ctx, + http.MethodPost, + c.address+"/"+method, + strings.NewReader(values.Encode()), + ) + if err != nil { + return nil, fmt.Errorf("new request: %w", err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("post: %w", err) + } + defer resp.Body.Close() + + responseBytes, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read response body: %w", err) + } + + return unmarshalResponseBytes(responseBytes, URIClientRequestID, result) +} diff --git a/rpc/jsonrpc/client/integration_test.go b/rpc/jsonrpc/client/integration_test.go new file mode 100644 index 0000000..9e996f7 --- /dev/null +++ b/rpc/jsonrpc/client/integration_test.go @@ -0,0 +1,69 @@ +//go:build release +// +build release + +// The code in here is comprehensive as an integration +// test and is long, hence is only run before releases. + +package client + +import ( + "bytes" + "errors" + "net" + "regexp" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" +) + +func TestWSClientReconnectWithJitter(t *testing.T) { + n := 8 + maxReconnectAttempts := 3 + // Max wait time is ceil(1+0.999) + ceil(2+0.999) + ceil(4+0.999) + ceil(...) = 2 + 3 + 5 = 10s + ... + maxSleepTime := time.Second * time.Duration(((1< c.maxReconnectAttempts { + return fmt.Errorf("reached maximum reconnect attempts: %w", err) + } + } +} + +func (c *WSClient) startReadWriteRoutines() { + c.wg.Add(2) + c.readRoutineQuit = make(chan struct{}) + go c.readRoutine() + go c.writeRoutine() +} + +func (c *WSClient) processBacklog() error { + select { + case request := <-c.backlog: + if c.writeWait > 0 { + if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil { + c.Logger.Error("failed to set write deadline", "err", err) + } + } + if err := c.conn.WriteJSON(request); err != nil { + c.Logger.Error("failed to resend request", "err", err) + c.reconnectAfter <- err + // requeue request + c.backlog <- request + return err + } + c.Logger.Info("resend a request", "req", request) + default: + } + return nil +} + +func (c *WSClient) reconnectRoutine() { + for { + select { + case originalError := <-c.reconnectAfter: + // wait until writeRoutine and readRoutine finish + c.wg.Wait() + if err := c.reconnect(); err != nil { + c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError) + if err = c.Stop(); err != nil { + c.Logger.Error("failed to stop conn", "error", err) + } + + return + } + // drain reconnectAfter + LOOP: + for { + select { + case <-c.reconnectAfter: + default: + break LOOP + } + } + err := c.processBacklog() + if err == nil { + c.startReadWriteRoutines() + } + + case <-c.Quit(): + return + } + } +} + +// The client ensures that there is at most one writer to a connection by +// executing all writes from this goroutine. +func (c *WSClient) writeRoutine() { + var ticker *time.Ticker + if c.pingPeriod > 0 { + // ticker with a predefined period + ticker = time.NewTicker(c.pingPeriod) + } else { + // ticker that never fires + ticker = &time.Ticker{C: make(<-chan time.Time)} + } + + defer func() { + ticker.Stop() + c.conn.Close() + // err != nil { + // ignore error; it will trigger in tests + // likely because it's closing an already closed connection + // } + c.wg.Done() + }() + + for { + select { + case request := <-c.send: + if c.writeWait > 0 { + if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil { + c.Logger.Error("failed to set write deadline", "err", err) + } + } + if err := c.conn.WriteJSON(request); err != nil { + c.Logger.Error("failed to send request", "err", err) + c.reconnectAfter <- err + // add request to the backlog, so we don't lose it + c.backlog <- request + return + } + case <-ticker.C: + if c.writeWait > 0 { + if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil { + c.Logger.Error("failed to set write deadline", "err", err) + } + } + if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { + c.Logger.Error("failed to write ping", "err", err) + c.reconnectAfter <- err + return + } + c.mtx.Lock() + c.sentLastPingAt = time.Now() + c.mtx.Unlock() + c.Logger.Debug("sent ping") + case <-c.readRoutineQuit: + return + case <-c.Quit(): + if err := c.conn.WriteMessage( + websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), + ); err != nil { + c.Logger.Error("failed to write message", "err", err) + } + return + } + } +} + +// The client ensures that there is at most one reader to a connection by +// executing all reads from this goroutine. +func (c *WSClient) readRoutine() { + defer func() { + c.conn.Close() + // err != nil { + // ignore error; it will trigger in tests + // likely because it's closing an already closed connection + // } + c.PingPongLatencyTimer.Stop() + c.wg.Done() + }() + + c.conn.SetPongHandler(func(string) error { + // gather latency stats + c.mtx.RLock() + t := c.sentLastPingAt + c.mtx.RUnlock() + c.PingPongLatencyTimer.UpdateSince(t) + + c.Logger.Debug("got pong") + return nil + }) + + for { + // reset deadline for every message type (control or data) + if c.readWait > 0 { + if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil { + c.Logger.Error("failed to set read deadline", "err", err) + } + } + _, data, err := c.conn.ReadMessage() + if err != nil { + if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) { + return + } + + c.Logger.Error("failed to read response", "err", err) + close(c.readRoutineQuit) + c.reconnectAfter <- err + return + } + + var response types.RPCResponse + err = json.Unmarshal(data, &response) + if err != nil { + c.Logger.Error("failed to parse response", "err", err, "data", string(data)) + continue + } + + if err = validateResponseID(response.ID); err != nil { + c.Logger.Error("error in response ID", "id", response.ID, "err", err) + continue + } + + // TODO: events resulting from /subscribe do not work with -> + // because they are implemented as responses with the subscribe request's + // ID. According to the spec, they should be notifications (requests + // without IDs). + // https://github.com/tendermint/tendermint/issues/2949 + // c.mtx.Lock() + // if _, ok := c.sentIDs[response.ID.(types.JSONRPCIntID)]; !ok { + // c.Logger.Error("unsolicited response ID", "id", response.ID, "expected", c.sentIDs) + // c.mtx.Unlock() + // continue + // } + // delete(c.sentIDs, response.ID.(types.JSONRPCIntID)) + // c.mtx.Unlock() + // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking + // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop + // both readRoutine and writeRoutine + + c.Logger.Info("got response", "id", response.ID, "result", log.NewLazySprintf("%X", response.Result)) + + select { + case <-c.Quit(): + case c.ResponsesCh <- response: + } + } +} + +// Predefined methods + +// Subscribe to a query. Note the server must have a "subscribe" route +// defined. +func (c *WSClient) Subscribe(ctx context.Context, query string) error { + params := map[string]interface{}{"query": query} + return c.Call(ctx, "subscribe", params) +} + +// Unsubscribe from a query. Note the server must have a "unsubscribe" route +// defined. +func (c *WSClient) Unsubscribe(ctx context.Context, query string) error { + params := map[string]interface{}{"query": query} + return c.Call(ctx, "unsubscribe", params) +} + +// UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route +// defined. +func (c *WSClient) UnsubscribeAll(ctx context.Context) error { + params := map[string]interface{}{} + return c.Call(ctx, "unsubscribe_all", params) +} diff --git a/rpc/jsonrpc/client/ws_client_test.go b/rpc/jsonrpc/client/ws_client_test.go new file mode 100644 index 0000000..c2e996d --- /dev/null +++ b/rpc/jsonrpc/client/ws_client_test.go @@ -0,0 +1,233 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +var wsCallTimeout = 5 * time.Second + +type myHandler struct { + closeConnAfterRead bool + mtx cmtsync.RWMutex +} + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + panic(err) + } + defer conn.Close() + for { + messageType, in, err := conn.ReadMessage() + if err != nil { + return + } + + var req types.RPCRequest + err = json.Unmarshal(in, &req) + if err != nil { + panic(err) + } + + h.mtx.RLock() + if h.closeConnAfterRead { + if err := conn.Close(); err != nil { + panic(err) + } + } + h.mtx.RUnlock() + + res := json.RawMessage(`{}`) + emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: res, ID: req.ID}) + if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil { + return + } + } +} + +func TestWSClientReconnectsAfterReadFailure(t *testing.T) { + var wg sync.WaitGroup + + // start server + h := &myHandler{} + s := httptest.NewServer(h) + defer s.Close() + + c := startClient(t, "//"+s.Listener.Addr().String()) + defer c.Stop() //nolint:errcheck // ignore for tests + + wg.Add(1) + go callWgDoneOnResult(t, c, &wg) + + h.mtx.Lock() + h.closeConnAfterRead = true + h.mtx.Unlock() + + // results in WS read error, no send retry because write succeeded + call(t, "a", c) + + // expect to reconnect almost immediately + time.Sleep(10 * time.Millisecond) + h.mtx.Lock() + h.closeConnAfterRead = false + h.mtx.Unlock() + + // should succeed + call(t, "b", c) + + wg.Wait() +} + +func TestWSClientReconnectsAfterWriteFailure(t *testing.T) { + var wg sync.WaitGroup + + // start server + h := &myHandler{} + s := httptest.NewServer(h) + + c := startClient(t, "//"+s.Listener.Addr().String()) + defer c.Stop() //nolint:errcheck // ignore for tests + + wg.Add(2) + go callWgDoneOnResult(t, c, &wg) + + // hacky way to abort the connection before write + if err := c.conn.Close(); err != nil { + t.Error(err) + } + + // results in WS write error, the client should resend on reconnect + call(t, "a", c) + + // expect to reconnect almost immediately + time.Sleep(10 * time.Millisecond) + + // should succeed + call(t, "b", c) + + wg.Wait() +} + +func TestWSClientReconnectFailure(t *testing.T) { + // start server + h := &myHandler{} + s := httptest.NewServer(h) + + c := startClient(t, "//"+s.Listener.Addr().String()) + defer c.Stop() //nolint:errcheck // ignore for tests + + go func() { + for { + select { + case <-c.ResponsesCh: + case <-c.Quit(): + return + } + } + }() + + // hacky way to abort the connection before write + if err := c.conn.Close(); err != nil { + t.Error(err) + } + s.Close() + + // results in WS write error + // provide timeout to avoid blocking + ctx, cancel := context.WithTimeout(context.Background(), wsCallTimeout) + defer cancel() + if err := c.Call(ctx, "a", make(map[string]interface{})); err != nil { + t.Error(err) + } + + // expect to reconnect almost immediately + time.Sleep(10 * time.Millisecond) + + done := make(chan struct{}) + go func() { + // client should block on this + call(t, "b", c) + close(done) + }() + + // test that client blocks on the second send + select { + case <-done: + t.Fatal("client should block on calling 'b' during reconnect") + case <-time.After(5 * time.Second): + t.Log("All good") + } +} + +func TestNotBlockingOnStop(t *testing.T) { + timeout := 2 * time.Second + s := httptest.NewServer(&myHandler{}) + c := startClient(t, "//"+s.Listener.Addr().String()) + c.Call(context.Background(), "a", make(map[string]interface{})) //nolint:errcheck // ignore for tests + // Let the readRoutine get around to blocking + time.Sleep(time.Second) + passCh := make(chan struct{}) + go func() { + // Unless we have a non-blocking write to ResponsesCh from readRoutine + // this blocks forever ont the waitgroup + err := c.Stop() + require.NoError(t, err) + passCh <- struct{}{} + }() + select { + case <-passCh: + // Pass + case <-time.After(timeout): + t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?", + timeout.Seconds()) + } +} + +func startClient(t *testing.T, addr string) *WSClient { + c, err := NewWS(addr, "/websocket") + require.Nil(t, err) + err = c.Start() + require.Nil(t, err) + c.SetLogger(log.TestingLogger()) + return c +} + +func call(t *testing.T, method string, c *WSClient) { + err := c.Call(context.Background(), method, make(map[string]interface{})) + require.NoError(t, err) +} + +func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) { + for { + select { + case resp := <-c.ResponsesCh: + if resp.Error != nil { + t.Errorf("unexpected error: %v", resp.Error) + return + } + if resp.Result != nil { + wg.Done() + } + case <-c.Quit(): + return + } + } +} diff --git a/rpc/jsonrpc/doc.go b/rpc/jsonrpc/doc.go new file mode 100644 index 0000000..1d6c80c --- /dev/null +++ b/rpc/jsonrpc/doc.go @@ -0,0 +1,84 @@ +// HTTP RPC server supporting calls via uri params, jsonrpc over HTTP, and jsonrpc over +// websockets +// +// # Client Requests +// +// Suppose we want to expose the rpc function `HelloWorld(name string, num int)`. +// +// GET (URI) +// +// As a GET request, it would have URI encoded parameters, and look like: +// +// curl 'http://localhost:8008/hello_world?name="my_world"&num=5' +// +// Note the `'` around the url, which is just so bash doesn't ignore the quotes in `"my_world"`. +// This should also work: +// +// curl http://localhost:8008/hello_world?name=\"my_world\"&num=5 +// +// A GET request to `/` returns a list of available endpoints. +// For those which take arguments, the arguments will be listed in order, with `_` where the actual value should be. +// +// POST (JSONRPC) +// +// As a POST request, we use JSONRPC. For instance, the same request would have this as the body: +// +// { +// "jsonrpc": "2.0", +// "id": "anything", +// "method": "hello_world", +// "params": { +// "name": "my_world", +// "num": 5 +// } +// } +// +// With the above saved in file `data.json`, we can make the request with +// +// curl --data @data.json http://localhost:8008 +// +// WebSocket (JSONRPC) +// +// All requests are exposed over websocket in the same form as the POST JSONRPC. +// Websocket connections are available at their own endpoint, typically `/websocket`, +// though this is configurable when starting the server. +// +// # Server Definition +// +// Define some types and routes: +// +// type ResultStatus struct { +// Value string +// } +// +// Define some routes +// +// var Routes = map[string]*rpcserver.RPCFunc{ +// "status": rpcserver.NewRPCFunc(Status, "arg"), +// } +// +// An rpc function: +// +// func Status(v string) (*ResultStatus, error) { +// return &ResultStatus{v}, nil +// } +// +// Now start the server: +// +// mux := http.NewServeMux() +// rpcserver.RegisterRPCFuncs(mux, Routes) +// wm := rpcserver.NewWebsocketManager(Routes) +// mux.HandleFunc("/websocket", wm.WebsocketHandler) +// logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) +// listener, err := rpc.Listen("0.0.0.0:8080", rpcserver.Config{}) +// if err != nil { panic(err) } +// go rpcserver.Serve(listener, mux, logger) +// +// Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:8008`) +// Now see all available endpoints by sending a GET request to `0.0.0.0:8008`. +// Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets. +// +// # Examples +// +// - [CometBFT](https://github.com/cometbft/cometbft/blob/v0.38.x/rpc/core/routes.go) +package jsonrpc diff --git a/rpc/jsonrpc/jsonrpc_test.go b/rpc/jsonrpc/jsonrpc_test.go new file mode 100644 index 0000000..b4a444f --- /dev/null +++ b/rpc/jsonrpc/jsonrpc_test.go @@ -0,0 +1,509 @@ +package jsonrpc + +import ( + "bytes" + "context" + crand "crypto/rand" + "encoding/json" + "fmt" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/log" + cmtrand "github.com/cometbft/cometbft/libs/rand" + + client "github.com/cometbft/cometbft/rpc/jsonrpc/client" + server "github.com/cometbft/cometbft/rpc/jsonrpc/server" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// Client and Server should work over tcp or unix sockets +const ( + tcpAddr = "tcp://127.0.0.1:47768" + + unixSocket = "/tmp/rpc_test.sock" + unixAddr = "unix://" + unixSocket + + websocketEndpoint = "/websocket/endpoint" + + testVal = "acbd" +) + +var ctx = context.Background() + +type ResultEcho struct { + Value string `json:"value"` +} + +type ResultEchoInt struct { + Value int `json:"value"` +} + +type ResultEchoBytes struct { + Value []byte `json:"value"` +} + +type ResultEchoDataBytes struct { + Value cmtbytes.HexBytes `json:"value"` +} + +type ResultEchoWithDefault struct { + Value int `json:"value"` +} + +// Define some routes +var Routes = map[string]*server.RPCFunc{ + "echo": server.NewRPCFunc(EchoResult, "arg"), + "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"), + "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"), + "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg"), + "echo_int": server.NewRPCFunc(EchoIntResult, "arg"), + "echo_default": server.NewRPCFunc(EchoWithDefault, "arg", server.Cacheable("arg")), +} + +func EchoResult(_ *types.Context, v string) (*ResultEcho, error) { + return &ResultEcho{v}, nil +} + +func EchoWSResult(_ *types.Context, v string) (*ResultEcho, error) { + return &ResultEcho{v}, nil +} + +func EchoIntResult(_ *types.Context, v int) (*ResultEchoInt, error) { + return &ResultEchoInt{v}, nil +} + +func EchoBytesResult(_ *types.Context, v []byte) (*ResultEchoBytes, error) { + return &ResultEchoBytes{v}, nil +} + +func EchoDataBytesResult(_ *types.Context, v cmtbytes.HexBytes) (*ResultEchoDataBytes, error) { + return &ResultEchoDataBytes{v}, nil +} + +func EchoWithDefault(_ *types.Context, v *int) (*ResultEchoWithDefault, error) { + val := -1 + if v != nil { + val = *v + } + return &ResultEchoWithDefault{val}, nil +} + +func TestMain(m *testing.M) { + setup() + code := m.Run() + os.Exit(code) +} + +var colorFn = func(keyvals ...interface{}) term.FgBgColor { + for i := 0; i < len(keyvals)-1; i += 2 { + if keyvals[i] == "socket" { + switch keyvals[i+1] { + case "tcp": + return term.FgBgColor{Fg: term.DarkBlue} + case "unix": + return term.FgBgColor{Fg: term.DarkCyan} + } + } + } + return term.FgBgColor{} +} + +// launch unix and tcp servers +func setup() { + logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn) + + cmd := exec.Command("rm", "-f", unixSocket) + err := cmd.Start() + if err != nil { + panic(err) + } + if err = cmd.Wait(); err != nil { + panic(err) + } + + tcpLogger := logger.With("socket", "tcp") + mux := http.NewServeMux() + server.RegisterRPCFuncs(mux, Routes, tcpLogger) + wm := server.NewWebsocketManager(Routes, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second)) + wm.SetLogger(tcpLogger) + mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) + config := server.DefaultConfig() + listener1, err := server.Listen(tcpAddr, config.MaxOpenConnections) + if err != nil { + panic(err) + } + go func() { + if err := server.Serve(listener1, mux, tcpLogger, config); err != nil { + panic(err) + } + }() + + unixLogger := logger.With("socket", "unix") + mux2 := http.NewServeMux() + server.RegisterRPCFuncs(mux2, Routes, unixLogger) + wm = server.NewWebsocketManager(Routes) + wm.SetLogger(unixLogger) + mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler) + listener2, err := server.Listen(unixAddr, config.MaxOpenConnections) + if err != nil { + panic(err) + } + go func() { + if err := server.Serve(listener2, mux2, unixLogger, config); err != nil { + panic(err) + } + }() + + // wait for servers to start + time.Sleep(time.Second * 2) +} + +func echoViaHTTP(cl client.Caller, val string) (string, error) { + params := map[string]interface{}{ + "arg": val, + } + result := new(ResultEcho) + if _, err := cl.Call(ctx, "echo", params, result); err != nil { + return "", err + } + return result.Value, nil +} + +func echoIntViaHTTP(cl client.Caller, val int) (int, error) { + params := map[string]interface{}{ + "arg": val, + } + result := new(ResultEchoInt) + if _, err := cl.Call(ctx, "echo_int", params, result); err != nil { + return 0, err + } + return result.Value, nil +} + +func echoBytesViaHTTP(cl client.Caller, bytes []byte) ([]byte, error) { + params := map[string]interface{}{ + "arg": bytes, + } + result := new(ResultEchoBytes) + if _, err := cl.Call(ctx, "echo_bytes", params, result); err != nil { + return []byte{}, err + } + return result.Value, nil +} + +func echoDataBytesViaHTTP(cl client.Caller, bytes cmtbytes.HexBytes) (cmtbytes.HexBytes, error) { + params := map[string]interface{}{ + "arg": bytes, + } + result := new(ResultEchoDataBytes) + if _, err := cl.Call(ctx, "echo_data_bytes", params, result); err != nil { + return []byte{}, err + } + return result.Value, nil +} + +func echoWithDefaultViaHTTP(cl client.Caller, v *int) (int, error) { + params := map[string]interface{}{} + if v != nil { + params["arg"] = *v + } + result := new(ResultEchoWithDefault) + if _, err := cl.Call(ctx, "echo_default", params, result); err != nil { + return 0, err + } + return result.Value, nil +} + +func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { + val := testVal + got, err := echoViaHTTP(cl, val) + require.NoError(t, err) + assert.Equal(t, got, val) + + val2 := randBytes(t) + got2, err := echoBytesViaHTTP(cl, val2) + require.NoError(t, err) + assert.Equal(t, got2, val2) + + val3 := cmtbytes.HexBytes(randBytes(t)) + got3, err := echoDataBytesViaHTTP(cl, val3) + require.NoError(t, err) + assert.Equal(t, got3, val3) + + val4 := cmtrand.Intn(10000) + got4, err := echoIntViaHTTP(cl, val4) + require.NoError(t, err) + assert.Equal(t, got4, val4) + + got5, err := echoWithDefaultViaHTTP(cl, nil) + require.NoError(t, err) + assert.Equal(t, got5, -1) + + val6 := cmtrand.Intn(10000) + got6, err := echoWithDefaultViaHTTP(cl, &val6) + require.NoError(t, err) + assert.Equal(t, got6, val6) +} + +func echoViaWS(cl *client.WSClient, val string) (string, error) { + params := map[string]interface{}{ + "arg": val, + } + err := cl.Call(context.Background(), "echo", params) + if err != nil { + return "", err + } + + msg := <-cl.ResponsesCh + if msg.Error != nil { + return "", err + } + result := new(ResultEcho) + err = json.Unmarshal(msg.Result, result) + if err != nil { + return "", nil + } + return result.Value, nil +} + +func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { + params := map[string]interface{}{ + "arg": bytes, + } + err := cl.Call(context.Background(), "echo_bytes", params) + if err != nil { + return []byte{}, err + } + + msg := <-cl.ResponsesCh + if msg.Error != nil { + return []byte{}, msg.Error + } + result := new(ResultEchoBytes) + err = json.Unmarshal(msg.Result, result) + if err != nil { + return []byte{}, nil + } + return result.Value, nil +} + +func testWithWSClient(t *testing.T, cl *client.WSClient) { + val := testVal + got, err := echoViaWS(cl, val) + require.Nil(t, err) + assert.Equal(t, got, val) + + val2 := randBytes(t) + got2, err := echoBytesViaWS(cl, val2) + require.Nil(t, err) + assert.Equal(t, got2, val2) +} + +//------------- + +func TestServersAndClientsBasic(t *testing.T) { + serverAddrs := [...]string{tcpAddr, unixAddr} + for _, addr := range serverAddrs { + cl1, err := client.NewURI(addr) + require.Nil(t, err) + fmt.Printf("=== testing server on %s using URI client", addr) + testWithHTTPClient(t, cl1) + + cl2, err := client.New(addr) + require.Nil(t, err) + fmt.Printf("=== testing server on %s using JSONRPC client", addr) + testWithHTTPClient(t, cl2) + + cl3, err := client.NewWS(addr, websocketEndpoint) + require.Nil(t, err) + cl3.SetLogger(log.TestingLogger()) + err = cl3.Start() + require.Nil(t, err) + fmt.Printf("=== testing server on %s using WS client", addr) + testWithWSClient(t, cl3) + err = cl3.Stop() + require.NoError(t, err) + } +} + +func TestHexStringArg(t *testing.T) { + cl, err := client.NewURI(tcpAddr) + require.Nil(t, err) + // should NOT be handled as hex + val := "0xabc" + got, err := echoViaHTTP(cl, val) + require.Nil(t, err) + assert.Equal(t, got, val) +} + +func TestQuotedStringArg(t *testing.T) { + cl, err := client.NewURI(tcpAddr) + require.Nil(t, err) + // should NOT be unquoted + val := "\"abc\"" + got, err := echoViaHTTP(cl, val) + require.Nil(t, err) + assert.Equal(t, got, val) +} + +func TestWSNewWSRPCFunc(t *testing.T) { + cl, err := client.NewWS(tcpAddr, websocketEndpoint) + require.Nil(t, err) + cl.SetLogger(log.TestingLogger()) + err = cl.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := cl.Stop(); err != nil { + t.Error(err) + } + }) + + val := testVal + params := map[string]interface{}{ + "arg": val, + } + err = cl.Call(context.Background(), "echo_ws", params) + require.Nil(t, err) + + msg := <-cl.ResponsesCh + if msg.Error != nil { + t.Fatal(err) + } + result := new(ResultEcho) + err = json.Unmarshal(msg.Result, result) + require.Nil(t, err) + got := result.Value + assert.Equal(t, got, val) +} + +func TestWSHandlesArrayParams(t *testing.T) { + cl, err := client.NewWS(tcpAddr, websocketEndpoint) + require.Nil(t, err) + cl.SetLogger(log.TestingLogger()) + err = cl.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := cl.Stop(); err != nil { + t.Error(err) + } + }) + + val := testVal + params := []interface{}{val} + err = cl.CallWithArrayParams(context.Background(), "echo_ws", params) + require.Nil(t, err) + + msg := <-cl.ResponsesCh + if msg.Error != nil { + t.Fatalf("%+v", err) + } + result := new(ResultEcho) + err = json.Unmarshal(msg.Result, result) + require.Nil(t, err) + got := result.Value + assert.Equal(t, got, val) +} + +// TestWSClientPingPong checks that a client & server exchange pings +// & pongs so connection stays alive. +func TestWSClientPingPong(t *testing.T) { + cl, err := client.NewWS(tcpAddr, websocketEndpoint) + require.Nil(t, err) + cl.SetLogger(log.TestingLogger()) + err = cl.Start() + require.Nil(t, err) + t.Cleanup(func() { + if err := cl.Stop(); err != nil { + t.Error(err) + } + }) + + time.Sleep(6 * time.Second) +} + +func TestJSONRPCCaching(t *testing.T) { + httpAddr := strings.Replace(tcpAddr, "tcp://", "http://", 1) + cl, err := client.DefaultHTTPClient(httpAddr) + require.NoError(t, err) + + // Not supplying the arg should result in not caching + params := make(map[string]interface{}) + req, err := types.MapToRequest(types.JSONRPCIntID(1000), "echo_default", params) + require.NoError(t, err) + + res1, err := rawJSONRPCRequest(t, cl, httpAddr, req) + defer func() { _ = res1.Body.Close() }() + require.NoError(t, err) + assert.Equal(t, "", res1.Header.Get("Cache-control")) + + // Supplying the arg should result in caching + params["arg"] = cmtrand.Intn(10000) + req, err = types.MapToRequest(types.JSONRPCIntID(1001), "echo_default", params) + require.NoError(t, err) + + res2, err := rawJSONRPCRequest(t, cl, httpAddr, req) + defer func() { _ = res2.Body.Close() }() + require.NoError(t, err) + assert.Equal(t, "public, max-age=86400", res2.Header.Get("Cache-control")) +} + +func rawJSONRPCRequest(t *testing.T, cl *http.Client, url string, req interface{}) (*http.Response, error) { + reqBytes, err := json.Marshal(req) + require.NoError(t, err) + + reqBuf := bytes.NewBuffer(reqBytes) + httpReq, err := http.NewRequest(http.MethodPost, url, reqBuf) + require.NoError(t, err) + + httpReq.Header.Set("Content-type", "application/json") + + return cl.Do(httpReq) +} + +func TestURICaching(t *testing.T) { + httpAddr := strings.Replace(tcpAddr, "tcp://", "http://", 1) + cl, err := client.DefaultHTTPClient(httpAddr) + require.NoError(t, err) + + // Not supplying the arg should result in not caching + args := url.Values{} + res1, err := rawURIRequest(t, cl, httpAddr+"/echo_default", args) + defer func() { _ = res1.Body.Close() }() + require.NoError(t, err) + assert.Equal(t, "", res1.Header.Get("Cache-control")) + + // Supplying the arg should result in caching + args.Set("arg", fmt.Sprintf("%d", cmtrand.Intn(10000))) + res2, err := rawURIRequest(t, cl, httpAddr+"/echo_default", args) + defer func() { _ = res2.Body.Close() }() + require.NoError(t, err) + assert.Equal(t, "public, max-age=86400", res2.Header.Get("Cache-control")) +} + +func rawURIRequest(t *testing.T, cl *http.Client, url string, args url.Values) (*http.Response, error) { + req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(args.Encode())) + require.NoError(t, err) + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + return cl.Do(req) +} + +func randBytes(t *testing.T) []byte { + n := cmtrand.Intn(10) + 2 + buf := make([]byte, n) + _, err := crand.Read(buf) + require.Nil(t, err) + return bytes.ReplaceAll(buf, []byte("="), []byte{100}) +} diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go new file mode 100644 index 0000000..da2bfc8 --- /dev/null +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -0,0 +1,258 @@ +package server + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "reflect" + "sort" + + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// HTTP + JSON handler + +// jsonrpc calls grab the given method's function info and runs reflect.Call +func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + if err != nil { + res := types.RPCInvalidRequestError(nil, + fmt.Errorf("error reading request body: %w", err), + ) + if wErr := WriteRPCResponseHTTPError(w, http.StatusBadRequest, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + return + } + + // if it's an empty request (like from a browser), just display a list of + // functions + if len(b) == 0 { + writeListOfEndpoints(w, r, funcMap) + return + } + + // first try to unmarshal the incoming request as an array of RPC requests + var ( + requests []types.RPCRequest + responses []types.RPCResponse + ) + if err := json.Unmarshal(b, &requests); err != nil { + // next, try to unmarshal as a single request + var request types.RPCRequest + if err := json.Unmarshal(b, &request); err != nil { + res := types.RPCParseError(fmt.Errorf("error unmarshaling request: %w", err)) + if wErr := WriteRPCResponseHTTPError(w, http.StatusInternalServerError, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + return + } + requests = []types.RPCRequest{request} + } + + // Set the default response cache to true unless + // 1. Any RPC request error. + // 2. Any RPC request doesn't allow to be cached. + // 3. Any RPC request has the height argument and the value is 0 (the default). + cache := true + for _, request := range requests { + request := request + + // A Notification is a Request object without an "id" member. + // The Server MUST NOT reply to a Notification, including those that are within a batch request. + if request.ID == nil { + logger.Debug( + "HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)", + "req", request, + ) + continue + } + if len(r.URL.Path) > 1 { + responses = append( + responses, + types.RPCInvalidRequestError(request.ID, fmt.Errorf("path %s is invalid", r.URL.Path)), + ) + cache = false + continue + } + rpcFunc, ok := funcMap[request.Method] + if !ok || (rpcFunc.ws) { + responses = append(responses, types.RPCMethodNotFoundError(request.ID)) + cache = false + continue + } + ctx := &types.Context{JSONReq: &request, HTTPReq: r} + args := []reflect.Value{reflect.ValueOf(ctx)} + if len(request.Params) > 0 { + fnArgs, err := jsonParamsToArgs(rpcFunc, request.Params) + if err != nil { + responses = append( + responses, + types.RPCInvalidParamsError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)), + ) + cache = false + continue + } + args = append(args, fnArgs...) + } + + if cache && !rpcFunc.cacheableWithArgs(args) { + cache = false + } + + returns := rpcFunc.f.Call(args) + result, err := unreflectResult(returns) + if err != nil { + responses = append(responses, types.RPCInternalError(request.ID, err)) + continue + } + responses = append(responses, types.NewRPCSuccessResponse(request.ID, result)) + } + + if len(responses) > 0 { + var wErr error + if cache { + wErr = WriteCacheableRPCResponseHTTP(w, responses...) + } else { + wErr = WriteRPCResponseHTTP(w, responses...) + } + if wErr != nil { + logger.Error("failed to write responses", "err", wErr) + } + } + } +} + +func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // Since the pattern "/" matches all paths not matched by other registered patterns, + // we check whether the path is indeed "/", otherwise return a 404 error + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + + next(w, r) + } +} + +func mapParamsToArgs( + rpcFunc *RPCFunc, + params map[string]json.RawMessage, + argsOffset int, +) ([]reflect.Value, error) { + values := make([]reflect.Value, len(rpcFunc.argNames)) + for i, argName := range rpcFunc.argNames { + argType := rpcFunc.args[i+argsOffset] + + if p, ok := params[argName]; ok && p != nil && len(p) > 0 { + val := reflect.New(argType) + err := cmtjson.Unmarshal(p, val.Interface()) + if err != nil { + return nil, err + } + values[i] = val.Elem() + } else { // use default for that type + values[i] = reflect.Zero(argType) + } + } + + return values, nil +} + +func arrayParamsToArgs( + rpcFunc *RPCFunc, + params []json.RawMessage, + argsOffset int, +) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, fmt.Errorf("expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) + } + + values := make([]reflect.Value, len(params)) + for i, p := range params { + argType := rpcFunc.args[i+argsOffset] + val := reflect.New(argType) + err := cmtjson.Unmarshal(p, val.Interface()) + if err != nil { + return nil, err + } + values[i] = val.Elem() + } + return values, nil +} + +// raw is unparsed json (from json.RawMessage) encoding either a map or an +// array. +// +// Example: +// +// rpcFunc.args = [rpctypes.Context string] +// rpcFunc.argNames = ["arg"] +func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) { + const argsOffset = 1 + + // TODO: Make more efficient, perhaps by checking the first character for '{' or '['? + // First, try to get the map. + var m map[string]json.RawMessage + err := json.Unmarshal(raw, &m) + if err == nil { + return mapParamsToArgs(rpcFunc, m, argsOffset) + } + + // Otherwise, try an array. + var a []json.RawMessage + err = json.Unmarshal(raw, &a) + if err == nil { + return arrayParamsToArgs(rpcFunc, a, argsOffset) + } + + // Otherwise, bad format, we cannot parse + return nil, fmt.Errorf("unknown type for JSON params: %v. Expected map or array", err) +} + +// writes a list of available rpc endpoints as an html page +func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) { + noArgNames := []string{} + argNames := []string{} + for name, funcData := range funcMap { + if len(funcData.args) == 0 { + noArgNames = append(noArgNames, name) + } else { + argNames = append(argNames, name) + } + } + sort.Strings(noArgNames) + sort.Strings(argNames) + buf := new(bytes.Buffer) + buf.WriteString("") + buf.WriteString("
Available endpoints:
") + + for _, name := range noArgNames { + link := fmt.Sprintf("//%s/%s", r.Host, name) + fmt.Fprintf(buf, "%s
", link, link) + } + + buf.WriteString("
Endpoints that require arguments:
") + for _, name := range argNames { + link := fmt.Sprintf("//%s/%s?", r.Host, name) + funcData := funcMap[name] + for i, argName := range funcData.argNames { + link += argName + "=_" + if i < len(funcData.argNames)-1 { + link += "&" + } + } + fmt.Fprintf(buf, "%s
", link, link) + } + buf.WriteString("") + w.Header().Set("Content-Type", "text/html") + w.WriteHeader(200) + w.Write(buf.Bytes()) //nolint: errcheck +} diff --git a/rpc/jsonrpc/server/http_json_handler_test.go b/rpc/jsonrpc/server/http_json_handler_test.go new file mode 100644 index 0000000..7de2e82 --- /dev/null +++ b/rpc/jsonrpc/server/http_json_handler_test.go @@ -0,0 +1,278 @@ +package server + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func testMux() *http.ServeMux { + funcMap := map[string]*RPCFunc{ + "c": NewRPCFunc(func(ctx *types.Context, s string, i int) (string, error) { return "foo", nil }, "s,i"), + "block": NewRPCFunc(func(ctx *types.Context, h int) (string, error) { return "block", nil }, "height", Cacheable("height")), + } + mux := http.NewServeMux() + buf := new(bytes.Buffer) + logger := log.NewTMLogger(buf) + RegisterRPCFuncs(mux, funcMap, logger) + + return mux +} + +func statusOK(code int) bool { return code >= 200 && code <= 299 } + +// Ensure that nefarious/unintended inputs to `params` +// do not crash our RPC handlers. +// See Issue https://github.com/tendermint/tendermint/issues/708. +func TestRPCParams(t *testing.T) { + mux := testMux() + tests := []struct { + payload string + wantErr string + expectedID interface{} + }{ + // bad + {`{"jsonrpc": "2.0", "id": "0"}`, "Method not found", types.JSONRPCStringID("0")}, + {`{"jsonrpc": "2.0", "method": "y", "id": "0"}`, "Method not found", types.JSONRPCStringID("0")}, + // id not captured in JSON parsing failures + {`{"method": "c", "id": "0", "params": a}`, "invalid character", nil}, + {`{"method": "c", "id": "0", "params": ["a"]}`, "got 1", types.JSONRPCStringID("0")}, + {`{"method": "c", "id": "0", "params": ["a", "b"]}`, "invalid character", types.JSONRPCStringID("0")}, + {`{"method": "c", "id": "0", "params": [1, 1]}`, "of type string", types.JSONRPCStringID("0")}, + + // no ID - notification + // {`{"jsonrpc": "2.0", "method": "c", "params": ["a", "10"]}`, false, nil}, + + // good + {`{"jsonrpc": "2.0", "method": "c", "id": "0", "params": null}`, "", types.JSONRPCStringID("0")}, + {`{"method": "c", "id": "0", "params": {}}`, "", types.JSONRPCStringID("0")}, + {`{"method": "c", "id": "0", "params": ["a", "10"]}`, "", types.JSONRPCStringID("0")}, + } + + for i, tt := range tests { + req, _ := http.NewRequest("POST", "http://localhost/", strings.NewReader(tt.payload)) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + defer res.Body.Close() + // Always expecting back a JSONRPCResponse + assert.NotZero(t, res.StatusCode, "#%d: should always return code", i) + blob, err := io.ReadAll(res.Body) + if err != nil { + t.Errorf("#%d: err reading body: %v", i, err) + continue + } + + recv := new(types.RPCResponse) + assert.Nil(t, json.Unmarshal(blob, recv), "#%d: expecting successful parsing of an RPCResponse:\nblob: %s", i, blob) + assert.NotEqual(t, recv, new(types.RPCResponse), "#%d: not expecting a blank RPCResponse", i) + assert.Equal(t, tt.expectedID, recv.ID, "#%d: expected ID not matched in RPCResponse", i) + if tt.wantErr == "" { + assert.Nil(t, recv.Error, "#%d: not expecting an error", i) + } else { + assert.True(t, recv.Error.Code < 0, "#%d: not expecting a positive JSONRPC code", i) + // The wanted error is either in the message or the data + assert.Contains(t, recv.Error.Message+recv.Error.Data, tt.wantErr, "#%d: expected substring", i) + } + } +} + +func TestJSONRPCID(t *testing.T) { + mux := testMux() + tests := []struct { + payload string + wantErr bool + expectedID interface{} + }{ + // good id + {`{"jsonrpc": "2.0", "method": "c", "id": "0", "params": ["a", "10"]}`, false, types.JSONRPCStringID("0")}, + {`{"jsonrpc": "2.0", "method": "c", "id": "abc", "params": ["a", "10"]}`, false, types.JSONRPCStringID("abc")}, + {`{"jsonrpc": "2.0", "method": "c", "id": 0, "params": ["a", "10"]}`, false, types.JSONRPCIntID(0)}, + {`{"jsonrpc": "2.0", "method": "c", "id": 1, "params": ["a", "10"]}`, false, types.JSONRPCIntID(1)}, + {`{"jsonrpc": "2.0", "method": "c", "id": 1.3, "params": ["a", "10"]}`, false, types.JSONRPCIntID(1)}, + {`{"jsonrpc": "2.0", "method": "c", "id": -1, "params": ["a", "10"]}`, false, types.JSONRPCIntID(-1)}, + + // bad id + {`{"jsonrpc": "2.0", "method": "c", "id": {}, "params": ["a", "10"]}`, true, nil}, + {`{"jsonrpc": "2.0", "method": "c", "id": [], "params": ["a", "10"]}`, true, nil}, + } + + for i, tt := range tests { + req, _ := http.NewRequest("POST", "http://localhost/", strings.NewReader(tt.payload)) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + // Always expecting back a JSONRPCResponse + assert.NotZero(t, res.StatusCode, "#%d: should always return code", i) + blob, err := io.ReadAll(res.Body) + if err != nil { + t.Errorf("#%d: err reading body: %v", i, err) + continue + } + res.Body.Close() + + recv := new(types.RPCResponse) + err = json.Unmarshal(blob, recv) + assert.Nil(t, err, "#%d: expecting successful parsing of an RPCResponse:\nblob: %s", i, blob) + if !tt.wantErr { + assert.NotEqual(t, recv, new(types.RPCResponse), "#%d: not expecting a blank RPCResponse", i) + assert.Equal(t, tt.expectedID, recv.ID, "#%d: expected ID not matched in RPCResponse", i) + assert.Nil(t, recv.Error, "#%d: not expecting an error", i) + } else { + assert.True(t, recv.Error.Code < 0, "#%d: not expecting a positive JSONRPC code", i) + } + } +} + +func TestRPCNotification(t *testing.T) { + mux := testMux() + body := strings.NewReader(`{"jsonrpc": "2.0"}`) + req, _ := http.NewRequest("POST", "http://localhost/", body) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + + // Always expecting back a JSONRPCResponse + require.True(t, statusOK(res.StatusCode), "should always return 2XX") + blob, err := io.ReadAll(res.Body) + res.Body.Close() + require.Nil(t, err, "reading from the body should not give back an error") + require.Equal(t, len(blob), 0, "a notification SHOULD NOT be responded to by the server") +} + +func TestRPCNotificationInBatch(t *testing.T) { + mux := testMux() + tests := []struct { + payload string + expectCount int + }{ + { + `[ + {"jsonrpc": "2.0"}, + {"jsonrpc": "2.0","method":"c","id":"abc","params":["a","10"]} + ]`, + 1, + }, + { + `[ + {"jsonrpc": "2.0"}, + {"jsonrpc": "2.0","method":"c","id":"abc","params":["a","10"]}, + {"jsonrpc": "2.0"}, + {"jsonrpc": "2.0","method":"c","id":"abc","params":["a","10"]} + ]`, + 2, + }, + } + for i, tt := range tests { + req, _ := http.NewRequest("POST", "http://localhost/", strings.NewReader(tt.payload)) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + // Always expecting back a JSONRPCResponse + assert.True(t, statusOK(res.StatusCode), "#%d: should always return 2XX", i) + blob, err := io.ReadAll(res.Body) + if err != nil { + t.Errorf("#%d: err reading body: %v", i, err) + continue + } + res.Body.Close() + + var responses []types.RPCResponse + // try to unmarshal an array first + err = json.Unmarshal(blob, &responses) + if err != nil { + // if we were actually expecting an array, but got an error + if tt.expectCount > 1 { + t.Errorf("#%d: expected an array, couldn't unmarshal it\nblob: %s", i, blob) + continue + } + // we were expecting an error here, so let's unmarshal a single response + var response types.RPCResponse + err = json.Unmarshal(blob, &response) + if err != nil { + t.Errorf("#%d: expected successful parsing of an RPCResponse\nblob: %s", i, blob) + continue + } + // have a single-element result + responses = []types.RPCResponse{response} + } + if tt.expectCount != len(responses) { + t.Errorf("#%d: expected %d response(s), but got %d\nblob: %s", i, tt.expectCount, len(responses), blob) + continue + } + for _, response := range responses { + assert.NotEqual(t, response, new(types.RPCResponse), "#%d: not expecting a blank RPCResponse", i) + } + } +} + +func TestUnknownRPCPath(t *testing.T) { + mux := testMux() + req, _ := http.NewRequest("GET", "http://localhost/unknownrpcpath", nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + + // Always expecting back a 404 error + require.Equal(t, http.StatusNotFound, res.StatusCode, "should always return 404") + res.Body.Close() +} + +func TestRPCResponseCache(t *testing.T) { + mux := testMux() + body := strings.NewReader(`{"jsonrpc": "2.0","method":"block","id": 0, "params": ["1"]}`) + req, _ := http.NewRequest("Get", "http://localhost/", body) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + + // Always expecting back a JSONRPCResponse + require.True(t, statusOK(res.StatusCode), "should always return 2XX") + require.Equal(t, "public, max-age=86400", res.Header.Get("Cache-control")) + + _, err := io.ReadAll(res.Body) + res.Body.Close() + require.Nil(t, err, "reading from the body should not give back an error") + + // send a request with default height. + body = strings.NewReader(`{"jsonrpc": "2.0","method":"block","id": 0, "params": ["0"]}`) + req, _ = http.NewRequest("Get", "http://localhost/", body) + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res = rec.Result() + + // Always expecting back a JSONRPCResponse + require.True(t, statusOK(res.StatusCode), "should always return 2XX") + require.Equal(t, "", res.Header.Get("Cache-control")) + + _, err = io.ReadAll(res.Body) + + res.Body.Close() + require.Nil(t, err, "reading from the body should not give back an error") + + // send a request with default height, but as empty set of parameters. + body = strings.NewReader(`{"jsonrpc": "2.0","method":"block","id": 0, "params": []}`) + req, _ = http.NewRequest("Get", "http://localhost/", body) + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res = rec.Result() + + // Always expecting back a JSONRPCResponse + require.True(t, statusOK(res.StatusCode), "should always return 2XX") + require.Equal(t, "", res.Header.Get("Cache-control")) + + _, err = io.ReadAll(res.Body) + + res.Body.Close() + require.Nil(t, err, "reading from the body should not give back an error") +} diff --git a/rpc/jsonrpc/server/http_server.go b/rpc/jsonrpc/server/http_server.go new file mode 100644 index 0000000..9c6f444 --- /dev/null +++ b/rpc/jsonrpc/server/http_server.go @@ -0,0 +1,329 @@ +// Commons for HTTP handling +package server + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "runtime/debug" + "strings" + "time" + + "golang.org/x/net/netutil" + + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// Config is a RPC server configuration. +type Config struct { + // see netutil.LimitListener + MaxOpenConnections int + // mirrors http.Server#ReadTimeout + ReadTimeout time.Duration + // mirrors http.Server#WriteTimeout + WriteTimeout time.Duration + // MaxBodyBytes controls the maximum number of bytes the + // server will read parsing the request body. + MaxBodyBytes int64 + // mirrors http.Server#MaxHeaderBytes + MaxHeaderBytes int + // maximum number of requests in a batch request + MaxRequestBatchSize int +} + +// DefaultConfig returns a default configuration. +func DefaultConfig() *Config { + return &Config{ + MaxOpenConnections: 0, // unlimited + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + MaxBodyBytes: int64(1000000), // 1MB + MaxHeaderBytes: 1 << 20, // same as the net/http default + MaxRequestBatchSize: 10, // default to max 10 requests per batch + } +} + +// Serve creates a http.Server and calls Serve with the given listener. It +// wraps handler with RecoverAndLogHandler and a handler, which limits the max +// body size to config.MaxBodyBytes. +// +// NOTE: This function blocks - you may want to call it in a go-routine. +func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error { + logger.Info("serve", "msg", log.NewLazySprintf("Starting RPC HTTP server on %s", listener.Addr())) + s := &http.Server{ + Handler: PreChecksHandler(RecoverAndLogHandler(defaultHandler{h: handler}, logger), config), + ReadTimeout: config.ReadTimeout, + ReadHeaderTimeout: config.ReadTimeout, + WriteTimeout: config.WriteTimeout, + MaxHeaderBytes: config.MaxHeaderBytes, + } + err := s.Serve(listener) + logger.Info("RPC HTTP server stopped", "err", err) + return err +} + +// ServeTLS creates a http.Server and calls ServeTLS with the given listener, +// certFile and keyFile. It wraps handler with RecoverAndLogHandler and a +// handler, which limits the max body size to config.MaxBodyBytes. +// +// NOTE: This function blocks - you may want to call it in a go-routine. +func ServeTLS( + listener net.Listener, + handler http.Handler, + certFile, keyFile string, + logger log.Logger, + config *Config, +) error { + logger.Info("serve tls", "msg", log.NewLazySprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)", + listener.Addr(), certFile, keyFile)) + s := &http.Server{ + Handler: PreChecksHandler(RecoverAndLogHandler(defaultHandler{h: handler}, logger), config), + ReadTimeout: config.ReadTimeout, + ReadHeaderTimeout: config.ReadTimeout, + WriteTimeout: config.WriteTimeout, + MaxHeaderBytes: config.MaxHeaderBytes, + } + err := s.ServeTLS(listener, certFile, keyFile) + + logger.Error("RPC HTTPS server stopped", "err", err) + return err +} + +// WriteRPCResponseHTTPError marshals res as JSON (with indent) and writes it +// to w. +// +// source: https://www.jsonrpc.org/historical/json-rpc-over-http.html +func WriteRPCResponseHTTPError( + w http.ResponseWriter, + httpCode int, + res types.RPCResponse, +) error { + if res.Error == nil { + panic("tried to write http error response without RPC error") + } + + jsonBytes, err := json.Marshal(res) + if err != nil { + return fmt.Errorf("json marshal: %w", err) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(httpCode) + _, err = w.Write(jsonBytes) + return err +} + +// WriteRPCResponseHTTP marshals res as JSON (with indent) and writes it to w. +func WriteRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) error { + return writeRPCResponseHTTP(w, []httpHeader{}, res...) +} + +// WriteCacheableRPCResponseHTTP marshals res as JSON (with indent) and writes +// it to w. Adds cache-control to the response header and sets the expiry to +// one day. +func WriteCacheableRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) error { + return writeRPCResponseHTTP(w, []httpHeader{{"Cache-Control", "public, max-age=86400"}}, res...) +} + +type httpHeader struct { + name string + value string +} + +func writeRPCResponseHTTP(w http.ResponseWriter, headers []httpHeader, res ...types.RPCResponse) error { + var v interface{} + if len(res) == 1 { + v = res[0] + } else { + v = res + } + + jsonBytes, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("json marshal: %w", err) + } + w.Header().Set("Content-Type", "application/json") + for _, header := range headers { + w.Header().Set(header.name, header.value) + } + w.WriteHeader(200) + _, err = w.Write(jsonBytes) + return err +} + +//----------------------------------------------------------------------------- + +// RecoverAndLogHandler wraps an HTTP handler, adding error logging. +// If the inner function panics, the outer function recovers, logs, sends an +// HTTP 500 error response. +func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Wrap the ResponseWriter to remember the status + rww := &responseWriterWrapper{-1, w} + begin := time.Now() + + rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix())) + + defer func() { + // Handle any panics in the panic handler below. Does not use the logger, since we want + // to avoid any further panics. However, we try to return a 500, since it otherwise + // defaults to 200 and there is no other way to terminate the connection. If that + // should panic for whatever reason then the Go HTTP server will handle it and + // terminate the connection - panicing is the de-facto and only way to get the Go HTTP + // server to terminate the request and close the connection/stream: + // https://github.com/golang/go/issues/17790#issuecomment-258481416 + if e := recover(); e != nil { + fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack())) + w.WriteHeader(500) + } + }() + + defer func() { + // Send a 500 error if a panic happens during a handler. + // Without this, Chrome & Firefox were retrying aborted ajax requests, + // at least to my localhost. + if e := recover(); e != nil { + // If RPCResponse + if res, ok := e.(types.RPCResponse); ok { + if wErr := WriteRPCResponseHTTP(rww, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + } else { + // Panics can contain anything, attempt to normalize it as an error. + var err error + switch e := e.(type) { + case error: + err = e + case string: + err = errors.New(e) + case fmt.Stringer: + err = errors.New(e.String()) + default: + } + + logger.Error("panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack())) + + res := types.RPCInternalError(types.JSONRPCIntID(-1), err) + if wErr := WriteRPCResponseHTTPError(rww, http.StatusInternalServerError, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + } + } + + // Finally, log. + durationMS := time.Since(begin).Nanoseconds() / 1000000 + if rww.Status == -1 { + rww.Status = 200 + } + logger.Debug("served RPC HTTP response", + "method", r.Method, + "url", r.URL, + "status", rww.Status, + "duration", durationMS, + "remoteAddr", r.RemoteAddr, + ) + }() + + handler.ServeHTTP(rww, r) + }) +} + +// Remember the status for logging +type responseWriterWrapper struct { + Status int + http.ResponseWriter +} + +func (w *responseWriterWrapper) WriteHeader(status int) { + w.Status = status + w.ResponseWriter.WriteHeader(status) +} + +// implements http.Hijacker +func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.ResponseWriter.(http.Hijacker).Hijack() +} + +type defaultHandler struct { + h http.Handler +} + +func (h defaultHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + h.h.ServeHTTP(w, r) +} + +// Listen starts a new net.Listener on the given address. +// It returns an error if the address is invalid or the call to Listen() fails. +func Listen(addr string, maxOpenConnections int) (listener net.Listener, err error) { + parts := strings.SplitN(addr, "://", 2) + if len(parts) != 2 { + return nil, fmt.Errorf( + "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", + addr, + ) + } + proto, addr := parts[0], parts[1] + listener, err = net.Listen(proto, addr) + if err != nil { + return nil, fmt.Errorf("failed to listen on %v: %v", addr, err) + } + if maxOpenConnections > 0 { + listener = netutil.LimitListener(listener, maxOpenConnections) + } + + return listener, nil +} + +// Middleware + +// PreChecksHandler is a middleware function that checks the size of batch requests and returns an error +// if it exceeds the maximum configured size. It also checks if the request body is not greater than the +// configured maximum request body bytes limit. +func PreChecksHandler(next http.Handler, config *Config) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // ensure that the current request body bytes is not greater than the configured maximum request body bytes + r.Body = http.MaxBytesReader(w, r.Body, config.MaxBodyBytes) + + // if maxBatchSize is 0 then don't constraint the limit of requests per batch + // It cannot be negative because the config.toml validation requires it to be + // greater than or equal to 0 + if config.MaxRequestBatchSize > 0 { + var requests []types.RPCRequest + var responses []types.RPCResponse + var err error + + data, err := io.ReadAll(r.Body) + if err != nil { + res := types.RPCInvalidRequestError(nil, fmt.Errorf("error reading request body: %w", err)) + _ = WriteRPCResponseHTTPError(w, http.StatusBadRequest, res) + return + } + + err = json.Unmarshal(data, &requests) + // if no err it means multiple requests, check if the number of request exceeds + // the maximum batch size configured + if err == nil { + // if the number of requests in batch exceed the maximum configured then return an error + if len(requests) > config.MaxRequestBatchSize { + res := types.RPCInvalidRequestError(nil, fmt.Errorf("batch request exceeds maximum (%d) allowed number of requests", config.MaxRequestBatchSize)) + responses = append(responses, res) + _ = WriteRPCResponseHTTP(w, responses...) + return + } + } + + // ensure the request body can be read again by other handlers + r.Body = io.NopCloser(bytes.NewBuffer(data)) + } + + // next handler + next.ServeHTTP(w, r) + }) +} diff --git a/rpc/jsonrpc/server/http_server_test.go b/rpc/jsonrpc/server/http_server_test.go new file mode 100644 index 0000000..ddd2bfa --- /dev/null +++ b/rpc/jsonrpc/server/http_server_test.go @@ -0,0 +1,155 @@ +package server + +import ( + "crypto/tls" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +type sampleResult struct { + Value string `json:"value"` +} + +func TestMaxOpenConnections(t *testing.T) { + const max = 5 // max simultaneous connections + + // Start the server. + var open int32 + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if n := atomic.AddInt32(&open, 1); n > int32(max) { + t.Errorf("%d open connections, want <= %d", n, max) + } + defer atomic.AddInt32(&open, -1) + time.Sleep(10 * time.Millisecond) + fmt.Fprint(w, "some body") + }) + config := DefaultConfig() + l, err := Listen("tcp://127.0.0.1:0", max) + require.NoError(t, err) + defer l.Close() + go Serve(l, mux, log.TestingLogger(), config) //nolint:errcheck // ignore for tests + + // Make N GET calls to the server. + attempts := max * 2 + var wg sync.WaitGroup + var failed int32 + for i := 0; i < attempts; i++ { + wg.Add(1) + go func() { + defer wg.Done() + c := http.Client{Timeout: 3 * time.Second} + r, err := c.Get("http://" + l.Addr().String()) + if err != nil { + atomic.AddInt32(&failed, 1) + return + } + defer r.Body.Close() + }() + } + wg.Wait() + + // We expect some Gets to fail as the server's accept queue is filled, + // but most should succeed. + if int(failed) >= attempts/2 { + t.Errorf("%d requests failed within %d attempts", failed, attempts) + } +} + +func TestServeTLS(t *testing.T) { + ln, err := net.Listen("tcp", "localhost:0") + require.NoError(t, err) + defer ln.Close() + + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "some body") + }) + + chErr := make(chan error, 1) + go func() { + // FIXME This goroutine leaks + chErr <- ServeTLS(ln, mux, "test.crt", "test.key", log.TestingLogger(), DefaultConfig()) + }() + + select { + case err := <-chErr: + require.NoError(t, err) + case <-time.After(100 * time.Millisecond): + } + + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + c := &http.Client{Transport: tr} + res, err := c.Get("https://" + ln.Addr().String()) + require.NoError(t, err) + defer res.Body.Close() + assert.Equal(t, http.StatusOK, res.StatusCode) + + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + assert.Equal(t, []byte("some body"), body) +} + +func TestWriteRPCResponseHTTP(t *testing.T) { + id := types.JSONRPCIntID(-1) + + // one argument + w := httptest.NewRecorder() + err := WriteCacheableRPCResponseHTTP(w, types.NewRPCSuccessResponse(id, &sampleResult{"hello"})) + require.NoError(t, err) + resp := w.Result() + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + require.NoError(t, err) + assert.Equal(t, 200, resp.StatusCode) + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) + assert.Equal(t, "public, max-age=86400", resp.Header.Get("Cache-control")) + assert.Equal(t, `{"jsonrpc":"2.0","id":-1,"result":{"value":"hello"}}`, string(body)) + + // multiple arguments + w = httptest.NewRecorder() + err = WriteRPCResponseHTTP(w, + types.NewRPCSuccessResponse(id, &sampleResult{"hello"}), + types.NewRPCSuccessResponse(id, &sampleResult{"world"})) + require.NoError(t, err) + resp = w.Result() + body, err = io.ReadAll(resp.Body) + _ = resp.Body.Close() + require.NoError(t, err) + + assert.Equal(t, 200, resp.StatusCode) + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) + assert.Equal(t, `[{"jsonrpc":"2.0","id":-1,"result":{"value":"hello"}},{"jsonrpc":"2.0","id":-1,"result":{"value":"world"}}]`, string(body)) +} + +func TestWriteRPCResponseHTTPError(t *testing.T) { + w := httptest.NewRecorder() + err := WriteRPCResponseHTTPError( + w, + http.StatusInternalServerError, + types.RPCInternalError(types.JSONRPCIntID(-1), errors.New("foo"))) + require.NoError(t, err) + resp := w.Result() + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + require.NoError(t, err) + assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) + assert.Equal(t, `{"jsonrpc":"2.0","id":-1,"error":{"code":-32603,"message":"Internal error","data":"foo"}}`, string(body)) +} diff --git a/rpc/jsonrpc/server/http_uri_handler.go b/rpc/jsonrpc/server/http_uri_handler.go new file mode 100644 index 0000000..c4f996e --- /dev/null +++ b/rpc/jsonrpc/server/http_uri_handler.go @@ -0,0 +1,218 @@ +package server + +import ( + "encoding/hex" + "fmt" + "net/http" + "reflect" + "regexp" + "strings" + + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// HTTP + URI handler + +var reInt = regexp.MustCompile(`^-?[0-9]+$`) + +// convert from a function name to the http handler +func makeHTTPHandler(rpcFunc *RPCFunc, logger log.Logger) func(http.ResponseWriter, *http.Request) { + // Always return -1 as there's no ID here. + dummyID := types.JSONRPCIntID(-1) // URIClientRequestID + + // Exception for websocket endpoints + if rpcFunc.ws { + return func(w http.ResponseWriter, r *http.Request) { + res := types.RPCMethodNotFoundError(dummyID) + if wErr := WriteRPCResponseHTTPError(w, http.StatusNotFound, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + } + } + + // All other endpoints + return func(w http.ResponseWriter, r *http.Request) { + logger.Debug("HTTP HANDLER", "req", r) + + ctx := &types.Context{HTTPReq: r} + args := []reflect.Value{reflect.ValueOf(ctx)} + + fnArgs, err := httpParamsToArgs(rpcFunc, r) + if err != nil { + res := types.RPCInvalidParamsError(dummyID, + fmt.Errorf("error converting http params to arguments: %w", err), + ) + if wErr := WriteRPCResponseHTTPError(w, http.StatusInternalServerError, res); wErr != nil { + logger.Error("failed to write response", "err", wErr) + } + return + } + args = append(args, fnArgs...) + + returns := rpcFunc.f.Call(args) + + logger.Debug("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + if err := WriteRPCResponseHTTPError(w, http.StatusInternalServerError, + types.RPCInternalError(dummyID, err)); err != nil { + logger.Error("failed to write response", "err", err) + return + } + return + } + + resp := types.NewRPCSuccessResponse(dummyID, result) + if rpcFunc.cacheableWithArgs(args) { + err = WriteCacheableRPCResponseHTTP(w, resp) + } else { + err = WriteRPCResponseHTTP(w, resp) + } + if err != nil { + logger.Error("failed to write response", "err", err) + return + } + } +} + +// Covert an http query to a list of properly typed values. +// To be properly decoded the arg must be a concrete type from CometBFT (if its an interface). +func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) { + // skip types.Context + const argsOffset = 1 + + values := make([]reflect.Value, len(rpcFunc.argNames)) + + for i, name := range rpcFunc.argNames { + argType := rpcFunc.args[i+argsOffset] + + values[i] = reflect.Zero(argType) // set default for that type + + arg := getParam(r, name) + // log.Notice("param to arg", "argType", argType, "name", name, "arg", arg) + + if arg == "" { + continue + } + + v, ok, err := nonJSONStringToArg(argType, arg) + if err != nil { + return nil, err + } + if ok { + values[i] = v + continue + } + + values[i], err = jsonStringToArg(argType, arg) + if err != nil { + return nil, err + } + } + + return values, nil +} + +func jsonStringToArg(rt reflect.Type, arg string) (reflect.Value, error) { + rv := reflect.New(rt) + err := cmtjson.Unmarshal([]byte(arg), rv.Interface()) + if err != nil { + return rv, err + } + rv = rv.Elem() + return rv, nil +} + +func nonJSONStringToArg(rt reflect.Type, arg string) (reflect.Value, bool, error) { + if rt.Kind() == reflect.Ptr { + rv1, ok, err := nonJSONStringToArg(rt.Elem(), arg) + switch { + case err != nil: + return reflect.Value{}, false, err + case ok: + rv := reflect.New(rt.Elem()) + rv.Elem().Set(rv1) + return rv, true, nil + default: + return reflect.Value{}, false, nil + } + } else { + return _nonJSONStringToArg(rt, arg) + } +} + +// NOTE: rt.Kind() isn't a pointer. +func _nonJSONStringToArg(rt reflect.Type, arg string) (reflect.Value, bool, error) { + isIntString := reInt.Match([]byte(arg)) + isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`) + isHexString := strings.HasPrefix(strings.ToLower(arg), "0x") + + var expectingString, expectingByteSlice, expectingInt bool + switch rt.Kind() { + case reflect.Int, + reflect.Uint, + reflect.Int8, + reflect.Uint8, + reflect.Int16, + reflect.Uint16, + reflect.Int32, + reflect.Uint32, + reflect.Int64, + reflect.Uint64: + expectingInt = true + case reflect.String: + expectingString = true + case reflect.Slice: + expectingByteSlice = rt.Elem().Kind() == reflect.Uint8 + } + + if isIntString && expectingInt { + qarg := `"` + arg + `"` + rv, err := jsonStringToArg(rt, qarg) + if err != nil { + return rv, false, err + } + + return rv, true, nil + } + + if isHexString { + if !expectingString && !expectingByteSlice { + err := fmt.Errorf("got a hex string arg, but expected '%s'", + rt.Kind().String()) + return reflect.ValueOf(nil), false, err + } + + var value []byte + value, err := hex.DecodeString(arg[2:]) + if err != nil { + return reflect.ValueOf(nil), false, err + } + if rt.Kind() == reflect.String { + return reflect.ValueOf(string(value)), true, nil + } + return reflect.ValueOf(value), true, nil + } + + if isQuotedString && expectingByteSlice { + v := reflect.New(reflect.TypeOf("")) + err := cmtjson.Unmarshal([]byte(arg), v.Interface()) + if err != nil { + return reflect.ValueOf(nil), false, err + } + v = v.Elem() + return reflect.ValueOf([]byte(v.String())), true, nil + } + + return reflect.ValueOf(nil), false, nil +} + +func getParam(r *http.Request, param string) string { + s := r.URL.Query().Get(param) + if s == "" { + s = r.FormValue(param) + } + return s +} diff --git a/rpc/jsonrpc/server/parse_test.go b/rpc/jsonrpc/server/parse_test.go new file mode 100644 index 0000000..c4eb497 --- /dev/null +++ b/rpc/jsonrpc/server/parse_test.go @@ -0,0 +1,213 @@ +package server + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/libs/bytes" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func TestParseJSONMap(t *testing.T) { + input := []byte(`{"value":"1234","height":22}`) + + // naive is float,string + var p1 map[string]interface{} + err := json.Unmarshal(input, &p1) + if assert.Nil(t, err) { + h, ok := p1["height"].(float64) + if assert.True(t, ok, "%#v", p1["height"]) { + assert.EqualValues(t, 22, h) + } + v, ok := p1["value"].(string) + if assert.True(t, ok, "%#v", p1["value"]) { + assert.EqualValues(t, "1234", v) + } + } + + // preloading map with values doesn't help + tmp := 0 + p2 := map[string]interface{}{ + "value": &bytes.HexBytes{}, + "height": &tmp, + } + err = json.Unmarshal(input, &p2) + if assert.Nil(t, err) { + h, ok := p2["height"].(float64) + if assert.True(t, ok, "%#v", p2["height"]) { + assert.EqualValues(t, 22, h) + } + v, ok := p2["value"].(string) + if assert.True(t, ok, "%#v", p2["value"]) { + assert.EqualValues(t, "1234", v) + } + } + + // preload here with *pointers* to the desired types + // struct has unknown types, but hard-coded keys + tmp = 0 + p3 := struct { + Value interface{} `json:"value"` + Height interface{} `json:"height"` + }{ + Height: &tmp, + Value: &bytes.HexBytes{}, + } + err = json.Unmarshal(input, &p3) + if assert.Nil(t, err) { + h, ok := p3.Height.(*int) + if assert.True(t, ok, "%#v", p3.Height) { + assert.Equal(t, 22, *h) + } + v, ok := p3.Value.(*bytes.HexBytes) + if assert.True(t, ok, "%#v", p3.Value) { + assert.EqualValues(t, []byte{0x12, 0x34}, *v) + } + } + + // simplest solution, but hard-coded + p4 := struct { + Value bytes.HexBytes `json:"value"` + Height int `json:"height"` + }{} + err = json.Unmarshal(input, &p4) + if assert.Nil(t, err) { + assert.EqualValues(t, 22, p4.Height) + assert.EqualValues(t, []byte{0x12, 0x34}, p4.Value) + } + + // so, let's use this trick... + // dynamic keys on map, and we can deserialize to the desired types + var p5 map[string]*json.RawMessage + err = json.Unmarshal(input, &p5) + if assert.Nil(t, err) { + var h int + err = json.Unmarshal(*p5["height"], &h) + if assert.Nil(t, err) { + assert.Equal(t, 22, h) + } + + var v bytes.HexBytes + err = json.Unmarshal(*p5["value"], &v) + if assert.Nil(t, err) { + assert.Equal(t, bytes.HexBytes{0x12, 0x34}, v) + } + } +} + +func TestParseJSONArray(t *testing.T) { + input := []byte(`["1234",22]`) + + // naive is float,string + var p1 []interface{} + err := json.Unmarshal(input, &p1) + if assert.Nil(t, err) { + v, ok := p1[0].(string) + if assert.True(t, ok, "%#v", p1[0]) { + assert.EqualValues(t, "1234", v) + } + h, ok := p1[1].(float64) + if assert.True(t, ok, "%#v", p1[1]) { + assert.EqualValues(t, 22, h) + } + } + + // preloading map with values helps here (unlike map - p2 above) + tmp := 0 + p2 := []interface{}{&bytes.HexBytes{}, &tmp} + err = json.Unmarshal(input, &p2) + if assert.Nil(t, err) { + v, ok := p2[0].(*bytes.HexBytes) + if assert.True(t, ok, "%#v", p2[0]) { + assert.EqualValues(t, []byte{0x12, 0x34}, *v) + } + h, ok := p2[1].(*int) + if assert.True(t, ok, "%#v", p2[1]) { + assert.EqualValues(t, 22, *h) + } + } +} + +func TestParseJSONRPC(t *testing.T) { + demo := func(ctx *types.Context, height int, name string) {} + call := NewRPCFunc(demo, "height,name") + + cases := []struct { + raw string + height int64 + name string + fail bool + }{ + // should parse + {`["7", "flew"]`, 7, "flew", false}, + {`{"name": "john", "height": "22"}`, 22, "john", false}, + // defaults + {`{"name": "solo", "unused": "stuff"}`, 0, "solo", false}, + // should fail - wrong types/length + {`["flew", 7]`, 0, "", true}, + {`[7,"flew",100]`, 0, "", true}, + {`{"name": -12, "height": "fred"}`, 0, "", true}, + } + for idx, tc := range cases { + i := strconv.Itoa(idx) + data := []byte(tc.raw) + vals, err := jsonParamsToArgs(call, data) + if tc.fail { + assert.NotNil(t, err, i) + } else { + assert.Nil(t, err, "%s: %+v", i, err) + if assert.Equal(t, 2, len(vals), i) { + assert.Equal(t, tc.height, vals[0].Int(), i) + assert.Equal(t, tc.name, vals[1].String(), i) + } + } + + } +} + +func TestParseURI(t *testing.T) { + demo := func(ctx *types.Context, height int, name string) {} + call := NewRPCFunc(demo, "height,name") + + cases := []struct { + raw []string + height int64 + name string + fail bool + }{ + // can parse numbers unquoted and strings quoted + {[]string{"7", `"flew"`}, 7, "flew", false}, + {[]string{"22", `"john"`}, 22, "john", false}, + {[]string{"-10", `"bob"`}, -10, "bob", false}, + // can parse numbers quoted, too + {[]string{`"7"`, `"flew"`}, 7, "flew", false}, + {[]string{`"-10"`, `"bob"`}, -10, "bob", false}, + // cant parse strings uquoted + {[]string{`"-10"`, `bob`}, -10, "bob", true}, + } + for idx, tc := range cases { + i := strconv.Itoa(idx) + // data := []byte(tc.raw) + url := fmt.Sprintf( + "test.com/method?height=%v&name=%v", + tc.raw[0], tc.raw[1]) + req, err := http.NewRequest("GET", url, nil) + assert.NoError(t, err) + vals, err := httpParamsToArgs(call, req) + if tc.fail { + assert.NotNil(t, err, i) + } else { + assert.Nil(t, err, "%s: %+v", i, err) + if assert.Equal(t, 2, len(vals), i) { + assert.Equal(t, tc.height, vals[0].Int(), i) + assert.Equal(t, tc.name, vals[1].String(), i) + } + } + + } +} diff --git a/rpc/jsonrpc/server/rpc_func.go b/rpc/jsonrpc/server/rpc_func.go new file mode 100644 index 0000000..a0a2f9a --- /dev/null +++ b/rpc/jsonrpc/server/rpc_func.go @@ -0,0 +1,154 @@ +package server + +import ( + "fmt" + "net/http" + "reflect" + "strings" + + "github.com/cometbft/cometbft/libs/log" +) + +// RegisterRPCFuncs adds a route for each function in the funcMap, as well as +// general jsonrpc and websocket handlers for all functions. "result" is the +// interface on which the result objects are registered, and is popualted with +// every RPCResponse +func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger log.Logger) { + // HTTP endpoints + for funcName, rpcFunc := range funcMap { + mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, logger)) + } + + // JSONRPC endpoints + mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger))) +} + +type Option func(*RPCFunc) + +// Cacheable enables returning a cache control header from RPC functions to +// which it is applied. +// +// `noCacheDefArgs` is a list of argument names that, if omitted or set to +// their defaults when calling the RPC function, will skip the response +// caching. +func Cacheable(noCacheDefArgs ...string) Option { + return func(r *RPCFunc) { + r.cacheable = true + r.noCacheDefArgs = make(map[string]interface{}) + for _, arg := range noCacheDefArgs { + r.noCacheDefArgs[arg] = nil + } + } +} + +// Ws enables WebSocket communication. +func Ws() Option { + return func(r *RPCFunc) { + r.ws = true + } +} + +// RPCFunc contains the introspected type information for a function +type RPCFunc struct { + f reflect.Value // underlying rpc function + args []reflect.Type // type of each function arg + returns []reflect.Type // type of each return arg + argNames []string // name of each argument + cacheable bool // enable cache control + ws bool // enable websocket communication + noCacheDefArgs map[string]interface{} // a lookup table of args that, if not supplied or are set to default values, cause us to not cache +} + +// NewRPCFunc wraps a function for introspection. +// f is the function, args are comma separated argument names +func NewRPCFunc(f interface{}, args string, options ...Option) *RPCFunc { + return newRPCFunc(f, args, options...) +} + +// NewWSRPCFunc wraps a function for introspection and use in the websockets. +func NewWSRPCFunc(f interface{}, args string, options ...Option) *RPCFunc { + options = append(options, Ws()) + return newRPCFunc(f, args, options...) +} + +// cacheableWithArgs returns whether or not a call to this function is cacheable, +// given the specified arguments. +func (f *RPCFunc) cacheableWithArgs(args []reflect.Value) bool { + if !f.cacheable { + return false + } + // Skip the context variable common to all RPC functions + for i := 1; i < len(f.args); i++ { + // f.argNames does not include the context variable + argName := f.argNames[i-1] + if _, hasDefault := f.noCacheDefArgs[argName]; hasDefault { + // Argument with default value was not supplied + if i >= len(args) { + return false + } + // Argument with default value is set to its zero value + if args[i].IsZero() { + return false + } + } + } + return true +} + +func newRPCFunc(f interface{}, args string, options ...Option) *RPCFunc { + var argNames []string + if args != "" { + argNames = strings.Split(args, ",") + } + + r := &RPCFunc{ + f: reflect.ValueOf(f), + args: funcArgTypes(f), + returns: funcReturnTypes(f), + argNames: argNames, + } + + for _, opt := range options { + opt(r) + } + + return r +} + +// return a function's argument types +func funcArgTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumIn() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.In(i) + } + return typez +} + +// return a function's return types +func funcReturnTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumOut() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.Out(i) + } + return typez +} + +//------------------------------------------------------------- + +// NOTE: assume returns is result struct and error. If error is not nil, return it +func unreflectResult(returns []reflect.Value) (interface{}, error) { + errV := returns[1] + if errV.Interface() != nil { + return nil, fmt.Errorf("%v", errV.Interface()) + } + rv := returns[0] + // the result is a registered interface, + // we need a pointer to it so we can marshal with type byte + rvp := reflect.New(rv.Type()) + rvp.Elem().Set(rv) + return rvp.Interface(), nil +} diff --git a/rpc/jsonrpc/server/test.crt b/rpc/jsonrpc/server/test.crt new file mode 100644 index 0000000..d4708f5 --- /dev/null +++ b/rpc/jsonrpc/server/test.crt @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEODCCAiCgAwIBAgIQWDHUrd4tOM2xExWhzOEJ7DANBgkqhkiG9w0BAQsFADAZ +MRcwFQYDVQQDEw50ZW5kZXJtaW50LmNvbTAeFw0xOTA2MDIxMTAyMDdaFw0yMDEy +MDIxMTAyMDRaMBExDzANBgNVBAMTBnNlcnZlcjCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBANBaa6dc9GZcIhAHWqVrx0LONYf+IlbvTP7yrV45ws0ix8TX +1NUOiDY1cwzKH8ay/HYX45e2fFLrtLidc9h+apsC55k3Vdcy00+Ksr/adjR8D4A/ +GpnTS+hVDHTlqINe9a7USok34Zr1rc3fh4Imu5RxEurjMwkA/36k6+OpXMp2qlKY +S1fGqwn2KGhXkp/yTWZILEMXBazNxGx4xfqYXzWm6boeyJAXpM2DNkv7dtwa/CWY +WacUQJApNInwn5+B8LLoo+pappkfZOjAD9/aHKsyFTSWmmWeg7V//ouB3u5vItqf +GP+3xmPgeYeEyOIe/P2f8bRuQs+GGwSCmi6F1GUCAwEAAaOBgzCBgDAOBgNVHQ8B +Af8EBAMCA7gwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQW +BBSpBFIMbkBR4xVYQZtUJQQwzPmbHjAfBgNVHSMEGDAWgBTUkz3u+N2iMe6yKb5+ +R1d4CeM9YTAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4ICAQBCqdzS +tPHkMYWjYs6aREwob9whjyG8a4Qp6IkP1SYHCwpzsTeWLi9ybEcDRb3jZ4iRxbZg +7GFxjqHoWgBZHAIyICMsHupOJEtXq5hx86NuMwk/12bx1eNj0yTIAnVOA+em/ZtB +zR38OwB8xXmjKd0Ow1Y7zCh5zE2gU+sR0JOJSfxXUZrJvwDNrbcmZPQ+kwuq4cyv +fxZnvZf/owbyOLQFdbiPQbbiZ7JSv8q7GCMleULCEygrsWClYkULUByhKykCHJIU +wfq1owge9EqG/4CDCCjB9vBFmUyv3FJhgWnzd6tPQckFoHSoD0Bjsv/pQFcsGLcg ++e/Mm6hZgCXXwI2WHYbxqz5ToOaRQQYo6N77jWejOBMecOZmPDyQ2nz73aJd11GW +NiDT7pyMlBJA8W4wAvVP4ow2ugqsPjqZ6EyismIGFUTqMp+NtXOsLPK+sEMhKhJ9 +ulczRpPEf25roBt6aEk2fTAfAPmbpvNamBLSbBU23mzJ38RmfhxLOlOgCGbBBX4d +kE+/+En8UJO4X8CKaKRo/c5G2UZ6++2cjp6SPrsGENDMW5yBGegrDw+ow8/bLxIr +OjWpSe2cygovy3aHE6UBOgkxw9KIaSEqFgjQZ0i+xO6l6qQoljQgUGXfecVMR+7C +4KsyVVTMlK9/thA7Zfc8a5z8ZCtIKkT52XsJhw== +-----END CERTIFICATE----- diff --git a/rpc/jsonrpc/server/test.key b/rpc/jsonrpc/server/test.key new file mode 100644 index 0000000..ae0e523 --- /dev/null +++ b/rpc/jsonrpc/server/test.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEoQIBAAKCAQEA0Fprp1z0ZlwiEAdapWvHQs41h/4iVu9M/vKtXjnCzSLHxNfU +1Q6INjVzDMofxrL8dhfjl7Z8Uuu0uJ1z2H5qmwLnmTdV1zLTT4qyv9p2NHwPgD8a +mdNL6FUMdOWog171rtRKiTfhmvWtzd+Hgia7lHES6uMzCQD/fqTr46lcynaqUphL +V8arCfYoaFeSn/JNZkgsQxcFrM3EbHjF+phfNabpuh7IkBekzYM2S/t23Br8JZhZ +pxRAkCk0ifCfn4Hwsuij6lqmmR9k6MAP39ocqzIVNJaaZZ6DtX/+i4He7m8i2p8Y +/7fGY+B5h4TI4h78/Z/xtG5Cz4YbBIKaLoXUZQIDAQABAoH/NodzpVmunRt/zrIe +By0t+U3+tJjOY/I9NHxO41o6oXV40wupqBkljQpwEejUaCxv5nhaGFqqLwmBQs/y +gbaUL/2Sn4bb8HZc13R1U8DZLuNJK0dYrumd9DBOEkoI0FkJ87ebyk3VvbiOxFK8 +JFP+w9rUGKVdtf2M4JhJJEwu/M2Yawx9/8CrCIY2G6ufaylrIysLeQMsxrogF8n4 +hq7fyqveWRzxhqUxS2fp9Ynpx4jnd1lMzv+z3i8eEsW+gB9yke7UkXZMbtZg1xfB +JjiEfcDVfSwSihhgOYttgQ9hkIdohDUak7OzRSWVBuoxWUhMfrQxw/HZlgZJL9Vf +rGdlAoGBANOGmgEGky+acV33WTWGV5OdAw6B/SlBEoORJbj6UzQiUz3hFH/Tgpbj +JOKHWGbGd8OtOYbt9JoofGlNgHA/4nAEYAc2HGa+q0fBwMUflU0DudAxXis4jDmE +D76moGmyJoSgwVrp1W/vwNixA5RpcZ3Wst2nf9RKLr+DxypHTit/AoGBAPwpDeqc +rwXOTl0KR/080Nc11Z03VIVZAGfA59J73HmADF9bBVlmReQdkwX0lERchdzD0lfa +XqbqBLr4FS5Uqyn5f3DCaMnOeKfvtGw2z6LnY+w03mii4PEW/vNKLlB18NdduPwL +KeAc08Zh+qJFMKD1PoEQOH+Y7NybBbaQL8IbAoGAfPPUYaq6o7I+Kd4FysKTVVW5 +CobrP8V65FGH0R++qttkBPfDHkeZqvx/O3nsVLoE4YigpP5IMhCcfbAUoTp7zuQm +vdvPJzqW/4qLD2c60QXUbBHdqPZ8jzVd/6d6tzVP36T+02+yb69XYiofDTrErRK5 +EorxzjwMJYH40xbQLI0CgYBh7d/FucwPSSwN3ixPIQtKSVIImLBuiT4rDTP6/reF +SEGF1ueg7KNAEGxE59OdKQGj1zkdfWU9Fa14n1g6gg9nYcoolJf1qAYb0nAThsXk +0lBwL6ggowERIIkrGygZf3Rlb7SjzgIZU5i7dtnLo2tbV2NK5G3MwCtdEaeKWzzw ++QKBgQC7+JPHoqbnNgis2vCGLKMOU3HpJK/rYEU/8ZUegc9lshEFZYsRbtKQQJQs +nqsChrG8UoK84frujEBkO/Nzsil85p8ar79wZguGnVvswTWaTuKvl8H/qQQ/JSHZ +OHGQD4qwTCkdRr8Vf8NfuCoZlJDnHncLJZNWjrb5feqCnJ/YIQ== +-----END RSA PRIVATE KEY----- diff --git a/rpc/jsonrpc/server/ws_handler.go b/rpc/jsonrpc/server/ws_handler.go new file mode 100644 index 0000000..e899092 --- /dev/null +++ b/rpc/jsonrpc/server/ws_handler.go @@ -0,0 +1,458 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "reflect" + "runtime/debug" + "time" + + "github.com/gorilla/websocket" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/service" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +// WebSocket handler + +const ( + defaultWSWriteChanCapacity = 100 + defaultWSWriteWait = 10 * time.Second + defaultWSReadWait = 30 * time.Second + defaultWSPingPeriod = (defaultWSReadWait * 9) / 10 +) + +// WebsocketManager provides a WS handler for incoming connections and passes a +// map of functions along with any additional params to new connections. +// NOTE: The websocket path is defined externally, e.g. in node/node.go +type WebsocketManager struct { + websocket.Upgrader + + funcMap map[string]*RPCFunc + logger log.Logger + wsConnOptions []func(*wsConnection) +} + +// NewWebsocketManager returns a new WebsocketManager that passes a map of +// functions, connection options and logger to new WS connections. +func NewWebsocketManager( + funcMap map[string]*RPCFunc, + wsConnOptions ...func(*wsConnection), +) *WebsocketManager { + return &WebsocketManager{ + funcMap: funcMap, + Upgrader: websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { + // TODO ??? + // + // The default behavior would be relevant to browser-based clients, + // afaik. I suppose having a pass-through is a workaround for allowing + // for more complex security schemes, shifting the burden of + // AuthN/AuthZ outside the CometBFT RPC. + // I can't think of other uses right now that would warrant a TODO + // though. The real backstory of this TODO shall remain shrouded in + // mystery + return true + }, + }, + logger: log.NewNopLogger(), + wsConnOptions: wsConnOptions, + } +} + +// SetLogger sets the logger. +func (wm *WebsocketManager) SetLogger(l log.Logger) { + wm.logger = l +} + +// WebsocketHandler upgrades the request/response (via http.Hijack) and starts +// the wsConnection. +func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) { + wsConn, err := wm.Upgrade(w, r, nil) + if err != nil { + // TODO - return http error + wm.logger.Error("Failed to upgrade connection", "err", err) + return + } + defer func() { + if err := wsConn.Close(); err != nil { + wm.logger.Error("Failed to close connection", "err", err) + } + }() + + // register connection + con := newWSConnection(wsConn, wm.funcMap, wm.wsConnOptions...) + con.SetLogger(wm.logger.With("remote", wsConn.RemoteAddr())) + wm.logger.Info("New websocket connection", "remote", con.remoteAddr) + err = con.Start() // BLOCKING + if err != nil { + wm.logger.Error("Failed to start connection", "err", err) + return + } + if err := con.Stop(); err != nil { + wm.logger.Error("error while stopping connection", "error", err) + } +} + +// WebSocket connection + +// A single websocket connection contains listener id, underlying ws +// connection, and the event switch for subscribing to events. +// +// In case of an error, the connection is stopped. +type wsConnection struct { + service.BaseService + + remoteAddr string + baseConn *websocket.Conn + // writeChan is never closed, to allow WriteRPCResponse() to fail. + writeChan chan types.RPCResponse + + // chan, which is closed when/if readRoutine errors + // used to abort writeRoutine + readRoutineQuit chan struct{} + + funcMap map[string]*RPCFunc + + // write channel capacity + writeChanCapacity int + + // each write times out after this. + writeWait time.Duration + + // Connection times out if we haven't received *anything* in this long, not even pings. + readWait time.Duration + + // Send pings to server with this period. Must be less than readWait, but greater than zero. + pingPeriod time.Duration + + // Maximum message size. + readLimit int64 + + // callback which is called upon disconnect + onDisconnect func(remoteAddr string) + + ctx context.Context + cancel context.CancelFunc +} + +// NewWSConnection wraps websocket.Conn. +// +// See the commentary on the func(*wsConnection) functions for a detailed +// description of how to configure ping period and pong wait time. NOTE: if the +// write buffer is full, pongs may be dropped, which may cause clients to +// disconnect. see https://github.com/gorilla/websocket/issues/97 +func newWSConnection( + baseConn *websocket.Conn, + funcMap map[string]*RPCFunc, + options ...func(*wsConnection), +) *wsConnection { + wsc := &wsConnection{ + remoteAddr: baseConn.RemoteAddr().String(), + baseConn: baseConn, + funcMap: funcMap, + writeWait: defaultWSWriteWait, + writeChanCapacity: defaultWSWriteChanCapacity, + readWait: defaultWSReadWait, + pingPeriod: defaultWSPingPeriod, + readRoutineQuit: make(chan struct{}), + } + for _, option := range options { + option(wsc) + } + wsc.baseConn.SetReadLimit(wsc.readLimit) + wsc.BaseService = *service.NewBaseService(nil, "wsConnection", wsc) + return wsc +} + +// OnDisconnect sets a callback which is used upon disconnect - not +// Goroutine-safe. Nop by default. +func OnDisconnect(onDisconnect func(remoteAddr string)) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.onDisconnect = onDisconnect + } +} + +// WriteWait sets the amount of time to wait before a websocket write times out. +// It should only be used in the constructor - not Goroutine-safe. +func WriteWait(writeWait time.Duration) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.writeWait = writeWait + } +} + +// WriteChanCapacity sets the capacity of the websocket write channel. +// It should only be used in the constructor - not Goroutine-safe. +func WriteChanCapacity(cap int) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.writeChanCapacity = cap + } +} + +// ReadWait sets the amount of time to wait before a websocket read times out. +// It should only be used in the constructor - not Goroutine-safe. +func ReadWait(readWait time.Duration) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.readWait = readWait + } +} + +// PingPeriod sets the duration for sending websocket pings. +// It should only be used in the constructor - not Goroutine-safe. +func PingPeriod(pingPeriod time.Duration) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.pingPeriod = pingPeriod + } +} + +// ReadLimit sets the maximum size for reading message. +// It should only be used in the constructor - not Goroutine-safe. +func ReadLimit(readLimit int64) func(*wsConnection) { + return func(wsc *wsConnection) { + wsc.readLimit = readLimit + } +} + +// OnStart implements service.Service by starting the read and write routines. It +// blocks until there's some error. +func (wsc *wsConnection) OnStart() error { + wsc.writeChan = make(chan types.RPCResponse, wsc.writeChanCapacity) + + // Read subscriptions/unsubscriptions to events + go wsc.readRoutine() + // Write responses, BLOCKING. + wsc.writeRoutine() + + return nil +} + +// OnStop implements service.Service by unsubscribing remoteAddr from all +// subscriptions. +func (wsc *wsConnection) OnStop() { + if wsc.onDisconnect != nil { + wsc.onDisconnect(wsc.remoteAddr) + } + + if wsc.ctx != nil { + wsc.cancel() + } +} + +// GetRemoteAddr returns the remote address of the underlying connection. +// It implements WSRPCConnection +func (wsc *wsConnection) GetRemoteAddr() string { + return wsc.remoteAddr +} + +// WriteRPCResponse pushes a response to the writeChan, and blocks until it is +// accepted. +// It implements WSRPCConnection. It is Goroutine-safe. +func (wsc *wsConnection) WriteRPCResponse(ctx context.Context, resp types.RPCResponse) error { + select { + case <-wsc.Quit(): + return errors.New("connection was stopped") + case <-ctx.Done(): + return ctx.Err() + case wsc.writeChan <- resp: + return nil + } +} + +// TryWriteRPCResponse attempts to push a response to the writeChan, but does +// not block. +// It implements WSRPCConnection. It is Goroutine-safe +func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool { + select { + case <-wsc.Quit(): + return false + case wsc.writeChan <- resp: + return true + default: + return false + } +} + +// Context returns the connection's context. +// The context is canceled when the client's connection closes. +func (wsc *wsConnection) Context() context.Context { + if wsc.ctx != nil { + return wsc.ctx + } + wsc.ctx, wsc.cancel = context.WithCancel(context.Background()) + return wsc.ctx +} + +// Read from the socket and subscribe to or unsubscribe from events +func (wsc *wsConnection) readRoutine() { + // readRoutine will block until response is written or WS connection is closed + writeCtx := context.Background() + + defer func() { + if r := recover(); r != nil { + err, ok := r.(error) + if !ok { + err = fmt.Errorf("WSJSONRPC: %v", r) + } + wsc.Logger.Error("Panic in WSJSONRPC handler", "err", err, "stack", string(debug.Stack())) + if err := wsc.WriteRPCResponse(writeCtx, types.RPCInternalError(types.JSONRPCIntID(-1), err)); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + go wsc.readRoutine() + } + }() + + wsc.baseConn.SetPongHandler(func(m string) error { + return wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait)) + }) + + for { + select { + case <-wsc.Quit(): + return + default: + // reset deadline for every type of message (control or data) + if err := wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait)); err != nil { + wsc.Logger.Error("failed to set read deadline", "err", err) + } + + _, r, err := wsc.baseConn.NextReader() + if err != nil { + if websocket.IsCloseError(err, websocket.CloseNormalClosure) { + wsc.Logger.Info("Client closed the connection") + } else { + wsc.Logger.Error("Failed to read request", "err", err) + } + if err := wsc.Stop(); err != nil { + wsc.Logger.Error("Error closing websocket connection", "err", err) + } + close(wsc.readRoutineQuit) + return + } + + dec := json.NewDecoder(r) + var request types.RPCRequest + err = dec.Decode(&request) + if err != nil { + if err := wsc.WriteRPCResponse(writeCtx, + types.RPCParseError(fmt.Errorf("error unmarshaling request: %w", err))); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + continue + } + + // A Notification is a Request object without an "id" member. + // The Server MUST NOT reply to a Notification, including those that are within a batch request. + if request.ID == nil { + wsc.Logger.Debug( + "WSJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)", + "req", request, + ) + continue + } + + // Now, fetch the RPCFunc and execute it. + rpcFunc := wsc.funcMap[request.Method] + if rpcFunc == nil { + if err := wsc.WriteRPCResponse(writeCtx, types.RPCMethodNotFoundError(request.ID)); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + continue + } + + ctx := &types.Context{JSONReq: &request, WSConn: wsc} + args := []reflect.Value{reflect.ValueOf(ctx)} + if len(request.Params) > 0 { + fnArgs, err := jsonParamsToArgs(rpcFunc, request.Params) + if err != nil { + if err := wsc.WriteRPCResponse(writeCtx, + types.RPCInternalError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)), + ); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + continue + } + args = append(args, fnArgs...) + } + + returns := rpcFunc.f.Call(args) + + // TODO: Need to encode args/returns to string if we want to log them + wsc.Logger.Info("WSJSONRPC", "method", request.Method) + + result, err := unreflectResult(returns) + if err != nil { + if err := wsc.WriteRPCResponse(writeCtx, types.RPCInternalError(request.ID, err)); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + continue + } + + if err := wsc.WriteRPCResponse(writeCtx, types.NewRPCSuccessResponse(request.ID, result)); err != nil { + wsc.Logger.Error("Error writing RPC response", "err", err) + } + } + } +} + +// receives on a write channel and writes out on the socket +func (wsc *wsConnection) writeRoutine() { + pingTicker := time.NewTicker(wsc.pingPeriod) + defer pingTicker.Stop() + + // https://github.com/gorilla/websocket/issues/97 + pongs := make(chan string, 1) + wsc.baseConn.SetPingHandler(func(m string) error { + select { + case pongs <- m: + default: + } + return nil + }) + + for { + select { + case <-wsc.Quit(): + return + case <-wsc.readRoutineQuit: // error in readRoutine + return + case m := <-pongs: + err := wsc.writeMessageWithDeadline(websocket.PongMessage, []byte(m)) + if err != nil { + wsc.Logger.Info("Failed to write pong (client may disconnect)", "err", err) + } + case <-pingTicker.C: + err := wsc.writeMessageWithDeadline(websocket.PingMessage, []byte{}) + if err != nil { + wsc.Logger.Error("Failed to write ping", "err", err) + return + } + case msg := <-wsc.writeChan: + // Use json.MarshalIndent instead of Marshal for pretty output. + // Pretty output not necessary, since most consumers of WS events are + // automated processes, not humans. + jsonBytes, err := json.Marshal(msg) + if err != nil { + wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err) + continue + } + if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil { + wsc.Logger.Error("Failed to write response", "err", err, "msg", msg) + return + } + } + } +} + +// All writes to the websocket must (re)set the write deadline. +// If some writes don't set it while others do, they may timeout incorrectly +// (https://github.com/tendermint/tendermint/issues/553) +func (wsc *wsConnection) writeMessageWithDeadline(msgType int, msg []byte) error { + if err := wsc.baseConn.SetWriteDeadline(time.Now().Add(wsc.writeWait)); err != nil { + return err + } + return wsc.baseConn.WriteMessage(msgType, msg) +} diff --git a/rpc/jsonrpc/server/ws_handler_test.go b/rpc/jsonrpc/server/ws_handler_test.go new file mode 100644 index 0000000..69ede2d --- /dev/null +++ b/rpc/jsonrpc/server/ws_handler_test.go @@ -0,0 +1,56 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/libs/log" + types "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func TestWebsocketManagerHandler(t *testing.T) { + s := newWSServer() + defer s.Close() + + // check upgrader works + d := websocket.Dialer{} + c, dialResp, err := d.Dial("ws://"+s.Listener.Addr().String()+"/websocket", nil) + require.NoError(t, err) + + if got, want := dialResp.StatusCode, http.StatusSwitchingProtocols; got != want { + t.Errorf("dialResp.StatusCode = %q, want %q", got, want) + } + + // check basic functionality works + req, err := types.MapToRequest( + types.JSONRPCStringID("TestWebsocketManager"), + "c", + map[string]interface{}{"s": "a", "i": 10}, + ) + require.NoError(t, err) + err = c.WriteJSON(req) + require.NoError(t, err) + + var resp types.RPCResponse + err = c.ReadJSON(&resp) + require.NoError(t, err) + require.Nil(t, resp.Error) + dialResp.Body.Close() +} + +func newWSServer() *httptest.Server { + funcMap := map[string]*RPCFunc{ + "c": NewWSRPCFunc(func(ctx *types.Context, s string, i int) (string, error) { return "foo", nil }, "s,i"), + } + wm := NewWebsocketManager(funcMap) + wm.SetLogger(log.TestingLogger()) + + mux := http.NewServeMux() + mux.HandleFunc("/websocket", wm.WebsocketHandler) + + return httptest.NewServer(mux) +} diff --git a/rpc/jsonrpc/test/data.json b/rpc/jsonrpc/test/data.json new file mode 100644 index 0000000..04b4df5 --- /dev/null +++ b/rpc/jsonrpc/test/data.json @@ -0,0 +1,9 @@ +{ + "jsonrpc": "2.0", + "id": "", + "method": "hello_world", + "params": { + "name": "my_world", + "num": 5 + } +} diff --git a/rpc/jsonrpc/test/integration_test.sh b/rpc/jsonrpc/test/integration_test.sh new file mode 100755 index 0000000..f0b81a2 --- /dev/null +++ b/rpc/jsonrpc/test/integration_test.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +set -e + +# Get the directory of where this script is. +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done +DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +# Change into that dir because we expect that. +pushd "$DIR" + +echo "==> Building the server" +go build -o rpcserver main.go + +echo "==> (Re)starting the server" +PID=$(pgrep rpcserver || echo "") +if [[ $PID != "" ]]; then + kill -9 "$PID" +fi +./rpcserver & +PID=$! +sleep 2 + +echo "==> simple request" +R1=$(curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5') +R2=$(curl -s --data @data.json http://localhost:8008) +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> request with 0x-prefixed hex string arg" +R1=$(curl -s 'http://localhost:8008/hello_world?name=0x41424344&num=123') +R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi ABCD 123"},"error":""}' +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> request with missing params" +R1=$(curl -s 'http://localhost:8008/hello_world') +R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi 0"},"error":""}' +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> request with unquoted string arg" +R1=$(curl -s 'http://localhost:8008/hello_world?name=abcd&num=123') +R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: invalid character 'a' looking for beginning of value\"}" +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> request with string type when expecting number arg" +R1=$(curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd') +R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a hex string arg, but expected 'int'\"}" +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> Stopping the server" +kill -9 $PID + +rm -f rpcserver + +popd +exit 0 diff --git a/rpc/jsonrpc/test/main.go b/rpc/jsonrpc/test/main.go new file mode 100644 index 0000000..72d9e7c --- /dev/null +++ b/rpc/jsonrpc/test/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "net/http" + "os" + + "github.com/cometbft/cometbft/libs/log" + cmtos "github.com/cometbft/cometbft/libs/os" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +var routes = map[string]*rpcserver.RPCFunc{ + "hello_world": rpcserver.NewRPCFunc(HelloWorld, "name,num"), +} + +func HelloWorld(_ *rpctypes.Context, name string, num int) (Result, error) { + return Result{fmt.Sprintf("hi %s %d", name, num)}, nil +} + +type Result struct { + Result string +} + +func main() { + var ( + mux = http.NewServeMux() + logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + ) + + // Stop upon receiving SIGTERM or CTRL-C. + cmtos.TrapSignal(logger, func() {}) + + rpcserver.RegisterRPCFuncs(mux, routes, logger) + config := rpcserver.DefaultConfig() + listener, err := rpcserver.Listen("tcp://127.0.0.1:8008", config.MaxOpenConnections) + if err != nil { + cmtos.Exit(err.Error()) + } + + if err = rpcserver.Serve(listener, mux, logger, config); err != nil { + cmtos.Exit(err.Error()) + } +} diff --git a/rpc/jsonrpc/types/types.go b/rpc/jsonrpc/types/types.go new file mode 100644 index 0000000..9aadb5e --- /dev/null +++ b/rpc/jsonrpc/types/types.go @@ -0,0 +1,327 @@ +package types + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "reflect" + "strings" + + cmtjson "github.com/cometbft/cometbft/libs/json" +) + +// a wrapper to emulate a sum type: jsonrpcid = string | int +// TODO: refactor when Go 2.0 arrives https://github.com/golang/go/issues/19412 +type jsonrpcid interface { + isJSONRPCID() +} + +// JSONRPCStringID a wrapper for JSON-RPC string IDs +type JSONRPCStringID string + +func (JSONRPCStringID) isJSONRPCID() {} +func (id JSONRPCStringID) String() string { return string(id) } + +// JSONRPCIntID a wrapper for JSON-RPC integer IDs +type JSONRPCIntID int + +func (JSONRPCIntID) isJSONRPCID() {} +func (id JSONRPCIntID) String() string { return fmt.Sprintf("%d", id) } + +func idFromInterface(idInterface interface{}) (jsonrpcid, error) { + switch id := idInterface.(type) { + case string: + return JSONRPCStringID(id), nil + case float64: + // json.Unmarshal uses float64 for all numbers + // (https://golang.org/pkg/encoding/json/#Unmarshal), + // but the JSONRPC2.0 spec says the id SHOULD NOT contain + // decimals - so we truncate the decimals here. + return JSONRPCIntID(int(id)), nil + default: + typ := reflect.TypeOf(id) + return nil, fmt.Errorf("json-rpc ID (%v) is of unknown type (%v)", id, typ) + } +} + +//---------------------------------------- +// REQUEST + +type RPCRequest struct { + JSONRPC string `json:"jsonrpc"` + ID jsonrpcid `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{} +} + +// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int +func (req *RPCRequest) UnmarshalJSON(data []byte) error { + unsafeReq := struct { + JSONRPC string `json:"jsonrpc"` + ID interface{} `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{} + }{} + + err := json.Unmarshal(data, &unsafeReq) + if err != nil { + return err + } + + if unsafeReq.ID == nil { // notification + return nil + } + + req.JSONRPC = unsafeReq.JSONRPC + req.Method = unsafeReq.Method + req.Params = unsafeReq.Params + id, err := idFromInterface(unsafeReq.ID) + if err != nil { + return err + } + req.ID = id + + return nil +} + +func NewRPCRequest(id jsonrpcid, method string, params json.RawMessage) RPCRequest { + return RPCRequest{ + JSONRPC: "2.0", + ID: id, + Method: method, + Params: params, + } +} + +func (req RPCRequest) String() string { + return fmt.Sprintf("RPCRequest{%s %s/%X}", req.ID, req.Method, req.Params) +} + +func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (RPCRequest, error) { + var paramsMap = make(map[string]json.RawMessage, len(params)) + for name, value := range params { + valueJSON, err := cmtjson.Marshal(value) + if err != nil { + return RPCRequest{}, err + } + paramsMap[name] = valueJSON + } + + payload, err := json.Marshal(paramsMap) + if err != nil { + return RPCRequest{}, err + } + + return NewRPCRequest(id, method, payload), nil +} + +func ArrayToRequest(id jsonrpcid, method string, params []interface{}) (RPCRequest, error) { + var paramsMap = make([]json.RawMessage, len(params)) + for i, value := range params { + valueJSON, err := cmtjson.Marshal(value) + if err != nil { + return RPCRequest{}, err + } + paramsMap[i] = valueJSON + } + + payload, err := json.Marshal(paramsMap) + if err != nil { + return RPCRequest{}, err + } + + return NewRPCRequest(id, method, payload), nil +} + +//---------------------------------------- +// RESPONSE + +type RPCError struct { + Code int `json:"code"` + Message string `json:"message"` + Data string `json:"data,omitempty"` +} + +func (err RPCError) Error() string { + const baseFormat = "RPC error %v - %s" + if err.Data != "" { + return fmt.Sprintf(baseFormat+": %s", err.Code, err.Message, err.Data) + } + return fmt.Sprintf(baseFormat, err.Code, err.Message) +} + +type RPCResponse struct { + JSONRPC string `json:"jsonrpc"` + ID jsonrpcid `json:"id,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *RPCError `json:"error,omitempty"` +} + +// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int +func (resp *RPCResponse) UnmarshalJSON(data []byte) error { + unsafeResp := &struct { + JSONRPC string `json:"jsonrpc"` + ID interface{} `json:"id,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *RPCError `json:"error,omitempty"` + }{} + err := json.Unmarshal(data, &unsafeResp) + if err != nil { + return err + } + resp.JSONRPC = unsafeResp.JSONRPC + resp.Error = unsafeResp.Error + resp.Result = unsafeResp.Result + if unsafeResp.ID == nil { + return nil + } + id, err := idFromInterface(unsafeResp.ID) + if err != nil { + return err + } + resp.ID = id + return nil +} + +func NewRPCSuccessResponse(id jsonrpcid, res interface{}) RPCResponse { + var rawMsg json.RawMessage + + if res != nil { + var js []byte + js, err := cmtjson.Marshal(res) + if err != nil { + return RPCInternalError(id, fmt.Errorf("error marshaling response: %w", err)) + } + rawMsg = json.RawMessage(js) + } + + return RPCResponse{JSONRPC: "2.0", ID: id, Result: rawMsg} +} + +func NewRPCErrorResponse(id jsonrpcid, code int, msg string, data string) RPCResponse { + return RPCResponse{ + JSONRPC: "2.0", + ID: id, + Error: &RPCError{Code: code, Message: msg, Data: data}, + } +} + +func (resp RPCResponse) String() string { + if resp.Error == nil { + return fmt.Sprintf("RPCResponse{%s %X}", resp.ID, resp.Result) + } + return fmt.Sprintf("RPCResponse{%s %v}", resp.ID, resp.Error) +} + +// From the JSON-RPC 2.0 spec: +// +// If there was an error in detecting the id in the Request object (e.g. Parse +// error/Invalid Request), it MUST be Null. +func RPCParseError(err error) RPCResponse { + return NewRPCErrorResponse(nil, -32700, "Parse error. Invalid JSON", err.Error()) +} + +// From the JSON-RPC 2.0 spec: +// +// If there was an error in detecting the id in the Request object (e.g. Parse +// error/Invalid Request), it MUST be Null. +func RPCInvalidRequestError(id jsonrpcid, err error) RPCResponse { + return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error()) +} + +func RPCMethodNotFoundError(id jsonrpcid) RPCResponse { + return NewRPCErrorResponse(id, -32601, "Method not found", "") +} + +func RPCInvalidParamsError(id jsonrpcid, err error) RPCResponse { + return NewRPCErrorResponse(id, -32602, "Invalid params", err.Error()) +} + +func RPCInternalError(id jsonrpcid, err error) RPCResponse { + return NewRPCErrorResponse(id, -32603, "Internal error", err.Error()) +} + +func RPCServerError(id jsonrpcid, err error) RPCResponse { + return NewRPCErrorResponse(id, -32000, "Server error", err.Error()) +} + +//---------------------------------------- + +// WSRPCConnection represents a websocket connection. +type WSRPCConnection interface { + // GetRemoteAddr returns a remote address of the connection. + GetRemoteAddr() string + // WriteRPCResponse writes the response onto connection (BLOCKING). + WriteRPCResponse(context.Context, RPCResponse) error + // TryWriteRPCResponse tries to write the response onto connection (NON-BLOCKING). + TryWriteRPCResponse(RPCResponse) bool + // Context returns the connection's context. + Context() context.Context +} + +// Context is the first parameter for all functions. It carries a json-rpc +// request, http request and websocket connection. +// +// - JSONReq is non-nil when JSONRPC is called over websocket or HTTP. +// - WSConn is non-nil when we're connected via a websocket. +// - HTTPReq is non-nil when URI or JSONRPC is called over HTTP. +type Context struct { + // json-rpc request + JSONReq *RPCRequest + // websocket connection + WSConn WSRPCConnection + // http request + HTTPReq *http.Request +} + +// RemoteAddr returns the remote address (usually a string "IP:port"). +// If neither HTTPReq nor WSConn is set, an empty string is returned. +// HTTP: +// +// http.Request#RemoteAddr +// +// WS: +// +// result of GetRemoteAddr +func (ctx *Context) RemoteAddr() string { + if ctx.HTTPReq != nil { + return ctx.HTTPReq.RemoteAddr + } else if ctx.WSConn != nil { + return ctx.WSConn.GetRemoteAddr() + } + return "" +} + +// Context returns the request's context. +// The returned context is always non-nil; it defaults to the background context. +// HTTP: +// +// The context is canceled when the client's connection closes, the request +// is canceled (with HTTP/2), or when the ServeHTTP method returns. +// +// WS: +// +// The context is canceled when the client's connections closes. +func (ctx *Context) Context() context.Context { + if ctx.HTTPReq != nil { + return ctx.HTTPReq.Context() + } else if ctx.WSConn != nil { + return ctx.WSConn.Context() + } + return context.Background() +} + +//---------------------------------------- +// SOCKETS + +// Determine if its a unix or tcp socket. +// If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port +// TODO: deprecate +func SocketType(listenAddr string) string { + socketType := "unix" + if len(strings.Split(listenAddr, ":")) >= 2 { + socketType = "tcp" + } + return socketType +} diff --git a/rpc/jsonrpc/types/types_test.go b/rpc/jsonrpc/types/types_test.go new file mode 100644 index 0000000..afee30e --- /dev/null +++ b/rpc/jsonrpc/types/types_test.go @@ -0,0 +1,83 @@ +package types + +import ( + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type SampleResult struct { + Value string +} + +type responseTest struct { + id jsonrpcid + expected string +} + +var responseTests = []responseTest{ + {JSONRPCStringID("1"), `"1"`}, + {JSONRPCStringID("alphabet"), `"alphabet"`}, + {JSONRPCStringID(""), `""`}, + {JSONRPCStringID("àáâ"), `"àáâ"`}, + {JSONRPCIntID(-1), "-1"}, + {JSONRPCIntID(0), "0"}, + {JSONRPCIntID(1), "1"}, + {JSONRPCIntID(100), "100"}, +} + +func TestResponses(t *testing.T) { + assert := assert.New(t) + for _, tt := range responseTests { + jsonid := tt.id + a := NewRPCSuccessResponse(jsonid, &SampleResult{"hello"}) + b, _ := json.Marshal(a) + s := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected) + assert.Equal(s, string(b)) + + d := RPCParseError(errors.New("hello world")) + e, _ := json.Marshal(d) + f := `{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error. Invalid JSON","data":"hello world"}}` + assert.Equal(f, string(e)) + + g := RPCMethodNotFoundError(jsonid) + h, _ := json.Marshal(g) + i := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"error":{"code":-32601,"message":"Method not found"}}`, tt.expected) + assert.Equal(string(h), i) + } +} + +func TestUnmarshallResponses(t *testing.T) { + assert := assert.New(t) + for _, tt := range responseTests { + response := &RPCResponse{} + err := json.Unmarshal( + []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected)), + response, + ) + assert.Nil(err) + a := NewRPCSuccessResponse(tt.id, &SampleResult{"hello"}) + assert.Equal(*response, a) + } + response := &RPCResponse{} + err := json.Unmarshal([]byte(`{"jsonrpc":"2.0","id":true,"result":{"Value":"hello"}}`), response) + assert.NotNil(err) +} + +func TestRPCError(t *testing.T) { + assert.Equal(t, "RPC error 12 - Badness: One worse than a code 11", + fmt.Sprintf("%v", &RPCError{ + Code: 12, + Message: "Badness", + Data: "One worse than a code 11", + })) + + assert.Equal(t, "RPC error 12 - Badness", + fmt.Sprintf("%v", &RPCError{ + Code: 12, + Message: "Badness", + })) +} diff --git a/rpc/openapi/index.html b/rpc/openapi/index.html new file mode 100644 index 0000000..a777d9f --- /dev/null +++ b/rpc/openapi/index.html @@ -0,0 +1,27 @@ + + + + + + + CometBFT RPC + + + + + + +
+ + + + diff --git a/rpc/openapi/openapi.yaml b/rpc/openapi/openapi.yaml new file mode 100644 index 0000000..aac949f --- /dev/null +++ b/rpc/openapi/openapi.yaml @@ -0,0 +1,2902 @@ +openapi: 3.0.0 +info: + title: CometBFT RPC + contact: + name: CometBFT + url: https://cometbft.com/ + description: | + CometBFT supports the following RPC protocols: + + * URI over HTTP + * JSONRPC over HTTP + * JSONRPC over websockets + + ## Configuration + + RPC can be configured by tuning parameters under `[rpc]` table in the + `$CMTHOME/config/config.toml` file or by using the `--rpc.X` command-line + flags. + + The default RPC listen address is `tcp://127.0.0.1:26657`. + To set another address, set the `laddr` config parameter to desired value. + CORS (Cross-Origin Resource Sharing) can be enabled by setting + `cors_allowed_origins`, `cors_allowed_methods`, `cors_allowed_headers` + config parameters. + + If testing using a local RPC node, under the `[rpc]` + section change the `cors_allowed_origins` property, please add the URL of + the site where this OpenAPI document is running, for example: + + `cors_allowed_origins = ["http://localhost:8088"]` + + or if testing from the official documentation site: + + `cors_allowed_origins = ["https://docs.cometbft.com"]` + + ## Arguments + + Arguments which expect strings or byte arrays may be passed as quoted + strings, like `"abc"` or as `0x`-prefixed strings, like `0x616263`. + + ## URI/HTTP + + A REST like interface. + + curl localhost:26657/block?height=5 + + ## JSONRPC/HTTP + + JSONRPC requests can be POST'd to the root RPC endpoint via HTTP. + + curl --header "Content-Type: application/json" --request POST --data '{"method": "block", "params": ["5"], "id": 1}' localhost:26657 + + ## JSONRPC/websockets + + JSONRPC requests can be also made via websocket. + The websocket endpoint is at `/websocket`, e.g. `localhost:26657/websocket`. + Asynchronous RPC functions like event `subscribe` and `unsubscribe` are + only available via websockets. + + For example using the [websocat](https://github.com/vi/websocat) tool, you can subscribe for 'NewBlock` events + with the following command: + + echo '{ "jsonrpc": "2.0","method": "subscribe","id": 0,"params": {"query": "tm.event='"'NewBlock'"'"} }' | websocat -n -t ws://127.0.0.1:26657/websocket + + version: "v0.38.x" + license: + name: Apache 2.0 + url: https://github.com/cometbft/cometbft/blob/v0.38.x/LICENSE +servers: + - url: https://rpc.cosmos.directory/cosmoshub + description: Interact with the CometBFT RPC from a public node in the Cosmos registry + - url: http://localhost:26657 + description: Interact with CometBFT RPC node running locally +tags: + - name: Info + description: Informations about the node APIs + - name: Tx + description: Transactions broadcast APIs + - name: ABCI + description: ABCI APIs + - name: Evidence + description: Evidence APIs + - name: Unsafe + description: Unsafe APIs +paths: + /broadcast_tx_sync: + get: + summary: Returns with the response from CheckTx. Does not wait for DeliverTx result. + tags: + - Tx + operationId: broadcast_tx_sync + description: | + If you want to be sure that the transaction is included in a block, you can + subscribe for the result using JSONRPC via a websocket. See + https://docs.cometbft.com/v0.38.x/core/subscription.html + If you haven't received anything after a couple of blocks, resend it. If the + same happens again, send it to some other node. A few reasons why it could + happen: + + 1. malicious node can drop or pretend it had committed your tx + 2. malicious proposer (not necessary the one you're communicating with) can + drop transactions, which might become valid in the future + (https://github.com/tendermint/tendermint/issues/3322) + + + Please refer to [formatting/encoding rules](https://docs.cometbft.com/v0.38.x/core/using-cometbft.html#formatting) + for additional details + + parameters: + - in: query + name: tx + required: true + schema: + type: string + example: "456" + description: The transaction + responses: + "200": + description: Empty + content: + application/json: + schema: + $ref: "#/components/schemas/BroadcastTxResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /broadcast_tx_async: + get: + summary: Returns right away, with no response. Does not wait for CheckTx nor DeliverTx results. + tags: + - Tx + operationId: broadcast_tx_async + description: | + If you want to be sure that the transaction is included in a block, you can + subscribe for the result using JSONRPC via a websocket. See + https://docs.cometbft.com/v0.38.x/core/subscription.html + If you haven't received anything after a couple of blocks, resend it. If the + same happens again, send it to some other node. A few reasons why it could + happen: + + 1. malicious node can drop or pretend it had committed your tx + 2. malicious proposer (not necessary the one you're communicating with) can + drop transactions, which might become valid in the future + (https://github.com/tendermint/tendermint/issues/3322) + 3. node can be offline + + Please refer to [formatting/encoding rules](https://docs.cometbft.com/v0.38.x/core/using-cometbft.html#formatting) + for additional details + + parameters: + - in: query + name: tx + required: true + schema: + type: string + example: "123" + description: The transaction + responses: + "200": + description: empty answer + content: + application/json: + schema: + $ref: "#/components/schemas/BroadcastTxResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /broadcast_tx_commit: + get: + summary: Returns with the responses from CheckTx and DeliverTx. + tags: + - Tx + operationId: broadcast_tx_commit + description: | + IMPORTANT: use only for testing and development. In production, use + BroadcastTxSync or BroadcastTxAsync. You can subscribe for the transaction + result using JSONRPC via a websocket. See + https://docs.cometbft.com/v0.38.x/core/subscription.html + + CONTRACT: only returns error if mempool.CheckTx() errs or if we timeout + waiting for tx to commit. + + If CheckTx or DeliverTx fail, no error will be returned, but the returned result + will contain a non-OK ABCI code. + + Please refer to [formatting/encoding rules](https://docs.cometbft.com/v0.38.x/core/using-cometbft.html#formatting) + for additional details + + parameters: + - in: query + name: tx + required: true + schema: + type: string + example: "785" + description: The transaction + responses: + "200": + description: empty answer + content: + application/json: + schema: + $ref: "#/components/schemas/BroadcastTxCommitResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /check_tx: + get: + summary: Checks the transaction without executing it. + tags: + - Tx + operationId: check_tx + description: | + The transaction won't be added to the mempool. + + Please refer to [formatting/encoding rules](https://docs.cometbft.com/v0.38.x/core/using-cometbft.html#formatting) + for additional details + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + parameters: + - in: query + name: tx + required: true + schema: + type: string + example: "785" + description: The transaction + responses: + "200": + description: ABCI application's CheckTx response + content: + application/json: + schema: + $ref: "#/components/schemas/CheckTxResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /health: + get: + summary: Node heartbeat + tags: + - Info + operationId: health + description: | + Get node health. Returns empty result (200 OK) on success, no response - in case of an error. + responses: + "200": + description: Gets Node Health + content: + application/json: + schema: + $ref: "#/components/schemas/EmptyResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /status: + get: + summary: Node Status + operationId: status + tags: + - Info + description: | + Get CometBFT status including node info, pubkey, latest block hash, app hash, block height and time. + responses: + "200": + description: Status of the node + content: + application/json: + schema: + $ref: "#/components/schemas/StatusResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /net_info: + get: + summary: Network information + operationId: net_info + tags: + - Info + description: | + Get network info. + responses: + "200": + description: empty answer + content: + application/json: + schema: + $ref: "#/components/schemas/NetInfoResponse" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /dial_seeds: + get: + summary: Dial Seeds (Unsafe) + operationId: dial_seeds + tags: + - Unsafe + description: | + Dial a peer, this route in under unsafe, and has to manually enabled to use + + **Example:** curl 'localhost:26657/dial_seeds?seeds=\["f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656","0491d373a8e0fcf1023aaf18c51d6a1d0d4f31bd@5.6.7.8:26656"\]' + parameters: + - in: query + name: peers + description: list of seed nodes to dial + schema: + type: array + items: + type: string + example: "f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656" + responses: + "200": + description: Dialing seeds in progress. See /net_info for details + content: + application/json: + schema: + $ref: "#/components/schemas/dialResp" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /dial_peers: + get: + summary: Add Peers/Persistent Peers (unsafe) + operationId: dial_peers + tags: + - Unsafe + description: | + Set a persistent peer, this route in under unsafe, and has to manually enabled to use. + + **Example:** curl 'localhost:26657/dial_peers?peers=\["f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656","0491d373a8e0fcf1023aaf18c51d6a1d0d4f31bd@5.6.7.8:26656"\]&persistent=false' + parameters: + - in: query + name: persistent + description: Have the peers you are dialing be persistent + schema: + type: boolean + example: true + - in: query + name: unconditional + description: Have the peers you are dialing be unconditional + schema: + type: boolean + example: true + - in: query + name: private + description: Have the peers you are dialing be private + schema: + type: boolean + example: true + - in: query + name: peers + description: array of peers to dial + schema: + type: array + items: + type: string + example: "f9baeaa15fedf5e1ef7448dd60f46c01f1a9e9c4@1.2.3.4:26656" + responses: + "200": + description: Dialing seeds in progress. See /net_info for details + content: + application/json: + schema: + $ref: "#/components/schemas/dialResp" + "500": + description: empty error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /blockchain: + get: + summary: "Get block headers (max: 20) for minHeight <= height <= maxHeight." + operationId: blockchain + parameters: + - in: query + name: minHeight + description: Minimum block height to return + schema: + type: integer + example: 1 + - in: query + name: maxHeight + description: Maximum block height to return + schema: + type: integer + example: 2 + tags: + - Info + description: | + Get block headers for minHeight <= height <= maxHeight. + + At most 20 items will be returned. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Block headers, returned in descending order (highest first). + content: + application/json: + schema: + $ref: "#/components/schemas/BlockchainResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /header: + get: + summary: Get header at a specified height + operationId: header + parameters: + - in: query + name: height + schema: + type: integer + default: 0 + example: 1 + description: height to return. If no height is provided, it will fetch the latest header. + tags: + - Info + description: | + Get Header. + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: Header informations. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockHeader" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /header_by_hash: + get: + summary: Get header by hash + operationId: header_by_hash + parameters: + - in: query + name: hash + description: header hash + required: true + schema: + type: string + example: "0xD70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED" + tags: + - Info + description: | + Get Header By Hash. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Header informations. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockHeader" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /block: + get: + summary: Get block at a specified height + operationId: block + parameters: + - in: query + name: height + schema: + type: integer + default: 0 + example: 1 + description: height to return. If no height is provided, it will fetch the latest block. + tags: + - Info + description: | + Get Block. + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: Block informations. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /block_by_hash: + get: + summary: Get block by hash + operationId: block_by_hash + parameters: + - in: query + name: hash + description: block hash + required: true + schema: + type: string + example: "0xD70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED" + tags: + - Info + description: | + Get Block By Hash. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Block informations. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /block_results: + get: + summary: Get block results at a specified height + operationId: block_results + parameters: + - in: query + name: height + description: height to return. If no height is provided, it will fetch information regarding the latest block. + schema: + type: integer + default: 0 + example: 1 + tags: + - Info + description: | + Get block_results. + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: Block results. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockResultsResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /commit: + get: + summary: Get commit results at a specified height + operationId: commit + parameters: + - in: query + name: height + description: height to return. If no height is provided, it will fetch commit informations regarding the latest block. + schema: + type: integer + default: 0 + example: 1 + tags: + - Info + description: | + Get Commit. + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: | + Commit results. + + canonical switches from false to true for block H once block H+1 has been committed. Until then it's subjective and only reflects what this node has seen so far. + content: + application/json: + schema: + $ref: "#/components/schemas/CommitResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /validators: + get: + summary: Get validator set at a specified height + operationId: validators + parameters: + - in: query + name: height + description: height to return. If no height is provided, it will fetch validator set which corresponds to the latest block. + schema: + type: integer + default: 0 + example: 1 + - in: query + name: page + description: "Page number (1-based)" + required: false + schema: + type: integer + default: 1 + example: 1 + - in: query + name: per_page + description: "Number of entries per page (max: 100)" + required: false + schema: + type: integer + example: 30 + default: 30 + tags: + - Info + description: | + Get Validators. Validators are sorted first by voting power + (descending), then by address (ascending). + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: Commit results. + content: + application/json: + schema: + $ref: "#/components/schemas/ValidatorsResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /genesis: + get: + summary: Get Genesis + operationId: genesis + tags: + - Info + description: | + Get genesis. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Genesis results. + content: + application/json: + schema: + $ref: "#/components/schemas/GenesisResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /genesis_chunked: + get: + summary: Get Genesis in multiple chunks + operationId: genesis_chunked + tags: + - Info + description: | + Get genesis document in multiple chunks to make it easier to iterate + through larger genesis structures. Each chunk is produced by converting + the genesis document to JSON and then splitting the resulting payload + into 16MB blocks, and then Base64-encoding each block. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + parameters: + - in: query + name: chunk + description: Sequence number of the chunk to download. + schema: + type: integer + default: 0 + example: 1 + responses: + "200": + description: Genesis chunk response. + content: + application/json: + schema: + $ref: "#/components/schemas/GenesisChunkedResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /dump_consensus_state: + get: + summary: Get consensus state + operationId: dump_consensus_state + tags: + - Info + description: | + Get consensus state. + + Not safe to call from inside the ABCI application during a block execution. + responses: + "200": + description: | + Complete consensus state. + + See https://pkg.go.dev/github.com/cometbft/cometbft/types?tab=doc#Vote.String for Vote string description. + content: + application/json: + schema: + $ref: "#/components/schemas/DumpConsensusResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /consensus_state: + get: + summary: Get consensus state + operationId: consensus_state + tags: + - Info + description: | + Get consensus state. + + Not safe to call from inside the ABCI application during a block execution. + responses: + "200": + description: consensus state results. + content: + application/json: + schema: + $ref: "#/components/schemas/ConsensusStateResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /consensus_params: + get: + summary: Get consensus parameters + operationId: consensus_params + parameters: + - in: query + name: height + description: height to return. If no height is provided, it will fetch commit informations regarding the latest block. + schema: + type: integer + default: 0 + example: 1 + tags: + - Info + description: | + Get consensus parameters. + + If the `height` field is set to a non-default value, upon success, the + `Cache-Control` header will be set with the default maximum age. + responses: + "200": + description: consensus parameters results. + content: + application/json: + schema: + $ref: "#/components/schemas/ConsensusParamsResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /unconfirmed_txs: + get: + summary: Get the list of unconfirmed transactions + operationId: unconfirmed_txs + parameters: + - in: query + name: limit + description: Maximum number of unconfirmed transactions to return (max 100) + required: false + schema: + type: integer + default: 30 + example: 1 + tags: + - Info + description: | + Get list of unconfirmed transactions + responses: + "200": + description: List of unconfirmed transactions + content: + application/json: + schema: + $ref: "#/components/schemas/UnconfirmedTransactionsResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /num_unconfirmed_txs: + get: + summary: Get data about unconfirmed transactions + operationId: num_unconfirmed_txs + tags: + - Info + description: | + Get data about unconfirmed transactions + responses: + "200": + description: status about unconfirmed transactions + content: + application/json: + schema: + $ref: "#/components/schemas/NumUnconfirmedTransactionsResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /tx_search: + get: + summary: Search for transactions + description: | + Search for transactions w/ their results. + + See /subscribe for the query syntax. + operationId: tx_search + parameters: + - in: query + name: query + description: Query + required: true + schema: + type: string + example: '"tx.height=1000"' + - in: query + name: prove + description: Include proofs of the transactions inclusion in the block + required: false + schema: + type: boolean + default: false + example: true + - in: query + name: page + description: "Page number (1-based)" + required: false + schema: + type: integer + default: 1 + example: 1 + - in: query + name: per_page + description: "Number of entries per page (max: 100)" + required: false + schema: + type: integer + default: 30 + example: 30 + - in: query + name: order_by + description: Order in which transactions are sorted ("asc" or "desc"), by height & index. If empty, default sorting will be still applied. + required: false + schema: + type: string + default: "asc" + example: "asc" + tags: + - Info + responses: + "200": + description: List of unconfirmed transactions + content: + application/json: + schema: + $ref: "#/components/schemas/TxSearchResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /block_search: + get: + summary: Search for blocks by FinalizeBlock events + description: | + Search for blocks by FinalizeBlock events. + + See /subscribe for the query syntax. + operationId: block_search + parameters: + - in: query + name: query + description: Query + required: true + schema: + type: string + example: '"block.height > 1000"' + - in: query + name: page + description: "Page number (1-based)" + required: false + schema: + type: integer + default: 1 + example: 1 + - in: query + name: per_page + description: "Number of entries per page (max: 100)" + required: false + schema: + type: integer + default: 30 + example: 30 + - in: query + name: order_by + description: Order in which blocks are sorted ("asc" or "desc"), by height. If empty, default sorting will be still applied. + required: false + schema: + type: string + default: "desc" + example: "asc" + tags: + - Info + responses: + "200": + description: List of paginated blocks matching the search criteria. + content: + application/json: + schema: + $ref: "#/components/schemas/BlockSearchResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + + /tx: + get: + summary: Get transactions by hash + operationId: tx + parameters: + - in: query + name: hash + description: hash of transaction to retrieve + required: true + schema: + type: string + example: "0xD70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED" + - in: query + name: prove + description: Include proofs of the transaction's inclusion in the block + required: false + schema: + type: boolean + example: true + default: false + tags: + - Info + description: | + Get a transaction + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Get a transaction` + content: + application/json: + schema: + $ref: "#/components/schemas/TxResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /abci_info: + get: + summary: Get info about the application. + operationId: abci_info + tags: + - ABCI + description: | + Get info about the application. + + Upon success, the `Cache-Control` header will be set with the default + maximum age. + responses: + "200": + description: Get some info about the application. + content: + application/json: + schema: + $ref: "#/components/schemas/ABCIInfoResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /abci_query: + get: + summary: Query the application for some information. + operationId: abci_query + parameters: + - in: query + name: path + description: Path to the data ("/a/b/c") + required: true + schema: + type: string + example: '"/a/b/c"' + - in: query + name: data + description: Data + required: true + schema: + type: string + example: "IHAVENOIDEA" + - in: query + name: height + description: Height (0 means latest) + required: false + schema: + type: integer + example: 1 + default: 0 + - in: query + name: prove + description: Include proofs of the transactions inclusion in the block + required: false + schema: + type: boolean + example: true + default: false + tags: + - ABCI + description: | + Query the application for some information. + responses: + "200": + description: Response of the submitted query + content: + application/json: + schema: + $ref: "#/components/schemas/ABCIQueryResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + /broadcast_evidence: + get: + summary: Broadcast evidence of the misbehavior. + operationId: broadcast_evidence + parameters: + - in: query + name: evidence + description: JSON evidence + required: true + schema: + type: string + example: "JSON_EVIDENCE_encoded" + tags: + - Info + description: | + Broadcast evidence of the misbehavior. + responses: + "200": + description: Broadcast evidence of the misbehavior. + content: + application/json: + schema: + $ref: "#/components/schemas/BroadcastEvidenceResponse" + "500": + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + +components: + schemas: + JSONRPC: + type: object + properties: + id: + type: integer + example: 0 + jsonrpc: + type: string + example: "2.0" + EmptyResponse: + description: Empty Response + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + result: + type: object + additionalProperties: {} + ErrorResponse: + description: Error Response + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + error: + type: string + example: "Description of failure" + ProtocolVersion: + type: object + properties: + p2p: + type: string + example: "7" + block: + type: string + example: "10" + app: + type: string + example: "0" + PubKey: + type: object + properties: + type: + type: string + example: "tendermint/PubKeyEd25519" + value: + type: string + example: "A6DoBUypNtUAyEHWtQ9bFjfNg8Bo9CrnkUGl6k6OHN4=" + NodeInfo: + type: object + properties: + protocol_version: + $ref: "#/components/schemas/ProtocolVersion" + id: + type: string + example: "5576458aef205977e18fd50b274e9b5d9014525a" + listen_addr: + type: string + example: "tcp:0.0.0.0:26656" + network: + type: string + example: "cosmoshub-2" + version: + type: string + example: "0.32.1" + channels: + type: string + example: "4020212223303800" + moniker: + type: string + example: "moniker-node" + other: + type: object + properties: + tx_index: + type: string + example: "on" + rpc_address: + type: string + example: "tcp:0.0.0.0:26657" + SyncInfo: + type: object + properties: + latest_block_hash: + type: string + example: "790BA84C3545FCCC49A5C629CEE6EA58A6E875C3862175BDC11EE7AF54703501" + latest_app_hash: + type: string + example: "C9AEBB441B787D9F1D846DE51F3826F4FD386108B59B08239653ABF59455C3F8" + latest_block_height: + type: string + example: "1262196" + latest_block_time: + type: string + example: "2019-08-01T11:52:22.818762194Z" + earliest_block_hash: + type: string + example: "790BA84C3545FCCC49A5C629CEE6EA58A6E875C3862175BDC11EE7AF54703501" + earliest_app_hash: + type: string + example: "C9AEBB441B787D9F1D846DE51F3826F4FD386108B59B08239653ABF59455C3F8" + earliest_block_height: + type: string + example: "1262196" + earliest_block_time: + type: string + example: "2019-08-01T11:52:22.818762194Z" + catching_up: + type: boolean + example: false + ValidatorInfo: + type: object + properties: + address: + type: string + example: "5D6A51A8E9899C44079C6AF90618BA0369070E6E" + pub_key: + $ref: "#/components/schemas/PubKey" + voting_power: + type: string + example: "0" + Status: + description: Status Response + type: object + properties: + node_info: + $ref: "#/components/schemas/NodeInfo" + sync_info: + $ref: "#/components/schemas/SyncInfo" + validator_info: + $ref: "#/components/schemas/ValidatorInfo" + StatusResponse: + description: Status Response + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + result: + $ref: "#/components/schemas/Status" + Monitor: + type: object + properties: + Active: + type: boolean + example: true + Start: + type: string + example: "2019-07-31T14:31:28.66Z" + Duration: + type: string + example: "168901060000000" + Idle: + type: string + example: "168901040000000" + Bytes: + type: string + example: "5" + Samples: + type: string + example: "1" + InstRate: + type: string + example: "0" + CurRate: + type: string + example: "0" + AvgRate: + type: string + example: "0" + PeakRate: + type: string + example: "0" + BytesRem: + type: string + example: "0" + TimeRem: + type: string + example: "0" + Progress: + type: integer + example: 0 + Channel: + type: object + properties: + ID: + type: integer + example: 48 + SendQueueCapacity: + type: string + example: "1" + SendQueueSize: + type: string + example: "0" + Priority: + type: string + example: "5" + RecentlySent: + type: string + example: "0" + ConnectionStatus: + type: object + properties: + Duration: + type: string + example: "168901057956119" + SendMonitor: + $ref: "#/components/schemas/Monitor" + RecvMonitor: + $ref: "#/components/schemas/Monitor" + Channels: + type: array + items: + $ref: "#/components/schemas/Channel" + Peer: + type: object + properties: + node_info: + $ref: "#/components/schemas/NodeInfo" + is_outbound: + type: boolean + example: true + connection_status: + $ref: "#/components/schemas/ConnectionStatus" + remote_ip: + type: string + example: "95.179.155.35" + NetInfo: + type: object + properties: + listening: + type: boolean + example: true + listeners: + type: array + items: + type: string + example: "Listener(@)" + n_peers: + type: string + example: "1" + peers: + type: array + items: + $ref: "#/components/schemas/Peer" + NetInfoResponse: + description: NetInfo Response + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + result: + $ref: "#/components/schemas/NetInfo" + + BlockMeta: + type: object + properties: + block_id: + $ref: "#/components/schemas/BlockID" + block_size: + type: integer + example: 1000000 + header: + $ref: "#/components/schemas/BlockHeader" + num_txs: + type: string + example: "54" + + Blockchain: + type: object + required: + - "last_height" + - "block_metas" + properties: + last_height: + type: string + example: "1276718" + block_metas: + type: array + items: + $ref: "#/components/schemas/BlockMeta" + + BlockchainResponse: + description: Blockchain info + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + result: + $ref: "#/components/schemas/Blockchain" + + Commit: + required: + - "type" + - "height" + - "round" + - "block_id" + - "timestamp" + - "validator_address" + - "validator_index" + - "signature" + properties: + type: + type: integer + example: 2 + height: + type: string + example: "1262085" + round: + type: integer + example: 0 + block_id: + $ref: "#/components/schemas/BlockID" + timestamp: + type: string + example: "2019-08-01T11:39:38.867269833Z" + validator_address: + type: string + example: "000001E443FD237E4B616E2FA69DF4EE3D49A94F" + validator_index: + type: integer + example: 0 + signature: + type: string + example: "DBchvucTzAUEJnGYpNvMdqLhBAHG4Px8BsOBB3J3mAFCLGeuG7uJqy+nVngKzZdPhPi8RhmE/xcw/M9DOJjEDg==" + + Block: + type: object + properties: + header: + $ref: "#/components/schemas/BlockHeader" + data: + type: array + items: + type: string + example: "yQHwYl3uCkKoo2GaChRnd+THLQ2RM87nEZrE19910Z28ABIUWW/t8AtIMwcyU0sT32RcMDI9GF0aEAoFdWF0b20SBzEwMDAwMDASEwoNCgV1YXRvbRIEMzEwMRCd8gEaagom61rphyEDoJPxlcjRoNDtZ9xMdvs+lRzFaHe2dl2P5R2yVCWrsHISQKkqX5H1zXAIJuC57yw0Yb03Fwy75VRip0ZBtLiYsUqkOsPUoQZAhDNP+6LY+RUwz/nVzedkF0S29NZ32QXdGv0=" + evidence: + type: array + items: + $ref: "#/components/schemas/Evidence" + last_commit: + type: object + properties: + height: + type: integer + round: + type: integer + block_id: + $ref: "#/components/schemas/BlockID" + signatures: + type: array + items: + $ref: "#/components/schemas/Commit" + + Evidence: + type: object + properties: + type: + type: string + height: + type: integer + time: + type: integer + total_voting_power: + type: integer + validator: + $ref: "#/components/schemas/Validator" + + BlockComplete: + type: object + properties: + block_id: + $ref: "#/components/schemas/BlockID" + block: + $ref: "#/components/schemas/Block" + BlockResponse: + description: Blockc info + allOf: + - $ref: "#/components/schemas/JSONRPC" + - type: object + properties: + result: + $ref: "#/components/schemas/BlockComplete" + + ################## FROM NOW ON NEEDS REFACTOR ################## + BlockResultsResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + type: object + required: + - "height" + properties: + height: + type: string + example: "12" + txs_results: + type: array + nullable: true + items: + type: object + properties: + code: + type: string + example: "0" + data: + type: string + example: "" + log: + type: string + example: "not enough gas" + info: + type: string + example: "" + gas_wanted: + type: string + example: "100" + gas_used: + type: string + example: "100" + events: + type: array + nullable: true + items: + type: object + properties: + type: + type: string + example: "app" + attributes: + type: array + nullable: false + items: + $ref: "#/components/schemas/Event" + codespace: + type: string + example: "ibc" + finalize_block_events: + type: array + nullable: true + items: + type: object + properties: + type: + type: string + example: "app" + attributes: + type: array + nullable: false + items: + $ref: "#/components/schemas/Event" + validator_updates: + type: array + nullable: true + items: + type: object + properties: + pub_key: + type: object + required: + - "type" + - "value" + properties: + type: + type: string + example: "tendermint/PubKeyEd25519" + value: + type: string + example: "9tK9IT+FPdf2qm+5c2qaxi10sWP+3erWTKgftn2PaQM=" + power: + type: string + example: "300" + consensus_param_updates: + $ref: "#/components/schemas/ConsensusParams" + + CommitResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "signed_header" + - "canonical" + properties: + signed_header: + required: + - "header" + - "commit" + properties: + header: + $ref: "#/components/schemas/BlockHeader" + commit: + required: + - "height" + - "round" + - "block_id" + - "signatures" + properties: + height: + type: string + example: "1311801" + round: + type: integer + example: 0 + block_id: + $ref: "#/components/schemas/BlockID" + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: integer + example: 2 + validator_address: + type: string + example: "000001E443FD237E4B616E2FA69DF4EE3D49A94F" + timestamp: + type: string + example: "2019-04-22T17:01:58.376629719Z" + signature: + type: string + example: "14jaTQXYRt8kbLKEhdHq7AXycrFImiLuZx50uOjs2+Zv+2i7RTG/jnObD07Jo2ubZ8xd7bNBJMqkgtkd0oQHAw==" + type: object + type: object + canonical: + type: boolean + example: true + type: object + ValidatorsResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "block_height" + - "validators" + properties: + block_height: + type: string + example: "55" + validators: + type: array + items: + $ref: "#/components/schemas/ValidatorPriority" + count: + type: string + example: "1" + total: + type: string + example: "25" + type: object + GenesisResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + type: object + required: + - "genesis" + properties: + genesis: + type: object + required: + - "genesis_time" + - "chain_id" + - "initial_height" + - "consensus_params" + - "validators" + - "app_hash" + properties: + genesis_time: + type: string + example: "2019-04-22T17:00:00Z" + chain_id: + type: string + example: "cosmoshub-2" + initial_height: + type: string + example: "2" + consensus_params: + $ref: "#/components/schemas/ConsensusParams" + validators: + type: array + items: + type: object + properties: + address: + type: string + example: "B00A6323737F321EB0B8D59C6FD497A14B60938A" + pub_key: + required: + - "type" + - "value" + properties: + type: + type: string + example: "tendermint/PubKeyEd25519" + value: + type: string + example: "cOQZvh/h9ZioSeUMZB/1Vy1Xo5x2sjrVjlE/qHnYifM=" + type: object + power: + type: string + example: "9328525" + name: + type: string + example: "Certus One" + app_hash: + type: string + example: "" + app_state: + properties: {} + type: object + + GenesisChunkedResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "chunk" + - "total" + - "data" + properties: + chunk: + type: integer + example: 0 + total: + type: integer + example: 1 + data: + type: string + example: "Z2VuZXNpcwo=" + + DumpConsensusResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "round_state" + - "peers" + properties: + round_state: + required: + - "height" + - "round" + - "step" + - "start_time" + - "commit_time" + - "validators" + - "proposal" + - "proposal_block" + - "proposal_block_parts" + - "locked_round" + - "locked_block" + - "locked_block_parts" + - "valid_round" + - "valid_block" + - "valid_block_parts" + - "votes" + - "commit_round" + - "last_commit" + - "last_validators" + - "triggered_timeout_precommit" + properties: + height: + type: string + example: "1311801" + round: + type: integer + example: 0 + step: + type: integer + example: 3 + start_time: + type: string + example: "2019-08-05T11:28:49.064658805Z" + commit_time: + type: string + example: "2019-08-05T11:28:44.064658805Z" + validators: + required: + - "validators" + - "proposer" + properties: + validators: + type: array + items: + $ref: "#/components/schemas/ValidatorPriority" + proposer: + $ref: "#/components/schemas/ValidatorPriority" + type: object + locked_round: + type: integer + example: -1 + valid_round: + type: string + example: "-1" + votes: + type: array + items: + type: object + properties: + round: + type: string + example: "0" + prevotes: + type: array + nullable: true + items: + type: string + example: + - "nil-Vote" + - "Vote{19:46A3F8B8393B 1311801/00/1(Prevote) 000000000000 64CE682305CB @ 2019-08-05T11:28:47.374703444Z}" + prevotes_bit_array: + type: string + example: "BA{100:___________________x________________________________________________________________________________} 209706/170220253 = 0.00" + precommits: + type: array + nullable: true + items: + type: string + example: + - "nil-Vote" + precommits_bit_array: + type: string + example: "BA{100:____________________________________________________________________________________________________} 0/170220253 = 0.00" + commit_round: + type: integer + example: -1 + last_commit: + nullable: true + required: + - "votes" + - "votes_bit_array" + - "peer_maj_23s" + properties: + votes: + type: array + items: + type: string + example: + - "Vote{0:000001E443FD 1311800/00/2(Precommit) 3071ADB27D1A 77EE1B6B6847 @ 2019-08-05T11:28:43.810128139Z}" + votes_bit_array: + type: string + example: "BA{100:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 170220253/170220253 = 1.00" + peer_maj_23s: + properties: {} + type: object + type: object + last_validators: + required: + - "validators" + - "proposer" + properties: + validators: + type: array + items: + $ref: "#/components/schemas/ValidatorPriority" + proposer: + $ref: "#/components/schemas/ValidatorPriority" + type: object + triggered_timeout_precommit: + type: boolean + example: false + type: object + peers: + type: array + items: + type: object + properties: + node_address: + type: string + example: "357f6a6c1d27414579a8185060aa8adf9815c43c@68.183.41.207:26656" + peer_state: + required: + - "round_state" + - "stats" + properties: + round_state: + required: + - "height" + - "round" + - "step" + - "start_time" + - "proposal" + - "proposal_block_parts_header" + - "proposal_block_parts" + - "proposal_pol_round" + - "proposal_pol" + - "prevotes" + - "precommits" + - "last_commit_round" + - "last_commit" + - "catchup_commit_round" + - "catchup_commit" + properties: + height: + type: string + example: "1311801" + round: + type: string + example: "0" + step: + type: integer + example: 3 + start_time: + type: string + example: "2019-08-05T11:28:49.21730864Z" + proposal: + type: boolean + example: false + proposal_block_parts_header: + required: + - "total" + - "hash" + properties: + total: + type: integer + example: 0 + hash: + type: string + example: "" + type: object + proposal_pol_round: + nullable: true + type: integer + example: -1 + proposal_pol: + nullable: true + type: string + example: "____________________________________________________________________________________________________" + prevotes: + nullable: true + type: string + example: "___________________x________________________________________________________________________________" + precommits: + nullable: true + type: string + example: "____________________________________________________________________________________________________" + last_commit_round: + nullable: true + type: integer + example: 0 + last_commit: + nullable: true + type: string + example: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + catchup_commit_round: + type: integer + nullable: true + example: -1 + catchup_commit: + nullable: true + type: string + example: "____________________________________________________________________________________________________" + type: object + stats: + required: + - "votes" + - "block_parts" + properties: + votes: + type: string + example: "1159558" + block_parts: + type: string + example: "4786" + type: object + type: object + type: object + + ConsensusStateResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "round_state" + properties: + round_state: + required: + - "height/round/step" + - "start_time" + - "proposal_block_hash" + - "locked_block_hash" + - "valid_block_hash" + - "height_vote_set" + - "proposer" + properties: + height/round/step: + type: string + example: "1262197/0/8" + start_time: + type: string + example: "2019-08-01T11:52:38.962730289Z" + proposal_block_hash: + type: string + example: "634ADAF1F402663BEC2ABC340ECE8B4B45AA906FA603272ACC5F5EED3097E009" + locked_block_hash: + type: string + example: "634ADAF1F402663BEC2ABC340ECE8B4B45AA906FA603272ACC5F5EED3097E009" + valid_block_hash: + type: string + example: "634ADAF1F402663BEC2ABC340ECE8B4B45AA906FA603272ACC5F5EED3097E009" + height_vote_set: + type: array + items: + type: object + properties: + round: + type: integer + example: 0 + prevotes: + type: array + items: + type: string + example: + - "Vote{0:000001E443FD 1262197/00/1(Prevote) 634ADAF1F402 7BB974E1BA40 @ 2019-08-01T11:52:35.513572509Z}" + - "nil-Vote" + prevotes_bit_array: + type: string + example: "BA{100:xxxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 169753436/170151262 = 1.00" + precommits: + type: array + items: + type: string + example: + - "Vote{5:18C78D135C9D 1262197/00/2(Precommit) 634ADAF1F402 8B5EFFFEABCD @ 2019-08-01T11:52:36.25600005Z}" + - "nil-Vote" + precommits_bit_array: + type: string + example: "BA{100:xxxxxx_xxxxx_xxxx_x_xxx_xx_xx_xx__x_x_x__xxxxxxxxxxxxxx_xxxx_xx_xxxxxx_xxxxxxxx_xxxx_xxx_x_xxxx__xxx} 118726247/170151262 = 0.70" + proposer: + type: object + properties: + address: + type: string + example: "D540AB022088612AC74B287D076DBFBC4A377A2E" + index: + type: integer + example: 0 + type: object + type: object + + ConsensusParamsResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + type: object + required: + - "block_height" + - "consensus_params" + properties: + block_height: + type: string + example: "1" + consensus_params: + $ref: "#/components/schemas/ConsensusParams" + + NumUnconfirmedTransactionsResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "n_txs" + - "total" + - "total_bytes" + properties: + n_txs: + type: string + example: "31" + total: + type: string + example: "82" + total_bytes: + type: string + example: "19974" + # txs: + # type: array + # nullable: true + # items: + # type: string + # nullable: true + # example: + # - "gAPwYl3uCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUA75/FmYq9WymsOBJ0XSJ8yV8zmQKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhQbrvwbvlNiT+Yjr86G+YQNx7kRVgowjE1xDQoUjJyJG+WaWBwSiGannBRFdrbma+8SFK2m+1oxgILuQLO55n8mWfnbIzyPCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUQNGfkmhTNMis4j+dyMDIWXdIPiYKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhS8sL0D0wwgGCItQwVowak5YB38KRIUCg4KBXVhdG9tEgUxMDA1NBDoxRgaagom61rphyECn8x7emhhKdRCB2io7aS/6Cpuq5NbVqbODmqOT3jWw6kSQKUresk+d+Gw0BhjiggTsu8+1voW+VlDCQ1GRYnMaFOHXhyFv7BCLhFWxLxHSAYT8a5XqoMayosZf9mANKdXArA=" + type: object + + UnconfirmedTransactionsResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "n_txs" + - "total" + - "total_bytes" + - "txs" + properties: + n_txs: + type: string + example: "82" + total: + type: string + example: "82" + total_bytes: + type: string + example: "19974" + txs: + type: array + nullable: true + items: + type: string + nullable: true + example: + - "gAPwYl3uCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUA75/FmYq9WymsOBJ0XSJ8yV8zmQKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhQbrvwbvlNiT+Yjr86G+YQNx7kRVgowjE1xDQoUjJyJG+WaWBwSiGannBRFdrbma+8SFK2m+1oxgILuQLO55n8mWfnbIzyPCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUQNGfkmhTNMis4j+dyMDIWXdIPiYKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhS8sL0D0wwgGCItQwVowak5YB38KRIUCg4KBXVhdG9tEgUxMDA1NBDoxRgaagom61rphyECn8x7emhhKdRCB2io7aS/6Cpuq5NbVqbODmqOT3jWw6kSQKUresk+d+Gw0BhjiggTsu8+1voW+VlDCQ1GRYnMaFOHXhyFv7BCLhFWxLxHSAYT8a5XqoMayosZf9mANKdXArA=" + type: object + + TxSearchResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "txs" + - "total_count" + properties: + txs: + type: array + items: + type: object + properties: + hash: + type: string + example: "D70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED" + height: + type: string + example: "1000" + index: + type: integer + example: 0 + tx_result: + required: + - "log" + - "gas_wanted" + - "gas_used" + - "tags" + properties: + log: + type: string + example: '[{"msg_index":"0","success":true,"log":""}]' + gas_wanted: + type: string + example: "200000" + gas_used: + type: string + example: "28596" + tags: + $ref: "#/components/schemas/Event" + type: object + tx: + type: string + example: "5wHwYl3uCkaoo2GaChQmSIu8hxpJxLcCuIi8fiHN4TMwrRIU/Af1cEG7Rcs/6LjTl7YjRSymJfYaFAoFdWF0b20SCzE0OTk5OTk1MDAwEhMKDQoFdWF0b20SBDUwMDAQwJoMGmoKJuta6YchAwswBShaB1wkZBctLIhYqBC3JrAI28XGzxP+rVEticGEEkAc+khTkKL9CDE47aDvjEHvUNt+izJfT4KVF2v2JkC+bmlH9K08q3PqHeMI9Z5up+XMusnTqlP985KF+SI5J3ZOIhhNYWRlIGJ5IENpcmNsZSB3aXRoIGxvdmU=" + proof: + required: + - "RootHash" + - "Data" + - "Proof" + properties: + RootHash: + type: string + example: "72FE6BF6D4109105357AECE0A82E99D0F6288854D16D8767C5E72C57F876A14D" + Data: + type: string + example: "5wHwYl3uCkaoo2GaChQmSIu8hxpJxLcCuIi8fiHN4TMwrRIU/Af1cEG7Rcs/6LjTl7YjRSymJfYaFAoFdWF0b20SCzE0OTk5OTk1MDAwEhMKDQoFdWF0b20SBDUwMDAQwJoMGmoKJuta6YchAwswBShaB1wkZBctLIhYqBC3JrAI28XGzxP+rVEticGEEkAc+khTkKL9CDE47aDvjEHvUNt+izJfT4KVF2v2JkC+bmlH9K08q3PqHeMI9Z5up+XMusnTqlP985KF+SI5J3ZOIhhNYWRlIGJ5IENpcmNsZSB3aXRoIGxvdmU=" + Proof: + required: + - "total" + - "index" + - "leaf_hash" + - "aunts" + properties: + total: + type: string + example: "2" + index: + type: string + example: "0" + leaf_hash: + type: string + example: "eoJxKCzF3m72Xiwb/Q43vJ37/2Sx8sfNS9JKJohlsYI=" + aunts: + type: array + items: + type: string + example: + - "eWb+HG/eMmukrQj4vNGyFYb3nKQncAWacq4HF5eFzDY=" + type: object + type: object + total_count: + type: string + example: "2" + type: object + + TxResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "hash" + - "height" + - "index" + - "tx_result" + - "tx" + properties: + hash: + type: string + example: "D70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED" + height: + type: string + example: "1000" + index: + type: integer + example: 0 + tx_result: + required: + - "log" + - "gas_wanted" + - "gas_used" + - "tags" + properties: + log: + type: string + example: '[{"msg_index":"0","success":true,"log":""}]' + gas_wanted: + type: string + example: "200000" + gas_used: + type: string + example: "28596" + tags: + type: array + items: + $ref: "#/components/schemas/Event" + type: object + tx: + type: string + example: "5wHwYl3uCkaoo2GaChQmSIu8hxpJxLcCuIi8fiHN4TMwrRIU/Af1cEG7Rcs/6LjTl7YjRSymJfYaFAoFdWF0b20SCzE0OTk5OTk1MDAwEhMKDQoFdWF0b20SBDUwMDAQwJoMGmoKJuta6YchAwswBShaB1wkZBctLIhYqBC3JrAI28XGzxP+rVEticGEEkAc+khTkKL9CDE47aDvjEHvUNt+izJfT4KVF2v2JkC+bmlH9K08q3PqHeMI9Z5up+XMusnTqlP985KF+SI5J3ZOIhhNYWRlIGJ5IENpcmNsZSB3aXRoIGxvdmU=" + type: object + + ABCIInfoResponse: + type: object + required: + - "jsonrpc" + - "id" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "response" + properties: + response: + required: + - "data" + - "version" + - "app_version" + - "last_block_height" + - "last_block_app_hash" + properties: + data: + type: string + example: '{"size":0}' + version: + type: string + example: "0.16.1" + app_version: + type: string + example: "1" + last_block_height: + type: string + example: "1314126" + last_block_app_hash: + type: string + example: "C9AEBB441B787D9F1D846DE51F3826F4FD386108B59B08239653ABF59455C3F8" + type: object + type: object + + ABCIQueryResponse: + type: object + required: + - "error" + - "result" + - "id" + - "jsonrpc" + properties: + error: + type: string + example: "" + result: + required: + - "response" + properties: + response: + required: + - "log" + - "height" + - "proof" + - "value" + - "key" + - "index" + - "code" + properties: + log: + type: string + example: "exists" + height: + type: string + example: "0" + proof: + type: string + example: "010114FED0DAD959F36091AD761C922ABA3CBF1D8349990101020103011406AA2262E2F448242DF2C2607C3CDC705313EE3B0001149D16177BC71E445476174622EA559715C293740C" + value: + type: string + example: "61626364" + key: + type: string + example: "61626364" + index: + type: string + example: "-1" + code: + type: string + example: "0" + type: object + type: object + id: + type: integer + example: 0 + jsonrpc: + type: string + example: "2.0" + + BroadcastEvidenceResponse: + type: object + required: + - "id" + - "jsonrpc" + properties: + error: + type: string + example: "" + result: + type: string + example: "" + id: + type: integer + example: 0 + jsonrpc: + type: string + example: "2.0" + + BroadcastTxCommitResponse: + type: object + required: + - "error" + - "result" + - "id" + - "jsonrpc" + properties: + error: + type: string + example: "" + result: + required: + - "height" + - "hash" + - "deliver_tx" + - "check_tx" + properties: + height: + type: string + example: "26682" + hash: + type: string + example: "75CA0F856A4DA078FC4911580360E70CEFB2EBEE" + deliver_tx: + required: + - "log" + - "data" + - "code" + properties: + log: + type: string + example: "" + data: + type: string + example: "" + code: + type: string + example: "0" + type: object + check_tx: + required: + - "log" + - "data" + - "code" + properties: + log: + type: string + example: "" + data: + type: string + example: "" + code: + type: string + example: "0" + type: object + type: object + id: + type: integer + example: 0 + jsonrpc: + type: string + example: "2.0" + + CheckTxResponse: + type: object + required: + - "error" + - "result" + - "id" + - "jsonrpc" + properties: + error: + type: string + example: "" + result: + required: + - "log" + - "data" + - "code" + properties: + code: + type: string + example: "0" + data: + type: string + example: "" + log: + type: string + example: "" + info: + type: string + example: "" + gas_wanted: + type: string + example: "1" + gas_used: + type: string + example: "0" + events: + type: array + nullable: true + items: + type: object + properties: + type: + type: string + example: "app" + attributes: + type: array + nullable: false + items: + $ref: "#/components/schemas/Event" + codespace: + type: string + example: "bank" + type: object + id: + type: integer + example: 0 + jsonrpc: + type: string + example: "2.0" + + BroadcastTxResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + - "error" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "code" + - "data" + - "log" + - "hash" + properties: + code: + type: string + example: "0" + data: + type: string + example: "" + log: + type: string + example: "" + codespace: + type: string + example: "ibc" + hash: + type: string + example: "0D33F2F03A5234F38706E43004489E061AC40A2E" + type: object + error: + type: string + example: "" + + dialResp: + type: object + properties: + Log: + type: string + example: "Dialing seeds in progress. See /net_info for details" + + BlockSearchResponse: + type: object + required: + - "jsonrpc" + - "id" + - "result" + properties: + jsonrpc: + type: string + example: "2.0" + id: + type: integer + example: 0 + result: + required: + - "blocks" + - "total_count" + properties: + blocks: + type: array + items: + $ref: "#/components/schemas/BlockComplete" + total_count: + type: integer + example: 2 + type: object + + ###### Reuseable types ###### + + # Validator type with proposer prioirty + ValidatorPriority: + type: object + properties: + address: + type: string + example: "000001E443FD237E4B616E2FA69DF4EE3D49A94F" + pub_key: + required: + - "type" + - "value" + properties: + type: + type: string + example: "tendermint/PubKeyEd25519" + value: + type: string + example: "9tK9IT+FPdf2qm+5c2qaxi10sWP+3erWTKgftn2PaQM=" + type: object + voting_power: + type: string + example: "239727" + proposer_priority: + type: string + example: "-11896414" + + # Stripped down validator + Validator: + type: object + properties: + pub_key: + $ref: "#/components/schemas/PubKey" + voting_power: + type: integer + address: + type: string + + # Consensus Params + ConsensusParams: + type: object + nullable: true + required: + - "block" + - "evidence" + - "validator" + properties: + block: + type: object + required: + - "max_bytes" + - "max_gas" + - "time_iota_ms" + properties: + max_bytes: + type: string + example: "22020096" + max_gas: + type: string + example: "1000" + time_iota_ms: + type: string + example: "1000" + evidence: + type: object + required: + - "max_age" + properties: + max_age: + type: string + example: "100000" + validator: + type: object + required: + - "pub_key_types" + properties: + pub_key_types: + type: array + items: + type: string + example: + - "ed25519" + + # Events in CometBFT + Event: + type: object + properties: + key: + type: string + example: "action" + value: + type: string + example: "send" + index: + type: boolean + example: false + + # Block Header + BlockHeader: + required: + - "version" + - "chain_id" + - "height" + - "time" + - "last_block_id" + - "last_commit_hash" + - "data_hash" + - "validators_hash" + - "next_validators_hash" + - "consensus_hash" + - "app_hash" + - "last_results_hash" + - "evidence_hash" + - "proposer_address" + properties: + version: + required: + - "block" + - "app" + properties: + block: + type: string + example: "10" + app: + type: string + example: "0" + type: object + chain_id: + type: string + example: "cosmoshub-2" + height: + type: string + example: "12" + time: + type: string + example: "2019-04-22T17:01:51.701356223Z" + last_block_id: + $ref: "#/components/schemas/BlockID" + last_commit_hash: + type: string + example: "21B9BC845AD2CB2C4193CDD17BFC506F1EBE5A7402E84AD96E64171287A34812" + data_hash: + type: string + example: "970886F99E77ED0D60DA8FCE0447C2676E59F2F77302B0C4AA10E1D02F18EF73" + validators_hash: + type: string + example: "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0" + next_validators_hash: + type: string + example: "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0" + consensus_hash: + type: string + example: "0F2908883A105C793B74495EB7D6DF2EEA479ED7FC9349206A65CB0F9987A0B8" + app_hash: + type: string + example: "223BF64D4A01074DC523A80E76B9BBC786C791FB0A1893AC5B14866356FCFD6C" + last_results_hash: + type: string + example: "" + evidence_hash: + type: string + example: "" + proposer_address: + type: string + example: "D540AB022088612AC74B287D076DBFBC4A377A2E" + type: object + + BlockID: + required: + - "hash" + - "parts" + properties: + hash: + type: string + example: "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7" + parts: + required: + - "total" + - "hash" + properties: + total: + type: integer + example: 1 + hash: + type: string + example: "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + type: object diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go new file mode 100644 index 0000000..ee25513 --- /dev/null +++ b/rpc/test/helpers.go @@ -0,0 +1,204 @@ +package rpctest + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + + cfg "github.com/cometbft/cometbft/config" + cmtnet "github.com/cometbft/cometbft/libs/net" + nm "github.com/cometbft/cometbft/node" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + ctypes "github.com/cometbft/cometbft/rpc/core/types" + core_grpc "github.com/cometbft/cometbft/rpc/grpc" + rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" +) + +// Options helps with specifying some parameters for our RPC testing for greater +// control. +type Options struct { + suppressStdout bool + recreateConfig bool + maxReqBatchSize int +} + +var ( + globalConfig *cfg.Config + defaultOptions = Options{ + suppressStdout: false, + recreateConfig: false, + } +) + +func waitForRPC() { + laddr := GetConfig().RPC.ListenAddress + client, err := rpcclient.New(laddr) + if err != nil { + panic(err) + } + result := new(ctypes.ResultStatus) + for { + _, err := client.Call(context.Background(), "status", map[string]interface{}{}, result) + if err == nil { + return + } + + fmt.Println("error", err) + time.Sleep(time.Millisecond) + } +} + +func waitForGRPC() { + client := GetGRPCClient() + for { + _, err := client.Ping(context.Background(), &core_grpc.RequestPing{}) + if err == nil { + return + } + } +} + +// f**ing long, but unique for each test +func makePathname() string { + // get path + p, err := os.Getwd() + if err != nil { + panic(err) + } + // fmt.Println(p) + sep := string(filepath.Separator) + return strings.ReplaceAll(p, sep, "_") +} + +func randPort() int { + port, err := cmtnet.GetFreePort() + if err != nil { + panic(err) + } + return port +} + +func makeAddrs() (string, string, string) { + return fmt.Sprintf("tcp://127.0.0.1:%d", randPort()), + fmt.Sprintf("tcp://127.0.0.1:%d", randPort()), + fmt.Sprintf("tcp://127.0.0.1:%d", randPort()) +} + +func createConfig() *cfg.Config { + pathname := makePathname() + c := test.ResetTestRoot(pathname) + + // and we use random ports to run in parallel + tm, rpc, grpc := makeAddrs() + c.P2P.ListenAddress = tm + c.RPC.ListenAddress = rpc + c.RPC.CORSAllowedOrigins = []string{"https://cometbft.com/"} + c.RPC.GRPCListenAddress = grpc + return c +} + +// GetConfig returns a config for the test cases as a singleton +func GetConfig(forceCreate ...bool) *cfg.Config { + if globalConfig == nil || (len(forceCreate) > 0 && forceCreate[0]) { + globalConfig = createConfig() + } + return globalConfig +} + +func GetGRPCClient() core_grpc.BroadcastAPIClient { + grpcAddr := globalConfig.RPC.GRPCListenAddress + //nolint:staticcheck // SA1019: core_grpc.StartGRPCClient is deprecated: A new gRPC API will be introduced after v0.38. + return core_grpc.StartGRPCClient(grpcAddr) +} + +// StartTendermint starts a test CometBFT server in a go routine and returns when it is initialized +func StartTendermint(app abci.Application, opts ...func(*Options)) *nm.Node { + nodeOpts := defaultOptions + for _, opt := range opts { + opt(&nodeOpts) + } + node := NewTendermint(app, &nodeOpts) + err := node.Start() + if err != nil { + panic(err) + } + + // wait for rpc + waitForRPC() + waitForGRPC() + + if !nodeOpts.suppressStdout { + fmt.Println("CometBFT running!") + } + + return node +} + +// StopTendermint stops a test CometBFT server, waits until it's stopped and +// cleans up test/config files. +func StopTendermint(node *nm.Node) { + if err := node.Stop(); err != nil { + node.Logger.Error("Error when trying to stop node", "err", err) + } + node.Wait() + os.RemoveAll(node.Config().RootDir) +} + +// NewTendermint creates a new CometBFT server and sleeps forever +func NewTendermint(app abci.Application, opts *Options) *nm.Node { + // Create & start node + config := GetConfig(opts.recreateConfig) + var logger log.Logger + if opts.suppressStdout { + logger = log.NewNopLogger() + } else { + logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger = log.NewFilter(logger, log.AllowError()) + } + if opts.maxReqBatchSize > 0 { + config.RPC.MaxRequestBatchSize = opts.maxReqBatchSize + } + pvKeyFile := config.PrivValidatorKeyFile() + pvKeyStateFile := config.PrivValidatorStateFile() + pv := privval.LoadOrGenFilePV(pvKeyFile, pvKeyStateFile) + papp := proxy.NewLocalClientCreator(app) + nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) + if err != nil { + panic(err) + } + node, err := nm.NewNode(config, pv, nodeKey, papp, + nm.DefaultGenesisDocProviderFunc(config), + cfg.DefaultDBProvider, + nm.DefaultMetricsProvider(config.Instrumentation), + logger) + if err != nil { + panic(err) + } + return node +} + +// SuppressStdout is an option that tries to make sure the RPC test CometBFT +// node doesn't log anything to stdout. +func SuppressStdout(o *Options) { + o.suppressStdout = true +} + +// RecreateConfig instructs the RPC test to recreate the configuration each +// time, instead of treating it as a global singleton. +func RecreateConfig(o *Options) { + o.recreateConfig = true +} + +// MaxReqBatchSize is an option to limit the maximum number of requests per batch. +func MaxReqBatchSize(o *Options) { + o.maxReqBatchSize = 2 +} diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000..4a2bd9a --- /dev/null +++ b/scripts/README.md @@ -0,0 +1 @@ +* http://redsymbol.net/articles/unofficial-bash-strict-mode/ diff --git a/scripts/authors.sh b/scripts/authors.sh new file mode 100755 index 0000000..44251c2 --- /dev/null +++ b/scripts/authors.sh @@ -0,0 +1,16 @@ +#! /bin/bash + +# Usage: +# `./authors.sh` +# Print a list of all authors who have committed to develop since master. +# +# `./authors.sh ` +# Lookup the email address on Github and print the associated username + +author=$1 + +if [[ "$author" == "" ]]; then + git log master..develop | grep Author | sort | uniq +else + curl -s "https://api.github.com/search/users?q=$author+in%3Aemail&type=Users&utf8=%E2%9C%93" | jq .items[0].login +fi diff --git a/scripts/dist.sh b/scripts/dist.sh new file mode 100755 index 0000000..45972b3 --- /dev/null +++ b/scripts/dist.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +set -e + +# WARN: non hermetic build (people must run this script inside docker to +# produce deterministic binaries). + +# Get the version from the environment, or try to figure it out. +if [ -z $VERSION ]; then + VERSION=$(awk -F\" 'TMCoreSemVer =/ { print $2; exit }' < version/version.go) +fi +if [ -z "$VERSION" ]; then + echo "Please specify a version." + exit 1 +fi +echo "==> Building version $VERSION..." + +# Delete the old dir +echo "==> Removing old directory..." +rm -rf build/pkg +mkdir -p build/pkg + +# Get the git commit +VERSION := "$(shell git describe --always)" +GIT_IMPORT="github.com/cometbft/cometbft/version" + +# Determine the arch/os combos we're building for +XC_ARCH=${XC_ARCH:-"386 amd64 arm"} +XC_OS=${XC_OS:-"solaris darwin freebsd linux windows"} +XC_EXCLUDE=${XC_EXCLUDE:-" darwin/arm solaris/amd64 solaris/386 solaris/arm freebsd/amd64 windows/arm "} + +# Make sure build tools are available. +make tools + +# Build! +# ldflags: -s Omit the symbol table and debug information. +# -w Omit the DWARF symbol table. +echo "==> Building..." +IFS=' ' read -ra arch_list <<< "$XC_ARCH" +IFS=' ' read -ra os_list <<< "$XC_OS" +for arch in "${arch_list[@]}"; do + for os in "${os_list[@]}"; do + if [[ "$XC_EXCLUDE" != *" $os/$arch "* ]]; then + echo "--> $os/$arch" + GOOS=${os} GOARCH=${arch} go build -ldflags "-s -w -X ${GIT_IMPORT}.TMCoreSemVer=${VERSION}" -tags="${BUILD_TAGS}" -o "build/pkg/${os}_${arch}/cometbft" ./cmd/cometbft + fi + done +done + +# Zip all the files. +echo "==> Packaging..." +for PLATFORM in $(find ./build/pkg -mindepth 1 -maxdepth 1 -type d); do + OSARCH=$(basename "${PLATFORM}") + echo "--> ${OSARCH}" + + pushd "$PLATFORM" >/dev/null 2>&1 + zip "../${OSARCH}.zip" ./* + popd >/dev/null 2>&1 +done + +# Add "cometbft" and $VERSION prefix to package name. +rm -rf ./build/dist +mkdir -p ./build/dist +for FILENAME in $(find ./build/pkg -mindepth 1 -maxdepth 1 -type f); do + FILENAME=$(basename "$FILENAME") + cp "./build/pkg/${FILENAME}" "./build/dist/cometbft_${VERSION}_${FILENAME}" +done + +# Make the checksums. +pushd ./build/dist +shasum -a256 ./* > "./cometbft_${VERSION}_SHA256SUMS" +popd + +# Done +echo +echo "==> Results:" +ls -hl ./build/dist + +exit 0 diff --git a/scripts/get_nodejs.sh b/scripts/get_nodejs.sh new file mode 100755 index 0000000..cd736e6 --- /dev/null +++ b/scripts/get_nodejs.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +VERSION=v12.9.0 +NODE_FULL=node-${VERSION}-linux-x64 + +mkdir -p ~/.local/bin +mkdir -p ~/.local/node +wget http://nodejs.org/dist/${VERSION}/${NODE_FULL}.tar.gz -O ~/.local/node/${NODE_FULL}.tar.gz +tar -xzf ~/.local/node/${NODE_FULL}.tar.gz -C ~/.local/node/ +ln -s ~/.local/node/${NODE_FULL}/bin/node ~/.local/bin/node +ln -s ~/.local/node/${NODE_FULL}/bin/npm ~/.local/bin/npm +export PATH=~/.local/bin:$PATH +npm i -g dredd +ln -s ~/.local/node/${NODE_FULL}/bin/dredd ~/.local/bin/dredd diff --git a/scripts/json2wal/main.go b/scripts/json2wal/main.go new file mode 100644 index 0000000..014a95e --- /dev/null +++ b/scripts/json2wal/main.go @@ -0,0 +1,69 @@ +/* + json2wal converts JSON file to binary WAL file. + + Usage: + json2wal +*/ + +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" + + cs "github.com/cometbft/cometbft/consensus" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/types" +) + +func main() { + if len(os.Args) < 3 { + fmt.Fprintln(os.Stderr, "missing arguments: Usage:json2wal ") + os.Exit(1) + } + + f, err := os.Open(os.Args[1]) + if err != nil { + panic(fmt.Errorf("failed to open WAL file: %v", err)) + } + defer f.Close() + + walFile, err := os.OpenFile(os.Args[2], os.O_EXCL|os.O_WRONLY|os.O_CREATE, 0666) + if err != nil { + panic(fmt.Errorf("failed to open WAL file: %v", err)) + } + defer walFile.Close() + + // the length of wal/MsgInfo in the wal.json may exceed the defaultBufSize(4096) of bufio + // because of the byte array in BlockPart + // leading to unmarshal error: unexpected end of JSON input + br := bufio.NewReaderSize(f, int(2*types.BlockPartSizeBytes)) + dec := cs.NewWALEncoder(walFile) + + for { + msgJSON, _, err := br.ReadLine() + if err == io.EOF { + break + } else if err != nil { + panic(fmt.Errorf("failed to read file: %v", err)) + } + // ignore the ENDHEIGHT in json.File + if strings.HasPrefix(string(msgJSON), "ENDHEIGHT") { + continue + } + + var msg cs.TimedWALMessage + err = cmtjson.Unmarshal(msgJSON, &msg) + if err != nil { + panic(fmt.Errorf("failed to unmarshal json: %v", err)) + } + + err = dec.Encode(&msg) + if err != nil { + panic(fmt.Errorf("failed to encode msg: %v", err)) + } + } +} diff --git a/scripts/linkify_changelog.py b/scripts/linkify_changelog.py new file mode 100644 index 0000000..429ec16 --- /dev/null +++ b/scripts/linkify_changelog.py @@ -0,0 +1,13 @@ +import fileinput +import re + +# This script goes through the provided file, and replaces any " \#", +# with the valid mark down formatted link to it. e.g. +# " [\#number](https://github.com/cometbft/cometbft/issues/) +# Note that if the number is for a PR, github will auto-redirect you when you click the link. +# It is safe to run the script multiple times in succession. +# +# Example usage $ python3 linkify_changelog.py ../CHANGELOG_PENDING.md +for line in fileinput.input(inplace=1): + line = re.sub(r"\s\\#([0-9]*)", r" [\\#\1](https://github.com/cometbft/cometbft/issues/\1)", line.rstrip()) + print(line) diff --git a/scripts/metricsgen/metricsdiff/metricsdiff.go b/scripts/metricsgen/metricsdiff/metricsdiff.go new file mode 100644 index 0000000..f8191fb --- /dev/null +++ b/scripts/metricsgen/metricsdiff/metricsdiff.go @@ -0,0 +1,197 @@ +// metricsdiff is a tool for generating a diff between two different files containing +// prometheus metrics. metricsdiff outputs which metrics have been added, removed, +// or have different sets of labels between the two files. +package main + +import ( + "flag" + "fmt" + "io" + "log" + "os" + "path/filepath" + "sort" + "strings" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/common/expfmt" +) + +func init() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, `Usage: %[1]s + +Generate the diff between the two files of Prometheus metrics. +The input should have the format output by a Prometheus HTTP endpoint. +The tool indicates which metrics have been added, removed, or use different +label sets from path1 to path2. + +`, filepath.Base(os.Args[0])) + flag.PrintDefaults() + } +} + +// Diff contains the set of metrics that were modified between two files +// containing prometheus metrics output. +type Diff struct { + Adds []string + Removes []string + + Changes []LabelDiff +} + +// LabelDiff describes the label changes between two versions of the same metric. +type LabelDiff struct { + Metric string + Adds []string + Removes []string +} + +type parsedMetric struct { + name string + labels []string +} + +type metricsList []parsedMetric + +func main() { + flag.Parse() + if flag.NArg() != 2 { + log.Fatalf("Usage is '%s ', got %d arguments", + filepath.Base(os.Args[0]), flag.NArg()) + } + fa, err := os.Open(flag.Arg(0)) + if err != nil { + log.Fatalf("Open: %v", err) + } + defer fa.Close() + fb, err := os.Open(flag.Arg(1)) + if err != nil { + log.Fatalf("Open: %v", err) + } + defer fb.Close() + md, err := DiffFromReaders(fa, fb) + if err != nil { + log.Fatalf("Generating diff: %v", err) + } + fmt.Print(md) +} + +// DiffFromReaders parses the metrics present in the readers a and b and +// determines which metrics were added and removed in b. +func DiffFromReaders(a, b io.Reader) (Diff, error) { + var parser expfmt.TextParser + amf, err := parser.TextToMetricFamilies(a) + if err != nil { + return Diff{}, err + } + bmf, err := parser.TextToMetricFamilies(b) + if err != nil { + return Diff{}, err + } + + md := Diff{} + aList := toList(amf) + bList := toList(bmf) + + i, j := 0, 0 + for i < len(aList) || j < len(bList) { + for j < len(bList) && (i >= len(aList) || bList[j].name < aList[i].name) { + md.Adds = append(md.Adds, bList[j].name) + j++ + } + for i < len(aList) && j < len(bList) && aList[i].name == bList[j].name { + adds, removes := listDiff(aList[i].labels, bList[j].labels) + if len(adds) > 0 || len(removes) > 0 { + md.Changes = append(md.Changes, LabelDiff{ + Metric: aList[i].name, + Adds: adds, + Removes: removes, + }) + } + i++ + j++ + } + for i < len(aList) && (j >= len(bList) || aList[i].name < bList[j].name) { + md.Removes = append(md.Removes, aList[i].name) + i++ + } + } + return md, nil +} + +func toList(l map[string]*dto.MetricFamily) metricsList { + r := make([]parsedMetric, len(l)) + var idx int + for name, family := range l { + r[idx] = parsedMetric{ + name: name, + labels: labelsToStringList(family.Metric[0].Label), + } + idx++ + } + sort.Sort(metricsList(r)) + return r +} + +func labelsToStringList(ls []*dto.LabelPair) []string { + r := make([]string, len(ls)) + for i, l := range ls { + r[i] = l.GetName() + } + return sort.StringSlice(r) +} + +func listDiff(a, b []string) ([]string, []string) { + adds, removes := []string{}, []string{} + i, j := 0, 0 + for i < len(a) || j < len(b) { + for j < len(b) && (i >= len(a) || b[j] < a[i]) { + adds = append(adds, b[j]) + j++ + } + for i < len(a) && j < len(b) && a[i] == b[j] { + i++ + j++ + } + for i < len(a) && (j >= len(b) || a[i] < b[j]) { + removes = append(removes, a[i]) + i++ + } + } + return adds, removes +} + +func (m metricsList) Len() int { return len(m) } +func (m metricsList) Less(i, j int) bool { return m[i].name < m[j].name } +func (m metricsList) Swap(i, j int) { m[i], m[j] = m[j], m[i] } + +func (m Diff) String() string { + var s strings.Builder + if len(m.Adds) > 0 || len(m.Removes) > 0 { + fmt.Fprintln(&s, "Metric changes:") + } + if len(m.Adds) > 0 { + for _, add := range m.Adds { + fmt.Fprintf(&s, "+++ %s\n", add) + } + } + if len(m.Removes) > 0 { + for _, rem := range m.Removes { + fmt.Fprintf(&s, "--- %s\n", rem) + } + } + if len(m.Changes) > 0 { + fmt.Fprintln(&s, "Label changes:") + for _, ld := range m.Changes { + fmt.Fprintf(&s, "Metric: %s\n", ld.Metric) + for _, add := range ld.Adds { + fmt.Fprintf(&s, "+++ %s\n", add) + } + for _, rem := range ld.Removes { + fmt.Fprintf(&s, "--- %s\n", rem) + } + } + } + return s.String() +} diff --git a/scripts/metricsgen/metricsdiff/metricsdiff_test.go b/scripts/metricsgen/metricsdiff/metricsdiff_test.go new file mode 100644 index 0000000..54bc595 --- /dev/null +++ b/scripts/metricsgen/metricsdiff/metricsdiff_test.go @@ -0,0 +1,63 @@ +package main_test + +import ( + "bytes" + "io" + "testing" + + "github.com/stretchr/testify/require" + + metricsdiff "github.com/cometbft/cometbft/scripts/metricsgen/metricsdiff" +) + +func TestDiff(t *testing.T) { + for _, tc := range []struct { + name string + aContents string + bContents string + + want string + }{ + { + name: "labels", + aContents: ` + metric_one{label_one="content", label_two="content"} 0 + `, + bContents: ` + metric_one{label_three="content", label_four="content"} 0 + `, + want: `Label changes: +Metric: metric_one ++++ label_three ++++ label_four +--- label_one +--- label_two +`, + }, + { + name: "metrics", + aContents: ` + metric_one{label_one="content"} 0 + `, + bContents: ` + metric_two{label_two="content"} 0 + `, + want: `Metric changes: ++++ metric_two +--- metric_one +`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + bufA := bytes.NewBuffer([]byte{}) + bufB := bytes.NewBuffer([]byte{}) + _, err := io.WriteString(bufA, tc.aContents) + require.NoError(t, err) + _, err = io.WriteString(bufB, tc.bContents) + require.NoError(t, err) + md, err := metricsdiff.DiffFromReaders(bufA, bufB) + require.NoError(t, err) + require.Equal(t, tc.want, md.String()) + }) + } +} diff --git a/scripts/metricsgen/metricsgen.go b/scripts/metricsgen/metricsgen.go new file mode 100644 index 0000000..087b0bd --- /dev/null +++ b/scripts/metricsgen/metricsgen.go @@ -0,0 +1,346 @@ +// metricsgen is a code generation tool for creating constructors for CometBFT +// metrics types. +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/token" + "go/types" + "io" + "io/fs" + "log" + "os" + "path" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "text/template" +) + +func init() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, `Usage: %[1]s -struct + +Generate constructors for the metrics type specified by -struct contained in +the current directory. The tool creates a new file in the current directory +containing the generated code. + +Options: +`, filepath.Base(os.Args[0])) + flag.PrintDefaults() + } +} + +const metricsPackageName = "github.com/go-kit/kit/metrics" + +const ( + metricNameTag = "metrics_name" + labelsTag = "metrics_labels" + bucketTypeTag = "metrics_buckettype" + bucketSizeTag = "metrics_bucketsizes" +) + +var ( + dir = flag.String("dir", ".", "Path to the directory containing the target package") + strct = flag.String("struct", "Metrics", "Struct to parse for metrics") +) + +var bucketType = map[string]string{ + "exprange": "stdprometheus.ExponentialBucketsRange", + "exp": "stdprometheus.ExponentialBuckets", + "lin": "stdprometheus.LinearBuckets", +} + +var tmpl = template.Must(template.New("tmpl").Parse(`// Code generated by metricsgen. DO NOT EDIT. + +package {{ .Package }} + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + {{ range $metric := .ParsedMetrics }} + {{- $metric.FieldName }}: prometheus.New{{ $metric.TypeName }}From(stdprometheus.{{$metric.TypeName }}Opts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "{{$metric.MetricName }}", + Help: "{{ $metric.Description }}", + {{ if ne $metric.HistogramOptions.BucketType "" }} + Buckets: {{ $metric.HistogramOptions.BucketType }}({{ $metric.HistogramOptions.BucketSizes }}), + {{ else if ne $metric.HistogramOptions.BucketSizes "" }} + Buckets: []float64{ {{ $metric.HistogramOptions.BucketSizes }} }, + {{ end }} + {{- if eq (len $metric.Labels) 0 }} + }, labels).With(labelsAndValues...), + {{ else }} + }, append(labels, {{$metric.Labels}})).With(labelsAndValues...), + {{ end }} + {{- end }} + } +} + + +func NopMetrics() *Metrics { + return &Metrics{ + {{- range $metric := .ParsedMetrics }} + {{ $metric.FieldName }}: discard.New{{ $metric.TypeName }}(), + {{- end }} + } +} +`)) + +// ParsedMetricField is the data parsed for a single field of a metric struct. +type ParsedMetricField struct { + TypeName string + FieldName string + MetricName string + Description string + Labels string + + HistogramOptions HistogramOpts +} + +type HistogramOpts struct { + BucketType string + BucketSizes string +} + +// TemplateData is all of the data required for rendering a metric file template. +type TemplateData struct { + Package string + ParsedMetrics []ParsedMetricField +} + +func main() { + flag.Parse() + if *strct == "" { + log.Fatal("You must specify a non-empty -struct") + } + td, err := ParseMetricsDir(".", *strct) + if err != nil { + log.Fatalf("Parsing file: %v", err) + } + out := filepath.Join(*dir, "metrics.gen.go") + f, err := os.Create(out) + if err != nil { + log.Fatalf("Opening file: %v", err) + } + err = GenerateMetricsFile(f, td) + if err != nil { + log.Fatalf("Generating code: %v", err) + } +} + +func ignoreTestFiles(f fs.FileInfo) bool { + return !strings.Contains(f.Name(), "_test.go") +} + +// ParseMetricsDir parses the dir and scans for a struct matching structName, +// ignoring all test files. ParseMetricsDir iterates the fields of the metrics +// struct and builds a TemplateData using the data obtained from the abstract syntax tree. +func ParseMetricsDir(dir string, structName string) (TemplateData, error) { + fs := token.NewFileSet() + d, err := parser.ParseDir(fs, dir, ignoreTestFiles, parser.ParseComments) + if err != nil { + return TemplateData{}, err + } + if len(d) > 1 { + return TemplateData{}, fmt.Errorf("multiple packages found in %s", dir) + } + if len(d) == 0 { + return TemplateData{}, fmt.Errorf("no go pacakges found in %s", dir) + } + + // Grab the package name. + var pkgName string + var pkg *ast.Package //nolint:staticcheck + for pkgName, pkg = range d { + } + td := TemplateData{ + Package: pkgName, + } + // Grab the metrics struct + m, mPkgName, err := findMetricsStruct(pkg.Files, structName) + if err != nil { + return TemplateData{}, err + } + for _, f := range m.Fields.List { + if !isMetric(f.Type, mPkgName) { + continue + } + pmf := parseMetricField(f) + td.ParsedMetrics = append(td.ParsedMetrics, pmf) + } + + return td, err +} + +// GenerateMetricsFile executes the metrics file template, writing the result +// into the io.Writer. +func GenerateMetricsFile(w io.Writer, td TemplateData) error { + b := []byte{} + buf := bytes.NewBuffer(b) + err := tmpl.Execute(buf, td) + if err != nil { + return err + } + b, err = format.Source(buf.Bytes()) + if err != nil { + return err + } + _, err = io.Copy(w, bytes.NewBuffer(b)) + if err != nil { + return err + } + return nil +} + +func findMetricsStruct(files map[string]*ast.File, structName string) (*ast.StructType, string, error) { + var st *ast.StructType + for _, file := range files { + mPkgName, err := extractMetricsPackageName(file.Imports) + if err != nil { + return nil, "", fmt.Errorf("unable to determine metrics package name: %v", err) + } + if !ast.FilterFile(file, func(name string) bool { + return name == structName + }) { + continue + } + ast.Inspect(file, func(n ast.Node) bool { + switch f := n.(type) { + case *ast.TypeSpec: + if f.Name.Name == structName { + var ok bool + st, ok = f.Type.(*ast.StructType) + if !ok { + err = fmt.Errorf("found identifier for %q of wrong type", structName) + } + } + return false + default: + return true + } + }) + if err != nil { + return nil, "", err + } + if st != nil { + return st, mPkgName, nil + } + } + return nil, "", fmt.Errorf("target struct %q not found in dir", structName) +} + +func parseMetricField(f *ast.Field) ParsedMetricField { + pmf := ParsedMetricField{ + Description: extractHelpMessage(f.Doc), + MetricName: extractFieldName(f.Names[0].String(), f.Tag), + FieldName: f.Names[0].String(), + TypeName: extractTypeName(f.Type), + Labels: extractLabels(f.Tag), + } + if pmf.TypeName == "Histogram" { + pmf.HistogramOptions = extractHistogramOptions(f.Tag) + } + return pmf +} + +func extractTypeName(e ast.Expr) string { + return strings.TrimPrefix(path.Ext(types.ExprString(e)), ".") +} + +func extractHelpMessage(cg *ast.CommentGroup) string { + if cg == nil { + return "" + } + var help []string //nolint: prealloc + for _, c := range cg.List { + mt := strings.TrimPrefix(c.Text, "//metrics:") + if mt != c.Text { + return strings.TrimSpace(mt) + } + help = append(help, strings.TrimSpace(strings.TrimPrefix(c.Text, "//"))) + } + return strings.Join(help, " ") +} + +func isMetric(e ast.Expr, mPkgName string) bool { + return strings.Contains(types.ExprString(e), fmt.Sprintf("%s.", mPkgName)) +} + +func extractLabels(bl *ast.BasicLit) string { + if bl != nil { + t := reflect.StructTag(strings.Trim(bl.Value, "`")) + if v := t.Get(labelsTag); v != "" { + var res []string + for _, s := range strings.Split(v, ",") { + res = append(res, strconv.Quote(strings.TrimSpace(s))) + } + return strings.Join(res, ",") + } + } + return "" +} + +func extractFieldName(name string, tag *ast.BasicLit) string { + if tag != nil { + t := reflect.StructTag(strings.Trim(tag.Value, "`")) + if v := t.Get(metricNameTag); v != "" { + return v + } + } + return toSnakeCase(name) +} + +func extractHistogramOptions(tag *ast.BasicLit) HistogramOpts { + h := HistogramOpts{} + if tag != nil { + t := reflect.StructTag(strings.Trim(tag.Value, "`")) + if v := t.Get(bucketTypeTag); v != "" { + h.BucketType = bucketType[v] + } + if v := t.Get(bucketSizeTag); v != "" { + h.BucketSizes = v + } + } + return h +} + +func extractMetricsPackageName(imports []*ast.ImportSpec) (string, error) { + for _, i := range imports { + u, err := strconv.Unquote(i.Path.Value) + if err != nil { + return "", err + } + if u == metricsPackageName { + if i.Name != nil { + return i.Name.Name, nil + } + return path.Base(u), nil + } + } + return "", nil +} + +var capitalChange = regexp.MustCompile("([a-z0-9])([A-Z])") + +func toSnakeCase(str string) string { + snake := capitalChange.ReplaceAllString(str, "${1}_${2}") + return strings.ToLower(snake) +} diff --git a/scripts/metricsgen/metricsgen_test.go b/scripts/metricsgen/metricsgen_test.go new file mode 100644 index 0000000..41307f2 --- /dev/null +++ b/scripts/metricsgen/metricsgen_test.go @@ -0,0 +1,259 @@ +package main_test + +import ( + "bytes" + "fmt" + "go/parser" + "go/token" + "io" + "os" + "path" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + + metricsgen "github.com/cometbft/cometbft/scripts/metricsgen" +) + +const testDataDir = "./testdata" + +func TestSimpleTemplate(t *testing.T) { + m := metricsgen.ParsedMetricField{ + TypeName: "Histogram", + FieldName: "MyMetric", + MetricName: "request_count", + Description: "how many requests were made since the start of the process", + Labels: "first, second, third", + } + td := metricsgen.TemplateData{ + Package: "mypack", + ParsedMetrics: []metricsgen.ParsedMetricField{m}, + } + b := bytes.NewBuffer([]byte{}) + err := metricsgen.GenerateMetricsFile(b, td) + if err != nil { + t.Fatalf("unable to parse template %v", err) + } +} + +func TestFromData(t *testing.T) { + infos, err := os.ReadDir(testDataDir) + if err != nil { + t.Fatalf("unable to open file %v", err) + } + for _, dir := range infos { + t.Run(dir.Name(), func(t *testing.T) { + if !dir.IsDir() { + t.Fatalf("expected file %s to be directory", dir.Name()) + } + dirName := path.Join(testDataDir, dir.Name()) + pt, err := metricsgen.ParseMetricsDir(dirName, "Metrics") + if err != nil { + t.Fatalf("unable to parse from dir %q: %v", dir, err) + } + outFile := path.Join(dirName, "out.go") + if err != nil { + t.Fatalf("unable to open file %s: %v", outFile, err) + } + of, err := os.Create(outFile) + if err != nil { + t.Fatalf("unable to open file %s: %v", outFile, err) + } + defer os.Remove(outFile) + if err := metricsgen.GenerateMetricsFile(of, pt); err != nil { + t.Fatalf("unable to generate metrics file %s: %v", outFile, err) + } + if _, err := parser.ParseFile(token.NewFileSet(), outFile, nil, parser.AllErrors); err != nil { + t.Fatalf("unable to parse generated file %s: %v", outFile, err) + } + bNew, err := os.ReadFile(outFile) + if err != nil { + t.Fatalf("unable to read generated file %s: %v", outFile, err) + } + goldenFile := path.Join(dirName, "metrics.gen.go") + bOld, err := os.ReadFile(goldenFile) + if err != nil { + t.Fatalf("unable to read file %s: %v", goldenFile, err) + } + if !bytes.Equal(bNew, bOld) { + t.Fatalf("newly generated code in file %s does not match golden file %s\n"+ + "if the output of the metricsgen tool is expected to change run the following make target: \n"+ + "\tmake metrics", outFile, goldenFile) + } + }) + } +} + +func TestParseMetricsStruct(t *testing.T) { + const pkgName = "mypkg" + metricsTests := []struct { + name string + shouldError bool + metricsStruct string + expected metricsgen.TemplateData + }{ + { + name: "basic", + metricsStruct: `type Metrics struct { + myGauge metrics.Gauge + }`, + expected: metricsgen.TemplateData{ + Package: pkgName, + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Gauge", + FieldName: "myGauge", + MetricName: "my_gauge", + }, + }, + }, + }, + { + name: "histogram", + metricsStruct: "type Metrics struct {\n" + + "myHistogram metrics.Histogram `metrics_buckettype:\"exp\" metrics_bucketsizes:\"1, 100, .8\"`\n" + + "}", + expected: metricsgen.TemplateData{ + Package: pkgName, + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Histogram", + FieldName: "myHistogram", + MetricName: "my_histogram", + + HistogramOptions: metricsgen.HistogramOpts{ + BucketType: "stdprometheus.ExponentialBuckets", + BucketSizes: "1, 100, .8", + }, + }, + }, + }, + }, + { + name: "labeled name", + metricsStruct: "type Metrics struct {\n" + + "myCounter metrics.Counter `metrics_name:\"new_name\"`\n" + + "}", + expected: metricsgen.TemplateData{ + Package: pkgName, + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Counter", + FieldName: "myCounter", + MetricName: "new_name", + }, + }, + }, + }, + { + name: "metric labels", + metricsStruct: "type Metrics struct {\n" + + "myCounter metrics.Counter `metrics_labels:\"label1,label2\"`\n" + + "}", + expected: metricsgen.TemplateData{ + Package: pkgName, + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Counter", + FieldName: "myCounter", + MetricName: "my_counter", + Labels: "\"label1\",\"label2\"", + }, + }, + }, + }, + { + name: "ignore non-metric field", + metricsStruct: `type Metrics struct { + myCounter metrics.Counter + nonMetric string + }`, + expected: metricsgen.TemplateData{ + Package: pkgName, + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Counter", + FieldName: "myCounter", + MetricName: "my_counter", + }, + }, + }, + }, + } + for _, testCase := range metricsTests { + t.Run(testCase.name, func(t *testing.T) { + dir, err := os.MkdirTemp(os.TempDir(), "metricsdir") + if err != nil { + t.Fatalf("unable to create directory: %v", err) + } + defer os.Remove(dir) + f, err := os.Create(filepath.Join(dir, "metrics.go")) + if err != nil { + t.Fatalf("unable to open file: %v", err) + } + pkgLine := fmt.Sprintf("package %s\n", pkgName) + importClause := ` + import( + "github.com/go-kit/kit/metrics" + ) + ` + + _, err = io.WriteString(f, pkgLine) + require.NoError(t, err) + _, err = io.WriteString(f, importClause) + require.NoError(t, err) + _, err = io.WriteString(f, testCase.metricsStruct) + require.NoError(t, err) + + td, err := metricsgen.ParseMetricsDir(dir, "Metrics") + if testCase.shouldError { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Equal(t, testCase.expected, td) + } + }) + } +} + +func TestParseAliasedMetric(t *testing.T) { + aliasedData := ` + package mypkg + + import( + mymetrics "github.com/go-kit/kit/metrics" + ) + type Metrics struct { + m mymetrics.Gauge + } + ` + dir, err := os.MkdirTemp(os.TempDir(), "metricsdir") + if err != nil { + t.Fatalf("unable to create directory: %v", err) + } + defer os.Remove(dir) + f, err := os.Create(filepath.Join(dir, "metrics.go")) + if err != nil { + t.Fatalf("unable to open file: %v", err) + } + _, err = io.WriteString(f, aliasedData) + if err != nil { + t.Fatalf("unable to write to file: %v", err) + } + td, err := metricsgen.ParseMetricsDir(dir, "Metrics") + require.NoError(t, err) + + expected := + metricsgen.TemplateData{ + Package: "mypkg", + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Gauge", + FieldName: "m", + MetricName: "m", + }, + }, + } + require.Equal(t, expected, td) +} diff --git a/scripts/metricsgen/testdata/basic/metrics.gen.go b/scripts/metricsgen/testdata/basic/metrics.gen.go new file mode 100644 index 0000000..5af8c3b --- /dev/null +++ b/scripts/metricsgen/testdata/basic/metrics.gen.go @@ -0,0 +1,30 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package basic + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "height", + Help: "simple metric that tracks the height of the chain.", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Height: discard.NewGauge(), + } +} diff --git a/scripts/metricsgen/testdata/basic/metrics.go b/scripts/metricsgen/testdata/basic/metrics.go new file mode 100644 index 0000000..068ac04 --- /dev/null +++ b/scripts/metricsgen/testdata/basic/metrics.go @@ -0,0 +1,11 @@ +package basic + +import "github.com/go-kit/kit/metrics" + +//go:generate go run ../../../../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // simple metric that tracks the height of the chain. + Height metrics.Gauge +} diff --git a/scripts/metricsgen/testdata/commented/metrics.gen.go b/scripts/metricsgen/testdata/commented/metrics.gen.go new file mode 100644 index 0000000..c143e8a --- /dev/null +++ b/scripts/metricsgen/testdata/commented/metrics.gen.go @@ -0,0 +1,30 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package commented + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Field: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "field", + Help: "Height of the chain. We expect multi-line comments to parse correctly.", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Field: discard.NewGauge(), + } +} diff --git a/scripts/metricsgen/testdata/commented/metrics.go b/scripts/metricsgen/testdata/commented/metrics.go new file mode 100644 index 0000000..3ac367a --- /dev/null +++ b/scripts/metricsgen/testdata/commented/metrics.go @@ -0,0 +1,11 @@ +package commented + +import "github.com/go-kit/kit/metrics" + +//go:generate go run ../../../../scripts/metricsgen -struct=Metrics + +type Metrics struct { + // Height of the chain. + // We expect multi-line comments to parse correctly. + Field metrics.Gauge +} diff --git a/scripts/metricsgen/testdata/tags/metrics.gen.go b/scripts/metricsgen/testdata/tags/metrics.gen.go new file mode 100644 index 0000000..a58542c --- /dev/null +++ b/scripts/metricsgen/testdata/tags/metrics.gen.go @@ -0,0 +1,55 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package tags + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + WithLabels: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "with_labels", + Help: "", + }, append(labels, "step", "time")).With(labelsAndValues...), + WithExpBuckets: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "with_exp_buckets", + Help: "", + + Buckets: stdprometheus.ExponentialBuckets(.1, 100, 8), + }, labels).With(labelsAndValues...), + WithBuckets: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "with_buckets", + Help: "", + + Buckets: []float64{1, 2, 3, 4, 5}, + }, labels).With(labelsAndValues...), + Named: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "metric_with_name", + Help: "", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + WithLabels: discard.NewCounter(), + WithExpBuckets: discard.NewHistogram(), + WithBuckets: discard.NewHistogram(), + Named: discard.NewCounter(), + } +} diff --git a/scripts/metricsgen/testdata/tags/metrics.go b/scripts/metricsgen/testdata/tags/metrics.go new file mode 100644 index 0000000..930c8a0 --- /dev/null +++ b/scripts/metricsgen/testdata/tags/metrics.go @@ -0,0 +1,12 @@ +package tags + +import "github.com/go-kit/kit/metrics" + +//go:generate go run ../../../../scripts/metricsgen -struct=Metrics + +type Metrics struct { + WithLabels metrics.Counter `metrics_labels:"step,time"` + WithExpBuckets metrics.Histogram `metrics_buckettype:"exp" metrics_bucketsizes:".1,100,8"` + WithBuckets metrics.Histogram `metrics_bucketsizes:"1, 2, 3, 4, 5"` + Named metrics.Counter `metrics_name:"metric_with_name"` +} diff --git a/scripts/mockery_generate.sh b/scripts/mockery_generate.sh new file mode 100755 index 0000000..6b9575a --- /dev/null +++ b/scripts/mockery_generate.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# +# Invoke Mockery v2 to update generated mocks for the given type. + +go run github.com/vektra/mockery/v2@v2.53.0 --name "$*" diff --git a/scripts/proto-gen.sh b/scripts/proto-gen.sh new file mode 100755 index 0000000..fefe575 --- /dev/null +++ b/scripts/proto-gen.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# Update the generated code for protocol buffers in the CometBFT repository. +# This must be run from inside a CometBFT working directory. +# +set -euo pipefail + +# Work from the root of the repository. +cd "$(git rev-parse --show-toplevel)" + +# Run inside Docker to install the correct versions of the required tools +# without polluting the local system. +docker run --rm -i -v "$PWD":/w --workdir=/w golang:1.20-alpine sh <<"EOF" +apk add git make + +go install github.com/bufbuild/buf/cmd/buf +go install github.com/cosmos/gogoproto/protoc-gen-gogofaster@latest +make proto-gen +EOF diff --git a/scripts/qa/reporting/README.md b/scripts/qa/reporting/README.md new file mode 100644 index 0000000..3ec8a94 --- /dev/null +++ b/scripts/qa/reporting/README.md @@ -0,0 +1,97 @@ +# Reporting Scripts + +This directory contains some utility scripts used in the reporting/QA. + +* [`latency_throughput.py`](./latency_throughput.py) is a Python script that uses + [matplotlib] to plot a graph of transaction latency vs throughput rate based on + the CSV output generated by the [loadtime reporting + tool](../../../test/loadtime/cmd/report/). + +* [`latency_plotter.py`](./latency_plotter.py) is a Python script that uses + [matplotlib] and [pandas] to plot graph of transaction latency vs throughput rate based on + the CSV output generated by the [loadtime reporting + tool](../../../test/loadtime/cmd/report/), for multiple experiments and configurations. + +* [`prometheus_plotter.py`](./prometheus_plotter.py) is a Python script that uses + [matplotlib] and [pandas] to plot graphs of several metrics from Prometheus. + +## Setup + +Execute the following within this directory (the same directory as the +`latency_throughput.py` file). + +```bash +# Create a virtual environment into which to install your dependencies +python3 -m venv .venv + +# Activate the virtual environment +source .venv/bin/activate + +# Install dependencies listed in requirements.txt +pip install -r requirements.txt +``` + +## Latency vs Throughput Plotting +To show the instructions and parameter options, execute + +```bash +./latency_throughput.py --help +``` + +Example: + +```bash +# Do the following while ensuring that the virtual environment is activated (see +# the Setup steps). +# +# This will generate a plot in a PNG file called 'tm034.png' in the current +# directory based on the reporting tool CSV output in the "raw.csv" file. The +# '-t' flag overrides the default title at the top of the plot. + +./latency_throughput.py \ + -t 'CometBFT v0.34.x Latency vs Throughput' \ + ./tm034.png \ + /path/to/csv/files/raw.csv +``` + +## Latency vs Throughput Plotting (version 2) +Example: + +```bash +# Do the following while ensuring that the virtual environment is activated (see +# the Setup steps). +# +# This will generate a series of plots in the `imgs` folder. +# Plots include combined experiment plots and experiments as subplots. +# - all_experiments - plots of all experiments as individual subplots. +# - all_configs - plots of all experiments, grouped by configuration (r,c). +# cXrY.png - Independent plot of experiments of configuration (c=X,r=Y) as different curves. +# cXrY_merged.png - Independent plot of experiments of configuration (c=X,r=Y) combined as single curve. +# e_ID.png - independent plot with just experiment with id ID as a single curve. + +mkdir -p imgs +python3 latency_plotter.py /path/to/csv/files/raw.csv +``` + +## Prometheus metrics + +1. Ensure that Prometheus is running locally and listening on port 9090. +2. Tweak the script to your needs + 1. Adjust the time window + 2. Select the right fork + 3. Select the right test case + 4. Tweak/add/remove metrics +3. Run the script as follows + ```bash + # Do the following while ensuring that the virtual environment is activated (see + # the Setup steps). + # + # This will generate a series of plots in the folder `imgs` of the current folder. + + mkdir imgs + python3 prometheus_plotter.py + ``` +4. Plots are saved in the `imgs` folder. + +[matplotlib]: https://matplotlib.org/ +[pandas]: https://pandas.pydata.org diff --git a/scripts/qa/reporting/latency_plotter.py b/scripts/qa/reporting/latency_plotter.py new file mode 100644 index 0000000..1397317 --- /dev/null +++ b/scripts/qa/reporting/latency_plotter.py @@ -0,0 +1,150 @@ +import sys +import os +from datetime import datetime +import pytz + +import matplotlib as mpl +import matplotlib.pyplot as plt + +import numpy as np +import pandas as pd + +release = 'v0.38.0-alpha2' + +#FIXME: figure out in which timezone prometheus was running to adjust to UTC. +tz = pytz.timezone('America/Sao_Paulo') + +if len(sys.argv) != 2: + print('Pls provide the raw.csv file') + exit() +else: + csvpath = sys.argv[1] + if not os.path.exists(csvpath): + print('Pls provide a valid the raw.csv file') + exit() + + print(csvpath) + +path = os.path.join('imgs') + +#Load the CSV +csv = pd.read_csv(csvpath) + +#Transform ns to s in the latency/duration +csv['duration_ns'] = csv['duration_ns'].apply(lambda x: x/10**9) +csv['block_time'] = csv['block_time'].apply(lambda x: x/10**9) + +#Group by experiment +groups = csv.groupby(['experiment_id']) + +#number of rows and columns in the graph +ncols = 2 if groups.ngroups > 1 else 1 +nrows = int( np.ceil(groups.ngroups / ncols)) if groups.ngroups > 1 else 1 +fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(6*ncols, 4*nrows), sharey=False) +fig.tight_layout(pad=5.0) + + +#Plot experiments as subplots +for (key,ax) in zip(groups.groups.keys(), [axes] if ncols == 1 else axes.flatten()): + group = groups.get_group(key) + ax.set_ylabel('latency (s)') + ax.set_xlabel('experiment time (s)') + ax.set_title(key) + ax.grid(True) + + #Group by connection number and transaction rate + paramGroups = group.groupby(['connections','rate']) + for (subKey) in paramGroups.groups.keys(): + subGroup = paramGroups.get_group(subKey) + startTime = subGroup.block_time.min() + endTime = subGroup.block_time.max() + localStartTime = tz.localize(datetime.fromtimestamp(startTime)).astimezone(pytz.utc) + localEndTime = tz.localize(datetime.fromtimestamp(endTime)).astimezone(pytz.utc) + subGroup.block_time.apply(lambda x: x - startTime ) + mean = subGroup.duration_ns.mean() + print('exp', key ,'start', localEndTime.strftime("%Y-%m-%dT%H:%M:%SZ"), 'end', localStartTime.strftime("%Y-%m-%dT%H:%M:%SZ"), 'duration', endTime - startTime, "mean", mean) + + (con,rate) = subKey + label = 'c='+str(con) + ' r='+ str(rate) + ax.axhline(y = mean, color = 'r', linestyle = '-', label="mean") + ax.scatter(subGroup.block_time, subGroup.duration_ns, label=label) + ax.legend() + + #Save individual axes + extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) + fig.savefig(os.path.join(path,'e_'+key + '.png'), bbox_inches=extent.expanded(1.2, 1.3)) + +fig.suptitle('Vote Extensions Testnet - ' + release) + +# Save the figure with subplots +fig.savefig(os.path.join(path,'all_experiments.png')) + + + +#Group by configuration +groups = csv.groupby(['connections','rate']) + +#number of rows and columns in the graph +ncols = 2 if groups.ngroups > 1 else 1 +nrows = int( np.ceil(groups.ngroups / ncols)) if groups.ngroups > 1 else 1 +fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(6*ncols, 4*nrows), sharey=True) +fig.tight_layout(pad=5.0) + +#Plot configurations as subplots +for (key,ax) in zip(groups.groups.keys(), [axes] if ncols == 1 else axes.flatten()): + group = groups.get_group(key) + ax.set_ylabel('latency (s)') + ax.set_xlabel('experiment time (s)') + ax.grid(True) + (con,rate) = key + label = 'c='+str(con) + ' r='+ str(rate) + ax.set_title(label) + + #Group by experiment + paramGroups = group.groupby(['experiment_id']) + for (subKey) in paramGroups.groups.keys(): + subGroup = paramGroups.get_group(subKey) + startTime = subGroup.block_time.min() + subGroupMod = subGroup.block_time.apply(lambda x: x - startTime) + ax.scatter(subGroupMod, subGroup.duration_ns, label=label) + #ax.legend() + + + #Save individual axes + extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) + fig.savefig(os.path.join(path,'c'+str(con) + 'r'+ str(rate) + '.png'), bbox_inches=extent.expanded(1.2, 1.3)) + +fig.suptitle('Vote Extensions Testnet - ' + release) + + +# Save the figure with subplots +fig.savefig(os.path.join(path,'all_configs.png')) + + +fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(6*ncols, 4*nrows), sharey=True) +fig.tight_layout(pad=5.0) + +#Plot configurations as subplots +for (key,ax) in zip(groups.groups.keys(), [axes] if ncols == 1 else axes.flatten()): + group = groups.get_group(key) + ax.set_ylabel('latency (s)') + ax.set_xlabel('experiment time (s)') + ax.grid(True) + (con,rate) = key + label = 'c='+str(con) + ' r='+ str(rate) + ax.set_title(label) + + #Group by experiment, but merge them as a single experiment + paramGroups = group.groupby(['experiment_id']) + for (subKey) in paramGroups.groups.keys(): + subGroup = paramGroups.get_group(subKey) + startTime = subGroup.block_time.min() + subGroupMod = subGroup.block_time.apply(lambda x: x - startTime) + ax.scatter(subGroupMod, subGroup.duration_ns, marker='o',c='#1f77b4') + + #Save individual axes + extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) + (con,rate) = key + fig.savefig(os.path.join(path,'c'+str(con) + 'r'+ str(rate) + '_merged.png'), bbox_inches=extent) + +plt.show() diff --git a/scripts/qa/reporting/latency_throughput.py b/scripts/qa/reporting/latency_throughput.py new file mode 100755 index 0000000..65e2b2e --- /dev/null +++ b/scripts/qa/reporting/latency_throughput.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +""" +A simple script to parse the CSV output from the loadtime reporting tool (see +https://github.com/cometbft/cometbft/tree/v0.38.x/test/loadtime/cmd/report). + +Produces a plot of average transaction latency vs total transaction throughput +according to the number of load testing tool WebSocket connections to the +CometBFT node. +""" + +import argparse +import csv +import logging +import sys +import matplotlib.pyplot as plt +import numpy as np + +DEFAULT_TITLE = "CometBFT latency vs throughput" + + +def main(): + parser = argparse.ArgumentParser( + description="Renders a latency vs throughput diagram " + "for a set of transactions provided by the loadtime reporting tool", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument('-t', + '--title', + default=DEFAULT_TITLE, + help='Plot title') + parser.add_argument('output_image', + help='Output image file (in PNG format)') + parser.add_argument( + 'input_csv_file', + nargs='+', + help="CSV input file from which to read transaction data " + "- must have been generated by the loadtime reporting tool") + args = parser.parse_args() + + logging.basicConfig(format='%(levelname)s\t%(message)s', + stream=sys.stdout, + level=logging.INFO) + plot_latency_vs_throughput(args.input_csv_file, + args.output_image, + title=args.title) + + +def plot_latency_vs_throughput(input_files, output_image, title=DEFAULT_TITLE): + avg_latencies, throughput_rates = process_input_files(input_files, ) + + fig, ax = plt.subplots() + + connections = sorted(avg_latencies.keys()) + for c in connections: + tr = np.array(throughput_rates[c]) + al = np.array(avg_latencies[c]) + label = '%d connection%s' % (c, '' if c == 1 else 's') + ax.plot(tr, al, 'o-', label=label) + + ax.set_title(title) + ax.set_xlabel('Throughput rate (tx/s)') + ax.set_ylabel('Average transaction latency (s)') + + plt.legend(loc='upper left') + plt.savefig(output_image) + + +def process_input_files(input_files): + # Experimental data from which we will derive the latency vs throughput + # statistics + experiments = {} + + for input_file in input_files: + logging.info('Reading %s...' % input_file) + + with open(input_file, 'rt') as inf: + reader = csv.DictReader(inf) + for tx in reader: + experiments = process_tx(experiments, tx) + + return compute_experiments_stats(experiments) + + +def process_tx(experiments, tx): + exp_id = tx['experiment_id'] + # Block time is nanoseconds from the epoch - convert to seconds + block_time = float(tx['block_time']) / (10**9) + # Duration is also in nanoseconds - convert to seconds + duration = float(tx['duration_ns']) / (10**9) + connections = int(tx['connections']) + rate = int(tx['rate']) + + if exp_id not in experiments: + experiments[exp_id] = { + 'connections': connections, + 'rate': rate, + 'block_time_min': block_time, + # We keep track of the latency associated with the minimum block + # time to estimate the start time of the experiment + 'block_time_min_duration': duration, + 'block_time_max': block_time, + 'total_latencies': duration, + 'tx_count': 1, + } + logging.info('Found experiment %s with rate=%d, connections=%d' % + (exp_id, rate, connections)) + else: + # Validation + for field in ['connections', 'rate']: + val = int(tx[field]) + if val != experiments[exp_id][field]: + raise Exception( + 'Found multiple distinct values for field ' + '"%s" for the same experiment (%s): %d and %d' % + (field, exp_id, val, experiments[exp_id][field])) + + if block_time < experiments[exp_id]['block_time_min']: + experiments[exp_id]['block_time_min'] = block_time + experiments[exp_id]['block_time_min_duration'] = duration + if block_time > experiments[exp_id]['block_time_max']: + experiments[exp_id]['block_time_max'] = block_time + + experiments[exp_id]['total_latencies'] += duration + experiments[exp_id]['tx_count'] += 1 + + return experiments + + +def compute_experiments_stats(experiments): + """Compute average latency vs throughput rate statistics from the given + experiments""" + stats = {} + + # Compute average latency and throughput rate for each experiment + for exp_id, exp in experiments.items(): + conns = exp['connections'] + avg_latency = exp['total_latencies'] / exp['tx_count'] + exp_start_time = exp['block_time_min'] - exp['block_time_min_duration'] + exp_duration = exp['block_time_max'] - exp_start_time + throughput_rate = exp['tx_count'] / exp_duration + if conns not in stats: + stats[conns] = [] + + stats[conns].append({ + 'avg_latency': avg_latency, + 'throughput_rate': throughput_rate, + }) + + # Sort stats for each number of connections in order of increasing + # throughput rate, and then extract average latencies and throughput rates + # as separate data series. + conns = sorted(stats.keys()) + avg_latencies = {} + throughput_rates = {} + for c in conns: + stats[c] = sorted(stats[c], key=lambda s: s['throughput_rate']) + avg_latencies[c] = [] + throughput_rates[c] = [] + for s in stats[c]: + avg_latencies[c].append(s['avg_latency']) + throughput_rates[c].append(s['throughput_rate']) + logging.info('For %d connection(s): ' + 'throughput rate = %.6f tx/s\t' + 'average latency = %.6fs' % + (c, s['throughput_rate'], s['avg_latency'])) + + return (avg_latencies, throughput_rates) + + +if __name__ == "__main__": + main() diff --git a/scripts/qa/reporting/prometheus_plotter.py b/scripts/qa/reporting/prometheus_plotter.py new file mode 100644 index 0000000..801bc53 --- /dev/null +++ b/scripts/qa/reporting/prometheus_plotter.py @@ -0,0 +1,151 @@ +# pip install numpy pandas matplotlib requests + +import sys +import os + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.dates as md + +import numpy as np +import pandas as pd + +import requests +from urllib.parse import urljoin + +from prometheus_pandas import query + +#release = 'v0.37.0-alpha.2' +release = 'v0.38.0-alpha.2' +path = os.path.join('imgs') +prometheus = query.Prometheus('http://localhost:9090') + +# Time window +#window_size = dict(seconds=150) #CMT 0.37.x-alpha3 +#window_size = dict(seconds=126) #TM v0.37 (200 nodes) baseline +#window_size = dict(hours=1, minutes=28, seconds=25) #TM v0.37.0-alpha.2 (rotating) +#window_size = dict(seconds=130) #homogeneous +#window_size = dict(seconds=127) #baseline +#window_size = dict(seconds=115) #CMT v0.38.0-alpha.2 (200 nodes) +#window_size = dict(hours=1, minutes=46) #CMT v0.38.0-alpha.2 (rotating) +window_size = dict(seconds=150) #CMT v0.38.0-alpha.2 (ve baseline) + +ext_window_size = dict(seconds=200) + +# Use the time provided by latency_plotter for the selected experiment. +#left_end = '2023-02-08T13:12:20Z' #cmt2 tm1 +#left_end = '2023-02-08T10:31:50Z' #cmt1 tm2 +#left_end = '2023-02-14T15:18:00Z' #cmt1 tm1 +#left_end = '2023-02-07T18:07:00Z' #homogeneous +#left_end = '2022-10-13T19:41:23Z' #baseline +#left_end = '2023-02-22T18:56:29Z' #CMT v0.37.x-alpha3 +#left_end = '2022-10-13T15:57:50Z' #TM v0.37 (200 nodes) baseline +#left_end = '2023-03-20T19:45:35Z' #feature/abci++vef merged with main (7d8c9d426) +#left_end = '2023-05-22T09:39:20Z' #CMT v0.38.0-alpha.2 - 200 nodes +#left_end = '2022-10-10T15:47:15Z' #TM v0.37.0-alpha.2 - rotating +#left_end = '2023-05-23T08:09:50Z' #CMT v0.38.0-alpha.2 - rotating + +#left_end = '2023-05-25T18:18:04Z' #CMT v0.38.0-alpha.2 - ve baseline +#left_end = '2023-05-30T19:05:32Z' #CMT v0.38.0-alpha.2 - ve 2k +left_end = '2023-05-30T20:44:46Z' #CMT v0.38.0-alpha.2 - ve 4k +#left_end = '2023-05-25T19:42:08Z' #CMT v0.38.0-alpha.2 - ve 8k +#left_end = '2023-05-26T00:28:12Z' #CMT v0.38.0-alpha.2 - ve 16k +#left_end = '2023-05-26T02:12:27Z' #CMT v0.38.0-alpha.2 - ve 32k + +useManualrightEnd = False +if useManualrightEnd: + #right_end = '2023-05-25T18:54:04Z' #CMT v0.38.0-alpha.2 - ve baseline + #right_end = '2023-05-30T19:40:41Z' #CMT v0.38.0-alpha.2 - ve 2k + right_end = '2023-05-30T21:15:37Z' #CMT v0.38.0-alpha.2 - ve 4k + #right_end = '2023-05-25T20:16:00Z' #CMT v0.38.0-alpha.2 - ve 8k + #right_end = '2023-05-26T01:01:57Z' #CMT v0.38.0-alpha.2 - ve 16k + #right_end = '2023-05-26T02:46:19Z' #CMT v0.38.0-alpha.2 - ve 32k + time_window = (left_end, right_end) +else: + right_end = pd.to_datetime(left_end) + pd.Timedelta(**window_size) + time_window = (left_end, right_end.strftime('%Y-%m-%dT%H:%M:%SZ')) + +ext_right_end = pd.to_datetime(left_end) + pd.Timedelta(**ext_window_size) +ext_time_window = (left_end, ext_right_end.strftime('%Y-%m-%dT%H:%M:%SZ')) + + +fork='cometbft' +#fork='tendermint' + +# Do prometheus queries, depending on the test case +queries200Nodes = [ + (( fork + '_mempool_size', time_window[0], time_window[1], '1s'), 'mempool_size', dict(ylabel='TXs', xlabel='time (s)', title='Mempool Size', legend=False, figsize=(10,6), grid=True, kind='area',stacked=True), False), + (( fork + '_p2p_peers', time_window[0], time_window[1], '1s'), 'peers', dict(ylabel='# Peers', xlabel='time (s)', title='Peers', legend=False, figsize=(10,6), grid=True), True), + (( 'avg(' + fork + '_mempool_size)', time_window[0], time_window[1], '1s'), 'avg_mempool_size', dict(ylabel='TXs', xlabel='time (s)', title='Average Mempool Size', legend=False, figsize=(10,6), grid=True), False), + #(( 'cometbft_consensus_height', time_window[0], time_window[1], '1s'), 'blocks_regular', dict(ylabel='# Blocks', xlabel='time (s)', title='Blocks in time', legend=False, figsize=(10,6), grid=True), False), + (( fork + '_consensus_rounds', time_window[0], time_window[1], '1s'), 'rounds', dict(ylabel='# Rounds', xlabel='time (s)', title='Rounds per block', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_height[20s])*60', time_window[0], time_window[1], '1s'), 'block_rate_regular', dict(ylabel='Blocks/min', xlabel='time (s)', title='Rate of block creation', legend=False, figsize=(10,6), grid=True), True), + #(( 'avg(rate(cometbft_consensus_height[20s])*60)', time_window[0], time_window[1], '1s'), 'block_rate_avg_reg', dict(ylabel='Blocks/min', xlabel='time (s)', title='Rate of block creation', legend=False, figsize=(10,6), grid=True), False), + #(( 'cometbft_consensus_total_txs', time_window[0], time_window[1], '1s'), 'total_txs_regular', dict(ylabel='# TXs', xlabel='time (s)', title='Transactions in time', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_total_txs[20s])*60', time_window[0], time_window[1], '1s'), 'total_txs_rate_regular', dict(ylabel='TXs/min', xlabel='time (s)', title='Rate of transaction processing', legend=False, figsize=(10,6), grid=True), True), + #(( 'avg(rate(cometbft_consensus_total_txs[20s])*60)', time_window[0], time_window[1], '1s'), 'total_txs_rate_avg_reg', dict(ylabel='TXs/min', xlabel='time (s)', title='Rate of transaction processing', legend=False, figsize=(10,6), grid=True), False), + (( 'process_resident_memory_bytes', time_window[0], time_window[1], '1s'), 'memory', dict(ylabel='Memory (bytes)', xlabel='time (s)', title='Memory usage', legend=False, figsize=(10,6), grid=True), False), + (( 'avg(process_resident_memory_bytes)', time_window[0], time_window[1], '1s'), 'avg_memory', dict(ylabel='Memory (bytes)', xlabel='time (s)', title='Average Memory usage', legend=False, figsize=(10,6), grid=True), False), + (( 'node_load1', time_window[0], time_window[1], '1s'), 'cpu', dict(ylabel='Load', xlabel='time (s)', title='Node load', legend=False, figsize=(10,6), grid=True), False), + (( 'avg(node_load1)', time_window[0], time_window[1], '1s'), 'avg_cpu', dict(ylabel='Load', xlabel='time (s)', title='Average Node load', legend=False, figsize=(10,6), grid=True), False), + #extended window metrics + (( fork + '_consensus_height', ext_time_window[0], ext_time_window[1], '1s'), 'blocks', dict(ylabel='# Blocks', xlabel='time (s)', title='Blocks in time', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_height[20s])*60', ext_time_window[0], ext_time_window[1], '1s'), 'block_rate', dict(ylabel='Blocks/min', xlabel='time (s)', title='Rate of block creation', legend=False, figsize=(10,6), grid=True), True), + (( fork + '_consensus_total_txs', ext_time_window[0], ext_time_window[1], '1s'), 'total_txs', dict(ylabel='# TXs', xlabel='time (s)', title='Transactions in time', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_total_txs[20s])*60', ext_time_window[0], ext_time_window[1], '1s'), 'total_txs_rate', dict(ylabel='TXs/min', xlabel='time (s)', title='Rate of transaction processing', legend=False, figsize=(10,6), grid=True), True), +] + +queriesRotating = [ + (( 'rate(' + fork + '_consensus_height[20s])*60', time_window[0], time_window[1], '1s'), 'rotating_block_rate', dict(ylabel='blocks/min', xlabel='time', title='Rate of Block Creation', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_total_txs[20s])*60', time_window[0], time_window[1], '1s'), 'rotating_txs_rate', dict(ylabel='TXs/min', xlabel='time', title='Rate of Transaction processing', legend=False, figsize=(10,6), grid=True), False), + (( fork + '_consensus_height{job=~"ephemeral.*"} or ' + fork + '_blocksync_latest_block_height{job=~"ephemeral.*"}', + time_window[0], time_window[1], '1s'), 'rotating_eph_heights', dict(ylabel='height', xlabel='time', title='Heights of Ephemeral Nodes', legend=False, figsize=(10,6), grid=True), False), + (( fork + '_p2p_peers', time_window[0], time_window[1], '1s'), 'rotating_peers', dict(ylabel='# peers', xlabel='time', title='Peers', legend=False, figsize=(10,6), grid=True), False), + (( 'avg(process_resident_memory_bytes)', time_window[0], time_window[1], '1s'), 'rotating_avg_memory', dict(ylabel='memory (bytes)', xlabel='time', title='Average Memory Usage', legend=False, figsize=(10,6), grid=True), False), + (( 'node_load1', time_window[0], time_window[1], '1s'), 'rotating_cpu', dict(ylabel='load', xlabel='time', title='Node Load', legend=False, figsize=(10,6), grid=True), False), +] + +queriesVExtension= [ + (( fork + '_mempool_size', time_window[0], time_window[1], '1s'), 'mempool_size', dict(ylabel='TXs', xlabel='time (s)', title='Mempool Size', legend=False, figsize=(10,6), grid=True, kind='area',stacked=True), False), + (( fork + '_mempool_size', time_window[0], time_window[1], '1s'), 'mempool_size_not_stacked', dict(ylabel='TXs', xlabel='time (s)', title='Mempool Size', legend=False, figsize=(10,6), grid=True, stacked=False), False), + (( fork + '_p2p_peers', time_window[0], time_window[1], '1s'), 'peers', dict(ylabel='# Peers', xlabel='time (s)', title='Peers', legend=False, figsize=(10,6), grid=True), True), + (( 'avg(' + fork + '_mempool_size)', time_window[0], time_window[1], '1s'), 'avg_mempool_size', dict(ylabel='TXs', xlabel='time (s)', title='Average Mempool Size', legend=False, figsize=(10,6), grid=True), False), + (( fork + '_consensus_rounds', time_window[0], time_window[1], '1s'), 'rounds', dict(ylabel='# Rounds', xlabel='time (s)', title='Rounds per block', legend=False, figsize=(10,6), grid=True), False), + (( 'process_resident_memory_bytes', time_window[0], time_window[1], '1s'), 'memory', dict(ylabel='Memory (bytes)', xlabel='time (s)', title='Memory usage', legend=False, figsize=(10,6), grid=True), False), + (( 'avg(process_resident_memory_bytes)', time_window[0], time_window[1], '1s'), 'avg_memory', dict(ylabel='Memory (bytes)', xlabel='time (s)', title='Average Memory usage', legend=False, figsize=(10,6), grid=True), False), + (( 'node_load1', time_window[0], time_window[1], '1s'), 'cpu', dict(ylabel='Load', xlabel='time (s)', title='Node load', legend=False, figsize=(10,6), grid=True), False), + (( 'avg(node_load1)', time_window[0], time_window[1], '1s'), 'avg_cpu', dict(ylabel='Load', xlabel='time (s)', title='Average Node load', legend=False, figsize=(10,6), grid=True), False), + (( fork + '_consensus_height', time_window[0], time_window[1], '1s'), 'blocks', dict(ylabel='# Blocks', xlabel='time (s)', title='Blocks in time', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_height[20s])*60', time_window[0], time_window[1], '1s'), 'block_rate', dict(ylabel='Blocks/min', xlabel='time (s)', title='Rate of block creation', legend=False, figsize=(10,6), grid=True), True), + (( fork + '_consensus_total_txs', time_window[0], time_window[1], '1s'), 'total_txs', dict(ylabel='# TXs', xlabel='time (s)', title='Transactions in time', legend=False, figsize=(10,6), grid=True), False), + (( 'rate(' + fork + '_consensus_total_txs[20s])*60', time_window[0], time_window[1], '1s'), 'total_txs_rate', dict(ylabel='TXs/min', xlabel='time (s)', title='Rate of transaction processing', legend=False, figsize=(10,6), grid=True), True), +] + +#queries = queries200Nodes +#queries = queriesRotating +queries = queriesVExtension + + +for (query, file_name, pandas_params, plot_average) in queries: + print(query) + + data_frame = prometheus.query_range(*query) + #Tweak the x ticks + data_frame = data_frame.set_index(md.date2num(data_frame.index)) + + + pandas_params["title"] += " - " + release + ax = data_frame.plot(**pandas_params) + if plot_average: + average = data_frame.mean(axis=1) + data_frame['__average__'] = average + pandas_params['lw'] = 8 + pandas_params['style'] = ['--'] + pandas_params['color'] = ['red'] + ax = data_frame['__average__'].plot(**pandas_params) + + ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S')) + plt.savefig(os.path.join(path, file_name + '.png')) + plt.plot() + +plt.show() diff --git a/scripts/qa/reporting/requirements.txt b/scripts/qa/reporting/requirements.txt new file mode 100644 index 0000000..b8b6b2c --- /dev/null +++ b/scripts/qa/reporting/requirements.txt @@ -0,0 +1,14 @@ +contourpy==1.0.5 +cycler==0.11.0 +fonttools==4.37.4 +kiwisolver==1.4.4 +matplotlib==3.6.3 +numpy==1.24.2 +packaging==21.3 +Pillow==10.0.1 +pyparsing==3.0.9 +python-dateutil==2.8.2 +six==1.16.0 +pandas==1.5.3 +prometheus-pandas==0.3.2 +requests==2.31.0 diff --git a/scripts/txs/random.sh b/scripts/txs/random.sh new file mode 100644 index 0000000..d70bdf1 --- /dev/null +++ b/scripts/txs/random.sh @@ -0,0 +1,19 @@ +#! /bin/bash +set -u + +function toHex() { + echo -n $1 | hexdump -ve '1/1 "%.2X"' +} + +N=$1 +PORT=$2 + +for i in `seq 1 $N`; do + # store key value pair + KEY=$(head -c 10 /dev/urandom) + VALUE="$i" + echo $(toHex $KEY=$VALUE) + curl 127.0.0.1:$PORT/broadcast_tx_sync?tx=0x$(toHex $KEY=$VALUE) +done + + diff --git a/scripts/wal2json/main.go b/scripts/wal2json/main.go new file mode 100644 index 0000000..74b8601 --- /dev/null +++ b/scripts/wal2json/main.go @@ -0,0 +1,62 @@ +/* + wal2json converts binary WAL file to JSON. + + Usage: + wal2json +*/ + +package main + +import ( + "fmt" + "io" + "os" + + cs "github.com/cometbft/cometbft/consensus" + cmtjson "github.com/cometbft/cometbft/libs/json" +) + +func main() { + if len(os.Args) < 2 { + fmt.Println("missing one argument: ") + os.Exit(1) + } + + f, err := os.Open(os.Args[1]) + if err != nil { + panic(fmt.Errorf("failed to open WAL file: %v", err)) + } + defer f.Close() + + dec := cs.NewWALDecoder(f) + for { + msg, err := dec.Decode() + if err == io.EOF { + break + } else if err != nil { + panic(fmt.Errorf("failed to decode msg: %v", err)) + } + + json, err := cmtjson.Marshal(msg) + if err != nil { + panic(fmt.Errorf("failed to marshal msg: %v", err)) + } + + _, err = os.Stdout.Write(json) + if err == nil { + _, err = os.Stdout.Write([]byte("\n")) + } + + if err == nil { + if endMsg, ok := msg.Msg.(cs.EndHeightMessage); ok { + _, err = fmt.Fprintf(os.Stdout, "ENDHEIGHT %d\n", endMsg.Height) + } + } + + if err != nil { + fmt.Println("Failed to write message", err) + os.Exit(1) //nolint:gocritic + } + + } +} diff --git a/spec/README.md b/spec/README.md new file mode 100644 index 0000000..334ea55 --- /dev/null +++ b/spec/README.md @@ -0,0 +1,93 @@ +--- +order: 1 +title: Overview +parent: + title: Spec + order: 7 +--- + +# CometBFT Spec + +This is a markdown specification of CometBFT. +It defines the base data structures, how they are validated, +and how they are communicated over the network. + +If you find discrepancies between the spec and the code that +do not have an associated issue or pull request on github, +please submit them to our [bug bounty](https://github.com/cometbft/cometbft#security)! + +## Contents + +- [Overview](#overview) + +### Data Structures + +- [Encoding and Digests](./core/encoding.md) +- [Blockchain](./core/data_structures.md) +- [State](./core/state.md) + +### Consensus Protocol + +- [Consensus Algorithm](./consensus/consensus.md) +- [Creating a proposal](./consensus/creating-proposal.md) +- [Time](./consensus/bft-time.md) +- [Light-Client](./consensus/light-client/README.md) + +### P2P and Network Protocols + +- [The Base P2P Layer](./p2p/legacy-docs/node.md): multiplex the protocols ("reactors") on authenticated and encrypted TCP connections +- [Peer Exchange (PEX)](./p2p/legacy-docs/messages/pex.md): gossip known peer addresses so peers can find each other +- [Block Sync](./p2p/legacy-docs/messages/block-sync.md): gossip blocks so peers can catch up quickly +- [Consensus](./p2p/legacy-docs/messages/consensus.md): gossip votes and block parts so new blocks can be committed +- [Mempool](./p2p/legacy-docs/messages/mempool.md): gossip transactions so they get included in blocks +- [Evidence](./p2p/legacy-docs/messages/evidence.md): sending invalid evidence will stop the peer + +### RPC + +- [RPC SPEC](./rpc/README.md): Specification of the CometBFT remote procedure call interface. + +### Software + +- [ABCI](./abci/README.md): Details about interactions between the + application and consensus engine over ABCI +- [Write-Ahead Log](./consensus/wal.md): Details about how the consensus + engine preserves data and recovers from crash failures + +## Overview + +CometBFT provides Byzantine Fault Tolerant State Machine Replication using +hash-linked batches of transactions. Such transaction batches are called "blocks". +Hence, CometBFT defines a "blockchain". + +Each block in CometBFT has a unique index - its Height. +Heights in the blockchain are monotonic. +Each block is committed by a known set of weighted Validators. +Membership and weighting within this validator set may change over time. +CometBFT guarantees the safety and liveness of the blockchain +as long as less than 1/3 of the total weight of the Validator set +is malicious or faulty. + +A commit in CometBFT is a set of signed messages from more than 2/3 of +the total weight of the current Validator set. Validators take turns proposing +blocks and voting on them. Once enough votes are received, the block is considered +committed. These votes are included in the _next_ block as proof that the previous block +was committed - they cannot be included in the current block, as that block has already been +created. + +Once a block is committed, it can be executed against an application. +The application returns results for each of the transactions in the block. +The application can also return changes to be made to the validator set, +as well as a cryptographic digest of its latest state. + +CometBFT is designed to enable efficient verification and authentication +of the latest state of the blockchain. To achieve this, it embeds +cryptographic commitments to certain information in the block "header". +This information includes the contents of the block (eg. the transactions), +the validator set committing the block, as well as the various results returned by the application. +Note, however, that block execution only occurs _after_ a block is committed. +Thus, application results can only be included in the _next_ block. + +Also note that information like the transaction results and the validator set are never +directly included in the block - only their cryptographic digests (Merkle roots) are. +Hence, verification of a block requires a separate data structure to store this information. +We call this the `State`. Block verification also requires access to the previous block. diff --git a/spec/abci/README.md b/spec/abci/README.md new file mode 100644 index 0000000..7276a07 --- /dev/null +++ b/spec/abci/README.md @@ -0,0 +1,41 @@ +--- +order: 1 +parent: + title: ABCI++ + order: 3 +--- + +# ABCI++ + +## Introduction + +ABCI++ is a major evolution of ABCI (**A**pplication **B**lock**c**hain **I**nterface). +Like its predecessor, ABCI++ is the interface between CometBFT (a state-machine +replication engine) and the actual state machine being replicated (i.e., the Application). +The API consists of a set of _methods_, each with a corresponding `Request` and `Response` +message type. + +The methods are always initiated by CometBFT. The Application implements its logic +for handling all ABCI++ methods. +Thus, CometBFT always sends the `Request*` messages and receives the `Response*` messages +in return. + +All ABCI++ messages and methods are defined in [protocol buffers](https://github.com/cometbft/cometbft/blob/v0.38.x/proto/tendermint/abci/types.proto). +This allows CometBFT to run with applications written in many programming languages. + +This specification is split as follows: + +- [Overview and basic concepts](./abci++_basic_concepts.md) - interface's overview and concepts + needed to understand other parts of this specification. +- [Methods](./abci++_methods.md) - complete details on all ABCI++ methods + and message types. +- [Requirements for the Application](./abci++_app_requirements.md) - formal requirements + on the Application's logic to ensure CometBFT properties such as liveness. These requirements define what + CometBFT expects from the Application; second part on managing ABCI application state and related topics. +- [CometBFT's expected behavior](./abci++_comet_expected_behavior.md) - specification of + how the different ABCI++ methods may be called by CometBFT. This explains what the Application + is to expect from CometBFT. +- [Example scenarios](./abci++_example_scenarios.md) - specific scenarios showing why the Application needs to account +for any CometBFT's behaviour prescribed by the specification. +- [Client and Server](./abci++_client_server.md) - for those looking to implement their + own ABCI application servers. diff --git a/spec/abci/abci++_app_requirements.md b/spec/abci/abci++_app_requirements.md new file mode 100644 index 0000000..04eed31 --- /dev/null +++ b/spec/abci/abci++_app_requirements.md @@ -0,0 +1,1070 @@ +--- +order: 3 +title: Requirements for the Application +--- + +# Requirements for the Application + +- [Requirements for the Application](#requirements-for-the-application) + - [Formal Requirements](#formal-requirements) + - [Consensus Connection Requirements](#consensus-connection-requirements) + - [Mempool Connection Requirements](#mempool-connection-requirements) + - [Managing the Application state and related topics](#managing-the-application-state-and-related-topics) + - [Connection State](#connection-state) + - [Concurrency](#concurrency) + - [FinalizeBlock](#finalizeblock) + - [Commit](#commit) + - [Candidate States](#candidate-states) + - [States and ABCI++ Connections](#states-and-abci-connections) + - [Consensus Connection](#consensus-connection) + - [Mempool Connection](#mempool-connection) + - [Replay Protection](#replay-protection) + - [Info/Query Connection](#infoquery-connection) + - [Snapshot Connection](#snapshot-connection) + - [Transaction Results](#transaction-results) + - [Gas](#gas) + - [Specifics of `ResponseCheckTx`](#specifics-of-responsechecktx) + - [Specifics of `ExecTxResult`](#specifics-of-exectxresult) + - [Updating the Validator Set](#updating-the-validator-set) + - [Consensus Parameters](#consensus-parameters) + - [List of Parameters](#list-of-parameters) + - [ABCIParams.VoteExtensionsEnableHeight](#abciparamsvoteextensionsenableheight) + - [BlockParams.MaxBytes](#blockparamsmaxbytes) + - [BlockParams.MaxGas](#blockparamsmaxgas) + - [EvidenceParams.MaxAgeDuration](#evidenceparamsmaxageduration) + - [EvidenceParams.MaxAgeNumBlocks](#evidenceparamsmaxagenumblocks) + - [EvidenceParams.MaxBytes](#evidenceparamsmaxbytes) + - [ValidatorParams.PubKeyTypes](#validatorparamspubkeytypes) + - [VersionParams.App](#versionparamsapp) + - [Updating Consensus Parameters](#updating-consensus-parameters) + - [`InitChain`](#initchain) + - [`FinalizeBlock`, `PrepareProposal`/`ProcessProposal`](#finalizeblock-prepareproposalprocessproposal) + - [`Query`](#query) + - [Query Proofs](#query-proofs) + - [Peer Filtering](#peer-filtering) + - [Paths](#paths) + - [Crash Recovery](#crash-recovery) + - [State Sync](#state-sync) + - [Taking Snapshots](#taking-snapshots) + - [Bootstrapping a Node](#bootstrapping-a-node) + - [Snapshot Discovery](#snapshot-discovery) + - [Snapshot Restoration](#snapshot-restoration) + - [Snapshot Verification](#snapshot-verification) + - [Transition to Consensus](#transition-to-consensus) + - [Application configuration required to switch to ABCI 2.0](#application-configuration-required-to-switch-to-abci-20) + + +## Formal Requirements + +### Consensus Connection Requirements + +This section specifies what CometBFT expects from the Application. It is structured as a set +of formal requirements that can be used for testing and verification of the Application's logic. + +Let *p* and *q* be two correct processes. +Let *rp* (resp. *rq*) be a round of height *h* where *p* (resp. *q*) is the +proposer. +Let *sp,h-1* be *p*'s Application's state committed for height *h-1*. +Let *vp* (resp. *vq*) be the block that *p*'s (resp. *q*'s) CometBFT passes +on to the Application +via `RequestPrepareProposal` as proposer of round *rp* (resp *rq*), height *h*, +also known as the raw proposal. +Let *up* (resp. *uq*) the possibly modified block *p*'s (resp. *q*'s) Application +returns via `ResponsePrepareProposal` to CometBFT, also known as the prepared proposal. + +Process *p*'s prepared proposal can differ in two different rounds where *p* is the proposer. + +- Requirement 1 [`PrepareProposal`, timeliness]: If *p*'s Application fully executes prepared blocks in + `PrepareProposal` and the network is in a synchronous period while processes *p* and *q* are in *rp*, + then the value of *TimeoutPropose* at *q* must be such that *q*'s propose timer does not time out + (which would result in *q* prevoting `nil` in *rp*). + +Full execution of blocks at `PrepareProposal` time stands on CometBFT's critical path. Thus, +Requirement 1 ensures the Application or operator will set a value for `TimeoutPropose` such that the time it takes +to fully execute blocks in `PrepareProposal` does not interfere with CometBFT's propose timer. +Note that the violation of Requirement 1 may lead to further rounds, but will not +compromise liveness because even though `TimeoutPropose` is used as the initial +value for proposal timeouts, CometBFT will be dynamically adjust these timeouts +such that they will eventually be enough for completing `PrepareProposal`. + +- Requirement 2 [`PrepareProposal`, tx-size]: When *p*'s Application calls `ResponsePrepareProposal`, the + total size in bytes of the transactions returned does not exceed `RequestPrepareProposal.max_tx_bytes`. + +Busy blockchains might seek to gain full visibility into transactions in CometBFT's mempool, +rather than having visibility only on *a* subset of those transactions that fit in a block. +The application can do so by setting `ConsensusParams.Block.MaxBytes` to -1. +This instructs CometBFT (a) to enforce the maximum possible value for `MaxBytes` (100 MB) at CometBFT level, +and (b) to provide *all* transactions in the mempool when calling `RequestPrepareProposal`. +Under these settings, the aggregated size of all transactions may exceed `RequestPrepareProposal.max_tx_bytes`. +Hence, Requirement 2 ensures that the size in bytes of the transaction list returned by the application will never +cause the resulting block to go beyond its byte size limit. + +- Requirement 3 [`PrepareProposal`, `ProcessProposal`, coherence]: For any two correct processes *p* and *q*, + if *q*'s CometBFT calls `RequestProcessProposal` on *up*, + *q*'s Application returns Accept in `ResponseProcessProposal`. + +Requirement 3 makes sure that blocks proposed by correct processes *always* pass the correct receiving process's +`ProcessProposal` check. +On the other hand, if there is a deterministic bug in `PrepareProposal` or `ProcessProposal` (or in both), +strictly speaking, this makes all processes that hit the bug byzantine. This is a problem in practice, +as very often validators are running the Application from the same codebase, so potentially *all* would +likely hit the bug at the same time. This would result in most (or all) processes prevoting `nil`, with the +serious consequences on CometBFT's liveness that this entails. Due to its criticality, Requirement 3 is a +target for extensive testing and automated verification. + +- Requirement 4 [`ProcessProposal`, determinism-1]: `ProcessProposal` is a (deterministic) function of the current + state and the block that is about to be applied. In other words, for any correct process *p*, and any arbitrary block *u*, + if *p*'s CometBFT calls `RequestProcessProposal` on *u* at height *h*, + then *p*'s Application's acceptance or rejection **exclusively** depends on *u* and *sp,h-1*. + +- Requirement 5 [`ProcessProposal`, determinism-2]: For any two correct processes *p* and *q*, and any arbitrary + block *u*, + if *p*'s (resp. *q*'s) CometBFT calls `RequestProcessProposal` on *u* at height *h*, + then *p*'s Application accepts *u* if and only if *q*'s Application accepts *u*. + Note that this requirement follows from Requirement 4 and the Agreement property of consensus. + +Requirements 4 and 5 ensure that all correct processes will react in the same way to a proposed block, even +if the proposer is Byzantine. However, `ProcessProposal` may contain a bug that renders the +acceptance or rejection of the block non-deterministic, and therefore prevents processes hitting +the bug from fulfilling Requirements 4 or 5 (effectively making those processes Byzantine). +In such a scenario, CometBFT's liveness cannot be guaranteed. +Again, this is a problem in practice if most validators are running the same software, as they are likely +to hit the bug at the same point. There is currently no clear solution to help with this situation, so +the Application designers/implementors must proceed very carefully with the logic/implementation +of `ProcessProposal`. As a general rule `ProcessProposal` SHOULD always accept the block. + +According to the Tendermint consensus algorithm, currently adopted in CometBFT, +a correct process can broadcast at most one precommit +message in round *r*, height *h*. +Since, as stated in the [Methods](./abci++_methods.md#extendvote) section, `ResponseExtendVote` +is only called when the consensus algorithm +is about to broadcast a non-`nil` precommit message, a correct process can only produce one vote extension +in round *r*, height *h*. +Let *erp* be the vote extension that the Application of a correct process *p* returns via +`ResponseExtendVote` in round *r*, height *h*. +Let *wrp* be the proposed block that *p*'s CometBFT passes to the Application via `RequestExtendVote` +in round *r*, height *h*. + +- Requirement 6 [`ExtendVote`, `VerifyVoteExtension`, coherence]: For any two different correct + processes *p* and *q*, if *q* receives *erp* from *p* in height *h*, *q*'s + Application returns Accept in `ResponseVerifyVoteExtension`. + +Requirement 6 constrains the creation and handling of vote extensions in a similar way as Requirement 3 +constrains the creation and handling of proposed blocks. +Requirement 6 ensures that extensions created by correct processes *always* pass the `VerifyVoteExtension` +checks performed by correct processes receiving those extensions. +However, if there is a (deterministic) bug in `ExtendVote` or `VerifyVoteExtension` (or in both), +we will face the same liveness issues as described for Requirement 5, as Precommit messages with invalid vote +extensions will be discarded. + +- Requirement 7 [`VerifyVoteExtension`, determinism-1]: `VerifyVoteExtension` is a (deterministic) function of + the current state, the vote extension received, and the prepared proposal that the extension refers to. + In other words, for any correct process *p*, and any arbitrary vote extension *e*, and any arbitrary + block *w*, if *p*'s (resp. *q*'s) CometBFT calls `RequestVerifyVoteExtension` on *e* and *w* at height *h*, + then *p*'s Application's acceptance or rejection **exclusively** depends on *e*, *w* and *sp,h-1*. + +- Requirement 8 [`VerifyVoteExtension`, determinism-2]: For any two correct processes *p* and *q*, + and any arbitrary vote extension *e*, and any arbitrary block *w*, + if *p*'s (resp. *q*'s) CometBFT calls `RequestVerifyVoteExtension` on *e* and *w* at height *h*, + then *p*'s Application accepts *e* if and only if *q*'s Application accepts *e*. + Note that this requirement follows from Requirement 7 and the Agreement property of consensus. + +Requirements 7 and 8 ensure that the validation of vote extensions will be deterministic at all +correct processes. +Requirements 7 and 8 protect against arbitrary vote extension data from Byzantine processes, +in a similar way as Requirements 4 and 5 protect against arbitrary proposed blocks. +Requirements 7 and 8 can be violated by a bug inducing non-determinism in +`VerifyVoteExtension`. In this case liveness can be compromised. +Extra care should be put in the implementation of `ExtendVote` and `VerifyVoteExtension`. +As a general rule, `VerifyVoteExtension` SHOULD always accept the vote extension. + +- Requirement 9 [*all*, no-side-effects]: *p*'s calls to `RequestPrepareProposal`, + `RequestProcessProposal`, `RequestExtendVote`, and `RequestVerifyVoteExtension` at height *h* do + not modify *sp,h-1*. + + +- Requirement 10 [`ExtendVote`, `FinalizeBlock`, non-dependency]: for any correct process *p*, +and any vote extension *e* that *p* received at height *h*, the computation of +*sp,h* does not depend on *e*. + +The call to correct process *p*'s `RequestFinalizeBlock` at height *h*, with block *vp,h* +passed as parameter, creates state *sp,h*. +Additionally, *p*'s `FinalizeBlock` creates a set of transaction results *Tp,h*. + +- Requirement 11 [`FinalizeBlock`, determinism-1]: For any correct process *p*, + *sp,h* exclusively depends on *sp,h-1* and *vp,h*. + +- Requirement 12 [`FinalizeBlock`, determinism-2]: For any correct process *p*, + the contents of *Tp,h* exclusively depend on *sp,h-1* and *vp,h*. + +Note that Requirements 11 and 12, combined with the Agreement property of consensus ensure +state machine replication, i.e., the Application state evolves consistently at all correct processes. + +Also, notice that neither `PrepareProposal` nor `ExtendVote` have determinism-related +requirements associated. +Indeed, `PrepareProposal` is not required to be deterministic: + +- *up* may depend on *vp* and *sp,h-1*, but may also depend on other values or operations. +- *vp = vq ⇏ up = uq*. + +Likewise, `ExtendVote` can also be non-deterministic: + +- *erp* may depend on *wrp* and *sp,h-1*, + but may also depend on other values or operations. +- *wrp = wrq ⇏ + erp = erq* + +### Mempool Connection Requirements + +Let *CheckTxCodestx,p,h* denote the set of result codes returned by *p*'s Application, +via `ResponseCheckTx`, +to successive calls to `RequestCheckTx` occurring while the Application is at height *h* +and having transaction *tx* as parameter. +*CheckTxCodestx,p,h* is a set since *p*'s Application may +return different result codes during height *h*. +If *CheckTxCodestx,p,h* is a singleton set, i.e. the Application always returned +the same result code in `ResponseCheckTx` while at height *h*, +we define *CheckTxCodetx,p,h* as the singleton value of *CheckTxCodestx,p,h*. +If *CheckTxCodestx,p,h* is not a singleton set, *CheckTxCodetx,p,h* is undefined. +Let predicate *OK(CheckTxCodetx,p,h)* denote whether *CheckTxCodetx,p,h* is `SUCCESS`. + +- Requirement 13 [`CheckTx`, eventual non-oscillation]: For any transaction *tx*, + there exists a boolean value *b*, + and a height *hstable* such that, + for any correct process *p*, + *CheckTxCodetx,p,h* is defined, and + *OK(CheckTxCodetx,p,h) = b* + for any height *h ≥ hstable*. + +Requirement 13 ensures that +a transaction will eventually stop oscillating between `CheckTx` success and failure +if it stays in *p's* mempool for long enough. +This condition on the Application's behavior allows the mempool to ensure that +a transaction will leave the mempool of all full nodes, +either because it is expunged everywhere due to failing `CheckTx` calls, +or because it stays valid long enough to be gossipped, proposed and decided. +Although Requirement 13 defines a global *hstable*, application developers +can consider such stabilization height as local to process *p* (*hp,stable*), +without loss for generality. +In contrast, the value of *b* MUST be the same across all processes. + +## Managing the Application state and related topics + +### Connection State + +CometBFT maintains four concurrent ABCI++ connections, namely +[Consensus Connection](#consensus-connection), +[Mempool Connection](#mempool-connection), +[Info/Query Connection](#infoquery-connection), and +[Snapshot Connection](#snapshot-connection). +It is common for an application to maintain a distinct copy of +the state for each connection, which are synchronized upon `Commit` calls. + +#### Concurrency + +In principle, each of the four ABCI++ connections operates concurrently with one +another. This means applications need to ensure access to state is +thread safe. Both the +[default in-process ABCI client](https://github.com/cometbft/cometbft/blob/v0.38.x/abci/client/local_client.go#L13) +and the +[default Go ABCI server](https://github.com/cometbft/cometbft/blob/v0.38.x/abci/server/socket_server.go#L20) +use a global lock to guard the handling of events across all connections, so they are not +concurrent at all. This means whether your app is compiled in-process with +CometBFT using the `NewLocalClient`, or run out-of-process using the `SocketServer`, +ABCI messages from all connections are received in sequence, one at a +time. + +The existence of this global mutex means Go application developers can get thread safety for application state by routing all reads and writes through the ABCI system. Thus it may be unsafe to expose application state directly to an RPC interface, and unless explicit measures are taken, all queries should be routed through the ABCI Query method. + +#### FinalizeBlock + +When the consensus algorithm decides on a block, CometBFT uses `FinalizeBlock` to send the +decided block's data to the Application, which uses it to transition its state, but MUST NOT persist it; +persisting MUST be done during `Commit`. + +The Application must remember the latest height from which it +has run a successful `Commit` so that it can tell CometBFT where to +pick up from when it recovers from a crash. See information on the Handshake +[here](#crash-recovery). + +#### Commit + +The Application should persist its state during `Commit`, before returning from it. + +Before invoking `Commit`, CometBFT locks the mempool and flushes the mempool connection. This ensures that +no new messages +will be received on the mempool connection during this processing step, providing an opportunity to safely +update all four +connection states to the latest committed state at the same time. + +When `Commit` returns, CometBFT unlocks the mempool. + +WARNING: if the ABCI app logic processing the `Commit` message sends a +`/broadcast_tx_sync` or `/broadcast_tx` and waits for the response +before proceeding, it will deadlock. Executing `broadcast_tx` calls +involves acquiring the mempool lock that CometBFT holds during the `Commit` call. +Synchronous mempool-related calls must be avoided as part of the sequential logic of the +`Commit` function. + +#### Candidate States + +CometBFT calls `PrepareProposal` when it is about to send a proposed block to the network. +Likewise, CometBFT calls `ProcessProposal` upon reception of a proposed block from the +network. The proposed block's data +that is disclosed to the Application by these two methods is the following: + +- the transaction list +- the `LastCommit` referring to the previous block +- the block header's hash (except in `PrepareProposal`, where it is not known yet) +- list of validators that misbehaved +- the block's timestamp +- `NextValidatorsHash` +- Proposer address + +The Application may decide to *immediately* execute the given block (i.e., upon `PrepareProposal` +or `ProcessProposal`). There are two main reasons why the Application may want to do this: + +- *Avoiding invalid transactions in blocks*. + In order to be sure that the block does not contain *any* invalid transaction, there may be + no way other than fully executing the transactions in the block as though it was the *decided* + block. +- *Quick `FinalizeBlock` execution*. + Upon reception of the decided block via `FinalizeBlock`, if that same block was executed + upon `PrepareProposal` or `ProcessProposal` and the resulting state was kept in memory, the + Application can simply apply that state (faster) to the main state, rather than reexecuting + the decided block (slower). + +`PrepareProposal`/`ProcessProposal` can be called many times for a given height. Moreover, +it is not possible to accurately predict which of the blocks proposed in a height will be decided, +being delivered to the Application in that height's `FinalizeBlock`. +Therefore, the state resulting from executing a proposed block, denoted a *candidate state*, should +be kept in memory as a possible final state for that height. When `FinalizeBlock` is called, the Application should +check if the decided block corresponds to one of its candidate states; if so, it will apply it as +its *ExecuteTxState* (see [Consensus Connection](#consensus-connection) below), +which will be persisted during the upcoming `Commit` call. + +Under adverse conditions (e.g., network instability), the consensus algorithm might take many rounds. +In this case, potentially many proposed blocks will be disclosed to the Application for a given height. +By the nature of Tendermint consensus algorithm, currently adopted in CometBFT, the number of proposed blocks received by the Application +for a particular height cannot be bound, so Application developers must act with care and use mechanisms +to bound memory usage. As a general rule, the Application should be ready to discard candidate states +before `FinalizeBlock`, even if one of them might end up corresponding to the +decided block and thus have to be reexecuted upon `FinalizeBlock`. + +### [States and ABCI++ Connections](#states-and-abci-connections) + +#### Consensus Connection + +The Consensus Connection should maintain an *ExecuteTxState* — the working state +for block execution. It should be updated by the call to `FinalizeBlock` +during block execution and committed to disk as the "latest +committed state" during `Commit`. Execution of a proposed block (via `PrepareProposal`/`ProcessProposal`) +**must not** update the *ExecuteTxState*, but rather be kept as a separate candidate state until `FinalizeBlock` +confirms which of the candidate states (if any) can be used to update *ExecuteTxState*. + +#### Mempool Connection + +The mempool Connection maintains *CheckTxState*. CometBFT sequentially processes an incoming +transaction (via RPC from client or P2P from the gossip layer) against *CheckTxState*. +If the processing does not return any error, the transaction is accepted into the mempool +and CometBFT starts gossipping it. +*CheckTxState* should be reset to the latest committed state +at the end of every `Commit`. + +During the execution of a consensus instance, the *CheckTxState* may be updated concurrently with the +*ExecuteTxState*, as messages may be sent concurrently on the Consensus and Mempool connections. +At the end of the consensus instance, as described above, CometBFT locks the mempool and flushes +the mempool connection before calling `Commit`. This ensures that all pending `CheckTx` calls are +responded to and no new ones can begin. + +After the `Commit` call returns, while still holding the mempool lock, `CheckTx` is run again on all +transactions that remain in the node's local mempool after filtering those included in the block. +Parameter `Type` in `RequestCheckTx` +indicates whether an incoming transaction is new (`CheckTxType_New`), or a +recheck (`CheckTxType_Recheck`). + +Finally, after re-checking transactions in the mempool, CometBFT will unlock +the mempool connection. New transactions are once again able to be processed through `CheckTx`. + +Note that `CheckTx` is just a weak filter to keep invalid transactions out of the mempool and, +ultimately, ouf of the blockchain. +Since the transaction cannot be guaranteed to be checked against the exact same state as it +will be executed as part of a (potential) decided block, `CheckTx` shouldn't check *everything* +that affects the transaction's validity, in particular those checks whose validity may depend on +transaction ordering. `CheckTx` is weak because a Byzantine node need not care about `CheckTx`; +it can propose a block full of invalid transactions if it wants. The mechanism ABCI++ has +in place for dealing with such behavior is `ProcessProposal`. + +##### Replay Protection + +It is possible for old transactions to be sent again to the Application. This is typically +undesirable for all transactions, except for a generally small subset of them which are idempotent. + +The mempool has a mechanism to prevent duplicated transactions from being processed. +This mechanism is nevertheless best-effort (currently based on the indexer) +and does not provide any guarantee of non duplication. +It is thus up to the Application to implement an application-specific +replay protection mechanism with strong guarantees as part of the logic in `CheckTx`. + +#### Info/Query Connection + +The Info (or Query) Connection should maintain a `QueryState`. This connection has two +purposes: 1) having the application answer the queries CometBFT receives from users +(see section [Query](#query)), +and 2) synchronizing CometBFT and the Application at start up time (see +[Crash Recovery](#crash-recovery)) +or after state sync (see [State Sync](#state-sync)). + +`QueryState` is a read-only copy of *ExecuteTxState* as it was after the last +`Commit`, i.e. +after the full block has been processed and the state committed to disk. + +#### Snapshot Connection + +The Snapshot Connection is used to serve state sync snapshots for other nodes +and/or restore state sync snapshots to a local node being bootstrapped. +Snapshot management is optional: an Application may choose not to implement it. + +For more information, see Section [State Sync](#state-sync). + +### Transaction Results + +The Application is expected to return a list of +[`ExecTxResult`](./abci%2B%2B_methods.md#exectxresult) in +[`ResponseFinalizeBlock`](./abci%2B%2B_methods.md#finalizeblock). The list of transaction +results MUST respect the same order as the list of transactions delivered via +[`RequestFinalizeBlock`](./abci%2B%2B_methods.md#finalizeblock). +This section discusses the fields inside this structure, along with the fields in +[`ResponseCheckTx`](./abci%2B%2B_methods.md#checktx), +whose semantics are similar. + +The `Info` and `Log` fields are +non-deterministic values for debugging/convenience purposes. CometBFT logs them but they +are otherwise ignored. + +#### Gas + +Ethereum introduced the notion of *gas* as an abstract representation of the +cost of the resources consumed by nodes when processing a transaction. Every operation in the +Ethereum Virtual Machine uses some amount of gas. +Gas has a market-variable price based on which miners can accept or reject to execute a +particular operation. + +Users propose a maximum amount of gas for their transaction; if the transaction uses less, they get +the difference credited back. CometBFT adopts a similar abstraction, +though uses it only optionally and weakly, allowing applications to define +their own sense of the cost of execution. + +In CometBFT, the [ConsensusParams.Block.MaxGas](#consensus-parameters) limits the amount of +total gas that can be used by all transactions in a block. +The default value is `-1`, which means the block gas limit is not enforced, or that the concept of +gas is meaningless. + +Responses contain a `GasWanted` and `GasUsed` field. The former is the maximum +amount of gas the sender of a transaction is willing to use, and the latter is how much it actually +used. Applications should enforce that `GasUsed <= GasWanted` — i.e. transaction execution +or validation should fail before it can use more resources than it requested. + +When `MaxGas > -1`, CometBFT enforces the following rules: + +- `GasWanted <= MaxGas` for every transaction in the mempool +- `(sum of GasWanted in a block) <= MaxGas` when proposing a block + +If `MaxGas == -1`, no rules about gas are enforced. + +In v0.34.x and earlier versions, CometBFT does not enforce anything about Gas in consensus, +only in the mempool. +This means it does not guarantee that committed blocks satisfy these rules. +It is the application's responsibility to return non-zero response codes when gas limits are exceeded +when executing the transactions of a block. +Since the introduction of `PrepareProposal` and `ProcessProposal` in v.0.37.x, it is now possible +for the Application to enforce that all blocks proposed (and voted for) in consensus — and thus all +blocks decided — respect the `MaxGas` limits described above. + +Since the Application should enforce that `GasUsed <= GasWanted` when executing a transaction, and +it can use `PrepareProposal` and `ProcessProposal` to enforce that `(sum of GasWanted in a block) <= MaxGas` +in all proposed or prevoted blocks, +we have: + +- `(sum of GasUsed in a block) <= MaxGas` for every block + +The `GasUsed` field is ignored by CometBFT. + +#### Specifics of `ResponseCheckTx` + +If `Code != 0`, it will be rejected from the mempool and hence +not broadcasted to other peers and not included in a proposal block. + +`Data` contains the result of the `CheckTx` transaction execution, if any. It does not need to be +deterministic since, given a transaction, nodes' Applications +might have a different *CheckTxState* values when they receive it and check their validity +via `CheckTx`. +CometBFT ignores this value in `ResponseCheckTx`. + +From v0.34.x on, there is a `Priority` field in `ResponseCheckTx` that can be +used to explicitly prioritize transactions in the mempool for inclusion in a block +proposal. + +#### Specifics of `ExecTxResult` + +`FinalizeBlock` is the workhorse of the blockchain. CometBFT delivers the decided block, +including the list of all its transactions synchronously to the Application. +The block delivered (and thus the transaction order) is the same at all correct nodes as guaranteed +by the Agreement property of consensus. + +The `Data` field in `ExecTxResult` contains an array of bytes with the transaction result. +It must be deterministic (i.e., the same value must be returned at all nodes), but it can contain arbitrary +data. Likewise, the value of `Code` must be deterministic. +If `Code != 0`, the transaction will be marked invalid, +though it is still included in the block. Invalid transactions are not indexed, as they are +considered analogous to those that failed `CheckTx`. + +Both the `Code` and `Data` are included in a structure that is hashed into the +`LastResultsHash` of the block header in the next height. + +`Events` include any events for the execution, which CometBFT will use to index +the transaction by. This allows transactions to be queried according to what +events took place during their execution. + +### Updating the Validator Set + +The application may set the validator set during +[`InitChain`](./abci%2B%2B_methods.md#initchain), and may update it during +[`FinalizeBlock`](./abci%2B%2B_methods.md#finalizeblock). In both cases, a structure of type +[`ValidatorUpdate`](./abci%2B%2B_methods.md#validatorupdate) is returned. + +The `InitChain` method, used to initialize the Application, can return a list of validators. +If the list is empty, CometBFT will use the validators loaded from the genesis +file. +If the list returned by `InitChain` is not empty, CometBFT will use its contents as the validator set. +This way the application can set the initial validator set for the +blockchain. + +Applications must ensure that a single set of validator updates does not contain duplicates, i.e. +a given public key can only appear once within a given update. If an update includes +duplicates, the block execution will fail irrecoverably. + +Structure `ValidatorUpdate` contains a public key, which is used to identify the validator: +The public key currently supports three types: + +- `ed25519` +- `secp256k1` +- `sr25519` + +Structure `ValidatorUpdate` also contains an `ìnt64` field denoting the validator's new power. +Applications must ensure that +`ValidatorUpdate` structures abide by the following rules: + +- power must be non-negative +- if power is set to 0, the validator must be in the validator set; it will be removed from the set +- if power is greater than 0: + - if the validator is not in the validator set, it will be added to the + set with the given power + - if the validator is in the validator set, its power will be adjusted to the given power +- the total power of the new validator set must not exceed `MaxTotalVotingPower`, where + `MaxTotalVotingPower = MaxInt64 / 8` + +Note the updates returned after processing the block at height `H` will only take effect +at block `H+2` (see Section [Methods](./abci%2B%2B_methods.md)). + +### Consensus Parameters + +`ConsensusParams` are global parameters that apply to all validators in a blockchain. +They enforce certain limits in the blockchain, like the maximum size +of blocks, amount of gas used in a block, and the maximum acceptable age of +evidence. They can be set in +[`InitChain`](./abci%2B%2B_methods.md#initchain), and updated in +[`FinalizeBlock`](./abci%2B%2B_methods.md#finalizeblock). +These parameters are deterministically set and/or updated by the Application, so +all full nodes have the same value at a given height. + +#### List of Parameters + +These are the current consensus parameters (as of v0.38.x): + +1. [ABCIParams.VoteExtensionsEnableHeight](#abciparamsvoteextensionsenableheight) +2. [BlockParams.MaxBytes](#blockparamsmaxbytes) +3. [BlockParams.MaxGas](#blockparamsmaxgas) +4. [EvidenceParams.MaxAgeDuration](#evidenceparamsmaxageduration) +5. [EvidenceParams.MaxAgeNumBlocks](#evidenceparamsmaxagenumblocks) +6. [EvidenceParams.MaxBytes](#evidenceparamsmaxbytes) +7. [ValidatorParams.PubKeyTypes](#validatorparamspubkeytypes) +8. [VersionParams.App](#versionparamsapp) + +##### ABCIParams.VoteExtensionsEnableHeight + +This parameter is either 0 or a positive height at which vote extensions +become mandatory. If the value is zero (which is the default), vote +extensions are not expected. Otherwise, at all heights greater than the +configured height `H` vote extensions must be present (even if empty). +When the configured height `H` is reached, `PrepareProposal` will not +include vote extensions yet, but `ExtendVote` and `VerifyVoteExtension` will +be called. Then, when reaching height `H+1`, `PrepareProposal` will +include the vote extensions from height `H`. For all heights after `H` + +- vote extensions cannot be disabled, +- they are mandatory: all precommit messages sent MUST have an extension + attached. Nevertheless, the application MAY provide 0-length + extensions. + +Must always be set to a future height, 0, or the same height that was previously set. +Once the chain's height reaches the value set, it cannot be changed to a different value. + +##### BlockParams.MaxBytes + +The maximum size of a complete Protobuf encoded block. +This is enforced by the consensus algorithm. + +This implies a maximum transaction size that is `MaxBytes`, less the expected size of +the header, the validator set, and any included evidence in the block. + +The Application should be aware that honest validators *may* produce and +broadcast blocks with up to the configured `MaxBytes` size. +As a result, the consensus +[timeout parameters](../../docs/core/configuration.md#consensus-timeouts-explained) +adopted by nodes should be configured so as to account for the worst-case +latency for the delivery of a full block with `MaxBytes` size to all validators. + +If the Application wants full control over the size of blocks, +it can do so by enforcing a byte limit set up at the Application level. +This Application-internal limit is used by `PrepareProposal` to bound the total size +of transactions it returns, and by `ProcessProposal` to reject any received block +whose total transaction size is bigger than the enforced limit. +In such case, the Application MAY set `MaxBytes` to -1. + +If the Application sets value -1, consensus will: + +- consider that the actual value to enforce is 100 MB +- will provide *all* transactions in the mempool in calls to `PrepareProposal` + +Must have `MaxBytes == -1` OR `0 < MaxBytes <= 100 MB`. + +> Bear in mind that the default value for the `BlockParams.MaxBytes` consensus +> parameter accepts as valid blocks with size up to 21 MB. +> If the Application's use case does not need blocks of that size, +> or if the impact (specially on bandwidth consumption and block latency) +> of propagating blocks of that size was not evaluated, +> it is strongly recommended to wind down this default value. + +##### BlockParams.MaxGas + +The maximum of the sum of `GasWanted` that will be allowed in a proposed block. +This is *not* enforced by the consensus algorithm. +It is left to the Application to enforce (ie. if transactions are included past the +limit, they should return non-zero codes). It is used by CometBFT to limit the +transactions included in a proposed block. + +Must have `MaxGas >= -1`. +If `MaxGas == -1`, no limit is enforced. + +##### EvidenceParams.MaxAgeDuration + +This is the maximum age of evidence in time units. +This is enforced by the consensus algorithm. + +If a block includes evidence older than this (AND the evidence was created more +than `MaxAgeNumBlocks` ago), the block will be rejected (validators won't vote +for it). + +Must have `MaxAgeDuration > 0`. + +##### EvidenceParams.MaxAgeNumBlocks + +This is the maximum age of evidence in blocks. +This is enforced by the consensus algorithm. + +If a block includes evidence older than this (AND the evidence was created more +than `MaxAgeDuration` ago), the block will be rejected (validators won't vote +for it). + +Must have `MaxAgeNumBlocks > 0`. + +##### EvidenceParams.MaxBytes + +This is the maximum size of total evidence in bytes that can be committed to a +single block. It should fall comfortably under the max block bytes. + +Its value must not exceed the size of +a block minus its overhead ( ~ `BlockParams.MaxBytes`). + +Must have `MaxBytes > 0`. + +##### ValidatorParams.PubKeyTypes + +The parameter restricts the type of keys validators can use. The parameter uses ABCI pubkey naming, not Amino names. + +##### VersionParams.App + +This is the version of the ABCI application. + +#### Updating Consensus Parameters + +The application may set the `ConsensusParams` during +[`InitChain`](./abci%2B%2B_methods.md#initchain), +and update them during +[`FinalizeBlock`](./abci%2B%2B_methods.md#finalizeblock). +If the `ConsensusParams` is empty, it will be ignored. Each field +that is not empty will be applied in full. For instance, if updating the +`Block.MaxBytes`, applications must also set the other `Block` fields (like +`Block.MaxGas`), even if they are unchanged, as they will otherwise cause the +value to be updated to the default. + +##### `InitChain` + +`ResponseInitChain` includes a `ConsensusParams` parameter. +If `ConsensusParams` is `nil`, CometBFT will use the params loaded in the genesis +file. If `ConsensusParams` is not `nil`, CometBFT will use it. +This way the application can determine the initial consensus parameters for the +blockchain. + +##### `FinalizeBlock`, `PrepareProposal`/`ProcessProposal` + +`ResponseFinalizeBlock` accepts a `ConsensusParams` parameter. +If `ConsensusParams` is `nil`, CometBFT will do nothing. +If `ConsensusParams` is not `nil`, CometBFT will use it. +This way the application can update the consensus parameters over time. + +The updates returned in block `H` will take effect right away for block +`H+1`. + +### `Query` + +`Query` is a generic method with lots of flexibility to enable diverse sets +of queries on application state. CometBFT makes use of `Query` to filter new peers +based on ID and IP, and exposes `Query` to the user over RPC. + +Note that calls to `Query` are not replicated across nodes, but rather query the +local node's state - hence they may return stale reads. For reads that require +consensus, use a transaction. + +The most important use of `Query` is to return Merkle proofs of the application state at some height +that can be used for efficient application-specific light-clients. + +Note CometBFT has technically no requirements from the `Query` +message for normal operation - that is, the ABCI app developer need not implement +Query functionality if they do not wish to. + +#### Query Proofs + +The CometBFT block header includes a number of hashes, each providing an +anchor for some type of proof about the blockchain. The `ValidatorsHash` enables +quick verification of the validator set, the `DataHash` gives quick +verification of the transactions included in the block. + +The `AppHash` is unique in that it is application specific, and allows for +application-specific Merkle proofs about the state of the application. +While some applications keep all relevant state in the transactions themselves +(like Bitcoin and its UTXOs), others maintain a separated state that is +computed deterministically *from* transactions, but is not contained directly in +the transactions themselves (like Ethereum contracts and accounts). +For such applications, the `AppHash` provides a much more efficient way to verify light-client proofs. + +ABCI applications can take advantage of more efficient light-client proofs for +their state as follows: + +- return the Merkle root of the deterministic application state in + `ResponseFinalizeBlock.Data`. This Merkle root will be included as the `AppHash` in the next block. +- return efficient Merkle proofs about that application state in `ResponseQuery.Proof` + that can be verified using the `AppHash` of the corresponding block. + +For instance, this allows an application's light-client to verify proofs of +absence in the application state, something which is much less efficient to do using the block hash. + +Some applications (eg. Ethereum, Cosmos-SDK) have multiple "levels" of Merkle trees, +where the leaves of one tree are the root hashes of others. To support this, and +the general variability in Merkle proofs, the `ResponseQuery.Proof` has some minimal structure: + +```protobuf +message ProofOps { + repeated ProofOp ops = 1 +} + +message ProofOp { + string type = 1; + bytes key = 2; + bytes data = 3; +} +``` + +Each `ProofOp` contains a proof for a single key in a single Merkle tree, of the specified `type`. +This allows ABCI to support many different kinds of Merkle trees, encoding +formats, and proofs (eg. of presence and absence) just by varying the `type`. +The `data` contains the actual encoded proof, encoded according to the `type`. +When verifying the full proof, the root hash for one ProofOp is the value being +verified for the next ProofOp in the list. The root hash of the final ProofOp in +the list should match the `AppHash` being verified against. + +#### Peer Filtering + +When CometBFT connects to a peer, it sends two queries to the ABCI application +using the following paths, with no additional data: + +- `/p2p/filter/addr/`, where `` denote the IP address and + the port of the connection +- `p2p/filter/id/`, where `` is the peer node ID (ie. the + pubkey.Address() for the peer's PubKey) + +If either of these queries return a non-zero ABCI code, CometBFT will refuse +to connect to the peer. + +#### Paths + +Queries are directed at paths, and may optionally include additional data. + +The expectation is for there to be some number of high level paths +differentiating concerns, like `/p2p`, `/store`, and `/app`. Currently, +CometBFT only uses `/p2p`, for filtering peers. For more advanced use, see the +implementation of +[Query in the Cosmos-SDK](https://github.com/cosmos/cosmos-sdk/blob/e2037f7696fed4fdd4bc076f9e7053fe8178a881/baseapp/abci.go#L557-L565). + +### Crash Recovery + +CometBFT and the application are expected to crash together and there should not +exist a scenario where the application has persisted state of a height greater than the +latest height persisted by CometBFT. + +In practice, persisting the state of a height consists of three steps, the last of which +is the call to the application's `Commit` method, the only place where the application is expected to +persist/commit its state. +On startup (upon recovery), CometBFT calls the `Info` method on the Info Connection to get the latest +committed state of the app. The app MUST return information consistent with the +last block for which it successfully completed `Commit`. + +The three steps performed before the state of a height is considered persisted are: + +- The block is stored by CometBFT in the blockstore +- CometBFT has stored the state returned by the application through `FinalizeBlockResponse` +- The application has committed its state within `Commit`. + +The following diagram depicts the order in which these events happen, and the corresponding +ABCI functions that are called and executed by CometBFT and the application: + + +``` +APP: Execute block Persist application state + / return ResultFinalizeBlock / + / / +Event: ------------- block_stored ------------ / ------------ state_stored --------------- / ----- app_persisted_state + | / | / | +CometBFT: Decide --- Persist block -- Call FinalizeBlock - Persist results ---------- Call Commit -- + on in the (txResults, validator + Block block store updates...) + +``` + +As these three steps are not atomic, we observe different cases based on which steps have been executed +before the crash occurred +(we assume that at least `block_stored` has been executed, otherwise, there is no state persisted, +and the operations for this height are repeated entirely): + +- `block_stored`: we replay `FinalizeBlock` and the steps afterwards. +- `block_stored` and `state_stored`: As the app did not persist its state within `Commit`, we need to re-execute + `FinalizeBlock` to retrieve the results and compare them to the state stored by CometBFT within `state_stored`. + The expected case is that the states will match, otherwise CometBFT panics. +- `block_stored`, `state_stored`, `app_persisted_state`: we move on to the next height. + +Based on the sequence of these events, CometBFT will panic if any of the steps in the sequence happen out of order, +that is if: + +- The application has persisted a block at a height higher than the blocked saved during `state_stored`. +- The `block_stored` step persisted a block at a height smaller than the `state_stored` +- And the difference between the heights of the blocks persisted by `state_stored` and `block_stored` is more +than 1 (this corresponds to a scenario where we stored two blocks in the block store but never persisted the state of the first +block, which should never happen). + +A special case is when a crash happens before the first block is committed - that is, after calling +`InitChain`. In that case, the application's state should still be at height 0 and thus `InitChain` +will be called again. + + +### State Sync + +A new node joining the network can simply join consensus at the genesis height and replay all +historical blocks until it is caught up. However, for large chains this can take a significant +amount of time, often on the order of days or weeks. + +State sync is an alternative mechanism for bootstrapping a new node, where it fetches a snapshot +of the state machine at a given height and restores it. Depending on the application, this can +be several orders of magnitude faster than replaying blocks. + +Note that state sync does not currently backfill historical blocks, so the node will have a +truncated block history - users are advised to consider the broader network implications of this in +terms of block availability and auditability. This functionality may be added in the future. + +For details on the specific ABCI calls and types, see the +[methods](abci%2B%2B_methods.md) section. + +#### Taking Snapshots + +Applications that want to support state syncing must take state snapshots at regular intervals. How +this is accomplished is entirely up to the application. A snapshot consists of some metadata and +a set of binary chunks in an arbitrary format: + +- `Height (uint64)`: The height at which the snapshot is taken. It must be taken after the given + height has been committed, and must not contain data from any later heights. + +- `Format (uint32)`: An arbitrary snapshot format identifier. This can be used to version snapshot + formats, e.g. to switch from Protobuf to MessagePack for serialization. The application can use + this when restoring to choose whether to accept or reject a snapshot. + +- `Chunks (uint32)`: The number of chunks in the snapshot. Each chunk contains arbitrary binary + data, and should be less than 16 MB; 10 MB is a good starting point. + +- `Hash ([]byte)`: An arbitrary hash of the snapshot. This is used to check whether a snapshot is + the same across nodes when downloading chunks. + +- `Metadata ([]byte)`: Arbitrary snapshot metadata, e.g. chunk hashes for verification or any other + necessary info. + +For a snapshot to be considered the same across nodes, all of these fields must be identical. When +sent across the network, snapshot metadata messages are limited to 4 MB. + +When a new node is running state sync and discovering snapshots, CometBFT will query an existing +application via the ABCI `ListSnapshots` method to discover available snapshots, and load binary +snapshot chunks via `LoadSnapshotChunk`. The application is free to choose how to implement this +and which formats to use, but must provide the following guarantees: + +- **Consistent:** A snapshot must be taken at a single isolated height, unaffected by + concurrent writes. This can be accomplished by using a data store that supports ACID + transactions with snapshot isolation. + +- **Asynchronous:** Taking a snapshot can be time-consuming, so it must not halt chain progress, + for example by running in a separate thread. + +- **Deterministic:** A snapshot taken at the same height in the same format must be identical + (at the byte level) across nodes, including all metadata. This ensures good availability of + chunks, and that they fit together across nodes. + +A very basic approach might be to use a datastore with MVCC transactions (such as RocksDB), +start a transaction immediately after block commit, and spawn a new thread which is passed the +transaction handle. This thread can then export all data items, serialize them using e.g. +Protobuf, hash the byte stream, split it into chunks, and store the chunks in the file system +along with some metadata - all while the blockchain is applying new blocks in parallel. + +A more advanced approach might include incremental verification of individual chunks against the +chain app hash, parallel or batched exports, compression, and so on. + +Old snapshots should be removed after some time - generally only the last two snapshots are needed +(to prevent the last one from being removed while a node is restoring it). + +#### Bootstrapping a Node + +An empty node can be state synced by setting the configuration option `statesync.enabled = +true`. The node also needs the chain genesis file for basic chain info, and configuration for +light client verification of the restored snapshot: a set of CometBFT RPC servers, and a +trusted header hash and corresponding height from a trusted source, via the `statesync` +configuration section. + +Once started, the node will connect to the P2P network and begin discovering snapshots. These +will be offered to the local application via the `OfferSnapshot` ABCI method. Once a snapshot +is accepted CometBFT will fetch and apply the snapshot chunks. After all chunks have been +successfully applied, CometBFT verifies the app's `AppHash` against the chain using the light +client, then switches the node to normal consensus operation. + +##### Snapshot Discovery + +When the empty node joins the P2P network, it asks all peers to report snapshots via the +`ListSnapshots` ABCI call (limited to 10 per node). After some time, the node picks the most +suitable snapshot (generally prioritized by height, format, and number of peers), and offers it +to the application via `OfferSnapshot`. The application can choose a number of responses, +including accepting or rejecting it, rejecting the offered format, rejecting the peer who sent +it, and so on. CometBFT will keep discovering and offering snapshots until one is accepted or +the application aborts. + +##### Snapshot Restoration + +Once a snapshot has been accepted via `OfferSnapshot`, CometBFT begins downloading chunks from +any peers that have the same snapshot (i.e. that have identical metadata fields). Chunks are +spooled in a temporary directory, and then given to the application in sequential order via +`ApplySnapshotChunk` until all chunks have been accepted. + +The method for restoring snapshot chunks is entirely up to the application. + +During restoration, the application can respond to `ApplySnapshotChunk` with instructions for how +to continue. This will typically be to accept the chunk and await the next one, but it can also +ask for chunks to be refetched (either the current one or any number of previous ones), P2P peers +to be banned, snapshots to be rejected or retried, and a number of other responses - see the ABCI +reference for details. + +If CometBFT fails to fetch a chunk after some time, it will reject the snapshot and try a +different one via `OfferSnapshot` - the application can choose whether it wants to support +restarting restoration, or simply abort with an error. + +##### Snapshot Verification + +Once all chunks have been accepted, CometBFT issues an `Info` ABCI call to retrieve the +`LastBlockAppHash`. This is compared with the trusted app hash from the chain, retrieved and +verified using the light client. CometBFT also checks that `LastBlockHeight` corresponds to the +height of the snapshot. + +This verification ensures that an application is valid before joining the network. However, the +snapshot restoration may take a long time to complete, so applications may want to employ additional +verification during the restore to detect failures early. This might e.g. include incremental +verification of each chunk against the app hash (using bundled Merkle proofs), checksums to +protect against data corruption by the disk or network, and so on. However, it is important to +note that the only trusted information available is the app hash, and all other snapshot metadata +can be spoofed by adversaries. + +Apps may also want to consider state sync denial-of-service vectors, where adversaries provide +invalid or harmful snapshots to prevent nodes from joining the network. The application can +counteract this by asking CometBFT to ban peers. As a last resort, node operators can use +P2P configuration options to whitelist a set of trusted peers that can provide valid snapshots. + +##### Transition to Consensus + +Once the snapshots have all been restored, CometBFT gathers additional information necessary for +bootstrapping the node (e.g. chain ID, consensus parameters, validator sets, and block headers) +from the genesis file and light client RPC servers. It also calls `Info` to verify the following: + +- that the app hash from the snapshot it has delivered to the Application matches the apphash + stored in the next height's block + +- that the version that the Application returns in `ResponseInfo` matches the version in the + current height's block header + +Once the state machine has been restored and CometBFT has gathered this additional +information, it transitions to consensus. As of ABCI 2.0, CometBFT ensures the necessary conditions +to switch are met [RFC-100](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/rfc/rfc-100-abci-vote-extension-propag.md#base-implementation-persist-and-propagate-extended-commit-history). +From the application's point of view, these operations are transparent, unless the application has just upgraded to ABCI 2.0. +In that case, the application needs to be properly configured and aware of certain constraints in terms of when +to provide vote extensions. More details can be found in the section below. + +Once a node switches to consensus, it operates like any other node, apart from having a truncated block history at the height of the restored snapshot. + +## Application configuration required to switch to ABCI 2.0 + +Introducing vote extensions requires changes to the configuration of the application. + +First of all, switching to a version of CometBFT with vote extensions, requires a coordinated upgrade. +For a detailed description on the upgrade path, please refer to the corresponding +[section](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/rfc/rfc-100-abci-vote-extension-propag.md#upgrade-path) in RFC-100. + +There is a newly introduced [**consensus parameter**](./abci%2B%2B_app_requirements.md#abciparamsvoteextensionsenableheight): `VoteExtensionsEnableHeight`. +This parameter represents the height at which vote extensions are +required for consensus to proceed, with 0 being the default value (no vote extensions). +A chain can enable vote extensions either: + +- at genesis by setting `VoteExtensionsEnableHeight` to be equal, e.g., to the `InitialHeight` +- or via the application logic by changing the `ConsensusParam` to configure the +`VoteExtensionsEnableHeight`. + +Once the (coordinated) upgrade to ABCI 2.0 has taken place, at height *hu*, +the value of `VoteExtensionsEnableHeight` MAY be set to some height, *he*, +which MUST be higher than the current height of the chain. Thus the earliest value for + *he* is *hu* + 1. + +Once a node reaches the configured height, +for all heights *h ≥ he*, the consensus algorithm will +reject as invalid any precommit messages that do not have signed vote extension data. +If the application requires it, a 0-length vote extension is allowed, but it MUST be signed +and present in the precommit message. +Likewise, for all heights *h < he*, any precommit messages that *do* have vote extensions +will also be rejected as malformed. +Height *he* is somewhat special, as calls to `PrepareProposal` MUST NOT +have vote extension data, but all precommit votes in that height MUST carry a vote extension, +even if the extension is `nil`. +Height *he + 1* is the first height for which `PrepareProposal` MUST have vote +extension data and all precommit votes in that height MUST have a vote extension. + +Corollary, [CometBFT will decide](./abci%2B%2B_comet_expected_behavior.md#handling-upgrades-to-abci-20) which data to store, and require for successful operations, based on the current height +of the chain. diff --git a/spec/abci/abci++_basic_concepts.md b/spec/abci/abci++_basic_concepts.md new file mode 100644 index 0000000..3910435 --- /dev/null +++ b/spec/abci/abci++_basic_concepts.md @@ -0,0 +1,436 @@ +--- +order: 1 +title: Overview and basic concepts +--- + +## Outline + +- [Overview and basic concepts](#overview-and-basic-concepts) + - [ABCI++ vs. ABCI](#abci-vs-abci) + - [Methods overview](#methods-overview) + - [Consensus/block execution methods](#consensusblock-execution-methods) + - [Mempool methods](#mempool-methods) + - [Info methods](#info-methods) + - [State-sync methods](#state-sync-methods) + - [Other methods](#other-methods) + - [Proposal timeout](#proposal-timeout) + - [Deterministic State-Machine Replication](#deterministic-state-machine-replication) + - [Events](#events) + - [Evidence](#evidence) + - [Errors](#errors) + - [`CheckTx`](#checktx) + - [`ExecTxResult` (as part of `FinalizeBlock`)](#exectxresult-as-part-of-finalizeblock) + - [`Query`](#query) + +# Overview and basic concepts + +## ABCI 2.0 vs. ABCI {#abci-vs-abci} + +[↑ Back to Outline](#outline) + +The Application's main role is to execute blocks decided (a.k.a. finalized) by consensus. The +decided blocks are the consensus's main output to the (replicated) Application. With ABCI, the +application only interacts with consensus at *decision* time. This restricted mode of interaction +prevents numerous features for the Application, including many scalability improvements that are +now better understood than when ABCI was first written. For example, many ideas proposed to improve +scalability can be boiled down to "make the block proposers do work, so the network does not have +to". This includes optimizations such as transaction level signature aggregation, state transition +proofs, etc. Furthermore, many new security properties cannot be achieved in the current paradigm, +as the Application cannot require validators to do more than executing the transactions contained in +finalized blocks. This includes features such as threshold cryptography, and guaranteed IBC +connection attempts. + +ABCI 2.0 addresses these limitations by allowing the application to intervene at three key places of +consensus execution: (a) at the moment a new proposal is to be created, (b) at the moment a +proposal is to be validated, and (c) at the moment a (precommit) vote is sent/received. +The new interface allows block proposers to perform application-dependent +work in a block through the `PrepareProposal` method (a); and validators to perform application-dependent work +and checks in a proposed block through the `ProcessProposal` method (b); and applications to require their validators +to do more than just validate blocks through the `ExtendVote` and `VerifyVoteExtensions` methods (c). + +Furthermore, ABCI 2.0 coalesces {`BeginBlock`, [`DeliverTx`], `EndBlock`} into `FinalizeBlock`, as a +simplified, efficient way to deliver a decided block to the Application. + +## Methods overview + +[↑ Back to Outline](#outline) + +Methods can be classified into four categories: *consensus*, *mempool*, *info*, and *state-sync*. + +### Consensus/block execution methods + +The first time a new blockchain is started, CometBFT calls `InitChain`. From then on, method +`FinalizeBlock` is executed upon the decision of each block, resulting in an updated Application +state. During the execution of an instance of consensus, which decides the block for a given +height, and before method `FinalizeBlock` is called, methods `PrepareProposal`, `ProcessProposal`, +`ExtendVote`, and `VerifyVoteExtension` may be called several times. See +[CometBFT's expected behavior](./abci++_comet_expected_behavior.md) for details on the possible +call sequences of these methods. + +- [**InitChain:**](./abci++_methods.md#initchain) This method initializes the blockchain. + CometBFT calls it once upon genesis. + +- [**PrepareProposal:**](./abci++_methods.md#prepareproposal) It allows the block + proposer to perform application-dependent work in a block before proposing it. + This enables, for instance, batch optimizations to a block, which has been empirically + demonstrated to be a key component for improved performance. Method `PrepareProposal` is called + every time CometBFT is about to broadcast a Proposal message and *validValue* is `nil`. + CometBFT gathers outstanding transactions from the + mempool, generates a block header, and uses them to create a block to propose. Then, it calls + `RequestPrepareProposal` with the newly created proposal, called *raw proposal*. The Application + can make changes to the raw proposal, such as reordering, adding and removing transactions, before returning the + (potentially) modified proposal, called *prepared proposal* in the `ResponsePrepareProposal`. + The logic modifying the raw proposal MAY be non-deterministic. + +- [**ProcessProposal:**](./abci++_methods.md#processproposal) It allows a validator to + perform application-dependent work in a proposed block. This enables features such as immediate + block execution, and allows the Application to reject invalid blocks. + + CometBFT calls it when it receives a proposal and *validValue* is `nil`. + The Application cannot modify the proposal at this point but can reject it if + invalid. If that is the case, the consensus algorithm will prevote `nil` on the proposal, which has + strong liveness implications for CometBFT. As a general rule, the Application + SHOULD accept a prepared proposal passed via `ProcessProposal`, even if a part of + the proposal is invalid (e.g., an invalid transaction); the Application can + ignore the invalid part of the prepared proposal at block execution time. + The logic in `ProcessProposal` MUST be deterministic. + +- [**ExtendVote:**](./abci++_methods.md#extendvote) It allows applications to let their + validators do more than just validate within consensus. `ExtendVote` allows applications to + include non-deterministic data, opaque to the consensus algorithm, to precommit messages (the final round of + voting). The data, called *vote extension*, will be broadcast and received together with the + vote it is extending, and will be made available to the Application in the next height, + in the rounds where the local process is the proposer. + CometBFT calls `ExtendVote` when the consensus algorithm is about to send a non-`nil` precommit message. + If the Application does not have vote extension information to provide at that time, it returns + a 0-length byte array as its vote extension. + The logic in `ExtendVote` MAY be non-deterministic. + +- [**VerifyVoteExtension:**](./abci++_methods.md#verifyvoteextension) It allows + validators to validate the vote extension data attached to a precommit message. If the validation + fails, the whole precommit message will be deemed invalid and ignored by consensus algorithm. + This has a negative impact on liveness, i.e., if vote extensions repeatedly cannot be + verified by correct validators, the consensus algorithm may not be able to finalize a block even if sufficiently + many (+2/3) validators send precommit votes for that block. Thus, `VerifyVoteExtension` + should be implemented with special care. + As a general rule, an Application that detects an invalid vote extension SHOULD + accept it in `ResponseVerifyVoteExtension` and ignore it in its own logic. CometBFT calls it when + a process receives a precommit message with a (possibly empty) vote extension, for the current height. It is not called for precommit votes received after the height is concluded but while waiting to accumulate more precommit votes. + The logic in `VerifyVoteExtension` MUST be deterministic. + +- [**FinalizeBlock:**](./abci++_methods.md#finalizeblock) It delivers a decided block to the + Application. The Application must execute the transactions in the block deterministically and + update its state accordingly. Cryptographic commitments to the block and transaction results, + returned via the corresponding parameters in `ResponseFinalizeBlock`, are included in the header + of the next block. CometBFT calls it when a new block is decided. + When calling `FinalizeBlock` with a block, the consensus algorithm run by CometBFT guarantees + that at least one non-byzantine validator has run `ProcessProposal` on that block. + +- [**Commit:**](./abci++_methods.md#commit) Instructs the Application to persist its + state. It is a fundamental part of CometBFT's crash-recovery mechanism that ensures the + synchronization between CometBFT and the Application upon recovery. CometBFT calls it just after + having persisted the data returned by calls to `ResponseFinalizeBlock`. The Application can now discard + any state or data except the one resulting from executing the transactions in the decided block. + +### Mempool methods + +- [**CheckTx:**](./abci++_methods.md#checktx) This method allows the Application to validate + transactions. Validation can be stateless (e.g., checking signatures ) or stateful + (e.g., account balances). The type of validation performed is up to the application. If a + transaction passes the validation, then CometBFT adds it to the mempool; otherwise the + transaction is discarded. + CometBFT calls it when it receives a new transaction either coming from an external + user (e.g., a client) or another node. Furthermore, CometBFT can be configured to call + re-`CheckTx` on all outstanding transactions in the mempool after calling `Commit` for a block. + +### Info methods + +- [**Info:**](./abci++_methods.md#info) Used to sync CometBFT with the Application during a + handshake that happens upon recovery, or on startup when state-sync is used. + +- [**Query:**](./abci++_methods.md#query) This method can be used to query the Application for + information about the application state. + +### State-sync methods + +State sync allows new nodes to rapidly bootstrap by discovering, fetching, and applying +state machine (application) snapshots instead of replaying historical blocks. For more details, see the +[state sync documentation](../p2p/legacy-docs/messages/state-sync.md). + +New nodes discover and request snapshots from other nodes in the P2P network. +A CometBFT node that receives a request for snapshots from a peer will call +`ListSnapshots` on its Application. The Application returns the list of locally available +snapshots. +Note that the list does not contain the actual snapshots but metadata about them: height at which +the snapshot was taken, application-specific verification data and more (see +[snapshot data type](./abci++_methods.md#snapshot) for more details). After receiving a +list of available snapshots from a peer, the new node can offer any of the snapshots in the list to +its local Application via the `OfferSnapshot` method. The Application can check at this point the +validity of the snapshot metadata. + +Snapshots may be quite large and are thus broken into smaller "chunks" that can be +assembled into the whole snapshot. Once the Application accepts a snapshot and +begins restoring it, CometBFT will fetch snapshot "chunks" from existing nodes. +The node providing "chunks" will fetch them from its local Application using +the `LoadSnapshotChunk` method. + +As the new node receives "chunks" it will apply them sequentially to the local +application with `ApplySnapshotChunk`. When all chunks have been applied, the +Application's `AppHash` is retrieved via an `Info` query. +To ensure that the sync proceeded correctly, CometBFT compares the local Application's `AppHash` +to the `AppHash` stored on the blockchain (verified via +[light client verification](../light-client/verification/README.md)). + +In summary: + +- [**ListSnapshots:**](./abci++_methods.md#listsnapshots) Used by nodes to discover available + snapshots on peers. + +- [**OfferSnapshot:**](./abci++_methods.md#offersnapshot) When a node receives a snapshot from a + peer, CometBFT uses this method to offer the snapshot to the Application. + +- [**LoadSnapshotChunk:**](./abci++_methods.md#loadsnapshotchunk) Used by CometBFT to retrieve + snapshot chunks from the Application to send to peers. + +- [**ApplySnapshotChunk:**](./abci++_methods.md#applysnapshotchunk) Used by CometBFT to hand + snapshot chunks to the Application. + +### Other methods + +Additionally, there is a [**Flush**](./abci++_methods.md#flush) method that is called on every connection, +and an [**Echo**](./abci++_methods.md#echo) method that is used for debugging. + +More details on managing state across connections can be found in the section on +[Managing Application State](./abci%2B%2B_app_requirements.md#managing-the-application-state-and-related-topics). + +## Proposal timeout + +`PrepareProposal` stands on the consensus algorithm critical path, +i.e., CometBFT cannot make progress while this method is being executed. +Hence, if the Application takes a long time preparing a proposal, +the default value of *TimeoutPropose* might not be sufficient +to accommodate the method's execution and validator nodes might time out and prevote `nil`. +The proposal, in this case, will probably be rejected and a new round will be necessary. + +Timeouts are automatically increased for each new round of a height and, if the execution of `PrepareProposal` is bound, eventually *TimeoutPropose* will be long enough to accommodate the execution of `PrepareProposal`. +However, relying on this self adaptation could lead to performance degradation and, therefore, +operators are suggested to adjust the initial value of *TimeoutPropose* in CometBFT's configuration file, +in order to suit the needs of the particular application being deployed. + +This is particularly important if applications implement *immediate execution*. +To implement this technique, proposers need to execute the block being proposed within `PrepareProposal`, which could take longer than *TimeoutPropose*. + +## Deterministic State-Machine Replication + +[↑ Back to Outline](#outline) + +ABCI applications must implement deterministic finite-state machines to be +securely replicated by the CometBFT consensus engine. This means block execution +must be strictly deterministic: given the same +ordered set of transactions, all nodes will compute identical responses, for all +successive `FinalizeBlock` calls. This is critical because the +responses are included in the header of the next block, either via a Merkle root +or directly, so all nodes must agree on exactly what they are. + +For this reason, it is recommended that application state is not exposed to any +external user or process except via the ABCI connections to a consensus engine +like CometBFT. The Application must only change its state based on input +from block execution (`FinalizeBlock` calls), and not through +any other kind of request. This is the only way to ensure all nodes see the same +transactions and compute the same results. + +Applications that implement immediate execution (execute the blocks +that are about to be proposed, in `PrepareProposal`, or that require validation, in `ProcessProposal`) produce a new candidate state before a block is decided. +The state changes caused by processing those +proposed blocks must never replace the previous state until `FinalizeBlock` confirms +that the proposed block was decided and `Commit` is invoked for it. + +The same is true to Applications that quickly accept blocks and execute the +blocks optimistically in parallel with the remaining consensus steps to save +time during `FinalizeBlock`; they must only apply state changes in `Commit`. + +Additionally, vote extensions or the validation thereof (via `ExtendVote` or +`VerifyVoteExtension`) must *never* have side effects on the current state. +They can only be used when their data is provided in a `RequestPrepareProposal` call but, again, +without side effects to the app state. + +If there is some non-determinism in the state machine, consensus will eventually +fail as nodes disagree over the correct values for the block header. The +non-determinism must be fixed and the nodes restarted. + +Sources of non-determinism in applications may include: + +- Hardware failures + - Cosmic rays, overheating, etc. +- Node-dependent state + - Random numbers + - Time +- Underspecification + - Library version changes + - Race conditions + - Floating point numbers + - JSON or protobuf serialization + - Iterating through hash-tables/maps/dictionaries +- External Sources + - Filesystem + - Network calls (eg. some external REST API service) + +See [#56](https://github.com/tendermint/abci/issues/56) for the original discussion. + +Note that some methods (e.g., `Query` and `FinalizeBlock`) may return +non-deterministic data in the form of `Info`, `Log` and/or `Events` fields. The +`Log` is intended for the literal output from the Application's logger, while +the `Info` is any additional info that should be returned. These fields are not +included in block header computations, so we don't need agreement on them. See +each field's description on whether it must be deterministic or not. + +## Events + +[↑ Back to Outline](#outline) + +Method `FinalizeBlock` includes an `events` field at the top level in its +`Response*`, and one `events` field per transaction included in the block. +Applications may respond to this ABCI 2.0 method with an event list for each executed +transaction, and a general event list for the block itself. +Events allow applications to associate metadata with transactions and blocks. +Events returned via `FinalizeBlock` do not impact the consensus algorithm in any way +and instead exist to power subscriptions and queries of CometBFT state. + +An `Event` contains a `type` and a list of `EventAttributes`, which are key-value +string pairs denoting metadata about what happened during the method's (or transaction's) +execution. `Event` values can be used to index transactions and blocks according to what +happened during their execution. + +Each event has a `type` which is meant to categorize the event for a particular +`Response*` or `Tx`. A `Response*` or `Tx` may contain multiple events with duplicate +`type` values, where each distinct entry is meant to categorize attributes for a +particular event. Every key and value in an event's attributes must be UTF-8 +encoded strings along with the event type itself. + +```protobuf +message Event { + string type = 1; + repeated EventAttribute attributes = 2; +} +``` + +The attributes of an `Event` consist of a `key`, a `value`, and an `index` +flag. The index flag notifies the CometBFT indexer to index the attribute. + +The `type` and `attributes` fields are non-deterministic and may vary across +different nodes in the network. + +```protobuf +message EventAttribute { + string key = 1; + string value = 2; + bool index = 3; // nondeterministic +} +``` + +Example: + +```go + abci.ResponseFinalizeBlock{ + // ... + Events: []abci.Event{ + { + Type: "validator.provisions", + Attributes: []abci.EventAttribute{ + abci.EventAttribute{Key: "address", Value: "...", Index: true}, + abci.EventAttribute{Key: "amount", Value: "...", Index: true}, + abci.EventAttribute{Key: "balance", Value: "...", Index: true}, + }, + }, + { + Type: "validator.provisions", + Attributes: []abci.EventAttribute{ + abci.EventAttribute{Key: "address", Value: "...", Index: true}, + abci.EventAttribute{Key: "amount", Value: "...", Index: false}, + abci.EventAttribute{Key: "balance", Value: "...", Index: false}, + }, + }, + { + Type: "validator.slashed", + Attributes: []abci.EventAttribute{ + abci.EventAttribute{Key: "address", Value: "...", Index: false}, + abci.EventAttribute{Key: "amount", Value: "...", Index: true}, + abci.EventAttribute{Key: "reason", Value: "...", Index: true}, + }, + }, + // ... + }, +} +``` + +## Evidence + +[↑ Back to Outline](#outline) + +CometBFT's security model relies on the use of evidences of misbehavior. An evidence is an +irrefutable proof of malicious behavior by a network participant. It is the responsibility of +CometBFT to detect such malicious behavior. When malicious behavior is detected, CometBFT +will gossip evidences of misbehavior to other nodes and commit the evidences to +the chain once they are verified by a subset of validators. These evidences will then be +passed on to the Application through ABCI++. It is the responsibility of the +Application to handle evidence of misbehavior and exercise punishment. + +There are two forms of evidence: Duplicate Vote and Light Client Attack. More +information can be found in either [data structures](../core/data_structures.md) +or [accountability](../light-client/accountability/). + +EvidenceType has the following protobuf format: + +```protobuf +enum EvidenceType { + UNKNOWN = 0; + DUPLICATE_VOTE = 1; + LIGHT_CLIENT_ATTACK = 2; +} +``` + +## Errors + +[↑ Back to Outline](#outline) + +The `Query` and `CheckTx` methods include a `Code` field in their `Response*`. +Field `Code` is meant to contain an application-specific response code. +A response code of `0` indicates no error. Any other response code +indicates to CometBFT that an error occurred. + +These methods also return a `Codespace` string to CometBFT. This field is +used to disambiguate `Code` values returned by different domains of the +Application. The `Codespace` is a namespace for the `Code`. + +Methods `Echo`, `Info`, `Commit` and `InitChain` do not return errors. +An error in any of these methods represents a critical issue that CometBFT +has no reasonable way to handle. If there is an error in one +of these methods, the Application must crash to ensure that the error is safely +handled by an operator. + +Method `FinalizeBlock` is a special case. It contains a number of +`Code` and `Codespace` fields as part of type `ExecTxResult`. Each of +these codes reports errors related to the transaction it is attached to. +However, `FinalizeBlock` does not return errors at the top level, so the +same considerations on critical issues made for `Echo`, `Info`, and +`InitChain` also apply here. + +The handling of non-zero response codes by CometBFT is described below. + +### `CheckTx` + +When CometBFT receives a `ResponseCheckTx` with a non-zero `Code`, the associated +transaction will not be added to CometBFT's mempool or it will be removed if +it is already included. + +### `ExecTxResult` (as part of `FinalizeBlock`) + +The `ExecTxResult` type delivers transaction results from the Application to CometBFT. When +CometBFT receives a `ResponseFinalizeBlock` containing an `ExecTxResult` with a non-zero `Code`, +the response code is logged. Past `Code` values can be queried by clients. As the transaction was +part of a decided block, the `Code` does not influence consensus. + +### `Query` + +When CometBFT receives a `ResponseQuery` with a non-zero `Code`, this code is +returned directly to the client that initiated the query. diff --git a/spec/abci/abci++_client_server.md b/spec/abci/abci++_client_server.md new file mode 100644 index 0000000..f6e872b --- /dev/null +++ b/spec/abci/abci++_client_server.md @@ -0,0 +1,94 @@ +--- +order: 5 +title: Client and Server +--- + +# Client and Server + +This section is for those looking to implement their own ABCI Server, perhaps in +a new programming language. + +You are expected to have read all previous sections of ABCI++ specification, namely +[Basic Concepts](./abci%2B%2B_basic_concepts.md), +[Methods](./abci%2B%2B_methods.md), +[Application Requirements](./abci%2B%2B_app_requirements.md), and +[Expected Behavior](./abci%2B%2B_comet_expected_behavior.md). + +## Message Protocol and Synchrony + +The message protocol consists of pairs of requests and responses defined in the +[protobuf file](https://github.com/cometbft/cometbft/blob/v0.38.x/proto/tendermint/abci/types.proto). + +Some messages have no fields, while others may include byte-arrays, strings, integers, +or custom protobuf types. + +For more details on protobuf, see the [documentation](https://developers.google.com/protocol-buffers/docs/overview). + + +## Server Implementations + +To use ABCI in your programming language of choice, there must be an ABCI +server in that language. CometBFT supports four implementations of the ABCI server: + +- in CometBFT's repository: + - In-process + - ABCI-socket + - GRPC +- [tendermint-rs](https://github.com/informalsystems/tendermint-rs) +- [tower-abci](https://github.com/penumbra-zone/tower-abci) + +The implementations in CometBFT's repository can be tested using `abci-cli` by setting +the `--abci` flag appropriately. + +See examples, in various stages of maintenance, in +[Go](https://github.com/cometbft/cometbft/tree/master/abci/server), +[JavaScript](https://github.com/tendermint/js-abci), +[C++](https://github.com/mdyring/cpp-tmsp), and +[Java](https://github.com/jTendermint/jabci). + +### In Process + +The simplest implementation uses function calls in Golang. +This means ABCI applications written in Golang can be linked with CometBFT and run as a single binary. + +### GRPC + +If you are not using Golang, +but [GRPC](https://grpc.io/) is available in your language, this is the easiest approach, +though it will have significant performance overhead. + +Please check GRPC's documentation to know to set up the Application as an +ABCI GRPC server. + +### Socket + +The CometBFT Socket Protocol is an asynchronous, raw socket server protocol which provides ordered +message passing over Unix or TCP sockets. Messages are serialized using Protobuf3 and length-prefixed +with an [unsigned varint](https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints) + +If gRPC is not available in your language, or you require higher performance, or +otherwise enjoy programming, you may implement your own ABCI server using the +CometBFT Socket Protocol. The first step is still to auto-generate the +relevant data types and codec in your language using `protoc`, and then you need to +ensure you handle the unsigned `varint`-based message length encoding scheme +when reading and writing messages to the socket. + +Note that our length prefixing scheme does not apply to gRPC. + +Also note that your ABCI server must be able to handle multiple connections, +as CometBFT uses four connections. + +## Client + +There are currently two use-cases for an ABCI client. One is testing +tools that allow ABCI requests to be sent to the actual application via +command line. An example of this is `abci-cli`, which accepts CLI commands +to send corresponding ABCI requests. +The other is a consensus engine, such as CometBFT, +which makes ABCI requests to the application as prescribed by the consensus +algorithm used. diff --git a/spec/abci/abci++_comet_expected_behavior.md b/spec/abci/abci++_comet_expected_behavior.md new file mode 100644 index 0000000..b6eb7ca --- /dev/null +++ b/spec/abci/abci++_comet_expected_behavior.md @@ -0,0 +1,282 @@ +--- +order: 4 +title: CometBFT's expected behavior +--- + +# CometBFT's expected behavior + +## Valid method call sequences + +This section describes what the Application can expect from CometBFT. + +The Tendermint consensus algorithm, currently adopted in CometBFT, is designed to protect safety under any network conditions, as long as +less than 1/3 of validators' voting power is byzantine. Most of the time, though, the network will behave +synchronously, no process will fall behind, and there will be no byzantine process. The following describes +what will happen during a block height _h_ in these frequent, benign conditions: + +* Consensus will decide in round 0, for height _h_; +* `PrepareProposal` will be called exactly once at the proposer process of round 0, height _h_; +* `ProcessProposal` will be called exactly once at all processes, and + will return _accept_ in its `Response*`; +* `ExtendVote` will be called exactly once at all processes; +* `VerifyVoteExtension` will be called exactly _n-1_ times at each validator process, where _n_ is + the number of validators, and will always return _accept_ in its `Response*`; +* `FinalizeBlock` will be called exactly once at all processes, conveying the same prepared + block that all calls to `PrepareProposal` and `ProcessProposal` had previously reported for + height _h_; and +* `Commit` will finally be called exactly once at all processes at the end of height _h_. + +However, the Application logic must be ready to cope with any possible run of the consensus algorithm for a given +height, including bad periods (byzantine proposers, network being asynchronous). +In these cases, the sequence of calls to ABCI++ methods may not be so straightforward, but +the Application should still be able to handle them, e.g., without crashing. +The purpose of this section is to define what these sequences look like in a precise way. + +As mentioned in the [Basic Concepts](./abci%2B%2B_basic_concepts.md) section, CometBFT +acts as a client of ABCI++ and the Application acts as a server. Thus, it is up to CometBFT to +determine when and in which order the different ABCI++ methods will be called. A well-written +Application design should consider _any_ of these possible sequences. + +The following grammar, written in case-sensitive Augmented Backus–Naur form (ABNF, specified +in [IETF rfc7405](https://datatracker.ietf.org/doc/html/rfc7405)), specifies all possible +sequences of calls to ABCI++, taken by a **correct process**, across all heights from the genesis block, +including recovery runs, from the point of view of the Application. + +```abnf +start = clean-start / recovery + +clean-start = init-chain [state-sync] consensus-exec +state-sync = *state-sync-attempt success-sync info +state-sync-attempt = offer-snapshot *apply-chunk +success-sync = offer-snapshot 1*apply-chunk + +recovery = info consensus-exec + +consensus-exec = (inf)consensus-height +consensus-height = *consensus-round decide commit +consensus-round = proposer / non-proposer + +proposer = *got-vote [prepare-proposal [process-proposal]] [extend] +extend = *got-vote extend-vote *got-vote +non-proposer = *got-vote [process-proposal] [extend] + +init-chain = %s"" +offer-snapshot = %s"" +apply-chunk = %s"" +info = %s"" +prepare-proposal = %s"" +process-proposal = %s"" +extend-vote = %s"" +got-vote = %s"" +decide = %s"" +commit = %s"" +``` + +We have kept some ABCI methods out of the grammar, in order to keep it as clear and concise as possible. +A common reason for keeping all these methods out is that they all can be called at any point in a sequence defined +by the grammar above. Other reasons depend on the method in question: + +* `Echo` and `Flush` are only used for debugging purposes. Further, their handling by the Application should be trivial. +* `CheckTx` is detached from the main method call sequence that drives block execution. +* `Query` provides read-only access to the current Application state, so handling it should also be independent from + block execution. +* Similarly, `ListSnapshots` and `LoadSnapshotChunk` provide read-only access to the Application's previously created + snapshots (if any), and help populate the parameters of `OfferSnapshot` and `ApplySnapshotChunk` at a process performing + state-sync while bootstrapping. Unlike `ListSnapshots` and `LoadSnapshotChunk`, both `OfferSnapshot` + and `ApplySnapshotChunk` _are_ included in the grammar. + +Finally, method `Info` is a special case. The method's purpose is three-fold, it can be used + +1. as part of handling an RPC call from an external client, +2. as a handshake between CometBFT and the Application upon recovery to check whether any blocks need + to be replayed, and +3. at the end of _state-sync_ to verify that the correct state has been reached. + +We have left `Info`'s first purpose out of the grammar for the same reasons as all the others: it can happen +at any time, and has nothing to do with the block execution sequence. The second and third purposes, on the other +hand, are present in the grammar. + +Let us now examine the grammar line by line, providing further details. + +* When a process starts, it may do so for the first time or after a crash (it is recovering). + +>```abnf +>start = clean-start / recovery +>``` + +* If the process is starting from scratch, CometBFT first calls `InitChain`, then it may optionally + start a _state-sync_ mechanism to catch up with other processes. Finally, it enters normal + consensus execution. + +>```abnf +>clean-start = init-chain [state-sync] consensus-exec +>``` + +* In _state-sync_ mode, CometBFT makes one or more attempts at synchronizing the Application's state. + At the beginning of each attempt, it offers the Application a snapshot found at another process. + If the Application accepts the snapshot, a sequence of calls to `ApplySnapshotChunk` method follow + to provide the Application with all the snapshots needed, in order to reconstruct the state locally. + A successful attempt must provide at least one chunk via `ApplySnapshotChunk`. + At the end of a successful attempt, CometBFT calls `Info` to make sure the reconstructed state's + _AppHash_ matches the one in the block header at the corresponding height. Note that the state + of the application does not contain vote extensions itself. The application can rely on + [CometBFT to ensure](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/rfc/rfc-100-abci-vote-extension-propag.md#base-implementation-persist-and-propagate-extended-commit-history) + the node has all the relevant data to proceed with the execution beyond this point. + +>```abnf +>state-sync = *state-sync-attempt success-sync info +>state-sync-attempt = offer-snapshot *apply-chunk +>success-sync = offer-snapshot 1*apply-chunk +>``` + +* In recovery mode, CometBFT first calls `Info` to know from which height it needs to replay decisions + to the Application. After this, CometBFT enters consensus execution, first in replay mode and then + in normal mode. + +>```abnf +>recovery = info consensus-exec +>``` + +* The non-terminal `consensus-exec` is a key point in this grammar. It is an infinite sequence of + consensus heights. The grammar is thus an + [omega-grammar](https://dl.acm.org/doi/10.5555/2361476.2361481), since it produces infinite + sequences of terminals (i.e., the API calls). + +>```abnf +>consensus-exec = (inf)consensus-height +>``` + +* A consensus height consists of zero or more rounds before deciding and executing via a call to + `FinalizeBlock`, followed by a call to `Commit`. In each round, the sequence of method calls + depends on whether the local process is the proposer or not. Note that, if a height contains zero + rounds, this means the process is replaying an already decided value (catch-up mode). + When calling `FinalizeBlock` with a block, the consensus algorithm run by CometBFT guarantees + that at least one non-byzantine validator has run `ProcessProposal` on that block. + + +>```abnf +>consensus-height = *consensus-round decide commit +>consensus-round = proposer / non-proposer +>``` + +* For every round, if the local process is the proposer of the current round, CometBFT calls `PrepareProposal`. + A successful execution of `PrepareProposal` results in a proposal block being (i) signed and (ii) stored + (e.g., in stable storage). + + A crash during this step will direct how the node proceeds the next time it is executed, for the same round, after restarted. + If it crashed before (i), then, during the recovery, `PrepareProposal` will execute as if for the first time. + Following a crash between (i) and (ii) and in (the likely) case `PrepareProposal` produces a different block, + the signing of this block will fail, which means that the new block will not be stored or broadcast. + If the crash happened after (ii), then signing fails but nothing happens to the stored block. + + If a block was stored, it is sent to all validators, including the proposer. + Receiving a proposal block triggers `ProcessProposal` with such a block. + + Then, optionally, the Application is + asked to extend its vote for that round. Calls to `VerifyVoteExtension` can come at any time: the + local process may be slightly late in the current round, or votes may come from a future round + of this height. + +>```abnf +>proposer = *got-vote [prepare-proposal [process-proposal]] [extend] +>extend = *got-vote extend-vote *got-vote +>``` + +* Also for every round, if the local process is _not_ the proposer of the current round, CometBFT + will call `ProcessProposal` at most once. + Under certain conditions, CometBFT may not call `ProcessProposal` in a round; + see [this section](./abci++_example_scenarios.md#scenario-3) for an example. + At most one call to `ExtendVote` may occur only after + `ProcessProposal` is called. A number of calls to `VerifyVoteExtension` can occur in any order + with respect to `ProcessProposal` and `ExtendVote` throughout the round. The reasons are the same + as above, namely, the process running slightly late in the current round, or votes from future + rounds of this height received. + +>```abnf +>non-proposer = *got-vote [process-proposal] [extend] +>``` + +* Finally, the grammar describes all its terminal symbols, which denote the different ABCI++ method calls that + may appear in a sequence. + +>```abnf +>init-chain = %s"" +>offer-snapshot = %s"" +>apply-chunk = %s"" +>info = %s"" +>prepare-proposal = %s"" +>process-proposal = %s"" +>extend-vote = %s"" +>got-vote = %s"" +>decide = %s"" +>commit = %s"" +>``` + +## Adapting existing Applications that use ABCI + +In some cases, an existing Application using the legacy ABCI may need to be adapted to work with ABCI++ +with as minimal changes as possible. In this case, of course, ABCI++ will not provide any advantage with respect +to the existing implementation, but will keep the same guarantees already provided by ABCI. +Here is how ABCI++ methods should be implemented. + +First of all, all the methods that did not change from ABCI 0.17.0 to ABCI 2.0, namely `Echo`, `Flush`, `Info`, `InitChain`, +`Query`, `CheckTx`, `ListSnapshots`, `LoadSnapshotChunk`, `OfferSnapshot`, and `ApplySnapshotChunk`, do not need +to undergo any changes in their implementation. + +As for the new methods: + +* `PrepareProposal` must create a list of [transactions](./abci++_methods.md#prepareproposal) + by copying over the transaction list passed in `RequestPrepareProposal.txs`, in the same order. + + The Application must check whether the size of all transactions exceeds the byte limit + (`RequestPrepareProposal.max_tx_bytes`). If so, the Application must remove transactions at the + end of the list until the total byte size is at or below the limit. +* `ProcessProposal` must set `ResponseProcessProposal.status` to _accept_ and return. +* `ExtendVote` is to set `ResponseExtendVote.extension` to an empty byte array and return. +* `VerifyVoteExtension` must set `ResponseVerifyVoteExtension.accept` to _true_ if the extension is + an empty byte array and _false_ otherwise, then return. +* `FinalizeBlock` is to coalesce the implementation of methods `BeginBlock`, `DeliverTx`, and + `EndBlock`. Legacy applications looking to reuse old code that implemented `DeliverTx` should + wrap the legacy `DeliverTx` logic in a loop that executes one transaction iteration per + transaction in `RequestFinalizeBlock.tx`. + +Finally, `Commit`, which is kept in ABCI++, no longer returns the `AppHash`. It is now up to +`FinalizeBlock` to do so. Thus, a slight refactoring of the old `Commit` implementation will be +needed to move the return of `AppHash` to `FinalizeBlock`. + +## Accommodating for vote extensions + +In a manner transparent to the application, CometBFT ensures the node is provided with all +the data it needs to participate in consensus. + +In the case of recovering from a crash, or joining the network via state sync, CometBFT will make +sure the node acquires the necessary vote extensions before switching to consensus. + +If a node is already in consensus but falls behind, during catch-up, CometBFT will provide the node with +vote extensions from past heights by retrieving the extensions within `ExtendedCommit` for old heights that it had previously stored. + +We realize this is sub-optimal due to the increase in storage needed to store the extensions, we are +working on an optimization of this implementation which should alleviate this concern. +However, the application can use the existing `retain_height` parameter to decide how much +history it wants to keep, just as is done with the block history. The network-wide implications +of the usage of `retain_height` stay the same. +The decision to store +historical commits and potential optimizations, are discussed in detail in [RFC-100](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/rfc/rfc-100-abci-vote-extension-propag.md#current-limitations-and-possible-implementations) + +## Handling upgrades to ABCI 2.0 + +If applications upgrade to ABCI 2.0, CometBFT internally ensures that the [application setup](./abci%2B%2B_app_requirements.md#application-configuration-required-to-switch-to-abci-20) is reflected in its operation. +CometBFT retrieves from the application configuration the value of `VoteExtensionsEnableHeight`( _he_,), +the height at which vote extensions are required for consensus to proceed, and uses it to determine the data it stores and data it sends to a peer that is catching up. + +Namely, upon saving the block for a given height _h_ in the block store at decision time + +* if _h ≥ he_, the corresponding extended commit that was used to decide locally is saved as well +* if _h < he_, there are no changes to the data saved + +In the catch-up mechanism, when a node _f_ realizes that another peer is at height _hp_, which is more than 2 heights behind height _hf_, + +* if _hp ≥ he_, _f_ uses the extended commit to + reconstruct the precommit votes with their corresponding extensions +* if _hp < he_, _f_ uses the canonical commit to reconstruct the precommit votes, + as done for ABCI 1.0 and earlier. diff --git a/spec/abci/abci++_example_scenarios.md b/spec/abci/abci++_example_scenarios.md new file mode 100644 index 0000000..00da2b2 --- /dev/null +++ b/spec/abci/abci++_example_scenarios.md @@ -0,0 +1,164 @@ +--- +order: 6 +title: ABCI++ extra +--- +# Introduction + +In the section [CometBFT's expected behaviour](./abci++_comet_expected_behavior.md#valid-method-call-sequences), +we presented the most common behaviour, usually referred to as the good case. +However, the grammar specified in the same section is more general and covers more scenarios +that an Application designer needs to account for. + +In this section, we give more information about these possible scenarios. We focus on methods +introduced by ABCI++: `PrepareProposal` and `ProcessProposal`. Specifically, we concentrate +on the part of the grammar presented below. + +```abnf +consensus-height = *consensus-round decide commit +consensus-round = proposer / non-proposer + +proposer = [prepare-proposal process-proposal] +non-proposer = [process-proposal] +``` + +We can see from the grammar that we can have several rounds before deciding a block. The reasons +why one round may not be enough are: + +* network asynchrony, and +* a Byzantine process being the proposer. + +If we assume that the consensus algorithm decides on block $X$ in round $r$, in the rounds +$r' <= r$, CometBFT can exhibit any of the following behaviours: + +1. Call `PrepareProposal` and/or `ProcessProposal` for block $X$. +1. Call `PrepareProposal` and/or `ProcessProposal` for block $Y \neq X$. +1. Does not call `PrepareProposal` and/or `ProcessProposal`. + +In the rounds in which the process is the proposer, CometBFT's `PrepareProposal` call is always followed by the +`ProcessProposal` call. The reason is that the process also broadcasts the proposal to itself, which is locally delivered and triggers the `ProcessProposal` call. +The proposal processed by `ProcessProposal` is the same as what was returned by any of the preceding `PrepareProposal` invoked for the same height and round. +While in the absence of restarts there is only one such preceding invocations, if the proposer restarts there could have been one extra invocation to `PrepareProposal` for each restart. + +As the number of rounds the consensus algorithm needs to decide in a given run is a priori unknown, the +application needs to account for any number of rounds, where each round can exhibit any of these three +behaviours. Recall that the application is unaware of the internals of consensus and thus of the rounds. + +# Possible scenarios + +The unknown number of rounds we can have when following the consensus algorithm yields a vast number of +scenarios we can expect. Listing them all is unfeasible. However, here we give several of them and draw the +main conclusions. Specifically, we will show that before block $X$ is decided: + +1. On a correct node, `PrepareProposal` may be called multiple times and for different blocks ([**Scenario 1**](#scenario-1)). +1. On a correct node, `ProcessProposal` may be called multiple times and for different blocks ([**Scenario 2**](#scenario-2)). +1. On a correct node, `PrepareProposal` and `ProcessProposal` for block $X$ may not be called ([**Scenario 3**](#scenario-3)). +1. On a correct node, `PrepareProposal` and `ProcessProposal` may not be called at all ([**Scenario 4**](#scenario-4)). + + +## Basic information + +Each scenario is presented from the perspective of a process $p$. More precisely, we show what happens in +each round's $step$ of the [Tendermint consensus algorithm](https://arxiv.org/pdf/1807.04938.pdf). While in +practice the consensus algorithm works with respect to voting power of the validators, in this document +we refer to number of processes (e.g., $n$, $f+1$, $2f+1$) for simplicity. The legend is below: + +### Round X + +1. **Propose:** Describes what happens while $step_p = propose$. +1. **Prevote:** Describes what happens while $step_p = prevote$. +1. **Precommit:** Describes what happens while $step_p = precommit$. + +## Scenario 1 + +$p$ calls `ProcessProposal` many times with different values. + +### Round 0 + +1. **Propose:** The proposer of this round is a Byzantine process, and it chooses not to send the proposal +message. Therefore, $p$'s $timeoutPropose$ expires, it sends $Prevote$ for $nil$, and it does not call +`ProcessProposal`. All correct processes do the same. +1. **Prevote:** $p$ eventually receives $2f+1$ $Prevote$ messages for $nil$ and starts $timeoutPrevote$. +When $timeoutPrevote$ expires it sends $Precommit$ for $nil$. +1. **Precommit:** $p$ eventually receives $2f+1$ $Precommit$ messages for $nil$ and starts $timeoutPrecommit$. +When it expires, it moves to the next round. + +### Round 1 + +1. **Propose:** A correct process is the proposer in this round. Its $validValue$ is $nil$, and it is free +to generate and propose a new block $Y$. Process $p$ receives this proposal in time, calls `ProcessProposal` +for block $Y$, and broadcasts a $Prevote$ message for it. +1. **Prevote:** Due to network asynchrony less than $2f+1$ processes send $Prevote$ for this block. +Therefore, $p$ does not update $validValue$ in this round. +1. **Precommit:** Since less than $2f+1$ processes send $Prevote$, no correct process will lock on this +block and send $Precommit$ message. As a consequence, $p$ does not decide on $Y$. + +### Round 2 + +1. **Propose:** Same as in [**Round 1**](#round-1), just another correct process is the proposer, and it +proposes another value $Z$. Process $p$ receives the proposal on time, calls `ProcessProposal` for new block +$Z$, and broadcasts a $Prevote$ message for it. +1. **Prevote:** Same as in [**Round 1**](#round-1). +1. **Precommit:** Same as in [**Round 1**](#round-1). + + +Rounds like these can continue until we have a round in which process $p$ updates its $validValue$ or until +we reach round $r$ where process $p$ decides on a block. After that, it will not call `ProcessProposal` +anymore for this height. + +## Scenario 2 + +$p$ calls `PrepareProposal` many times with different values. + +### Round 0 + +1. **Propose:** Process $p$ is the proposer in this round. Its $validValue$ is $nil$, and it is free to +generate and propose new block $Y$. Before proposing, it calls `PrepareProposal` for $Y$. After that, it +broadcasts the proposal, delivers it to itself, calls `ProcessProposal` and broadcasts $Prevote$ for it. +1. **Prevote:** Due to network asynchrony less than $2f+1$ processes receive the proposal on time and send +$Prevote$ for it. Therefore, $p$ does not update $validValue$ in this round. +1. **Precommit:** Since less than $2f+1$ processes send $Prevote$, no correct process will lock on this +block and send non-$nil$ $Precommit$ message. As a consequence, $p$ does not decide on $Y$. + +After this round, we can have multiple rounds like those in [Scenario 1](#scenario-1). The important thing +is that process $p$ should not update its $validValue$. Consequently, when process $p$ reaches the round +when it is again the proposer, it will ask the mempool for the new block again, and the mempool may return a +different block $Z$, and we can have the same round as [Round 0](#round-0-1) just for a different block. As +a result, process $p$ calls `PrepareProposal` again but for a different value. When it reaches round $r$ +some process will propose block $X$ and if $p$ receives $2f+1$ $Precommit$ messages, it will decide on this +value. + + +## Scenario 3 + +$p$ calls `PrepareProposal` and `ProcessProposal` for many values, but decides on a value for which it did +not call `PrepareProposal` or `ProcessProposal`. + +In this scenario, in all rounds before $r$ we can have any round presented in [Scenario 1](#scenario-1) or +[Scenario 2](#scenario-2). What is important is that: + +* no proposer proposed block $X$ or if it did, process $p$, due to asynchrony, did not receive it in time, +so it did not call `ProcessProposal`, and + +* if $p$ was the proposer it proposed some other value $\neq X$. + +### Round $r$ + +1. **Propose:** A correct process is the proposer in this round, and it proposes block $X$. +Due to asynchrony, the proposal message arrives to process $p$ after its $timeoutPropose$ +expires and it sends $Prevote$ for $nil$. Consequently, process $p$ does not call +`ProcessProposal` for block $X$. However, the same proposal arrives at other processes +before their $timeoutPropose$ expires, and they send $Prevote$ for this proposal. +1. **Prevote:** Process $p$ receives $2f+1$ $Prevote$ messages for proposal $X$, updates correspondingly its +$validValue$ and $lockedValue$ and sends $Precommit$ message. All correct processes do the same. +1. **Precommit:** Finally, process $p$ receives $2f+1$ $Precommit$ messages, and decides on block $X$. + + + +## Scenario 4 + +[Scenario 3](#scenario-3) can be translated into a scenario where $p$ does not call `PrepareProposal` and +`ProcessProposal` at all. For this, it is necessary that process $p$ is not the proposer in any of the +rounds $0 <= r' <= r$ and that due to network asynchrony or Byzantine proposer, it does not receive the +proposal before $timeoutPropose$ expires. As a result, it will enter round $r$ without calling +`PrepareProposal` and `ProcessProposal` before it, and as shown in Round $r$ of [Scenario 3](#scenario-3) it +will decide in this round. Again without calling any of these two calls. diff --git a/spec/abci/abci++_methods.md b/spec/abci/abci++_methods.md new file mode 100644 index 0000000..d8c57d8 --- /dev/null +++ b/spec/abci/abci++_methods.md @@ -0,0 +1,911 @@ +--- +order: 2 +title: Methods +--- + +# Methods + +## Methods existing in ABCI + +### Echo + +* **Request**: + * `Message (string)`: A string to echo back +* **Response**: + * `Message (string)`: The input string +* **Usage**: + * Echo a string to test an ABCI client/server implementation + +### Flush + +* **Usage**: + * Signals that messages queued on the client should be flushed to + the server. It is called periodically by the client + implementation to ensure asynchronous requests are actually + sent, and is called immediately to make a synchronous request, + which returns when the Flush response comes back. + +### Info + +* **Request**: + + | Name | Type | Description | Field Number | + |---------------|--------|----------------------------------------|--------------| + | version | string | The CometBFT software semantic version | 1 | + | block_version | uint64 | The CometBFT Block version | 2 | + | p2p_version | uint64 | The CometBFT P2P version | 3 | + | abci_version | string | The CometBFT ABCI semantic version | 4 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |---------------------|--------|-----------------------------------------------------|--------------|---------------| + | data | string | Some arbitrary information | 1 | N/A | + | version | string | The application software semantic version | 2 | N/A | + | app_version | uint64 | The application version | 3 | N/A | + | last_block_height | int64 | Latest height for which the app persisted its state | 4 | N/A | + | last_block_app_hash | bytes | Latest AppHash returned by `FinalizeBlock` | 5 | N/A | + +* **Usage**: + * Return information about the application state. + * Used to sync CometBFT with the application during a handshake + that happens on startup or on recovery. + * The returned `app_version` will be included in the Header of every block. + * CometBFT expects `last_block_app_hash` and `last_block_height` to + be updated and persisted during `Commit`. + +> Note: Semantic version is a reference to [semantic versioning](https://semver.org/). Semantic versions in info will be displayed as X.X.x. + +### InitChain + +* **Request**: + + | Name | Type | Description | Field Number | + |------------------|-------------------------------------------------|-----------------------------------------------------|--------------| + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Genesis time | 1 | + | chain_id | string | ID of the blockchain. | 2 | + | consensus_params | [ConsensusParams](#consensusparams) | Initial consensus-critical parameters. | 3 | + | validators | repeated [ValidatorUpdate](#validatorupdate) | Initial genesis validators, sorted by voting power. | 4 | + | app_state_bytes | bytes | Serialized initial application state. JSON bytes. | 5 | + | initial_height | int64 | Height of the initial block (typically `1`). | 6 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |------------------|----------------------------------------------|--------------------------------------------------|--------------|---------------| + | consensus_params | [ConsensusParams](#consensusparams) | Initial consensus-critical parameters (optional) | 1 | Yes | + | validators | repeated [ValidatorUpdate](#validatorupdate) | Initial validator set (optional). | 2 | Yes | + | app_hash | bytes | Initial application hash. | 3 | Yes | + +* **Usage**: + * Called once upon genesis. + * If `ResponseInitChain.Validators` is empty, the initial validator set will be the `RequestInitChain.Validators` + * If `ResponseInitChain.Validators` is not empty, it will be the initial + validator set (regardless of what is in `RequestInitChain.Validators`). + * This allows the app to decide if it wants to accept the initial validator + set proposed by CometBFT (ie. in the genesis file), or if it wants to use + a different one (perhaps computed based on some application specific + information in the genesis file). + * Both `RequestInitChain.Validators` and `ResponseInitChain.Validators` are [ValidatorUpdate](#validatorupdate) structs. + So, technically, they both are _updating_ the set of validators from the empty set. + +### Query + +* **Request**: + + | Name | Type | Description | Field Number | + |--------|--------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------| + | data | bytes | Request parameters for the application to interpret analogously to a [URI query component](https://www.rfc-editor.org/rfc/rfc3986#section-3.4). Can be used with or in lieu of `path`. | 1 | + | path | string | A request path for the application to interpret analogously to a [URI path component](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) in e.g. routing. Can be used with or in lieu of `data`. Applications MUST interpret "/store" or any path starting with "/store/" as a query by key on the underlying store, in which case a key SHOULD be specified in `data`. Applications SHOULD allow queries over specific types like `/accounts/...` or `/votes/...`. | 2 | + | height | int64 | The block height against which to query (default=0 returns data for the latest committed block). Note that this is the height of the block containing the application's Merkle root hash, which represents the state as it was after committing the block at Height-1. | 3 | + | prove | bool | Return Merkle proof with response if possible. | 4 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |-----------|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|---------------| + | code | uint32 | Response code. | 1 | N/A | + | log | string | The output of the application's logger. | 3 | N/A | + | info | string | Additional information. | 4 | N/A | + | index | int64 | The index of the key in the tree. | 5 | N/A | + | key | bytes | The key of the matching data. | 6 | N/A | + | value | bytes | The value of the matching data. | 7 | N/A | + | proof_ops | [ProofOps](#proofops) | Serialized proof for the value data, if requested, to be verified against the `app_hash` for the given Height. | 8 | N/A | + | height | int64 | The block height from which data was derived. Note that this is the height of the block containing the application's Merkle root hash, which represents the state as it was after committing the block at Height-1 | 9 | N/A | + | codespace | string | Namespace for the `code`. | 10 | N/A | + +* **Usage**: + * Query for data from the application at current or past height. + * Optionally return Merkle proof. + * Merkle proof includes self-describing `type` field to support many types + of Merkle trees and encoding formats. + +### CheckTx + +* **Request**: + + | Name | Type | Description | Field Number | + |------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------| + | tx | bytes | The request transaction bytes | 1 | + | type | CheckTxType | One of `CheckTx_New` or `CheckTx_Recheck`. `CheckTx_New` is the default and means that a full check of the tranasaction is required. `CheckTx_Recheck` types are used when the mempool is initiating a normal recheck of a transaction. | 2 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |------------|---------------------------------------------------|----------------------------------------------------------------------|--------------|---------------| + | code | uint32 | Response code. | 1 | N/A | + | data | bytes | Result bytes, if any. | 2 | N/A | + | log | string | The output of the application's logger. | 3 | N/A | + | info | string | Additional information. | 4 | N/A | + | gas_wanted | int64 | Amount of gas requested for transaction. | 5 | N/A | + | gas_used | int64 | Amount of gas consumed by transaction. | 6 | N/A | + | events | repeated [Event](abci++_basic_concepts.md#events) | Type & Key-Value events for indexing transactions (e.g. by account). | 7 | N/A | + | codespace | string | Namespace for the `code`. | 8 | N/A | + +* **Usage**: + + * Technically optional - not involved in processing blocks. + * Guardian of the mempool: every node runs `CheckTx` before letting a + transaction into its local mempool. + * The transaction may come from an external user or another node + * `CheckTx` validates the transaction against the current state of the application, + for example, checking signatures and account balances, but does not apply any + of the state changes described in the transaction. + * Transactions where `ResponseCheckTx.Code != 0` will be rejected - they will not be broadcast + to other nodes or included in a proposal block. + CometBFT attributes no other value to the response code. + +### Commit + +#### Parameters and Types + +* **Request**: + + Commit signals the application to persist application state. It takes no parameters. + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |---------------|-------|------------------------------------------------------------------------|--------------|---------------| + | retain_height | int64 | Blocks below this height may be removed. Defaults to `0` (retain all). | 3 | No | + +* **Usage**: + + * Signal the Application to persist the application state. + Application is expected to persist its state at the end of this call, before calling `ResponseCommit`. + * Use `ResponseCommit.retain_height` with caution! If all nodes in the network remove historical + blocks then this data is permanently lost, and no new nodes will be able to join the network and + bootstrap, unless state sync is enabled on the chain. Historical blocks may also be required for other purposes, e.g. auditing, replay of + non-persisted heights, light client verification, and so on. + +### ListSnapshots + +* **Request**: + + Empty request asking the application for a list of snapshots. + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |-----------|--------------------------------|--------------------------------|--------------|---------------| + | snapshots | repeated [Snapshot](#snapshot) | List of local state snapshots. | 1 | N/A | + +* **Usage**: + * Used during state sync to discover available snapshots on peers. + * See `Snapshot` data type for details. + +### LoadSnapshotChunk + +* **Request**: + + | Name | Type | Description | Field Number | + |--------|--------|-----------------------------------------------------------------------|--------------| + | height | uint64 | The height of the snapshot the chunk belongs to. | 1 | + | format | uint32 | The application-specific format of the snapshot the chunk belongs to. | 2 | + | chunk | uint32 | The chunk index, starting from `0` for the initial chunk. | 3 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |-------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|---------------| + | chunk | bytes | The binary chunk contents, in an arbitrary format. Chunk messages cannot be larger than 16 MB _including metadata_, so 10 MB is a good starting point. | 1 | N/A | + +* **Usage**: + * Used during state sync to retrieve snapshot chunks from peers. + +### OfferSnapshot + +* **Request**: + + | Name | Type | Description | Field Number | + |----------|-----------------------|--------------------------------------------------------------------------|--------------| + | snapshot | [Snapshot](#snapshot) | The snapshot offered for restoration. | 1 | + | app_hash | bytes | The light client-verified app hash for this height, from the blockchain. | 2 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |--------|-------------------|-----------------------------------|--------------|---------------| + | result | [Result](#result) | The result of the snapshot offer. | 1 | N/A | + +#### Result + +```protobuf + enum Result { + UNKNOWN = 0; // Unknown result, abort all snapshot restoration + ACCEPT = 1; // Snapshot is accepted, start applying chunks. + ABORT = 2; // Abort snapshot restoration, and don't try any other snapshots. + REJECT = 3; // Reject this specific snapshot, try others. + REJECT_FORMAT = 4; // Reject all snapshots with this `format`, try others. + REJECT_SENDER = 5; // Reject all snapshots from all senders of this snapshot, try others. + } +``` + +* **Usage**: + * `OfferSnapshot` is called when bootstrapping a node using state sync. The application may + accept or reject snapshots as appropriate. Upon accepting, CometBFT will retrieve and + apply snapshot chunks via `ApplySnapshotChunk`. The application may also choose to reject a + snapshot in the chunk response, in which case it should be prepared to accept further + `OfferSnapshot` calls. + * Only `AppHash` can be trusted, as it has been verified by the light client. Any other data + can be spoofed by adversaries, so applications should employ additional verification schemes + to avoid denial-of-service attacks. The verified `AppHash` is automatically checked against + the restored application at the end of snapshot restoration. + * For more information, see the `Snapshot` data type or the [state sync section](../p2p/legacy-docs/messages/state-sync.md). + +### ApplySnapshotChunk + +* **Request**: + + | Name | Type | Description | Field Number | + |--------|--------|---------------------------------------------------------------------------|--------------| + | index | uint32 | The chunk index, starting from `0`. CometBFT applies chunks sequentially. | 1 | + | chunk | bytes | The binary chunk contents, as returned by `LoadSnapshotChunk`. | 2 | + | sender | string | The P2P ID of the node who sent this chunk. | 3 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |----------------|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|---------------| + | result | Result (see below) | The result of applying this chunk. | 1 | N/A | + | refetch_chunks | repeated uint32 | Refetch and reapply the given chunks, regardless of `result`. Only the listed chunks will be refetched, and reapplied in sequential order. | 2 | N/A | + | reject_senders | repeated string | Reject the given P2P senders, regardless of `Result`. Any chunks already applied will not be refetched unless explicitly requested, but queued chunks from these senders will be discarded, and new chunks or other snapshots rejected. | 3 | N/A | + +```proto + enum Result { + UNKNOWN = 0; // Unknown result, abort all snapshot restoration + ACCEPT = 1; // The chunk was accepted. + ABORT = 2; // Abort snapshot restoration, and don't try any other snapshots. + RETRY = 3; // Reapply this chunk, combine with `RefetchChunks` and `RejectSenders` as appropriate. + RETRY_SNAPSHOT = 4; // Restart this snapshot from `OfferSnapshot`, reusing chunks unless instructed otherwise. + REJECT_SNAPSHOT = 5; // Reject this snapshot, try a different one. + } +``` + +* **Usage**: + * The application can choose to refetch chunks and/or ban P2P peers as appropriate. CometBFT + will not do this unless instructed by the application. + * The application may want to verify each chunk, e.g. by attaching chunk hashes in + `Snapshot.Metadata` and/or incrementally verifying contents against `AppHash`. + * When all chunks have been accepted, CometBFT will make an ABCI `Info` call to verify that + `LastBlockAppHash` and `LastBlockHeight` matches the expected values, and record the + `AppVersion` in the node state. It then switches to block sync or consensus and joins the + network. + * If CometBFT is unable to retrieve the next chunk after some time (e.g. because no suitable + peers are available), it will reject the snapshot and try a different one via `OfferSnapshot`. + The application should be prepared to reset and accept it or abort as appropriate. + +## New methods introduced in ABCI 2.0 + +### PrepareProposal + +#### Parameters and Types + +* **Request**: + + | Name | Type | Description | Field Number | + |----------------------|-------------------------------------------------|-----------------------------------------------------------------------------------------------|--------------| + | max_tx_bytes | int64 | Currently configured maximum size in bytes taken by the modified transactions. | 1 | + | txs | repeated bytes | Preliminary list of transactions that have been picked as part of the block to propose. | 2 | + | local_last_commit | [ExtendedCommitInfo](#extendedcommitinfo) | Info about the last commit, obtained locally from CometBFT's data structures. | 3 | + | misbehavior | repeated [Misbehavior](#misbehavior) | List of information about validators that misbehaved. | 4 | + | height | int64 | The height of the block that will be proposed. | 5 | + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Timestamp of the block that that will be proposed. | 6 | + | next_validators_hash | bytes | Merkle root of the next validator set. | 7 | + | proposer_address | bytes | [Address](../core/data_structures.md#address) of the validator that is creating the proposal. | 8 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |------|----------------|---------------------------------------------------------------------------------------------|--------------|---------------| + | txs | repeated bytes | Possibly modified list of transactions that have been picked as part of the proposed block. | 2 | No | + +* **Usage**: + * `RequestPrepareProposal`'s parameters `txs`, `misbehavior`, `height`, `time`, + `next_validators_hash`, and `proposer_address` are the same as in `RequestProcessProposal` + and `RequestFinalizeBlock`. + * `RequestPrepareProposal.local_last_commit` is a set of the precommit votes for the previous + height, including the ones that led to the decision of the previous block, + together with their corresponding vote extensions. + * The `height`, `time`, and `proposer_address` values match the values from the header of the + proposed block. + * `RequestPrepareProposal` contains a preliminary set of transactions `txs` that CometBFT + retrieved from the mempool, called _raw proposal_. The Application can modify this + set and return a modified set of transactions via `ResponsePrepareProposal.txs` . + * The Application _can_ modify the raw proposal: it can reorder, remove or add transactions. + Let `tx` be a transaction in `txs` (set of transactions within `RequestPrepareProposal`): + * If the Application considers that `tx` should not be proposed in this block, e.g., + there are other transactions with higher priority, then it should not include it in + `ResponsePrepareProposal.txs`. However, this will not remove `tx` from the mempool. + * If the Application wants to add a new transaction to the proposed block, then the + Application includes it in `ResponsePrepareProposal.txs`. CometBFT will not add + the transaction to the mempool. + * The Application should be aware that removing and adding transactions may compromise + _traceability_. + > Consider the following example: the Application transforms a client-submitted + transaction `t1` into a second transaction `t2`, i.e., the Application asks CometBFT + to remove `t1` from the block and add `t2` to the block. If a client wants to eventually check what + happened to `t1`, it will discover that `t1` is not in a + committed block (assuming a _re-CheckTx_ evicted it from the mempool), getting the wrong idea that `t1` did not make it into a block. Note + that `t2` _will be_ in a committed block, but unless the Application tracks this + information, no component will be aware of it. Thus, if the Application wants + traceability, it is its responsibility's to support it. For instance, the Application + could attach to a transformed transaction a list with the hashes of the transactions it + derives from. + * The Application MAY configure CometBFT to include a list of transactions in `RequestPrepareProposal.txs` + whose total size in bytes exceeds `RequestPrepareProposal.max_tx_bytes`. + If the Application sets `ConsensusParams.Block.MaxBytes` to -1, CometBFT + will include _all_ transactions currently in the mempool in `RequestPrepareProposal.txs`, + which may not fit in `RequestPrepareProposal.max_tx_bytes`. + Therefore, if the size of `RequestPrepareProposal.txs` is greater than + `RequestPrepareProposal.max_tx_bytes`, the Application MUST remove transactions to ensure + that the `RequestPrepareProposal.max_tx_bytes` limit is respected by those transactions + returned in `ResponsePrepareProposal.txs`. + This is specified in [Requirement 2](./abci%2B%2B_app_requirements.md). + * As a result of executing the prepared proposal, the Application may produce block events or transaction events. + The Application must keep those events until a block is decided and then pass them on to CometBFT via + `ResponseFinalizeBlock`. + * CometBFT does NOT provide any additional validity checks (such as checking for duplicate + transactions). + + * If CometBFT fails to validate the `ResponsePrepareProposal`, CometBFT will assume the + Application is faulty and crash. + * The implementation of `PrepareProposal` MAY be non-deterministic. + + +#### When does CometBFT call "PrepareProposal" ? + +When a validator _p_ enters consensus round _r_, height _h_, in which _p_ is the proposer, +and _p_'s _validValue_ is `nil`: + +1. CometBFT collects outstanding transactions from _p_'s mempool + * the transactions will be collected in order of priority + * _p_'s CometBFT creates a block header. +2. _p_'s CometBFT calls `RequestPrepareProposal` with the newly generated block, the local + commit of the previous height (with vote extensions), and any outstanding evidence of + misbehavior. The call is synchronous: CometBFT's execution will block until the Application + returns from the call. +3. The Application uses the information received (transactions, commit info, misbehavior, time) to + (potentially) modify the proposal. + * the Application MAY fully execute the block and produce a candidate state (immediate execution) + * the Application can manipulate transactions: + * leave transactions untouched + * add new transactions (not present initially) to the proposal + * remove transactions from the proposal (but not from the mempool thus effectively _delaying_ them) - the + Application does not include the transaction in `ResponsePrepareProposal.txs`. + * modify transactions (e.g. aggregate them). As explained above, this compromises client traceability, unless + it is implemented at the Application level. + * reorder transactions - the Application reorders transactions in the list + * the Application MAY use the vote extensions in the commit info to modify the proposal, in which case it is suggested + that extensions be validated in the same maner as done in `VerifyVoteExtension`, since extensions of votes included + in the commit info after the minimum of +2/3 had been reached are not verified. +4. The Application includes the transaction list (whether modified or not) in the return parameters + (see the rules in section _Usage_), and returns from the call. +5. _p_ uses the (possibly) modified block as _p_'s proposal in round _r_, height _h_. + +Note that, if _p_ has a non-`nil` _validValue_ in round _r_, height _h_, +the consensus algorithm will use it as proposal and will not call `RequestPrepareProposal`. + +### ProcessProposal + +#### Parameters and Types + +* **Request**: + + | Name | Type | Description | Field Number | + |----------------------|-------------------------------------------------|-------------------------------------------------------------------------------------------|--------------| + | txs | repeated bytes | List of transactions of the proposed block. | 1 | + | proposed_last_commit | [CommitInfo](#commitinfo) | Info about the last commit, obtained from the information in the proposed block. | 2 | + | misbehavior | repeated [Misbehavior](#misbehavior) | List of information about validators that misbehaved. | 3 | + | hash | bytes | The hash of the proposed block. | 4 | + | height | int64 | The height of the proposed block. | 5 | + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Timestamp of the proposed block. | 6 | + | next_validators_hash | bytes | Merkle root of the next validator set. | 7 | + | proposer_address | bytes | [Address](../core/data_structures.md#address) of the validator that created the proposal. | 8 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |--------|-----------------------------------|------------------------------------------------------------------|--------------|---------------| + | status | [ProposalStatus](#proposalstatus) | `enum` that signals if the application finds the proposal valid. | 1 | Yes | + +* **Usage**: + * Contains all information on the proposed block needed to fully execute it. + * The Application may fully execute the block as though it was handling + `RequestFinalizeBlock`. + * However, any resulting state changes must be kept as _candidate state_, + and the Application should be ready to discard it in case another block is decided. + * `RequestProcessProposal` is also called at the proposer of a round. + Normally the call to `RequestProcessProposal` occurs right after the call to `RequestPrepareProposal` and + `RequestProcessProposal` matches the block produced based on `ResponsePrepareProposal` (i.e., + `RequestPrepareProposal.txs` equals `RequestProcessProposal.txs`). + However, no such guarantee is made since, in the presence of failures, `RequestProcessProposal` may match + `ResponsePrepareProposal` from an earlier invocation or `ProcessProposal` may not be invoked at all. + * The height and time values match the values from the header of the proposed block. + * If `ResponseProcessProposal.status` is `REJECT`, consensus assumes the proposal received + is not valid. + * The Application MAY fully execute the block (immediate execution) + * The implementation of `ProcessProposal` MUST be deterministic. Moreover, the value of + `ResponseProcessProposal.status` MUST **exclusively** depend on the parameters passed in + the call to `RequestProcessProposal`, and the last committed Application state + (see [Requirements](./abci++_app_requirements.md) section). + * Moreover, application implementors SHOULD always set `ResponseProcessProposal.status` to `ACCEPT`, + unless they _really_ know what the potential liveness implications of returning `REJECT` are. + +#### When does CometBFT call "ProcessProposal" ? + +When a node _p_ enters consensus round _r_, height _h_, in which _q_ is the proposer (possibly _p_ = _q_): + +1. _p_ sets up timer `ProposeTimeout`. +2. If _p_ is the proposer, _p_ executes steps 1-6 in [PrepareProposal](#prepareproposal). +3. Upon reception of Proposal message (which contains the header) for round _r_, height _h_ from + _q_, _p_ verifies the block header. +4. Upon reception of Proposal message, along with all the block parts, for round _r_, height _h_ + from _q_, _p_ follows the validators' algorithm to check whether it should prevote for the + proposed block, or `nil`. +5. If the validators' consensus algorithm indicates _p_ should prevote non-nil: + 1. CometBFT calls `RequestProcessProposal` with the block. The call is synchronous. + 2. The Application checks/processes the proposed block, which is read-only, and returns + `ACCEPT` or `REJECT` in the `ResponseProcessProposal.status` field. + * The Application, depending on its needs, may call `ResponseProcessProposal` + * either after it has completely processed the block (immediate execution), + * or after doing some basic checks, and process the block asynchronously. In this case the + Application will not be able to reject the block, or force prevote/precommit `nil` + afterwards. + * or immediately, returning `ACCEPT`, if _p_ is not a validator + and the Application does not want non-validating nodes to handle `ProcessProposal` + 3. If _p_ is a validator and the returned value is + * `ACCEPT`: _p_ prevotes on this proposal for round _r_, height _h_. + * `REJECT`: _p_ prevotes `nil`. + * + +### ExtendVote + +#### Parameters and Types + +* **Request**: + + | Name | Type | Description | Field Number | + |----------------------|-------------------------------------------------|-------------------------------------------------------------------------------------------|--------------| + | hash | bytes | The header hash of the proposed block that the vote extension is to refer to. | 1 | + | height | int64 | Height of the proposed block (for sanity check). | 2 | + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Timestamp of the proposed block (that the extension is to refer to). | 3 | + | txs | repeated bytes | List of transactions of the block that the extension is to refer to. | 4 | + | proposed_last_commit | [CommitInfo](#commitinfo) | Info about the last proposed block's last commit. | 5 | + | misbehavior | repeated [Misbehavior](#misbehavior) | List of information about validators that misbehaved contained in the proposed block. | 6 | + | next_validators_hash | bytes | Merkle root of the next validator set contained in the proposed block. | 7 | + | proposer_address | bytes | [Address](../core/data_structures.md#address) of the validator that created the proposal. | 8 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |----------------|-------|-------------------------------------------------------|--------------|---------------| + | vote_extension | bytes | Information signed by by CometBFT. Can have 0 length. | 1 | No | + +* **Usage**: + * `ResponseExtendVote.vote_extension` is application-generated information that will be signed + by CometBFT and attached to the Precommit message. + * The Application may choose to use an empty vote extension (0 length). + * The contents of `RequestExtendVote` correspond to the proposed block on which the consensus algorithm + will send the Precommit message. + * `ResponseExtendVote.vote_extension` will only be attached to a non-`nil` Precommit message. If the consensus algorithm is to + precommit `nil`, it will not call `RequestExtendVote`. + * The Application logic that creates the extension can be non-deterministic. + +#### When does CometBFT call `ExtendVote`? + +When a validator _p_ is in consensus state _prevote_ of round _r_, height _h_, in which _q_ is the proposer; and _p_ has received + +* the Proposal message _v_ for round _r_, height _h_, along with all the block parts, from _q_, +* `Prevote` messages from _2f + 1_ validators' voting power for round _r_, height _h_, prevoting for the same block _id(v)_, + +then _p_ locks _v_ and sends a Precommit message in the following way + +1. _p_ sets _lockedValue_ and _validValue_ to _v_, and sets _lockedRound_ and _validRound_ to _r_ +2. _p_'s CometBFT calls `RequestExtendVote` with _v_ (`RequestExtendVote`). The call is synchronous. +3. The Application returns an array of bytes, `ResponseExtendVote.extension`, which is not interpreted by the consensus algorithm. +4. _p_ sets `ResponseExtendVote.extension` as the value of the `extension` field of type + [CanonicalVoteExtension](../core/data_structures.md#canonicalvoteextension), + populates the other fields in [CanonicalVoteExtension](../core/data_structures.md#canonicalvoteextension), + and signs the populated data structure. +5. _p_ constructs and signs the [CanonicalVote](../core/data_structures.md#canonicalvote) structure. +6. _p_ constructs the Precommit message (i.e. [Vote](../core/data_structures.md#vote) structure) + using [CanonicalVoteExtension](../core/data_structures.md#canonicalvoteextension) + and [CanonicalVote](../core/data_structures.md#canonicalvote). +7. _p_ broadcasts the Precommit message. + +In the cases when _p_ is to broadcast `precommit nil` messages (either _2f+1_ `prevote nil` messages received, +or _timeoutPrevote_ triggered), _p_'s CometBFT does **not** call `RequestExtendVote` and will not include +a [CanonicalVoteExtension](../core/data_structures.md#canonicalvoteextension) field in the `precommit nil` message. + +### VerifyVoteExtension + +#### Parameters and Types + +* **Request**: + + | Name | Type | Description | Field Number | + |-------------------|-------|-------------------------------------------------------------------------------------------|--------------| + | hash | bytes | The hash of the proposed block that the vote extension refers to. | 1 | + | validator_address | bytes | [Address](../core/data_structures.md#address) of the validator that signed the extension. | 2 | + | height | int64 | Height of the block (for sanity check). | 3 | + | vote_extension | bytes | Application-specific information signed by CometBFT. Can have 0 length. | 4 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |--------|-------------------------------|----------------------------------------------------------------|--------------|---------------| + | status | [VerifyStatus](#verifystatus) | `enum` signaling if the application accepts the vote extension | 1 | Yes | + +* **Usage**: + * `RequestVerifyVoteExtension.vote_extension` can be an empty byte array. The Application's + interpretation of it should be + that the Application running at the process that sent the vote chose not to extend it. + CometBFT will always call `RequestVerifyVoteExtension`, even for 0 length vote extensions. + * `RequestVerifyVoteExtension` is not called for precommit votes sent by the local process. + * `RequestVerifyVoteExtension.hash` refers to a proposed block. There is not guarantee that + this proposed block has previously been exposed to the Application via `ProcessProposal`. + * If `ResponseVerifyVoteExtension.status` is `REJECT`, the consensus algorithm will reject the whole received vote. + See the [Requirements](./abci++_app_requirements.md) section to understand the potential + liveness implications of this. + * The implementation of `VerifyVoteExtension` MUST be deterministic. Moreover, the value of + `ResponseVerifyVoteExtension.status` MUST **exclusively** depend on the parameters passed in + the call to `RequestVerifyVoteExtension`, and the last committed Application state + (see [Requirements](./abci++_app_requirements.md) section). + * Moreover, application implementers SHOULD always set `ResponseVerifyVoteExtension.status` to `ACCEPT`, + unless they _really_ know what the potential liveness implications of returning `REJECT` are. + +#### When does CometBFT call `VerifyVoteExtension`? + +When a node _p_ is in consensus round _r_, height _h_, and _p_ receives a Precommit +message for round _r_, height _h_ from validator _q_ (_q_ ≠ _p_): + +1. If the Precommit message does not contain a vote extension with a valid signature, _p_ + discards the Precommit message as invalid. + * a 0-length vote extension is valid as long as its accompanying signature is also valid. +2. Else, _p_'s CometBFT calls `RequestVerifyVoteExtension`. +3. The Application returns `ACCEPT` or `REJECT` via `ResponseVerifyVoteExtension.status`. +4. If the Application returns + * `ACCEPT`, _p_ will keep the received vote, together with its corresponding + vote extension in its internal data structures. It will be used to populate the [ExtendedCommitInfo](#extendedcommitinfo) + structure in calls to `RequestPrepareProposal`, in rounds of height _h + 1_ where _p_ is the proposer. + * `REJECT`, _p_ will deem the Precommit message invalid and discard it. + +When a node _p_ is in consensus round _0_, height _h_, and _p_ receives a Precommit +message for CommitRound _r_, height _h-1_ from validator _q_ (_q_ ≠ _p_), _p_ +MAY add the Precommit message and associated extension to [ExtendedCommitInfo](#extendedcommitinfo) +without calling `RequestVerifyVoteExtension` to verify it. + + +### FinalizeBlock + +#### Parameters and Types + +* **Request**: + + | Name | Type | Description | Field Number | + |----------------------|-------------------------------------------------|-------------------------------------------------------------------------------------------|--------------| + | txs | repeated bytes | List of transactions committed as part of the block. | 1 | + | decided_last_commit | [CommitInfo](#commitinfo) | Info about the last commit, obtained from the block that was just decided. | 2 | + | misbehavior | repeated [Misbehavior](#misbehavior) | List of information about validators that misbehaved. | 3 | + | hash | bytes | The block's hash. | 4 | + | height | int64 | The height of the finalized block. | 5 | + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Timestamp of the finalized block. | 6 | + | next_validators_hash | bytes | Merkle root of the next validator set. | 7 | + | proposer_address | bytes | [Address](../core/data_structures.md#address) of the validator that created the proposal. | 8 | + +* **Response**: + + | Name | Type | Description | Field Number | Deterministic | + |-------------------------|---------------------------------------------------|----------------------------------------------------------------------------------|--------------|---------------| + | events | repeated [Event](abci++_basic_concepts.md#events) | Type & Key-Value events for indexing | 1 | No | + | tx_results | repeated [ExecTxResult](#exectxresult) | List of structures containing the data resulting from executing the transactions | 2 | Yes | + | validator_updates | repeated [ValidatorUpdate](#validatorupdate) | Changes to validator set (set voting power to 0 to remove). | 3 | Yes | + | consensus_param_updates | [ConsensusParams](#consensusparams) | Changes to gas, size, and other consensus-related parameters. | 4 | Yes | + | app_hash | bytes | The Merkle root hash of the application state. | 5 | Yes | + +* **Usage**: + * Contains the fields of the newly decided block. + * This method is equivalent to the call sequence `BeginBlock`, [`DeliverTx`], + and `EndBlock` in ABCI 1.0. + * The height and time values match the values from the header of the proposed block. + * The Application can use `RequestFinalizeBlock.decided_last_commit` and `RequestFinalizeBlock.misbehavior` + to determine rewards and punishments for the validators. + * The Application executes the transactions in `RequestFinalizeBlock.txs` deterministically, + according to the rules set up by the Application, before returning control to CometBFT. + Alternatively, it can apply the candidate state corresponding to the same block previously + executed via `PrepareProposal` or `ProcessProposal`. + * `ResponseFinalizeBlock.tx_results[i].Code == 0` only if the _i_-th transaction is fully valid. + * The Application must provide values for `ResponseFinalizeBlock.app_hash`, + `ResponseFinalizeBlock.tx_results`, `ResponseFinalizeBlock.validator_updates`, and + `ResponseFinalizeBlock.consensus_param_updates` as a result of executing the block. + * The values for `ResponseFinalizeBlock.validator_updates`, or + `ResponseFinalizeBlock.consensus_param_updates` may be empty. In this case, CometBFT will keep + the current values. + * `ResponseFinalizeBlock.validator_updates`, triggered by block `H`, affect validation + for blocks `H+1`, `H+2`, and `H+3`. Heights following a validator update are affected in the following way: + * Height `H+1`: `NextValidatorsHash` includes the new `validator_updates` value. + * Height `H+2`: The validator set change takes effect and `ValidatorsHash` is updated. + * Height `H+3`: `*_last_commit` fields in `PrepareProposal`, `ProcessProposal`, and + `FinalizeBlock` now include the altered validator set. + * `ResponseFinalizeBlock.consensus_param_updates` returned for block `H` apply to the consensus + params for block `H+1`. For more information on the consensus parameters, + see the [consensus parameters](./abci%2B%2B_app_requirements.md#consensus-parameters) + section. + * `ResponseFinalizeBlock.app_hash` contains an (optional) Merkle root hash of the application state. + * `ResponseFinalizeBlock.app_hash` is included as the `Header.AppHash` in the next block. + * `ResponseFinalizeBlock.app_hash` may also be empty or hard-coded, but MUST be + **deterministic** - it must not be a function of anything that did not come from the parameters + of `RequestFinalizeBlock` and the previous committed state. + * Later calls to `Query` can return proofs about the application state anchored + in this Merkle root hash. + * The implementation of `FinalizeBlock` MUST be deterministic, since it is + making the Application's state evolve in the context of state machine replication. + * Currently, CometBFT will fill up all fields in `RequestFinalizeBlock`, even if they were + already passed on to the Application via `RequestPrepareProposal` or `RequestProcessProposal`. + * When calling `FinalizeBlock` with a block, the consensus algorithm run by CometBFT guarantees + that at least one non-byzantine validator has run `ProcessProposal` on that block. + +#### When does CometBFT call `FinalizeBlock`? + +When a node _p_ is in consensus height _h_, and _p_ receives + +* the Proposal message with block _v_ for a round _r_, along with all its block parts, from _q_, + which is the proposer of round _r_, height _h_, +* `Precommit` messages from _2f + 1_ validators' voting power for round _r_, height _h_, + precommitting the same block _id(v)_, + +then _p_ decides block _v_ and finalizes consensus for height _h_ in the following way + +1. _p_ persists _v_ as the decision for height _h_. +2. _p_'s CometBFT calls `RequestFinalizeBlock` with _v_'s data. The call is synchronous. +3. _p_'s Application executes block _v_. +4. _p_'s Application calculates and returns the _AppHash_, along with a list containing + the outputs of each of the transactions executed. +5. _p_'s CometBFT hashes all the transaction outputs and stores it in _ResultHash_. +6. _p_'s CometBFT persists the transaction outputs, _AppHash_, and _ResultsHash_. +7. _p_'s CometBFT locks the mempool — no calls to `CheckTx` on new transactions. +8. _p_'s CometBFT calls `RequestCommit` to instruct the Application to persist its state. +9. _p_'s CometBFT, optionally, re-checks all outstanding transactions in the mempool + against the newly persisted Application state. +10. _p_'s CometBFT unlocks the mempool — newly received transactions can now be checked. +11. _p_ starts consensus for height _h+1_, round 0 + +## Data Types existing in ABCI + +Most of the data structures used in ABCI are shared [common data structures](../core/data_structures.md). In certain cases, ABCI uses different data structures which are documented here: + +### Validator + +* **Fields**: + + | Name | Type | Description | Field Number | + |---------|-------|------------------------------------------------------------|--------------| + | address | bytes | [Address](../core/data_structures.md#address) of validator | 1 | + | power | int64 | Voting power of the validator | 3 | + +* **Usage**: + * Validator identified by address + * Used as part of `VoteInfo` within `CommitInfo` (used in `ProcessProposal` + and `FinalizeBlock`), and `ExtendedCommitInfo` (used in `PrepareProposal`). + * Does not include PubKey to avoid sending potentially large quantum pubkeys + over the ABCI + +### ValidatorUpdate + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |---------|--------------------------------------------------|-------------------------------|--------------|---------------| + | pub_key | [Public Key](../core/data_structures.md#pub_key) | Public key of the validator | 1 | Yes | + | power | int64 | Voting power of the validator | 2 | Yes | + +* **Usage**: + * Validator identified by PubKey + * Used to tell CometBFT to update the validator set + +### Misbehavior + +* **Fields**: + + | Name | Type | Description | Field Number | + |--------------------|-------------------------------------------------|--------------------------------------------------------------|--------------| + | type | [MisbehaviorType](#misbehaviortype) | Type of the misbehavior. An enum of possible misbehaviors. | 1 | + | validator | [Validator](#validator) | The offending validator | 2 | + | height | int64 | Height when the offense occurred | 3 | + | time | [google.protobuf.Timestamp][protobuf-timestamp] | Timestamp of the block that was committed at height `height` | 4 | + | total_voting_power | int64 | Total voting power of the validator set at height `height` | 5 | + +#### MisbehaviorType + +* **Fields** + + MisbehaviorType is an enum with the listed fields: + + | Name | Field Number | + |---------------------|--------------| + | UNKNOWN | 0 | + | DUPLICATE_VOTE | 1 | + | LIGHT_CLIENT_ATTACK | 2 | + +### ConsensusParams + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |-----------|---------------------------------------------------------------|------------------------------------------------------------------------------|--------------|---------------| + | block | [BlockParams](../core/data_structures.md#blockparams) | Parameters limiting the size of a block and time between consecutive blocks. | 1 | Yes | + | evidence | [EvidenceParams](../core/data_structures.md#evidenceparams) | Parameters limiting the validity of evidence of byzantine behaviour. | 2 | Yes | + | validator | [ValidatorParams](../core/data_structures.md#validatorparams) | Parameters limiting the types of public keys validators can use. | 3 | Yes | + | version | [VersionsParams](../core/data_structures.md#versionparams) | The ABCI application version. | 4 | Yes | + +### ProofOps + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |------|------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|---------------| + | ops | repeated [ProofOp](#proofop) | List of chained Merkle proofs, of possibly different types. The Merkle root of one op is the value being proven in the next op. The Merkle root of the final op should equal the ultimate root hash being verified against.. | 1 | N/A | + +### ProofOp + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |------|--------|------------------------------------------------|--------------|---------------| + | type | string | Type of Merkle proof and how it's encoded. | 1 | N/A | + | key | bytes | Key in the Merkle tree that this proof is for. | 2 | N/A | + | data | bytes | Encoded Merkle proof for the key. | 3 | N/A | + +### Snapshot + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |----------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|---------------| + | height | uint64 | The height at which the snapshot was taken (after commit). | 1 | N/A | + | format | uint32 | An application-specific snapshot format, allowing applications to version their snapshot data format and make backwards-incompatible changes. CometBFT does not interpret this. | 2 | N/A | + | chunks | uint32 | The number of chunks in the snapshot. Must be at least 1 (even if empty). | 3 | N/A | + | hash | bytes | An arbitrary snapshot hash. Must be equal only for identical snapshots across nodes. CometBFT does not interpret the hash, it only compares them. | 4 | N/A | + | metadata | bytes | Arbitrary application metadata, for example chunk hashes or other verification data. | 5 | N/A | + +* **Usage**: + * Used for state sync snapshots, see the [state sync section](../p2p/legacy-docs/messages/state-sync.md) for details. + * A snapshot is considered identical across nodes only if _all_ fields are equal (including + `Metadata`). Chunks may be retrieved from all nodes that have the same snapshot. + * When sent across the network, a snapshot message can be at most 4 MB. + +## Data types introduced or modified in ABCI++ + +### VoteInfo + +* **Fields**: + + | Name | Type | Description | Field Number | + |---------------|-------------------------------------------------------|------------------------------------------------------------------------------------------|--------------| + | validator | [Validator](#validator) | The validator that sent the vote. | 1 | + | block_id_flag | [BlockIDFlag](../core/data_structures.md#blockidflag) | Indicates whether the validator voted the last block, nil, or its vote was not received. | 3 | + +* **Usage**: + * Indicates whether a validator signed the last block, allowing for rewards based on validator availability. + * This information is typically extracted from a proposed or decided block. + +### ExtendedVoteInfo + +* **Fields**: + + | Name | Type | Description | Field Number | + |---------------------|-------------------------------------------------------|---------------------------------------------------------------------------------------------|--------------| + | validator | [Validator](#validator) | The validator that sent the vote. | 1 | + | vote_extension | bytes | Non-deterministic extension provided by the sending validator's Application. | 3 | + | extension_signature | bytes | Signature of the vote extension produced by the sending validator and verified by CometBFT. | 4 | + | block_id_flag | [BlockIDFlag](../core/data_structures.md#blockidflag) | Indicates whether the validator voted the last block, nil, or its vote was not received. | 5 | + +* **Usage**: + * Indicates whether a validator signed the last block, allowing for rewards based on validator availability. + * This information is extracted from CometBFT's data structures in the local process. + * `vote_extension` contains the sending validator's vote extension, whose signature was verified by CometBFT. It can be empty. + * `extension_signature` is the signature of the vote extension, which was verified verified by CometBFT. This way, we expose the signature to the application for further processing or verification. + +### CommitInfo + +* **Fields**: + + | Name | Type | Description | Field Number | + |-------|--------------------------------|----------------------------------------------------------------------------------------------|--------------| + | round | int32 | Commit round. Reflects the round at which the block proposer decided in the previous height. | 1 | + | votes | repeated [VoteInfo](#voteinfo) | List of validators' addresses in the last validator set with their voting information. | 2 | + +* **Notes** + * The `VoteInfo` in `votes` are ordered by the voting power of the validators (descending order, highest to lowest voting power). + * CometBFT guarantees the `votes` ordering through its logic to update the validator set in which, in the end, the validators are sorted (descending) by their voting power. + * The ordering is also persisted when a validator set is saved in the store. + * The validator set is loaded from the store when building the `CommitInfo`, ensuring order is maintained from the persisted validator set. + +### ExtendedCommitInfo + +* **Fields**: + + | Name | Type | Description | Field Number | + |-------|------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|--------------| + | round | int32 | Commit round. Reflects the round at which the block proposer decided in the previous height. | 1 | + | votes | repeated [ExtendedVoteInfo](#extendedvoteinfo) | List of validators' addresses in the last validator set with their voting information, including vote extensions. | 2 | + +* **Notes** + * The `ExtendedVoteInfo` in `votes` are ordered by the voting power of the validators (descending order, highest to lowest voting power). + * CometBFT guarantees the `votes` ordering through its logic to update the validator set in which, in the end, the validators are sorted (descending) by their voting power. + * The ordering is also persisted when a validator set is saved in the store. + * The validator set is loaded from the store when building the `ExtendedCommitInfo`, ensuring order is maintained from the persisted validator set. + +### ExecTxResult + +* **Fields**: + + | Name | Type | Description | Field Number | Deterministic | + |------------|---------------------------------------------------|----------------------------------------------------------------------|--------------|---------------| + | code | uint32 | Response code. | 1 | Yes | + | data | bytes | Result bytes, if any. | 2 | Yes | + | log | string | The output of the application's logger. | 3 | No | + | info | string | Additional information. | 4 | No | + | gas_wanted | int64 | Amount of gas requested for transaction. | 5 | Yes | + | gas_used | int64 | Amount of gas consumed by transaction. | 6 | Yes | + | events | repeated [Event](abci++_basic_concepts.md#events) | Type & Key-Value events for indexing transactions (e.g. by account). | 7 | No | + | codespace | string | Namespace for the `code`. | 8 | Yes | + +### ProposalStatus + +```proto +enum ProposalStatus { + UNKNOWN = 0; // Unknown status. Returning this from the application is always an error. + ACCEPT = 1; // Status that signals that the application finds the proposal valid. + REJECT = 2; // Status that signals that the application finds the proposal invalid. +} +``` + +* **Usage**: + * Used within the [ProcessProposal](#processproposal) response. + * If `Status` is `UNKNOWN`, a problem happened in the Application. CometBFT will assume the application is faulty and crash. + * If `Status` is `ACCEPT`, the consensus algorithm accepts the proposal and will issue a Prevote message for it. + * If `Status` is `REJECT`, the consensus algorithm rejects the proposal and will issue a Prevote for `nil` instead. + + +### VerifyStatus + +```proto +enum VerifyStatus { + UNKNOWN = 0; // Unknown status. Returning this from the application is always an error. + ACCEPT = 1; // Status that signals that the application finds the vote extension valid. + REJECT = 2; // Status that signals that the application finds the vote extension invalid. +} +``` + +* **Usage**: + * Used within the [VerifyVoteExtension](#verifyvoteextension) response. + * If `Status` is `UNKNOWN`, a problem happened in the Application. CometBFT will assume the application is faulty and crash. + * If `Status` is `ACCEPT`, the consensus algorithm will accept the vote as valid. + * If `Status` is `REJECT`, the consensus algorithm will reject the vote as invalid. + +[protobuf-timestamp]: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp diff --git a/spec/blockchain/blockchain.md b/spec/blockchain/blockchain.md new file mode 100644 index 0000000..18c86dd --- /dev/null +++ b/spec/blockchain/blockchain.md @@ -0,0 +1,3 @@ +# Blockchain + +Deprecated see [core/data_structures.md](../core/data_structures.md) diff --git a/spec/blockchain/encoding.md b/spec/blockchain/encoding.md new file mode 100644 index 0000000..fbd38b9 --- /dev/null +++ b/spec/blockchain/encoding.md @@ -0,0 +1,3 @@ +# Encoding + +Deprecated see [core/data_structures.md](../core/encoding.md) diff --git a/spec/blockchain/readme.md b/spec/blockchain/readme.md new file mode 100644 index 0000000..f5b4fcb --- /dev/null +++ b/spec/blockchain/readme.md @@ -0,0 +1,14 @@ +--- +order: 1 +parent: + title: Blockchain + order: false +--- + +# Blockchain + +This section describes the core types and functionality of the CometBFT protocol implementation. + +[Core Data Structures](../core/data_structures.md) +[Encoding](../core/encoding.md) +[State](../core/state.md) diff --git a/spec/blockchain/state.md b/spec/blockchain/state.md new file mode 100644 index 0000000..43c90b2 --- /dev/null +++ b/spec/blockchain/state.md @@ -0,0 +1,3 @@ +# State + +Deprecated see [core/state.md](../core/state.md) diff --git a/spec/consensus/README.md b/spec/consensus/README.md new file mode 100644 index 0000000..3a626b1 --- /dev/null +++ b/spec/consensus/README.md @@ -0,0 +1,29 @@ +--- +order: 1 +parent: + title: Consensus + order: 4 +--- + +# Consensus + +Specification of the consensus protocol implemented in CometBFT. + +## Contents + +- [Consensus Paper](./consensus-paper) - Latex paper on + [arxiv](https://arxiv.org/abs/1807.04938) describing the + Tendermint consensus algorithm, adopted in CometBFT, with proofs of safety and termination. +- [BFT Time](./bft-time.md) - How the timestamp in a CometBFT + block header is computed in a Byzantine Fault Tolerant manner +- [Creating Proposal](./creating-proposal.md) - How a proposer + creates a block proposal for consensus +- [Light Client Protocol](./light-client) - A protocol for light weight consensus + verification and syncing to the latest state +- [Validator Signing](./signing.md) - Rules for cryptographic signatures + produced by validators. +- [Write Ahead Log](./wal.md) - Write ahead log used by the + consensus state machine to recover from crashes. + +There is also a [stale markdown description](consensus.md) of the consensus state machine +(TODO update this). diff --git a/spec/consensus/bft-time.md b/spec/consensus/bft-time.md new file mode 100644 index 0000000..e64d2f7 --- /dev/null +++ b/spec/consensus/bft-time.md @@ -0,0 +1,56 @@ +--- +order: 2 +--- +# BFT Time + +CometBFT provides a deterministic, Byzantine fault-tolerant, source of time. +Time in CometBFT is defined with the Time field of the block header. + +It satisfies the following properties: + +- Time Monotonicity: Time is monotonically increasing, i.e., given +a header H1 for height h1 and a header H2 for height `h2 = h1 + 1`, `H1.Time < H2.Time`. +- Time Validity: Given a set of Commit votes that forms the `block.LastCommit` field, a range of +valid values for the Time field of the block header is defined only by +Precommit messages (from the LastCommit field) sent by correct processes, i.e., +a faulty process cannot arbitrarily increase the Time value. + +In the context of CometBFT, time is of type int64 and denotes UNIX time in milliseconds, i.e., +corresponds to the number of milliseconds since January 1, 1970. +Before defining rules that need to be enforced by Tendermint, the consensus algorithm adopted in CometBFT, +so the properties above holds, we introduce the following definition: + +- median of a Commit is equal to the median of `Vote.Time` fields of the `Vote` messages, +where the value of `Vote.Time` is counted number of times proportional to the process voting power. As +the voting power is not uniform (one process one vote), a vote message is actually an aggregator of the same votes whose +number is equal to the voting power of the process that has casted the corresponding votes message. + +Let's consider the following example: + +- we have four processes p1, p2, p3 and p4, with the following voting power distribution (p1, 23), (p2, 27), (p3, 10) +and (p4, 10). The total voting power is 70 (`N = 3f+1`, where `N` is the total voting power, and `f` is the maximum voting +power of the faulty processes), so we assume that the faulty processes have at most 23 of voting power. +Furthermore, we have the following vote messages in some LastCommit field (we ignore all fields except Time field): + - (p1, 100), (p2, 98), (p3, 1000), (p4, 500). We assume that p3 and p4 are faulty processes. Let's assume that the + `block.LastCommit` message contains votes of processes p2, p3 and p4. Median is then chosen the following way: + the value 98 is counted 27 times, the value 1000 is counted 10 times and the value 500 is counted also 10 times. + So the median value will be the value 98. No matter what set of messages with at least `2f+1` voting power we + choose, the median value will always be between the values sent by correct processes. + +We ensure Time Monotonicity and Time Validity properties by the following rules: + +- let rs denotes `RoundState` (consensus internal state) of some process. Then +`rs.ProposalBlock.Header.Time == median(rs.LastCommit) && +rs.Proposal.Timestamp == rs.ProposalBlock.Header.Time`. + +- Furthermore, when creating the `vote` message, the following rules for determining `vote.Time` field should hold: + + - if `rs.LockedBlock` is defined then + `vote.Time = max(rs.LockedBlock.Timestamp + time.Millisecond, time.Now())`, where `time.Now()` + denotes local Unix time in milliseconds + + - else if `rs.Proposal` is defined then + `vote.Time = max(rs.Proposal.Timestamp + time.Millisecond,, time.Now())`, + + - otherwise, `vote.Time = time.Now())`. In this case vote is for `nil` so it is not taken into account for + the timestamp of the next block. diff --git a/spec/consensus/consensus-paper/IEEEtran.bst b/spec/consensus/consensus-paper/IEEEtran.bst new file mode 100644 index 0000000..075a58f --- /dev/null +++ b/spec/consensus/consensus-paper/IEEEtran.bst @@ -0,0 +1,2417 @@ +%% +%% IEEEtran.bst +%% BibTeX Bibliography Style file for IEEE Journals and Conferences (unsorted) +%% Version 1.12 (2007/01/11) +%% +%% Copyright (c) 2003-2007 Michael Shell +%% +%% Original starting code base and algorithms obtained from the output of +%% Patrick W. Daly's makebst package as well as from prior versions of +%% IEEE BibTeX styles: +%% +%% 1. Howard Trickey and Oren Patashnik's ieeetr.bst (1985/1988) +%% 2. Silvano Balemi and Richard H. Roy's IEEEbib.bst (1993) +%% +%% Support sites: +%% http://www.michaelshell.org/tex/ieeetran/ +%% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/ +%% and/or +%% http://www.ieee.org/ +%% +%% For use with BibTeX version 0.99a or later +%% +%% This is a numerical citation style. +%% +%%************************************************************************* +%% Legal Notice: +%% This code is offered as-is without any warranty either expressed or +%% implied; without even the implied warranty of MERCHANTABILITY or +%% FITNESS FOR A PARTICULAR PURPOSE! +%% User assumes all risk. +%% In no event shall IEEE or any contributor to this code be liable for +%% any damages or losses, including, but not limited to, incidental, +%% consequential, or any other damages, resulting from the use or misuse +%% of any information contained here. +%% +%% All comments are the opinions of their respective authors and are not +%% necessarily endorsed by the IEEE. +%% +%% This work is distributed under the LaTeX Project Public License (LPPL) +%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used, +%% distributed and modified. A copy of the LPPL, version 1.3, is included +%% in the base LaTeX documentation of all distributions of LaTeX released +%% 2003/12/01 or later. +%% Retain all contribution notices and credits. +%% ** Modified files should be clearly indicated as such, including ** +%% ** renaming them and changing author support contact information. ** +%% +%% File list of work: IEEEabrv.bib, IEEEfull.bib, IEEEexample.bib, +%% IEEEtran.bst, IEEEtranS.bst, IEEEtranSA.bst, +%% IEEEtranN.bst, IEEEtranSN.bst, IEEEtran_bst_HOWTO.pdf +%%************************************************************************* +% +% +% Changelog: +% +% 1.00 (2002/08/13) Initial release +% +% 1.10 (2002/09/27) +% 1. Corrected minor bug for improperly formed warning message when a +% book was not given a title. Thanks to Ming Kin Lai for reporting this. +% 2. Added support for CTLname_format_string and CTLname_latex_cmd fields +% in the BST control entry type. +% +% 1.11 (2003/04/02) +% 1. Fixed bug with URLs containing underscores when using url.sty. Thanks +% to Ming Kin Lai for reporting this. +% +% 1.12 (2007/01/11) +% 1. Fixed bug with unwanted comma before "et al." when an entry contained +% more than two author names. Thanks to Pallav Gupta for reporting this. +% 2. Fixed bug with anomalous closing quote in tech reports that have a +% type, but without a number or address. Thanks to Mehrdad Mirreza for +% reporting this. +% 3. Use braces in \providecommand in begin.bib to better support +% latex2html. TeX style length assignments OK with recent versions +% of latex2html - 1.71 (2002/2/1) or later is strongly recommended. +% Use of the language field still causes trouble with latex2html. +% Thanks to Federico Beffa for reporting this. +% 4. Added IEEEtran.bst ID and version comment string to .bbl output. +% 5. Provide a \BIBdecl hook that allows the user to execute commands +% just prior to the first entry. +% 6. Use default urlstyle (is using url.sty) of "same" rather than rm to +% better work with a wider variety of bibliography styles. +% 7. Changed month abbreviations from Sept., July and June to Sep., Jul., +% and Jun., respectively, as IEEE now does. Thanks to Moritz Borgmann +% for reporting this. +% 8. Control entry types should not be considered when calculating longest +% label width. +% 9. Added alias www for electronic/online. +% 10. Added CTLname_url_prefix control entry type. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% DEFAULTS FOR THE CONTROLS OF THE BST STYLE %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% These are the defaults for the user adjustable controls. The values used +% here can be overridden by the user via IEEEtranBSTCTL entry type. + +% NOTE: The recommended LaTeX command to invoke a control entry type is: +% +%\makeatletter +%\def\bstctlcite{\@ifnextchar[{\@bstctlcite}{\@bstctlcite[@auxout]}} +%\def\@bstctlcite[#1]#2{\@bsphack +% \@for\@citeb:=#2\do{% +% \edef\@citeb{\expandafter\@firstofone\@citeb}% +% \if@filesw\immediate\write\csname #1\endcsname{\string\citation{\@citeb}}\fi}% +% \@esphack} +%\makeatother +% +% It is called at the start of the document, before the first \cite, like: +% \bstctlcite{IEEEexample:BSTcontrol} +% +% IEEEtran.cls V1.6 and later does provide this command. + + + +% #0 turns off the display of the number for articles. +% #1 enables +FUNCTION {default.is.use.number.for.article} { #1 } + + +% #0 turns off the display of the paper and type fields in @inproceedings. +% #1 enables +FUNCTION {default.is.use.paper} { #1 } + + +% #0 turns off the forced use of "et al." +% #1 enables +FUNCTION {default.is.forced.et.al} { #0 } + +% The maximum number of names that can be present beyond which an "et al." +% usage is forced. Be sure that num.names.shown.with.forced.et.al (below) +% is not greater than this value! +% Note: There are many instances of references in IEEE journals which have +% a very large number of authors as well as instances in which "et al." is +% used profusely. +FUNCTION {default.max.num.names.before.forced.et.al} { #10 } + +% The number of names that will be shown with a forced "et al.". +% Must be less than or equal to max.num.names.before.forced.et.al +FUNCTION {default.num.names.shown.with.forced.et.al} { #1 } + + +% #0 turns off the alternate interword spacing for entries with URLs. +% #1 enables +FUNCTION {default.is.use.alt.interword.spacing} { #1 } + +% If alternate interword spacing for entries with URLs is enabled, this is +% the interword spacing stretch factor that will be used. For example, the +% default "4" here means that the interword spacing in entries with URLs can +% stretch to four times normal. Does not have to be an integer. Note that +% the value specified here can be overridden by the user in their LaTeX +% code via a command such as: +% "\providecommand\BIBentryALTinterwordstretchfactor{1.5}" in addition to +% that via the IEEEtranBSTCTL entry type. +FUNCTION {default.ALTinterwordstretchfactor} { "4" } + + +% #0 turns off the "dashification" of repeated (i.e., identical to those +% of the previous entry) names. IEEE normally does this. +% #1 enables +FUNCTION {default.is.dash.repeated.names} { #1 } + + +% The default name format control string. +FUNCTION {default.name.format.string}{ "{f.~}{vv~}{ll}{, jj}" } + + +% The default LaTeX font command for the names. +FUNCTION {default.name.latex.cmd}{ "" } + + +% The default URL prefix. +FUNCTION {default.name.url.prefix}{ "[Online]. Available:" } + + +% Other controls that cannot be accessed via IEEEtranBSTCTL entry type. + +% #0 turns off the terminal startup banner/completed message so as to +% operate more quietly. +% #1 enables +FUNCTION {is.print.banners.to.terminal} { #1 } + + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% FILE VERSION AND BANNER %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FUNCTION{bst.file.version} { "1.12" } +FUNCTION{bst.file.date} { "2007/01/11" } +FUNCTION{bst.file.website} { "http://www.michaelshell.org/tex/ieeetran/bibtex/" } + +FUNCTION {banner.message} +{ is.print.banners.to.terminal + { "-- IEEEtran.bst version" " " * bst.file.version * + " (" * bst.file.date * ") " * "by Michael Shell." * + top$ + "-- " bst.file.website * + top$ + "-- See the " quote$ * "IEEEtran_bst_HOWTO.pdf" * quote$ * " manual for usage information." * + top$ + } + { skip$ } + if$ +} + +FUNCTION {completed.message} +{ is.print.banners.to.terminal + { "" + top$ + "Done." + top$ + } + { skip$ } + if$ +} + + + + +%%%%%%%%%%%%%%%%%%%%%% +%% STRING CONSTANTS %% +%%%%%%%%%%%%%%%%%%%%%% + +FUNCTION {bbl.and}{ "and" } +FUNCTION {bbl.etal}{ "et~al." } +FUNCTION {bbl.editors}{ "eds." } +FUNCTION {bbl.editor}{ "ed." } +FUNCTION {bbl.edition}{ "ed." } +FUNCTION {bbl.volume}{ "vol." } +FUNCTION {bbl.of}{ "of" } +FUNCTION {bbl.number}{ "no." } +FUNCTION {bbl.in}{ "in" } +FUNCTION {bbl.pages}{ "pp." } +FUNCTION {bbl.page}{ "p." } +FUNCTION {bbl.chapter}{ "ch." } +FUNCTION {bbl.paper}{ "paper" } +FUNCTION {bbl.part}{ "pt." } +FUNCTION {bbl.patent}{ "Patent" } +FUNCTION {bbl.patentUS}{ "U.S." } +FUNCTION {bbl.revision}{ "Rev." } +FUNCTION {bbl.series}{ "ser." } +FUNCTION {bbl.standard}{ "Std." } +FUNCTION {bbl.techrep}{ "Tech. Rep." } +FUNCTION {bbl.mthesis}{ "Master's thesis" } +FUNCTION {bbl.phdthesis}{ "Ph.D. dissertation" } +FUNCTION {bbl.st}{ "st" } +FUNCTION {bbl.nd}{ "nd" } +FUNCTION {bbl.rd}{ "rd" } +FUNCTION {bbl.th}{ "th" } + + +% This is the LaTeX spacer that is used when a larger than normal space +% is called for (such as just before the address:publisher). +FUNCTION {large.space} { "\hskip 1em plus 0.5em minus 0.4em\relax " } + +% The LaTeX code for dashes that are used to represent repeated names. +% Note: Some older IEEE journals used something like +% "\rule{0.275in}{0.5pt}\," which is fairly thick and runs right along +% the baseline. However, IEEE now uses a thinner, above baseline, +% six dash long sequence. +FUNCTION {repeated.name.dashes} { "------" } + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% PREDEFINED STRING MACROS %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +MACRO {jan} {"Jan."} +MACRO {feb} {"Feb."} +MACRO {mar} {"Mar."} +MACRO {apr} {"Apr."} +MACRO {may} {"May"} +MACRO {jun} {"Jun."} +MACRO {jul} {"Jul."} +MACRO {aug} {"Aug."} +MACRO {sep} {"Sep."} +MACRO {oct} {"Oct."} +MACRO {nov} {"Nov."} +MACRO {dec} {"Dec."} + + + +%%%%%%%%%%%%%%%%%% +%% ENTRY FIELDS %% +%%%%%%%%%%%%%%%%%% + +ENTRY + { address + assignee + author + booktitle + chapter + day + dayfiled + edition + editor + howpublished + institution + intype + journal + key + language + month + monthfiled + nationality + note + number + organization + pages + paper + publisher + school + series + revision + title + type + url + volume + year + yearfiled + CTLuse_article_number + CTLuse_paper + CTLuse_forced_etal + CTLmax_names_forced_etal + CTLnames_show_etal + CTLuse_alt_spacing + CTLalt_stretch_factor + CTLdash_repeated_names + CTLname_format_string + CTLname_latex_cmd + CTLname_url_prefix + } + {} + { label } + + + + +%%%%%%%%%%%%%%%%%%%%%%% +%% INTEGER VARIABLES %% +%%%%%%%%%%%%%%%%%%%%%%% + +INTEGERS { prev.status.punct this.status.punct punct.std + punct.no punct.comma punct.period + prev.status.space this.status.space space.std + space.no space.normal space.large + prev.status.quote this.status.quote quote.std + quote.no quote.close + prev.status.nline this.status.nline nline.std + nline.no nline.newblock + status.cap cap.std + cap.no cap.yes} + +INTEGERS { longest.label.width multiresult nameptr namesleft number.label numnames } + +INTEGERS { is.use.number.for.article + is.use.paper + is.forced.et.al + max.num.names.before.forced.et.al + num.names.shown.with.forced.et.al + is.use.alt.interword.spacing + is.dash.repeated.names} + + +%%%%%%%%%%%%%%%%%%%%%% +%% STRING VARIABLES %% +%%%%%%%%%%%%%%%%%%%%%% + +STRINGS { bibinfo + longest.label + oldname + s + t + ALTinterwordstretchfactor + name.format.string + name.latex.cmd + name.url.prefix} + + + + +%%%%%%%%%%%%%%%%%%%%%%%%% +%% LOW LEVEL FUNCTIONS %% +%%%%%%%%%%%%%%%%%%%%%%%%% + +FUNCTION {initialize.controls} +{ default.is.use.number.for.article 'is.use.number.for.article := + default.is.use.paper 'is.use.paper := + default.is.forced.et.al 'is.forced.et.al := + default.max.num.names.before.forced.et.al 'max.num.names.before.forced.et.al := + default.num.names.shown.with.forced.et.al 'num.names.shown.with.forced.et.al := + default.is.use.alt.interword.spacing 'is.use.alt.interword.spacing := + default.is.dash.repeated.names 'is.dash.repeated.names := + default.ALTinterwordstretchfactor 'ALTinterwordstretchfactor := + default.name.format.string 'name.format.string := + default.name.latex.cmd 'name.latex.cmd := + default.name.url.prefix 'name.url.prefix := +} + + +% This IEEEtran.bst features a very powerful and flexible mechanism for +% controlling the capitalization, punctuation, spacing, quotation, and +% newlines of the formatted entry fields. (Note: IEEEtran.bst does not need +% or use the newline/newblock feature, but it has been implemented for +% possible future use.) The output states of IEEEtran.bst consist of +% multiple independent attributes and, as such, can be thought of as being +% vectors, rather than the simple scalar values ("before.all", +% "mid.sentence", etc.) used in most other .bst files. +% +% The more flexible and complex design used here was motivated in part by +% IEEE's rather unusual bibliography style. For example, IEEE ends the +% previous field item with a period and large space prior to the publisher +% address; the @electronic entry types use periods as inter-item punctuation +% rather than the commas used by the other entry types; and URLs are never +% followed by periods even though they are the last item in the entry. +% Although it is possible to accommodate these features with the conventional +% output state system, the seemingly endless exceptions make for convoluted, +% unreliable and difficult to maintain code. +% +% IEEEtran.bst's output state system can be easily understood via a simple +% illustration of two most recently formatted entry fields (on the stack): +% +% CURRENT_ITEM +% "PREVIOUS_ITEM +% +% which, in this example, is to eventually appear in the bibliography as: +% +% "PREVIOUS_ITEM," CURRENT_ITEM +% +% It is the job of the output routine to take the previous item off of the +% stack (while leaving the current item at the top of the stack), apply its +% trailing punctuation (including closing quote marks) and spacing, and then +% to write the result to BibTeX's output buffer: +% +% "PREVIOUS_ITEM," +% +% Punctuation (and spacing) between items is often determined by both of the +% items rather than just the first one. The presence of quotation marks +% further complicates the situation because, in standard English, trailing +% punctuation marks are supposed to be contained within the quotes. +% +% IEEEtran.bst maintains two output state (aka "status") vectors which +% correspond to the previous and current (aka "this") items. Each vector +% consists of several independent attributes which track punctuation, +% spacing, quotation, and newlines. Capitalization status is handled by a +% separate scalar because the format routines, not the output routine, +% handle capitalization and, therefore, there is no need to maintain the +% capitalization attribute for both the "previous" and "this" items. +% +% When a format routine adds a new item, it copies the current output status +% vector to the previous output status vector and (usually) resets the +% current (this) output status vector to a "standard status" vector. Using a +% "standard status" vector in this way allows us to redefine what we mean by +% "standard status" at the start of each entry handler and reuse the same +% format routines under the various inter-item separation schemes. For +% example, the standard status vector for the @book entry type may use +% commas for item separators, while the @electronic type may use periods, +% yet both entry handlers exploit many of the exact same format routines. +% +% Because format routines have write access to the output status vector of +% the previous item, they can override the punctuation choices of the +% previous format routine! Therefore, it becomes trivial to implement rules +% such as "Always use a period and a large space before the publisher." By +% pushing the generation of the closing quote mark to the output routine, we +% avoid all the problems caused by having to close a quote before having all +% the information required to determine what the punctuation should be. +% +% The IEEEtran.bst output state system can easily be expanded if needed. +% For instance, it is easy to add a "space.tie" attribute value if the +% bibliography rules mandate that two items have to be joined with an +% unbreakable space. + +FUNCTION {initialize.status.constants} +{ #0 'punct.no := + #1 'punct.comma := + #2 'punct.period := + #0 'space.no := + #1 'space.normal := + #2 'space.large := + #0 'quote.no := + #1 'quote.close := + #0 'cap.no := + #1 'cap.yes := + #0 'nline.no := + #1 'nline.newblock := +} + +FUNCTION {std.status.using.comma} +{ punct.comma 'punct.std := + space.normal 'space.std := + quote.no 'quote.std := + nline.no 'nline.std := + cap.no 'cap.std := +} + +FUNCTION {std.status.using.period} +{ punct.period 'punct.std := + space.normal 'space.std := + quote.no 'quote.std := + nline.no 'nline.std := + cap.yes 'cap.std := +} + +FUNCTION {initialize.prev.this.status} +{ punct.no 'prev.status.punct := + space.no 'prev.status.space := + quote.no 'prev.status.quote := + nline.no 'prev.status.nline := + punct.no 'this.status.punct := + space.no 'this.status.space := + quote.no 'this.status.quote := + nline.no 'this.status.nline := + cap.yes 'status.cap := +} + +FUNCTION {this.status.std} +{ punct.std 'this.status.punct := + space.std 'this.status.space := + quote.std 'this.status.quote := + nline.std 'this.status.nline := +} + +FUNCTION {cap.status.std}{ cap.std 'status.cap := } + +FUNCTION {this.to.prev.status} +{ this.status.punct 'prev.status.punct := + this.status.space 'prev.status.space := + this.status.quote 'prev.status.quote := + this.status.nline 'prev.status.nline := +} + + +FUNCTION {not} +{ { #0 } + { #1 } + if$ +} + +FUNCTION {and} +{ { skip$ } + { pop$ #0 } + if$ +} + +FUNCTION {or} +{ { pop$ #1 } + { skip$ } + if$ +} + + +% convert the strings "yes" or "no" to #1 or #0 respectively +FUNCTION {yes.no.to.int} +{ "l" change.case$ duplicate$ + "yes" = + { pop$ #1 } + { duplicate$ "no" = + { pop$ #0 } + { "unknown boolean " quote$ * swap$ * quote$ * + " in " * cite$ * warning$ + #0 + } + if$ + } + if$ +} + + +% pushes true if the single char string on the stack is in the +% range of "0" to "9" +FUNCTION {is.num} +{ chr.to.int$ + duplicate$ "0" chr.to.int$ < not + swap$ "9" chr.to.int$ > not and +} + +% multiplies the integer on the stack by a factor of 10 +FUNCTION {bump.int.mag} +{ #0 'multiresult := + { duplicate$ #0 > } + { #1 - + multiresult #10 + + 'multiresult := + } + while$ +pop$ +multiresult +} + +% converts a single character string on the stack to an integer +FUNCTION {char.to.integer} +{ duplicate$ + is.num + { chr.to.int$ "0" chr.to.int$ - } + {"noninteger character " quote$ * swap$ * quote$ * + " in integer field of " * cite$ * warning$ + #0 + } + if$ +} + +% converts a string on the stack to an integer +FUNCTION {string.to.integer} +{ duplicate$ text.length$ 'namesleft := + #1 'nameptr := + #0 'numnames := + { nameptr namesleft > not } + { duplicate$ nameptr #1 substring$ + char.to.integer numnames bump.int.mag + + 'numnames := + nameptr #1 + + 'nameptr := + } + while$ +pop$ +numnames +} + + + + +% The output routines write out the *next* to the top (previous) item on the +% stack, adding punctuation and such as needed. Since IEEEtran.bst maintains +% the output status for the top two items on the stack, these output +% routines have to consider the previous output status (which corresponds to +% the item that is being output). Full independent control of punctuation, +% closing quote marks, spacing, and newblock is provided. +% +% "output.nonnull" does not check for the presence of a previous empty +% item. +% +% "output" does check for the presence of a previous empty item and will +% remove an empty item rather than outputing it. +% +% "output.warn" is like "output", but will issue a warning if it detects +% an empty item. + +FUNCTION {output.nonnull} +{ swap$ + prev.status.punct punct.comma = + { "," * } + { skip$ } + if$ + prev.status.punct punct.period = + { add.period$ } + { skip$ } + if$ + prev.status.quote quote.close = + { "''" * } + { skip$ } + if$ + prev.status.space space.normal = + { " " * } + { skip$ } + if$ + prev.status.space space.large = + { large.space * } + { skip$ } + if$ + write$ + prev.status.nline nline.newblock = + { newline$ "\newblock " write$ } + { skip$ } + if$ +} + +FUNCTION {output} +{ duplicate$ empty$ + 'pop$ + 'output.nonnull + if$ +} + +FUNCTION {output.warn} +{ 't := + duplicate$ empty$ + { pop$ "empty " t * " in " * cite$ * warning$ } + 'output.nonnull + if$ +} + +% "fin.entry" is the output routine that handles the last item of the entry +% (which will be on the top of the stack when "fin.entry" is called). + +FUNCTION {fin.entry} +{ this.status.punct punct.no = + { skip$ } + { add.period$ } + if$ + this.status.quote quote.close = + { "''" * } + { skip$ } + if$ +write$ +newline$ +} + + +FUNCTION {is.last.char.not.punct} +{ duplicate$ + "}" * add.period$ + #-1 #1 substring$ "." = +} + +FUNCTION {is.multiple.pages} +{ 't := + #0 'multiresult := + { multiresult not + t empty$ not + and + } + { t #1 #1 substring$ + duplicate$ "-" = + swap$ duplicate$ "," = + swap$ "+" = + or or + { #1 'multiresult := } + { t #2 global.max$ substring$ 't := } + if$ + } + while$ + multiresult +} + +FUNCTION {capitalize}{ "u" change.case$ "t" change.case$ } + +FUNCTION {emphasize} +{ duplicate$ empty$ + { pop$ "" } + { "\emph{" swap$ * "}" * } + if$ +} + +FUNCTION {do.name.latex.cmd} +{ name.latex.cmd + empty$ + { skip$ } + { name.latex.cmd "{" * swap$ * "}" * } + if$ +} + +% IEEEtran.bst uses its own \BIBforeignlanguage command which directly +% invokes the TeX hyphenation patterns without the need of the Babel +% package. Babel does a lot more than switch hyphenation patterns and +% its loading can cause unintended effects in many class files (such as +% IEEEtran.cls). +FUNCTION {select.language} +{ duplicate$ empty$ 'pop$ + { language empty$ 'skip$ + { "\BIBforeignlanguage{" language * "}{" * swap$ * "}" * } + if$ + } + if$ +} + +FUNCTION {tie.or.space.prefix} +{ duplicate$ text.length$ #3 < + { "~" } + { " " } + if$ + swap$ +} + +FUNCTION {get.bbl.editor} +{ editor num.names$ #1 > 'bbl.editors 'bbl.editor if$ } + +FUNCTION {space.word}{ " " swap$ * " " * } + + +% Field Conditioners, Converters, Checkers and External Interfaces + +FUNCTION {empty.field.to.null.string} +{ duplicate$ empty$ + { pop$ "" } + { skip$ } + if$ +} + +FUNCTION {either.or.check} +{ empty$ + { pop$ } + { "can't use both " swap$ * " fields in " * cite$ * warning$ } + if$ +} + +FUNCTION {empty.entry.warn} +{ author empty$ title empty$ howpublished empty$ + month empty$ year empty$ note empty$ url empty$ + and and and and and and + { "all relevant fields are empty in " cite$ * warning$ } + 'skip$ + if$ +} + + +% The bibinfo system provides a way for the electronic parsing/acquisition +% of a bibliography's contents as is done by ReVTeX. For example, a field +% could be entered into the bibliography as: +% \bibinfo{volume}{2} +% Only the "2" would show up in the document, but the LaTeX \bibinfo command +% could do additional things with the information. IEEEtran.bst does provide +% a \bibinfo command via "\providecommand{\bibinfo}[2]{#2}". However, it is +% currently not used as the bogus bibinfo functions defined here output the +% entry values directly without the \bibinfo wrapper. The bibinfo functions +% themselves (and the calls to them) are retained for possible future use. +% +% bibinfo.check avoids acting on missing fields while bibinfo.warn will +% issue a warning message if a missing field is detected. Prior to calling +% the bibinfo functions, the user should push the field value and then its +% name string, in that order. + +FUNCTION {bibinfo.check} +{ swap$ duplicate$ missing$ + { pop$ pop$ "" } + { duplicate$ empty$ + { swap$ pop$ } + { swap$ pop$ } + if$ + } + if$ +} + +FUNCTION {bibinfo.warn} +{ swap$ duplicate$ missing$ + { swap$ "missing " swap$ * " in " * cite$ * warning$ pop$ "" } + { duplicate$ empty$ + { swap$ "empty " swap$ * " in " * cite$ * warning$ } + { swap$ pop$ } + if$ + } + if$ +} + + +% IEEE separates large numbers with more than 4 digits into groups of +% three. IEEE uses a small space to separate these number groups. +% Typical applications include patent and page numbers. + +% number of consecutive digits required to trigger the group separation. +FUNCTION {large.number.trigger}{ #5 } + +% For numbers longer than the trigger, this is the blocksize of the groups. +% The blocksize must be less than the trigger threshold, and 2 * blocksize +% must be greater than the trigger threshold (can't do more than one +% separation on the initial trigger). +FUNCTION {large.number.blocksize}{ #3 } + +% What is actually inserted between the number groups. +FUNCTION {large.number.separator}{ "\," } + +% So as to save on integer variables by reusing existing ones, numnames +% holds the current number of consecutive digits read and nameptr holds +% the number that will trigger an inserted space. +FUNCTION {large.number.separate} +{ 't := + "" + #0 'numnames := + large.number.trigger 'nameptr := + { t empty$ not } + { t #-1 #1 substring$ is.num + { numnames #1 + 'numnames := } + { #0 'numnames := + large.number.trigger 'nameptr := + } + if$ + t #-1 #1 substring$ swap$ * + t #-2 global.max$ substring$ 't := + numnames nameptr = + { duplicate$ #1 nameptr large.number.blocksize - substring$ swap$ + nameptr large.number.blocksize - #1 + global.max$ substring$ + large.number.separator swap$ * * + nameptr large.number.blocksize - 'numnames := + large.number.blocksize #1 + 'nameptr := + } + { skip$ } + if$ + } + while$ +} + +% Converts all single dashes "-" to double dashes "--". +FUNCTION {n.dashify} +{ large.number.separate + 't := + "" + { t empty$ not } + { t #1 #1 substring$ "-" = + { t #1 #2 substring$ "--" = not + { "--" * + t #2 global.max$ substring$ 't := + } + { { t #1 #1 substring$ "-" = } + { "-" * + t #2 global.max$ substring$ 't := + } + while$ + } + if$ + } + { t #1 #1 substring$ * + t #2 global.max$ substring$ 't := + } + if$ + } + while$ +} + + +% This function detects entries with names that are identical to that of +% the previous entry and replaces the repeated names with dashes (if the +% "is.dash.repeated.names" user control is nonzero). +FUNCTION {name.or.dash} +{ 's := + oldname empty$ + { s 'oldname := s } + { s oldname = + { is.dash.repeated.names + { repeated.name.dashes } + { s 'oldname := s } + if$ + } + { s 'oldname := s } + if$ + } + if$ +} + +% Converts the number string on the top of the stack to +% "numerical ordinal form" (e.g., "7" to "7th"). There is +% no artificial limit to the upper bound of the numbers as the +% least significant digit always determines the ordinal form. +FUNCTION {num.to.ordinal} +{ duplicate$ #-1 #1 substring$ "1" = + { bbl.st * } + { duplicate$ #-1 #1 substring$ "2" = + { bbl.nd * } + { duplicate$ #-1 #1 substring$ "3" = + { bbl.rd * } + { bbl.th * } + if$ + } + if$ + } + if$ +} + +% If the string on the top of the stack begins with a number, +% (e.g., 11th) then replace the string with the leading number +% it contains. Otherwise retain the string as-is. s holds the +% extracted number, t holds the part of the string that remains +% to be scanned. +FUNCTION {extract.num} +{ duplicate$ 't := + "" 's := + { t empty$ not } + { t #1 #1 substring$ + t #2 global.max$ substring$ 't := + duplicate$ is.num + { s swap$ * 's := } + { pop$ "" 't := } + if$ + } + while$ + s empty$ + 'skip$ + { pop$ s } + if$ +} + +% Converts the word number string on the top of the stack to +% Arabic string form. Will be successful up to "tenth". +FUNCTION {word.to.num} +{ duplicate$ "l" change.case$ 's := + s "first" = + { pop$ "1" } + { skip$ } + if$ + s "second" = + { pop$ "2" } + { skip$ } + if$ + s "third" = + { pop$ "3" } + { skip$ } + if$ + s "fourth" = + { pop$ "4" } + { skip$ } + if$ + s "fifth" = + { pop$ "5" } + { skip$ } + if$ + s "sixth" = + { pop$ "6" } + { skip$ } + if$ + s "seventh" = + { pop$ "7" } + { skip$ } + if$ + s "eighth" = + { pop$ "8" } + { skip$ } + if$ + s "ninth" = + { pop$ "9" } + { skip$ } + if$ + s "tenth" = + { pop$ "10" } + { skip$ } + if$ +} + + +% Converts the string on the top of the stack to numerical +% ordinal (e.g., "11th") form. +FUNCTION {convert.edition} +{ duplicate$ empty$ 'skip$ + { duplicate$ #1 #1 substring$ is.num + { extract.num + num.to.ordinal + } + { word.to.num + duplicate$ #1 #1 substring$ is.num + { num.to.ordinal } + { "edition ordinal word " quote$ * edition * quote$ * + " may be too high (or improper) for conversion" * " in " * cite$ * warning$ + } + if$ + } + if$ + } + if$ +} + + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% LATEX BIBLIOGRAPHY CODE %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FUNCTION {start.entry} +{ newline$ + "\bibitem{" write$ + cite$ write$ + "}" write$ + newline$ + "" + initialize.prev.this.status +} + +% Here we write out all the LaTeX code that we will need. The most involved +% code sequences are those that control the alternate interword spacing and +% foreign language hyphenation patterns. The heavy use of \providecommand +% gives users a way to override the defaults. Special thanks to Javier Bezos, +% Johannes Braams, Robin Fairbairns, Heiko Oberdiek, Donald Arseneau and all +% the other gurus on comp.text.tex for their help and advice on the topic of +% \selectlanguage, Babel and BibTeX. +FUNCTION {begin.bib} +{ "% Generated by IEEEtran.bst, version: " bst.file.version * " (" * bst.file.date * ")" * + write$ newline$ + preamble$ empty$ 'skip$ + { preamble$ write$ newline$ } + if$ + "\begin{thebibliography}{" longest.label * "}" * + write$ newline$ + "\providecommand{\url}[1]{#1}" + write$ newline$ + "\csname url@samestyle\endcsname" + write$ newline$ + "\providecommand{\newblock}{\relax}" + write$ newline$ + "\providecommand{\bibinfo}[2]{#2}" + write$ newline$ + "\providecommand{\BIBentrySTDinterwordspacing}{\spaceskip=0pt\relax}" + write$ newline$ + "\providecommand{\BIBentryALTinterwordstretchfactor}{" + ALTinterwordstretchfactor * "}" * + write$ newline$ + "\providecommand{\BIBentryALTinterwordspacing}{\spaceskip=\fontdimen2\font plus " + write$ newline$ + "\BIBentryALTinterwordstretchfactor\fontdimen3\font minus \fontdimen4\font\relax}" + write$ newline$ + "\providecommand{\BIBforeignlanguage}[2]{{%" + write$ newline$ + "\expandafter\ifx\csname l@#1\endcsname\relax" + write$ newline$ + "\typeout{** WARNING: IEEEtran.bst: No hyphenation pattern has been}%" + write$ newline$ + "\typeout{** loaded for the language `#1'. Using the pattern for}%" + write$ newline$ + "\typeout{** the default language instead.}%" + write$ newline$ + "\else" + write$ newline$ + "\language=\csname l@#1\endcsname" + write$ newline$ + "\fi" + write$ newline$ + "#2}}" + write$ newline$ + "\providecommand{\BIBdecl}{\relax}" + write$ newline$ + "\BIBdecl" + write$ newline$ +} + +FUNCTION {end.bib} +{ newline$ "\end{thebibliography}" write$ newline$ } + +FUNCTION {if.url.alt.interword.spacing} +{ is.use.alt.interword.spacing + {url empty$ 'skip$ {"\BIBentryALTinterwordspacing" write$ newline$} if$} + { skip$ } + if$ +} + +FUNCTION {if.url.std.interword.spacing} +{ is.use.alt.interword.spacing + {url empty$ 'skip$ {"\BIBentrySTDinterwordspacing" write$ newline$} if$} + { skip$ } + if$ +} + + + + +%%%%%%%%%%%%%%%%%%%%%%%% +%% LONGEST LABEL PASS %% +%%%%%%%%%%%%%%%%%%%%%%%% + +FUNCTION {initialize.longest.label} +{ "" 'longest.label := + #1 'number.label := + #0 'longest.label.width := +} + +FUNCTION {longest.label.pass} +{ type$ "ieeetranbstctl" = + { skip$ } + { number.label int.to.str$ 'label := + number.label #1 + 'number.label := + label width$ longest.label.width > + { label 'longest.label := + label width$ 'longest.label.width := + } + { skip$ } + if$ + } + if$ +} + + + + +%%%%%%%%%%%%%%%%%%%%% +%% FORMAT HANDLERS %% +%%%%%%%%%%%%%%%%%%%%% + +%% Lower Level Formats (used by higher level formats) + +FUNCTION {format.address.org.or.pub.date} +{ 't := + "" + year empty$ + { "empty year in " cite$ * warning$ } + { skip$ } + if$ + address empty$ t empty$ and + year empty$ and month empty$ and + { skip$ } + { this.to.prev.status + this.status.std + cap.status.std + address "address" bibinfo.check * + t empty$ + { skip$ } + { punct.period 'prev.status.punct := + space.large 'prev.status.space := + address empty$ + { skip$ } + { ": " * } + if$ + t * + } + if$ + year empty$ month empty$ and + { skip$ } + { t empty$ address empty$ and + { skip$ } + { ", " * } + if$ + month empty$ + { year empty$ + { skip$ } + { year "year" bibinfo.check * } + if$ + } + { month "month" bibinfo.check * + year empty$ + { skip$ } + { " " * year "year" bibinfo.check * } + if$ + } + if$ + } + if$ + } + if$ +} + + +FUNCTION {format.names} +{ 'bibinfo := + duplicate$ empty$ 'skip$ { + this.to.prev.status + this.status.std + 's := + "" 't := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr + name.format.string + format.name$ + bibinfo bibinfo.check + 't := + nameptr #1 > + { nameptr num.names.shown.with.forced.et.al #1 + = + numnames max.num.names.before.forced.et.al > + is.forced.et.al and and + { "others" 't := + #1 'namesleft := + } + { skip$ } + if$ + namesleft #1 > + { ", " * t do.name.latex.cmd * } + { s nameptr "{ll}" format.name$ duplicate$ "others" = + { 't := } + { pop$ } + if$ + t "others" = + { " " * bbl.etal emphasize * } + { numnames #2 > + { "," * } + { skip$ } + if$ + bbl.and + space.word * t do.name.latex.cmd * + } + if$ + } + if$ + } + { t do.name.latex.cmd } + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ + cap.status.std + } if$ +} + + + + +%% Higher Level Formats + +%% addresses/locations + +FUNCTION {format.address} +{ address duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + } + if$ +} + + + +%% author/editor names + +FUNCTION {format.authors}{ author "author" format.names } + +FUNCTION {format.editors} +{ editor "editor" format.names duplicate$ empty$ 'skip$ + { ", " * + get.bbl.editor + capitalize + * + } + if$ +} + + + +%% date + +FUNCTION {format.date} +{ + month "month" bibinfo.check duplicate$ empty$ + year "year" bibinfo.check duplicate$ empty$ + { swap$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + "there's a month but no year in " cite$ * warning$ } + if$ + * + } + { this.to.prev.status + this.status.std + cap.status.std + swap$ 'skip$ + { + swap$ + " " * swap$ + } + if$ + * + } + if$ +} + +FUNCTION {format.date.electronic} +{ month "month" bibinfo.check duplicate$ empty$ + year "year" bibinfo.check duplicate$ empty$ + { swap$ + { pop$ } + { "there's a month but no year in " cite$ * warning$ + pop$ ")" * "(" swap$ * + this.to.prev.status + punct.no 'this.status.punct := + space.normal 'this.status.space := + quote.no 'this.status.quote := + cap.yes 'status.cap := + } + if$ + } + { swap$ + { swap$ pop$ ")" * "(" swap$ * } + { "(" swap$ * ", " * swap$ * ")" * } + if$ + this.to.prev.status + punct.no 'this.status.punct := + space.normal 'this.status.space := + quote.no 'this.status.quote := + cap.yes 'status.cap := + } + if$ +} + + + +%% edition/title + +% Note: IEEE considers the edition to be closely associated with +% the title of a book. So, in IEEEtran.bst the edition is normally handled +% within the formatting of the title. The format.edition function is +% retained here for possible future use. +FUNCTION {format.edition} +{ edition duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + convert.edition + status.cap + { "t" } + { "l" } + if$ change.case$ + "edition" bibinfo.check + "~" * bbl.edition * + cap.status.std + } + if$ +} + +% This is used to format the booktitle of a conference proceedings. +% Here we use the "intype" field to provide the user a way to +% override the word "in" (e.g., with things like "presented at") +% Use of intype stops the emphasis of the booktitle to indicate that +% we no longer mean the written conference proceedings, but the +% conference itself. +FUNCTION {format.in.booktitle} +{ booktitle "booktitle" bibinfo.check duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + select.language + intype missing$ + { emphasize + bbl.in " " * + } + { intype " " * } + if$ + swap$ * + cap.status.std + } + if$ +} + +% This is used to format the booktitle of collection. +% Here the "intype" field is not supported, but "edition" is. +FUNCTION {format.in.booktitle.edition} +{ booktitle "booktitle" bibinfo.check duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + select.language + emphasize + edition empty$ 'skip$ + { ", " * + edition + convert.edition + "l" change.case$ + * "~" * bbl.edition * + } + if$ + bbl.in " " * swap$ * + cap.status.std + } + if$ +} + +FUNCTION {format.article.title} +{ title duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + "t" change.case$ + } + if$ + "title" bibinfo.check + duplicate$ empty$ 'skip$ + { quote.close 'this.status.quote := + is.last.char.not.punct + { punct.std 'this.status.punct := } + { punct.no 'this.status.punct := } + if$ + select.language + "``" swap$ * + cap.status.std + } + if$ +} + +FUNCTION {format.article.title.electronic} +{ title duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + "t" change.case$ + } + if$ + "title" bibinfo.check + duplicate$ empty$ + { skip$ } + { select.language } + if$ +} + +FUNCTION {format.book.title.edition} +{ title "title" bibinfo.check + duplicate$ empty$ + { "empty title in " cite$ * warning$ } + { this.to.prev.status + this.status.std + select.language + emphasize + edition empty$ 'skip$ + { ", " * + edition + convert.edition + status.cap + { "t" } + { "l" } + if$ + change.case$ + * "~" * bbl.edition * + } + if$ + cap.status.std + } + if$ +} + +FUNCTION {format.book.title} +{ title "title" bibinfo.check + duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + select.language + emphasize + } + if$ +} + + + +%% journal + +FUNCTION {format.journal} +{ journal duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + select.language + emphasize + } + if$ +} + + + +%% how published + +FUNCTION {format.howpublished} +{ howpublished duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + } + if$ +} + + + +%% institutions/organization/publishers/school + +FUNCTION {format.institution} +{ institution duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + } + if$ +} + +FUNCTION {format.organization} +{ organization duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + } + if$ +} + +FUNCTION {format.address.publisher.date} +{ publisher "publisher" bibinfo.warn format.address.org.or.pub.date } + +FUNCTION {format.address.publisher.date.nowarn} +{ publisher "publisher" bibinfo.check format.address.org.or.pub.date } + +FUNCTION {format.address.organization.date} +{ organization "organization" bibinfo.check format.address.org.or.pub.date } + +FUNCTION {format.school} +{ school duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + cap.status.std + } + if$ +} + + + +%% volume/number/series/chapter/pages + +FUNCTION {format.volume} +{ volume empty.field.to.null.string + duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + bbl.volume + status.cap + { capitalize } + { skip$ } + if$ + swap$ tie.or.space.prefix + "volume" bibinfo.check + * * + cap.status.std + } + if$ +} + +FUNCTION {format.number} +{ number empty.field.to.null.string + duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + status.cap + { bbl.number capitalize } + { bbl.number } + if$ + swap$ tie.or.space.prefix + "number" bibinfo.check + * * + cap.status.std + } + if$ +} + +FUNCTION {format.number.if.use.for.article} +{ is.use.number.for.article + { format.number } + { "" } + if$ +} + +% IEEE does not seem to tie the series so closely with the volume +% and number as is done in other bibliography styles. Instead the +% series is treated somewhat like an extension of the title. +FUNCTION {format.series} +{ series empty$ + { "" } + { this.to.prev.status + this.status.std + bbl.series " " * + series "series" bibinfo.check * + cap.status.std + } + if$ +} + + +FUNCTION {format.chapter} +{ chapter empty$ + { "" } + { this.to.prev.status + this.status.std + type empty$ + { bbl.chapter } + { type "l" change.case$ + "type" bibinfo.check + } + if$ + chapter tie.or.space.prefix + "chapter" bibinfo.check + * * + cap.status.std + } + if$ +} + + +% The intended use of format.paper is for paper numbers of inproceedings. +% The paper type can be overridden via the type field. +% We allow the type to be displayed even if the paper number is absent +% for things like "postdeadline paper" +FUNCTION {format.paper} +{ is.use.paper + { paper empty$ + { type empty$ + { "" } + { this.to.prev.status + this.status.std + type "type" bibinfo.check + cap.status.std + } + if$ + } + { this.to.prev.status + this.status.std + type empty$ + { bbl.paper } + { type "type" bibinfo.check } + if$ + " " * paper + "paper" bibinfo.check + * + cap.status.std + } + if$ + } + { "" } + if$ +} + + +FUNCTION {format.pages} +{ pages duplicate$ empty$ 'skip$ + { this.to.prev.status + this.status.std + duplicate$ is.multiple.pages + { + bbl.pages swap$ + n.dashify + } + { + bbl.page swap$ + } + if$ + tie.or.space.prefix + "pages" bibinfo.check + * * + cap.status.std + } + if$ +} + + + +%% technical report number + +FUNCTION {format.tech.report.number} +{ number "number" bibinfo.check + this.to.prev.status + this.status.std + cap.status.std + type duplicate$ empty$ + { pop$ + bbl.techrep + } + { skip$ } + if$ + "type" bibinfo.check + swap$ duplicate$ empty$ + { pop$ } + { tie.or.space.prefix * * } + if$ +} + + + +%% note + +FUNCTION {format.note} +{ note empty$ + { "" } + { this.to.prev.status + this.status.std + punct.period 'this.status.punct := + note #1 #1 substring$ + duplicate$ "{" = + { skip$ } + { status.cap + { "u" } + { "l" } + if$ + change.case$ + } + if$ + note #2 global.max$ substring$ * "note" bibinfo.check + cap.yes 'status.cap := + } + if$ +} + + + +%% patent + +FUNCTION {format.patent.date} +{ this.to.prev.status + this.status.std + year empty$ + { monthfiled duplicate$ empty$ + { "monthfiled" bibinfo.check pop$ "" } + { "monthfiled" bibinfo.check } + if$ + dayfiled duplicate$ empty$ + { "dayfiled" bibinfo.check pop$ "" * } + { "dayfiled" bibinfo.check + monthfiled empty$ + { "dayfiled without a monthfiled in " cite$ * warning$ + * + } + { " " swap$ * * } + if$ + } + if$ + yearfiled empty$ + { "no year or yearfiled in " cite$ * warning$ } + { yearfiled "yearfiled" bibinfo.check + swap$ + duplicate$ empty$ + { pop$ } + { ", " * swap$ * } + if$ + } + if$ + } + { month duplicate$ empty$ + { "month" bibinfo.check pop$ "" } + { "month" bibinfo.check } + if$ + day duplicate$ empty$ + { "day" bibinfo.check pop$ "" * } + { "day" bibinfo.check + month empty$ + { "day without a month in " cite$ * warning$ + * + } + { " " swap$ * * } + if$ + } + if$ + year "year" bibinfo.check + swap$ + duplicate$ empty$ + { pop$ } + { ", " * swap$ * } + if$ + } + if$ + cap.status.std +} + +FUNCTION {format.patent.nationality.type.number} +{ this.to.prev.status + this.status.std + nationality duplicate$ empty$ + { "nationality" bibinfo.warn pop$ "" } + { "nationality" bibinfo.check + duplicate$ "l" change.case$ "united states" = + { pop$ bbl.patentUS } + { skip$ } + if$ + " " * + } + if$ + type empty$ + { bbl.patent "type" bibinfo.check } + { type "type" bibinfo.check } + if$ + * + number duplicate$ empty$ + { "number" bibinfo.warn pop$ } + { "number" bibinfo.check + large.number.separate + swap$ " " * swap$ * + } + if$ + cap.status.std +} + + + +%% standard + +FUNCTION {format.organization.institution.standard.type.number} +{ this.to.prev.status + this.status.std + organization duplicate$ empty$ + { pop$ + institution duplicate$ empty$ + { "institution" bibinfo.warn } + { "institution" bibinfo.warn " " * } + if$ + } + { "organization" bibinfo.warn " " * } + if$ + type empty$ + { bbl.standard "type" bibinfo.check } + { type "type" bibinfo.check } + if$ + * + number duplicate$ empty$ + { "number" bibinfo.check pop$ } + { "number" bibinfo.check + large.number.separate + swap$ " " * swap$ * + } + if$ + cap.status.std +} + +FUNCTION {format.revision} +{ revision empty$ + { "" } + { this.to.prev.status + this.status.std + bbl.revision + revision tie.or.space.prefix + "revision" bibinfo.check + * * + cap.status.std + } + if$ +} + + +%% thesis + +FUNCTION {format.master.thesis.type} +{ this.to.prev.status + this.status.std + type empty$ + { + bbl.mthesis + } + { + type "type" bibinfo.check + } + if$ +cap.status.std +} + +FUNCTION {format.phd.thesis.type} +{ this.to.prev.status + this.status.std + type empty$ + { + bbl.phdthesis + } + { + type "type" bibinfo.check + } + if$ +cap.status.std +} + + + +%% URL + +FUNCTION {format.url} +{ url empty$ + { "" } + { this.to.prev.status + this.status.std + cap.yes 'status.cap := + name.url.prefix " " * + "\url{" * url * "}" * + punct.no 'this.status.punct := + punct.period 'prev.status.punct := + space.normal 'this.status.space := + space.normal 'prev.status.space := + quote.no 'this.status.quote := + } + if$ +} + + + + +%%%%%%%%%%%%%%%%%%%% +%% ENTRY HANDLERS %% +%%%%%%%%%%%%%%%%%%%% + + +% Note: In many journals, IEEE (or the authors) tend not to show the number +% for articles, so the display of the number is controlled here by the +% switch "is.use.number.for.article" +FUNCTION {article} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.journal "journal" bibinfo.check "journal" output.warn + format.volume output + format.number.if.use.for.article output + format.pages output + format.date "year" output.warn + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {book} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + author empty$ + { format.editors "author and editor" output.warn } + { format.authors output.nonnull } + if$ + name.or.dash + format.book.title.edition output + format.series output + author empty$ + { skip$ } + { format.editors output } + if$ + format.address.publisher.date output + format.volume output + format.number output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {booklet} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.article.title "title" output.warn + format.howpublished "howpublished" bibinfo.check output + format.organization "organization" bibinfo.check output + format.address "address" bibinfo.check output + format.date output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {electronic} +{ std.status.using.period + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.date.electronic output + format.article.title.electronic output + format.howpublished "howpublished" bibinfo.check output + format.organization "organization" bibinfo.check output + format.address "address" bibinfo.check output + format.note output + format.url output + fin.entry + empty.entry.warn + if.url.std.interword.spacing +} + +FUNCTION {inbook} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + author empty$ + { format.editors "author and editor" output.warn } + { format.authors output.nonnull } + if$ + name.or.dash + format.book.title.edition output + format.series output + format.address.publisher.date output + format.volume output + format.number output + format.chapter output + format.pages output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {incollection} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.in.booktitle.edition "booktitle" output.warn + format.series output + format.editors output + format.address.publisher.date.nowarn output + format.volume output + format.number output + format.chapter output + format.pages output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {inproceedings} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.in.booktitle "booktitle" output.warn + format.series output + format.editors output + format.volume output + format.number output + publisher empty$ + { format.address.organization.date output } + { format.organization "organization" bibinfo.check output + format.address.publisher.date output + } + if$ + format.paper output + format.pages output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {manual} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.book.title.edition "title" output.warn + format.howpublished "howpublished" bibinfo.check output + format.organization "organization" bibinfo.check output + format.address "address" bibinfo.check output + format.date output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {mastersthesis} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.master.thesis.type output.nonnull + format.school "school" bibinfo.warn output + format.address "address" bibinfo.check output + format.date "year" output.warn + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {misc} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.article.title output + format.howpublished "howpublished" bibinfo.check output + format.organization "organization" bibinfo.check output + format.address "address" bibinfo.check output + format.pages output + format.date output + format.note output + format.url output + fin.entry + empty.entry.warn + if.url.std.interword.spacing +} + +FUNCTION {patent} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.article.title output + format.patent.nationality.type.number output + format.patent.date output + format.note output + format.url output + fin.entry + empty.entry.warn + if.url.std.interword.spacing +} + +FUNCTION {periodical} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.editors output + name.or.dash + format.book.title "title" output.warn + format.series output + format.volume output + format.number output + format.organization "organization" bibinfo.check output + format.date "year" output.warn + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {phdthesis} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.phd.thesis.type output.nonnull + format.school "school" bibinfo.warn output + format.address "address" bibinfo.check output + format.date "year" output.warn + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {proceedings} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.editors output + name.or.dash + format.book.title "title" output.warn + format.series output + format.volume output + format.number output + publisher empty$ + { format.address.organization.date output } + { format.organization "organization" bibinfo.check output + format.address.publisher.date output + } + if$ + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {standard} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors output + name.or.dash + format.book.title "title" output.warn + format.howpublished "howpublished" bibinfo.check output + format.organization.institution.standard.type.number output + format.revision output + format.date output + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {techreport} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.howpublished "howpublished" bibinfo.check output + format.institution "institution" bibinfo.warn output + format.address "address" bibinfo.check output + format.tech.report.number output.nonnull + format.date "year" output.warn + format.note output + format.url output + fin.entry + if.url.std.interword.spacing +} + +FUNCTION {unpublished} +{ std.status.using.comma + start.entry + if.url.alt.interword.spacing + format.authors "author" output.warn + name.or.dash + format.article.title "title" output.warn + format.date output + format.note "note" output.warn + format.url output + fin.entry + if.url.std.interword.spacing +} + + +% The special entry type which provides the user interface to the +% BST controls +FUNCTION {IEEEtranBSTCTL} +{ is.print.banners.to.terminal + { "** IEEEtran BST control entry " quote$ * cite$ * quote$ * " detected." * + top$ + } + { skip$ } + if$ + CTLuse_article_number + empty$ + { skip$ } + { CTLuse_article_number + yes.no.to.int + 'is.use.number.for.article := + } + if$ + CTLuse_paper + empty$ + { skip$ } + { CTLuse_paper + yes.no.to.int + 'is.use.paper := + } + if$ + CTLuse_forced_etal + empty$ + { skip$ } + { CTLuse_forced_etal + yes.no.to.int + 'is.forced.et.al := + } + if$ + CTLmax_names_forced_etal + empty$ + { skip$ } + { CTLmax_names_forced_etal + string.to.integer + 'max.num.names.before.forced.et.al := + } + if$ + CTLnames_show_etal + empty$ + { skip$ } + { CTLnames_show_etal + string.to.integer + 'num.names.shown.with.forced.et.al := + } + if$ + CTLuse_alt_spacing + empty$ + { skip$ } + { CTLuse_alt_spacing + yes.no.to.int + 'is.use.alt.interword.spacing := + } + if$ + CTLalt_stretch_factor + empty$ + { skip$ } + { CTLalt_stretch_factor + 'ALTinterwordstretchfactor := + "\renewcommand{\BIBentryALTinterwordstretchfactor}{" + ALTinterwordstretchfactor * "}" * + write$ newline$ + } + if$ + CTLdash_repeated_names + empty$ + { skip$ } + { CTLdash_repeated_names + yes.no.to.int + 'is.dash.repeated.names := + } + if$ + CTLname_format_string + empty$ + { skip$ } + { CTLname_format_string + 'name.format.string := + } + if$ + CTLname_latex_cmd + empty$ + { skip$ } + { CTLname_latex_cmd + 'name.latex.cmd := + } + if$ + CTLname_url_prefix + missing$ + { skip$ } + { CTLname_url_prefix + 'name.url.prefix := + } + if$ + + + num.names.shown.with.forced.et.al max.num.names.before.forced.et.al > + { "CTLnames_show_etal cannot be greater than CTLmax_names_forced_etal in " cite$ * warning$ + max.num.names.before.forced.et.al 'num.names.shown.with.forced.et.al := + } + { skip$ } + if$ +} + + +%%%%%%%%%%%%%%%%%%% +%% ENTRY ALIASES %% +%%%%%%%%%%%%%%%%%%% +FUNCTION {conference}{inproceedings} +FUNCTION {online}{electronic} +FUNCTION {internet}{electronic} +FUNCTION {webpage}{electronic} +FUNCTION {www}{electronic} +FUNCTION {default.type}{misc} + + + +%%%%%%%%%%%%%%%%%% +%% MAIN PROGRAM %% +%%%%%%%%%%%%%%%%%% + +READ + +EXECUTE {initialize.controls} +EXECUTE {initialize.status.constants} +EXECUTE {banner.message} + +EXECUTE {initialize.longest.label} +ITERATE {longest.label.pass} + +EXECUTE {begin.bib} +ITERATE {call.type$} +EXECUTE {end.bib} + +EXECUTE{completed.message} + + +%% That's all folks, mds. diff --git a/spec/consensus/consensus-paper/IEEEtran.cls b/spec/consensus/consensus-paper/IEEEtran.cls new file mode 100644 index 0000000..e360736 --- /dev/null +++ b/spec/consensus/consensus-paper/IEEEtran.cls @@ -0,0 +1,4733 @@ +%% +%% IEEEtran.cls 2011/11/03 version V1.8 based on +%% IEEEtran.cls 2007/03/05 version V1.7a +%% The changes in V1.8 are made with a single goal in mind: +%% to change the look of the output using the [conference] option +%% and the default font size (10pt) to match the Word template more closely. +%% These changes may well have undesired side effects when other options +%% are in force! +%% +%% +%% This is the official IEEE LaTeX class for authors of the Institute of +%% Electrical and Electronics Engineers (IEEE) Transactions journals and +%% conferences. +%% +%% Support sites: +%% http://www.michaelshell.org/tex/ieeetran/ +%% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/ +%% and +%% http://www.ieee.org/ +%% +%% Based on the original 1993 IEEEtran.cls, but with many bug fixes +%% and enhancements (from both JVH and MDS) over the 1996/7 version. +%% +%% +%% Contributors: +%% Gerry Murray (1993), Silvano Balemi (1993), +%% Jon Dixon (1996), Peter N"uchter (1996), +%% Juergen von Hagen (2000), and Michael Shell (2001-2007) +%% +%% +%% Copyright (c) 1993-2000 by Gerry Murray, Silvano Balemi, +%% Jon Dixon, Peter N"uchter, +%% Juergen von Hagen +%% and +%% Copyright (c) 2001-2007 by Michael Shell +%% +%% Current maintainer (V1.3 to V1.7): Michael Shell +%% See: +%% http://www.michaelshell.org/ +%% for current contact information. +%% +%% Special thanks to Peter Wilson (CUA) and Donald Arseneau +%% for allowing the inclusion of the \@ifmtarg command +%% from their ifmtarg LaTeX package. +%% +%%************************************************************************* +%% Legal Notice: +%% This code is offered as-is without any warranty either expressed or +%% implied; without even the implied warranty of MERCHANTABILITY or +%% FITNESS FOR A PARTICULAR PURPOSE! +%% User assumes all risk. +%% In no event shall IEEE or any contributor to this code be liable for +%% any damages or losses, including, but not limited to, incidental, +%% consequential, or any other damages, resulting from the use or misuse +%% of any information contained here. +%% +%% All comments are the opinions of their respective authors and are not +%% necessarily endorsed by the IEEE. +%% +%% This work is distributed under the LaTeX Project Public License (LPPL) +%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used, +%% distributed and modified. A copy of the LPPL, version 1.3, is included +%% in the base LaTeX documentation of all distributions of LaTeX released +%% 2003/12/01 or later. +%% Retain all contribution notices and credits. +%% ** Modified files should be clearly indicated as such, including ** +%% ** renaming them and changing author support contact information. ** +%% +%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex, +%% bare_conf.tex, bare_jrnl.tex, bare_jrnl_compsoc.tex +%% +%% Major changes to the user interface should be indicated by an +%% increase in the version numbers. If a version is a beta, it will +%% be indicated with a BETA suffix, i.e., 1.4 BETA. +%% Small changes can be indicated by appending letters to the version +%% such as "IEEEtran_v14a.cls". +%% In all cases, \Providesclass, any \typeout messages to the user, +%% \IEEEtransversionmajor and \IEEEtransversionminor must reflect the +%% correct version information. +%% The changes should also be documented via source comments. +%%************************************************************************* +%% +% +% Available class options +% e.g., \documentclass[10pt,conference]{IEEEtran} +% +% *** choose only one from each category *** +% +% 9pt, 10pt, 11pt, 12pt +% Sets normal font size. The default is 10pt. +% +% conference, journal, technote, peerreview, peerreviewca +% determines format mode - conference papers, journal papers, +% correspondence papers (technotes), or peer review papers. The user +% should also select 9pt when using technote. peerreview is like +% journal mode, but provides for a single-column "cover" title page for +% anonymous peer review. The paper title (without the author names) is +% repeated at the top of the page after the cover page. For peer review +% papers, the \IEEEpeerreviewmaketitle command must be executed (will +% automatically be ignored for non-peerreview modes) at the place the +% cover page is to end, usually just after the abstract (keywords are +% not normally used with peer review papers). peerreviewca is like +% peerreview, but allows the author names to be entered and formatted +% as with conference mode so that author affiliation and contact +% information can be easily seen on the cover page. +% The default is journal. +% +% draft, draftcls, draftclsnofoot, final +% determines if paper is formatted as a widely spaced draft (for +% handwritten editor comments) or as a properly typeset final version. +% draftcls restricts draft mode to the class file while all other LaTeX +% packages (i.e., \usepackage{graphicx}) will behave as final - allows +% for a draft paper with visible figures, etc. draftclsnofoot is like +% draftcls, but does not display the date and the word "DRAFT" at the foot +% of the pages. If using one of the draft modes, the user will probably +% also want to select onecolumn. +% The default is final. +% +% letterpaper, a4paper +% determines paper size: 8.5in X 11in or 210mm X 297mm. CHANGING THE PAPER +% SIZE WILL NOT ALTER THE TYPESETTING OF THE DOCUMENT - ONLY THE MARGINS +% WILL BE AFFECTED. In particular, documents using the a4paper option will +% have reduced side margins (A4 is narrower than US letter) and a longer +% bottom margin (A4 is longer than US letter). For both cases, the top +% margins will be the same and the text will be horizontally centered. +% For final submission to IEEE, authors should use US letter (8.5 X 11in) +% paper. Note that authors should ensure that all post-processing +% (ps, pdf, etc.) uses the same paper specificiation as the .tex document. +% Problems here are by far the number one reason for incorrect margins. +% IEEEtran will automatically set the default paper size under pdflatex +% (without requiring a change to pdftex.cfg), so this issue is more +% important to dvips users. Fix config.ps, config.pdf, or ~/.dvipsrc for +% dvips, or use the dvips -t papersize option instead as needed. See the +% testflow documentation +% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/testflow +% for more details on dvips paper size configuration. +% The default is letterpaper. +% +% oneside, twoside +% determines if layout follows single sided or two sided (duplex) +% printing. The only notable change is with the headings at the top of +% the pages. +% The default is oneside. +% +% onecolumn, twocolumn +% determines if text is organized into one or two columns per page. One +% column mode is usually used only with draft papers. +% The default is twocolumn. +% +% compsoc +% Use the format of the IEEE Computer Society. +% +% romanappendices +% Use the "Appendix I" convention when numbering appendices. IEEEtran.cls +% now defaults to Alpha "Appendix A" convention - the opposite of what +% v1.6b and earlier did. +% +% captionsoff +% disables the display of the figure/table captions. Some IEEE journals +% request that captions be removed and figures/tables be put on pages +% of their own at the end of an initial paper submission. The endfloat +% package can be used with this class option to achieve this format. +% +% nofonttune +% turns off tuning of the font interword spacing. Maybe useful to those +% not using the standard Times fonts or for those who have already "tuned" +% their fonts. +% The default is to enable IEEEtran to tune font parameters. +% +% +%---------- +% Available CLASSINPUTs provided (all are macros unless otherwise noted): +% \CLASSINPUTbaselinestretch +% \CLASSINPUTinnersidemargin +% \CLASSINPUToutersidemargin +% \CLASSINPUTtoptextmargin +% \CLASSINPUTbottomtextmargin +% +% Available CLASSINFOs provided: +% \ifCLASSINFOpdf (TeX if conditional) +% \CLASSINFOpaperwidth (macro) +% \CLASSINFOpaperheight (macro) +% \CLASSINFOnormalsizebaselineskip (length) +% \CLASSINFOnormalsizeunitybaselineskip (length) +% +% Available CLASSOPTIONs provided: +% all class option flags (TeX if conditionals) unless otherwise noted, +% e.g., \ifCLASSOPTIONcaptionsoff +% point size options provided as a single macro: +% \CLASSOPTIONpt +% which will be defined as 9, 10, 11, or 12 depending on the document's +% normalsize point size. +% also, class option peerreviewca implies the use of class option peerreview +% and classoption draft implies the use of class option draftcls + + + + + +\ProvidesClass{IEEEtran}[2012/11/21 V1.8c by Harald Hanche-Olsen and Anders Christensen] +\typeout{-- Based on V1.7a by Michael Shell} +\typeout{-- See the "IEEEtran_HOWTO" manual for usage information.} +\typeout{-- http://www.michaelshell.org/tex/ieeetran/} +\NeedsTeXFormat{LaTeX2e} + +% IEEEtran.cls version numbers, provided as of V1.3 +% These values serve as a way a .tex file can +% determine if the new features are provided. +% The version number of this IEEEtrans.cls can be obtained from +% these values. i.e., V1.4 +% KEEP THESE AS INTEGERS! i.e., NO {4a} or anything like that- +% (no need to enumerate "a" minor changes here) +\def\IEEEtransversionmajor{1} +\def\IEEEtransversionminor{7} + +% These do nothing, but provide them like in article.cls +\newif\if@restonecol +\newif\if@titlepage + + +% class option conditionals +\newif\ifCLASSOPTIONonecolumn \CLASSOPTIONonecolumnfalse +\newif\ifCLASSOPTIONtwocolumn \CLASSOPTIONtwocolumntrue + +\newif\ifCLASSOPTIONoneside \CLASSOPTIONonesidetrue +\newif\ifCLASSOPTIONtwoside \CLASSOPTIONtwosidefalse + +\newif\ifCLASSOPTIONfinal \CLASSOPTIONfinaltrue +\newif\ifCLASSOPTIONdraft \CLASSOPTIONdraftfalse +\newif\ifCLASSOPTIONdraftcls \CLASSOPTIONdraftclsfalse +\newif\ifCLASSOPTIONdraftclsnofoot \CLASSOPTIONdraftclsnofootfalse + +\newif\ifCLASSOPTIONpeerreview \CLASSOPTIONpeerreviewfalse +\newif\ifCLASSOPTIONpeerreviewca \CLASSOPTIONpeerreviewcafalse + +\newif\ifCLASSOPTIONjournal \CLASSOPTIONjournaltrue +\newif\ifCLASSOPTIONconference \CLASSOPTIONconferencefalse +\newif\ifCLASSOPTIONtechnote \CLASSOPTIONtechnotefalse + +\newif\ifCLASSOPTIONnofonttune \CLASSOPTIONnofonttunefalse + +\newif\ifCLASSOPTIONcaptionsoff \CLASSOPTIONcaptionsofffalse + +\newif\ifCLASSOPTIONcompsoc \CLASSOPTIONcompsocfalse + +\newif\ifCLASSOPTIONromanappendices \CLASSOPTIONromanappendicesfalse + + +% class info conditionals + +% indicates if pdf (via pdflatex) output +\newif\ifCLASSINFOpdf \CLASSINFOpdffalse + + +% V1.6b internal flag to show if using a4paper +\newif\if@IEEEusingAfourpaper \@IEEEusingAfourpaperfalse + + + +% IEEEtran class scratch pad registers +% dimen +\newdimen\@IEEEtrantmpdimenA +\newdimen\@IEEEtrantmpdimenB +% count +\newcount\@IEEEtrantmpcountA +\newcount\@IEEEtrantmpcountB +% token list +\newtoks\@IEEEtrantmptoksA + +% we use \CLASSOPTIONpt so that we can ID the point size (even for 9pt docs) +% as well as LaTeX's \@ptsize to retain some compatability with some +% external packages +\def\@ptsize{0} +% LaTeX does not support 9pt, so we set \@ptsize to 0 - same as that of 10pt +\DeclareOption{9pt}{\def\CLASSOPTIONpt{9}\def\@ptsize{0}} +\DeclareOption{10pt}{\def\CLASSOPTIONpt{10}\def\@ptsize{0}} +\DeclareOption{11pt}{\def\CLASSOPTIONpt{11}\def\@ptsize{1}} +\DeclareOption{12pt}{\def\CLASSOPTIONpt{12}\def\@ptsize{2}} + + + +\DeclareOption{letterpaper}{\setlength{\paperheight}{11in}% + \setlength{\paperwidth}{8.5in}% + \@IEEEusingAfourpaperfalse + \def\CLASSOPTIONpaper{letter}% + \def\CLASSINFOpaperwidth{8.5in}% + \def\CLASSINFOpaperheight{11in}} + + +\DeclareOption{a4paper}{\setlength{\paperheight}{297mm}% + \setlength{\paperwidth}{210mm}% + \@IEEEusingAfourpapertrue + \def\CLASSOPTIONpaper{a4}% + \def\CLASSINFOpaperwidth{210mm}% + \def\CLASSINFOpaperheight{297mm}} + +\DeclareOption{oneside}{\@twosidefalse\@mparswitchfalse + \CLASSOPTIONonesidetrue\CLASSOPTIONtwosidefalse} +\DeclareOption{twoside}{\@twosidetrue\@mparswitchtrue + \CLASSOPTIONtwosidetrue\CLASSOPTIONonesidefalse} + +\DeclareOption{onecolumn}{\CLASSOPTIONonecolumntrue\CLASSOPTIONtwocolumnfalse} +\DeclareOption{twocolumn}{\CLASSOPTIONtwocolumntrue\CLASSOPTIONonecolumnfalse} + +% If the user selects draft, then this class AND any packages +% will go into draft mode. +\DeclareOption{draft}{\CLASSOPTIONdrafttrue\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofootfalse} +% draftcls is for a draft mode which will not affect any packages +% used by the document. +\DeclareOption{draftcls}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofootfalse} +% draftclsnofoot is like draftcls, but without the footer. +\DeclareOption{draftclsnofoot}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofoottrue} +\DeclareOption{final}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclsfalse + \CLASSOPTIONdraftclsnofootfalse} + +\DeclareOption{journal}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournaltrue\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{conference}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencetrue\CLASSOPTIONtechnotefalse} + +\DeclareOption{technote}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotetrue} + +\DeclareOption{peerreview}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{peerreviewca}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcatrue + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{nofonttune}{\CLASSOPTIONnofonttunetrue} + +\DeclareOption{captionsoff}{\CLASSOPTIONcaptionsofftrue} + +\DeclareOption{compsoc}{\CLASSOPTIONcompsoctrue} + +\DeclareOption{romanappendices}{\CLASSOPTIONromanappendicestrue} + + +% default to US letter paper, 10pt, twocolumn, one sided, final, journal +\ExecuteOptions{letterpaper,10pt,twocolumn,oneside,final,journal} +% overrride these defaults per user requests +\ProcessOptions + + + +% Computer Society conditional execution command +\long\def\@IEEEcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\relax#1\relax\fi\relax} +% inverse +\long\def\@IEEEnotcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\else\relax#1\relax\fi\relax} +% compsoc conference +\long\def\@IEEEcompsocconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\relax#1\relax\fi\fi\relax} +% compsoc not conference +\long\def\@IEEEcompsocnotconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\else\relax#1\relax\fi\fi\relax} + + +% IEEE uses Times Roman font, so we'll default to Times. +% These three commands make up the entire times.sty package. +\renewcommand{\sfdefault}{phv} +\renewcommand{\rmdefault}{ptm} +\renewcommand{\ttdefault}{pcr} + +\@IEEEcompsoconly{\typeout{-- Using IEEE Computer Society mode.}} + +% V1.7 compsoc nonconference papers, use Palatino/Palladio as the main text font, +% not Times Roman. +\@IEEEcompsocnotconfonly{\renewcommand{\rmdefault}{ppl}} + +% enable Times/Palatino main text font +\normalfont\selectfont + + + + + +% V1.7 conference notice message hook +\def\@IEEEconsolenoticeconference{\typeout{}% +\typeout{** Conference Paper **}% +\typeout{Before submitting the final camera ready copy, remember to:}% +\typeout{}% +\typeout{ 1. Manually equalize the lengths of two columns on the last page}% +\typeout{ of your paper;}% +\typeout{}% +\typeout{ 2. Ensure that any PostScript and/or PDF output post-processing}% +\typeout{ uses only Type 1 fonts and that every step in the generation}% +\typeout{ process uses the appropriate paper size.}% +\typeout{}} + + +% we can send console reminder messages to the user here +\AtEndDocument{\ifCLASSOPTIONconference\@IEEEconsolenoticeconference\fi} + + +% warn about the use of single column other than for draft mode +\ifCLASSOPTIONtwocolumn\else% + \ifCLASSOPTIONdraftcls\else% + \typeout{** ATTENTION: Single column mode is not typically used with IEEE publications.}% + \fi% +\fi + + +% V1.7 improved paper size setting code. +% Set pdfpage and dvips paper sizes. Conditional tests are similar to that +% of ifpdf.sty. Retain within {} to ensure tested macros are never altered, +% even if only effect is to set them to \relax. +% if \pdfoutput is undefined or equal to relax, output a dvips special +{\@ifundefined{pdfoutput}{\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}}{% +% pdfoutput is defined and not equal to \relax +% check for pdfpageheight existence just in case someone sets pdfoutput +% under non-pdflatex. If exists, set them regardless of value of \pdfoutput. +\@ifundefined{pdfpageheight}{\relax}{\global\pdfpagewidth\paperwidth +\global\pdfpageheight\paperheight}% +% if using \pdfoutput=0 under pdflatex, send dvips papersize special +\ifcase\pdfoutput +\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}% +\else +% we are using pdf output, set CLASSINFOpdf flag +\global\CLASSINFOpdftrue +\fi}} + +% let the user know the selected papersize +\typeout{-- Using \CLASSINFOpaperwidth\space x \CLASSINFOpaperheight\space +(\CLASSOPTIONpaper)\space paper.} + +\ifCLASSINFOpdf +\typeout{-- Using PDF output.} +\else +\typeout{-- Using DVI output.} +\fi + + +% The idea hinted here is for LaTeX to generate markleft{} and markright{} +% automatically for you after you enter \author{}, \journal{}, +% \journaldate{}, journalvol{}, \journalnum{}, etc. +% However, there may be some backward compatibility issues here as +% well as some special applications for IEEEtran.cls and special issues +% that may require the flexible \markleft{}, \markright{} and/or \markboth{}. +% We'll leave this as an open future suggestion. +%\newcommand{\journal}[1]{\def\@journal{#1}} +%\def\@journal{} + + + +% pointsize values +% used with ifx to determine the document's normal size +\def\@IEEEptsizenine{9} +\def\@IEEEptsizeten{10} +\def\@IEEEptsizeeleven{11} +\def\@IEEEptsizetwelve{12} + + + +% FONT DEFINITIONS (No sizexx.clo file needed) +% V1.6 revised font sizes, displayskip values and +% revised normalsize baselineskip to reduce underfull vbox problems +% on the 58pc = 696pt = 9.5in text height we want +% normalsize #lines/column baselineskip (aka leading) +% 9pt 63 11.0476pt (truncated down) +% 10pt 58 12pt (exact) +% 11pt 52 13.3846pt (truncated down) +% 12pt 50 13.92pt (exact) +% + +% we need to store the nominal baselineskip for the given font size +% in case baselinestretch ever changes. +% this is a dimen, so it will not hold stretch or shrink +\newdimen\@IEEEnormalsizeunitybaselineskip +\@IEEEnormalsizeunitybaselineskip\baselineskip + +\ifx\CLASSOPTIONpt\@IEEEptsizenine +\typeout{-- This is a 9 point document.} +\def\normalsize{\@setfontsize{\normalsize}{9}{11.0476pt}}% +\setlength{\@IEEEnormalsizeunitybaselineskip}{11.0476pt}% +\normalsize +\abovedisplayskip 1.5ex plus3pt minus1pt% +\belowdisplayskip \abovedisplayskip% +\abovedisplayshortskip 0pt plus3pt% +\belowdisplayshortskip 1.5ex plus3pt minus1pt +\def\small{\@setfontsize{\small}{8.5}{10pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} +\def\tiny{\@setfontsize{\tiny}{5}{6pt}} +% sublargesize is the same as large - 10pt +\def\sublargesize{\@setfontsize{\sublargesize}{10}{12pt}} +\def\large{\@setfontsize{\large}{10}{12pt}} +\def\Large{\@setfontsize{\Large}{12}{14pt}} +\def\LARGE{\@setfontsize{\LARGE}{14}{17pt}} +\def\huge{\@setfontsize{\huge}{17}{20pt}} +\def\Huge{\@setfontsize{\Huge}{20}{24pt}} +\fi + + +% Check if we have selected 10 points +\ifx\CLASSOPTIONpt\@IEEEptsizeten +\typeout{-- This is a 10 point document.} +\def\normalsize{\@setfontsize{\normalsize}{10}{11}}% +\setlength{\@IEEEnormalsizeunitybaselineskip}{11pt}% +\normalsize +\abovedisplayskip 1.5ex plus4pt minus2pt% +\belowdisplayskip \abovedisplayskip% +\abovedisplayshortskip 0pt plus4pt% +\belowdisplayshortskip 1.5ex plus4pt minus2pt +\def\small{\@setfontsize{\small}{9}{10pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} +\def\tiny{\@setfontsize{\tiny}{5}{6pt}} +% sublargesize is a tad smaller than large - 11pt +\def\sublargesize{\@setfontsize{\sublargesize}{11}{13.4pt}} +\def\large{\@setfontsize{\large}{12}{14pt}} +\def\Large{\@setfontsize{\Large}{14}{17pt}} +\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} +\def\huge{\@setfontsize{\huge}{20}{24pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi + + +% Check if we have selected 11 points +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven +\typeout{-- This is an 11 point document.} +\def\normalsize{\@setfontsize{\normalsize}{11}{13.3846pt}}% +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.3846pt}% +\normalsize +\abovedisplayskip 1.5ex plus5pt minus3pt% +\belowdisplayskip \abovedisplayskip% +\abovedisplayshortskip 0pt plus5pt% +\belowdisplayshortskip 1.5ex plus5pt minus3pt +\def\small{\@setfontsize{\small}{10}{12pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} +\def\tiny{\@setfontsize{\tiny}{6}{7pt}} +% sublargesize is the same as large - 12pt +\def\sublargesize{\@setfontsize{\sublargesize}{12}{14pt}} +\def\large{\@setfontsize{\large}{12}{14pt}} +\def\Large{\@setfontsize{\Large}{14}{17pt}} +\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} +\def\huge{\@setfontsize{\huge}{20}{24pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi + + +% Check if we have selected 12 points +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve +\typeout{-- This is a 12 point document.} +\def\normalsize{\@setfontsize{\normalsize}{12}{13.92pt}}% +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.92pt}% +\normalsize +\abovedisplayskip 1.5ex plus6pt minus4pt% +\belowdisplayskip \abovedisplayskip% +\abovedisplayshortskip 0pt plus6pt% +\belowdisplayshortskip 1.5ex plus6pt minus4pt +\def\small{\@setfontsize{\small}{10}{12pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} +\def\tiny{\@setfontsize{\tiny}{6}{7pt}} +% sublargesize is the same as large - 14pt +\def\sublargesize{\@setfontsize{\sublargesize}{14}{17pt}} +\def\large{\@setfontsize{\large}{14}{17pt}} +\def\Large{\@setfontsize{\Large}{17}{20pt}} +\def\LARGE{\@setfontsize{\LARGE}{20}{24pt}} +\def\huge{\@setfontsize{\huge}{22}{26pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi + + +% V1.6 The Computer Modern Fonts will issue a substitution warning for +% 24pt titles (24.88pt is used instead) increase the substitution +% tolerance to turn off this warning +\def\fontsubfuzz{.9pt} +% However, the default (and correct) Times font will scale exactly as needed. + + +% warn the user in case they forget to use the 9pt option with +% technote +\ifCLASSOPTIONtechnote% + \ifx\CLASSOPTIONpt\@IEEEptsizenine\else% + \typeout{** ATTENTION: Technotes are normally 9pt documents.}% + \fi% +\fi + + +% V1.7 +% Improved \textunderscore to provide a much better fake _ when used with +% OT1 encoding. Under OT1, detect use of pcr or cmtt \ttfamily and use +% available true _ glyph for those two typewriter fonts. +\def\@IEEEstringptm{ptm} % Times Roman family +\def\@IEEEstringppl{ppl} % Palatino Roman family +\def\@IEEEstringphv{phv} % Helvetica Sans Serif family +\def\@IEEEstringpcr{pcr} % Courier typewriter family +\def\@IEEEstringcmtt{cmtt} % Computer Modern typewriter family +\DeclareTextCommandDefault{\textunderscore}{\leavevmode +\ifx\f@family\@IEEEstringpcr\string_\else +\ifx\f@family\@IEEEstringcmtt\string_\else +\ifx\f@family\@IEEEstringptm\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else +\ifx\f@family\@IEEEstringppl\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else +\ifx\f@family\@IEEEstringphv\kern -0.03em\vbox{\hrule\@width 0.62em\@height 0.52pt\kern -0.33ex}\kern -0.03em\else +\kern 0.09em\vbox{\hrule\@width 0.6em\@height 0.44pt\kern -0.63pt\kern -0.42ex}\kern 0.09em\fi\fi\fi\fi\fi\relax} + + + + +% set the default \baselinestretch +\def\baselinestretch{1} +\ifCLASSOPTIONdraftcls + \def\baselinestretch{1.5}% default baselinestretch for draft modes +\fi + + +% process CLASSINPUT baselinestretch +\ifx\CLASSINPUTbaselinestretch\@IEEEundefined +\else + \edef\baselinestretch{\CLASSINPUTbaselinestretch} % user CLASSINPUT override + \typeout{** ATTENTION: Overriding \string\baselinestretch\space to + \baselinestretch\space via \string\CLASSINPUT.} +\fi + +\normalsize % make \baselinestretch take affect + + + + +% store the normalsize baselineskip +\newdimen\CLASSINFOnormalsizebaselineskip +\CLASSINFOnormalsizebaselineskip=\baselineskip\relax +% and the normalsize unity (baselinestretch=1) baselineskip +% we could save a register by giving the user access to +% \@IEEEnormalsizeunitybaselineskip. However, let's protect +% its read only internal status +\newdimen\CLASSINFOnormalsizeunitybaselineskip +\CLASSINFOnormalsizeunitybaselineskip=\@IEEEnormalsizeunitybaselineskip\relax +% store the nominal value of jot +\newdimen\IEEEnormaljot +\IEEEnormaljot=0.25\baselineskip\relax + +% set \jot +\jot=\IEEEnormaljot\relax + + + + +% V1.6, we are now going to fine tune the interword spacing +% The default interword glue for Times under TeX appears to use a +% nominal interword spacing of 25% (relative to the font size, i.e., 1em) +% a maximum of 40% and a minimum of 19%. +% For example, 10pt text uses an interword glue of: +% +% 2.5pt plus 1.49998pt minus 0.59998pt +% +% However, IEEE allows for a more generous range which reduces the need +% for hyphenation, especially for two column text. Furthermore, IEEE +% tends to use a little bit more nominal space between the words. +% IEEE's interword spacing percentages appear to be: +% 35% nominal +% 23% minimum +% 50% maximum +% (They may even be using a tad more for the largest fonts such as 24pt.) +% +% for bold text, IEEE increases the spacing a little more: +% 37.5% nominal +% 23% minimum +% 55% maximum + +% here are the interword spacing ratios we'll use +% for medium (normal weight) +\def\@IEEEinterspaceratioM{0.35} +\def\@IEEEinterspaceMINratioM{0.23} +\def\@IEEEinterspaceMAXratioM{0.50} + +% for bold +\def\@IEEEinterspaceratioB{0.375} +\def\@IEEEinterspaceMINratioB{0.23} +\def\@IEEEinterspaceMAXratioB{0.55} + + +% command to revise the interword spacing for the current font under TeX: +% \fontdimen2 = nominal interword space +% \fontdimen3 = interword stretch +% \fontdimen4 = interword shrink +% since all changes to the \fontdimen are global, we can enclose these commands +% in braces to confine any font attribute or length changes +\def\@@@IEEEsetfontdimens#1#2#3{{% +\setlength{\@IEEEtrantmpdimenB}{\f@size pt}% grab the font size in pt, could use 1em instead. +\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% +\fontdimen2\font=\@IEEEtrantmpdimenA\relax +\addtolength{\@IEEEtrantmpdimenA}{-#2\@IEEEtrantmpdimenB}% +\fontdimen3\font=-\@IEEEtrantmpdimenA\relax +\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% +\addtolength{\@IEEEtrantmpdimenA}{-#3\@IEEEtrantmpdimenB}% +\fontdimen4\font=\@IEEEtrantmpdimenA\relax}} + +% revise the interword spacing for each font weight +\def\@@IEEEsetfontdimens{{% +\mdseries +\@@@IEEEsetfontdimens{\@IEEEinterspaceratioM}{\@IEEEinterspaceMAXratioM}{\@IEEEinterspaceMINratioM}% +\bfseries +\@@@IEEEsetfontdimens{\@IEEEinterspaceratioB}{\@IEEEinterspaceMAXratioB}{\@IEEEinterspaceMINratioB}% +}} + +% revise the interword spacing for each font shape +% \slshape is not often used for IEEE work and is not altered here. The \scshape caps are +% already a tad too large in the free LaTeX fonts (as compared to what IEEE uses) so we +% won't alter these either. +\def\@IEEEsetfontdimens{{% +\normalfont +\@@IEEEsetfontdimens +\normalfont\itshape +\@@IEEEsetfontdimens +}} + +% command to revise the interword spacing for each font size (and shape +% and weight). Only the \rmfamily is done here as \ttfamily uses a +% fixed spacing and \sffamily is not used as the main text of IEEE papers. +\def\@IEEEtunefonts{{\selectfont\rmfamily +\tiny\@IEEEsetfontdimens +\scriptsize\@IEEEsetfontdimens +\footnotesize\@IEEEsetfontdimens +\small\@IEEEsetfontdimens +\normalsize\@IEEEsetfontdimens +\sublargesize\@IEEEsetfontdimens +\large\@IEEEsetfontdimens +\LARGE\@IEEEsetfontdimens +\huge\@IEEEsetfontdimens +\Huge\@IEEEsetfontdimens}} + +% if the nofonttune class option is not given, revise the interword spacing +% now - in case IEEEtran makes any default length measurements, and make +% sure all the default fonts are loaded +\ifCLASSOPTIONnofonttune\else +\@IEEEtunefonts +\fi + +% and again at the start of the document in case the user loaded different fonts +\AtBeginDocument{\ifCLASSOPTIONnofonttune\else\@IEEEtunefonts\fi} + + + +% V1.6 +% LaTeX is a little to quick to use hyphenations +% So, we increase the penalty for their use and raise +% the badness level that triggers an underfull hbox +% warning. The author may still have to tweak things, +% but the appearance will be much better "right out +% of the box" than that under V1.5 and prior. +% TeX default is 50 +\hyphenpenalty=750 +% If we didn't adjust the interword spacing, 2200 might be better. +% The TeX default is 1000 +\hbadness=1350 +% IEEE does not use extra spacing after punctuation +\frenchspacing + +% V1.7 increase this a tad to discourage equation breaks +\binoppenalty=1000 % default 700 +\relpenalty=800 % default 500 + + +% margin note stuff +\marginparsep 10pt +\marginparwidth 20pt +\marginparpush 25pt + + +% if things get too close, go ahead and let them touch +\lineskip 0pt +\normallineskip 0pt +\lineskiplimit 0pt +\normallineskiplimit 0pt + +% The distance from the lower edge of the text body to the +% footline +\footskip 0.4in + +% normally zero, should be relative to font height. +% put in a little rubber to help stop some bad breaks (underfull vboxes) +\parskip 0ex plus 0.2ex minus 0.1ex +\ifCLASSOPTIONconference +\parskip 6pt plus 2pt minus 1pt +\fi + +\parindent 1.0em +\ifCLASSOPTIONconference +\parindent 14.45pt +\fi + +\topmargin -49.0pt +\headheight 12pt +\headsep 0.25in + +% use the normal font baselineskip +% so that \topskip is unaffected by changes in \baselinestretch +\topskip=\@IEEEnormalsizeunitybaselineskip +\textheight 58pc % 9.63in, 696pt +% Tweak textheight to a perfect integer number of lines/page. +% The normal baselineskip for each document point size is used +% to determine these values. +\ifx\CLASSOPTIONpt\@IEEEptsizenine\textheight=63\@IEEEnormalsizeunitybaselineskip\fi % 63 lines/page +\ifx\CLASSOPTIONpt\@IEEEptsizeten\textheight=58\@IEEEnormalsizeunitybaselineskip\fi % 58 lines/page +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven\textheight=52\@IEEEnormalsizeunitybaselineskip\fi % 52 lines/page +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve\textheight=50\@IEEEnormalsizeunitybaselineskip\fi % 50 lines/page + + +\columnsep 1.5pc +\textwidth 184.2mm + + +% the default side margins are equal +\if@IEEEusingAfourpaper +\oddsidemargin 14.32mm +\evensidemargin 14.32mm +\else +\oddsidemargin 0.680in +\evensidemargin 0.680in +\fi +% compensate for LaTeX's 1in offset +\addtolength{\oddsidemargin}{-1in} +\addtolength{\evensidemargin}{-1in} + + + +% adjust margins for conference mode +\ifCLASSOPTIONconference + \topmargin -0.25in + % we retain the reserved, but unused space for headers + \addtolength{\topmargin}{-\headheight} + \addtolength{\topmargin}{-\headsep} + \textheight 9.25in % The standard for conferences (668.4975pt) + % Tweak textheight to a perfect integer number of lines/page. + \ifx\CLASSOPTIONpt\@IEEEptsizenine\textheight=61\@IEEEnormalsizeunitybaselineskip\fi % 61 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizeten\textheight=62\@IEEEnormalsizeunitybaselineskip\fi % 62 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizeeleven\textheight=50\@IEEEnormalsizeunitybaselineskip\fi % 50 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizetwelve\textheight=48\@IEEEnormalsizeunitybaselineskip\fi % 48 lines/page +\fi + + +% compsoc conference +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference + % compsoc conference use a larger value for columnsep + \columnsep 0.375in + % compsoc conferences want 1in top margin, 1.125in bottom margin + \topmargin 0in + \addtolength{\topmargin}{-6pt}% we tweak this a tad to better comply with top of line stuff + % we retain the reserved, but unused space for headers + \addtolength{\topmargin}{-\headheight} + \addtolength{\topmargin}{-\headsep} + \textheight 8.875in % (641.39625pt) + % Tweak textheight to a perfect integer number of lines/page. + \ifx\CLASSOPTIONpt\@IEEEptsizenine\textheight=58\@IEEEnormalsizeunitybaselineskip\fi % 58 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizeten\textheight=53\@IEEEnormalsizeunitybaselineskip\fi % 53 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizeeleven\textheight=48\@IEEEnormalsizeunitybaselineskip\fi % 48 lines/page + \ifx\CLASSOPTIONpt\@IEEEptsizetwelve\textheight=46\@IEEEnormalsizeunitybaselineskip\fi % 46 lines/page + \textwidth 6.5in + % the default side margins are equal + \if@IEEEusingAfourpaper + \oddsidemargin 22.45mm + \evensidemargin 22.45mm + \else + \oddsidemargin 1in + \evensidemargin 1in + \fi + % compensate for LaTeX's 1in offset + \addtolength{\oddsidemargin}{-1in} + \addtolength{\evensidemargin}{-1in} +\fi\fi + + + +% draft mode settings override that of all other modes +% provides a nice 1in margin all around the paper and extra +% space between the lines for editor's comments +\ifCLASSOPTIONdraftcls + % want 1in from top of paper to text + \setlength{\topmargin}{-\headsep}% + \addtolength{\topmargin}{-\headheight}% + % we want 1in side margins regardless of paper type + \oddsidemargin 0in + \evensidemargin 0in + % set the text width + \setlength{\textwidth}{\paperwidth}% + \addtolength{\textwidth}{-2.0in}% + \setlength{\textheight}{\paperheight}% + \addtolength{\textheight}{-2.0in}% + % digitize textheight to be an integer number of lines. + % this may cause the bottom margin to be off a tad + \addtolength{\textheight}{-1\topskip}% + \divide\textheight by \baselineskip% + \multiply\textheight by \baselineskip% + \addtolength{\textheight}{\topskip}% +\fi + + + +% process CLASSINPUT inner/outer margin +% if inner margin defined, but outer margin not, set outer to inner. +\ifx\CLASSINPUTinnersidemargin\@IEEEundefined +\else + \ifx\CLASSINPUToutersidemargin\@IEEEundefined + \edef\CLASSINPUToutersidemargin{\CLASSINPUTinnersidemargin} + \fi +\fi + +\ifx\CLASSINPUToutersidemargin\@IEEEundefined +\else + % if outer margin defined, but inner margin not, set inner to outer. + \ifx\CLASSINPUTinnersidemargin\@IEEEundefined + \edef\CLASSINPUTinnersidemargin{\CLASSINPUToutersidemargin} + \fi + \setlength{\oddsidemargin}{\CLASSINPUTinnersidemargin} + \ifCLASSOPTIONtwoside + \setlength{\evensidemargin}{\CLASSINPUToutersidemargin} + \else + \setlength{\evensidemargin}{\CLASSINPUTinnersidemargin} + \fi + \addtolength{\oddsidemargin}{-1in} + \addtolength{\evensidemargin}{-1in} + \setlength{\textwidth}{\paperwidth} + \addtolength{\textwidth}{-\CLASSINPUTinnersidemargin} + \addtolength{\textwidth}{-\CLASSINPUToutersidemargin} + \typeout{** ATTENTION: Overriding inner side margin to \CLASSINPUTinnersidemargin\space and + outer side margin to \CLASSINPUToutersidemargin\space via \string\CLASSINPUT.} +\fi + + + +% process CLASSINPUT top/bottom text margin +% if toptext margin defined, but bottomtext margin not, set bottomtext to toptext margin +\ifx\CLASSINPUTtoptextmargin\@IEEEundefined +\else + \ifx\CLASSINPUTbottomtextmargin\@IEEEundefined + \edef\CLASSINPUTbottomtextmargin{\CLASSINPUTtoptextmargin} + \fi +\fi + +\ifx\CLASSINPUTbottomtextmargin\@IEEEundefined +\else + % if bottomtext margin defined, but toptext margin not, set toptext to bottomtext margin + \ifx\CLASSINPUTtoptextmargin\@IEEEundefined + \edef\CLASSINPUTtoptextmargin{\CLASSINPUTbottomtextmargin} + \fi + \setlength{\topmargin}{\CLASSINPUTtoptextmargin} + \addtolength{\topmargin}{-1in} + \addtolength{\topmargin}{-\headheight} + \addtolength{\topmargin}{-\headsep} + \setlength{\textheight}{\paperheight} + \addtolength{\textheight}{-\CLASSINPUTtoptextmargin} + \addtolength{\textheight}{-\CLASSINPUTbottomtextmargin} + % in the default format we use the normal baselineskip as topskip + % we only need 0.7 of this to clear typical top text and we need + % an extra 0.3 spacing at the bottom for descenders. This will + % correct for both. + \addtolength{\topmargin}{-0.3\@IEEEnormalsizeunitybaselineskip} + \typeout{** ATTENTION: Overriding top text margin to \CLASSINPUTtoptextmargin\space and + bottom text margin to \CLASSINPUTbottomtextmargin\space via \string\CLASSINPUT.} +\fi + + + + + + + +% LIST SPACING CONTROLS + +% Controls the amount of EXTRA spacing +% above and below \trivlist +% Both \list and IED lists override this. +% However, \trivlist will use this as will most +% things built from \trivlist like the \center +% environment. +\topsep 0.5\baselineskip + +% Controls the additional spacing around lists preceded +% or followed by blank lines. IEEE does not increase +% spacing before or after paragraphs so it is set to zero. +% \z@ is the same as zero, but faster. +\partopsep \z@ + +% Controls the spacing between paragraphs in lists. +% IEEE does not increase spacing before or after paragraphs +% so this is also zero. +% With IEEEtran.cls, global changes to +% this value DO affect lists (but not IED lists). +\parsep \z@ + +% Controls the extra spacing between list items. +% IEEE does not put extra spacing between items. +% With IEEEtran.cls, global changes to this value DO affect +% lists (but not IED lists). +\itemsep \z@ + +% \itemindent is the amount to indent the FIRST line of a list +% item. It is auto set to zero within the \list environment. To alter +% it, you have to do so when you call the \list. +% However, IEEE uses this for the theorem environment +% There is an alternative value for this near \leftmargini below +\itemindent -1em + +% \leftmargin, the spacing from the left margin of the main text to +% the left of the main body of a list item is set by \list. +% Hence this statement does nothing for lists. +% But, quote and verse do use it for indention. +\leftmargin 2em + +% we retain this stuff from the older IEEEtran.cls so that \list +% will work the same way as before. However, itemize, enumerate and +% description (IED) could care less about what these are as they +% all are overridden. +\leftmargini 2em +%\itemindent 2em % Alternative values: sometimes used. +%\leftmargini 0em +\leftmarginii 1em +\leftmarginiii 1.5em +\leftmarginiv 1.5em +\leftmarginv 1.0em +\leftmarginvi 1.0em +\labelsep 0.5em +\labelwidth \z@ + + +% The old IEEEtran.cls behavior of \list is retained. +% However, the new V1.3 IED list environments override all the +% @list stuff (\@listX is called within \list for the +% appropriate level just before the user's list_decl is called). +% \topsep is now 2pt as IEEE puts a little extra space around +% lists - used by those non-IED macros that depend on \list. +% Note that \parsep and \itemsep are not redefined as in +% the sizexx.clo \@listX (which article.cls uses) so global changes +% of these values DO affect \list +% +\def\@listi{\leftmargin\leftmargini \topsep 2pt plus 1pt minus 1pt} +\let\@listI\@listi +\def\@listii{\leftmargin\leftmarginii\labelwidth\leftmarginii% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listiii{\leftmargin\leftmarginiii\labelwidth\leftmarginiii% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listiv{\leftmargin\leftmarginiv\labelwidth\leftmarginiv% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listv{\leftmargin\leftmarginv\labelwidth\leftmarginv% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listvi{\leftmargin\leftmarginvi\labelwidth\leftmarginvi% + \advance\labelwidth-\labelsep \topsep 2pt} + + +% IEEE uses 5) not 5. +\def\labelenumi{\theenumi)} \def\theenumi{\arabic{enumi}} + +% IEEE uses a) not (a) +\def\labelenumii{\theenumii)} \def\theenumii{\alph{enumii}} + +% IEEE uses iii) not iii. +\def\labelenumiii{\theenumiii)} \def\theenumiii{\roman{enumiii}} + +% IEEE uses A) not A. +\def\labelenumiv{\theenumiv)} \def\theenumiv{\Alph{enumiv}} + +% exactly the same as in article.cls +\def\p@enumii{\theenumi} +\def\p@enumiii{\theenumi(\theenumii)} +\def\p@enumiv{\p@enumiii\theenumiii} + +% itemized list label styles +\def\labelitemi{$\bullet$} +\def\labelitemii{$\circ$} +\def\labelitemiii{\vrule height 0.8ex depth -0.2ex width 0.6ex} +\def\labelitemiv{$\ast$} + + + +% **** V1.3 ENHANCEMENTS **** +% Itemize, Enumerate and Description (IED) List Controls +% *************************** +% +% +% IEEE seems to use at least two different values by +% which ITEMIZED list labels are indented to the right +% For The Journal of Lightwave Technology (JLT) and The Journal +% on Selected Areas in Communications (JSAC), they tend to use +% an indention equal to \parindent. For Transactions on Communications +% they tend to indent ITEMIZED lists a little more--- 1.3\parindent. +% We'll provide both values here for you so that you can choose +% which one you like in your document using a command such as: +% setlength{\IEEEilabelindent}{\IEEEilabelindentB} +\newdimen\IEEEilabelindentA +\IEEEilabelindentA \parindent + +\newdimen\IEEEilabelindentB +\IEEEilabelindentB 1.3\parindent +% However, we'll default to using \parindent +% which makes more sense to me +\newdimen\IEEEilabelindent +\IEEEilabelindent \IEEEilabelindentA + + +% This controls the default amount the enumerated list labels +% are indented to the right. +% Normally, this is the same as the paragraph indention +\newdimen\IEEEelabelindent +\IEEEelabelindent \parindent + +% This controls the default amount the description list labels +% are indented to the right. +% Normally, this is the same as the paragraph indention +\newdimen\IEEEdlabelindent +\IEEEdlabelindent \parindent + +% This is the value actually used within the IED lists. +% The IED environments automatically set its value to +% one of the three values above, so global changes do +% not have any effect +\newdimen\IEEElabelindent +\IEEElabelindent \parindent + +% The actual amount labels will be indented is +% \IEEElabelindent multiplied by the factor below +% corresponding to the level of nesting depth +% This provides a means by which the user can +% alter the effective \IEEElabelindent for deeper +% levels +% There may not be such a thing as correct "standard IEEE" +% values. What IEEE actually does may depend on the specific +% circumstances. +% The first list level almost always has full indention. +% The second levels I've seen have only 75% of the normal indentation +% Three level or greater nestings are very rare. I am guessing +% that they don't use any indentation. +\def\IEEElabelindentfactori{1.0} % almost always one +\def\IEEElabelindentfactorii{0.75} % 0.0 or 1.0 may be used in some cases +\def\IEEElabelindentfactoriii{0.0} % 0.75? 0.5? 0.0? +\def\IEEElabelindentfactoriv{0.0} +\def\IEEElabelindentfactorv{0.0} +\def\IEEElabelindentfactorvi{0.0} + +% value actually used within IED lists, it is auto +% set to one of the 6 values above +% global changes here have no effect +\def\IEEElabelindentfactor{1.0} + +% This controls the default spacing between the end of the IED +% list labels and the list text, when normal text is used for +% the labels. +\newdimen\IEEEiednormlabelsep +\IEEEiednormlabelsep \parindent + +% This controls the default spacing between the end of the IED +% list labels and the list text, when math symbols are used for +% the labels (nomenclature lists). IEEE usually increases the +% spacing in these cases +\newdimen\IEEEiedmathlabelsep +\IEEEiedmathlabelsep 1.2em + +% This controls the extra vertical separation put above and +% below each IED list. IEEE usually puts a little extra spacing +% around each list. However, this spacing is barely noticeable. +\newskip\IEEEiedtopsep +\IEEEiedtopsep 2pt plus 1pt minus 1pt + + +% This command is executed within each IED list environment +% at the beginning of the list. You can use this to set the +% parameters for some/all your IED list(s) without disturbing +% global parameters that affect things other than lists. +% i.e., renewcommand{\IEEEiedlistdecl}{\setlength{\labelsep}{5em}} +% will alter the \labelsep for the next list(s) until +% \IEEEiedlistdecl is redefined. +\def\IEEEiedlistdecl{\relax} + +% This command provides an easy way to set \leftmargin based +% on the \labelwidth, \labelsep and the argument \IEEElabelindent +% Usage: \IEEEcalcleftmargin{width-to-indent-the-label} +% output is in the \leftmargin variable, i.e., effectively: +% \leftmargin = argument + \labelwidth + \labelsep +% Note controlled spacing here, shield end of lines with % +\def\IEEEcalcleftmargin#1{\setlength{\leftmargin}{#1}% +\addtolength{\leftmargin}{\labelwidth}% +\addtolength{\leftmargin}{\labelsep}} + +% This command provides an easy way to set \labelwidth to the +% width of the given text. It is the same as +% \settowidth{\labelwidth}{label-text} +% and useful as a shorter alternative. +% Typically used to set \labelwidth to be the width +% of the longest label in the list +\def\IEEEsetlabelwidth#1{\settowidth{\labelwidth}{#1}} + +% When this command is executed, IED lists will use the +% IEEEiedmathlabelsep label separation rather than the normal +% spacing. To have an effect, this command must be executed via +% the \IEEEiedlistdecl or within the option of the IED list +% environments. +\def\IEEEusemathlabelsep{\setlength{\labelsep}{\IEEEiedmathlabelsep}} + +% A flag which controls whether the IED lists automatically +% calculate \leftmargin from \IEEElabelindent, \labelwidth and \labelsep +% Useful if you want to specify your own \leftmargin +% This flag must be set (\IEEEnocalcleftmargintrue or \IEEEnocalcleftmarginfalse) +% via the \IEEEiedlistdecl or within the option of the IED list +% environments to have an effect. +\newif\ifIEEEnocalcleftmargin +\IEEEnocalcleftmarginfalse + +% A flag which controls whether \IEEElabelindent is multiplied by +% the \IEEElabelindentfactor for each list level. +% This flag must be set via the \IEEEiedlistdecl or within the option +% of the IED list environments to have an effect. +\newif\ifIEEEnolabelindentfactor +\IEEEnolabelindentfactorfalse + + +% internal variable to indicate type of IED label +% justification +% 0 - left; 1 - center; 2 - right +\def\@IEEEiedjustify{0} + + +% commands to allow the user to control IED +% label justifications. Use these commands within +% the IED environment option or in the \IEEEiedlistdecl +% Note that changing the normal list justifications +% is nonstandard and IEEE may not like it if you do so! +% I include these commands as they may be helpful to +% those who are using these enhanced list controls for +% other non-IEEE related LaTeX work. +% itemize and enumerate automatically default to right +% justification, description defaults to left. +\def\IEEEiedlabeljustifyl{\def\@IEEEiedjustify{0}}%left +\def\IEEEiedlabeljustifyc{\def\@IEEEiedjustify{1}}%center +\def\IEEEiedlabeljustifyr{\def\@IEEEiedjustify{2}}%right + + + + +% commands to save to and restore from the list parameter copies +% this allows us to set all the list parameters within +% the list_decl and prevent \list (and its \@list) +% from overriding any of our parameters +% V1.6 use \edefs instead of dimen's to conserve dimen registers +% Note controlled spacing here, shield end of lines with % +\def\@IEEEsavelistparams{\edef\@IEEEiedtopsep{\the\topsep}% +\edef\@IEEEiedlabelwidth{\the\labelwidth}% +\edef\@IEEEiedlabelsep{\the\labelsep}% +\edef\@IEEEiedleftmargin{\the\leftmargin}% +\edef\@IEEEiedpartopsep{\the\partopsep}% +\edef\@IEEEiedparsep{\the\parsep}% +\edef\@IEEEieditemsep{\the\itemsep}% +\edef\@IEEEiedrightmargin{\the\rightmargin}% +\edef\@IEEEiedlistparindent{\the\listparindent}% +\edef\@IEEEieditemindent{\the\itemindent}} + +% Note controlled spacing here +\def\@IEEErestorelistparams{\topsep\@IEEEiedtopsep\relax% +\labelwidth\@IEEEiedlabelwidth\relax% +\labelsep\@IEEEiedlabelsep\relax% +\leftmargin\@IEEEiedleftmargin\relax% +\partopsep\@IEEEiedpartopsep\relax% +\parsep\@IEEEiedparsep\relax% +\itemsep\@IEEEieditemsep\relax% +\rightmargin\@IEEEiedrightmargin\relax% +\listparindent\@IEEEiedlistparindent\relax% +\itemindent\@IEEEieditemindent\relax} + + +% v1.6b provide original LaTeX IED list environments +% note that latex.ltx defines \itemize and \enumerate, but not \description +% which must be created by the base classes +% save original LaTeX itemize and enumerate +\let\LaTeXitemize\itemize +\let\endLaTeXitemize\enditemize +\let\LaTeXenumerate\enumerate +\let\endLaTeXenumerate\endenumerate + +% provide original LaTeX description environment from article.cls +\newenvironment{LaTeXdescription} + {\list{}{\labelwidth\z@ \itemindent-\leftmargin + \let\makelabel\descriptionlabel}} + {\endlist} +\newcommand*\descriptionlabel[1]{\hspace\labelsep + \normalfont\bfseries #1} + + +% override LaTeX's default IED lists +\def\itemize{\@IEEEitemize} +\def\enditemize{\@endIEEEitemize} +\def\enumerate{\@IEEEenumerate} +\def\endenumerate{\@endIEEEenumerate} +\def\description{\@IEEEdescription} +\def\enddescription{\@endIEEEdescription} + +% provide the user with aliases - may help those using packages that +% override itemize, enumerate, or description +\def\IEEEitemize{\@IEEEitemize} +\def\endIEEEitemize{\@endIEEEitemize} +\def\IEEEenumerate{\@IEEEenumerate} +\def\endIEEEenumerate{\@endIEEEenumerate} +\def\IEEEdescription{\@IEEEdescription} +\def\endIEEEdescription{\@endIEEEdescription} + + +% V1.6 we want to keep the IEEEtran IED list definitions as our own internal +% commands so they are protected against redefinition +\def\@IEEEitemize{\@ifnextchar[{\@@IEEEitemize}{\@@IEEEitemize[\relax]}} +\def\@IEEEenumerate{\@ifnextchar[{\@@IEEEenumerate}{\@@IEEEenumerate[\relax]}} +\def\@IEEEdescription{\@ifnextchar[{\@@IEEEdescription}{\@@IEEEdescription[\relax]}} +\def\@endIEEEitemize{\endlist} +\def\@endIEEEenumerate{\endlist} +\def\@endIEEEdescription{\endlist} + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran itemized list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEitemize[#1]{% + \ifnum\@itemdepth>3\relax\@toodeep\else% + \ifnum\@listdepth>5\relax\@toodeep\else% + \advance\@itemdepth\@ne% + \edef\@itemitem{labelitem\romannumeral\the\@itemdepth}% + % get the labelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{2}% right justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEilabelindent% + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep \parskip% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % calculate the label width + % the user can override this later if + % they specified a \labelwidth + \settowidth{\labelwidth}{\csname labelitem\romannumeral\the\@itemdepth\endcsname}% + \@IEEEsavelistparams% save our list parameters + \list{\csname\@itemitem\endcsname}{% + \@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % labelindent factor, don't revise \labelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\labelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}% + \fi}\fi\fi}% + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran enumerate list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEenumerate[#1]{% + \ifnum\@enumdepth>3\relax\@toodeep\else% + \ifnum\@listdepth>5\relax\@toodeep\else% + \advance\@enumdepth\@ne% + \edef\@enumctr{enum\romannumeral\the\@enumdepth}% + % get the labelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{2}% right justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEelabelindent% + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep 0ex% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % calculate the label width + % We'll set it to the width suitable for all labels using + % normalfont 1) to 9) + % The user can override this later + \settowidth{\labelwidth}{9)}% + \@IEEEsavelistparams% save our list parameters + \list{\csname label\@enumctr\endcsname}{\usecounter{\@enumctr}% + \@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % IEEElabelindent factor, don't revise \IEEElabelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}% + \fi}\fi\fi}% + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran description list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEdescription[#1]{% + \ifnum\@listdepth>5\relax\@toodeep\else% + % get the labelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{0}% left justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEdlabelindent% + % assume normal labelsep + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep 0ex% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % Bogus label width in case the user forgets + % to set it. + % TIP: If you want to see what a variable's width is you + % can use the TeX command \showthe\width-variable to + % display it on the screen during compilation + % (This might be helpful to know when you need to find out + % which label is the widest) + \settowidth{\labelwidth}{Hello}% + \@IEEEsavelistparams% save our list parameters + \list{}{\@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % labelindent factor, don't revise \IEEElabelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}\relax% + \fi}\fi} + +% v1.6b we use one makelabel that does justification as needed. +\def\@IEEEiedmakelabel#1{\relax\if\@IEEEiedjustify 0\relax +\makebox[\labelwidth][l]{\normalfont #1}\else +\if\@IEEEiedjustify 1\relax +\makebox[\labelwidth][c]{\normalfont #1}\else +\makebox[\labelwidth][r]{\normalfont #1}\fi\fi} + + +% VERSE and QUOTE +% V1.7 define environments with newenvironment +\newenvironment{verse}{\let\\=\@centercr + \list{}{\itemsep\z@ \itemindent -1.5em \listparindent \itemindent + \rightmargin\leftmargin\advance\leftmargin 1.5em}\item\relax} + {\endlist} +\newenvironment{quotation}{\list{}{\listparindent 1.5em \itemindent\listparindent + \rightmargin\leftmargin \parsep 0pt plus 1pt}\item\relax} + {\endlist} +\newenvironment{quote}{\list{}{\rightmargin\leftmargin}\item\relax} + {\endlist} + + +% \titlepage +% provided only for backward compatibility. \maketitle is the correct +% way to create the title page. +\newif\if@restonecol +\def\titlepage{\@restonecolfalse\if@twocolumn\@restonecoltrue\onecolumn + \else \newpage \fi \thispagestyle{empty}\c@page\z@} +\def\endtitlepage{\if@restonecol\twocolumn \else \newpage \fi} + +% standard values from article.cls +\arraycolsep 5pt +\arrayrulewidth .4pt +\doublerulesep 2pt + +\tabcolsep 6pt +\tabbingsep 0.5em + + +%% FOOTNOTES +% +%\skip\footins 10pt plus 4pt minus 2pt +% V1.6 respond to changes in font size +% space added above the footnotes (if present) +\skip\footins 0.9\baselineskip plus 0.4\baselineskip minus 0.2\baselineskip + +% V1.6, we need to make \footnotesep responsive to changes +% in \baselineskip or strange spacings will result when in +% draft mode. Here is a little LaTeX secret - \footnotesep +% determines the height of an invisible strut that is placed +% *above* the baseline of footnotes after the first. Since +% LaTeX considers the space for characters to be 0.7/baselineskip +% above the baseline and 0.3/baselineskip below it, we need to +% use 0.7/baselineskip as a \footnotesep to maintain equal spacing +% between all the lines of the footnotes. IEEE often uses a tad +% more, so use 0.8\baselineskip. This slightly larger value also helps +% the text to clear the footnote marks. Note that \thanks in IEEEtran +% uses its own value of \footnotesep which is set in \maketitle. +{\footnotesize +\global\footnotesep 0.8\baselineskip} + +\def\unnumberedfootnote{\gdef\@thefnmark{\quad}\@footnotetext} + +\skip\@mpfootins 0.3\baselineskip +\fboxsep = 3pt +\fboxrule = .4pt +% V1.6 use 1em, then use LaTeX2e's \@makefnmark +% Note that IEEE normally *left* aligns the footnote marks, so we don't need +% box resizing tricks here. +%\long\def\@makefnmark{\scriptsize\normalfont\@thefnmark} +\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@makefnmark}#1}% V1.6 use 1em +\long\def\@maketablefntext#1{\raggedleft\leavevmode\hbox{\@makefnmark}#1} +% V1.7 compsoc does not use superscipts for footnote marks +\ifCLASSOPTIONcompsoc +\def\@IEEEcompsocmakefnmark{\hbox{\normalfont\@thefnmark.\ }} +\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@IEEEcompsocmakefnmark}#1} +\fi + +% IEEE does not use footnote rules. Or do they? +\def\footnoterule{\vskip-2pt \hrule height 0.6pt depth \z@ \vskip1.6pt\relax} +\toks@\expandafter{\@setminipage\let\footnoterule\relax\footnotesep\z@} +\edef\@setminipage{\the\toks@} + +% V1.7 for compsoc, IEEE uses a footnote rule only for \thanks. We devise a "one-shot" +% system to implement this. +\newif\if@IEEEenableoneshotfootnoterule +\@IEEEenableoneshotfootnoterulefalse +\ifCLASSOPTIONcompsoc +\def\footnoterule{\relax\if@IEEEenableoneshotfootnoterule +\kern-5pt +\hbox to \columnwidth{\hfill\vrule width 0.5\columnwidth height 0.4pt\hfill} +\kern4.6pt +\global\@IEEEenableoneshotfootnoterulefalse +\else +\relax +\fi} +\fi + +% V1.6 do not allow LaTeX to break a footnote across multiple pages +\interfootnotelinepenalty=10000 + +% V1.6 discourage breaks within equations +% Note that amsmath normally sets this to 10000, +% but LaTeX2e normally uses 100. +\interdisplaylinepenalty=2500 + +% default allows section depth up to /paragraph +\setcounter{secnumdepth}{4} + +% technotes do not allow /paragraph +\ifCLASSOPTIONtechnote + \setcounter{secnumdepth}{3} +\fi +% neither do compsoc conferences +\@IEEEcompsocconfonly{\setcounter{secnumdepth}{3}} + + +\newcounter{section} +\newcounter{subsection}[section] +\newcounter{subsubsection}[subsection] +\newcounter{paragraph}[subsubsection] + +% used only by IEEEtran's IEEEeqnarray as other packages may +% have their own, different, implementations +\newcounter{IEEEsubequation}[equation] + +% as shown when called by user from \ref, \label and in table of contents +\def\theequation{\arabic{equation}} % 1 +\def\theIEEEsubequation{\theequation\alph{IEEEsubequation}} % 1a (used only by IEEEtran's IEEEeqnarray) +\ifCLASSOPTIONcompsoc +% compsoc is all arabic +\def\thesection{\arabic{section}} +\def\thesubsection{\thesection.\arabic{subsection}} +\def\thesubsubsection{\thesubsection.\arabic{subsubsection}} +\def\theparagraph{\thesubsubsection.\arabic{paragraph}} +\else +\def\thesection{\Roman{section}} % I +% V1.7, \mbox prevents breaks around - +\def\thesubsection{\mbox{\thesection-\Alph{subsection}}} % I-A +% V1.7 use I-A1 format used by IEEE rather than I-A.1 +\def\thesubsubsection{\thesubsection\arabic{subsubsection}} % I-A1 +\def\theparagraph{\thesubsubsection\alph{paragraph}} % I-A1a +\fi + +% From Heiko Oberdiek. Because of the \mbox in \thesubsection, we need to +% tell hyperref to disable the \mbox command when making PDF bookmarks. +% This done already with hyperref.sty version 6.74o and later, but +% it will not hurt to do it here again for users of older versions. +\@ifundefined{pdfstringdefPreHook}{\let\pdfstringdefPreHook\@empty}{}% +\g@addto@macro\pdfstringdefPreHook{\let\mbox\relax} + + +% Main text forms (how shown in main text headings) +% V1.6, using \thesection in \thesectiondis allows changes +% in the former to automatically appear in the latter +\ifCLASSOPTIONcompsoc + \ifCLASSOPTIONconference% compsoc conference + \def\thesectiondis{\thesection.} + \def\thesubsectiondis{\thesectiondis\arabic{subsection}.} + \def\thesubsubsectiondis{\thesubsectiondis\arabic{subsubsection}.} + \def\theparagraphdis{\thesubsubsectiondis\arabic{paragraph}.} + \else% compsoc not conferencs + \def\thesectiondis{\thesection} + \def\thesubsectiondis{\thesectiondis.\arabic{subsection}} + \def\thesubsubsectiondis{\thesubsectiondis.\arabic{subsubsection}} + \def\theparagraphdis{\thesubsubsectiondis.\arabic{paragraph}} + \fi +\else% not compsoc + \def\thesectiondis{\thesection.} % I. + \def\thesubsectiondis{\Alph{subsection}.} % B. + \def\thesubsubsectiondis{\arabic{subsubsection})} % 3) + \def\theparagraphdis{\alph{paragraph})} % d) +\fi + +% just like LaTeX2e's \@eqnnum +\def\theequationdis{{\normalfont \normalcolor (\theequation)}}% (1) +% IEEEsubequation used only by IEEEtran's IEEEeqnarray +\def\theIEEEsubequationdis{{\normalfont \normalcolor (\theIEEEsubequation)}}% (1a) +% redirect LaTeX2e's equation number display and all that depend on +% it, through IEEEtran's \theequationdis +\def\@eqnnum{\theequationdis} + + + +% V1.7 provide string macros as article.cls does +\def\contentsname{Contents} +\def\listfigurename{List of Figures} +\def\listtablename{List of Tables} +\def\refname{References} +\def\indexname{Index} +\def\figurename{Fig.} +\def\tablename{TABLE} +\@IEEEcompsocconfonly{\def\figurename{Figure}\def\tablename{Table}} +\def\partname{Part} +\def\appendixname{Appendix} +\def\abstractname{Abstract} +% IEEE specific names +\def\IEEEkeywordsname{Keywords} +\def\IEEEproofname{Proof} + + +% LIST OF FIGURES AND TABLES AND TABLE OF CONTENTS +% +\def\@pnumwidth{1.55em} +\def\@tocrmarg{2.55em} +\def\@dotsep{4.5} +\setcounter{tocdepth}{3} + +% adjusted some spacings here so that section numbers will not easily +% collide with the section titles. +% VIII; VIII-A; and VIII-A.1 are usually the worst offenders. +% MDS 1/2001 +\def\tableofcontents{\section*{\contentsname}\@starttoc{toc}} +\def\l@section#1#2{\addpenalty{\@secpenalty}\addvspace{1.0em plus 1pt}% + \@tempdima 2.75em \begingroup \parindent \z@ \rightskip \@pnumwidth% + \parfillskip-\@pnumwidth {\bfseries\leavevmode #1}\hfil\hbox to\@pnumwidth{\hss #2}\par% + \endgroup} +% argument format #1:level, #2:labelindent,#3:labelsep +\def\l@subsection{\@dottedtocline{2}{2.75em}{3.75em}} +\def\l@subsubsection{\@dottedtocline{3}{6.5em}{4.5em}} +% must provide \l@ defs for ALL sublevels EVEN if tocdepth +% is such as they will not appear in the table of contents +% these defs are how TOC knows what level these things are! +\def\l@paragraph{\@dottedtocline{4}{6.5em}{5.5em}} +\def\l@subparagraph{\@dottedtocline{5}{6.5em}{6.5em}} +\def\listoffigures{\section*{\listfigurename}\@starttoc{lof}} +\def\l@figure{\@dottedtocline{1}{0em}{2.75em}} +\def\listoftables{\section*{\listtablename}\@starttoc{lot}} +\let\l@table\l@figure + + +%% Definitions for floats +%% +%% Normal Floats +\floatsep 1\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip +\textfloatsep 1.7\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip +\@fptop 0pt plus 1fil +\@fpsep 0.75\baselineskip plus 2fil +\@fpbot 0pt plus 1fil +\def\topfraction{0.9} +\def\bottomfraction{0.4} +\def\floatpagefraction{0.8} +% V1.7, let top floats approach 90% of page +\def\textfraction{0.1} + +%% Double Column Floats +\dblfloatsep 1\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip + +\dbltextfloatsep 1.7\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip +% Note that it would be nice if the rubber here actually worked in LaTeX2e. +% There is a long standing limitation in LaTeX, first discovered (to the best +% of my knowledge) by Alan Jeffrey in 1992. LaTeX ignores the stretchable +% portion of \dbltextfloatsep, and as a result, double column figures can and +% do result in an non-integer number of lines in the main text columns with +% underfull vbox errors as a consequence. A post to comp.text.tex +% by Donald Arseneau confirms that this had not yet been fixed in 1998. +% IEEEtran V1.6 will fix this problem for you in the titles, but it doesn't +% protect you from other double floats. Happy vspace'ing. + +\@dblfptop 0pt plus 1fil +\@dblfpsep 0.75\baselineskip plus 2fil +\@dblfpbot 0pt plus 1fil +\def\dbltopfraction{0.8} +\def\dblfloatpagefraction{0.8} +\setcounter{dbltopnumber}{4} + +\intextsep 1\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip +\setcounter{topnumber}{2} +\setcounter{bottomnumber}{2} +\setcounter{totalnumber}{4} + + + +% article class provides these, we should too. +\newlength\abovecaptionskip +\newlength\belowcaptionskip +% but only \abovecaptionskip is used above figure captions and *below* table +% captions +\setlength\abovecaptionskip{0.65\baselineskip} +\setlength\belowcaptionskip{0.75\baselineskip} +% V1.6 create hooks in case the caption spacing ever needs to be +% overridden by a user +\def\@IEEEfigurecaptionsepspace{\vskip\abovecaptionskip\relax}% +\def\@IEEEtablecaptionsepspace{\vskip\belowcaptionskip\relax}% + + +% 1.6b revise caption system so that \@makecaption uses two arguments +% as with LaTeX2e. Otherwise, there will be problems when using hyperref. +\def\@IEEEtablestring{table} + +\ifCLASSOPTIONcompsoc +% V1.7 compsoc \@makecaption +\ifCLASSOPTIONconference% compsoc conference +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\normalsize\begin{center}{\normalfont\sffamily\normalsize {#1.}~ #2}\end{center}% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +\setbox\@tempboxa\hbox{\normalfont\sffamily\normalsize {#1.}~ #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\sffamily\normalsize {#1.}~ }% +\parbox[t]{\hsize}{\normalfont\sffamily\normalsize \noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, center +\else% +\hbox to\hsize{\normalfont\sffamily\normalsize\hfil\box\@tempboxa\hfil}% +\fi\fi} +\else% nonconference compsoc +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\normalsize\begin{center}{\normalfont\sffamily\normalsize #1}\\{\normalfont\sffamily\normalsize #2}\end{center}% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +\setbox\@tempboxa\hbox{\normalfont\sffamily\normalsize {#1.}~ #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\sffamily\normalsize {#1.}~ }% +\parbox[t]{\hsize}{\normalfont\sffamily\normalsize \noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, left justify +\else% +\hbox to\hsize{\normalfont\sffamily\normalsize\box\@tempboxa\hfil}% +\fi\fi} +\fi + +\else% traditional noncompsoc \@makecaption +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\footnotesize{\centering\normalfont\footnotesize#1.\qquad\scshape #2\par}% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +% 3/2001 use footnotesize, not small; use two nonbreaking spaces, not one +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}~~ #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}~~ }% +\parbox[t]{\hsize}{\normalfont\footnotesize\noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, center if conference, left justify otherwise +\else% +\ifCLASSOPTIONconference \hbox to\hsize{\normalfont\footnotesize\box\@tempboxa\hfil}% +\else \hbox to\hsize{\normalfont\footnotesize\box\@tempboxa\hfil}% +\fi\fi\fi} +\fi + + + +% V1.7 disable captions class option, do so in a way that retains operation of \label +% within \caption +\ifCLASSOPTIONcaptionsoff +\long\def\@makecaption#1#2{\vspace*{2em}\footnotesize\begin{center}{\footnotesize #1}\end{center}% +\let\@IEEEtemporiglabeldefsave\label +\let\@IEEEtemplabelargsave\relax +\def\label##1{\gdef\@IEEEtemplabelargsave{##1}}% +\setbox\@tempboxa\hbox{#2}% +\let\label\@IEEEtemporiglabeldefsave +\ifx\@IEEEtemplabelargsave\relax\else\label{\@IEEEtemplabelargsave}\fi} +\fi + + +% V1.7 define end environments with \def not \let so as to work OK with +% preview-latex +\newcounter{figure} +\def\thefigure{\@arabic\c@figure} +\def\fps@figure{tbp} +\def\ftype@figure{1} +\def\ext@figure{lof} +\def\fnum@figure{\figurename~\thefigure} +\def\figure{\@float{figure}} +\def\endfigure{\end@float} +\@namedef{figure*}{\@dblfloat{figure}} +\@namedef{endfigure*}{\end@dblfloat} +\newcounter{table} +\ifCLASSOPTIONcompsoc +\def\thetable{\arabic{table}} +\else +\def\thetable{\@Roman\c@table} +\fi +\def\fps@table{tbp} +\def\ftype@table{2} +\def\ext@table{lot} +\def\fnum@table{\tablename~\thetable} +% V1.6 IEEE uses 8pt text for tables +% to default to footnotesize, we hack into LaTeX2e's \@floatboxreset and pray +\def\table{\def\@floatboxreset{\reset@font\scriptsize\@setminipage}% + \let\@makefntext\@maketablefntext + \@float{table}} +\def\endtable{\end@float} +% v1.6b double column tables need to default to footnotesize as well. +\@namedef{table*}{\def\@floatboxreset{\reset@font\scriptsize\@setminipage}\@dblfloat{table}} +\@namedef{endtable*}{\end@dblfloat} + + + + +%% +%% START OF IEEEeqnarry DEFINITIONS +%% +%% Inspired by the concepts, examples, and previous works of LaTeX +%% coders and developers such as Donald Arseneau, Fred Bartlett, +%% David Carlisle, Tony Liu, Frank Mittelbach, Piet van Oostrum, +%% Roland Winkler and Mark Wooding. +%% I don't make the claim that my work here is even near their calibre. ;) + + +% hook to allow easy changeover to IEEEtran.cls/tools.sty error reporting +\def\@IEEEclspkgerror{\ClassError{IEEEtran}} + +\newif\if@IEEEeqnarraystarform% flag to indicate if the environment was called as the star form +\@IEEEeqnarraystarformfalse + +\newif\if@advanceIEEEeqncolcnt% tracks if the environment should advance the col counter +% allows a way to make an \IEEEeqnarraybox that can be used within an \IEEEeqnarray +% used by IEEEeqnarraymulticol so that it can work properly in both +\@advanceIEEEeqncolcnttrue + +\newcount\@IEEEeqnnumcols % tracks how many IEEEeqnarray cols are defined +\newcount\@IEEEeqncolcnt % tracks how many IEEEeqnarray cols the user actually used + + +% The default math style used by the columns +\def\IEEEeqnarraymathstyle{\displaystyle} +% The default text style used by the columns +% default to using the current font +\def\IEEEeqnarraytextstyle{\relax} + +% like the iedlistdecl but for \IEEEeqnarray +\def\IEEEeqnarraydecl{\relax} +\def\IEEEeqnarrayboxdecl{\relax} + +% \yesnumber is the opposite of \nonumber +% a novel concept with the same def as the equationarray package +% However, we give IEEE versions too since some LaTeX packages such as +% the MDWtools mathenv.sty redefine \nonumber to something else. +\providecommand{\yesnumber}{\global\@eqnswtrue} +\def\IEEEyesnumber{\global\@eqnswtrue} +\def\IEEEnonumber{\global\@eqnswfalse} + + +\def\IEEEyessubnumber{\global\@IEEEissubequationtrue\global\@eqnswtrue% +\if@IEEEeqnarrayISinner% only do something inside an IEEEeqnarray +\if@IEEElastlinewassubequation\addtocounter{equation}{-1}\else\setcounter{IEEEsubequation}{1}\fi% +\def\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\fi} + +% flag to indicate that an equation is a sub equation +\newif\if@IEEEissubequation% +\@IEEEissubequationfalse + +% allows users to "push away" equations that get too close to the equation numbers +\def\IEEEeqnarraynumspace{\hphantom{\if@IEEEissubequation\theIEEEsubequationdis\else\theequationdis\fi}} + +% provides a way to span multiple columns within IEEEeqnarray environments +% will consider \if@advanceIEEEeqncolcnt before globally advancing the +% column counter - so as to work within \IEEEeqnarraybox +% usage: \IEEEeqnarraymulticol{number cols. to span}{col type}{cell text} +\long\def\IEEEeqnarraymulticol#1#2#3{\multispan{#1}% +% check if column is defined +\relax\expandafter\ifx\csname @IEEEeqnarraycolDEF#2\endcsname\@IEEEeqnarraycolisdefined% +\csname @IEEEeqnarraycolPRE#2\endcsname#3\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST#2\endcsname% +\else% if not, error and use default type +\@IEEEclspkgerror{Invalid column type "#2" in \string\IEEEeqnarraymulticol.\MessageBreak +Using a default centering column instead}% +{You must define IEEEeqnarray column types before use.}% +\csname @IEEEeqnarraycolPRE@IEEEdefault\endcsname#3\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST@IEEEdefault\endcsname% +\fi% +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by #1\relax\fi} + +% like \omit, but maintains track of the column counter for \IEEEeqnarray +\def\IEEEeqnarrayomit{\omit\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by 1\relax\fi} + + +% provides a way to define a letter referenced column type +% usage: \IEEEeqnarraydefcol{col. type letter/name}{pre insertion text}{post insertion text} +\def\IEEEeqnarraydefcol#1#2#3{\expandafter\def\csname @IEEEeqnarraycolPRE#1\endcsname{#2}% +\expandafter\def\csname @IEEEeqnarraycolPOST#1\endcsname{#3}% +\expandafter\def\csname @IEEEeqnarraycolDEF#1\endcsname{1}} + + +% provides a way to define a numerically referenced inter-column glue types +% usage: \IEEEeqnarraydefcolsep{col. glue number}{glue definition} +\def\IEEEeqnarraydefcolsep#1#2{\expandafter\def\csname @IEEEeqnarraycolSEP\romannumeral #1\endcsname{#2}% +\expandafter\def\csname @IEEEeqnarraycolSEPDEF\romannumeral #1\endcsname{1}} + + +\def\@IEEEeqnarraycolisdefined{1}% just a macro for 1, used for checking undefined column types + + +% expands and appends the given argument to the \@IEEEtrantmptoksA token list +% used to build up the \halign preamble +\def\@IEEEappendtoksA#1{\edef\@@IEEEappendtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA #1}}% +\@@IEEEappendtoksA} + +% also appends to \@IEEEtrantmptoksA, but does not expand the argument +% uses \toks8 as a scratchpad register +\def\@IEEEappendNOEXPANDtoksA#1{\toks8={#1}% +\edef\@@IEEEappendNOEXPANDtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA\the\toks8}}% +\@@IEEEappendNOEXPANDtoksA} + +% define some common column types for the user +% math +\IEEEeqnarraydefcol{l}{$\IEEEeqnarraymathstyle}{$\hfil} +\IEEEeqnarraydefcol{c}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} +\IEEEeqnarraydefcol{r}{\hfil$\IEEEeqnarraymathstyle}{$} +\IEEEeqnarraydefcol{L}{$\IEEEeqnarraymathstyle{}}{{}$\hfil} +\IEEEeqnarraydefcol{C}{\hfil$\IEEEeqnarraymathstyle{}}{{}$\hfil} +\IEEEeqnarraydefcol{R}{\hfil$\IEEEeqnarraymathstyle{}}{{}$} +% text +\IEEEeqnarraydefcol{s}{\IEEEeqnarraytextstyle}{\hfil} +\IEEEeqnarraydefcol{t}{\hfil\IEEEeqnarraytextstyle}{\hfil} +\IEEEeqnarraydefcol{u}{\hfil\IEEEeqnarraytextstyle}{} + +% vertical rules +\IEEEeqnarraydefcol{v}{}{\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{vv}{\vrule width\arrayrulewidth\hfil}{\hfil\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{V}{}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{VV}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth\hfil}% +{\hfil\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} + +% horizontal rules +\IEEEeqnarraydefcol{h}{}{\leaders\hrule height\arrayrulewidth\hfil} +\IEEEeqnarraydefcol{H}{}{\leaders\vbox{\hrule width\arrayrulewidth\vskip\doublerulesep\hrule width\arrayrulewidth}\hfil} + +% plain +\IEEEeqnarraydefcol{x}{}{} +\IEEEeqnarraydefcol{X}{$}{$} + +% the default column type to use in the event a column type is not defined +\IEEEeqnarraydefcol{@IEEEdefault}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} + + +% a zero tabskip (used for "-" col types) +\def\@IEEEeqnarraycolSEPzero{0pt plus 0pt minus 0pt} +% a centering tabskip (used for "+" col types) +\def\@IEEEeqnarraycolSEPcenter{1000pt plus 0pt minus 1000pt} + +% top level default tabskip glues for the start, end, and inter-column +% may be reset within environments not always at the top level, e.g., \IEEEeqnarraybox +\edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPcenter}% default start glue +\edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPcenter}% default end glue +\edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue + + + +% creates a vertical rule that extends from the bottom to the top a a cell +% Provided in case other packages redefine \vline some other way. +% usage: \IEEEeqnarrayvrule[rule thickness] +% If no argument is provided, \arrayrulewidth will be used for the rule thickness. +\newcommand\IEEEeqnarrayvrule[1][\arrayrulewidth]{\vrule\@width#1\relax} + +% creates a blank separator row +% usage: \IEEEeqnarrayseprow[separation length][font size commands] +% default is \IEEEeqnarrayseprow[0.25\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers +\def\IEEEeqnarrayseprow{\relax\@ifnextchar[{\@IEEEeqnarrayseprow}{\@IEEEeqnarrayseprow[0.25\normalbaselineskip]}} +\def\@IEEEeqnarrayseprow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprow[#1]}{\@@IEEEeqnarrayseprow[#1][\relax]}} +\def\@@IEEEeqnarrayseprow[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% +\ifx\@IEEEeqnarrayseprowARGONE\@empty% +% get the skip value, based on the font commands +% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 +% assign within a bogus box to confine the font changes +{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% +\else% +{\setbox0=\hbox{#2\relax\global\skip5=#1}}% +\fi% +\@IEEEeqnarrayhoptolastcolumn\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} + +% creates a blank separator row, but omits all the column templates +% usage: \IEEEeqnarrayseprowcut[separation length][font size commands] +% default is \IEEEeqnarrayseprowcut[0.25\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers +\def\IEEEeqnarrayseprowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarrayseprowcut}{\@IEEEeqnarrayseprowcut[0.25\normalbaselineskip]}} +\def\@IEEEeqnarrayseprowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprowcut[#1]}{\@@IEEEeqnarrayseprowcut[#1][\relax]}} +\def\@@IEEEeqnarrayseprowcut[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% +\ifx\@IEEEeqnarrayseprowARGONE\@empty% +% get the skip value, based on the font commands +% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 +% assign within a bogus box to confine the font changes +{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% +\else% +{\setbox0=\hbox{#2\relax\global\skip5=#1}}% +\fi% +\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} + + + +% draws a single rule across all the columns optional +% argument determines the rule width, \arrayrulewidth is the default +% updates column counter as needed and turns off struts +% usage: \IEEEeqnarrayrulerow[rule line thickness] +\def\IEEEeqnarrayrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarrayrulerow}{\@IEEEeqnarrayrulerow[\arrayrulewidth]}} +\def\@IEEEeqnarrayrulerow[#1]{\leaders\hrule height#1\hfil\relax% put in our rule +% turn off any struts +\IEEEeqnarraystrutsize{0pt}{0pt}[\relax]\relax} + + +% draws a double rule by using a single rule row, a separator row, and then +% another single rule row +% first optional argument determines the rule thicknesses, \arrayrulewidth is the default +% second optional argument determines the rule spacing, \doublerulesep is the default +% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] +\def\IEEEeqnarraydblrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarraydblrulerow}{\@IEEEeqnarraydblrulerow[\arrayrulewidth]}} +\def\@IEEEeqnarraydblrulerow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerow[#1]}% +{\@@IEEEeqnarraydblrulerow[#1][\doublerulesep]}} +\def\@@IEEEeqnarraydblrulerow[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% +% we allow the user to say \IEEEeqnarraydblrulerow[][] +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]\relax% +\fi% +\def\@IEEEeqnarraydblrulerowARG{#2}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\\\IEEEeqnarrayseprow[\doublerulesep][\relax]% +\else% +\\\IEEEeqnarrayseprow[#2][\relax]% +\fi% +\\\multispan{\@IEEEeqnnumcols}% +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\def\@IEEEeqnarraydblrulerowARG{#1}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +} + +% draws a double rule by using a single rule row, a separator (cutting) row, and then +% another single rule row +% first optional argument determines the rule thicknesses, \arrayrulewidth is the default +% second optional argument determines the rule spacing, \doublerulesep is the default +% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] +\def\IEEEeqnarraydblrulerowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarraydblrulerowcut}{\@IEEEeqnarraydblrulerowcut[\arrayrulewidth]}} +\def\@IEEEeqnarraydblrulerowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerowcut[#1]}% +{\@@IEEEeqnarraydblrulerowcut[#1][\doublerulesep]}} +\def\@@IEEEeqnarraydblrulerowcut[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% +% we allow the user to say \IEEEeqnarraydblrulerow[][] +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +\def\@IEEEeqnarraydblrulerowARG{#2}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\\\IEEEeqnarrayseprowcut[\doublerulesep][\relax]% +\else% +\\\IEEEeqnarrayseprowcut[#2][\relax]% +\fi% +\\\multispan{\@IEEEeqnnumcols}% +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\def\@IEEEeqnarraydblrulerowARG{#1}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +} + + + +% inserts a full row's worth of &'s +% relies on \@IEEEeqnnumcols to provide the correct number of columns +% uses \@IEEEtrantmptoksA, \count0 as scratch registers +\def\@IEEEeqnarrayhoptolastcolumn{\@IEEEtrantmptoksA={}\count0=1\relax% +\loop% add cols if the user did not use them all +\ifnum\count0<\@IEEEeqnnumcols\relax% +\@IEEEappendtoksA{&}% +\advance\count0 by 1\relax% update the col count +\repeat% +\the\@IEEEtrantmptoksA%execute the &'s +} + + + +\newif\if@IEEEeqnarrayISinner % flag to indicate if we are within the lines +\@IEEEeqnarrayISinnerfalse % of an IEEEeqnarray - after the IEEEeqnarraydecl + +\edef\@IEEEeqnarrayTHEstrutheight{0pt} % height and depth of IEEEeqnarray struts +\edef\@IEEEeqnarrayTHEstrutdepth{0pt} + +\edef\@IEEEeqnarrayTHEmasterstrutheight{0pt} % default height and depth of +\edef\@IEEEeqnarrayTHEmasterstrutdepth{0pt} % struts within an IEEEeqnarray + +\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{0pt} % saved master strut height +\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{0pt} % and depth + +\newif\if@IEEEeqnarrayusemasterstrut % flag to indicate that the master strut value +\@IEEEeqnarrayusemasterstruttrue % is to be used + + + +% saves the strut height and depth of the master strut +\def\@IEEEeqnarraymasterstrutsave{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% save values +\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{\the\dimen2}} + +% restores the strut height and depth of the master strut +\def\@IEEEeqnarraymasterstrutrestore{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutHSAVE\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutDSAVE\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% restore values +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}} + + +% globally restores the strut height and depth to the +% master values and sets the master strut flag to true +\def\@IEEEeqnarraystrutreset{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% restore values +\xdef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\xdef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\global\@IEEEeqnarrayusemasterstruttrue} + + +% if the master strut is not to be used, make the current +% values of \@IEEEeqnarrayTHEstrutheight, \@IEEEeqnarrayTHEstrutdepth +% and the use master strut flag, global +% this allows user strut commands issued in the last column to be carried +% into the isolation/strut column +\def\@IEEEeqnarrayglobalizestrutstatus{\relax% +\if@IEEEeqnarrayusemasterstrut\else% +\xdef\@IEEEeqnarrayTHEstrutheight{\@IEEEeqnarrayTHEstrutheight}% +\xdef\@IEEEeqnarrayTHEstrutdepth{\@IEEEeqnarrayTHEstrutdepth}% +\global\@IEEEeqnarrayusemasterstrutfalse% +\fi} + + + +% usage: \IEEEeqnarraystrutsize{height}{depth}[font size commands] +% If called outside the lines of an IEEEeqnarray, sets the height +% and depth of both the master and local struts. If called inside +% an IEEEeqnarray line, sets the height and depth of the local strut +% only and sets the flag to indicate the use of the local strut +% values. If the height or depth is left blank, 0.7\normalbaselineskip +% and 0.3\normalbaselineskip will be used, respectively. +% The optional argument can be used to evaluate the lengths under +% a different font size and styles. If none is specified, the current +% font is used. +% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 +\def\IEEEeqnarraystrutsize#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsize{#1}{#2}}{\@IEEEeqnarraystrutsize{#1}{#2}[\relax]}} +\def\@IEEEeqnarraystrutsize#1#2[#3]{\def\@IEEEeqnarraystrutsizeARG{#1}% +\ifx\@IEEEeqnarraystrutsizeARG\@empty% +{\setbox0=\hbox{#3\relax\global\skip3=0.7\normalbaselineskip}}% +\skip0=\skip3\relax% +\else% arg one present +{\setbox0=\hbox{#3\relax\global\skip3=#1\relax}}% +\skip0=\skip3\relax% +\fi% if null arg +\def\@IEEEeqnarraystrutsizeARG{#2}% +\ifx\@IEEEeqnarraystrutsizeARG\@empty% +{\setbox0=\hbox{#3\relax\global\skip3=0.3\normalbaselineskip}}% +\skip2=\skip3\relax% +\else% arg two present +{\setbox0=\hbox{#3\relax\global\skip3=#2\relax}}% +\skip2=\skip3\relax% +\fi% if null arg +% remove stretchability, just to be safe +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +\if@IEEEeqnarrayISinner% inner does not touch master strut size +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstrutfalse% do not use master +\else% outer, have to set master strut too +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstruttrue% use master strut +\fi} + + +% usage: \IEEEeqnarraystrutsizeadd{added height}{added depth}[font size commands] +% If called outside the lines of an IEEEeqnarray, adds the given height +% and depth to both the master and local struts. +% If called inside an IEEEeqnarray line, adds the given height and depth +% to the local strut only and sets the flag to indicate the use +% of the local strut values. +% In both cases, if a height or depth is left blank, 0pt is used instead. +% The optional argument can be used to evaluate the lengths under +% a different font size and styles. If none is specified, the current +% font is used. +% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 +\def\IEEEeqnarraystrutsizeadd#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsizeadd{#1}{#2}}{\@IEEEeqnarraystrutsizeadd{#1}{#2}[\relax]}} +\def\@IEEEeqnarraystrutsizeadd#1#2[#3]{\def\@IEEEeqnarraystrutsizearg{#1}% +\ifx\@IEEEeqnarraystrutsizearg\@empty% +\skip0=0pt\relax% +\else% arg one present +{\setbox0=\hbox{#3\relax\global\skip3=#1}}% +\skip0=\skip3\relax% +\fi% if null arg +\def\@IEEEeqnarraystrutsizearg{#2}% +\ifx\@IEEEeqnarraystrutsizearg\@empty% +\skip2=0pt\relax% +\else% arg two present +{\setbox0=\hbox{#3\relax\global\skip3=#2}}% +\skip2=\skip3\relax% +\fi% if null arg +% remove stretchability, just to be safe +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +\if@IEEEeqnarrayISinner% inner does not touch master strut size +% get local strut size +\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% +% add it to the user supplied values +\advance\dimen0 by \skip0\relax% +\advance\dimen2 by \skip2\relax% +% update the local strut size +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstrutfalse% do not use master +\else% outer, have to set master strut too +% get master strut size +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% add it to the user supplied values +\advance\dimen0 by \skip0\relax% +\advance\dimen2 by \skip2\relax% +% update the local and master strut sizes +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstruttrue% use master strut +\fi} + + +% allow user a way to see the struts +\newif\ifIEEEvisiblestruts +\IEEEvisiblestrutsfalse + +% inserts an invisible strut using the master or local strut values +% uses scratch registers \skip0, \skip2, \dimen0, \dimen2 +\def\@IEEEeqnarrayinsertstrut{\relax% +\if@IEEEeqnarrayusemasterstrut +% get master strut size +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +\else% +% get local strut size +\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% +\fi% +% remove stretchability, probably not needed +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +% allow user to see struts if desired +\ifIEEEvisiblestruts% +\vrule width0.2pt height\dimen0 depth\dimen2\relax% +\else% +\vrule width0pt height\dimen0 depth\dimen2\relax\fi} + + +% creates an invisible strut, useable even outside \IEEEeqnarray +% if \IEEEvisiblestrutstrue, the strut will be visible and 0.2pt wide. +% usage: \IEEEstrut[height][depth][font size commands] +% default is \IEEEstrut[0.7\normalbaselineskip][0.3\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \dimen0, \dimen2, \skip0, \skip2 +\def\IEEEstrut{\relax\@ifnextchar[{\@IEEEstrut}{\@IEEEstrut[0.7\normalbaselineskip]}} +\def\@IEEEstrut[#1]{\relax\@ifnextchar[{\@@IEEEstrut[#1]}{\@@IEEEstrut[#1][0.3\normalbaselineskip]}} +\def\@@IEEEstrut[#1][#2]{\relax\@ifnextchar[{\@@@IEEEstrut[#1][#2]}{\@@@IEEEstrut[#1][#2][\relax]}} +\def\@@@IEEEstrut[#1][#2][#3]{\mbox{#3\relax% +\def\@IEEEstrutARG{#1}% +\ifx\@IEEEstrutARG\@empty% +\skip0=0.7\normalbaselineskip\relax% +\else% +\skip0=#1\relax% +\fi% +\def\@IEEEstrutARG{#2}% +\ifx\@IEEEstrutARG\@empty% +\skip2=0.3\normalbaselineskip\relax% +\else% +\skip2=#2\relax% +\fi% +% remove stretchability, probably not needed +\dimen0\skip0\relax% +\dimen2\skip2\relax% +\ifIEEEvisiblestruts% +\vrule width0.2pt height\dimen0 depth\dimen2\relax% +\else% +\vrule width0.0pt height\dimen0 depth\dimen2\relax\fi}} + + +% enables strut mode by setting a default strut size and then zeroing the +% \baselineskip, \lineskip, \lineskiplimit and \jot +\def\IEEEeqnarraystrutmode{\IEEEeqnarraystrutsize{0.7\normalbaselineskip}{0.3\normalbaselineskip}[\relax]% +\baselineskip=0pt\lineskip=0pt\lineskiplimit=0pt\jot=0pt} + + + +\def\IEEEeqnarray{\@IEEEeqnarraystarformfalse\@IEEEeqnarray} +\def\endIEEEeqnarray{\end@IEEEeqnarray} + +\@namedef{IEEEeqnarray*}{\@IEEEeqnarraystarformtrue\@IEEEeqnarray} +\@namedef{endIEEEeqnarray*}{\end@IEEEeqnarray} + + +% \IEEEeqnarray is an enhanced \eqnarray. +% The star form defaults to not putting equation numbers at the end of each row. +% usage: \IEEEeqnarray[decl]{cols} +\def\@IEEEeqnarray{\relax\@ifnextchar[{\@@IEEEeqnarray}{\@@IEEEeqnarray[\relax]}} +\def\@@IEEEeqnarray[#1]#2{% + % default to showing the equation number or not based on whether or not + % the star form was involked + \if@IEEEeqnarraystarform\global\@eqnswfalse + \else% not the star form + \global\@eqnswtrue + \fi% if star form + \@IEEEissubequationfalse% default to no subequations + \@IEEElastlinewassubequationfalse% assume last line is not a sub equation + \@IEEEeqnarrayISinnerfalse% not yet within the lines of the halign + \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default + \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise + \IEEEvisiblestrutsfalse% diagnostic mode defaults to off + % no extra space unless the user specifically requests it + \lineskip=0pt\relax + \lineskiplimit=0pt\relax + \baselineskip=\normalbaselineskip\relax% + \jot=\IEEEnormaljot\relax% + \mathsurround\z@\relax% no extra spacing around math + \@advanceIEEEeqncolcnttrue% advance the col counter for each col the user uses, + % used in \IEEEeqnarraymulticol and in the preamble build + \stepcounter{equation}% advance equation counter before first line + \setcounter{IEEEsubequation}{0}% no subequation yet + \def\@currentlabel{\p@equation\theequation}% redefine the ref label + \IEEEeqnarraydecl\relax% allow a way for the user to make global overrides + #1\relax% allow user to override defaults + \let\\\@IEEEeqnarraycr% replace newline with one that can put in eqn. numbers + \global\@IEEEeqncolcnt\z@% col. count = 0 for first line + \@IEEEbuildpreamble #2\end\relax% build the preamble and put it into \@IEEEtrantmptoksA + % put in the column for the equation number + \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first + \toks0={##}% + % advance the \@IEEEeqncolcnt for the isolation col, this helps with error checking + \@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}% + % add the isolation column + \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% + % advance the \@IEEEeqncolcnt for the equation number col, this helps with error checking + \@IEEEappendtoksA{&\global\advance\@IEEEeqncolcnt by 1\relax}% + % add the equation number col to the preamble + \@IEEEappendtoksA{\tabskip\z@skip\hb@xt@\z@\bgroup\hss\the\toks0\egroup}% + % note \@IEEEeqnnumcols does not count the equation col or isolation col + % set the starting tabskip glue as determined by the preamble build + \tabskip=\@IEEEBPstartglue\relax + % begin the display alignment + \@IEEEeqnarrayISinnertrue% commands are now within the lines + $$\everycr{}\halign to\displaywidth\bgroup + % "exspand" the preamble + \span\the\@IEEEtrantmptoksA\cr} + +% enter isolation/strut column (or the next column if the user did not use +% every column), record the strut status, complete the columns, do the strut if needed, +% restore counters to correct values and exit +\def\end@IEEEeqnarray{\@IEEEeqnarrayglobalizestrutstatus&\@@IEEEeqnarraycr\egroup% +\if@IEEElastlinewassubequation\global\advance\c@IEEEsubequation\m@ne\fi% +\global\advance\c@equation\m@ne% +$$\@ignoretrue} + +% need a way to remember if last line is a subequation +\newif\if@IEEElastlinewassubequation% +\@IEEElastlinewassubequationfalse + +% IEEEeqnarray uses a modifed \\ instead of the plain \cr to +% end rows. This allows for things like \\*[vskip amount] +% This "cr" macros are modified versions those for LaTeX2e's eqnarray +% the {\ifnum0=`} braces must be kept away from the last column to avoid +% altering spacing of its math, so we use & to advance to the next column +% as there is an isolation/strut column after the user's columns +\def\@IEEEeqnarraycr{\@IEEEeqnarrayglobalizestrutstatus&% save strut status and advance to next column + {\ifnum0=`}\fi + \@ifstar{% + \global\@eqpen\@M\@IEEEeqnarrayYCR + }{% + \global\@eqpen\interdisplaylinepenalty \@IEEEeqnarrayYCR + }% +} + +\def\@IEEEeqnarrayYCR{\@testopt\@IEEEeqnarrayXCR\z@skip} + +\def\@IEEEeqnarrayXCR[#1]{% + \ifnum0=`{\fi}% + \@@IEEEeqnarraycr + \noalign{\penalty\@eqpen\vskip\jot\vskip #1\relax}}% + +\def\@@IEEEeqnarraycr{\@IEEEtrantmptoksA={}% clear token register + \advance\@IEEEeqncolcnt by -1\relax% adjust col count because of the isolation column + \ifnum\@IEEEeqncolcnt>\@IEEEeqnnumcols\relax + \@IEEEclspkgerror{Too many columns within the IEEEeqnarray\MessageBreak + environment}% + {Use fewer \string &'s or put more columns in the IEEEeqnarry column\MessageBreak + specifications.}\relax% + \else + \loop% add cols if the user did not use them all + \ifnum\@IEEEeqncolcnt<\@IEEEeqnnumcols\relax + \@IEEEappendtoksA{&}% + \advance\@IEEEeqncolcnt by 1\relax% update the col count + \repeat + % this number of &'s will take us the the isolation column + \fi + % execute the &'s + \the\@IEEEtrantmptoksA% + % handle the strut/isolation column + \@IEEEeqnarrayinsertstrut% do the strut if needed + \@IEEEeqnarraystrutreset% reset the strut system for next line or IEEEeqnarray + &% and enter the equation number column + % is this line needs an equation number, display it and advance the + % (sub)equation counters, record what type this line was + \if@eqnsw% + \if@IEEEissubequation\theIEEEsubequationdis\addtocounter{equation}{1}\stepcounter{IEEEsubequation}% + \global\@IEEElastlinewassubequationtrue% + \else% display a standard equation number, initialize the IEEEsubequation counter + \theequationdis\stepcounter{equation}\setcounter{IEEEsubequation}{0}% + \global\@IEEElastlinewassubequationfalse\fi% + \fi% + % reset the eqnsw flag to indicate default preference of the display of equation numbers + \if@IEEEeqnarraystarform\global\@eqnswfalse\else\global\@eqnswtrue\fi + \global\@IEEEissubequationfalse% reset the subequation flag + % reset the number of columns the user actually used + \global\@IEEEeqncolcnt\z@\relax + % the real end of the line + \cr} + + + + + +% \IEEEeqnarraybox is like \IEEEeqnarray except the box form puts everything +% inside a vtop, vbox, or vcenter box depending on the letter in the second +% optional argument (t,b,c). Vbox is the default. Unlike \IEEEeqnarray, +% equation numbers are not displayed and \IEEEeqnarraybox can be nested. +% \IEEEeqnarrayboxm is for math mode (like \array) and does not put the vbox +% within an hbox. +% \IEEEeqnarrayboxt is for text mode (like \tabular) and puts the vbox within +% a \hbox{$ $} construct. +% \IEEEeqnarraybox will auto detect whether to use \IEEEeqnarrayboxm or +% \IEEEeqnarrayboxt depending on the math mode. +% The third optional argument specifies the width this box is to be set to - +% natural width is the default. +% The * forms do not add \jot line spacing +% usage: \IEEEeqnarraybox[decl][pos][width]{cols} +\def\IEEEeqnarrayboxm{\@IEEEeqnarraystarformfalse\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} +\def\endIEEEeqnarrayboxm{\end@IEEEeqnarraybox} +\@namedef{IEEEeqnarrayboxm*}{\@IEEEeqnarraystarformtrue\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarrayboxm*}{\end@IEEEeqnarraybox} + +\def\IEEEeqnarrayboxt{\@IEEEeqnarraystarformfalse\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} +\def\endIEEEeqnarrayboxt{\end@IEEEeqnarraybox} +\@namedef{IEEEeqnarrayboxt*}{\@IEEEeqnarraystarformtrue\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarrayboxt*}{\end@IEEEeqnarraybox} + +\def\IEEEeqnarraybox{\@IEEEeqnarraystarformfalse\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% +\@IEEEeqnarraybox} +\def\endIEEEeqnarraybox{\end@IEEEeqnarraybox} + +\@namedef{IEEEeqnarraybox*}{\@IEEEeqnarraystarformtrue\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% +\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarraybox*}{\end@IEEEeqnarraybox} + +% flag to indicate if the \IEEEeqnarraybox needs to put things into an hbox{$ $} +% for \vcenter in non-math mode +\newif\if@IEEEeqnarrayboxHBOXSW% +\@IEEEeqnarrayboxHBOXSWfalse + +\def\@IEEEeqnarraybox{\relax\@ifnextchar[{\@@IEEEeqnarraybox}{\@@IEEEeqnarraybox[\relax]}} +\def\@@IEEEeqnarraybox[#1]{\relax\@ifnextchar[{\@@@IEEEeqnarraybox[#1]}{\@@@IEEEeqnarraybox[#1][b]}} +\def\@@@IEEEeqnarraybox[#1][#2]{\relax\@ifnextchar[{\@@@@IEEEeqnarraybox[#1][#2]}{\@@@@IEEEeqnarraybox[#1][#2][\relax]}} + +% #1 = decl; #2 = t,b,c; #3 = width, #4 = col specs +\def\@@@@IEEEeqnarraybox[#1][#2][#3]#4{\@IEEEeqnarrayISinnerfalse % not yet within the lines of the halign + \@IEEEeqnarraymasterstrutsave% save current master strut values + \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default + \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise + \IEEEvisiblestrutsfalse% diagnostic mode defaults to off + % no extra space unless the user specifically requests it + \lineskip=0pt\relax% + \lineskiplimit=0pt\relax% + \baselineskip=\normalbaselineskip\relax% + \jot=\IEEEnormaljot\relax% + \mathsurround\z@\relax% no extra spacing around math + % the default end glues are zero for an \IEEEeqnarraybox + \edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPzero}% default start glue + \edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPzero}% default end glue + \edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue + \@advanceIEEEeqncolcntfalse% do not advance the col counter for each col the user uses, + % used in \IEEEeqnarraymulticol and in the preamble build + \IEEEeqnarrayboxdecl\relax% allow a way for the user to make global overrides + #1\relax% allow user to override defaults + \let\\\@IEEEeqnarrayboxcr% replace newline with one that allows optional spacing + \@IEEEbuildpreamble #4\end\relax% build the preamble and put it into \@IEEEtrantmptoksA + % add an isolation column to the preamble to stop \\'s {} from getting into the last col + \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first + \toks0={##}% + % add the isolation column to the preamble + \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% + % set the starting tabskip glue as determined by the preamble build + \tabskip=\@IEEEBPstartglue\relax + % begin the alignment + \everycr{}% + % use only the very first token to determine the positioning + % this stops some problems when the user uses more than one letter, + % but is probably not worth the effort + % \noindent is used as a delimiter + \def\@IEEEgrabfirstoken##1##2\noindent{\let\@IEEEgrabbedfirstoken=##1}% + \@IEEEgrabfirstoken#2\relax\relax\noindent + % \@IEEEgrabbedfirstoken has the first token, the rest are discarded + % if we need to put things into and hbox and go into math mode, do so now + \if@IEEEeqnarrayboxHBOXSW \leavevmode \hbox \bgroup $\fi% + % use the appropriate vbox type + \if\@IEEEgrabbedfirstoken t\relax\vtop\else\if\@IEEEgrabbedfirstoken c\relax% + \vcenter\else\vbox\fi\fi\bgroup% + \@IEEEeqnarrayISinnertrue% commands are now within the lines + \ifx#3\relax\halign\else\halign to #3\relax\fi% + \bgroup + % "exspand" the preamble + \span\the\@IEEEtrantmptoksA\cr} + +% carry strut status and enter the isolation/strut column, +% exit from math mode if needed, and exit +\def\end@IEEEeqnarraybox{\@IEEEeqnarrayglobalizestrutstatus% carry strut status +&% enter isolation/strut column +\@IEEEeqnarrayinsertstrut% do strut if needed +\@IEEEeqnarraymasterstrutrestore% restore the previous master strut values +% reset the strut system for next IEEEeqnarray +% (sets local strut values back to previous master strut values) +\@IEEEeqnarraystrutreset% +% ensure last line, exit from halign, close vbox +\crcr\egroup\egroup% +% exit from math mode and close hbox if needed +\if@IEEEeqnarrayboxHBOXSW $\egroup\fi} + + + +% IEEEeqnarraybox uses a modifed \\ instead of the plain \cr to +% end rows. This allows for things like \\[vskip amount] +% This "cr" macros are modified versions those for LaTeX2e's eqnarray +% For IEEEeqnarraybox, \\* is the same as \\ +% the {\ifnum0=`} braces must be kept away from the last column to avoid +% altering spacing of its math, so we use & to advance to the isolation/strut column +% carry strut status into isolation/strut column +\def\@IEEEeqnarrayboxcr{\@IEEEeqnarrayglobalizestrutstatus% carry strut status +&% enter isolation/strut column +\@IEEEeqnarrayinsertstrut% do strut if needed +% reset the strut system for next line or IEEEeqnarray +\@IEEEeqnarraystrutreset% +{\ifnum0=`}\fi% +\@ifstar{\@IEEEeqnarrayboxYCR}{\@IEEEeqnarrayboxYCR}} + +% test and setup the optional argument to \\[] +\def\@IEEEeqnarrayboxYCR{\@testopt\@IEEEeqnarrayboxXCR\z@skip} + +% IEEEeqnarraybox does not automatically increase line spacing by \jot +\def\@IEEEeqnarrayboxXCR[#1]{\ifnum0=`{\fi}% +\cr\noalign{\if@IEEEeqnarraystarform\else\vskip\jot\fi\vskip#1\relax}} + + + +% starts the halign preamble build +\def\@IEEEbuildpreamble{\@IEEEtrantmptoksA={}% clear token register +\let\@IEEEBPcurtype=u%current column type is not yet known +\let\@IEEEBPprevtype=s%the previous column type was the start +\let\@IEEEBPnexttype=u%next column type is not yet known +% ensure these are valid +\def\@IEEEBPcurglue={0pt plus 0pt minus 0pt}% +\def\@IEEEBPcurcolname{@IEEEdefault}% name of current column definition +% currently acquired numerically referenced glue +% use a name that is easier to remember +\let\@IEEEBPcurnum=\@IEEEtrantmpcountA% +\@IEEEBPcurnum=0% +% tracks number of columns in the preamble +\@IEEEeqnnumcols=0% +% record the default end glues +\edef\@IEEEBPstartglue{\@IEEEeqnarraycolSEPdefaultstart}% +\edef\@IEEEBPendglue{\@IEEEeqnarraycolSEPdefaultend}% +% now parse the user's column specifications +\@@IEEEbuildpreamble} + + +% parses and builds the halign preamble +\def\@@IEEEbuildpreamble#1#2{\let\@@nextIEEEbuildpreamble=\@@IEEEbuildpreamble% +% use only the very first token to check the end +% \noindent is used as a delimiter as \end can be present here +\def\@IEEEgrabfirstoken##1##2\noindent{\let\@IEEEgrabbedfirstoken=##1}% +\@IEEEgrabfirstoken#1\relax\relax\noindent +\ifx\@IEEEgrabbedfirstoken\end\let\@@nextIEEEbuildpreamble=\@@IEEEfinishpreamble\else% +% identify current and next token type +\@IEEEgetcoltype{#1}{\@IEEEBPcurtype}{1}% current, error on invalid +\@IEEEgetcoltype{#2}{\@IEEEBPnexttype}{0}% next, no error on invalid next +% if curtype is a glue, get the glue def +\if\@IEEEBPcurtype g\@IEEEgetcurglue{#1}{\@IEEEBPcurglue}\fi% +% if curtype is a column, get the column def and set the current column name +\if\@IEEEBPcurtype c\@IEEEgetcurcol{#1}\fi% +% if curtype is a numeral, acquire the user defined glue +\if\@IEEEBPcurtype n\@IEEEprocessNcol{#1}\fi% +% process the acquired glue +\if\@IEEEBPcurtype g\@IEEEprocessGcol\fi% +% process the acquired col +\if\@IEEEBPcurtype c\@IEEEprocessCcol\fi% +% ready prevtype for next col spec. +\let\@IEEEBPprevtype=\@IEEEBPcurtype% +% be sure and put back the future token(s) as a group +\fi\@@nextIEEEbuildpreamble{#2}} + + +% executed just after preamble build is completed +% warn about zero cols, and if prevtype type = u, put in end tabskip glue +\def\@@IEEEfinishpreamble#1{\ifnum\@IEEEeqnnumcols<1\relax +\@IEEEclspkgerror{No column specifiers declared for IEEEeqnarray}% +{At least one column type must be declared for each IEEEeqnarray.}% +\fi%num cols less than 1 +%if last type undefined, set default end tabskip glue +\if\@IEEEBPprevtype u\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue}\fi} + + +% Identify and return the column specifier's type code +\def\@IEEEgetcoltype#1#2#3{% +% use only the very first token to determine the type +% \noindent is used as a delimiter as \end can be present here +\def\@IEEEgrabfirstoken##1##2\noindent{\let\@IEEEgrabbedfirstoken=##1}% +\@IEEEgrabfirstoken#1\relax\relax\noindent +% \@IEEEgrabfirstoken has the first token, the rest are discarded +% n = number +% g = glue (any other char in catagory 12) +% c = letter +% e = \end +% u = undefined +% third argument: 0 = no error message, 1 = error on invalid char +\let#2=u\relax% assume invalid until know otherwise +\ifx\@IEEEgrabbedfirstoken\end\let#2=e\else +\ifcat\@IEEEgrabbedfirstoken\relax\else% screen out control sequences +\if0\@IEEEgrabbedfirstoken\let#2=n\else +\if1\@IEEEgrabbedfirstoken\let#2=n\else +\if2\@IEEEgrabbedfirstoken\let#2=n\else +\if3\@IEEEgrabbedfirstoken\let#2=n\else +\if4\@IEEEgrabbedfirstoken\let#2=n\else +\if5\@IEEEgrabbedfirstoken\let#2=n\else +\if6\@IEEEgrabbedfirstoken\let#2=n\else +\if7\@IEEEgrabbedfirstoken\let#2=n\else +\if8\@IEEEgrabbedfirstoken\let#2=n\else +\if9\@IEEEgrabbedfirstoken\let#2=n\else +\ifcat,\@IEEEgrabbedfirstoken\let#2=g\relax +\else\ifcat a\@IEEEgrabbedfirstoken\let#2=c\relax\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi +\if#2u\relax +\if0\noexpand#3\relax\else\@IEEEclspkgerror{Invalid character in column specifications}% +{Only letters, numerals and certain other symbols are allowed \MessageBreak +as IEEEeqnarray column specifiers.}\fi\fi} + + +% identify the current letter referenced column +% if invalid, use a default column +\def\@IEEEgetcurcol#1{\expandafter\ifx\csname @IEEEeqnarraycolDEF#1\endcsname\@IEEEeqnarraycolisdefined% +\def\@IEEEBPcurcolname{#1}\else% invalid column name +\@IEEEclspkgerror{Invalid column type "#1" in column specifications.\MessageBreak +Using a default centering column instead}% +{You must define IEEEeqnarray column types before use.}% +\def\@IEEEBPcurcolname{@IEEEdefault}\fi} + + +% identify and return the predefined (punctuation) glue value +\def\@IEEEgetcurglue#1#2{% +% ! = \! (neg small) -0.16667em (-3/18 em) +% , = \, (small) 0.16667em ( 3/18 em) +% : = \: (med) 0.22222em ( 4/18 em) +% ; = \; (large) 0.27778em ( 5/18 em) +% ' = \quad 1em +% " = \qquad 2em +% . = 0.5\arraycolsep +% / = \arraycolsep +% ? = 2\arraycolsep +% * = 1fil +% + = \@IEEEeqnarraycolSEPcenter +% - = \@IEEEeqnarraycolSEPzero +% Note that all em values are referenced to the math font (textfont2) fontdimen6 +% value for 1em. +% +% use only the very first token to determine the type +% this prevents errant tokens from getting in the main text +% \noindent is used as a delimiter here +\def\@IEEEgrabfirstoken##1##2\noindent{\let\@IEEEgrabbedfirstoken=##1}% +\@IEEEgrabfirstoken#1\relax\relax\noindent +% get the math font 1em value +% LaTeX2e's NFSS2 does not preload the fonts, but \IEEEeqnarray needs +% to gain access to the math (\textfont2) font's spacing parameters. +% So we create a bogus box here that uses the math font to ensure +% that \textfont2 is loaded and ready. If this is not done, +% the \textfont2 stuff here may not work. +% Thanks to Bernd Raichle for his 1997 post on this topic. +{\setbox0=\hbox{$\displaystyle\relax$}}% +% fontdimen6 has the width of 1em (a quad). +\@IEEEtrantmpdimenA=\fontdimen6\textfont2\relax% +% identify the glue value based on the first token +% we discard anything after the first +\if!\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=-0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if,\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if:\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=0.22222\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if;\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=0.27778\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if'\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=1\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if"\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=2\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if.\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=0.5\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else +\if/\@IEEEgrabbedfirstoken\edef#2{\the\arraycolsep}\else +\if?\@IEEEgrabbedfirstoken\@IEEEtrantmpdimenA=2\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else +\if *\@IEEEgrabbedfirstoken\edef#2{0pt plus 1fil minus 0pt}\else +\if+\@IEEEgrabbedfirstoken\edef#2{\@IEEEeqnarraycolSEPcenter}\else +\if-\@IEEEgrabbedfirstoken\edef#2{\@IEEEeqnarraycolSEPzero}\else +\edef#2{\@IEEEeqnarraycolSEPzero}% +\@IEEEclspkgerror{Invalid predefined inter-column glue type "#1" in\MessageBreak +column specifications. Using a default value of\MessageBreak +0pt instead}% +{Only !,:;'"./?*+ and - are valid predefined glue types in the\MessageBreak +IEEEeqnarray column specifications.}\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi} + + + +% process a numerical digit from the column specification +% and look up the corresponding user defined glue value +% can transform current type from n to g or a as the user defined glue is acquired +\def\@IEEEprocessNcol#1{\if\@IEEEBPprevtype g% +\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak +specifications. Ignoring consecutive glue specifiers\MessageBreak +after the first}% +{You cannot have two or more glue types next to each other\MessageBreak +in the IEEEeqnarray column specifications.}% +\let\@IEEEBPcurtype=a% abort this glue, future digits will be discarded +\@IEEEBPcurnum=0\relax% +\else% if we previously aborted a glue +\if\@IEEEBPprevtype a\@IEEEBPcurnum=0\let\@IEEEBPcurtype=a%maintain digit abortion +\else%acquire this number +% save the previous type before the numerical digits started +\if\@IEEEBPprevtype n\else\let\@IEEEBPprevsavedtype=\@IEEEBPprevtype\fi% +\multiply\@IEEEBPcurnum by 10\relax% +\advance\@IEEEBPcurnum by #1\relax% add in number, \relax is needed to stop TeX's number scan +\if\@IEEEBPnexttype n\else%close acquisition +\expandafter\ifx\csname @IEEEeqnarraycolSEPDEF\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname\@IEEEeqnarraycolisdefined% +\edef\@IEEEBPcurglue{\csname @IEEEeqnarraycolSEP\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname}% +\else%user glue not defined +\@IEEEclspkgerror{Invalid user defined inter-column glue type "\number\@IEEEBPcurnum" in\MessageBreak +column specifications. Using a default value of\MessageBreak +0pt instead}% +{You must define all IEEEeqnarray numerical inter-column glue types via\MessageBreak +\string\IEEEeqnarraydefcolsep \space before they are used in column specifications.}% +\edef\@IEEEBPcurglue{\@IEEEeqnarraycolSEPzero}% +\fi% glue defined or not +\let\@IEEEBPcurtype=g% change the type to reflect the acquired glue +\let\@IEEEBPprevtype=\@IEEEBPprevsavedtype% restore the prev type before this number glue +\@IEEEBPcurnum=0\relax%ready for next acquisition +\fi%close acquisition, get glue +\fi%discard or acquire number +\fi%prevtype glue or not +} + + +% process an acquired glue +% add any acquired column/glue pair to the preamble +\def\@IEEEprocessGcol{\if\@IEEEBPprevtype a\let\@IEEEBPcurtype=a%maintain previous glue abortions +\else +% if this is the start glue, save it, but do nothing else +% as this is not used in the preamble, but before +\if\@IEEEBPprevtype s\edef\@IEEEBPstartglue{\@IEEEBPcurglue}% +\else%not the start glue +\if\@IEEEBPprevtype g%ignore if back to back glues +\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak +specifications. Ignoring consecutive glue specifiers\MessageBreak +after the first}% +{You cannot have two or more glue types next to each other\MessageBreak +in the IEEEeqnarray column specifications.}% +\let\@IEEEBPcurtype=a% abort this glue +\else% not a back to back glue +\if\@IEEEBPprevtype c\relax% if the previoustype was a col, add column/glue pair to preamble +\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi +\toks0={##}% +% make preamble advance col counter if this environment needs this +\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi +% insert the column defintion into the preamble, being careful not to expand +% the column definition +\@IEEEappendtoksA{\tabskip=\@IEEEBPcurglue}% +\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname}% +\@IEEEappendtoksA{\the\toks0}% +\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\endgroup}% +\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble +\else% error: non-start glue with no pending column +\@IEEEclspkgerror{Inter-column glue specifier without a prior column\MessageBreak +type in the column specifications. Ignoring this glue\MessageBreak +specifier}% +{Except for the first and last positions, glue can be placed only\MessageBreak +between column types.}% +\let\@IEEEBPcurtype=a% abort this glue +\fi% previous was a column +\fi% back-to-back glues +\fi% is start column glue +\fi% prev type not a +} + + +% process an acquired letter referenced column and, if necessary, add it to the preamble +\def\@IEEEprocessCcol{\if\@IEEEBPnexttype g\else +\if\@IEEEBPnexttype n\else +% we have a column followed by something other than a glue (or numeral glue) +% so we must add this column to the preamble now +\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi%col separator for those after the first +\if\@IEEEBPnexttype e\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue\relax}\else%put in end glue +\@IEEEappendtoksA{\tabskip=\@IEEEeqnarraycolSEPdefaultmid\relax}\fi% or default mid glue +\toks0={##}% +% make preamble advance col counter if this environment needs this +\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi +% insert the column definition into the preamble, being careful not to expand +% the column definition +\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname}% +\@IEEEappendtoksA{\the\toks0}% +\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\endgroup}% +\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble +\fi%next type not numeral +\fi%next type not glue +} + + +%% +%% END OF IEEEeqnarry DEFINITIONS +%% + + + + +% set up the running headings, this complex because of all the different +% modes IEEEtran supports +\if@twoside + \ifCLASSOPTIONtechnote + \def\ps@headings{% + \def\@oddhead{\hbox{}\scriptsize\leftmark \hfil \thepage} + \def\@evenhead{\scriptsize\thepage \hfil \leftmark\hbox{}} + \ifCLASSOPTIONdraftcls + \ifCLASSOPTIONdraftclsnofoot + \def\@oddfoot{}\def\@evenfoot{}% + \else + \def\@oddfoot{\scriptsize\@date\hfil DRAFT} + \def\@evenfoot{\scriptsize DRAFT\hfil\@date} + \fi + \else + \def\@oddfoot{}\def\@evenfoot{} + \fi} + \else % not a technote + \def\ps@headings{% + \ifCLASSOPTIONconference + \def\@oddhead{} + \def\@evenhead{} + \else + \def\@oddhead{\hbox{}\scriptsize\rightmark \hfil \thepage} + \def\@evenhead{\scriptsize\thepage \hfil \leftmark\hbox{}} + \fi + \ifCLASSOPTIONdraftcls + \def\@oddhead{\hbox{}\scriptsize\rightmark \hfil \thepage} + \def\@evenhead{\scriptsize\thepage \hfil \leftmark\hbox{}} + \ifCLASSOPTIONdraftclsnofoot + \def\@oddfoot{}\def\@evenfoot{}% + \else + \def\@oddfoot{\scriptsize\@date\hfil DRAFT} + \def\@evenfoot{\scriptsize DRAFT\hfil\@date} + \fi + \else + \def\@oddfoot{}\def\@evenfoot{}% + \fi} + \fi +\else % single side +\def\ps@headings{% + \ifCLASSOPTIONconference + \def\@oddhead{} + \def\@evenhead{} + \else + \def\@oddhead{\hbox{}\scriptsize\leftmark \hfil \thepage} + \def\@evenhead{} + \fi + \ifCLASSOPTIONdraftcls + \def\@oddhead{\hbox{}\scriptsize\leftmark \hfil \thepage} + \def\@evenhead{} + \ifCLASSOPTIONdraftclsnofoot + \def\@oddfoot{} + \else + \def\@oddfoot{\scriptsize \@date \hfil DRAFT} + \fi + \else + \def\@oddfoot{} + \fi + \def\@evenfoot{}} +\fi + + +% title page style +\def\ps@IEEEtitlepagestyle{\def\@oddfoot{}\def\@evenfoot{}% +\ifCLASSOPTIONconference + \def\@oddhead{}% + \def\@evenhead{}% +\else + \def\@oddhead{\hbox{}\scriptsize\leftmark \hfil \thepage}% + \def\@evenhead{\scriptsize\thepage \hfil \leftmark\hbox{}}% +\fi +\ifCLASSOPTIONdraftcls + \def\@oddhead{\hbox{}\scriptsize\leftmark \hfil \thepage}% + \def\@evenhead{\scriptsize\thepage \hfil \leftmark\hbox{}}% + \ifCLASSOPTIONdraftclsnofoot\else + \def\@oddfoot{\scriptsize \@date\hfil DRAFT}% + \def\@evenfoot{\scriptsize DRAFT\hfil \@date}% + \fi +\else + % all non-draft mode footers + \if@IEEEusingpubid + % for title pages that are using a pubid + % do not repeat pubid if using peer review option + \ifCLASSOPTIONpeerreview + \else + \footskip 0pt% + \ifCLASSOPTIONcompsoc + \def\@oddfoot{\hss\normalfont\scriptsize\raisebox{-1.5\@IEEEnormalsizeunitybaselineskip}[0ex][0ex]{\@IEEEpubid}\hss}% + \def\@evenfoot{\hss\normalfont\scriptsize\raisebox{-1.5\@IEEEnormalsizeunitybaselineskip}[0ex][0ex]{\@IEEEpubid}\hss}% + \else + \def\@oddfoot{\hss\normalfont\footnotesize\raisebox{1.5ex}[1.5ex]{\@IEEEpubid}\hss}% + \def\@evenfoot{\hss\normalfont\footnotesize\raisebox{1.5ex}[1.5ex]{\@IEEEpubid}\hss}% + \fi + \fi + \fi +\fi} + + +% peer review cover page style +\def\ps@IEEEpeerreviewcoverpagestyle{% +\def\@oddhead{}\def\@evenhead{}% +\def\@oddfoot{}\def\@evenfoot{}% +\ifCLASSOPTIONdraftcls + \ifCLASSOPTIONdraftclsnofoot\else + \def\@oddfoot{\scriptsize \@date\hfil DRAFT}% + \def\@evenfoot{\scriptsize DRAFT\hfil \@date}% + \fi +\else + % non-draft mode footers + \if@IEEEusingpubid + \footskip 0pt% + \ifCLASSOPTIONcompsoc + \def\@oddfoot{\hss\normalfont\scriptsize\raisebox{-1.5\@IEEEnormalsizeunitybaselineskip}[0ex][0ex]{\@IEEEpubid}\hss}% + \def\@evenfoot{\hss\normalfont\scriptsize\raisebox{-1.5\@IEEEnormalsizeunitybaselineskip}[0ex][0ex]{\@IEEEpubid}\hss}% + \else + \def\@oddfoot{\hss\normalfont\footnotesize\raisebox{1.5ex}[1.5ex]{\@IEEEpubid}\hss}% + \def\@evenfoot{\hss\normalfont\footnotesize\raisebox{1.5ex}[1.5ex]{\@IEEEpubid}\hss}% + \fi + \fi +\fi} + + +% start with empty headings +\def\rightmark{}\def\leftmark{} + + +%% Defines the command for putting the header. \footernote{TEXT} is the same +%% as \markboth{TEXT}{TEXT}. +%% Note that all the text is forced into uppercase, if you have some text +%% that needs to be in lower case, for instance et. al., then either manually +%% set \leftmark and \rightmark or use \MakeLowercase{et. al.} within the +%% arguments to \markboth. +\def\markboth#1#2{\def\leftmark{\@IEEEcompsoconly{\sffamily}\MakeUppercase{#1}}% +\def\rightmark{\@IEEEcompsoconly{\sffamily}\MakeUppercase{#2}}} +\def\footernote#1{\markboth{#1}{#1}} + +\def\today{\ifcase\month\or + January\or February\or March\or April\or May\or June\or + July\or August\or September\or October\or November\or December\fi + \space\number\day, \number\year} + + + + +%% CITATION AND BIBLIOGRAPHY COMMANDS +%% +%% V1.6 no longer supports the older, nonstandard \shortcite and \citename setup stuff +% +% +% Modify Latex2e \@citex to separate citations with "], [" +\def\@citex[#1]#2{% + \let\@citea\@empty + \@cite{\@for\@citeb:=#2\do + {\@citea\def\@citea{], [}% + \edef\@citeb{\expandafter\@firstofone\@citeb\@empty}% + \if@filesw\immediate\write\@auxout{\string\citation{\@citeb}}\fi + \@ifundefined{b@\@citeb}{\mbox{\reset@font\bfseries ?}% + \G@refundefinedtrue + \@latex@warning + {Citation `\@citeb' on page \thepage \space undefined}}% + {\hbox{\csname b@\@citeb\endcsname}}}}{#1}} + +% V1.6 we create hooks for the optional use of Donald Arseneau's +% cite.sty package. cite.sty is "smart" and will notice that the +% following format controls are already defined and will not +% redefine them. The result will be the proper sorting of the +% citation numbers and auto detection of 3 or more entry "ranges" - +% all in IEEE style: [1], [2], [5]--[7], [12] +% This also allows for an optional note, i.e., \cite[mynote]{..}. +% If the \cite with note has more than one reference, the note will +% be applied to the last of the listed references. It is generally +% desired that if a note is given, only one reference is listed in +% that \cite. +% Thanks to Mr. Arseneau for providing the required format arguments +% to produce the IEEE style. +\def\citepunct{], [} +\def\citedash{]--[} + +% V1.7 default to using same font for urls made by url.sty +\AtBeginDocument{\csname url@samestyle\endcsname} + +% V1.6 class files should always provide these +\def\newblock{\hskip .11em\@plus.33em\@minus.07em} +\let\@openbib@code\@empty + + +% Provide support for the control entries of IEEEtran.bst V1.00 and later. +% V1.7 optional argument allows for a different aux file to be specified in +% order to handle multiple bibliographies. For example, with multibib.sty: +% \newcites{sec}{Secondary Literature} +% \bstctlcite[@auxoutsec]{BSTcontrolhak} +\def\bstctlcite{\@ifnextchar[{\@bstctlcite}{\@bstctlcite[@auxout]}} +\def\@bstctlcite[#1]#2{\@bsphack + \@for\@citeb:=#2\do{% + \edef\@citeb{\expandafter\@firstofone\@citeb}% + \if@filesw\immediate\write\csname #1\endcsname{\string\citation{\@citeb}}\fi}% + \@esphack} + +% V1.6 provide a way for a user to execute a command just before +% a given reference number - used to insert a \newpage to balance +% the columns on the last page +\edef\@IEEEtriggerrefnum{0} % the default of zero means that + % the command is not executed +\def\@IEEEtriggercmd{\newpage} + +% allow the user to alter the triggered command +\long\def\IEEEtriggercmd#1{\long\def\@IEEEtriggercmd{#1}} + +% allow user a way to specify the reference number just before the +% command is executed +\def\IEEEtriggeratref#1{\@IEEEtrantmpcountA=#1% +\edef\@IEEEtriggerrefnum{\the\@IEEEtrantmpcountA}}% + +% trigger command at the given reference +\def\@IEEEbibitemprefix{\@IEEEtrantmpcountA=\@IEEEtriggerrefnum\relax% +\advance\@IEEEtrantmpcountA by -1\relax% +\ifnum\c@enumiv=\@IEEEtrantmpcountA\relax\@IEEEtriggercmd\relax\fi} + + +\def\@biblabel#1{[#1]} + +% compsoc journals left align the reference numbers +\@IEEEcompsocnotconfonly{\def\@biblabel#1{[#1]\hfill}} + +% controls bib item spacing +\def\IEEEbibitemsep{2.5pt plus .5pt} + +\@IEEEcompsocconfonly{\def\IEEEbibitemsep{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}} + + +\def\thebibliography#1{\section*{\refname}% + \addcontentsline{toc}{section}{\refname}% + % V1.6 add some rubber space here and provide a command trigger + \footnotesize\@IEEEcompsocconfonly{\small}\vskip 0.3\baselineskip plus 0.1\baselineskip minus 0.1\baselineskip% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \labelsep 1em + \advance\leftmargin\labelsep\relax + \itemsep \IEEEbibitemsep\relax + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \let\@IEEElatexbibitem\bibitem% + \def\bibitem{\@IEEEbibitemprefix\@IEEElatexbibitem}% +\def\newblock{\hskip .11em plus .33em minus .07em}% +% originally: +% \sloppy\clubpenalty4000\widowpenalty4000% +% by adding the \interlinepenalty here, we make it more +% difficult, but not impossible, for LaTeX to break within a reference. +% IEEE almost never breaks a reference (but they do it more often with +% technotes). You may get an underfull vbox warning around the bibliography, +% but the final result will be much more like what IEEE will publish. +% MDS 11/2000 +\ifCLASSOPTIONtechnote\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty100% +\else\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty500\fi% + \sfcode`\.=1000\relax} +\let\endthebibliography=\endlist + + + + +% TITLE PAGE COMMANDS +% +% +% \IEEEmembership is used to produce the sublargesize italic font used to indicate author +% IEEE membership. compsoc uses a large size sans slant font +\def\IEEEmembership#1{{\@IEEEnotcompsoconly{\sublargesize}\normalfont\@IEEEcompsoconly{\sffamily}\textit{#1}}} + + +% \IEEEauthorrefmark{} produces a footnote type symbol to indicate author affiliation. +% When given an argument of 1 to 9, \IEEEauthorrefmark{} follows the standard LaTeX footnote +% symbol sequence convention. However, for arguments 10 and above, \IEEEauthorrefmark{} +% reverts to using lower case roman numerals, so it cannot overflow. Do note that you +% cannot use \footnotemark[] in place of \IEEEauthorrefmark{} within \author as the footnote +% symbols will have been turned off to prevent \thanks from creating footnote marks. +% \IEEEauthorrefmark{} produces a symbol that appears to LaTeX as having zero vertical +% height - this allows for a more compact line packing, but the user must ensure that +% the interline spacing is large enough to prevent \IEEEauthorrefmark{} from colliding +% with the text above. +% V1.7 make this a robust command +\DeclareRobustCommand*{\IEEEauthorrefmark}[1]{\raisebox{0pt}[0pt][0pt]{\textsuperscript{\footnotesize\ensuremath{\ifcase#1\or *\or \dagger\or \ddagger\or% + \mathsection\or \mathparagraph\or \|\or **\or \dagger\dagger% + \or \ddagger\ddagger \else\textsuperscript{\expandafter\romannumeral#1}\fi}}}} + + +% FONT CONTROLS AND SPACINGS FOR CONFERENCE MODE AUTHOR NAME AND AFFILIATION BLOCKS +% +% The default font styles for the author name and affiliation blocks (confmode) +\def\@IEEEauthorblockNstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize\@IEEEcompsocconfonly{\large}} +\def\@IEEEauthorblockAstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\@IEEEcompsocconfonly{\itshape}\normalsize\@IEEEcompsocconfonly{\large}} +% The default if the user does not use an author block +\def\@IEEEauthordefaulttextstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize} + +% spacing from title (or special paper notice) to author name blocks (confmode) +% can be negative +\def\@IEEEauthorblockconfadjspace{-0.25em} +% compsoc conferences need more space here +\@IEEEcompsocconfonly{\def\@IEEEauthorblockconfadjspace{0.75\@IEEEnormalsizeunitybaselineskip}} +\ifCLASSOPTIONconference\def\@IEEEauthorblockconfadjspace{20pt}\fi + +% spacing between name and affiliation blocks (confmode) +% This can be negative. +% IEEE doesn't want any added spacing here, but I will leave these +% controls in place in case they ever change their mind. +% Personally, I like 0.75ex. +%\def\@IEEEauthorblockNtopspace{0.75ex} +%\def\@IEEEauthorblockAtopspace{0.75ex} +\def\@IEEEauthorblockNtopspace{0.0ex} +\def\@IEEEauthorblockAtopspace{0.0ex} +% baseline spacing within name and affiliation blocks (confmode) +% must be positive, spacings below certain values will make +% the position of line of text sensitive to the contents of the +% line above it i.e., whether or not the prior line has descenders, +% subscripts, etc. For this reason it is a good idea to keep +% these above 2.6ex +\def\@IEEEauthorblockNinterlinespace{2.6ex} +\def\@IEEEauthorblockAinterlinespace{2.75ex} + +% This tracks the required strut size. +% See the \@IEEEauthorhalign command for the actual default value used. +\def\@IEEEauthorblockXinterlinespace{2.7ex} + +% variables to retain font size and style across groups +% values given here have no effect as they will be overwritten later +\gdef\@IEEESAVESTATEfontsize{10} +\gdef\@IEEESAVESTATEfontbaselineskip{12} +\gdef\@IEEESAVESTATEfontencoding{OT1} +\gdef\@IEEESAVESTATEfontfamily{ptm} +\gdef\@IEEESAVESTATEfontseries{m} +\gdef\@IEEESAVESTATEfontshape{n} + +% saves the current font attributes +\def\@IEEEcurfontSAVE{\global\let\@IEEESAVESTATEfontsize\f@size% +\global\let\@IEEESAVESTATEfontbaselineskip\f@baselineskip% +\global\let\@IEEESAVESTATEfontencoding\f@encoding% +\global\let\@IEEESAVESTATEfontfamily\f@family% +\global\let\@IEEESAVESTATEfontseries\f@series% +\global\let\@IEEESAVESTATEfontshape\f@shape} + +% restores the saved font attributes +\def\@IEEEcurfontRESTORE{\fontsize{\@IEEESAVESTATEfontsize}{\@IEEESAVESTATEfontbaselineskip}% +\fontencoding{\@IEEESAVESTATEfontencoding}% +\fontfamily{\@IEEESAVESTATEfontfamily}% +\fontseries{\@IEEESAVESTATEfontseries}% +\fontshape{\@IEEESAVESTATEfontshape}% +\selectfont} + + +% variable to indicate if the current block is the first block in the column +\newif\if@IEEEprevauthorblockincol \@IEEEprevauthorblockincolfalse + + +% the command places a strut with height and depth = \@IEEEauthorblockXinterlinespace +% we use this technique to have complete manual control over the spacing of the lines +% within the halign environment. +% We set the below baseline portion at 30%, the above +% baseline portion at 70% of the total length. +% Responds to changes in the document's \baselinestretch +\def\@IEEEauthorstrutrule{\@IEEEtrantmpdimenA\@IEEEauthorblockXinterlinespace% +\@IEEEtrantmpdimenA=\baselinestretch\@IEEEtrantmpdimenA% +\rule[-0.3\@IEEEtrantmpdimenA]{0pt}{\@IEEEtrantmpdimenA}} + + +% blocks to hold the authors' names and affilations. +% Makes formatting easy for conferences +% +% use real definitions in conference mode +% name block +\def\IEEEauthorblockN#1{\relax\@IEEEauthorblockNstyle% set the default text style +\gdef\@IEEEauthorblockXinterlinespace{0pt}% disable strut for spacer row +% the \expandafter hides the \cr in conditional tex, see the array.sty docs +% for details, probably not needed here as the \cr is in a macro +% do a spacer row if needed +\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockNtopspaceline\fi +\global\@IEEEprevauthorblockincoltrue% we now have a block in this column +%restore the correct strut value +\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockNinterlinespace}% +% input the author names +#1% +% end the row if the user did not already +\crcr} +% spacer row for names +\def\@IEEEauthorblockNtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockNtopspace}} +% +% affiliation block +\def\IEEEauthorblockA#1{\relax\@IEEEauthorblockAstyle% set the default text style +\gdef\@IEEEauthorblockXinterlinespace{0pt}%disable strut for spacer row +% the \expandafter hides the \cr in conditional tex, see the array.sty docs +% for details, probably not needed here as the \cr is in a macro +% do a spacer row if needed +\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockAtopspaceline\fi +\global\@IEEEprevauthorblockincoltrue% we now have a block in this column +%restore the correct strut value +\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockAinterlinespace}% +% input the author affiliations +#1% +% end the row if the user did not already +\crcr} +% spacer row for affiliations +\def\@IEEEauthorblockAtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockAtopspace}} + + +% allow papers to compile even if author blocks are used in modes other +% than conference or peerreviewca. For such cases, we provide dummy blocks. +\ifCLASSOPTIONconference +\else + \ifCLASSOPTIONpeerreviewca\else + % not conference or peerreviewca mode + \def\IEEEauthorblockN#1{#1}% + \def\IEEEauthorblockA#1{#1}% + \fi +\fi + + + +% we provide our own halign so as not to have to depend on tabular +\def\@IEEEauthorhalign{\@IEEEauthordefaulttextstyle% default text style + \lineskip=0pt\relax% disable line spacing + \lineskiplimit=0pt\relax% + \baselineskip=0pt\relax% + \@IEEEcurfontSAVE% save the current font + \mathsurround\z@\relax% no extra spacing around math + \let\\\@IEEEauthorhaligncr% replace newline with halign friendly one + \tabskip=0pt\relax% no column spacing + \everycr{}% ensure no problems here + \@IEEEprevauthorblockincolfalse% no author blocks yet + \def\@IEEEauthorblockXinterlinespace{2.7ex}% default interline space + \vtop\bgroup%vtop box + \halign\bgroup&\relax\hfil\@IEEEcurfontRESTORE\relax ##\relax + \hfil\@IEEEcurfontSAVE\@IEEEauthorstrutrule\cr} + +% ensure last line, exit from halign, close vbox +\def\end@IEEEauthorhalign{\crcr\egroup\egroup} + +% handle bogus star form +\def\@IEEEauthorhaligncr{{\ifnum0=`}\fi\@ifstar{\@@IEEEauthorhaligncr}{\@@IEEEauthorhaligncr}} + +% test and setup the optional argument to \\[] +\def\@@IEEEauthorhaligncr{\@testopt\@@@IEEEauthorhaligncr\z@skip} + +% end the line and do the optional spacer +\def\@@@IEEEauthorhaligncr[#1]{\ifnum0=`{\fi}\cr\noalign{\vskip#1\relax}} + + + +% flag to prevent multiple \and warning messages +\newif\if@IEEEWARNand +\@IEEEWARNandtrue + +% if in conference or peerreviewca modes, we support the use of \and as \author is a +% tabular environment, otherwise we warn the user that \and is invalid +% outside of conference or peerreviewca modes. +\def\and{\relax} % provide a bogus \and that we will then override + +\renewcommand{\and}[1][\relax]{\if@IEEEWARNand\typeout{** WARNING: \noexpand\and is valid only + when in conference or peerreviewca}\typeout{modes (line \the\inputlineno).}\fi\global\@IEEEWARNandfalse} + +\ifCLASSOPTIONconference% +\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% +\fi +\ifCLASSOPTIONpeerreviewca +\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% +\fi + + +% page clearing command +% based on LaTeX2e's \cleardoublepage, but allows different page styles +% for the inserted blank pages +\def\@IEEEcleardoublepage#1{\clearpage\if@twoside\ifodd\c@page\else +\hbox{}\thispagestyle{#1}\newpage\if@twocolumn\hbox{}\thispagestyle{#1}\newpage\fi\fi\fi} + + +% user command to invoke the title page +\def\maketitle{\par% + \begingroup% + \normalfont% + \def\thefootnote{}% the \thanks{} mark type is empty + \def\footnotemark{}% and kill space from \thanks within author + \let\@makefnmark\relax% V1.7, must *really* kill footnotemark to remove all \textsuperscript spacing as well. + \footnotesize% equal spacing between thanks lines + \footnotesep 0.7\baselineskip%see global setting of \footnotesep for more info + % V1.7 disable \thanks note indention for compsoc + \@IEEEcompsoconly{\long\def\@makefntext##1{\parindent 1em\noindent\hbox{\@makefnmark}##1}}% + \normalsize% + \ifCLASSOPTIONpeerreview + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \thispagestyle{IEEEpeerreviewcoverpagestyle}\@thanks% + \else + \if@twocolumn% + \ifCLASSOPTIONtechnote% + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \else + \twocolumn[\@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext]% + \fi + \else + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \fi + \thispagestyle{IEEEtitlepagestyle}\@thanks% + \fi + % pullup page for pubid if used. + \if@IEEEusingpubid + \enlargethispage{-\@IEEEpubidpullup}% + \fi + \endgroup + \setcounter{footnote}{0}\let\maketitle\relax\let\@maketitle\relax + \gdef\@thanks{}% + % v1.6b do not clear these as we will need the title again for peer review papers + % \gdef\@author{}\gdef\@title{}% + \let\thanks\relax} + + + +% V1.7 parbox to format \@IEEEcompsoctitleabstractindextext +\long\def\@IEEEcompsoctitleabstractindextextbox#1{\parbox{0.915\textwidth}{#1}} + +% formats the Title, authors names, affiliations and special paper notice +% THIS IS A CONTROLLED SPACING COMMAND! Do not allow blank lines or unintentional +% spaces to enter the definition - use % at the end of each line +\def\@maketitle{\newpage +\begingroup\centering +\ifCLASSOPTIONtechnote% technotes + {\bfseries\large\@IEEEcompsoconly{\sffamily}\@title\par}\vskip 1.3em{\lineskip .5em\@IEEEcompsoconly{\sffamily}\@author + \@IEEEspecialpapernotice\par{\@IEEEcompsoconly{\vskip 1.5em\relax + \@IEEEcompsoctitleabstractindextextbox{\@IEEEcompsoctitleabstractindextext}\par + \hfill\@IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax +\else% not a technote + \vskip0.2em{\Huge\@IEEEcompsoconly{\sffamily}\@IEEEcompsocconfonly{\normalfont\normalsize\vskip 2\@IEEEnormalsizeunitybaselineskip + \bfseries\Large}\@title\par}\vskip1.0em\par% + % V1.6 handle \author differently if in conference mode + \ifCLASSOPTIONconference% + {\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% + \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par}\relax + \else% peerreviewca, peerreview or journal + \ifCLASSOPTIONpeerreviewca + % peerreviewca handles author names just like conference mode + {\@IEEEcompsoconly{\sffamily}\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% + \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par + {\@IEEEcompsoconly{\vskip 1.5em\relax + \@IEEEcompsoctitleabstractindextextbox{\@IEEEcompsoctitleabstractindextext}\par\hfill + \@IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax + \else% journal or peerreview + {\lineskip.5em\@IEEEcompsoconly{\sffamily}\sublargesize\@author\@IEEEspecialpapernotice\par + {\@IEEEcompsoconly{\vskip 1.5em\relax + \@IEEEcompsoctitleabstractindextextbox{\@IEEEcompsoctitleabstractindextext}\par\hfill + \@IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax + \fi + \fi +\fi\par\endgroup} + + + +% V1.7 Computer Society "diamond line" which follows index terms for nonconference papers +\def\@IEEEcompsocdiamondline{\vrule depth 0pt height 0.5pt width 4cm\hspace{7.5pt}% +\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}% +\hspace{7.5pt}\vrule depth 0pt height 0.5pt width 4cm\relax} + +% V1.7 standard LateX2e \thanks, but with \itshape under compsoc. Also make it a \long\def +% We also need to trigger the one-shot footnote rule +\def\@IEEEtriggeroneshotfootnoterule{\global\@IEEEenableoneshotfootnoteruletrue} + + +\long\def\thanks#1{\footnotemark + \protected@xdef\@thanks{\@thanks + \protect\footnotetext[\the\c@footnote]{\@IEEEcompsoconly{\itshape + \protect\@IEEEtriggeroneshotfootnoterule\relax}\ignorespaces#1}}} +\let\@thanks\@empty + +% V1.7 allow \author to contain \par's. This is needed to allow \thanks to contain \par. +\long\def\author#1{\gdef\@author{#1}} + + +% in addition to setting up IEEEitemize, we need to remove a baselineskip space above and +% below it because \list's \pars introduce blank lines because of the footnote struts. +\def\@IEEEsetupcompsocitemizelist{\def\labelitemi{$\bullet$}% +\setlength{\IEEElabelindent}{0pt}\setlength{\parskip}{0pt}% +\setlength{\partopsep}{0pt}\setlength{\topsep}{0.5\baselineskip}\vspace{-1\baselineskip}\relax} + + +% flag for fake non-compsoc \IEEEcompsocthanksitem - prevents line break on very first item +\newif\if@IEEEbreakcompsocthanksitem \@IEEEbreakcompsocthanksitemfalse + +\ifCLASSOPTIONcompsoc +% V1.7 compsoc bullet item \thanks +% also, we need to redefine this to destroy the argument in \@IEEEdynamictitlevspace +\long\def\IEEEcompsocitemizethanks#1{\relax\@IEEEbreakcompsocthanksitemfalse\footnotemark + \protected@xdef\@thanks{\@thanks + \protect\footnotetext[\the\c@footnote]{\itshape\protect\@IEEEtriggeroneshotfootnoterule + {\let\IEEEiedlistdecl\relax\protect\begin{IEEEitemize}[\protect\@IEEEsetupcompsocitemizelist]\ignorespaces#1\relax + \protect\end{IEEEitemize}}\protect\vspace{-1\baselineskip}}}} +\DeclareRobustCommand*{\IEEEcompsocthanksitem}{\item} +\else +% non-compsoc, allow for dual compilation via rerouting to normal \thanks +\long\def\IEEEcompsocitemizethanks#1{\thanks{#1}} +% redirect to "pseudo-par" \hfil\break\indent after swallowing [] from \IEEEcompsocthanksitem[] +\DeclareRobustCommand{\IEEEcompsocthanksitem}{\@ifnextchar [{\@IEEEthanksswallowoptionalarg}% +{\@IEEEthanksswallowoptionalarg[\relax]}} +% be sure and break only after first item, be sure and ignore spaces after optional argument +\def\@IEEEthanksswallowoptionalarg[#1]{\relax\if@IEEEbreakcompsocthanksitem\hfil\break +\indent\fi\@IEEEbreakcompsocthanksitemtrue\ignorespaces} +\fi + + +% V1.6b define the \IEEEpeerreviewmaketitle as needed +\ifCLASSOPTIONpeerreview +\def\IEEEpeerreviewmaketitle{\@IEEEcleardoublepage{empty}% +\ifCLASSOPTIONtwocolumn +\twocolumn[\@IEEEpeerreviewmaketitle\@IEEEdynamictitlevspace] +\else +\newpage\@IEEEpeerreviewmaketitle\@IEEEstatictitlevskip +\fi +\thispagestyle{IEEEtitlepagestyle}} +\else +% \IEEEpeerreviewmaketitle does nothing if peer review option has not been selected +\def\IEEEpeerreviewmaketitle{\relax} +\fi + +% peerreview formats the repeated title like the title in journal papers. +\def\@IEEEpeerreviewmaketitle{\begin{center}\@IEEEcompsoconly{\sffamily}% +\normalfont\normalsize\vskip0.2em{\Huge\@title\par}\vskip1.0em\par +\end{center}} + + + +% V1.6 +% this is a static rubber spacer between the title/authors and the main text +% used for single column text, or when the title appears in the first column +% of two column text (technotes). +\def\@IEEEstatictitlevskip{{\normalfont\normalsize +% adjust spacing to next text +% v1.6b handle peer review papers +\ifCLASSOPTIONpeerreview +% for peer review papers, the same value is used for both title pages +% regardless of the other paper modes + \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip +\else + \ifCLASSOPTIONconference% conference + \vskip 0.6\baselineskip + \else% + \ifCLASSOPTIONtechnote% technote + \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip% + \else% journal uses more space + \vskip 2.5\baselineskip plus 0.75\baselineskip minus 0.375\baselineskip% + \fi + \fi +\fi}} + + +% V1.6 +% This is a dynamically determined rigid spacer between the title/authors +% and the main text. This is used only for single column titles over two +% column text (most common) +% This is bit tricky because we have to ensure that the textheight of the +% main text is an integer multiple of \baselineskip +% otherwise underfull vbox problems may develop in the second column of the +% text on the titlepage +% The possible use of \IEEEpubid must also be taken into account. +\def\@IEEEdynamictitlevspace{{% + % we run within a group so that all the macros can be forgotten when we are done + \long\def\thanks##1{\relax}%don't allow \thanks to run when we evaluate the vbox height + \long\def\IEEEcompsocitemizethanks##1{\relax}%don't allow \IEEEcompsocitemizethanks to run when we evaluate the vbox height + \normalfont\normalsize% we declare more descriptive variable names + \let\@IEEEmaintextheight=\@IEEEtrantmpdimenA%height of the main text columns + \let\@IEEEINTmaintextheight=\@IEEEtrantmpdimenB%height of the main text columns with integer # lines + % set the nominal and minimum values for the title spacer + % the dynamic algorithm will not allow the spacer size to + % become less than \@IEEEMINtitlevspace - instead it will be + % lengthened + % default to journal values + \def\@IEEENORMtitlevspace{2.5\baselineskip}% + \def\@IEEEMINtitlevspace{2\baselineskip}% + % conferences and technotes need tighter spacing + \ifCLASSOPTIONconference%conference + \def\@IEEENORMtitlevspace{1\baselineskip}% + \def\@IEEEMINtitlevspace{0.75\baselineskip}% + \fi + \ifCLASSOPTIONtechnote%technote + \def\@IEEENORMtitlevspace{1\baselineskip}% + \def\@IEEEMINtitlevspace{0.75\baselineskip}% + \fi% + % get the height that the title will take up + \ifCLASSOPTIONpeerreview + \settoheight{\@IEEEmaintextheight}{\vbox{\hsize\textwidth \@IEEEpeerreviewmaketitle}}% + \else + \settoheight{\@IEEEmaintextheight}{\vbox{\hsize\textwidth \@maketitle}}% + \fi + \@IEEEmaintextheight=-\@IEEEmaintextheight% title takes away from maintext, so reverse sign + % add the height of the page textheight + \advance\@IEEEmaintextheight by \textheight% + % correct for title pages using pubid + \ifCLASSOPTIONpeerreview\else + % peerreview papers use the pubid on the cover page only. + % And the cover page uses a static spacer. + \if@IEEEusingpubid\advance\@IEEEmaintextheight by -\@IEEEpubidpullup\fi + \fi% + % subtract off the nominal value of the title bottom spacer + \advance\@IEEEmaintextheight by -\@IEEENORMtitlevspace% + % \topskip takes away some too + \advance\@IEEEmaintextheight by -\topskip% + % calculate the column height of the main text for lines + % now we calculate the main text height as if holding + % an integer number of \normalsize lines after the first + % and discard any excess fractional remainder + % we subtracted the first line, because the first line + % is placed \topskip into the maintext, not \baselineskip like the + % rest of the lines. + \@IEEEINTmaintextheight=\@IEEEmaintextheight% + \divide\@IEEEINTmaintextheight by \baselineskip% + \multiply\@IEEEINTmaintextheight by \baselineskip% + % now we calculate how much the title spacer height will + % have to be reduced from nominal (\@IEEEREDUCEmaintextheight is always + % a positive value) so that the maintext area will contain an integer + % number of normal size lines + % we change variable names here (to avoid confusion) as we no longer + % need \@IEEEINTmaintextheight and can reuse its dimen register + \let\@IEEEREDUCEmaintextheight=\@IEEEINTmaintextheight% + \advance\@IEEEREDUCEmaintextheight by -\@IEEEmaintextheight% + \advance\@IEEEREDUCEmaintextheight by \baselineskip% + % this is the calculated height of the spacer + % we change variable names here (to avoid confusion) as we no longer + % need \@IEEEmaintextheight and can reuse its dimen register + \let\@IEEECOMPENSATElen=\@IEEEmaintextheight% + \@IEEECOMPENSATElen=\@IEEENORMtitlevspace% set the nominal value + % we go with the reduced length if it is smaller than an increase + \ifdim\@IEEEREDUCEmaintextheight < 0.5\baselineskip\relax% + \advance\@IEEECOMPENSATElen by -\@IEEEREDUCEmaintextheight% + % if the resulting spacer is too small back out and go with an increase instead + \ifdim\@IEEECOMPENSATElen<\@IEEEMINtitlevspace\relax% + \advance\@IEEECOMPENSATElen by \baselineskip% + \fi% + \else% + % go with an increase because it is closer to the nominal than a decrease + \advance\@IEEECOMPENSATElen by -\@IEEEREDUCEmaintextheight% + \advance\@IEEECOMPENSATElen by \baselineskip% + \fi% + % set the calculated rigid spacer + \vspace{\@IEEECOMPENSATElen}}} + + + +% V1.6 +% we allow the user access to the last part of the title area +% useful in emergencies such as when a different spacing is needed +% This text is NOT compensated for in the dynamic sizer. +\let\@IEEEaftertitletext=\relax +\long\def\IEEEaftertitletext#1{\def\@IEEEaftertitletext{#1}} + +% V1.7 provide a way for users to enter abstract and keywords +% into the onecolumn title are. This text is compensated for +% in the dynamic sizer. +\let\@IEEEcompsoctitleabstractindextext=\relax +\long\def\IEEEcompsoctitleabstractindextext#1{\def\@IEEEcompsoctitleabstractindextext{#1}} +% V1.7 provide a way for users to get the \@IEEEcompsoctitleabstractindextext if +% not in compsoc journal mode - this way abstract and keywords can be placed +% in their conventional position if not in compsoc mode. +\def\IEEEdisplaynotcompsoctitleabstractindextext{% +\ifCLASSOPTIONcompsoc% display if compsoc conf +\ifCLASSOPTIONconference\@IEEEcompsoctitleabstractindextext\fi +\else% or if not compsoc +\@IEEEcompsoctitleabstractindextext\fi} + + +% command to allow alteration of baselinestretch, but only if the current +% baselineskip is unity. Used to tweak the compsoc abstract and keywords line spacing. +\def\@IEEEtweakunitybaselinestretch#1{{\def\baselinestretch{1}\selectfont +\global\@tempskipa\baselineskip}\ifnum\@tempskipa=\baselineskip% +\def\baselinestretch{#1}\selectfont\fi\relax} + + +% abstract and keywords are in \small, except +% for 9pt docs in which they are in \footnotesize +% Because 9pt docs use an 8pt footnotesize, \small +% becomes a rather awkward 8.5pt +\def\@IEEEabskeysecsize{\small} +\ifx\CLASSOPTIONpt\@IEEEptsizenine + \def\@IEEEabskeysecsize{\footnotesize} +\fi + +% compsoc journals use \footnotesize, compsoc conferences use normalsize +\@IEEEcompsoconly{\def\@IEEEabskeysecsize{\footnotesize}} +\@IEEEcompsocconfonly{\def\@IEEEabskeysecsize{\normalsize}} + + + + +% V1.6 have abstract and keywords strip leading spaces, pars and newlines +% so that spacing is more tightly controlled. +\def\abstract{\normalfont + \if@twocolumn + \par\@IEEEabskeysecsize\bfseries\leavevmode\kern-1pt\textit{\abstractname}---\relax + \else + \begin{center}\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\end{center}\quotation\@IEEEabskeysecsize + \fi\@IEEEgobbleleadPARNLSP} +% V1.6 IEEE wants only 1 pica from end of abstract to introduction heading when in +% conference mode (the heading already has this much above it) +\def\endabstract{\relax\ifCLASSOPTIONconference\vspace{0ex}\else\vspace{1.34ex}\fi\par\if@twocolumn\else\endquotation\fi + \normalfont\normalsize} + +\def\IEEEkeywords{\normalfont + \if@twocolumn + \@IEEEabskeysecsize\bfseries\leavevmode\kern-1pt\textit{\IEEEkeywordsname}---\relax + \else + \begin{center}\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\end{center}\quotation\@IEEEabskeysecsize + \fi\itshape\@IEEEgobbleleadPARNLSP} +\def\endIEEEkeywords{\relax\ifCLASSOPTIONtechnote\vspace{1.34ex}\else\vspace{0.5ex}\fi + \par\if@twocolumn\else\endquotation\fi% + \normalfont\normalsize} + +% V1.7 compsoc keywords index terms +\ifCLASSOPTIONcompsoc + \ifCLASSOPTIONconference% compsoc conference +\def\abstract{\normalfont + \begin{center}\@IEEEabskeysecsize\textbf{\large\abstractname}\end{center}\vskip 0.5\baselineskip plus 0.1\baselineskip minus 0.1\baselineskip + \if@twocolumn\else\quotation\fi\itshape\@IEEEabskeysecsize% + \par\@IEEEgobbleleadPARNLSP} +\def\IEEEkeywords{\normalfont\vskip 1.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip + \begin{center}\@IEEEabskeysecsize\textbf{\large\IEEEkeywordsname}\end{center}\vskip 0.5\baselineskip plus 0.1\baselineskip minus 0.1\baselineskip + \if@twocolumn\else\quotation\fi\itshape\@IEEEabskeysecsize% + \par\@IEEEgobbleleadPARNLSP} + \else% compsoc not conference +\def\abstract{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily + \if@twocolumn + \@IEEEabskeysecsize\noindent\textbf{\abstractname}---\relax + \else + \begin{center}\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\end{center}\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} +\def\IEEEkeywords{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily + \if@twocolumn + \@IEEEabskeysecsize\vskip 0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip\noindent + \textbf{\IEEEkeywordsname}---\relax + \else + \begin{center}\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\end{center}\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} + \fi +\fi + + + +% gobbles all leading \, \\ and \par, upon finding first token that +% is not a \ , \\ or a \par, it ceases and returns that token +% +% used to strip leading \, \\ and \par from the input +% so that such things in the beginning of an environment will not +% affect the formatting of the text +\long\def\@IEEEgobbleleadPARNLSP#1{\let\@IEEEswallowthistoken=0% +\let\@IEEEgobbleleadPARNLSPtoken#1% +\let\@IEEEgobbleleadPARtoken=\par% +\let\@IEEEgobbleleadNLtoken=\\% +\let\@IEEEgobbleleadSPtoken=\ % +\def\@IEEEgobbleleadSPMACRO{\ }% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadPARtoken% +\let\@IEEEswallowthistoken=1% +\fi% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadNLtoken% +\let\@IEEEswallowthistoken=1% +\fi% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPtoken% +\let\@IEEEswallowthistoken=1% +\fi% +% a control space will come in as a macro +% when it is the last one on a line +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPMACRO% +\let\@IEEEswallowthistoken=1% +\fi% +% if we have to swallow this token, do so and taste the next one +% else spit it out and stop gobbling +\ifx\@IEEEswallowthistoken 1\let\@IEEEnextgobbleleadPARNLSP=\@IEEEgobbleleadPARNLSP\else% +\let\@IEEEnextgobbleleadPARNLSP=#1\fi% +\@IEEEnextgobbleleadPARNLSP}% + + + + +% TITLING OF SECTIONS +\def\@IEEEsectpunct{:\ \,} % Punctuation after run-in section heading (headings which are + % part of the paragraphs), need little bit more than a single space + % spacing from section number to title +% compsoc conferences use regular period/space punctuation +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference +\def\@IEEEsectpunct{.\ } +\fi\fi + +\def\@seccntformat#1{\hb@xt@ 1.4em{\csname the#1dis\endcsname\hss\relax}} +\def\@seccntformatinl#1{\hb@xt@ 1.1em{\csname the#1dis\endcsname\hss\relax}} +\def\@seccntformatch#1{\csname the#1dis\endcsname\hskip 1em\relax} + +\ifCLASSOPTIONcompsoc +% compsoc journals need extra spacing +\ifCLASSOPTIONconference\else +\def\@seccntformat#1{\csname the#1dis\endcsname\hskip 1em\relax} +\fi\fi + +%v1.7 put {} after #6 to allow for some types of user font control +%and use \@@par rather than \par +\def\@sect#1#2#3#4#5#6[#7]#8{% + \ifnum #2>\c@secnumdepth + \let\@svsec\@empty + \else + \refstepcounter{#1}% + % load section label and spacer into \@svsec + \ifnum #2=1 + \protected@edef\@svsec{\@seccntformatch{#1}\relax}% + \else + \ifnum #2>2 + \protected@edef\@svsec{\@seccntformatinl{#1}\relax}% + \else + \protected@edef\@svsec{\@seccntformat{#1}\relax}% + \fi + \fi + \fi% + \@tempskipa #5\relax + \ifdim \@tempskipa>\z@% tempskipa determines whether is treated as a high + \begingroup #6{\relax% or low level heading + \noindent % subsections are NOT indented + % print top level headings. \@svsec is label, #8 is heading title + % IEEE does not block indent the section title text, it flows like normal + {\hskip #3\relax\@svsec}{\interlinepenalty \@M #8\@@par}}% + \endgroup + \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else + \protect\numberline{\csname the#1\endcsname}\fi#7}% + \else % printout low level headings + % svsechd seems to swallow the trailing space, protect it with \mbox{} + % got rid of sectionmark stuff + \def\@svsechd{#6{\hskip #3\relax\@svsec #8\@IEEEsectpunct\mbox{}}% + \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else + \protect\numberline{\csname the#1\endcsname}\fi#7}}% + \fi%skip down + \@xsect{#5}} + + +% section* handler +%v1.7 put {} after #4 to allow for some types of user font control +%and use \@@par rather than \par +\def\@ssect#1#2#3#4#5{\@tempskipa #3\relax + \ifdim \@tempskipa>\z@ + %\begingroup #4\@hangfrom{\hskip #1}{\interlinepenalty \@M #5\par}\endgroup + % IEEE does not block indent the section title text, it flows like normal + \begingroup \noindent #4{\relax{\hskip #1}{\interlinepenalty \@M #5\@@par}}\endgroup + % svsechd swallows the trailing space, protect it with \mbox{} + \else \def\@svsechd{#4{\hskip #1\relax #5\@IEEEsectpunct\mbox{}}}\fi + \@xsect{#3}} + + +%% SECTION heading spacing and font +%% +% arguments are: #1 - sectiontype name +% (for \@sect) #2 - section level +% #3 - section heading indent +% #4 - top separation (absolute value used, neg indicates not to indent main text) +% If negative, make stretch parts negative too! +% #5 - (absolute value used) positive: bottom separation after heading, +% negative: amount to indent main text after heading +% Both #4 and #5 negative means to indent main text and use negative top separation +% #6 - font control +% You've got to have \normalfont\normalsize in the font specs below to prevent +% trouble when you do something like: +% \section{Note}{\ttfamily TT-TEXT} is known to ... +% IEEE sometimes REALLY stretches the area before a section +% heading by up to about 0.5in. However, it may not be a good +% idea to let LaTeX have quite this much rubber. +\ifCLASSOPTIONconference% +% IEEE wants section heading spacing to decrease for conference mode +\def\section{\@startsection{section}{1}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% +{1sp}{\normalfont\normalsize\centering\scshape}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% +{1sp}{\normalfont\normalsize\itshape}}% +\else % for journals +\def\section{\@startsection{section}{1}{\z@}{3.0ex plus 1.5ex minus 1.5ex}% V1.6 3.0ex from 3.5ex +{0.7ex plus 1ex minus 0ex}{\normalfont\normalsize\centering\scshape}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{3.5ex plus 1.5ex minus 1.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% +\fi + +% for both journals and conferences +% decided to put in a little rubber above the section, might help somebody +\def\subsubsection{\@startsection{subsubsection}{3}{\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize\itshape}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize\itshape}}% + + +% compsoc +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference +% compsoc conference +\def\section{\@startsection{section}{1}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\large\bfseries}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\sublargesize\bfseries}}% +\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{0ex}{\normalfont\normalsize\bfseries}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize}}% +\else% compsoc journals +% use negative top separation as compsoc journals do not indent paragraphs after section titles +\def\section{\@startsection{section}{1}{\z@}{-3ex plus -2ex minus -1.5ex}% +{0.7ex plus 1ex minus 0ex}{\normalfont\large\sffamily\bfseries\scshape}}% +% Note that subsection and smaller may not be correct for the Computer Society, +% I have to look up an example. +\def\subsection{\@startsection{subsection}{2}{\z@}{-3.5ex plus -1.5ex minus -1.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\sffamily\bfseries}}% +\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex plus -1ex minus -1ex}% +{0.5ex plus 0.5ex minus 0ex}{\normalfont\normalsize\sffamily\itshape}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{-0ex plus -0.1ex minus -0.1ex}% +{0ex}{\normalfont\normalsize}}% +\fi\fi + + + + +%% ENVIRONMENTS +% "box" symbols at end of proofs +\def\IEEEQEDclosed{\mbox{\rule[0pt]{1.3ex}{1.3ex}}} % for a filled box +% V1.6 some journals use an open box instead that will just fit around a closed one +\def\IEEEQEDopen{{\setlength{\fboxsep}{0pt}\setlength{\fboxrule}{0.2pt}\fbox{\rule[0pt]{0pt}{1.3ex}\rule[0pt]{1.3ex}{0pt}}}} +\ifCLASSOPTIONcompsoc +\def\IEEEQED{\IEEEQEDopen} % default to open for compsoc +\else +\def\IEEEQED{\IEEEQEDclosed} % otherwise default to closed +\fi + +% v1.7 name change to avoid namespace collision with amsthm. Also add support +% for an optional argument. +\def\IEEEproof{\@ifnextchar[{\@IEEEproof}{\@IEEEproof[\IEEEproofname]}} +\def\@IEEEproof[#1]{\par\noindent\hspace{2em}{\itshape #1: }} +\def\endIEEEproof{\hspace*{\fill}~\IEEEQED\par} + + +%\itemindent is set to \z@ by list, so define new temporary variable +\newdimen\@IEEEtmpitemindent +\def\@begintheorem#1#2{\@IEEEtmpitemindent\itemindent\topsep 0pt\rmfamily\trivlist% + \item[\hskip \labelsep{\indent\itshape #1\ #2:}]\itemindent\@IEEEtmpitemindent} +\def\@opargbegintheorem#1#2#3{\@IEEEtmpitemindent\itemindent\topsep 0pt\rmfamily \trivlist% +% V1.6 IEEE is back to using () around theorem names which are also in italics +% Thanks to Christian Peel for reporting this. + \item[\hskip\labelsep{\indent\itshape #1\ #2\ (#3):}]\itemindent\@IEEEtmpitemindent} +% V1.7 remove bogus \unskip that caused equations in theorems to collide with +% lines below. +\def\@endtheorem{\endtrivlist} + +% V1.6 +% display command for the section the theorem is in - so that \thesection +% is not used as this will be in Roman numerals when we want arabic. +% LaTeX2e uses \def\@thmcounter#1{\noexpand\arabic{#1}} for the theorem number +% (second part) display and \def\@thmcountersep{.} as a separator. +% V1.7 intercept calls to the section counter and reroute to \@IEEEthmcounterinsection +% to allow \appendix(ices} to override as needed. +% +% special handler for sections, allows appendix(ices) to override +\gdef\@IEEEthmcounterinsection#1{\arabic{#1}} +% string macro +\edef\@IEEEstringsection{section} + +% redefine the #1#2[#3] form of newtheorem to use a hook to \@IEEEthmcounterinsection +% if section in_counter is used +\def\@xnthm#1#2[#3]{% + \expandafter\@ifdefinable\csname #1\endcsname + {\@definecounter{#1}\@newctr{#1}[#3]% + \edef\@IEEEstringtmp{#3} + \ifx\@IEEEstringtmp\@IEEEstringsection + \expandafter\xdef\csname the#1\endcsname{% + \noexpand\@IEEEthmcounterinsection{#3}\@thmcountersep + \@thmcounter{#1}}% + \else + \expandafter\xdef\csname the#1\endcsname{% + \expandafter\noexpand\csname the#3\endcsname \@thmcountersep + \@thmcounter{#1}}% + \fi + \global\@namedef{#1}{\@thm{#1}{#2}}% + \global\@namedef{end#1}{\@endtheorem}}} + + + +%% SET UP THE DEFAULT PAGESTYLE +\ps@headings +\pagenumbering{arabic} + +% normally the page counter starts at 1 +\setcounter{page}{1} +% however, for peerreview the cover sheet is page 0 or page -1 +% (for duplex printing) +\ifCLASSOPTIONpeerreview + \if@twoside + \setcounter{page}{-1} + \else + \setcounter{page}{0} + \fi +\fi + +% standard book class behavior - let bottom line float up and down as +% needed when single sided +\ifCLASSOPTIONtwoside\else\raggedbottom\fi +% if two column - turn on twocolumn, allow word spacings to stretch more and +% enforce a rigid position for the last lines +\ifCLASSOPTIONtwocolumn +% the peer review option delays invoking twocolumn + \ifCLASSOPTIONpeerreview\else + \twocolumn + \fi +\sloppy +\flushbottom +\fi + + + + +% \APPENDIX and \APPENDICES definitions + +% This is the \@ifmtarg command from the LaTeX ifmtarg package +% by Peter Wilson (CUA) and Donald Arseneau +% \@ifmtarg is used to determine if an argument to a command +% is present or not. +% For instance: +% \@ifmtarg{#1}{\typeout{empty}}{\typeout{has something}} +% \@ifmtarg is used with our redefined \section command if +% \appendices is invoked. +% The command \section will behave slightly differently depending +% on whether the user specifies a title: +% \section{My appendix title} +% or not: +% \section{} +% This way, we can eliminate the blank lines where the title +% would be, and the unneeded : after Appendix in the table of +% contents +\begingroup +\catcode`\Q=3 +\long\gdef\@ifmtarg#1{\@xifmtarg#1QQ\@secondoftwo\@firstoftwo\@nil} +\long\gdef\@xifmtarg#1#2Q#3#4#5\@nil{#4} +\endgroup +% end of \@ifmtarg defs + + +% V1.7 +% command that allows the one time saving of the original definition +% of section to \@IEEEappendixsavesection for \appendix or \appendices +% we don't save \section here as it may be redefined later by other +% packages (hyperref.sty, etc.) +\def\@IEEEsaveoriginalsectiononce{\let\@IEEEappendixsavesection\section +\let\@IEEEsaveoriginalsectiononce\relax} + +% neat trick to grab and process the argument from \section{argument} +% we process differently if the user invoked \section{} with no +% argument (title) +% note we reroute the call to the old \section* +\def\@IEEEprocessthesectionargument#1{% +\@ifmtarg{#1}{% +\@IEEEappendixsavesection*{\appendixname~\thesectiondis}% +\addcontentsline{toc}{section}{\appendixname~\thesection}}{% +\@IEEEappendixsavesection*{\appendixname~\thesectiondis \\* #1}% +\addcontentsline{toc}{section}{\appendixname~\thesection: #1}}} + +% we use this if the user calls \section{} after +% \appendix-- which has no meaning. So, we ignore the +% command and its argument. Then, warn the user. +\def\@IEEEdestroythesectionargument#1{\typeout{** WARNING: Ignoring useless +\protect\section\space in Appendix (line \the\inputlineno).}} + + +% remember \thesection forms will be displayed in \ref calls +% and in the Table of Contents. +% The \sectiondis form is used in the actual heading itself + +% appendix command for one single appendix +% normally has no heading. However, if you want a +% heading, you can do so via the optional argument: +% \appendix[Optional Heading] +\def\appendix{\relax} +\renewcommand{\appendix}[1][]{\@IEEEsaveoriginalsectiononce\par + % v1.6 keep hyperref's identifiers unique + \gdef\theHsection{Appendix.A}% + % v1.6 adjust hyperref's string name for the section + \xdef\Hy@chapapp{appendix}% + \setcounter{section}{0}% + \setcounter{subsection}{0}% + \setcounter{subsubsection}{0}% + \setcounter{paragraph}{0}% + \gdef\thesection{A}% + \gdef\thesectiondis{}% + \gdef\thesubsection{\Alph{subsection}}% + \gdef\@IEEEthmcounterinsection##1{A} + \refstepcounter{section}% update the \ref counter + \@ifmtarg{#1}{\@IEEEappendixsavesection*{\appendixname}% + \addcontentsline{toc}{section}{\appendixname}}{% + \@IEEEappendixsavesection*{\appendixname~\\* #1}% + \addcontentsline{toc}{section}{\appendixname: #1}}% + % redefine \section command for appendix + % leave \section* as is + \def\section{\@ifstar{\@IEEEappendixsavesection*}{% + \@IEEEdestroythesectionargument}}% throw out the argument + % of the normal form +} + + + +% appendices command for multiple appendices +% user then calls \section with an argument (possibly empty) to +% declare the individual appendices +\def\appendices{\@IEEEsaveoriginalsectiononce\par + % v1.6 keep hyperref's identifiers unique + \gdef\theHsection{Appendix.\Alph{section}}% + % v1.6 adjust hyperref's string name for the section + \xdef\Hy@chapapp{appendix}% + \setcounter{section}{-1}% we want \refstepcounter to use section 0 + \setcounter{subsection}{0}% + \setcounter{subsubsection}{0}% + \setcounter{paragraph}{0}% + \ifCLASSOPTIONromanappendices% + \gdef\thesection{\Roman{section}}% + \gdef\thesectiondis{\Roman{section}}% + \@IEEEcompsocconfonly{\gdef\thesectiondis{\Roman{section}.}}% + \gdef\@IEEEthmcounterinsection##1{A\arabic{##1}} + \else% + \gdef\thesection{\Alph{section}}% + \gdef\thesectiondis{\Alph{section}}% + \@IEEEcompsocconfonly{\gdef\thesectiondis{\Alph{section}.}}% + \gdef\@IEEEthmcounterinsection##1{\Alph{##1}} + \fi% + \refstepcounter{section}% update the \ref counter + \setcounter{section}{0}% NEXT \section will be the FIRST appendix + % redefine \section command for appendices + % leave \section* as is + \def\section{\@ifstar{\@IEEEappendixsavesection*}{% process the *-form + \refstepcounter{section}% or is a new section so, + \@IEEEprocessthesectionargument}}% process the argument + % of the normal form +} + + + +% \IEEEPARstart +% Definition for the big two line drop cap letter at the beginning of the +% first paragraph of journal papers. The first argument is the first letter +% of the first word, the second argument is the remaining letters of the +% first word which will be rendered in upper case. +% In V1.6 this has been completely rewritten to: +% +% 1. no longer have problems when the user begins an environment +% within the paragraph that uses \IEEEPARstart. +% 2. auto-detect and use the current font family +% 3. revise handling of the space at the end of the first word so that +% interword glue will now work as normal. +% 4. produce correctly aligned edges for the (two) indented lines. +% +% We generalize things via control macros - playing with these is fun too. +% +% V1.7 added more control macros to make it easy for IEEEtrantools.sty users +% to change the font style. +% +% the number of lines that are indented to clear it +% may need to increase if using decenders +\def\@IEEEPARstartDROPLINES{2} +% minimum number of lines left on a page to allow a \@IEEEPARstart +% Does not take into consideration rubber shrink, so it tends to +% be overly cautious +\def\@IEEEPARstartMINPAGELINES{2} +% V1.7 the height of the drop cap is adjusted to match the height of this text +% in the current font (when \IEEEPARstart is called). +\def\@IEEEPARstartHEIGHTTEXT{T} +% the depth the letter is lowered below the baseline +% the height (and size) of the letter is determined by the sum +% of this value and the height of the \@IEEEPARstartHEIGHTTEXT in the current +% font. It is a good idea to set this value in terms of the baselineskip +% so that it can respond to changes therein. +\def\@IEEEPARstartDROPDEPTH{1.1\baselineskip} +% V1.7 the font the drop cap will be rendered in, +% can take zero or one argument. +\def\@IEEEPARstartFONTSTYLE{\bfseries} +% V1.7 any additional, non-font related commands needed to modify +% the drop cap letter, can take zero or one argument. +\def\@IEEEPARstartCAPSTYLE{\MakeUppercase} +% V1.7 the font that will be used to render the rest of the word, +% can take zero or one argument. +\def\@IEEEPARstartWORDFONTSTYLE{\relax} +% V1.7 any additional, non-font related commands needed to modify +% the rest of the word, can take zero or one argument. +\def\@IEEEPARstartWORDCAPSTYLE{\MakeUppercase} +% This is the horizontal separation distance from the drop letter to the main text. +% Lengths that depend on the font (e.g., ex, em, etc.) will be referenced +% to the font that is active when \IEEEPARstart is called. +\def\@IEEEPARstartSEP{0.15em} +% V1.7 horizontal offset applied to the left of the drop cap. +\def\@IEEEPARstartHOFFSET{0em} +% V1.7 Italic correction command applied at the end of the drop cap. +\def\@IEEEPARstartITLCORRECT{\/} + +% V1.7 compoc uses nonbold drop cap and small caps word style +\ifCLASSOPTIONcompsoc +\def\@IEEEPARstartFONTSTYLE{\mdseries} +\def\@IEEEPARstartWORDFONTSTYLE{\scshape} +\def\@IEEEPARstartWORDCAPSTYLE{\relax} +\fi + +% definition of \IEEEPARstart +% THIS IS A CONTROLLED SPACING AREA, DO NOT ALLOW SPACES WITHIN THESE LINES +% +% The token \@IEEEPARstartfont will be globally defined after the first use +% of \IEEEPARstart and will be a font command which creates the big letter +% The first argument is the first letter of the first word and the second +% argument is the rest of the first word(s). +\def\IEEEPARstart#1#2{\par{% +% if this page does not have enough space, break it and lets start +% on a new one +\@IEEEtranneedspace{\@IEEEPARstartMINPAGELINES\baselineskip}{\relax}% +% V1.7 move this up here in case user uses \textbf for \@IEEEPARstartFONTSTYLE +% which uses command \leavevmode which causes an unwanted \indent to be issued +\noindent +% calculate the desired height of the big letter +% it extends from the top of \@IEEEPARstartHEIGHTTEXT in the current font +% down to \@IEEEPARstartDROPDEPTH below the current baseline +\settoheight{\@IEEEtrantmpdimenA}{\@IEEEPARstartHEIGHTTEXT}% +\addtolength{\@IEEEtrantmpdimenA}{\@IEEEPARstartDROPDEPTH}% +% extract the name of the current font in bold +% and place it in \@IEEEPARstartFONTNAME +\def\@IEEEPARstartGETFIRSTWORD##1 ##2\relax{##1}% +{\@IEEEPARstartFONTSTYLE{\selectfont\edef\@IEEEPARstartFONTNAMESPACE{\fontname\font\space}% +\xdef\@IEEEPARstartFONTNAME{\expandafter\@IEEEPARstartGETFIRSTWORD\@IEEEPARstartFONTNAMESPACE\relax}}}% +% define a font based on this name with a point size equal to the desired +% height of the drop letter +\font\@IEEEPARstartsubfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenA\relax% +% save this value as a counter (integer) value (sp points) +\@IEEEtrantmpcountA=\@IEEEtrantmpdimenA% +% now get the height of the actual letter produced by this font size +\settoheight{\@IEEEtrantmpdimenB}{\@IEEEPARstartsubfont\@IEEEPARstartCAPSTYLE{#1}}% +% If something bogus happens like the first argument is empty or the +% current font is strange, do not allow a zero height. +\ifdim\@IEEEtrantmpdimenB=0pt\relax% +\typeout{** WARNING: IEEEPARstart drop letter has zero height! (line \the\inputlineno)}% +\typeout{ Forcing the drop letter font size to 10pt.}% +\@IEEEtrantmpdimenB=10pt% +\fi% +% and store it as a counter +\@IEEEtrantmpcountB=\@IEEEtrantmpdimenB% +% Since a font size doesn't exactly correspond to the height of the capital +% letters in that font, the actual height of the letter, \@IEEEtrantmpcountB, +% will be less than that desired, \@IEEEtrantmpcountA +% we need to raise the font size, \@IEEEtrantmpdimenA +% by \@IEEEtrantmpcountA / \@IEEEtrantmpcountB +% But, TeX doesn't have floating point division, so we have to use integer +% division. Hence the use of the counters. +% We need to reduce the denominator so that the loss of the remainder will +% have minimal affect on the accuracy of the result +\divide\@IEEEtrantmpcountB by 200% +\divide\@IEEEtrantmpcountA by \@IEEEtrantmpcountB% +% Then reequalize things when we use TeX's ability to multiply by +% floating point values +\@IEEEtrantmpdimenB=0.005\@IEEEtrantmpdimenA% +\multiply\@IEEEtrantmpdimenB by \@IEEEtrantmpcountA% +% \@IEEEPARstartfont is globaly set to the calculated font of the big letter +% We need to carry this out of the local calculation area to to create the +% big letter. +\global\font\@IEEEPARstartfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenB% +% Now set \@IEEEtrantmpdimenA to the width of the big letter +% We need to carry this out of the local calculation area to set the +% hanging indent +\settowidth{\global\@IEEEtrantmpdimenA}{\@IEEEPARstartfont +\@IEEEPARstartCAPSTYLE{#1\@IEEEPARstartITLCORRECT}}}% +% end of the isolated calculation environment +% add in the extra clearance we want +\advance\@IEEEtrantmpdimenA by \@IEEEPARstartSEP\relax% +% add in the optional offset +\advance\@IEEEtrantmpdimenA by \@IEEEPARstartHOFFSET\relax% +% V1.7 don't allow negative offsets to produce negative hanging indents +\@IEEEtrantmpdimenB\@IEEEtrantmpdimenA +\ifnum\@IEEEtrantmpdimenB < 0 \@IEEEtrantmpdimenB 0pt\fi +% \@IEEEtrantmpdimenA has the width of the big letter plus the +% separation space and \@IEEEPARstartfont is the font we need to use +% Now, we make the letter and issue the hanging indent command +% The letter is placed in a box of zero width and height so that other +% text won't be displaced by it. +\hangindent\@IEEEtrantmpdimenB\hangafter=-\@IEEEPARstartDROPLINES% +\makebox[0pt][l]{\hspace{-\@IEEEtrantmpdimenA}% +\raisebox{-\@IEEEPARstartDROPDEPTH}[0pt][0pt]{\hspace{\@IEEEPARstartHOFFSET}% +\@IEEEPARstartfont\@IEEEPARstartCAPSTYLE{#1\@IEEEPARstartITLCORRECT}% +\hspace{\@IEEEPARstartSEP}}}% +{\@IEEEPARstartWORDFONTSTYLE{\@IEEEPARstartWORDCAPSTYLE{\selectfont#2}}}} + + + + + + +% determines if the space remaining on a given page is equal to or greater +% than the specified space of argument one +% if not, execute argument two (only if the remaining space is greater than zero) +% and issue a \newpage +% +% example: \@IEEEtranneedspace{2in}{\vfill} +% +% Does not take into consideration rubber shrinkage, so it tends to +% be overly cautious +% Based on an example posted by Donald Arseneau +% Note this macro uses \@IEEEtrantmpdimenB internally for calculations, +% so DO NOT PASS \@IEEEtrantmpdimenB to this routine +% if you need a dimen register, import with \@IEEEtrantmpdimenA instead +\def\@IEEEtranneedspace#1#2{\penalty-100\begingroup%shield temp variable +\@IEEEtrantmpdimenB\pagegoal\advance\@IEEEtrantmpdimenB-\pagetotal% space left +\ifdim #1>\@IEEEtrantmpdimenB\relax% not enough space left +\ifdim\@IEEEtrantmpdimenB>\z@\relax #2\fi% +\newpage% +\fi\endgroup} + + + +% IEEEbiography ENVIRONMENT +% Allows user to enter biography leaving place for picture (adapts to font size) +% As of V1.5, a new optional argument allows you to have a real graphic! +% V1.5 and later also fixes the "colliding biographies" which could happen when a +% biography's text was shorter than the space for the photo. +% MDS 7/2001 +% V1.6 prevent multiple biographies from making multiple TOC entries +\newif\if@IEEEbiographyTOCentrynotmade +\global\@IEEEbiographyTOCentrynotmadetrue + +% biography counter so hyperref can jump directly to the biographies +% and not just the previous section +\newcounter{IEEEbiography} +\setcounter{IEEEbiography}{0} + +% photo area size +\def\@IEEEBIOphotowidth{1.0in} % width of the biography photo area +\def\@IEEEBIOphotodepth{1.25in} % depth (height) of the biography photo area +% area cleared for photo +\def\@IEEEBIOhangwidth{1.14in} % width cleared for the biography photo area +\def\@IEEEBIOhangdepth{1.25in} % depth cleared for the biography photo area + % actual depth will be a multiple of + % \baselineskip, rounded up +\def\@IEEEBIOskipN{4\baselineskip}% nominal value of the vskip above the biography + +\newenvironment{IEEEbiography}[2][]{\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize% +\unitlength 1in\parskip=0pt\par\parindent 1em\interlinepenalty500% +% we need enough space to support the hanging indent +% the nominal value of the spacer +% and one extra line for good measure +\@IEEEtrantmpdimenA=\@IEEEBIOhangdepth% +\advance\@IEEEtrantmpdimenA by \@IEEEBIOskipN% +\advance\@IEEEtrantmpdimenA by 1\baselineskip% +% if this page does not have enough space, break it and lets start +% with a new one +\@IEEEtranneedspace{\@IEEEtrantmpdimenA}{\relax}% +% nominal spacer can strech, not shrink use 1fil so user can out stretch with \vfill +\vskip \@IEEEBIOskipN plus 1fil minus 0\baselineskip% +% the default box for where the photo goes +\def\@IEEEtempbiographybox{{\setlength{\fboxsep}{0pt}\framebox{% +\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}\centering PLACE\\ PHOTO\\ HERE \end{minipage}}}}% +% +% detect if the optional argument was supplied, this requires the +% \@ifmtarg command as defined in the appendix section above +% and if so, override the default box with what they want +\@ifmtarg{#1}{\relax}{\def\@IEEEtempbiographybox{\mbox{\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}% +\centering% +#1% +\end{minipage}}}}% end if optional argument supplied +% Make an entry into the table of contents only if we have not done so before +\if@IEEEbiographyTOCentrynotmade% +% link labels to the biography counter so hyperref will jump +% to the biography, not the previous section +\setcounter{IEEEbiography}{-1}% +\refstepcounter{IEEEbiography}% +\addcontentsline{toc}{section}{Biographies}% +\global\@IEEEbiographyTOCentrynotmadefalse% +\fi% +% one more biography +\refstepcounter{IEEEbiography}% +% Make an entry for this name into the table of contents +\addcontentsline{toc}{subsection}{#2}% +% V1.6 properly handle if a new paragraph should occur while the +% hanging indent is still active. Do this by redefining \par so +% that it will not start a new paragraph. (But it will appear to the +% user as if it did.) Also, strip any leading pars, newlines, or spaces. +\let\@IEEEBIOORGparCMD=\par% save the original \par command +\edef\par{\hfil\break\indent}% the new \par will not be a "real" \par +\settoheight{\@IEEEtrantmpdimenA}{\@IEEEtempbiographybox}% get height of biography box +\@IEEEtrantmpdimenB=\@IEEEBIOhangdepth% +\@IEEEtrantmpcountA=\@IEEEtrantmpdimenB% countA has the hang depth +\divide\@IEEEtrantmpcountA by \baselineskip% calculates lines needed to produce the hang depth +\advance\@IEEEtrantmpcountA by 1% ensure we overestimate +% set the hanging indent +\hangindent\@IEEEBIOhangwidth% +\hangafter-\@IEEEtrantmpcountA% +% reference the top of the photo area to the top of a capital T +\settoheight{\@IEEEtrantmpdimenB}{\mbox{T}}% +% set the photo box, give it zero width and height so as not to disturb anything +\noindent\makebox[0pt][l]{\hspace{-\@IEEEBIOhangwidth}\raisebox{\@IEEEtrantmpdimenB}[0pt][0pt]{% +\raisebox{-\@IEEEBIOphotodepth}[0pt][0pt]{\@IEEEtempbiographybox}}}% +% now place the author name and begin the bio text +\noindent\textbf{#2\ }\@IEEEgobbleleadPARNLSP}{\relax\let\par=\@IEEEBIOORGparCMD\par% +% 7/2001 V1.5 detect when the biography text is shorter than the photo area +% and pad the unused area - preventing a collision from the next biography entry +% MDS +\ifnum \prevgraf <\@IEEEtrantmpcountA\relax% detect when the biography text is shorter than the photo + \advance\@IEEEtrantmpcountA by -\prevgraf% calculate how many lines we need to pad + \advance\@IEEEtrantmpcountA by -1\relax% we compensate for the fact that we indented an extra line + \@IEEEtrantmpdimenA=\baselineskip% calculate the length of the padding + \multiply\@IEEEtrantmpdimenA by \@IEEEtrantmpcountA% + \noindent\rule{0pt}{\@IEEEtrantmpdimenA}% insert an invisible support strut +\fi% +\par\normalfont} + + + +% V1.6 +% added biography without a photo environment +\newenvironment{IEEEbiographynophoto}[1]{% +% Make an entry into the table of contents only if we have not done so before +\if@IEEEbiographyTOCentrynotmade% +% link labels to the biography counter so hyperref will jump +% to the biography, not the previous section +\setcounter{IEEEbiography}{-1}% +\refstepcounter{IEEEbiography}% +\addcontentsline{toc}{section}{Biographies}% +\global\@IEEEbiographyTOCentrynotmadefalse% +\fi% +% one more biography +\refstepcounter{IEEEbiography}% +% Make an entry for this name into the table of contents +\addcontentsline{toc}{subsection}{#1}% +\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize\interlinepenalty500% +\vskip 4\baselineskip plus 1fil minus 0\baselineskip% +\parskip=0pt\par% +\noindent\textbf{#1\ }\@IEEEgobbleleadPARNLSP}{\relax\par\normalfont} + + +% provide the user with some old font commands +% got this from article.cls +\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm} +\DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf} +\DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt} +\DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf} +\DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit} +\DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl} +\DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc} +\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal} +\DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal} + + +% SPECIAL PAPER NOTICE COMMANDS +% +% holds the special notice text +\def\@IEEEspecialpapernotice{\relax} + +% for special papers, like invited papers, the user can do: +% \IEEEspecialpapernotice{(Invited Paper)} before \maketitle +\def\IEEEspecialpapernotice#1{\ifCLASSOPTIONconference% +\def\@IEEEspecialpapernotice{{\Large#1\vspace*{1em}}}% +\else% +\def\@IEEEspecialpapernotice{{\\*[1.5ex]\sublargesize\textit{#1}}\vspace*{-2ex}}% +\fi} + + + + +% PUBLISHER ID COMMANDS +% to insert a publisher's ID footer +% V1.6 \IEEEpubid has been changed so that the change in page size and style +% occurs in \maketitle. \IEEEpubid must now be issued prior to \maketitle +% use \IEEEpubidadjcol as before - in the second column of the title page +% These changes allow \maketitle to take the reduced page height into +% consideration when dynamically setting the space between the author +% names and the maintext. +% +% the amount the main text is pulled up to make room for the +% publisher's ID footer +% IEEE uses about 1.3\baselineskip for journals, +% dynamic title spacing will clean up the fraction +\def\@IEEEpubidpullup{1.3\baselineskip} +\ifCLASSOPTIONtechnote +% for technotes it must be an integer of baselineskip as there can be no +% dynamic title spacing for two column mode technotes (the title is in the +% in first column) and we should maintain an integer number of lines in the +% second column +% There are some examples (such as older issues of "Transactions on +% Information Theory") in which IEEE really pulls the text off the ID for +% technotes - about 0.55in (or 4\baselineskip). We'll use 2\baselineskip +% and call it even. +\def\@IEEEpubidpullup{2\baselineskip} +\fi + +% V1.7 compsoc does not use a pullup +\ifCLASSOPTIONcompsoc +\def\@IEEEpubidpullup{0pt} +\fi + +% holds the ID text +\def\@IEEEpubid{\relax} + +% flag so \maketitle can tell if \IEEEpubid was called +\newif\if@IEEEusingpubid +\global\@IEEEusingpubidfalse +% issue this command in the page to have the ID at the bottom +% V1.6 use before \maketitle +\def\IEEEpubid#1{\def\@IEEEpubid{#1}\global\@IEEEusingpubidtrue} + + +% command which will pull up (shorten) the column it is executed in +% to make room for the publisher ID. Place in the second column of +% the title page when using \IEEEpubid +% Is smart enough not to do anything when in single column text or +% if the user hasn't called \IEEEpubid +% currently needed in for the second column of a page with the +% publisher ID. If not needed in future releases, please provide this +% command and define it as \relax for backward compatibility +% v1.6b do not allow command to operate if the peer review option has been +% selected because \IEEEpubidadjcol will not be on the cover page. +% V1.7 do nothing if compsoc +\def\IEEEpubidadjcol{\ifCLASSOPTIONcompsoc\else\ifCLASSOPTIONpeerreview\else +\if@twocolumn\if@IEEEusingpubid\enlargethispage{-\@IEEEpubidpullup}\fi\fi\fi\fi} + +% Special thanks to Peter Wilson, Daniel Luecking, and the other +% gurus at comp.text.tex, for helping me to understand how best to +% implement the IEEEpubid command in LaTeX. + + + +%% Lockout some commands under various conditions + +% general purpose bit bucket +\newsavebox{\@IEEEtranrubishbin} + +% flags to prevent multiple warning messages +\newif\if@IEEEWARNthanks +\newif\if@IEEEWARNIEEEPARstart +\newif\if@IEEEWARNIEEEbiography +\newif\if@IEEEWARNIEEEbiographynophoto +\newif\if@IEEEWARNIEEEpubid +\newif\if@IEEEWARNIEEEpubidadjcol +\newif\if@IEEEWARNIEEEmembership +\newif\if@IEEEWARNIEEEaftertitletext +\@IEEEWARNthankstrue +\@IEEEWARNIEEEPARstarttrue +\@IEEEWARNIEEEbiographytrue +\@IEEEWARNIEEEbiographynophototrue +\@IEEEWARNIEEEpubidtrue +\@IEEEWARNIEEEpubidadjcoltrue +\@IEEEWARNIEEEmembershiptrue +\@IEEEWARNIEEEaftertitletexttrue + + +%% Lockout some commands when in various modes, but allow them to be restored if needed +%% +% save commands which might be locked out +% so that the user can later restore them if needed +\let\@IEEESAVECMDthanks\thanks +\let\@IEEESAVECMDIEEEPARstart\IEEEPARstart +\let\@IEEESAVECMDIEEEbiography\IEEEbiography +\let\@IEEESAVECMDendIEEEbiography\endIEEEbiography +\let\@IEEESAVECMDIEEEbiographynophoto\IEEEbiographynophoto +\let\@IEEESAVECMDendIEEEbiographynophoto\endIEEEbiographynophoto +\let\@IEEESAVECMDIEEEpubid\IEEEpubid +\let\@IEEESAVECMDIEEEpubidadjcol\IEEEpubidadjcol +\let\@IEEESAVECMDIEEEmembership\IEEEmembership +\let\@IEEESAVECMDIEEEaftertitletext\IEEEaftertitletext + + +% disable \IEEEPARstart when in draft mode +% This may have originally been done because the pre-V1.6 drop letter +% algorithm had problems with a non-unity baselinestretch +% At any rate, it seems too formal to have a drop letter in a draft +% paper. +\ifCLASSOPTIONdraftcls +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** ATTENTION: \noexpand\IEEEPARstart + is disabled in draft mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} +\fi +% and for technotes +\ifCLASSOPTIONtechnote +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart + is locked out for technotes (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} +\fi + + +% lockout unneeded commands when in conference mode +\ifCLASSOPTIONconference +% when locked out, \thanks, \IEEEbiography, \IEEEbiographynophoto, \IEEEpubid, +% \IEEEmembership and \IEEEaftertitletext will all swallow their given text. +% \IEEEPARstart will output a normal character instead +% warn the user about these commands only once to prevent the console screen +% from filling up with redundant messages +\def\thanks#1{\if@IEEEWARNthanks\typeout{** WARNING: \noexpand\thanks + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNthanksfalse} +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} + + +% LaTeX treats environments and commands with optional arguments differently. +% the actual ("internal") command is stored as \\commandname +% (accessed via \csname\string\commandname\endcsname ) +% the "external" command \commandname is a macro with code to determine +% whether or not the optional argument is presented and to provide the +% default if it is absent. So, in order to save and restore such a command +% we would have to save and restore \\commandname as well. But, if LaTeX +% ever changes the way it names the internal names, the trick would break. +% Instead let us just define a new environment so that the internal +% name can be left undisturbed. +\newenvironment{@IEEEbogusbiography}[2][]{\if@IEEEWARNIEEEbiography\typeout{** WARNING: \noexpand\IEEEbiography + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographyfalse% +\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} +% and make biography point to our bogus biography +\let\IEEEbiography=\@IEEEbogusbiography +\let\endIEEEbiography=\end@IEEEbogusbiography + +\renewenvironment{IEEEbiographynophoto}[1]{\if@IEEEWARNIEEEbiographynophoto\typeout{** WARNING: \noexpand\IEEEbiographynophoto + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographynophotofalse% +\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} + +\def\IEEEpubid#1{\if@IEEEWARNIEEEpubid\typeout{** WARNING: \noexpand\IEEEpubid + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidfalse} +\def\IEEEpubidadjcol{\if@IEEEWARNIEEEpubidadjcol\typeout{** WARNING: \noexpand\IEEEpubidadjcol + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidadjcolfalse} +\def\IEEEmembership#1{\if@IEEEWARNIEEEmembership\typeout{** WARNING: \noexpand\IEEEmembership + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEmembershipfalse} +\def\IEEEaftertitletext#1{\if@IEEEWARNIEEEaftertitletext\typeout{** WARNING: \noexpand\IEEEaftertitletext + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEaftertitletextfalse} +\fi + + +% provide a way to restore the commands that are locked out +\def\IEEEoverridecommandlockouts{% +\typeout{** ATTENTION: Overriding command lockouts (line \the\inputlineno).}% +\let\thanks\@IEEESAVECMDthanks% +\let\IEEEPARstart\@IEEESAVECMDIEEEPARstart% +\let\IEEEbiography\@IEEESAVECMDIEEEbiography% +\let\endIEEEbiography\@IEEESAVECMDendIEEEbiography% +\let\IEEEbiographynophoto\@IEEESAVECMDIEEEbiographynophoto% +\let\endIEEEbiographynophoto\@IEEESAVECMDendIEEEbiographynophoto% +\let\IEEEpubid\@IEEESAVECMDIEEEpubid% +\let\IEEEpubidadjcol\@IEEESAVECMDIEEEpubidadjcol% +\let\IEEEmembership\@IEEESAVECMDIEEEmembership% +\let\IEEEaftertitletext\@IEEESAVECMDIEEEaftertitletext} + + + +% need a backslash character for typeout output +{\catcode`\|=0 \catcode`\\=12 +|xdef|@IEEEbackslash{\}} + + +% hook to allow easy disabling of all legacy warnings +\def\@IEEElegacywarn#1#2{\typeout{** ATTENTION: \@IEEEbackslash #1 is deprecated (line \the\inputlineno). +Use \@IEEEbackslash #2 instead.}} + + +% provide for legacy commands +\def\authorblockA{\@IEEElegacywarn{authorblockA}{IEEEauthorblockA}\IEEEauthorblockA} +\def\authorblockN{\@IEEElegacywarn{authorblockN}{IEEEauthorblockN}\IEEEauthorblockN} +\def\authorrefmark{\@IEEElegacywarn{authorrefmark}{IEEEauthorrefmark}\IEEEauthorrefmark} +\def\PARstart{\@IEEElegacywarn{PARstart}{IEEEPARstart}\IEEEPARstart} +\def\pubid{\@IEEElegacywarn{pubid}{IEEEpubid}\IEEEpubid} +\def\pubidadjcol{\@IEEElegacywarn{pubidadjcol}{IEEEpubidadjcol}\IEEEpubidadjcol} +\def\QED{\@IEEElegacywarn{QED}{IEEEQED}\IEEEQED} +\def\QEDclosed{\@IEEElegacywarn{QEDclosed}{IEEEQEDclosed}\IEEEQEDclosed} +\def\QEDopen{\@IEEElegacywarn{QEDopen}{IEEEQEDopen}\IEEEQEDopen} +\def\specialpapernotice{\@IEEElegacywarn{specialpapernotice}{IEEEspecialpapernotice}\IEEEspecialpapernotice} + + + +% provide for legacy environments +\def\biography{\@IEEElegacywarn{biography}{IEEEbiography}\IEEEbiography} +\def\biographynophoto{\@IEEElegacywarn{biographynophoto}{IEEEbiographynophoto}\IEEEbiographynophoto} +\def\keywords{\@IEEElegacywarn{keywords}{IEEEkeywords}\IEEEkeywords} +\def\endbiography{\endIEEEbiography} +\def\endbiographynophoto{\endIEEEbiographynophoto} +\def\endkeywords{\endIEEEkeywords} + + +% provide for legacy IED commands/lengths when possible +\let\labelindent\IEEElabelindent +\def\calcleftmargin{\@IEEElegacywarn{calcleftmargin}{IEEEcalcleftmargin}\IEEEcalcleftmargin} +\def\setlabelwidth{\@IEEElegacywarn{setlabelwidth}{IEEEsetlabelwidth}\IEEEsetlabelwidth} +\def\usemathlabelsep{\@IEEElegacywarn{usemathlabelsep}{IEEEusemathlabelsep}\IEEEusemathlabelsep} +\def\iedlabeljustifyc{\@IEEElegacywarn{iedlabeljustifyc}{IEEEiedlabeljustifyc}\IEEEiedlabeljustifyc} +\def\iedlabeljustifyl{\@IEEElegacywarn{iedlabeljustifyl}{IEEEiedlabeljustifyl}\IEEEiedlabeljustifyl} +\def\iedlabeljustifyr{\@IEEElegacywarn{iedlabeljustifyr}{IEEEiedlabeljustifyr}\IEEEiedlabeljustifyr} + + + +% let \proof use the IEEEtran version even after amsthm is loaded +% \proof is now deprecated in favor of \IEEEproof +\AtBeginDocument{\def\proof{\@IEEElegacywarn{proof}{IEEEproof}\IEEEproof}\def\endproof{\endIEEEproof}} + +% V1.7 \overrideIEEEmargins is no longer supported. +\def\overrideIEEEmargins{% +\typeout{** WARNING: \string\overrideIEEEmargins \space no longer supported (line \the\inputlineno).}% +\typeout{** Use the \string\CLASSINPUTinnersidemargin, \string\CLASSINPUToutersidemargin \space controls instead.}} + + +\endinput + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of IEEEtran.cls %%%%%%%%%%%%%%%%%%%%%%%%%%%% +% That's all folks! + diff --git a/spec/consensus/consensus-paper/README.md b/spec/consensus/consensus-paper/README.md new file mode 100644 index 0000000..1a3507b --- /dev/null +++ b/spec/consensus/consensus-paper/README.md @@ -0,0 +1,28 @@ +--- +order: 1 +--- + +# Consensus Paper + +The repository contains the specification (and the proofs) of the Tendermint +consensus protocol, adopted in CometBFT. + +## How to install Latex on MacOS + +MacTex is Latex distribution for MacOS. You can download it [here](http://www.tug.org/mactex/mactex-download.html). + +Popular IDE for Latex-based projects is TexStudio. It can be downloaded +[here](https://www.texstudio.org/). + +## How to build project + +In order to compile the latex files (and write bibliography), execute + +`$ pdflatex paper`
+`$ bibtex paper`
+`$ pdflatex paper`
+`$ pdflatex paper`
+ +The generated file is paper.pdf. You can open it with + +`$ open paper.pdf` diff --git a/spec/consensus/consensus-paper/algorithmicplus.sty b/spec/consensus/consensus-paper/algorithmicplus.sty new file mode 100644 index 0000000..345bf5f --- /dev/null +++ b/spec/consensus/consensus-paper/algorithmicplus.sty @@ -0,0 +1,195 @@ +% ALGORITHMICPLUS STYLE +% for LaTeX version 2e +% Original ``algorithmic.sty'' by -- 1994 Peter Williams +% Bug fix (13 July 2004) by Arnaud Giersch +% Includes ideas from 'algorithmicext' by Martin Biely +% and 'distribalgo' by Xavier Defago +% Modifications: Martin Hutle +% +% This style file is free software; you can redistribute it and/or +% modify it under the terms of the GNU Lesser General Public +% License as published by the Free Software Foundation; either +% version 2 of the License, or (at your option) any later version. +% +% This style file is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +% Lesser General Public License for more details. +% +% You should have received a copy of the GNU Lesser General Public +% License along with this style file; if not, write to the +% Free Software Foundation, Inc., 59 Temple Place - Suite 330, +% Boston, MA 02111-1307, USA. +% +\NeedsTeXFormat{LaTeX2e} +\ProvidesPackage{algorithmicplus} +\typeout{Document Style `algorithmicplus' - environment, replaces `algorithmic'} +% +\RequirePackage{ifthen} +\RequirePackage{calc} +\newboolean{ALC@noend} +\setboolean{ALC@noend}{false} +\newcounter{ALC@line} +\newcounter{ALC@rem} +\newcounter{ALC@depth} +\newcounter{ALCPLUS@lastline} +\newlength{\ALC@tlm} +% +\DeclareOption{noend}{\setboolean{ALC@noend}{true}} +% +\ProcessOptions +% +% ALGORITHMIC +\newcommand{\algorithmiclnosize}{\small} +\newcommand{\algorithmiclnofont}{\tt} +\newcommand{\algorithmiclnodelimiter}{:} +% +\newcommand{\algorithmicrequire}{\textbf{Require:}} +\newcommand{\algorithmicensure}{\textbf{Ensure:}} +\newcommand{\algorithmiccomment}[1]{\{#1\}} +\newcommand{\algorithmicend}{\textbf{end}} +\newcommand{\algorithmicif}{\textbf{if}} +\newcommand{\algorithmicthen}{\textbf{then}} +\newcommand{\algorithmicelse}{\textbf{else}} +\newcommand{\algorithmicelsif}{\algorithmicelse\ \algorithmicif} +\newcommand{\algorithmicendif}{\algorithmicend\ \algorithmicif} +\newcommand{\algorithmicfor}{\textbf{for}} +\newcommand{\algorithmicforall}{\textbf{for all}} +\newcommand{\algorithmicdo}{\textbf{do}} +\newcommand{\algorithmicendfor}{\algorithmicend\ \algorithmicfor} +\newcommand{\algorithmicwhile}{\textbf{while}} +\newcommand{\algorithmicendwhile}{\algorithmicend\ \algorithmicwhile} +\newcommand{\algorithmicloop}{\textbf{loop}} +\newcommand{\algorithmicendloop}{\algorithmicend\ \algorithmicloop} +\newcommand{\algorithmicrepeat}{\textbf{repeat}} +\newcommand{\algorithmicuntil}{\textbf{until}} +\def\ALC@item[#1]{% +\if@noparitem \@donoparitem + \else \if@inlabel \indent \par \fi + \ifhmode \unskip\unskip \par \fi + \if@newlist \if@nobreak \@nbitem \else + \addpenalty\@beginparpenalty + \addvspace\@topsep \addvspace{-\parskip}\fi + \else \addpenalty\@itempenalty \addvspace\itemsep + \fi + \global\@inlabeltrue +\fi +\everypar{\global\@minipagefalse\global\@newlistfalse + \if@inlabel\global\@inlabelfalse \hskip -\parindent \box\@labels + \penalty\z@ \fi + \everypar{}}\global\@nobreakfalse +\if@noitemarg \@noitemargfalse \if@nmbrlist \refstepcounter{\@listctr}\fi \fi +\sbox\@tempboxa{\makelabel{#1}}% +\global\setbox\@labels + \hbox{\unhbox\@labels \hskip \itemindent + \hskip -\labelwidth \hskip -\ALC@tlm + \ifdim \wd\@tempboxa >\labelwidth + \box\@tempboxa + \else \hbox to\labelwidth {\unhbox\@tempboxa}\fi + \hskip \ALC@tlm}\ignorespaces} +% +\newenvironment{algorithmic}[1][0]{ +\setcounter{ALC@depth}{\@listdepth}% +\let\@listdepth\c@ALC@depth% +\let\@item\ALC@item + \newcommand{\ALC@lno}{% +\ifthenelse{\equal{\arabic{ALC@rem}}{0}} +{{\algorithmiclnosize\algorithmiclnofont \arabic{ALC@line}\algorithmiclnodelimiter}}{}% +} +\let\@listii\@listi +\let\@listiii\@listi +\let\@listiv\@listi +\let\@listv\@listi +\let\@listvi\@listi +\let\@listvii\@listi + \newenvironment{ALC@g}{ + \begin{list}{\ALC@lno}{ \itemsep\z@ \itemindent\z@ + \listparindent\z@ \rightmargin\z@ + \topsep\z@ \partopsep\z@ \parskip\z@\parsep\z@ + \leftmargin 1em + \addtolength{\ALC@tlm}{\leftmargin} + } + } + {\end{list}} + \newcommand{\ALC@it}{\refstepcounter{ALC@line}\addtocounter{ALC@rem}{1}\ifthenelse{\equal{\arabic{ALC@rem}}{#1}}{\setcounter{ALC@rem}{0}}{}\item} + \newcommand{\ALC@com}[1]{\ifthenelse{\equal{##1}{default}}% +{}{\ \algorithmiccomment{##1}}} + \newcommand{\REQUIRE}{\item[\algorithmicrequire]} + \newcommand{\ENSURE}{\item[\algorithmicensure]} + \newcommand{\STATE}{\ALC@it} + \newcommand{\COMMENT}[1]{\algorithmiccomment{##1}} + \newenvironment{ALC@if}{\begin{ALC@g}}{\end{ALC@g}} + \newenvironment{ALC@for}{\begin{ALC@g}}{\end{ALC@g}} + \newenvironment{ALC@whl}{\begin{ALC@g}}{\end{ALC@g}} + \newenvironment{ALC@loop}{\begin{ALC@g}}{\end{ALC@g}} + \newenvironment{ALC@rpt}{\begin{ALC@g}}{\end{ALC@g}} + \renewcommand{\\}{\@centercr} + \newcommand{\IF}[2][default]{\ALC@it\algorithmicif\ ##2\ \algorithmicthen% +\ALC@com{##1}\begin{ALC@if}} + \newcommand{\ELSE}[1][default]{\end{ALC@if}\ALC@it\algorithmicelse% +\ALC@com{##1}\begin{ALC@if}} + \newcommand{\ELSIF}[2][default]% +{\end{ALC@if}\ALC@it\algorithmicelsif\ ##2\ \algorithmicthen% +\ALC@com{##1}\begin{ALC@if}} + \newcommand{\FOR}[2][default]{\ALC@it\algorithmicfor\ ##2\ \algorithmicdo% +\ALC@com{##1}\begin{ALC@for}} + \newcommand{\FORALL}[2][default]{\ALC@it\algorithmicforall\ ##2\ % +\algorithmicdo% +\ALC@com{##1}\begin{ALC@for}} + \newcommand{\WHILE}[2][default]{\ALC@it\algorithmicwhile\ ##2\ % +\algorithmicdo% +\ALC@com{##1}\begin{ALC@whl}} + \newcommand{\LOOP}[1][default]{\ALC@it\algorithmicloop% +\ALC@com{##1}\begin{ALC@loop}} + \newcommand{\REPEAT}[1][default]{\ALC@it\algorithmicrepeat% +\ALC@com{##1}\begin{ALC@rpt}} + \newcommand{\UNTIL}[1]{\end{ALC@rpt}\ALC@it\algorithmicuntil\ ##1} + \ifthenelse{\boolean{ALC@noend}}{ + \newcommand{\ENDIF}{\end{ALC@if}} + \newcommand{\ENDFOR}{\end{ALC@for}} + \newcommand{\ENDWHILE}{\end{ALC@whl}} + \newcommand{\ENDLOOP}{\end{ALC@loop}} + }{ + \newcommand{\ENDIF}{\end{ALC@if}\ALC@it\algorithmicendif} + \newcommand{\ENDFOR}{\end{ALC@for}\ALC@it\algorithmicendfor} + \newcommand{\ENDWHILE}{\end{ALC@whl}\ALC@it\algorithmicendwhile} + \newcommand{\ENDLOOP}{\end{ALC@loop}\ALC@it\algorithmicendloop} + } + \renewcommand{\@toodeep}{} + \begin{list}{\ALC@lno}{\setcounter{ALC@line}{0}\setcounter{ALC@rem}{0}% + \itemsep\z@ \itemindent\z@ \listparindent\z@% + \partopsep\z@ \parskip\z@ \parsep\z@% + \labelsep 0.5em \topsep 0.2em% +\ifthenelse{\equal{#1}{0}} + {\labelwidth 0.5em } + {\labelwidth 1.2em } +\leftmargin\labelwidth \addtolength{\leftmargin}{\labelsep} + \ALC@tlm\labelsep + } +} +{% +\setcounter{ALCPLUS@lastline}{\value{ALC@line}}% +\end{list}} + +\newcommand{\continuecounting}{\setcounter{ALC@line}{\value{ALCPLUS@lastline}}} +\newcommand{\startcounting}[1]{\setcounter{ALC@line}{#1}\addtocounter{ALC@line}{-1}} + +\newcommand{\EMPTY}{\item[]} +\newcommand{\SPACE}{\vspace{3mm}} +\newcommand{\SHORTSPACE}{\vspace{1mm}} +\newcommand{\newlinetag}[3]{\newcommand{#1}[#2]{\item[#3]}} +\newcommand{\newconstruct}[5]{% + \newenvironment{ALC@\string#1}{\begin{ALC@g}}{\end{ALC@g}} + \newcommand{#1}[2][default]{\ALC@it#2\ ##2\ #3% + \ALC@com{##1}\begin{ALC@\string#1}} + \ifthenelse{\boolean{ALC@noend}}{ + \newcommand{#4}{\end{ALC@\string#1}} + }{ + \newcommand{#4}{\end{ALC@\string#1}\ALC@it#5} + } +} + +\newconstruct{\INDENT}{}{}{\ENDINDENT}{} + +\newcommand{\setlinenosize}[1]{\renewcommand{\algorithmiclnosize}{#1}} +\newcommand{\setlinenofont}[1]{\renewcommand{\algorithmiclnofont}{#1}} diff --git a/spec/consensus/consensus-paper/conclusion.tex b/spec/consensus/consensus-paper/conclusion.tex new file mode 100644 index 0000000..86c4564 --- /dev/null +++ b/spec/consensus/consensus-paper/conclusion.tex @@ -0,0 +1,16 @@ +\section{Conclusion} \label{sec:conclusion} + +We have proposed a new Byzantine-fault tolerant consensus algorithm that is the +core of the Tendermint BFT SMR platform. The algorithm is designed for the wide +area network with high number of mutually distrusted nodes that communicate +over gossip based peer-to-peer network. It has only a single mode of execution +and the communication pattern is very similar to the "normal" case of the +state-of-the art PBFT algorithm. The algorithm ensures termination with a novel +mechanism that takes advantage of the gossip based communication between nodes. +The proposed algorithm and the proofs are simple and elegant, and we believe +that this makes it easier to understand and implement correctly. + +\section*{Acknowledgment} + +We would like to thank Anton Kaliaev, Ismail Khoffi and Dahlia Malkhi for comments on an earlier version of the paper. We also want to thank Marko Vukolic, Ming Chuan Lin, Maria Potop-Butucaru, Sara Tucci, Antonella Del Pozzo and Yackolley Amoussou-Guenou for pointing out the liveness issues +in the previous version of the algorithm. Finally, we want to thank the Tendermint team members and all project contributors for making Tendermint such a great platform. diff --git a/spec/consensus/consensus-paper/consensus.tex b/spec/consensus/consensus-paper/consensus.tex new file mode 100644 index 0000000..2d4e9a6 --- /dev/null +++ b/spec/consensus/consensus-paper/consensus.tex @@ -0,0 +1,397 @@ + +\section{Tendermint consensus algorithm} \label{sec:tendermint} + +\newcommand\Disseminate{\textbf{Disseminate}} + +\newcommand\Proposal{\mathsf{PROPOSAL}} +\newcommand\ProposalPart{\mathsf{PROPOSAL\mbox{-}PART}} +\newcommand\PrePrepare{\mathsf{INIT}} \newcommand\Prevote{\mathsf{PREVOTE}} +\newcommand\Precommit{\mathsf{PRECOMMIT}} +\newcommand\Decision{\mathsf{DECISION}} + +\newcommand\ViewChange{\mathsf{VC}} +\newcommand\ViewChangeAck{\mathsf{VC\mbox{-}ACK}} +\newcommand\NewPrePrepare{\mathsf{VC\mbox{-}INIT}} +\newcommand\coord{\mathsf{proposer}} + +\newcommand\newHeight{newHeight} \newcommand\newRound{newRound} +\newcommand\nil{nil} \newcommand\id{id} \newcommand{\propose}{propose} +\newcommand\prevote{prevote} \newcommand\prevoteWait{prevoteWait} +\newcommand\precommit{precommit} \newcommand\precommitWait{precommitWait} +\newcommand\commit{commit} + +\newcommand\timeoutPropose{timeoutPropose} +\newcommand\timeoutPrevote{timeoutPrevote} +\newcommand\timeoutPrecommit{timeoutPrecommit} +\newcommand\proofOfLocking{proof\mbox{-}of\mbox{-}locking} + +\begin{algorithm}[htb!] \def\baselinestretch{1} \scriptsize\raggedright + \begin{algorithmic}[1] + \SHORTSPACE + \INIT{} + \STATE $h_p := 0$ + \COMMENT{current height, or consensus instance we are currently executing} + \STATE $round_p := 0$ \COMMENT{current round number} + \STATE $step_p \in \set{\propose, \prevote, \precommit}$ + \STATE $decision_p[] := nil$ + \STATE $lockedValue_p := nil$ + \STATE $lockedRound_p := -1$ + \STATE $validValue_p := nil$ + \STATE $validRound_p := -1$ + \ENDINIT + \SHORTSPACE + \STATE \textbf{upon} start \textbf{do} $StartRound(0)$ + \SHORTSPACE + \FUNCTION{$StartRound(round)$} \label{line:tab:startRound} + \STATE $round_p \assign round$ + \STATE $step_p \assign \propose$ + \IF{$\coord(h_p, round_p) = p$} + \IF{$validValue_p \neq \nil$} \label{line:tab:isThereLockedValue} + \STATE $proposal \assign validValue_p$ \ELSE \STATE $proposal \assign + getValue()$ + \label{line:tab:getValidValue} + \ENDIF + \STATE \Broadcast\ $\li{\Proposal,h_p, round_p, proposal, validRound_p}$ + \label{line:tab:send-proposal} + \ELSE + \STATE \textbf{schedule} $OnTimeoutPropose(h_p, + round_p)$ to be executed \textbf{after} $\timeoutPropose(round_p)$ + \ENDIF + \ENDFUNCTION + + \SPACE + \UPON{$\li{\Proposal,h_p,round_p, v, -1}$ \From\ $\coord(h_p,round_p)$ + \With\ $step_p = \propose$} \label{line:tab:recvProposal} + \IF{$valid(v) \wedge (lockedRound_p = -1 \vee lockedValue_p = v$)} + \label{line:tab:accept-proposal-2} + \STATE \Broadcast \ $\li{\Prevote,h_p,round_p,id(v)}$ + \label{line:tab:prevote-proposal} + \ELSE + \label{line:tab:acceptProposal1} + \STATE \Broadcast \ $\li{\Prevote,h_p,round_p,\nil}$ + \label{line:tab:prevote-nil} + \ENDIF + \STATE $step_p \assign \prevote$ \label{line:tab:setStateToPrevote1} + \ENDUPON + + \SPACE + \UPON{$\li{\Proposal,h_p,round_p, v, vr}$ \From\ $\coord(h_p,round_p)$ + \textbf{AND} $2f+1$ $\li{\Prevote,h_p, vr,id(v)}$ \With\ $step_p = \propose \wedge (vr \ge 0 \wedge vr < round_p)$} + \label{line:tab:acceptProposal} + \IF{$valid(v) \wedge (lockedRound_p \le vr + \vee lockedValue_p = v)$} \label{line:tab:cond-prevote-higher-proposal} + \STATE \Broadcast \ $\li{\Prevote,h_p,round_p,id(v)}$ + \label{line:tab:prevote-higher-proposal} + \ELSE + \label{line:tab:acceptProposal2} + \STATE \Broadcast \ $\li{\Prevote,h_p,round_p,\nil}$ + \label{line:tab:prevote-nil2} + \ENDIF + \STATE $step_p \assign \prevote$ \label{line:tab:setStateToPrevote3} + \ENDUPON + + \SPACE + \UPON{$2f+1$ $\li{\Prevote,h_p, round_p,*}$ \With\ $step_p = \prevote$ for the first time} + \label{line:tab:recvAny2/3Prevote} + \STATE \textbf{schedule} $OnTimeoutPrevote(h_p, round_p)$ to be executed \textbf{after} $\timeoutPrevote(round_p)$ \label{line:tab:timeoutPrevote} + \ENDUPON + + \SPACE + \UPON{$\li{\Proposal,h_p,round_p, v, *}$ \From\ $\coord(h_p,round_p)$ + \textbf{AND} $2f+1$ $\li{\Prevote,h_p, round_p,id(v)}$ \With\ $valid(v) \wedge step_p \ge \prevote$ for the first time} + \label{line:tab:recvPrevote} + \IF{$step_p = \prevote$} + \STATE $lockedValue_p \assign v$ \label{line:tab:setLockedValue} + \STATE $lockedRound_p \assign round_p$ \label{line:tab:setLockedRound} + \STATE \Broadcast \ $\li{\Precommit,h_p,round_p,id(v))}$ + \label{line:tab:precommit-v} + \STATE $step_p \assign \precommit$ \label{line:tab:setStateToCommit} + \ENDIF + \STATE $validValue_p \assign v$ \label{line:tab:setValidRound} + \STATE $validRound_p \assign round_p$ \label{line:tab:setValidValue} + \ENDUPON + + \SHORTSPACE + \UPON{$2f+1$ $\li{\Prevote,h_p,round_p, \nil}$ + \With\ $step_p = \prevote$} + \STATE \Broadcast \ $\li{\Precommit,h_p,round_p, \nil}$ + \label{line:tab:precommit-v-1} + \STATE $step_p \assign \precommit$ + \ENDUPON + + \SPACE + \UPON{$2f+1$ $\li{\Precommit,h_p,round_p,*}$ for the first time} + \label{line:tab:startTimeoutPrecommit} + \STATE \textbf{schedule} $OnTimeoutPrecommit(h_p, round_p)$ to be executed \textbf{after} $\timeoutPrecommit(round_p)$ + + \ENDUPON + + \SPACE + \UPON{$\li{\Proposal,h_p,r, v, *}$ \From\ $\coord(h_p,r)$ \textbf{AND} + $2f+1$ $\li{\Precommit,h_p,r,id(v)}$ \With\ $decision_p[h_p] = \nil$} + \label{line:tab:onDecideRule} + \IF{$valid(v)$} \label{line:tab:validDecisionValue} + \STATE $decision_p[h_p] = v$ \label{line:tab:decide} + \STATE$h_p \assign h_p + 1$ \label{line:tab:increaseHeight} + \STATE reset $lockedRound_p$, $lockedValue_p$, $validRound_p$ and $validValue_p$ to initial values + and empty message log + \STATE $StartRound(0)$ + \ENDIF + \ENDUPON + + \SHORTSPACE + \UPON{$f+1$ $\li{*,h_p,round, *, *}$ \textbf{with} $round > round_p$} + \label{line:tab:skipRounds} + \STATE $StartRound(round)$ \label{line:tab:nextRound2} + \ENDUPON + + \SHORTSPACE + \FUNCTION{$OnTimeoutPropose(height,round)$} \label{line:tab:onTimeoutPropose} + \IF{$height = h_p \wedge round = round_p \wedge step_p = \propose$} + \STATE \Broadcast \ $\li{\Prevote,h_p,round_p, \nil}$ + \label{line:tab:prevote-nil-on-timeout} + \STATE $step_p \assign \prevote$ + \ENDIF + \ENDFUNCTION + + \SHORTSPACE + \FUNCTION{$OnTimeoutPrevote(height,round)$} \label{line:tab:onTimeoutPrevote} + \IF{$height = h_p \wedge round = round_p \wedge step_p = \prevote$} + \STATE \Broadcast \ $\li{\Precommit,h_p,round_p,\nil}$ + \label{line:tab:precommit-nil-onTimeout} + \STATE $step_p \assign \precommit$ + \ENDIF + \ENDFUNCTION + + \SHORTSPACE + \FUNCTION{$OnTimeoutPrecommit(height,round)$} \label{line:tab:onTimeoutPrecommit} + \IF{$height = h_p \wedge round = round_p$} + \STATE $StartRound(round_p + 1)$ \label{line:tab:nextRound} + \ENDIF + \ENDFUNCTION + \end{algorithmic} \caption{Tendermint consensus algorithm} + \label{alg:tendermint} +\end{algorithm} + +In this section we present the Tendermint Byzantine fault-tolerant consensus +algorithm. The algorithm is specified by the pseudo-code shown in +Algorithm~\ref{alg:tendermint}. We present the algorithm as a set of \emph{upon +rules} that are executed atomically\footnote{In case several rules are active +at the same time, the first rule to be executed is picked randomly. The +correctness of the algorithm does not depend on the order in which rules are +executed.}. We assume that processes exchange protocol messages using a gossip +protocol and that both sent and received messages are stored in a local message +log for every process. An upon rule is triggered once the message log contains +messages such that the corresponding condition evaluates to $\tt{true}$. The +condition that assumes reception of $X$ messages of a particular type and +content denotes reception of messages whose senders have aggregate voting power at +least equal to $X$. For example, the condition $2f+1$ $\li{\Precommit,h_p,r,id(v)}$, +evaluates to true upon reception of $\Precommit$ messages for height $h_p$, +a round $r$ and with value equal to $id(v)$ whose senders have aggregate voting +power at least equal to $2f+1$. Some of the rules ends with "for the first time" constraint +to denote that it is triggered only the first time a corresponding condition evaluates +to $\tt{true}$. This is because those rules do not always change the state of algorithm +variables so without this constraint, the algorithm could keep +executing those rules forever. The variables with index $p$ are process local state +variables, while variables without index $p$ are value placeholders. The sign +$*$ denotes any value. + +We denote with $n$ the total voting power of processes in the system, and we +assume that the total voting power of faulty processes in the system is bounded +with a system parameter $f$. The algorithm assumes that $n > 3f$, i.e., it +requires that the total voting power of faulty processes is smaller than one +third of the total voting power. For simplicity we present the algorithm for +the case $n = 3f + 1$. + +The algorithm proceeds in rounds, where each round has a dedicated +\emph{proposer}. The mapping of rounds to proposers is known to all processes +and is given as a function $\coord(h, round)$, returning the proposer for +the round $round$ in the consensus instance $h$. We +assume that the proposer selection function is weighted round-robin, where +processes are rotated proportional to their voting power\footnote{A validator +with more voting power is selected more frequently, proportional to its power. +More precisely, during a sequence of rounds of size $n$, every process is +proposer in a number of rounds equal to its voting power.}. +The internal protocol state transitions are triggered by message reception and +by expiration of timeouts. There are three timeouts in Algorithm \ref{alg:tendermint}: +$\timeoutPropose$, $\timeoutPrevote$ and $\timeoutPrecommit$. +The timeouts prevent the algorithm from blocking and +waiting forever for some condition to be true, ensure that processes continuously +transition between rounds, and guarantee that eventually (after GST) communication +between correct processes is timely and reliable so they can decide. +The last role is achieved by increasing the timeouts with every new round $r$, +i.e, $timeoutX(r) = initTimeoutX + r*timeoutDelta$; +they are reset for every new height (consensus +instance). + +Processes exchange the following messages in Tendermint: $\Proposal$, +$\Prevote$ and $\Precommit$. The $\Proposal$ message is used by the proposer of +the current round to suggest a potential decision value, while $\Prevote$ and +$\Precommit$ are votes for a proposed value. According to the classification of +consensus algorithms from \cite{RMS10:dsn}, Tendermint, like PBFT +\cite{CL02:tcs} and DLS \cite{DLS88:jacm}, belongs to class 3, so it requires +two voting steps (three communication exchanges in total) to decide a value. +The Tendermint consensus algorithm is designed for the blockchain context where +the value to decide is a block of transactions (ie. it is potentially quite +large, consisting of many transactions). Therefore, in the Algorithm +\ref{alg:tendermint} (similar as in \cite{CL02:tcs}) we are explicit about +sending a value (block of transactions) and a small, constant size value id (a +unique value identifier, normally a hash of the value, i.e., if $\id(v) = +\id(v')$, then $v=v'$). The $\Proposal$ message is the only one carrying the +value; $\Prevote$ and $\Precommit$ messages carry the value id. A correct +process decides on a value $v$ in Tendermint upon receiving the $\Proposal$ for +$v$ and $2f+1$ voting-power equivalent $\Precommit$ messages for $\id(v)$ in +some round $r$. In order to send $\Precommit$ message for $v$ in a round $r$, a +correct process waits to receive the $\Proposal$ and $2f+1$ of the +corresponding $\Prevote$ messages in the round $r$. Otherwise, +it sends $\Precommit$ message with a special $\nil$ value. +This ensures that correct processes can $\Precommit$ only a +single value (or $\nil$) in a round. As +proposers may be faulty, the proposed value is treated by correct processes as +a suggestion (it is not blindly accepted), and a correct process tells others +if it accepted the $\Proposal$ for value $v$ by sending $\Prevote$ message for +$\id(v)$; otherwise it sends $\Prevote$ message with the special $\nil$ value. + +Every process maintains the following variables in the Algorithm +\ref{alg:tendermint}: $step$, $lockedValue$, $lockedRound$, $validValue$ and +$validRound$. The $step$ denotes the current state of the internal Tendermint +state machine, i.e., it reflects the stage of the algorithm execution in the +current round. The $lockedValue$ stores the most recent value (with respect to +a round number) for which a $\Precommit$ message has been sent. The +$lockedRound$ is the last round in which the process sent a $\Precommit$ +message that is not $\nil$. We also say that a correct process locks a value +$v$ in a round $r$ by setting $lockedValue = v$ and $lockedRound = r$ before +sending $\Precommit$ message for $\id(v)$. As a correct process can decide a +value $v$ only if $2f+1$ $\Precommit$ messages for $\id(v)$ are received, this +implies that a possible decision value is a value that is locked by at least +$f+1$ voting power equivalent of correct processes. Therefore, any value $v$ +for which $\Proposal$ and $2f+1$ of the corresponding $\Prevote$ messages are +received in some round $r$ is a \emph{possible decision} value. The role of the +$validValue$ variable is to store the most recent possible decision value; the +$validRound$ is the last round in which $validValue$ is updated. Apart from +those variables, a process also stores the current consensus instance ($h_p$, +called \emph{height} in Tendermint), and the current round number ($round_p$) +and attaches them to every message. Finally, a process also stores an array of +decisions, $decision_p$ (Tendermint assumes a sequence of consensus instances, +one for each height). + +Every round starts by a proposer suggesting a value with the $\Proposal$ +message (see line \ref{line:tab:send-proposal}). In the initial round of each +height, the proposer is free to chose the value to suggest. In the +Algorithm~\ref{alg:tendermint}, a correct process obtains a value to propose +using an external function $getValue()$ that returns a valid value to +propose. In the following rounds, a correct proposer will suggest a new value +only if $validValue = \nil$; otherwise $validValue$ is proposed (see +lines~\ref{line:tab:isThereLockedValue}-\ref{line:tab:getValidValue}). +In addition to the value proposed, the $\Proposal$ message also +contains the $validRound$ so other processes are informed about the last round +in which the proposer observed $validValue$ as a possible decision value. +Note that if a correct proposer $p$ sends $validValue$ with the $validRound$ in the +$\Proposal$, this implies that the process $p$ received $\Proposal$ and the +corresponding $2f+1$ $\Prevote$ messages for $validValue$ in the round +$validRound$. +If a correct process sends $\Proposal$ message with $validValue$ ($validRound > -1$) +at time $t > GST$, by the \emph{Gossip communication} property, the +corresponding $\Proposal$ and the $\Prevote$ messages will be received by all +correct processes before time $t+\Delta$. Therefore, all correct processes will +be able to verify the correctness of the suggested value as it is supported by +the $\Proposal$ and the corresponding $2f+1$ voting power equivalent $\Prevote$ +messages. + +A correct process $p$ accepts the proposal for a value $v$ (send $\Prevote$ +for $id(v)$) if an external \emph{valid} function returns $true$ for the value +$v$, and if $p$ hasn't locked any value ($lockedRound = -1$) or $p$ has locked +the value $v$ ($lockedValue = v$); see the line +\ref{line:tab:accept-proposal-2}. In case the proposed pair is $(v,vr \ge 0)$ and a +correct process $p$ has locked some value, it will accept +$v$ if it is a more recent possible decision value\footnote{As +explained above, the possible decision value in a round $r$ is the one for +which $\Proposal$ and the corresponding $2f+1$ $\Prevote$ messages are received +for the round $r$.}, $vr > lockedRound_p$, or if $lockedValue = v$ +(see line~\ref{line:tab:cond-prevote-higher-proposal}). Otherwise, a correct +process will reject the proposal by sending $\Prevote$ message with $\nil$ +value. A correct process will send $\Prevote$ message with $\nil$ value also in +case $\timeoutPropose$ expired (it is triggered when a correct process starts a +new round) and a process has not sent $\Prevote$ message in the current round +yet (see the line \ref{line:tab:onTimeoutPropose}). + +If a correct process receives $\Proposal$ message for some value $v$ and $2f+1$ +$\Prevote$ messages for $\id(v)$, then it sends $\Precommit$ message with +$\id(v)$. Otherwise, it sends $\Precommit$ $\nil$. A correct process will send +$\Precommit$ message with $\nil$ value also in case $\timeoutPrevote$ expired +(it is started when a correct process sent $\Prevote$ message and received any +$2f+1$ $\Prevote$ messages) and a process has not sent $\Precommit$ message in +the current round yet (see the line \ref{line:tab:onTimeoutPrecommit}). A +correct process decides on some value $v$ if it receives in some round $r$ +$\Proposal$ message for $v$ and $2f+1$ $\Precommit$ messages with $\id(v)$ (see +the line \ref{line:tab:decide}). To prevent the algorithm from blocking and +waiting forever for this condition to be true, the Algorithm +\ref{alg:tendermint} relies on $\timeoutPrecommit$. It is triggered after a +process receives any set of $2f+1$ $\Precommit$ messages for the current round. +If the $\timeoutPrecommit$ expires and a process has not decided yet, the +process starts the next round (see the line \ref{line:tab:onTimeoutPrecommit}). +When a correct process $p$ decides, it starts the next consensus instance +(for the next height). The \emph{Gossip communication} property ensures +that $\Proposal$ and $2f+1$ $\Prevote$ messages that led $p$ to decide +are eventually received by all correct processes, so they will also decide. + +\subsection{Termination mechanism} + +Tendermint ensures termination by a novel mechanism that benefits from the +gossip based nature of communication (see \emph{Gossip communication} +property). It requires managing two additional variables, $validValue$ and +$validRound$ that are then used by the proposer during the propose step as +explained above. The $validValue$ and $validRound$ are updated to $v$ and $r$ +by a correct process in a round $r$ when the process receives valid $\Proposal$ +message for the value $v$ and the corresponding $2f+1$ $\Prevote$ messages for +$id(v)$ in the round $r$ (see the rule at line~\ref{line:tab:recvPrevote}). + +We now give briefly the intuition how managing and proposing $validValue$ +and $validRound$ ensures termination. Formal treatment is left for +Section~\ref{sec:proof}. + +The first thing to note is that during good period, because of the +\emph{Gossip communication} property, if a correct process $p$ locks a value +$v$ in some round $r$, all correct processes will update $validValue$ to $v$ +and $validRound$ to $r$ before the end of the round $r$ (we prove this formally +in the Section~\ref{sec:proof}). The intuition is that messages that led to $p$ +locking a value $v$ in the round $r$ will be gossiped to all correct processes +before the end of the round $r$, so it will update $validValue$ and +$validRound$ (the line~\ref{line:tab:recvPrevote}). Therefore, if a correct +process locks some value during good period, $validValue$ and $validRound$ are +updated by all correct processes so that the value proposed in the following +rounds will be acceptable by all correct processes. Note +that it could happen that during good period, no correct process locks a value, +but some correct process $q$ updates $validValue$ and $validRound$ during some +round. As no correct process locks a value in this case, $validValue_q$ and +$validRound_q$ will also be acceptable by all correct processes as +$validRound_q > lockedRound_c$ for every correct process $c$ and as the +\emph{Gossip communication} property ensures that the corresponding $\Prevote$ +messages that $q$ received in the round $validRound_q$ are received by all +correct processes $\Delta$ time later. + +Finally, it could happen that after GST, there is a long sequence of rounds in which +no correct process neither locks a value nor update $validValue$ and $validRound$. +In this case, during this sequence of rounds, the proposed value suggested by correct +processes was not accepted by all correct processes. Note that this sequence of rounds +is always finite as at the beginning of every +round there is at least a single correct process $c$ such that $validValue_c$ +and $validRound_c$ are acceptable by every correct process. This is true as +there exists a correct process $c$ such that for every other correct process +$p$, $validRound_c > lockedRound_p$ or $validValue_c = lockedValue_p$. This is +true as $c$ is the process that has locked a value in the most recent round +among all correct processes (or no correct process locked any value). Therefore, +eventually $c$ will be the proper in some round and the proposed value will be accepted +by all correct processes, terminating therefore this sequence of +rounds. + +Therefore, updating $validValue$ and $validRound$ variables, and the +\emph{Gossip communication} property, together ensures that eventually, during +the good period, there exists a round with a correct proposer whose proposed +value will be accepted by all correct processes, and all correct processes will +terminate in that round. Note that this mechanism, contrary to the common +termination mechanism illustrated in the +Figure~\ref{ch3:fig:coordinator-change}, does not require exchanging any +additional information in addition to messages already sent as part of what is +normally being called "normal" case. + diff --git a/spec/consensus/consensus-paper/definitions.tex b/spec/consensus/consensus-paper/definitions.tex new file mode 100644 index 0000000..1cd5398 --- /dev/null +++ b/spec/consensus/consensus-paper/definitions.tex @@ -0,0 +1,126 @@ +\section{Definitions} \label{sec:definitions} + +\subsection{Model} + +We consider a system of processes that communicate by exchanging messages. +Processes can be correct or faulty, where a faulty process can behave in an +arbitrary way, i.e., we consider Byzantine faults. We assume that each process +has some amount of voting power (voting power of a process can be $0$). +Processes in our model are not part of a single administrative domain; +therefore we cannot enforce a direct network connectivity between all +processes. Instead, we assume that each process is connected to a subset of +processes called peers, such that there is an indirect communication channel +between all correct processes. Communication between processes is established +using a gossip protocol \cite{Dem1987:gossip}. + +Formally, we model the network communication using a variant of the \emph{partially +synchronous system model}~\cite{DLS88:jacm}: in all executions of the system +there is a bound $\Delta$ and an instant GST (Global Stabilization Time) such +that all communication among correct processes after GST is reliable and +$\Delta$-timely, i.e., if a correct process $p$ sends message $m$ at time $t +\ge GST$ to a correct process $q$, then $q$ will receive $m$ before $t + +\Delta$\footnote{Note that as we do not assume direct communication channels + among all correct processes, this implies that before the message $m$ + reaches $q$, it might pass through a number of correct processes that will +forward the message $m$ using gossip protocol towards $q$.}. +In addition to the standard \emph{partially + synchronous system model}~\cite{DLS88:jacm}, we assume an auxiliary property +that captures gossip-based nature of communication\footnote{The details of the Tendermint gossip protocol will be discussed in a separate + technical report. }: + + +\begin{itemize} \item \emph{Gossip communication:} If a correct process $p$ + sends some message $m$ at time $t$, all correct processes will receive + $m$ before $max\{t, GST\} + \Delta$. Furthermore, if a correct process $p$ + receives some message $m$ at time $t$, all correct processes will receive + $m$ before $max\{t, GST\} + \Delta$. \end{itemize} + + +The bound $\Delta$ and GST are system +parameters whose values are not required to be known for the safety of our +algorithm. Termination of the algorithm is guaranteed within a bounded duration +after GST. In practice, the algorithm will work correctly in the slightly +weaker variant of the model where the system alternates between (long enough) +good periods (corresponds to the \emph{after} GST period where system is +reliable and $\Delta$-timely) and bad periods (corresponds to the period +\emph{before} GST during which the system is asynchronous and messages can be +lost), but consideration of the GST model simplifies the discussion. + +We assume that process steps (which might include sending and receiving +messages) take zero time. Processes are equipped with clocks so they can +measure local timeouts. +Spoofing/impersonation attacks are assumed to be impossible at all times due to +the use of public-key cryptography, i.e., we assume that all protocol messages contains a digital signature. +Therefore, when a correct +process $q$ receives a signed message $m$ from its peer, the process $q$ can +verify who was the original sender of the message $m$ and if the message signature is valid. +We do not explicitly state a signature verification step in the pseudo-code of the algorithm to improve readability; +we assume that only messages with the valid signature are considered at that level (and messages with invalid signatures +are dropped). + + + +%Messages that are being gossiped are created by the consensus layer. We can + %think about consensus protocol as a content creator, which %defines what + %messages should be disseminated using the gossip protocol. A correct + %process creates the message for dissemination either i) %explicitly, by + %invoking \emph{send} function as part of the consensus protocol or ii) + %implicitly, by receiving a message from some other %process. Note that in + %the case ii) gossiping of messages is implicit, i.e., it happens without + %explicit send clause in the consensus algorithm %whenever a correct + %process receives some messages in the consensus algorithm\footnote{If a + %message is received by a correct process at %the consensus level then it + %is considered valid from the protocol point of view, i.e., it has a + %correct signature, a proper message structure %and a valid height and + %round number.}. + +%\item Processes keep resending messages (in case of failures or message loss) + %until all its peers get them. This ensures that every message %sent or + %received by a correct process is eventually received by all correct + %processes. + +\subsection{State Machine Replication} + +State machine replication (SMR) is a general approach for replicating services +modeled as a deterministic state machine~\cite{Lam78:cacm,Sch90:survey}. The +key idea of this approach is to guarantee that all replicas start in the same +state and then apply requests from clients in the same order, thereby +guaranteeing that the replicas' states will not diverge. Following +Schneider~\cite{Sch90:survey}, we note that the following is key for +implementing a replicated state machine tolerant to (Byzantine) faults: + +\begin{itemize} \item \emph{Replica Coordination.} All [non-faulty] replicas + receive and process the same sequence of requests. \end{itemize} + +Moreover, as Schneider also notes, this property can be decomposed into two +parts, \emph{Agreement} and \emph{Order}: Agreement requires all (non-faulty) +replicas to receive all requests, and Order requires that the order of received +requests is the same at all replicas. + +There is an additional requirement that needs to be ensured by Byzantine +tolerant state machine replication: only requests (called transactions in the +Tendermint terminology) proposed by clients are executed. In Tendermint, +transaction verification is the responsibility of the service that is being +replicated; upon receiving a transaction from the client, the Tendermint +process will ask the service if the request is valid, and only valid requests +will be processed. + + \subsection{Consensus} \label{sec:consensus} + +Tendermint solves state machine replication by sequentially executing consensus +instances to agree on each block of transactions that are +then executed by the service being replicated. We consider a variant of the +Byzantine consensus problem called Validity Predicate-based Byzantine consensus +that is motivated by blockchain systems~\cite{GLR17:red-belly-bc}. The problem +is defined by an agreement, a termination, and a validity property. + + \begin{itemize} \item \emph{Agreement:} No two correct processes decide on + different values. \item \emph{Termination:} All correct processes + eventually decide on a value. \item \emph{Validity:} A decided value + is valid, i.e., it satisfies the predefined predicate denoted + \emph{valid()}. \end{itemize} + + This variant of the Byzantine consensus problem has an application-specific + \emph{valid()} predicate to indicate whether a value is valid. In the context + of blockchain systems, for example, a value is not valid if it does not + contain an appropriate hash of the last value (block) added to the blockchain. diff --git a/spec/consensus/consensus-paper/homodel.sty b/spec/consensus/consensus-paper/homodel.sty new file mode 100644 index 0000000..0ba4318 --- /dev/null +++ b/spec/consensus/consensus-paper/homodel.sty @@ -0,0 +1,32 @@ +\newcommand{\NC}{\mbox{\it NC}} +\newcommand{\HO}{\mbox{\it HO}} +\newcommand{\AS}{\mbox{\it AS}} +\newcommand{\SK}{\mbox{\it SK}} +\newcommand{\SHO}{\mbox{\it SHO}} +\newcommand{\AHO}{\mbox{\it AHO}} +\newcommand{\CONS}{\mbox{\it CONS}} +\newcommand{\K}{\mbox{\it K}} + +\newcommand{\Alg}{\mathcal{A}} +\newcommand{\Pred}{\mathcal{P}} +\newcommand{\Spr}{S_p^r} +\newcommand{\Tpr}{T_p^r} +\newcommand{\mupr}{\vec{\mu}_p^{\,r}} + +\newcommand{\MSpr}{S_p^{\rho}} +\newcommand{\MTpr}{T_p^{\rho}} + + + +\newconstruct{\SEND}{$\Spr$:}{}{\ENDSEND}{} +\newconstruct{\TRAN}{$\Tpr$:}{}{\ENDTRAN}{} +\newconstruct{\ROUND}{\textbf{Round}}{\!\textbf{:}}{\ENDROUND}{} +\newconstruct{\VARIABLES}{\textbf{Variables:}}{}{\ENDVARIABLES}{} +\newconstruct{\INIT}{\textbf{Initialization:}}{}{\ENDINIT}{} + +\newconstruct{\MSEND}{$\MSpr$:}{}{\ENDMSEND}{} +\newconstruct{\MTRAN}{$\MTpr$:}{}{\ENDMTRAN}{} + +\newconstruct{\SROUND}{\textbf{Selection Round}}{\!\textbf{:}}{\ENDSROUND}{} +\newconstruct{\VROUND}{\textbf{Validation Round}}{\!\textbf{:}}{\ENDVROUND}{} +\newconstruct{\DROUND}{\textbf{Decision Round}}{\!\textbf{:}}{\ENDDROUND}{} diff --git a/spec/consensus/consensus-paper/intro.tex b/spec/consensus/consensus-paper/intro.tex new file mode 100644 index 0000000..45d0d11 --- /dev/null +++ b/spec/consensus/consensus-paper/intro.tex @@ -0,0 +1,138 @@ +\section{Introduction} \label{sec:tendermint} + +Consensus is a fundamental problem in distributed computing. It +is important because of it's role in State Machine Replication (SMR), a generic +approach for replicating services that can be modeled as a deterministic state +machine~\cite{Lam78:cacm, Sch90:survey}. The key idea of this approach is that +service replicas start in the same initial state, and then execute requests +(also called transactions) in the same order; thereby guaranteeing that +replicas stay in sync with each other. The role of consensus in the SMR +approach is ensuring that all replicas receive transactions in the same order. +Traditionally, deployments of SMR based systems are in data-center settings +(local area network), have a small number of replicas (three to seven) and are +typically part of a single administration domain (e.g., Chubby +\cite{Bur:osdi06}); therefore they handle benign (crash) failures only, as more +general forms of failure (in particular, malicious or Byzantine faults) are +considered to occur with only negligible probability. + +The success of cryptocurrencies and blockchain systems in recent years (e.g., +\cite{Nak2012:bitcoin, But2014:ethereum}) pose a whole new set of challenges on +the design and deployment of SMR based systems: reaching agreement over wide +area network, among large number of nodes (hundreds or thousands) that are not +part of the same administrative domain, and where a subset of nodes can behave +maliciously (Byzantine faults). Furthermore, contrary to the previous +data-center deployments where nodes are fully connected to each other, in +blockchain systems, a node is only connected to a subset of other nodes, so +communication is achieved by gossip-based peer-to-peer protocols. +The new requirements demand designs and algorithms that are not necessarily +present in the classical academic literature on Byzantine fault tolerant +consensus (or SMR) systems (e.g., \cite{DLS88:jacm, CL02:tcs}) as the primary +focus was different setup. + +In this paper we describe a novel Byzantine-fault tolerant consensus algorithm +that is the core of the BFT SMR platform called Tendermint\footnote{The + Tendermint platform is available open source at + https://github.com/tendermint/tendermint.}. The Tendermint platform consists of +a high-performance BFT SMR implementation written in Go, a flexible interface +for +building arbitrary deterministic applications above the consensus, and a suite +of tools for deployment and management. + +The Tendermint consensus algorithm is inspired by the PBFT SMR +algorithm~\cite{CL99:osdi} and the DLS algorithm for authenticated faults (the +Algorithm 2 from \cite{DLS88:jacm}). Similar to DLS algorithm, Tendermint +proceeds in +rounds\footnote{Tendermint is not presented in the basic round model of + \cite{DLS88:jacm}. Furthermore, we use the term round differently than in + \cite{DLS88:jacm}; in Tendermint a round denotes a sequence of communication + steps instead of a single communication step in \cite{DLS88:jacm}.}, where each +round has a dedicated proposer (also called coordinator or +leader) and a process proceeds to a new round as part of normal +processing (not only in case the proposer is faulty or suspected as being faulty +by enough processes as in PBFT). +The communication pattern of each round is very similar to the "normal" case +of PBFT. Therefore, in preferable conditions (correct proposer, timely and +reliable communication between correct processes), Tendermint decides in three +communication steps (the same as PBFT). + +The major novelty and contribution of the Tendermint consensus algorithm is a +new termination mechanism. As explained in \cite{MHS09:opodis, RMS10:dsn}, the +existing BFT consensus (and SMR) algorithms for the partially synchronous +system model (for example PBFT~\cite{CL99:osdi}, \cite{DLS88:jacm}, +\cite{MA06:tdsc}) typically relies on the communication pattern illustrated in +Figure~\ref{ch3:fig:coordinator-change} for termination. The +Figure~\ref{ch3:fig:coordinator-change} illustrates messages exchanged during +the proposer change when processes start a new round\footnote{There is no + consistent terminology in the distributed computing terminology on naming + sequence of communication steps that corresponds to a logical unit. It is + sometimes called a round, phase or a view.}. It guarantees that eventually (ie. +after some Global Stabilization Time, GST), there exists a round with a correct +proposer that will bring the system into a univalent configuration. +Intuitively, in a round in which the proposed value is accepted +by all correct processes, and communication between correct processes is +timely and reliable, all correct processes decide. + + +\begin{figure}[tbh!] \def\rdstretch{5} \def\ystretch{3} \centering + \begin{rounddiag}{4}{2} \round{1}{~} \rdmessage{1}{1}{$v_1$} + \rdmessage{2}{1}{$v_2$} \rdmessage{3}{1}{$v_3$} \rdmessage{4}{1}{$v_4$} + \round{2}{~} \rdmessage{1}{1}{$x, [v_{1..4}]$} + \rdmessage{1}{2}{$~~~~~~x, [v_{1..4}]$} \rdmessage{1}{3}{$~~~~~~~~x, + [v_{1..4}]$} \rdmessage{1}{4}{$~~~~~~~x, [v_{1..4}]$} \end{rounddiag} + \vspace{-5mm} \caption{\boldmath Proposer (coordinator) change: $p_1$ is the + new proposer.} \label{ch3:fig:coordinator-change} \end{figure} + +To ensure that a proposed value is accepted by all correct +processes\footnote{The proposed value is not blindly accepted by correct + processes in BFT algorithms. A correct process always verifies if the proposed + value is safe to be accepted so that safety properties of consensus are not + violated.} +a proposer will 1) build the global state by receiving messages from other +processes, 2) select the safe value to propose and 3) send the selected value +together with the signed messages +received in the first step to support it. The +value $v_i$ that a correct process sends to the next proposer normally +corresponds to a value the process considers as acceptable for a decision: + +\begin{itemize} \item in PBFT~\cite{CL99:osdi} and DLS~\cite{DLS88:jacm} it is + not the value itself but a set of $2f+1$ signed messages with the same + value id, \item in Fast Byzantine Paxos~\cite{MA06:tdsc} the value + itself is being sent. \end{itemize} + +In both cases, using this mechanism in our system model (ie. high +number of nodes over gossip based network) would have high communication +complexity that increases with the number of processes: in the first case as +the message sent depends on the total number of processes, and in the second +case as the value (block of transactions) is sent by each process. The set of +messages received in the first step are normally piggybacked on the proposal +message (in the Figure~\ref{ch3:fig:coordinator-change} denoted with +$[v_{1..4}]$) to justify the choice of the selected value $x$. Note that +sending this message also does not scale with the number of processes in the +system. + +We designed a novel termination mechanism for Tendermint that better suits the +system model we consider. It does not require additional communication (neither +sending new messages nor piggybacking information on the existing messages) and +it is fully based on the communication pattern that is very similar to the +normal case in PBFT \cite{CL99:osdi}. Therefore, there is only a single mode of +execution in Tendermint, i.e., there is no separation between the normal and +the recovery mode, which is the case in other PBFT-like protocols (e.g., +\cite{CL99:osdi}, \cite{Ver09:spinning} or \cite{Cle09:aardvark}). We believe +this makes Tendermint simpler to understand and implement correctly. + +Note that the orthogonal approach for reducing message complexity in order to +improve +scalability and decentralization (number of processes) of BFT consensus +algorithms is using advanced cryptography (for example Boneh-Lynn-Shacham (BLS) +signatures \cite{BLS2001:crypto}) as done for example in SBFT +\cite{Gue2018:sbft}. + +The remainder of the paper is as follows: Section~\ref{sec:definitions} defines +the system model and gives the problem definitions. Tendermint +consensus algorithm is presented in Section~\ref{sec:tendermint} and the +proofs are given in Section~\ref{sec:proof}. We conclude in +Section~\ref{sec:conclusion}. + + + + diff --git a/spec/consensus/consensus-paper/latex8.bst b/spec/consensus/consensus-paper/latex8.bst new file mode 100644 index 0000000..3f39743 --- /dev/null +++ b/spec/consensus/consensus-paper/latex8.bst @@ -0,0 +1,1124 @@ + +% --------------------------------------------------------------- +% +% $Id: latex8.bst,v 1.1 1995/09/15 15:13:49 ienne Exp $ +% +% by Paolo.Ienne@di.epfl.ch +% + +% --------------------------------------------------------------- +% +% no guarantee is given that the format corresponds perfectly to +% IEEE 8.5" x 11" Proceedings, but most features should be ok. +% +% --------------------------------------------------------------- +% +% `latex8' from BibTeX standard bibliography style `abbrv' +% version 0.99a for BibTeX versions 0.99a or later, LaTeX version 2.09. +% Copyright (C) 1985, all rights reserved. +% Copying of this file is authorized only if either +% (1) you make absolutely no changes to your copy, including name, or +% (2) if you do make changes, you name it something other than +% btxbst.doc, plain.bst, unsrt.bst, alpha.bst, and abbrv.bst. +% This restriction helps ensure that all standard styles are identical. +% The file btxbst.doc has the documentation for this style. + +ENTRY + { address + author + booktitle + chapter + edition + editor + howpublished + institution + journal + key + month + note + number + organization + pages + publisher + school + series + title + type + volume + year + } + {} + { label } + +INTEGERS { output.state before.all mid.sentence after.sentence after.block } + +FUNCTION {init.state.consts} +{ #0 'before.all := + #1 'mid.sentence := + #2 'after.sentence := + #3 'after.block := +} + +STRINGS { s t } + +FUNCTION {output.nonnull} +{ 's := + output.state mid.sentence = + { ", " * write$ } + { output.state after.block = + { add.period$ write$ + newline$ + "\newblock " write$ + } + { output.state before.all = + 'write$ + { add.period$ " " * write$ } + if$ + } + if$ + mid.sentence 'output.state := + } + if$ + s +} + +FUNCTION {output} +{ duplicate$ empty$ + 'pop$ + 'output.nonnull + if$ +} + +FUNCTION {output.check} +{ 't := + duplicate$ empty$ + { pop$ "empty " t * " in " * cite$ * warning$ } + 'output.nonnull + if$ +} + +FUNCTION {output.bibitem} +{ newline$ + "\bibitem{" write$ + cite$ write$ + "}" write$ + newline$ + "" + before.all 'output.state := +} + +FUNCTION {fin.entry} +{ add.period$ + write$ + newline$ +} + +FUNCTION {new.block} +{ output.state before.all = + 'skip$ + { after.block 'output.state := } + if$ +} + +FUNCTION {new.sentence} +{ output.state after.block = + 'skip$ + { output.state before.all = + 'skip$ + { after.sentence 'output.state := } + if$ + } + if$ +} + +FUNCTION {not} +{ { #0 } + { #1 } + if$ +} + +FUNCTION {and} +{ 'skip$ + { pop$ #0 } + if$ +} + +FUNCTION {or} +{ { pop$ #1 } + 'skip$ + if$ +} + +FUNCTION {new.block.checka} +{ empty$ + 'skip$ + 'new.block + if$ +} + +FUNCTION {new.block.checkb} +{ empty$ + swap$ empty$ + and + 'skip$ + 'new.block + if$ +} + +FUNCTION {new.sentence.checka} +{ empty$ + 'skip$ + 'new.sentence + if$ +} + +FUNCTION {new.sentence.checkb} +{ empty$ + swap$ empty$ + and + 'skip$ + 'new.sentence + if$ +} + +FUNCTION {field.or.null} +{ duplicate$ empty$ + { pop$ "" } + 'skip$ + if$ +} + +FUNCTION {emphasize} +{ duplicate$ empty$ + { pop$ "" } + { "{\em " swap$ * "}" * } + if$ +} + +INTEGERS { nameptr namesleft numnames } + +FUNCTION {format.names} +{ 's := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr "{f.~}{vv~}{ll}{, jj}" format.name$ 't := + nameptr #1 > + { namesleft #1 > + { ", " * t * } + { numnames #2 > + { "," * } + 'skip$ + if$ + t "others" = + { " et~al." * } + { " and " * t * } + if$ + } + if$ + } + 't + if$ + nameptr #1 + 'nameptr := + + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {format.authors} +{ author empty$ + { "" } + { author format.names } + if$ +} + +FUNCTION {format.editors} +{ editor empty$ + { "" } + { editor format.names + editor num.names$ #1 > + { ", editors" * } + { ", editor" * } + if$ + } + if$ +} + +FUNCTION {format.title} +{ title empty$ + { "" } + { title "t" change.case$ } + if$ +} + +FUNCTION {n.dashify} +{ 't := + "" + { t empty$ not } + { t #1 #1 substring$ "-" = + { t #1 #2 substring$ "--" = not + { "--" * + t #2 global.max$ substring$ 't := + } + { { t #1 #1 substring$ "-" = } + { "-" * + t #2 global.max$ substring$ 't := + } + while$ + } + if$ + } + { t #1 #1 substring$ * + t #2 global.max$ substring$ 't := + } + if$ + } + while$ +} + +FUNCTION {format.date} +{ year empty$ + { month empty$ + { "" } + { "there's a month but no year in " cite$ * warning$ + month + } + if$ + } + { month empty$ + 'year + { month " " * year * } + if$ + } + if$ +} + +FUNCTION {format.btitle} +{ title emphasize +} + +FUNCTION {tie.or.space.connect} +{ duplicate$ text.length$ #3 < + { "~" } + { " " } + if$ + swap$ * * +} + +FUNCTION {either.or.check} +{ empty$ + 'pop$ + { "can't use both " swap$ * " fields in " * cite$ * warning$ } + if$ +} + +FUNCTION {format.bvolume} +{ volume empty$ + { "" } + { "volume" volume tie.or.space.connect + series empty$ + 'skip$ + { " of " * series emphasize * } + if$ + "volume and number" number either.or.check + } + if$ +} + +FUNCTION {format.number.series} +{ volume empty$ + { number empty$ + { series field.or.null } + { output.state mid.sentence = + { "number" } + { "Number" } + if$ + number tie.or.space.connect + series empty$ + { "there's a number but no series in " cite$ * warning$ } + { " in " * series * } + if$ + } + if$ + } + { "" } + if$ +} + +FUNCTION {format.edition} +{ edition empty$ + { "" } + { output.state mid.sentence = + { edition "l" change.case$ " edition" * } + { edition "t" change.case$ " edition" * } + if$ + } + if$ +} + +INTEGERS { multiresult } + +FUNCTION {multi.page.check} +{ 't := + #0 'multiresult := + { multiresult not + t empty$ not + and + } + { t #1 #1 substring$ + duplicate$ "-" = + swap$ duplicate$ "," = + swap$ "+" = + or or + { #1 'multiresult := } + { t #2 global.max$ substring$ 't := } + if$ + } + while$ + multiresult +} + +FUNCTION {format.pages} +{ pages empty$ + { "" } + { pages multi.page.check + { "pages" pages n.dashify tie.or.space.connect } + { "page" pages tie.or.space.connect } + if$ + } + if$ +} + +FUNCTION {format.vol.num.pages} +{ volume field.or.null + number empty$ + 'skip$ + { "(" number * ")" * * + volume empty$ + { "there's a number but no volume in " cite$ * warning$ } + 'skip$ + if$ + } + if$ + pages empty$ + 'skip$ + { duplicate$ empty$ + { pop$ format.pages } + { ":" * pages n.dashify * } + if$ + } + if$ +} + +FUNCTION {format.chapter.pages} +{ chapter empty$ + 'format.pages + { type empty$ + { "chapter" } + { type "l" change.case$ } + if$ + chapter tie.or.space.connect + pages empty$ + 'skip$ + { ", " * format.pages * } + if$ + } + if$ +} + +FUNCTION {format.in.ed.booktitle} +{ booktitle empty$ + { "" } + { editor empty$ + { "In " booktitle emphasize * } + { "In " format.editors * ", " * booktitle emphasize * } + if$ + } + if$ +} + +FUNCTION {empty.misc.check} + +{ author empty$ title empty$ howpublished empty$ + month empty$ year empty$ note empty$ + and and and and and + key empty$ not and + { "all relevant fields are empty in " cite$ * warning$ } + 'skip$ + if$ +} + +FUNCTION {format.thesis.type} +{ type empty$ + 'skip$ + { pop$ + type "t" change.case$ + } + if$ +} + +FUNCTION {format.tr.number} +{ type empty$ + { "Technical Report" } + 'type + if$ + number empty$ + { "t" change.case$ } + { number tie.or.space.connect } + if$ +} + +FUNCTION {format.article.crossref} +{ key empty$ + { journal empty$ + { "need key or journal for " cite$ * " to crossref " * crossref * + warning$ + "" + } + { "In {\em " journal * "\/}" * } + if$ + } + { "In " key * } + if$ + " \cite{" * crossref * "}" * +} + +FUNCTION {format.crossref.editor} +{ editor #1 "{vv~}{ll}" format.name$ + editor num.names$ duplicate$ + #2 > + { pop$ " et~al." * } + { #2 < + 'skip$ + { editor #2 "{ff }{vv }{ll}{ jj}" format.name$ "others" = + { " et~al." * } + { " and " * editor #2 "{vv~}{ll}" format.name$ * } + if$ + } + if$ + } + if$ +} + +FUNCTION {format.book.crossref} +{ volume empty$ + { "empty volume in " cite$ * "'s crossref of " * crossref * warning$ + "In " + } + { "Volume" volume tie.or.space.connect + " of " * + } + if$ + editor empty$ + editor field.or.null author field.or.null = + or + { key empty$ + { series empty$ + { "need editor, key, or series for " cite$ * " to crossref " * + crossref * warning$ + "" * + } + { "{\em " * series * "\/}" * } + if$ + } + { key * } + if$ + } + { format.crossref.editor * } + if$ + " \cite{" * crossref * "}" * +} + +FUNCTION {format.incoll.inproc.crossref} +{ editor empty$ + editor field.or.null author field.or.null = + or + { key empty$ + { booktitle empty$ + { "need editor, key, or booktitle for " cite$ * " to crossref " * + crossref * warning$ + "" + } + { "In {\em " booktitle * "\/}" * } + if$ + } + { "In " key * } + if$ + } + { "In " format.crossref.editor * } + if$ + " \cite{" * crossref * "}" * +} + +FUNCTION {article} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + crossref missing$ + { journal emphasize "journal" output.check + format.vol.num.pages output + format.date "year" output.check + } + { format.article.crossref output.nonnull + format.pages output + } + if$ + new.block + note output + fin.entry +} + +FUNCTION {book} +{ output.bibitem + author empty$ + { format.editors "author and editor" output.check } + { format.authors output.nonnull + crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + new.block + format.btitle "title" output.check + crossref missing$ + { format.bvolume output + new.block + format.number.series output + new.sentence + publisher "publisher" output.check + address output + } + { new.block + format.book.crossref output.nonnull + } + if$ + format.edition output + format.date "year" output.check + new.block + note output + fin.entry +} + +FUNCTION {booklet} +{ output.bibitem + format.authors output + new.block + format.title "title" output.check + howpublished address new.block.checkb + howpublished output + address output + format.date output + new.block + note output + fin.entry +} + +FUNCTION {inbook} +{ output.bibitem + author empty$ + { format.editors "author and editor" output.check } + { format.authors output.nonnull + + crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + new.block + format.btitle "title" output.check + crossref missing$ + { format.bvolume output + format.chapter.pages "chapter and pages" output.check + new.block + format.number.series output + new.sentence + publisher "publisher" output.check + address output + } + { format.chapter.pages "chapter and pages" output.check + new.block + format.book.crossref output.nonnull + } + if$ + format.edition output + format.date "year" output.check + new.block + note output + fin.entry +} + +FUNCTION {incollection} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + format.bvolume output + format.number.series output + format.chapter.pages output + new.sentence + publisher "publisher" output.check + address output + format.edition output + format.date "year" output.check + } + { format.incoll.inproc.crossref output.nonnull + format.chapter.pages output + } + if$ + new.block + note output + fin.entry +} + +FUNCTION {inproceedings} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + format.bvolume output + format.number.series output + format.pages output + address empty$ + { organization publisher new.sentence.checkb + organization output + publisher output + format.date "year" output.check + } + { address output.nonnull + format.date "year" output.check + new.sentence + organization output + publisher output + } + if$ + } + { format.incoll.inproc.crossref output.nonnull + format.pages output + } + if$ + new.block + note output + fin.entry +} + +FUNCTION {conference} { inproceedings } + +FUNCTION {manual} +{ output.bibitem + author empty$ + { organization empty$ + 'skip$ + { organization output.nonnull + address output + } + if$ + } + { format.authors output.nonnull } + if$ + new.block + format.btitle "title" output.check + author empty$ + { organization empty$ + { address new.block.checka + address output + } + 'skip$ + if$ + } + { organization address new.block.checkb + organization output + address output + } + if$ + format.edition output + format.date output + new.block + note output + fin.entry +} + +FUNCTION {mastersthesis} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + "Master's thesis" format.thesis.type output.nonnull + school "school" output.check + address output + format.date "year" output.check + new.block + note output + fin.entry +} + +FUNCTION {misc} +{ output.bibitem + format.authors output + title howpublished new.block.checkb + format.title output + howpublished new.block.checka + howpublished output + format.date output + new.block + note output + fin.entry + empty.misc.check +} + +FUNCTION {phdthesis} +{ output.bibitem + format.authors "author" output.check + new.block + format.btitle "title" output.check + new.block + "PhD thesis" format.thesis.type output.nonnull + school "school" output.check + address output + format.date "year" output.check + new.block + note output + fin.entry +} + +FUNCTION {proceedings} +{ output.bibitem + editor empty$ + { organization output } + { format.editors output.nonnull } + + if$ + new.block + format.btitle "title" output.check + format.bvolume output + format.number.series output + address empty$ + { editor empty$ + { publisher new.sentence.checka } + { organization publisher new.sentence.checkb + organization output + } + if$ + publisher output + format.date "year" output.check + } + { address output.nonnull + format.date "year" output.check + new.sentence + editor empty$ + 'skip$ + { organization output } + if$ + publisher output + } + if$ + new.block + note output + fin.entry +} + +FUNCTION {techreport} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + format.tr.number output.nonnull + institution "institution" output.check + address output + format.date "year" output.check + new.block + note output + fin.entry +} + +FUNCTION {unpublished} +{ output.bibitem + format.authors "author" output.check + new.block + format.title "title" output.check + new.block + note "note" output.check + format.date output + fin.entry +} + +FUNCTION {default.type} { misc } + +MACRO {jan} {"Jan."} + +MACRO {feb} {"Feb."} + +MACRO {mar} {"Mar."} + +MACRO {apr} {"Apr."} + +MACRO {may} {"May"} + +MACRO {jun} {"June"} + +MACRO {jul} {"July"} + +MACRO {aug} {"Aug."} + +MACRO {sep} {"Sept."} + +MACRO {oct} {"Oct."} + +MACRO {nov} {"Nov."} + +MACRO {dec} {"Dec."} + +MACRO {acmcs} {"ACM Comput. Surv."} + +MACRO {acta} {"Acta Inf."} + +MACRO {cacm} {"Commun. ACM"} + +MACRO {ibmjrd} {"IBM J. Res. Dev."} + +MACRO {ibmsj} {"IBM Syst.~J."} + +MACRO {ieeese} {"IEEE Trans. Softw. Eng."} + +MACRO {ieeetc} {"IEEE Trans. Comput."} + +MACRO {ieeetcad} + {"IEEE Trans. Comput.-Aided Design Integrated Circuits"} + +MACRO {ipl} {"Inf. Process. Lett."} + +MACRO {jacm} {"J.~ACM"} + +MACRO {jcss} {"J.~Comput. Syst. Sci."} + +MACRO {scp} {"Sci. Comput. Programming"} + +MACRO {sicomp} {"SIAM J. Comput."} + +MACRO {tocs} {"ACM Trans. Comput. Syst."} + +MACRO {tods} {"ACM Trans. Database Syst."} + +MACRO {tog} {"ACM Trans. Gr."} + +MACRO {toms} {"ACM Trans. Math. Softw."} + +MACRO {toois} {"ACM Trans. Office Inf. Syst."} + +MACRO {toplas} {"ACM Trans. Prog. Lang. Syst."} + +MACRO {tcs} {"Theoretical Comput. Sci."} + +READ + +FUNCTION {sortify} +{ purify$ + "l" change.case$ +} + +INTEGERS { len } + +FUNCTION {chop.word} +{ 's := + 'len := + s #1 len substring$ = + { s len #1 + global.max$ substring$ } + 's + if$ +} + +FUNCTION {sort.format.names} +{ 's := + #1 'nameptr := + "" + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { nameptr #1 > + { " " * } + 'skip$ + if$ + s nameptr "{vv{ } }{ll{ }}{ f{ }}{ jj{ }}" format.name$ 't := + nameptr numnames = t "others" = and + { "et al" * } + { t sortify * } + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {sort.format.title} +{ 't := + "A " #2 + "An " #3 + "The " #4 t chop.word + chop.word + chop.word + sortify + #1 global.max$ substring$ +} + +FUNCTION {author.sort} +{ author empty$ + { key empty$ + { "to sort, need author or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { author sort.format.names } + if$ +} + +FUNCTION {author.editor.sort} +{ author empty$ + { editor empty$ + { key empty$ + { "to sort, need author, editor, or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { editor sort.format.names } + if$ + } + { author sort.format.names } + if$ +} + +FUNCTION {author.organization.sort} +{ author empty$ + + { organization empty$ + { key empty$ + { "to sort, need author, organization, or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { "The " #4 organization chop.word sortify } + if$ + } + { author sort.format.names } + if$ +} + +FUNCTION {editor.organization.sort} +{ editor empty$ + { organization empty$ + { key empty$ + { "to sort, need editor, organization, or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { "The " #4 organization chop.word sortify } + if$ + } + { editor sort.format.names } + if$ +} + +FUNCTION {presort} +{ type$ "book" = + type$ "inbook" = + or + 'author.editor.sort + { type$ "proceedings" = + 'editor.organization.sort + { type$ "manual" = + 'author.organization.sort + 'author.sort + if$ + } + if$ + } + if$ + " " + * + year field.or.null sortify + * + " " + * + title field.or.null + sort.format.title + * + #1 entry.max$ substring$ + 'sort.key$ := +} + +ITERATE {presort} + +SORT + +STRINGS { longest.label } + +INTEGERS { number.label longest.label.width } + +FUNCTION {initialize.longest.label} +{ "" 'longest.label := + #1 'number.label := + #0 'longest.label.width := +} + +FUNCTION {longest.label.pass} +{ number.label int.to.str$ 'label := + number.label #1 + 'number.label := + label width$ longest.label.width > + { label 'longest.label := + label width$ 'longest.label.width := + } + 'skip$ + if$ +} + +EXECUTE {initialize.longest.label} + +ITERATE {longest.label.pass} + +FUNCTION {begin.bib} +{ preamble$ empty$ + 'skip$ + { preamble$ write$ newline$ } + if$ + "\begin{thebibliography}{" longest.label * + "}\setlength{\itemsep}{-1ex}\small" * write$ newline$ +} + +EXECUTE {begin.bib} + +EXECUTE {init.state.consts} + +ITERATE {call.type$} + +FUNCTION {end.bib} +{ newline$ + "\end{thebibliography}" write$ newline$ +} + +EXECUTE {end.bib} + +% end of file latex8.bst +% --------------------------------------------------------------- + + + diff --git a/spec/consensus/consensus-paper/latex8.sty b/spec/consensus/consensus-paper/latex8.sty new file mode 100644 index 0000000..a4ac5e3 --- /dev/null +++ b/spec/consensus/consensus-paper/latex8.sty @@ -0,0 +1,168 @@ +% --------------------------------------------------------------- +% +% $Id: latex8.sty,v 1.2 1995/09/15 15:31:13 ienne Exp $ +% +% by Paolo.Ienne@di.epfl.ch +% +% --------------------------------------------------------------- +% +% no guarantee is given that the format corresponds perfectly to +% IEEE 8.5" x 11" Proceedings, but most features should be ok. +% +% --------------------------------------------------------------- +% with LaTeX2e: +% ============= +% +% use as +% \documentclass[times,10pt,twocolumn]{article} +% \usepackage{latex8} +% \usepackage{times} +% +% --------------------------------------------------------------- + +% with LaTeX 2.09: +% ================ +% +% use as +% \documentstyle[times,art10,twocolumn,latex8]{article} +% +% --------------------------------------------------------------- +% with both versions: +% =================== +% +% specify \pagestyle{empty} to omit page numbers in the final +% version +% +% specify references as +% \bibliographystyle{latex8} +% \bibliography{...your files...} +% +% use Section{} and SubSection{} instead of standard section{} +% and subsection{} to obtain headings in the form +% "1.3. My heading" +% +% --------------------------------------------------------------- + +\typeout{IEEE 8.5 x 11-Inch Proceedings Style `latex8.sty'.} + +% ten point helvetica bold required for captions +% in some sites the name of the helvetica bold font may differ, +% change the name here: +\font\tenhv = phvb at 10pt +%\font\tenhv = phvb7t at 10pt + +% eleven point times bold required for second-order headings +% \font\elvbf = cmbx10 scaled 1100 +\font\elvbf = ptmb scaled 1100 + +% set dimensions of columns, gap between columns, and paragraph indent +\setlength{\textheight}{8.875in} +\setlength{\textwidth}{6.875in} +\setlength{\columnsep}{0.3125in} +\setlength{\topmargin}{0in} +\setlength{\headheight}{0in} +\setlength{\headsep}{0in} +\setlength{\parindent}{1pc} +\setlength{\oddsidemargin}{-.304in} +\setlength{\evensidemargin}{-.304in} + +% memento from size10.clo +% \normalsize{\@setfontsize\normalsize\@xpt\@xiipt} +% \small{\@setfontsize\small\@ixpt{11}} +% \footnotesize{\@setfontsize\footnotesize\@viiipt{9.5}} +% \scriptsize{\@setfontsize\scriptsize\@viipt\@viiipt} +% \tiny{\@setfontsize\tiny\@vpt\@vipt} +% \large{\@setfontsize\large\@xiipt{14}} +% \Large{\@setfontsize\Large\@xivpt{18}} +% \LARGE{\@setfontsize\LARGE\@xviipt{22}} +% \huge{\@setfontsize\huge\@xxpt{25}} +% \Huge{\@setfontsize\Huge\@xxvpt{30}} + +\def\@maketitle + { + \newpage + \null + \vskip .375in + \begin{center} + {\Large \bf \@title \par} + % additional two empty lines at the end of the title + \vspace*{24pt} + { + \large + \lineskip .5em + \begin{tabular}[t]{c} + \@author + \end{tabular} + \par + } + % additional small space at the end of the author name + \vskip .5em + { + \large + \begin{tabular}[t]{c} + \@affiliation + \end{tabular} + \par + \ifx \@empty \@email + \else + \begin{tabular}{r@{~}l} + E-mail: & {\tt \@email} + \end{tabular} + \par + \fi + } + % additional empty line at the end of the title block + \vspace*{12pt} + \end{center} + } + +\def\abstract + {% + \centerline{\large\bf Abstract}% + \vspace*{12pt}% + \it% + } + +\def\endabstract + { + % additional empty line at the end of the abstract + \vspace*{12pt} + } + +\def\affiliation#1{\gdef\@affiliation{#1}} \gdef\@affiliation{} + +\def\email#1{\gdef\@email{#1}} +\gdef\@email{} + +\newlength{\@ctmp} +\newlength{\@figindent} +\setlength{\@figindent}{1pc} + +\long\def\@makecaption#1#2{ + \vskip 10pt + \setbox\@tempboxa\hbox{\tenhv\noindent #1.~#2} + \setlength{\@ctmp}{\hsize} + \addtolength{\@ctmp}{-\@figindent}\addtolength{\@ctmp}{-\@figindent} + % IF longer than one indented paragraph line + \ifdim \wd\@tempboxa >\@ctmp + % THEN set as an indented paragraph + \begin{list}{}{\leftmargin\@figindent \rightmargin\leftmargin} + \item[]\tenhv #1.~#2\par + \end{list} + \else + % ELSE center + \hbox to\hsize{\hfil\box\@tempboxa\hfil} + \fi} + +% correct heading spacing and type +\def\section{\@startsection {section}{1}{\z@} + {14pt plus 2pt minus 2pt}{14pt plus 2pt minus 2pt} {\large\bf}} +\def\subsection{\@startsection {subsection}{2}{\z@} + {13pt plus 2pt minus 2pt}{13pt plus 2pt minus 2pt} {\elvbf}} + +% add the period after section numbers +\newcommand{\Section}[1]{\section{\hskip -1em.~#1}} +\newcommand{\SubSection}[1]{\subsection{\hskip -1em.~#1}} + +% end of file latex8.sty +% --------------------------------------------------------------- diff --git a/spec/consensus/consensus-paper/lit.bib b/spec/consensus/consensus-paper/lit.bib new file mode 100644 index 0000000..0d0f977 --- /dev/null +++ b/spec/consensus/consensus-paper/lit.bib @@ -0,0 +1,1659 @@ +%--- conferences -------------------------------------------------- +@STRING{WDAG96 = "Proceedings of the 10th International Workshop + on Distributed Algorithms (WDAG'96)"} +@STRING{WDAG97 = "Proceedings of the 11th International Workshop + on Distributed Algorithms (WDAG'97)"} +@STRING{DISC98 = "Proceedings of the 12th International Conference + on Distributed Computing ({DISC}'98)"} +@STRING{DISC99 = "Proceedings of the 13th International Conference + on Distributed Computing ({DISC}'99)"} +@STRING{DISC98 = "Proceedings of the 13th International Conference + on Distributed Computing ({DISC}'98)"} +@STRING{DISC99 = "Proceedings of the 13th International Conference + on Distributed Computing ({DISC}'99)"} +@STRING{DISC00 = "Proceedings of the 14th International Conference + on Distributed Computing ({DISC}'00)"} +@STRING{DISC01 = "Proceedings of the 15th International Conference + on Distributed Computing ({DISC}'01)"} +@STRING{DISC02 = "Proceedings of the 16th International Conference + on Distributed Computing ({DISC}'02)"} +@STRING{DISC03 = "Proceedings of the 17th International Conference + on Distributed Computing ({DISC}'03)"} +@STRING{DISC04 = "Proceedings of the 18th International Conference + on Distributed Computing ({DISC}'04)"} +@STRING{DISC05 = "Proceedings of the 19th International Conference + on Distributed Computing ({DISC}'05)"} +@STRING{PODC83 = "Proceeding of the 1st Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'83)"} +@STRING{PODC91 = "Proceeding of the 9th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'91)"} +@STRING{PODC94 = "Proceeding of the 12th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'94)"} +@STRING{PODC95 = "Proceeding of the 13th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'95)"} +@STRING{PODC96 = "Proceeding of the 14th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'96)"} +@STRING{PODC97 = "Proceeding of the 15th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'97)"} +@STRING{PODC98 = "Proceeding of the 16th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'98)"} +@STRING{PODC99 = "Proceeding of the 17th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'99)"} +@STRING{PODC00 = "Proceeding of the 18th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'00)"} +@STRING{PODC01 = "Proceeding of the 19th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'01)"} +@STRING{PODC02 = "Proceeding of the 20th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'02)"} +@STRING{PODC03 = "Proceeding of the 21st Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'03)"} +@STRING{PODC03 = "Proceeding of the 22nd Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'03)"} +@STRING{PODC04 = "Proceeding of the 23rd Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'04)"} +@STRING{PODC05 = "Proceeding of the 24th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'05)"} +@STRING{PODC06 = "Proceedings of the 25th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'06)"} +@STRING{PODC07 = "Proceedings of the 26th Annual {ACM} Symposium on + Principles of Distributed Computing ({PODC}'07)"} +@STRING{STOC91 = "Proceedings of the 23rd Annual {ACM} Symposium on + Theory of Computing ({STOC}'91)"} +@STRING{WSS01 = "Proceedings of the 5th International Workshop on + Self-Stabilizing Systems ({WSS} '01)"} +@STRING{SSS06 = "Proceedings of the 8th International Symposium on + Stabilization, Safety, and Security of Distributed + Systems ({SSS} '06)"} +@STRING{DSN00 = "Dependable Systems and Networks ({DSN} 2000)"} +@STRING{DSN05 = "Dependable Systems and Networks ({DSN} 2005)"} +@STRING{DSN06 = "Dependable Systems and Networks ({DSN} 2006)"} +@STRING{DSN07 = "Dependable Systems and Networks ({DSN} 2007)"} + +%--- journals ----------------------------------------------------- +@STRING{PPL = "Parallel Processing Letters"} +@STRING{IPL = "Information Processing Letters"} +@STRING{DC = "Distributed Computing"} +@STRING{JACM = "Journal of the ACM"} +@STRING{IC = "Information and Control"} +@STRING{TCS = "Theoretical Computer Science"} +@STRING{ACMTCS = "ACM Transactions on Computer Systems"} +@STRING{TDSC = "Transactions on Dependable and Secure Computing"} +@STRING{TPLS = "ACM Trans. Program. Lang. Syst."} + +%--- publisher ---------------------------------------------------- +@STRING{ACM = "ACM Press"} +@STRING{IEEE = "IEEE"} +@STRING{SPR = "Springer-Verlag"} + +%--- institution -------------------------------------------------- +@STRING{TUAuto = {Technische Universit\"at Wien, Department of + Automation}} +@STRING{TUECS = {Technische Universit\"at Wien, Embedded Computing + Systems Group}} + + +%------------------------------------------------------------------ +@article{ABND+90:jacm, + author = {Hagit Attiya and Amotz Bar-Noy and Danny Dolev and + David Peleg and R{\"u}diger Reischuk}, + title = {Renaming in an asynchronous environment}, + journal = JACM, + volume = {37}, + number = {3}, + year = {1990}, + pages = {524--548}, + publisher = ACM, + address = {New York, NY, USA}, +} + +@article{ABND95:jacm, + author = {Hagit Attiya and Amotz Bar-Noy and Danny Dolev}, + title = {Sharing memory robustly in message-passing systems}, + journal = JACM, + volume = {42}, + number = {1}, + year = {1995}, + pages = {124--142}, + publisher = ACM, + address = {New York, NY, USA}, +} + +@inproceedings{ACKM04:podc, + author = {Ittai Abraham and Gregory Chockler and Idit Keidar + and Dahlia Malkhi}, + title = {Byzantine disk paxos: optimal resilience with + byzantine shared memory.}, + booktitle = PODC04, + year = {2004}, + pages = {226-235} +} + +@article{ACKM05:dc, + author = {Ittai Abraham and Gregory Chockler and Idit Keidar + and Dahlia Malkhi}, + title = {Byzantine disk paxos: optimal resilience with + byzantine shared memory.}, + journal = DC, + volume = {18}, + number = {5}, + year = {2006}, + pages = {387-408} +} + +@article{ACT00:dc, + author = "Marcos Kawazoe Aguilera and Wei Chen and Sam Toueg", + title = "Failure Detection and Consensus in the + Crash-Recovery Model", + journal = DC, + year = 2000, + month = apr, + volume = 13, + number = 2, + pages = "99--125", + url = + "http://www.cs.cornell.edu/home/sam/FDpapers/crash-recovery-finaldcversion.ps" +} + +@article{ACT00:siam, + author = "Marcos Kawazoe Aguilera and Wei Chen and Sam Toueg", + title = "On quiescent reliable communication", + journal = "SIAM Journal of Computing", + year = 2000, + volume = 29, + number = 6, + pages = "2040--2073", + month = apr +} + +@inproceedings{ACT97:wdag, + author = "Marcos Kawazoe Aguilera and Wei Chen and Sam Toueg", + title = "Heartbeat: A Timeout-Free Failure Detector for + Quiescent Reliable Communication", + booktitle = WDAG97, + year = 1997, + pages = "126--140", + url = + "http://simon.cs.cornell.edu/Info/People/weichen/research/mypapers/wdag97final.ps" +} + +@article{ACT98:disc, + author = "Marcos Kawazoe Aguilera and Wei Chen and Sam Toueg", + title = "Failure Detection and Consensus in the + Crash-Recovery Model", + journal = DISC98, + year = 1998, + pages = "231--245", + publisher = SPR +} + +@article{ACT99:tcs, + author = "Marcos Kawazoe Aguilera and Wei Chen and Sam Toueg", + title = "Using the Heartbeat Failure Detector for Quiescent + Reliable Communication and Consensus in + Partitionable Networks", + journal = "Theoretical Computer Science", + year = 1999, + month = jun, + volume = 220, + number = 1, + pages = "3--30", + url = + "http://www.cs.cornell.edu/home/sam/FDpapers/TCS98final.ps" +} + +@inproceedings{ADGF+04:ispdc, + author = {Anceaume, Emmanuelle and Delporte-Gallet, Carole and + Fauconnier, Hugues and Hurfin, Michel and Le Lann, + G{\'e}rard }, + title = {Designing Modular Services in the Scattered + Byzantine Failure Model.}, + booktitle = {ISPDC/HeteroPar}, + year = {2004}, + pages = {262-269} +} + +@inproceedings{ADGF+06:dsn, + author = {Marcos Kawazoe Aguilera and Carole Delporte-Gallet + and Hugues Fauconnier and Sam Toueg}, + title = {Consensus with Byzantine Failures and Little System + Synchrony.}, + booktitle = DSN06, + year = {2006}, + pages = {147-155} +} + +@inproceedings{ADGFT01:disc, + author = "Marcos Kawazoe Aguilera and Carole Delporte-Gallet + and Hugues Fauconnier and Sam Toueg", + title = "Stable Leader Election", + booktitle = DISC01, + year = 2001, + pages = "108--122", + publisher = SPR +} + +@inproceedings{ADGFT03:podc, + author = "Marcos K. Aguilera and Carole Delporte-Gallet and + Hugues Fauconnier and Sam Toueg", + title = "On implementing {O}mega with weak reliability and + synchrony assumptions", + booktitle = PODC03, + year = 2003, + publisher = ACM +} + +@inproceedings{ADGFT04:podc, + author = {Marcos K. Aguilera and Carole Delporte-Gallet and + Hugues Fauconnier and Sam Toueg}, + title = {Communication-efficient leader election and + consensus with limited link synchrony}, + booktitle = PODC04, + year = 2004, + pages = {328--337}, + address = {St. John's, Newfoundland, Canada}, + publisher = ACM +} + +@inproceedings{ADGFT06:dsn, + author = {Marcos Kawazoe Aguilera and Carole Delporte-Gallet + and Hugues Fauconnier and Sam Toueg}, + title = {Consensus with Byzantine Failures and Little System + Synchrony.}, + booktitle = DSN06, + year = 2006, + pages = {147-155}, + ee = + {http://doi.ieeecomputersociety.org/10.1109/DSN.2006.22}, + bibsource = {DBLP, http://dblp.uni-trier.de} +} + +@inproceedings{ADLS91:stoc, + author = "Hagit Attiya and Cynthia Dwork and Nancy A. Lynch + and Larry J. Stockmeyer", + title = "Bounds on the Time to Reach Agreement in the + Presence of Timing Uncertainty", + booktitle = STOC91, + year = 1991, + pages = "359--369", +} + +@article{AT99:ipl, + author = "Marcos Kawazoe Aguilera and Sam Toueg", + title = "A Simple Bivalency Proof that t -Resilient Consensus + Requires t + 1 Rounds", + journal = IPL, + volume = "71", + number = "3-4", + pages = "155--158", + year = "1999" +} + +@Book{AW04:book, + author = {Attiya, Hagit and Welch, Jennifer}, + title = {Distributed Computing}, + publisher = {John Wiley {\&} Sons}, + edition = {2nd}, + year = {2004} +} + +@Book{AW98:book, + author = {Hagit Attiya and Jennifer Welch}, + title = {Distributed Computing}, + publisher = {McGraw-Hill Publishing Company}, + year = {1998} +} + +@InBook{AW98:book:chap12, + author = {Hagit Attiya and Jennifer Welch}, + title = {Distributed Computing}, + publisher = {McGraw-Hill Publishing Company}, + year = {1998}, + chapter = {12, "Improving the fault-tolerance of algorithms"} +} + +@inproceedings{ABHMS11:disc, + author = {Hagit Attiya and + Fatemeh Borran and + Martin Hutle and + Zarko Milosevic and + Andr{\'e} Schiper}, + title = {Structured Derivation of Semi-Synchronous Algorithms}, + booktitle = {DISC}, + year = {2011}, + pages = {374-388} +} + +@inproceedings{BCBG+07:podc, + author = {Martin Biely and Bernadette Charron-Bost and Antoine + Gaillard and Martin Hutle and Andr{\'e} Schiper and + Josef Widder}, + title = {Tolerating Corrupted Communication}, + publisher = ACM, + booktitle = PODC07, + year = {2007} +} + +@InProceedings{BCBT96:wdag, + author = {Anindya Basu and Bernadette Charron-Bost and Sam + Toueg}, + title = {Simulating Reliable Links with Unreliable Links in + the Presence of Process Crashes}, + pages = {105--122}, + booktitle = {WDAG 1996}, + editor = {Babao{\u g}lu, {\"O}zalp}, + year = {1996}, + month = {Oct}, + volume = {1151}, + ISBN = {3-540-61769-8}, + pubisher = {Springer}, + series = {Lecture Notes in Computer Science}, +} + +@article{BDFG03:sigact, + author = "R. Boichat and P. Dutta and S. Frolund and + R. Guerraoui", + title = "Reconstructing {P}axos", + journal = "ACM SIGACT News", + year = "2003", + volume = "34", + number = "1", + pages = "47-67" +} + +@unpublished{BHR+06:note, + author = "Martin Biely and Martin Hutle and Sergio Rajsbaum + and Ulrich Schmid and Corentin Travers and Josef + Widder", + title = "Discussion note on moving timely links", + note = "Unpublished", + month = apr, + year = 2006 +} + +@article{BHRT03:jda, + author = {Roberto Baldoni and Jean-Michel H{\'e}lary and + Michel Raynal and L{\'e}naick Tanguy}, + title = {Consensus in Byzantine asynchronous systems.}, + journal = {J. Discrete Algorithms}, + volume = {1}, + number = {2}, + year = {2003}, + pages = {185-210}, + ee = {http://dx.doi.org/10.1016/S1570-8667(03)00025-X}, + bibsource = {DBLP, http://dblp.uni-trier.de} +} + +@unpublished{BHSS08:tdsc, + author = {Fatemeh Borran and Martin Hutle and Nuno Santos and + Andr{\'e} Schiper}, + title = {Solving Consensus with Communication Predicates: + A~Quantitative Approach}, + note = {Under submission}, + year = {2008} +} + +@inproceedings{Ben83:podc, + author = {Michael Ben-Or}, + title = {Another Advantage of Free Choice: Completely + Asynchronous Agreement Protocols}, + booktitle = {PODC}, + year = {1983}, +} + +@inproceedings{Bra04:podc, + author = {Bracha, Gabriel}, + title = {An asynchronous [(n - 1)/3]-resilient consensus protocol}, + booktitle = {PODC '84: Proceedings of the third annual ACM symposium on Principles of distributed computing}, + year = {1984}, + isbn = {0-89791-143-1}, + pages = {154--162}, + location = {Vancouver, British Columbia, Canada}, + doi = {http://doi.acm.org/10.1145/800222.806743}, + publisher = {ACM}, + address = {New York, NY, USA}, + } + + +@inproceedings{CBGS00:dsn, + author = "Bernadette Charron-Bost and Rachid Guerraoui and + Andr{\'{e}} Schiper", + title = "Synchronous System and Perfect Failure Detector: + {S}olvability and efficiency issues", + booktitle = DSN00, + publisher = "{IEEE} Computer Society", + address = "New York, {USA}", + pages = "523--532", + year = "2000" +} + +@inproceedings{CBS06:prdc, + author = {Bernadette Charron-Bost and Andr{\'e} Schiper}, + title = {Improving Fast Paxos: being optimistic with no + overhead}, + booktitle = {Pacific Rim Dependable Computing, Proceedings}, + year = {2006} +} + +@article{CBS09, + author = {B. Charron-Bost and A. Schiper}, + title = {The {H}eard-{O}f model: computing in distributed systems with benign failures}, + journal ={Distributed Computing}, + number = {1}, + volume = {22}, + pages = {49-71}, + year ={2009} + } + + +@article{CBS07:sigact, + author = {Bernadette Charron-Bost and Andr\'{e} Schiper}, + title = {Harmful dogmas in fault tolerant distributed + computing}, + journal = {SIGACT News}, + volume = {38}, + number = {1}, + year = {2007}, + pages = {53--61}, +} + +@techreport{CBS07:tr, + author = {Charron-Bost, Bernadette and Schiper, Andr{\'{e}}}, + title = {The Heard-Of Model: Unifying all Benign Failures}, + institution = {EPFL}, + year = 2007, + OPTnumber = {LSR-REPORT-2006-004} +} + +@article{CELT00:jacm, + author = {Soma Chaudhuri and Maurice Erlihy and Nancy A. Lynch + and Mark R. Tuttle}, + title = {Tight bounds for k-set agreement}, + journal = JACM, + volume = {47}, + number = {5}, + year = {2000}, + pages = {912--943}, + publisher = ACM, + address = {New York, NY, USA}, +} + +@article{CF99:tpds, + author = "Flaviu Cristian and Christof Fetzer", + title = "The Timed Asynchronous Distributed System Model", + journal = "IEEE Transactions on Parallel and Distributed + Systems", + volume = "10", + number = "6", + pages = "642--657", + year = "1999" +} + +@article{CHT96:jacm, + author = "Tushar Deepak Chandra and Vassos Hadzilacos and Sam + Toueg", + title = "The Weakest Failure Detector for Solving Consensus", + journal = {JACM}, + year = {1996}, +} + +@article{CL02:tcs, + author = {Miguel Castro and Barbara Liskov}, + title = {Practical byzantine fault tolerance and proactive + recovery}, + journal = {ACMTCS}, + year = {2002}, +} + +@inproceedings{CL99:osdi, + author = {Miguel Castro and Barbara Liskov}, + title = {Practical byzantine fault tolerance and proactive + recovery}, + booktitle = {Proceedings of the 3rd Symposium on Operating + Systems Design and Implementation}, + year = {1999}, + month = feb +} + +@inproceedings{CT91:podc, + author = {Tushar Deepak Chandra and Sam Toueg}, + title = {Unreliable Failure Detectors for Asynchronous + Systems (Preliminary Version)}, + booktitle = PODC91, + year = {1991}, + pages = {325-340} +} + +@article{CT96:jacm1, + author = "Tushar Deepak Chandra and Sam Toueg", + title = "Unreliable Failure Detectors for Reliable + Distributed Systems", + journal = {JACM}, + year = {1996}, +} + +@inproceedings{CTA00:dsn, + author = "Wei Chen and Sam Toueg and Marcos Kawazoe Aguilera", + title = "On the Quality of Service of Failure Detectors", + booktitle = "Proceedings IEEE International Conference on + Dependable Systems and Networks (DSN / FTCS'30)", + address = "New York City, USA", + year = 2000 +} + +@TechReport{DFKM96:tr, + author = {Danny Dolev and Roy Friedman and Idit Keidar and + Dahlia Malkhi}, + title = {Failure detectors in omission failure environments}, + institution = {Department of Computer Science, Cornell University}, + year = {1996}, + type = {Technical Report}, + number = {96-1608} +} + +@inproceedings{DG02:podc, + author = {Partha Dutta and Rachid Guerraoui}, + title = {The inherent price of indulgence}, + booktitle = PODC02, + year = 2002, + pages = {88--97}, + location = {Monterey, California}, + publisher = ACM, + address = {New York, NY, USA}, +} + +@inproceedings{DGFG+04:podc, + author = {Carole Delporte-Gallet and Hugues Fauconnier and + Rachid Guerraoui and Vassos Hadzilacos and Petr + Kouznetsov and Sam Toueg}, + title = {The weakest failure detectors to solve certain + fundamental problems in distributed computing}, + booktitle = PODC04, + year = 2004, + pages = {338--346}, + location = {St. John's, Newfoundland, Canada}, + publisher = ACM, + address = {New York, NY, USA} +} + +@inproceedings{DGL05:dsn, + author = {Partha Dutta and Rachid Guerraoui and Leslie + Lamport}, + title = {How Fast Can Eventual Synchrony Lead to Consensus?}, + booktitle = {Proceedings of the 2005 International Conference on + Dependable Systems and Networks (DSN'05)}, + pages = {22--27}, + year = {2005}, + address = {Los Alamitos, CA, USA} +} + +@article{DLS88:jacm, + author = "Cynthia Dwork and Nancy Lynch and Larry Stockmeyer", + title = "Consensus in the Presence of Partial Synchrony", + journal = {JACM}, + year = {1988}, +} + +@article{DPLL00:tcs, + author = "De Prisco, Roberto and Butler Lampson and Nancy + Lynch", + title = "Revisiting the {PAXOS} algorithm", + journal = TCS, + volume = "243", + number = "1--2", + pages = "35--91", + year = "2000" +} + +@techreport{DS97:tr, + author = {A. Doudou and A. Schiper}, + title = {Muteness Failure Detectors for Consensus with + {B}yzantine Processes}, + institution = {EPFL, Dept d'Informatique}, + year = {1997}, + type = {TR}, + month = {October}, + number = {97/230}, +} + +@inproceedings{DS98:podc, + author = {A. Doudou and A. Schiper}, + title = {Muteness Detectors for Consensus with {B}yzantine + Processes ({B}rief {A}nnouncement)}, + booktitle = {PODC}, + month = jul, + year = {1998} +} + +@article{DSU04:survey, + author = {D{\'e}fago, Xavier and Schiper, Andr{\'e} and Urb\'{a}n, P{\'e}ter}, + title = {Total order broadcast and multicast algorithms: Taxonomy and survey}, + journal = {ACM Comput. Surv.}, + issue_date = {December 2004}, + volume = {36}, + number = {4}, + month = dec, + year = {2004}, + issn = {0360-0300}, + pages = {372--421}, + numpages = {50}, + publisher = {ACM}, + address = {New York, NY, USA}, + keywords = {Distributed systems, agreement problems, atomic broadcast, atomic multicast, classification, distributed algorithms, fault-tolerance, global ordering, group communication, message passing, survey, taxonomy, total ordering}, +} + +@article{DeCandia07:dynamo, + author = {DeCandia, Giuseppe and Hastorun, Deniz and Jampani, Madan and Kakulapati, Gunavardhan and Lakshman, Avinash and Pilchin, Alex and Sivasubramanian, Swaminathan and Vosshall, Peter and Vogels, Werner}, + title = {Dynamo: amazon's highly available key-value store}, + journal = {SIGOPS Oper. Syst. Rev.}, + issue_date = {December 2007}, + volume = {41}, + number = {6}, + month = oct, + year = {2007}, + issn = {0163-5980}, + pages = {205--220}, + numpages = {16}, + publisher = {ACM}, + address = {New York, NY, USA}, + keywords = {performance, reliability, scalability}, +} + + +@book{Dol00:book, + author = {Shlomi Dolev}, + title = {Self-Stabilization}, + publisher = {The MIT Press}, + year = {2000} +} + +@inproceedings{FC95:podc, + author = "Christof Fetzer and Flaviu Cristian", + title = "Lower Bounds for Convergence Function Based Clock + Synchronization", + booktitle = PODC95, + year = 1995, + pages = "137--143" +} + +@article{FLP85:jacm, + author = "Michael J. Fischer and Nancy A. Lynch and + M. S. Paterson", + title = "Impossibility of Distributed Consensus with one + Faulty Process", + journal = {JACM}, + year = {1985}, +} + +@article{FMR05:tdsc, + author = {Roy Friedman and Achour Most{\'e}faoui and Michel + Raynal}, + title = {Simple and Efficient Oracle-Based Consensus + Protocols for Asynchronous Byzantine Systems.}, + journal = TDSC, + volume = {2}, + number = {1}, + year = {2005}, + pages = {46-56}, + ee = {http://dx.doi.org/10.1109/TDSC.2005.13}, + bibsource = {DBLP, http://dblp.uni-trier.de} +} + +@inproceedings{FS04:podc, + author = "Christof Fetzer and Ulrich Schmid", + title = "Brief announcement: on the possibility of consensus + in asynchronous systems with finite average response + times.", + booktitle = PODC04, + year = 2004, + pages = 402 +} + +@InProceedings{GL00:disc, + author = {Eli Gafni and Lesli Lamport}, + title = {Disk Paxos}, + booktitle = DISC00, + pages = {330--344}, + year = {2000}, +} + +@Article{GL03:dc, + author = {Eli Gafni and Lesli Lamport}, + title = {Disk Paxos}, + journal = DC, + year = 2003, + volume = {16}, + number = {1}, + pages = {1--20} +} + +@inproceedings{GP01:wss, + author = "Felix C. G{\"a}rtner and Stefan Pleisch", + title = "({I}m)Possibilities of Predicate Detection in + Crash-Affected Systems", + booktitle = WSS01, + year = 2001, + pages = "98--113" +} + +@inproceedings{GP02:disc, + author = "Felix C. G{\"a}rtner and Stefan Pleisch", + title = "Failure Detection Sequencers: Necessary and + Sufficient Information about Failures to Solve + Predicate Detection", + booktitle = DISC02, + year = 2002, + pages = "280--294" +} + +@inproceedings{GS96:wdag, + author = {Rachid Guerraoui and Andr{\'e} Schiper}, + title = {{``Gamma-Accurate''} Failure Detectors}, + booktitle = WDAG96, + year = {1996}, + pages = {269--286}, + publisher = SPR, + address = {London, UK} +} + +@inproceedings{Gaf98:podc, + author = {Eli Gafni}, + title = {Round-by-round fault detectors (extended abstract): + unifying synchrony and asynchrony}, + booktitle = PODC98, + year = {1998}, + pages = {143--152}, + address = {Puerto Vallarta, Mexico}, + publisher = ACM +} + +@incollection{Gra78:book, + author = {Jim N. Gray}, + title = {Notes on data base operating systems}, + booktitle = {Operating Systems: An Advanced Course}, + chapter = {3.F}, + publisher = {Springer}, + year = {1978}, + editor = {R. Bayer, R.M. Graham, G. Seegm\"uller}, + volume = {60}, + series = {Lecture Notes in Computer Science}, + address = {New York}, + pages = {465}, +} + +@InProceedings{HMR98:srds, + author = {Hurfin, M. and Mostefaoui, A. and Raynal, M.}, + title = {Consensus in asynchronous systems where processes + can crash and recover}, + booktitle = {Seventeenth IEEE Symposium on Reliable Distributed + Systems, Proceedings. }, + pages = { 280--286}, + year = {1998}, + address = {West Lafayette, IN}, + month = oct, + organization = {IEEE} +} + +@inproceedings{HMSZ06:sss, + author = "Martin Hutle and Dahlia Malkhi and Ulrich Schmid and + Lidong Zhou", + title = "Brief Announcement: Chasing the Weakest System Model + for Implementing {$\Omega$} and Consensus", + booktitle = SSS06, + year = 2006 +} + +@incollection{HT93:ds, + author = {Hadzilacos, Vassos and Toueg, Sam}, + title = {Fault-tolerant broadcasts and related problems}, + booktitle = {Distributed systems (2nd Ed.)}, + editor = {Mullender, Sape}, + year = {1993}, + isbn = {0-201-62427-3}, + pages = {97--145}, + numpages = {49} +} + + +@inproceedings{HS06:opodis, + author = {Heinrich Moser and Ulrich Schmid}, + title = {Optimal Clock Synchronization Revisited: Upper and + Lower Bounds in Real-Time Systems}, + booktitle = { Principles of Distributed Systems}, + pages = {94--109}, + year = {2006}, + volume = {4305}, + series = {Lecture Notes in Computer Science}, + publisher = SPR +} + +@techreport{HS06:tr, + author = {Martin Hutle and Andr{\'e} Schiper}, + title = { Communication predicates: A high-level abstraction + for coping with transient and dynamic faults}, + institution = {EPFL}, + number = { LSR-REPORT-2006-006 }, + year = {2006} +} + +@inproceedings{HS07:dsn, + author = {Martin Hutle and Andr{\'e} Schiper}, + title = { Communication predicates: A high-level abstraction + for coping with transient and dynamic faults}, + year = 2007, + booktitle = DSN07, + publisher = IEEE, + location = {Edinburgh,UK}, + pages = {92--10}, + month = jun +} + +@article{Her91:tpls, + author = {Maurice Herlihy}, + title = {Wait-free synchronization}, + journal = TPLS, + volume = {13}, + number = {1}, + year = {1991}, + pages = {124--149}, + publisher = ACM, + address = {New York, NY, USA}, +} + +@article{Kot09:zyzzyva, + author = {Kotla, Ramakrishna and Alvisi, Lorenzo and Dahlin, Mike and Clement, Allen and Wong, Edmund}, + title = {Zyzzyva: Speculative Byzantine fault tolerance}, + journal = {ACM Trans. Comput. Syst.}, + issue_date = {December 2009}, + volume = {27}, + number = {4}, + month = jan, + year = {2010}, + issn = {0734-2071}, + pages = {7:1--7:39}, + articleno = {7}, + numpages = {39}, + publisher = {ACM}, + address = {New York, NY, USA}, + keywords = {Byzantine fault tolerance, output commit, replication, speculative execution}, +} + + +@inproceedings{KMMS97:opodis, + author = "Kim Potter Kihlstrom and Louise E. Moser and + P. M. Melliar-Smith", + title = "Solving Consensus in a Byzantine Environment Using + an Unreliable Fault Detector", + booktitle = "Proceedings of the International Conference on + Principles of Distributed Systems (OPODIS)", + year = 1997, + month = dec, + address = "Chantilly, France", + pages = "61--75" +} + +@inproceedings{KS06:podc, + author = {Idit Keidar and Alexander Shraer}, + title = {Timeliness, failure-detectors, and consensus + performance}, + booktitle = PODC06, + year = {2006}, + pages = {169--178}, + location = {Denver, Colorado, USA}, + publisher = {ACM Press}, + address = {New York, NY, USA}, +} + +@InProceedings{LFA99:disc, + author = {Mikel Larrea and Antonio Fern\'andez and Sergio + Ar\'evalo}, + title = {Efficient algorithms to implement unreliable failure + detectors in partially synchronous systems}, + year = 1999, + month = sep, + pages = {34-48}, + series = "LNCS 1693", + booktitle = DISC99, + publisher = SPR, + address = {Bratislava, Slovaquia}, +} + +@article{LL84:ic, + author = "Jennifer Lundelius and Nancy A. Lynch", + title = "An Upper and Lower Bound for Clock Synchronization", + journal = IC, + volume = 62, + number = {2/3}, + year = 1984, + pages = {190--204} +} + +@techreport{LLS03:tr, + title = {How to Implement a Timer-free Perfect Failure + Detector in Partially Synchronous Systems}, + author = {Le Lann, G\'erard and Schmid, Ulrich}, + institution = TUAuto, + number = "183/1-127", + month = jan, + year = 2003 +} + +@article{LSP82:tpls, + author = {Leslie Lamport and Robert Shostak and Marshall + Pease}, + title = {The {B}yzantine Generals Problem}, + journal = {ACM Trans. Program. Lang. Syst.}, + year = {1982}, +} + +@inproceedings{Lam01:podc, + author = {Butler Lampson}, + title = {The ABCD's of Paxos}, + booktitle = {PODC}, + year = {2001}, + +} + +@inproceedings{Lam03:fddc, + author = {Leslie Lamport}, + title = {Lower Bounds for Asynchronous Consensus}, + booktitle = {Future Directions in Distributed Computing}, + pages = {22--23}, + year = {2003}, + editor = {Andr{\'e} Schiper and Alex A. Shvartsman and Hakim + Weatherspoon and Ben Y. Zhao}, + number = {2584}, + series = {Lecture Notes in Computer Science}, + publisher = SPR +} + +@techreport{Lam04:tr, + author = {Leslie Lamport}, + title = {Lower Bounds for Asynchronous Consensus}, + institution = {Microsoft Research}, + year = {2004}, + number = {MSR-TR-2004-72} +} + +@techreport{Lam05:tr, + author = {Leslie Lamport}, + title = {Fast Paxos}, + institution = {Microsoft Research}, + year = {2005}, + number = {MSR-TR-2005-12} +} + +@techreport{Lam05:tr-33, + author = {Leslie Lamport}, + title = {Generalized Consensus and Paxos}, + institution = {Microsoft Research}, + year = {2005}, + number = {MSR-TR-2005-33} +} + +@Misc{Lam06:slides, + author = {Leslie Lamport}, + title = {Byzantine Paxos}, + howpublished = {Unpublished slides}, + year = {2006} +} + +@Article{Lam86:dc, + author = {Lesli Lamport}, + title = {On Interprocess Communication--Part I: Basic + Formalism, Part II: Algorithms}, + journal = DC, + year = 1986, + volume = 1, + number = 2, + pages = {77--101} +} + +@Article {Lam98:tcs, + author = {Leslie Lamport}, + title = {The part-time parliament}, + journal = ACMTCS, + year = 1998, + volume = 16, + number = 2, + month = may, + pages = {133-169}, +} + +@book{Lyn96:book, + author = {Nancy Lynch}, + title = {Distributed Algorithms}, + publisher = {Morgan Kaufman}, + year = {1996}, +} + +@inproceedings{MA05:dsn, + author = {Martin, J.-P. and Alvisi, L. }, + title = {Fast Byzantine consensus}, + booktitle = DSN05, + pages = {402--411}, + year = {2005}, + month = jun, + organization = {IEEE}, +} + +@article{MA06:tdsc, + author = {Martin, J.-P. and Alvisi, L. }, + title = {Fast {B}yzantine Consensus}, + journal = {TDSC}, + year = {2006}, +} + +@InProceedings{MOZ05:dsn, + author = {Dahlia Malkhi and Florin Oprea and Lidong Zhou}, + title = {{$\Omega$} Meets Paxos: Leader Election and + Stability without Eventual Timely Links}, + booktitle = DSN05, + year = {2005} +} + +@inproceedings{MR00:podc, + author = "Achour Most{\'e}faoui and Michel Raynal", + title = "k-set agreement with limited accuracy failure + detectors", + booktitle = PODC00, + year = 2000, + pages = {143--152}, + location = {Portland, Oregon, United States}, + publisher = ACM +} + +@article{MR01:ppl, + author = "Achour Most{\'e}faoui and Michel Raynal", + title = "Leader-Based Consensus", + journal = PPL, + volume = 11, + number = 1, + year = 2001, + pages = {95--107} +} + +@techreport{OGS97:tr, + author = "Rui Oliveira and Rachid Guerraoui and {Andr\'e} + Schiper", + title = "Consensus in the crash-recover model", + number = "TR-97/239", + year = "1997" +} + +@article{PSL80:jacm, + author = {M. Pease and R. Shostak and L. Lamport}, + title = {Reaching Agreement in the Presence of Faults}, + journal = JACM, + volume = {27}, + number = {2}, + year = {1980}, + pages = {228--234}, + publisher = ACM, + address = ACMADDR, +} + +@article{ST87:jacm, + author = "T. K. Srikanth and Sam Toueg", + title = "Optimal clock synchronization", + journal = JACM, + volume = 34, + number = 3, + year = 1987, + pages = "626--645" +} + +@article{ST87:dc, + author = {T. K. Srikanth and Sam Toueg,}, + title = {Simulating authenticated broadcasts to derive simple fault-tolerant algorithms}, + journal = DC, + volume = {2}, + number = {2}, + year = {1987}, + pages = {80-94} +} + + +@inproceedings{SW89:stacs, + author = {Santoro, Nicola and Widmayer, Peter}, + title = {Time is not a healer}, + booktitle = {Proc.\ 6th Annual Symposium on Theor.\ Aspects of + Computer Science (STACS'89)}, + publisher = "Springer-Verlag", + series = {LNCS}, + volume = "349", + address = "Paderborn, Germany", + pages = "304-313", + year = "1989", + month = feb, +} + +@inproceedings{SW90:sigal, + author = {Nicola Santoro and Peter Widmayer}, + title = {Distributed Function Evaluation in the Presence of + Transmission Faults.}, + booktitle = {SIGAL International Symposium on Algorithms}, + year = {1990}, + pages = {358-367} +} + +@inproceedings{SWR02:icdcs, + author = {Ulrich Schmid and Bettina Weiss and John Rushby}, + title = {Formally Verified Byzantine Agreement in Presence of + Link Faults}, + booktitle = "22nd International Conference on Distributed + Computing Systems (ICDCS'02)", + year = 2002, + month = jul # " 2-5, ", + pages = "608--616", + address = "Vienna, Austria", +} + +@incollection{Sch93a:mullender, + Author = {F. B. Schneider}, + Title = {What Good are Models and What Models are Good}, + BookTitle = {Distributed Systems}, + Year = {1993}, + Editor = {Sape Mullender}, + Publisher = {ACM Press}, + Pages = {169-197}, +} + +@article{VL96:ic, + author = {George Varghese and Nancy A. Lynch}, + title = {A Tradeoff Between Safety and Liveness for + Randomized Coordinated Attack.}, + journal = {Inf. Comput.}, + volume = {128}, + number = {1}, + year = 1996, + pages = {57--71} +} + +@inproceedings{WGWB07:dsn, + title = {Synchronous Consensus with Mortal Byzantines}, + author = {Josef Widder and Günther Gridling and Bettina Weiss + and Jean-Paul Blanquart}, + year = {2007}, + booktitle = DSN07, + publisher = IEEE +} + +@inproceedings{Wid03:disc, + author = {Josef Widder}, + title = {Booting clock Synchronization in Partially + Synchronous Systems}, + booktitle = DISC03, + year = {2003}, + pages = {121--135} +} + +@techreport{Zie04:tr, + author = {Piotr Zieli{\'n}ski}, + title = {Paxos at War}, + institution = {University of Cambridge}, + year = {2004}, + number = {UCAM-CL-TR-593}, +} + +@article{Lam78:cacm, + author = {Leslie Lamport}, + title = {Time, clocks, and the ordering of events in a + distributed system}, + journal = {Commun. ACM}, + year = {1978}, +} + +@Article{Gue06:cj, + author = {Guerraoui, R. and Raynal, M.}, + journal = {The {C}omputer {J}ournal}, + title = {The {A}lpha of {I}ndulgent {C}onsensus}, + year = {2006} +} + +@Article{Gue03:toc, + affiliation = {EPFL}, + author = {Guerraoui, Rachid and Raynal, Michel}, + journal = {{IEEE} {T}rans. on {C}omputers}, + title = {The {I}nformation {S}tructure of {I}ndulgent {C}onsensus}, + year = {2004}, +} + +@techreport{Cas00, + author = {Castro, Miguel}, + title = {Practical {B}yzantine Fault-Tolerance. {PhD} thesis}, + institution = {MIT}, + year = 2000, +} + +@inproceedings{SongRSD08:icdcn, + author = {Yee Jiun Song and + Robbert van Renesse and + Fred B. Schneider and + Danny Dolev}, + title = {The Building Blocks of Consensus}, + booktitle = {ICDCN}, + year = {2008}, +} + + +@inproceedings{BS09:icdcn, + author = {Borran, Fatemeh and Schiper, Andr{\'e}}, + + title = {A {L}eader-free {B}yzantine {C}onsensus {A}lgorithm}, + note = {To appear in ICDCN, 2010}, +} + + +@inproceedings{MHS09:opodis, + author = {Zarko Milosevic and Martin Hutle and Andr{\'e} + Schiper}, + title = {Unifying {B}yzantine Consensus Algorithms with {W}eak + {I}nteractive {C}onsistency}, + note = {To appear in OPODIS 2009}, +} + +@inproceedings{MRR:dsn02, + author = {Most\'{e}faoui, Achour and Rajsbaum, Sergio and Raynal, Michel}, + title = {A Versatile and Modular Consensus Protocol}, + booktitle = {DSN}, + year = {2002}, + } + +@article{MR98:dc, + author = {Dahlia Malkhi and + Michael K. Reiter}, + title = {Byzantine Quorum Systems}, + journal = {Distributed Computing}, + year = {1998}, +} + +@inproceedings{Rei:ccs94, + author = {Reiter, Michael K.}, + title = {Secure agreement protocols: reliable and atomic group multicast in rampart}, + booktitle = {CCS}, + year = {1994}, + pages = {68--80}, + numpages = {13} +} + + +@techreport{RMS09-tr, + author = {Olivier R\"utti and Zarko Milosevic and Andr\'e Schiper}, + title = {{G}eneric construction of consensus algorithm for benign and {B}yzantine faults}, + institution = {EPFL-IC}, + number = {LSR-REPORT-2009-005}, + year = 2009, +} + +@inproceedings{Li:srds07, + author = {Li, Harry C. and Clement, Allen and Aiyer, Amitanand S. and Alvisi, Lorenzo}, + title = {The Paxos Register}, + booktitle = {SRDS}, + year = {2007}, + } + + @article{Amir11:prime, + author = {Amir, Yair and Coan, Brian and Kirsch, Jonathan and Lane, John}, + title = {Prime: Byzantine Replication under Attack}, + journal = {IEEE Trans. Dependable Secur. Comput.}, + issue_date = {July 2011}, + volume = {8}, + number = {4}, + month = jul, + year = {2011}, + issn = {1545-5971}, + pages = {564--577}, + numpages = {14}, + publisher = {IEEE Computer Society Press}, + address = {Los Alamitos, CA, USA}, + keywords = {Performance under attack, Byzantine fault tolerance, replicated state machines, distributed systems.}, +} + +@inproceedings{Mao08:mencius, + author = {Mao, Yanhua and Junqueira, Flavio P. and Marzullo, Keith}, + title = {Mencius: building efficient replicated state machines for WANs}, + booktitle = {OSDI}, + year = {2008}, + pages = {369--384}, + numpages = {16} +} + +@article{Sch90:survey, + author = {Schneider, Fred B.}, + title = {Implementing fault-tolerant services using the state machine approach: a tutorial}, + journal = {ACM Comput. Surv.}, + volume = {22}, + number = {4}, + month = dec, + year = {1990} +} + + +@techreport{HT94:TR, + author = {Hadzilacos, Vassos and Toueg, Sam}, + title = {A Modular Approach to Fault-Tolerant Broadcasts and Related Problems}, + year = {1994}, + source = {http://www.ncstrl.org:8900/ncstrl/servlet/search?formname=detail\&id=oai%3Ancstrlh%3Acornellcs%3ACORNELLCS%3ATR94-1425}, + publisher = {Cornell University}, + address = {Ithaca, NY, USA}, +} + +@inproceedings{Ver09:spinning, + author = {Veronese, Giuliana Santos and Correia, Miguel and Bessani, Alysson Neves and Lung, Lau Cheuk}, + title = {Spin One's Wheels? Byzantine Fault Tolerance with a Spinning Primary}, + booktitle = {SRDS}, + year = {2009}, + numpages = {10} +} + +@inproceedings{Cle09:aardvark, + author = {Clement, Allen and Wong, Edmund and Alvisi, Lorenzo and Dahlin, Mike and Marchetti, Mirco}, + title = {Making Byzantine fault tolerant systems tolerate Byzantine faults}, + booktitle = {NSDI}, + year = {2009}, + pages = {153--168}, + numpages = {16} +} + +@inproceedings{Aiyer05:barB, + author = {Aiyer, Amitanand S. and Alvisi, Lorenzo and Clement, Allen and Dahlin, Mike and Martin, Jean-Philippe and Porth, Carl}, + title = {BAR fault tolerance for cooperative services}, + booktitle = {SOSP}, + year = {2005}, + pages = {45--58}, + numpages = {14} +} + +@inproceedings{Cach01:crypto, + author = {Cachin, Christian and Kursawe, Klaus and Petzold, Frank and Shoup, Victor}, + title = {Secure and Efficient Asynchronous Broadcast Protocols}, + booktitle = {CRYPTO}, + year = {2001}, + pages = {524--541}, + numpages = {18} +} + +@article{Moniz11:ritas, + author = {Moniz, Henrique and Neves, Nuno Ferreria and Correia, Miguel and Verissimo, Paulo}, + title = {RITAS: Services for Randomized Intrusion Tolerance}, + journal = {IEEE Trans. Dependable Secur. Comput.}, + volume = {8}, + number = {1}, + month = jan, + year = {2011}, + pages = {122--136}, + numpages = {15} +} + +@inproceedings{MHS11:jabc, + author = {Milosevic, Zarko and Hutle, Martin and Schiper, Andre}, + title = {On the Reduction of Atomic Broadcast to Consensus with Byzantine Faults}, + booktitle = {SRDS}, + year = {2011}, + pages = {235--244}, + numpages = {10} +} + +@incollection{DHSZ03, + author={Driscoll, Kevin and Hall, Brendan and Sivencrona, Håkan and Zumsteg, Phil}, + title={Byzantine Fault Tolerance, from Theory to Reality}, + year={2003}, + booktitle={Computer Safety, Reliability, and Security}, + volume={2788}, + pages={235--248} +} + +@inproceedings{RMES:dsn07, + author = {Olivier R{\"u}tti and + Sergio Mena and + Richard Ekwall and + Andr{\'e} Schiper}, + title = {On the Cost of Modularity in Atomic Broadcast}, + booktitle = {DSN}, + year = {2007}, + pages = {635-644} +} + +@article{Ben:jc92, + author = {Charles H. Bennett and + Fran\c{c}ois Bessette and + Gilles Brassard and + Louis Salvail and + John A. Smolin}, + title = {Experimental Quantum Cryptography}, + journal = {J. Cryptology}, + volume = {5}, + number = {1}, + year = {1992}, + pages = {3-28} +} + +@inproceedings{Aiyer:disc08, + author = {Aiyer, Amitanand S. and Alvisi, Lorenzo and Bazzi, Rida A. and Clement, Allen}, + title = {Matrix Signatures: From MACs to Digital Signatures in Distributed Systems}, + booktitle = {DISC}, + year = {2008}, + pages = {16--31}, + numpages = {16} +} + +@inproceedings{Biel13:dsn, + author = {Biely, Martin and Delgado, Pamela and Milosevic, Zarko and Schiper, Andr{\'e}}, + title = {Distal: A Framework for Implementing Fault-tolerant Distributed Algorithms}, + note = {To appear in DSN, 2013}, + year = 2013 +} + +@inproceedings{BS10:icdcn, + author = {Borran, Fatemeh and Schiper, Andr{\'e}}, + title = {A leader-free Byzantine consensus algorithm}, + booktitle = {ICDCN}, + year = {2010}, + pages = {67--78}, + numpages = {12} +} + +@article{Cor06:cj, + author = {Correia, Miguel and Neves, Nuno Ferreira and Ver\'{\i}ssimo, Paulo}, + title = {From Consensus to Atomic Broadcast: Time-Free Byzantine-Resistant Protocols without Signatures}, + journal = {Comput. J.}, + volume = {49}, + number = {1}, + year = {2006}, + pages = {82--96}, + numpages = {15} +} + +@inproceedings{RMS10:dsn, + author = {Olivier R{\"u}tti and + Zarko Milosevic and + Andr{\'e} Schiper}, + title = {Generic construction of consensus algorithms for benign + and Byzantine faults}, + booktitle = {DSN}, + year = {2010}, + pages = {343-352} +} + + + +@inproceedings{HKJR:usenix10, + author = {Hunt, Patrick and Konar, Mahadev and Junqueira, Flavio P. and Reed, Benjamin}, + title = {ZooKeeper: wait-free coordination for internet-scale systems}, + OPTbooktitle = {Proceedings of the 2010 USENIX conference on USENIX annual technical conference}, + booktitle = {USENIXATC}, + year = {2010}, + OPTlocation = {Boston, MA}, + pages = {11}, + numpages = {1}, + OPTurl = {http://dl.acm.org/citation.cfm?id=1855840.1855851}, + acmid = {1855851}, + OPTpublisher = {USENIX Association}, + OPTaddress = {Berkeley, CA, USA}, +} + +@inproceedings{Bur:osdi06, + author = {Burrows, Mike}, + title = {The Chubby lock service for loosely-coupled distributed systems}, + booktitle = {OSDI}, + year = {2006}, + pages = {335--350}, + numpages = {16}, +} + +@INPROCEEDINGS{Mao09:hotdep, + author = {Yanhua Mao and Flavio P. Junqueira and Keith Marzullo}, + title = {Towards low latency state machine replication for uncivil wide-area networks}, + booktitle = {HotDep}, + year = {2009} +} + +@inproceedings{Chun07:a2m, + author = {Chun, Byung-Gon and Maniatis, Petros and Shenker, Scott and Kubiatowicz, John}, + title = {Attested append-only memory: making adversaries stick to their word}, + booktitle = {SOSP}, + year = {2007}, + pages = {189--204}, + numpages = {16} +} + +@TECHREPORT{MBS:epfltr, + author = {Zarko Milosevic and Martin Biely and Andr\'e Schiper}, + title = {Bounded {D}elay in {B}yzantine {T}olerant {S}tate {M}achine {R}eplication}, + year = 2013, + month = april, + institution = {EPFL}, + number = {185962}, +} + +@book{BH09:datacenter, + author = {Barroso, Luiz Andre and Hoelzle, Urs}, + title = {The Datacenter as a Computer: An Introduction to the Design of Warehouse-Scale Machines}, + year = {2009}, + isbn = {159829556X, 9781598295566}, + edition = {1st}, + publisher = {Morgan and Claypool Publishers}, +} + +@inproceedings{Kir11:csiirw, + author = {Kirsch, Jonathan and Goose, Stuart and Amir, Yair and Skare, Paul}, + title = {Toward survivable SCADA}, + booktitle = {CSIIRW}, + year = {2011}, + pages = {21:1--21:1}, + articleno = {21}, + numpages = {1} +} + +@inproceedings{Ongaro14:raft, + author = {Ongaro, Diego and Ousterhout, John}, + title = {In Search of an Understandable Consensus Algorithm}, + booktitle = {Proceedings of the 2014 USENIX Conference on USENIX Annual Technical Conference}, + series = {USENIX ATC'14}, + year = {2014}, + isbn = {978-1-931971-10-2}, + location = {Philadelphia, PA}, + pages = {305--320}, + numpages = {16}, + url = {http://dl.acm.org/citation.cfm?id=2643634.2643666}, + acmid = {2643666}, + publisher = {USENIX Association}, + address = {Berkeley, CA, USA}, +} + +@article{GLR17:red-belly-bc, + author = {Tyler Crain and + Vincent Gramoli and + Mikel Larrea and + Michel Raynal}, + title = {Leader/Randomization/Signature-free Byzantine Consensus for Consortium + Blockchains}, + journal = {CoRR}, + volume = {abs/1702.03068}, + year = {2017}, + url = {http://arxiv.org/abs/1702.03068}, + archivePrefix = {arXiv}, + eprint = {1702.03068}, + timestamp = {Wed, 07 Jun 2017 14:41:08 +0200}, + biburl = {http://dblp.org/rec/bib/journals/corr/CrainGLR17}, + bibsource = {dblp computer science bibliography, http://dblp.org} +} + + +@misc{Nak2012:bitcoin, + added-at = {2014-04-17T08:33:06.000+0200}, + author = {Nakamoto, Satoshi}, + biburl = {https://www.bibsonomy.org/bibtex/23db66df0fc9fa2b5033f096a901f1c36/ngnn}, + interhash = {423c2cdff70ba0cd0bca55ebb164d770}, + intrahash = {3db66df0fc9fa2b5033f096a901f1c36}, + keywords = {imported}, + timestamp = {2014-04-17T08:33:06.000+0200}, + title = {Bitcoin: A peer-to-peer electronic cash system}, + url = {http://www.bitcoin.org/bitcoin.pdf}, + year = 2009 +} + +@misc{But2014:ethereum, + author = {Vitalik Buterin}, + title = {Ethereum: A next-generation smart contract and decentralized application platform}, + year = {2014}, + howpublished = {\url{https://github.com/ethereum/wiki/wiki/White-Paper}}, + note = {Accessed: 2018-07-11}, + url = {https://github.com/ethereum/wiki/wiki/White-Paper}, +} + +@inproceedings{Dem1987:gossip, + author = {Demers, Alan and Greene, Dan and Hauser, Carl and Irish, Wes and Larson, John and Shenker, Scott and Sturgis, Howard and Swinehart, Dan and Terry, Doug}, + title = {Epidemic Algorithms for Replicated Database Maintenance}, + booktitle = {Proceedings of the Sixth Annual ACM Symposium on Principles of Distributed Computing}, + series = {PODC '87}, + year = {1987}, + isbn = {0-89791-239-X}, + location = {Vancouver, British Columbia, Canada}, + pages = {1--12}, + numpages = {12}, + url = {http://doi.acm.org/10.1145/41840.41841}, + doi = {10.1145/41840.41841}, + acmid = {41841}, + publisher = {ACM}, + address = {New York, NY, USA}, +} + +@article{Gue2018:sbft, + author = {Guy Golan{-}Gueta and + Ittai Abraham and + Shelly Grossman and + Dahlia Malkhi and + Benny Pinkas and + Michael K. Reiter and + Dragos{-}Adrian Seredinschi and + Orr Tamir and + Alin Tomescu}, + title = {{SBFT:} a Scalable Decentralized Trust Infrastructure for Blockchains}, + journal = {CoRR}, + volume = {abs/1804.01626}, + year = {2018}, + url = {http://arxiv.org/abs/1804.01626}, + archivePrefix = {arXiv}, + eprint = {1804.01626}, + timestamp = {Tue, 01 May 2018 19:46:29 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1804-01626}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@inproceedings{BLS2001:crypto, + author = {Boneh, Dan and Lynn, Ben and Shacham, Hovav}, + title = {Short Signatures from the Weil Pairing}, + booktitle = {Proceedings of the 7th International Conference on the Theory and Application of Cryptology and Information Security: Advances in Cryptology}, + series = {ASIACRYPT '01}, + year = {2001}, + isbn = {3-540-42987-5}, + pages = {514--532}, + numpages = {19}, + url = {http://dl.acm.org/citation.cfm?id=647097.717005}, + acmid = {717005}, + publisher = {Springer-Verlag}, + address = {Berlin, Heidelberg}, +} + + diff --git a/spec/consensus/consensus-paper/paper.tex b/spec/consensus/consensus-paper/paper.tex new file mode 100644 index 0000000..8681bb2 --- /dev/null +++ b/spec/consensus/consensus-paper/paper.tex @@ -0,0 +1,153 @@ +%\documentclass[conference]{IEEEtran} +\documentclass[conference,onecolumn,draft,a4paper]{IEEEtran} +% Add the compsoc option for Computer Society conferences. +% +% If IEEEtran.cls has not been installed into the LaTeX system files, +% manually specify the path to it like: +% \documentclass[conference]{../sty/IEEEtran} + + + +% *** GRAPHICS RELATED PACKAGES *** +% +\ifCLASSINFOpdf +\else +\fi + +% correct bad hyphenation here +\hyphenation{op-tical net-works semi-conduc-tor} + +%\usepackage[caption=false,font=footnotesize]{subfig} +\usepackage{tikz} +\usetikzlibrary{decorations,shapes,backgrounds,calc} +\tikzstyle{msg}=[->,black,>=latex] +\tikzstyle{rubber}=[|<->|] +\tikzstyle{announce}=[draw=blue,fill=blue,shape=diamond,right,minimum + height=2mm,minimum width=1.6667mm,inner sep=0pt] +\tikzstyle{decide}=[draw=red,fill=red,shape=isosceles triangle,right,minimum + height=2mm,minimum width=1.6667mm,inner sep=0pt,shape border rotate=90] +\tikzstyle{cast}=[draw=green!50!black,fill=green!50!black,shape=circle,left,minimum + height=2mm,minimum width=1.6667mm,inner sep=0pt] + + +\usepackage{multirow} +\usepackage{graphicx} +\usepackage{epstopdf} +\usepackage{amssymb} +\usepackage{rounddiag} +\graphicspath{{../}} + +\usepackage{technote} +\usepackage{homodel} +\usepackage{enumerate} +%%\usepackage{ulem}\normalem + +% to center caption +\usepackage{caption} + +\newcommand{\textstretch}{1.4} +\newcommand{\algostretch}{1} +\newcommand{\eqnstretch}{0.5} + +\newconstruct{\FOREACH}{\textbf{for each}}{\textbf{do}}{\ENDFOREACH}{} + +%\newconstruct{\ON}{\textbf{on}}{\textbf{do}}{\ENDON}{\textbf{end on}} +\newcommand\With{\textbf{while}} +\newcommand\From{\textbf{from}} +\newcommand\Broadcast{\textbf{broadcast}} +\newcommand\PBroadcast{send} +\newcommand\UpCall{\textbf{UpCall}} +\newcommand\DownCall{\textbf{DownCall}} +\newcommand \Call{\textbf{Call}} +\newident{noop} +\newconstruct{\UPON}{\textbf{upon}}{\textbf{do}}{\ENDUPON}{} + + + +\newcommand{\abcast}{\mathsf{to\mbox{\sf-}broadcast}} +\newcommand{\adeliver}{\mathsf{to\mbox{\sf-}deliver}} + +\newcommand{\ABCAgreement}{\emph{TO-Agreement}} +\newcommand{\ABCIntegrity}{\emph{TO-Integrity}} +\newcommand{\ABCValidity}{\emph{TO-Validity}} +\newcommand{\ABCTotalOrder}{\emph{TO-Order}} +\newcommand{\ABCBoundedDelivery}{\emph{TO-Bounded Delivery}} + + +\newcommand{\tabc}{\mathit{atab\mbox{\sf-}cast}} +\newcommand{\anno}{\mathit{atab\mbox{\sf-}announce}} +\newcommand{\abort}{\mathit{atab\mbox{\sf-}abort}} +\newcommand{\tadel}{\mathit{atab\mbox{\sf-}deliver}} + +\newcommand{\ATABAgreement}{\emph{ATAB-Agreement}} +\newcommand{\ATABAbort}{\emph{ATAB-Abort}} +\newcommand{\ATABIntegrity}{\emph{ATAB-Integrity}} +\newcommand{\ATABValidity}{\emph{ATAB-Validity}} +\newcommand{\ATABAnnounce}{\emph{ATAB-Announcement}} +\newcommand{\ATABTermination}{\emph{ATAB-Termination}} +%\newcommand{\ATABFastAnnounce}{\emph{ATAB-Fast-Announcement}} + +%% Command for observations. +\newtheorem{observation}{Observation} + + +%% HO ALGORITHM DEFINITIONS +\newconstruct{\FUNCTION}{\textbf{Function}}{\textbf{:}}{\ENDFUNCTION}{} + +%% Uncomment the following four lines to remove remarks and visible traces of +%% modifications in the document +%%\renewcommand{\sout}[1]{\relaxx} +%%\renewcommand{\uline}[1]{#1} +%% \renewcommand{\uwave}[1]{#1} + \renewcommand{\note}[2][default]{\relax} + + +%% The following commands can be used to generate TR or Conference version of the paper +\newcommand{\tr}[1]{} +\renewcommand{\tr}[1]{#1} +\newcommand{\onlypaper}[1]{#1} +%\renewcommand{\onlypaper}[1]{} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%\pagestyle{plain} +%\pagestyle{empty} + +%% IEEE tweaks +%\setlength{\IEEEilabelindent}{.5\parindent} +%\setlength{\IEEEiednormlabelsep}{.5\parindent} + +\begin{document} +% +% paper title +% can use linebreaks \\ within to get better formatting as desired +\title{The latest gossip on BFT consensus\vspace{-0.7\baselineskip}} + + + +\author{\IEEEauthorblockN{\large Ethan Buchman, Jae Kwon and Zarko Milosevic\\} + \IEEEauthorblockN{\large Tendermint}\\ + %\\\vspace{-0.5\baselineskip} + \IEEEauthorblockN{September 24, 2018} +} + +% make the title area +\maketitle +\vspace*{0.5em} + +\begin{abstract} +This paper presents Tendermint, a new protocol for ordering events in a distributed network under adversarial conditions. More commonly known as Byzantine Fault Tolerant (BFT) consensus or atomic broadcast, the problem has attracted significant attention in recent years due to the widespread success of blockchain-based digital currencies, such as Bitcoin and Ethereum, which successfully solved the problem in a public setting without a central authority. Tendermint modernizes classic academic work on the subject and simplifies the design of the BFT algorithm by relying on a peer-to-peer gossip protocol among nodes. +\end{abstract} + +%\noindent \textbf{Keywords:} Blockchain, Byzantine Fault Tolerance, State Machine %Replication + +\input{intro} +\input{definitions} +\input{consensus} +\input{proof} +\input{conclusion} + +\bibliographystyle{IEEEtran} +\bibliography{lit} + +%\appendix + +\end{document} diff --git a/spec/consensus/consensus-paper/proof.tex b/spec/consensus/consensus-paper/proof.tex new file mode 100644 index 0000000..76a64e9 --- /dev/null +++ b/spec/consensus/consensus-paper/proof.tex @@ -0,0 +1,280 @@ +\section{Proof of Tendermint consensus algorithm} \label{sec:proof} + +\begin{lemma} \label{lemma:majority-intersection} For all $f\geq 0$, any two +sets of processes with voting power at least equal to $2f+1$ have at least one +correct process in common. \end{lemma} + +\begin{proof} As the total voting power is equal to $n=3f+1$, we have $2(2f+1) + = n+f+1$. This means that the intersection of two sets with the voting + power equal to $2f+1$ contains at least $f+1$ voting power in common, \ie, + at least one correct process (as the total voting power of faulty processes + is $f$). The result follows directly from this. \end{proof} + +\begin{lemma} \label{lemma:locked-decision_value-prevote-v} If $f+1$ correct +processes lock value $v$ in round $r_0$ ($lockedValue = v$ and $lockedRound = +r_0$), then in all rounds $r > r_0$, they send $\Prevote$ for $id(v)$ or +$\nil$. \end{lemma} + +\begin{proof} We prove the result by induction on $r$. + +\emph{Base step $r = r_0 + 1:$} Let's denote with $C$ the set of correct +processes with voting power equal to $f+1$. By the rules at +line~\ref{line:tab:recvProposal} and line~\ref{line:tab:acceptProposal}, the +processes from the set $C$ can't accept $\Proposal$ for any value different +from $v$ in round $r$, and therefore can't send a $\li{\Prevote,height_p, +r,id(v')}$ message, if $v' \neq v$. Therefore, the Lemma holds for the base +step. + +\emph{Induction step from $r_1$ to $r_1+1$:} We assume that no process from the +set $C$ has sent $\Prevote$ for values different than $id(v)$ or $\nil$ until +round $r_1 + 1$. We now prove that the Lemma also holds for round $r_1 + 1$. As +processes from the set $C$ send $\Prevote$ for $id(v)$ or $\nil$ in rounds $r_0 +\le r \le r_1$, by Lemma~\ref{lemma:majority-intersection} there is no value +$v' \neq v$ for which it is possible to receive $2f+1$ $\Prevote$ messages in +those rounds (i). Therefore, we have for all processes from the set $C$, +$lockedValue = v$ and $lockedRound \ge r_0$. Let's assume by a contradiction +that a process $q$ from the set $C$ sends $\Prevote$ in round $r_1 + 1$ for +value $id(v')$, where $v' \neq v$. This is possible only by +line~\ref{line:tab:prevote-higher-proposal}. Note that this implies that $q$ +received $2f+1$ $\li{\Prevote,h_q, r,id(v')}$ messages, where $r > r_0$ and $r +< r_1 +1$ (see line~\ref{line:tab:cond-prevote-higher-proposal}). A +contradiction with (i) and Lemma~\ref{lemma:majority-intersection}. +\end{proof} + +\begin{lemma} \label{lemma:agreement} Algorithm~\ref{alg:tendermint} satisfies +Agreement. \end{lemma} + +\begin{proof} Let round $r_0$ be the first round of height $h$ such that some + correct process $p$ decides $v$. We now prove that if some correct process + $q$ decides $v'$ in some round $r \ge r_0$, then $v = v'$. + +In case $r = r_0$, $q$ has received at least $2f+1$ +$\li{\Precommit,h_p,r_0,id(v')}$ messages at line~\ref{line:tab:onDecideRule}, +while $p$ has received at least $2f+1$ $\li{\Precommit,h_p,r_0,id(v)}$ +messages. By Lemma~\ref{lemma:majority-intersection} two sets of messages of +voting power $2f+1$ intersect in at least one correct process. As a correct +process sends a single $\Precommit$ message in a round, then $v=v'$. + +We prove the case $r > r_0$ by contradiction. By the +rule~\ref{line:tab:onDecideRule}, $p$ has received at least $2f+1$ voting-power +equivalent of $\li{\Precommit,h_p,r_0,id(v)}$ messages, i.e., at least $f+1$ +voting-power equivalent correct processes have locked value $v$ in round $r_0$ and have +sent those messages (i). Let denote this set of messages with $C$. On the +other side, $q$ has received at least $2f+1$ voting power equivalent of +$\li{\Precommit,h_q, r,id(v')}$ messages. As the voting power of all faulty +processes is at most $f$, some correct process $c$ has sent one of those +messages. By the rule at line~\ref{line:tab:recvPrevote}, $c$ has locked value +$v'$ in round $r$ before sending $\li{\Precommit,h_q, r,id(v')}$. Therefore $c$ +has received $2f+1$ $\Prevote$ messages for $id(v')$ in round $r > r_0$ (see +line~\ref{line:tab:recvPrevote}). By Lemma~\ref{lemma:majority-intersection}, a +process from the set $C$ has sent $\Prevote$ message for $id(v')$ in round $r$. +A contradiction with (i) and Lemma~\ref{lemma:locked-decision_value-prevote-v}. +\end{proof} + +\begin{lemma} \label{lemma:agreement} Algorithm~\ref{alg:tendermint} satisfies +Validity. \end{lemma} + +\begin{proof} Trivially follows from the rule at line +\ref{line:tab:validDecisionValue} which ensures that only valid values can be +decided. \end{proof} + +\begin{lemma} \label{lemma:round-synchronisation} If we assume that: +\begin{enumerate} + \item a correct process $p$ is the first correct process to + enter a round $r>0$ at time $t > GST$ (for every correct process + $c$, $round_c \le r$ at time $t$) + \item the proposer of round $r$ is + a correct process $q$ + \item for every correct process $c$, + $lockedRound_c \le validRound_q$ at time $t$ + \item $\timeoutPropose(r) + > 2\Delta + \timeoutPrecommit(r-1)$, $\timeoutPrevote(r) > 2\Delta$ and + $\timeoutPrecommit(r) > 2\Delta$, +\end{enumerate} +then all correct processes decide in round $r$ before $t + 4\Delta + + \timeoutPrecommit(r-1)$. +\end{lemma} + +\begin{proof} As $p$ is the first correct process to enter round $r$, it + executed the line~\ref{line:tab:nextRound} after $\timeoutPrecommit(r-1)$ + expired. Therefore, $p$ received $2f+1$ $\Precommit$ messages in the round + $r-1$ before time $t$. By the \emph{Gossip communication} property, all + correct processes will receive those messages the latest at time $t + + \Delta$. Correct processes that are in rounds $< r-1$ at time $t$ will + enter round $r-1$ (see the rule at line~\ref{line:tab:nextRound2}) and + trigger $\timeoutPrecommit(r-1)$ (see rule~\ref{line:tab:startTimeoutPrecommit}) + by time $t+\Delta$. Therefore, all correct processes will start round $r$ + by time $t+\Delta+\timeoutPrecommit(r-1)$ (i). + +In the worst case, the process $q$ is the last correct process to enter round +$r$, so $q$ starts round $r$ and sends $\Proposal$ message for some value $v$ +at time $t + \Delta + \timeoutPrecommit(r-1)$. Therefore, all correct processes +receive the $\Proposal$ message from $q$ the latest by time $t + 2\Delta + +\timeoutPrecommit(r-1)$. Therefore, if $\timeoutPropose(r) > 2\Delta + +\timeoutPrecommit(r-1)$, all correct processes will receive $\Proposal$ message +before $\timeoutPropose(r)$ expires. + +By (3) and the rules at line~\ref{line:tab:recvProposal} and +\ref{line:tab:acceptProposal}, all correct processes will accept the +$\Proposal$ message for value $v$ and will send a $\Prevote$ message for +$id(v)$ by time $t + 2\Delta + \timeoutPrecommit(r-1)$. Note that by the +\emph{Gossip communication} property, the $\Prevote$ messages needed to trigger +the rule at line~\ref{line:tab:acceptProposal} are received before time $t + +\Delta$. + +By time $t + 3\Delta + \timeoutPrecommit(r-1)$, all correct processes will receive +$\Proposal$ for $v$ and $2f+1$ corresponding $\Prevote$ messages for $id(v)$. +By the rule at line~\ref{line:tab:recvPrevote}, all correct processes will send +a $\Precommit$ message (see line~\ref{line:tab:precommit-v}) for $id(v)$ by +time $t + 3\Delta + \timeoutPrecommit(r-1)$. Therefore, by time $t + 4\Delta + +\timeoutPrecommit(r-1)$, all correct processes will have received the $\Proposal$ +for $v$ and $2f+1$ $\Precommit$ messages for $id(v)$, so they decide at +line~\ref{line:tab:decide} on $v$. + +This scenario holds if every correct process $q$ sends a $\Precommit$ message +before $\timeoutPrevote(r)$ expires, and if $\timeoutPrecommit(r)$ does not expire +before $t + 4\Delta + \timeoutPrecommit(r-1)$. Let's assume that a correct process +$c_1$ is the first correct process to trigger $\timeoutPrevote(r)$ (see the rule +at line~\ref{line:tab:recvAny2/3Prevote}) at time $t_1 > t$. This implies that +before time $t_1$, $c_1$ received a $\Proposal$ ($step_{c_1}$ must be +$\prevote$ by the rule at line~\ref{line:tab:recvAny2/3Prevote}) and a set of +$2f+1$ $\Prevote$ messages. By time $t_1 + \Delta$, all correct processes will +receive those messages. Note that even if some correct process was in the +smaller round before time $t_1$, at time $t_1 + \Delta$ it will start round $r$ +after receiving those messages (see the rule at +line~\ref{line:tab:skipRounds}). Therefore, all correct processes will send +their $\Prevote$ message for $id(v)$ by time $t_1 + \Delta$, and all correct +processes will receive those messages the by time $t_1 + 2\Delta$. Therefore, +as $\timeoutPrevote(r) > 2\Delta$, this ensures that all correct processes receive +$\Prevote$ messages from all correct processes before their respective local +$\timeoutPrevote(r)$ expire. + +On the other hand, $\timeoutPrecommit(r)$ is triggered in a correct process $c_2$ +after it receives any set of $2f+1$ $\Precommit$ messages for the first time. +Let's denote with $t_2 > t$ the earliest point in time $\timeoutPrecommit(r)$ is +triggered in some correct process $c_2$. This implies that $c_2$ has received +at least $f+1$ $\Precommit$ messages for $id(v)$ from correct processes, i.e., +those processes have received $\Proposal$ for $v$ and $2f+1$ $\Prevote$ +messages for $id(v)$ before time $t_2$. By the \emph{Gossip communication} +property, all correct processes will receive those messages by time $t_2 + +\Delta$, and will send $\Precommit$ messages for $id(v)$. Note that even if +some correct processes were at time $t_2$ in a round smaller than $r$, by the +rule at line~\ref{line:tab:skipRounds} they will enter round $r$ by time $t_2 + +\Delta$. Therefore, by time $t_2 + 2\Delta$, all correct processes will +receive $\Proposal$ for $v$ and $2f+1$ $\Precommit$ messages for $id(v)$. So if +$\timeoutPrecommit(r) > 2\Delta$, all correct processes will decide before the +timeout expires. \end{proof} + + +\begin{lemma} \label{lemma:validValue} If a correct process $p$ locks a value + $v$ at time $t_0 > GST$ in some round $r$ ($lockedValue = v$ and + $lockedRound = r$) and $\timeoutPrecommit(r) > 2\Delta$, then all correct + processes set $validValue$ to $v$ and $validRound$ to $r$ before starting + round $r+1$. \end{lemma} + +\begin{proof} In order to prove this Lemma, we need to prove that if the + process $p$ locks a value $v$ at time $t_0$, then no correct process will + leave round $r$ before time $t_0 + \Delta$ (unless it has already set + $validValue$ to $v$ and $validRound$ to $r$). It is sufficient to prove + this, since by the \emph{Gossip communication} property the messages that + $p$ received at time $t_0$ and that triggered rule at + line~\ref{line:tab:recvPrevote} will be received by time $t_0 + \Delta$ by + all correct processes, so all correct processes that are still in round $r$ + will set $validValue$ to $v$ and $validRound$ to $r$ (by the rule at + line~\ref{line:tab:recvPrevote}). To prove this, we need to compute the + earliest point in time a correct process could leave round $r$ without + updating $validValue$ to $v$ and $validRound$ to $r$ (we denote this time + with $t_1$). The Lemma is correct if $t_0 + \Delta < t_1$. + +If the process $p$ locks a value $v$ at time $t_0$, this implies that $p$ +received the valid $\Proposal$ message for $v$ and $2f+1$ +$\li{\Prevote,h,r,id(v)}$ at time $t_0$. At least $f+1$ of those messages are +sent by correct processes. Let's denote this set of correct processes as $C$. By +Lemma~\ref{lemma:majority-intersection} any set of $2f+1$ $\Prevote$ messages +in round $r$ contains at least a single message from the set $C$. + +Let's denote as time $t$ the earliest point in time a correct process, $c_1$, triggered +$\timeoutPrevote(r)$. This implies that $c_1$ received $2f+1$ $\Prevote$ messages +(see the rule at line \ref{line:tab:recvAny2/3Prevote}), where at least one of +those messages was sent by a process $c_2$ from the set $C$. Therefore, process +$c_2$ had received $\Proposal$ message before time $t$. By the \emph{Gossip +communication} property, all correct processes will receive $\Proposal$ and +$2f+1$ $\Prevote$ messages for round $r$ by time $t+\Delta$. The latest point +in time $p$ will trigger $\timeoutPrevote(r)$ is $t+\Delta$\footnote{Note that +even if $p$ was in smaller round at time $t$ it will start round $r$ by time +$t+\Delta$.}. So the latest point in time $p$ can lock the value $v$ in +round $r$ is $t_0 = t+\Delta+\timeoutPrevote(r)$ (as at this point +$\timeoutPrevote(r)$ expires, so a process sends $\Precommit$ $\nil$ and updates +$step$ to $\precommit$, see line \ref{line:tab:onTimeoutPrevote}). + +Note that according to the Algorithm \ref{alg:tendermint}, a correct process +can not send a $\Precommit$ message before receiving $2f+1$ $\Prevote$ +messages. Therefore, no correct process can send a $\Precommit$ message in +round $r$ before time $t$. If a correct process sends a $\Precommit$ message +for $\nil$, it implies that it has waited for the full duration of +$\timeoutPrevote(r)$ (see line +\ref{line:tab:precommit-nil-onTimeout})\footnote{The other case in which a +correct process $\Precommit$ for $\nil$ is after receiving $2f+1$ $Prevote$ for +$\nil$ messages, see the line \ref{line:tab:precommit-v-1}. By +Lemma~\ref{lemma:majority-intersection}, this is not possible in round $r$.}. +Therefore, no correct process can send $\Precommit$ for $\nil$ before time $t + +\timeoutPrevote(r)$ (*). + +A correct process $q$ that enters round $r+1$ must wait (i) $\timeoutPrecommit(r)$ +(see line \ref{line:tab:nextRound}) or (ii) receiving $f+1$ messages from the +round $r+1$ (see the line \ref{line:tab:skipRounds}). In the former case, $q$ +receives $2f+1$ $\Precommit$ messages before starting $\timeoutPrecommit(r)$. If +at least a single $\Precommit$ message from a correct process (at least $f+1$ +voting power equivalent of those messages is sent by correct processes) is for +$\nil$, then $q$ cannot start round $r+1$ before time $t_1 = t + +\timeoutPrevote(r) + \timeoutPrecommit(r)$ (see (*)). Therefore in this case we have: +$t_0 + \Delta < t_1$, i.e., $t+2\Delta+\timeoutPrevote(r) < t + \timeoutPrevote(r) + +\timeoutPrecommit(r)$, and this is true whenever $\timeoutPrecommit(r) > 2\Delta$, so +Lemma holds in this case. + +If in the set of $2f+1$ $\Precommit$ messages $q$ receives, there is at least a +single $\Precommit$ for $id(v)$ message from a correct process $c$, then $q$ +can start the round $r+1$ the earliest at time $t_1 = t+\timeoutPrecommit(r)$. In +this case, by the \emph{Gossip communication} property, all correct processes +will receive $\Proposal$ and $2f+1$ $\Prevote$ messages (that $c$ received +before time $t$) the latest at time $t+\Delta$. Therefore, $q$ will set +$validValue$ to $v$ and $validRound$ to $r$ the latest at time $t+\Delta$. As +$t+\Delta < t+\timeoutPrecommit(r)$, whenever $\timeoutPrecommit(r) > \Delta$, the +Lemma holds also in this case. + +In case (ii), $q$ received at least a single message from a correct process $c$ +from the round $r+1$. The earliest point in time $c$ could have started round +$r+1$ is $t+\timeoutPrecommit(r)$ in case it received a $\Precommit$ message for +$v$ from some correct process in the set of $2f+1$ $\Precommit$ messages it +received. The same reasoning as above holds also in this case, so $q$ set +$validValue$ to $v$ and $validRound$ to $r$ the latest by time $t+\Delta$. As +$t+\Delta < t+\timeoutPrecommit(r)$, whenever $\timeoutPrecommit(r) > \Delta$, the +Lemma holds also in this case. \end{proof} + +\begin{lemma} \label{lemma:agreement} Algorithm~\ref{alg:tendermint} satisfies +Termination. \end{lemma} + +\begin{proof} Lemma~\ref{lemma:round-synchronisation} defines a scenario in + which all correct processes decide. We now prove that within a bounded + duration after GST such a scenario will unfold. Let's assume that at time + $GST$ the highest round started by a correct process is $r_0$, and that + there exists a correct process $p$ such that the following holds: for every + correct process $c$, $lockedRound_c \le validRound_p$. Furthermore, we + assume that $p$ will be the proposer in some round $r_1 > r$ (this is + ensured by the $\coord$ function). + +We have two cases to consider. In the first case, for all rounds $r \ge r_0$ +and $r < r_1$, no correct process locks a value (set $lockedRound$ to $r$). So +in round $r_1$ we have the scenario from the +Lemma~\ref{lemma:round-synchronisation}, so all correct processes decides in +round $r_1$. + +In the second case, a correct process locks a value $v$ in round $r_2$, where +$r_2 \ge r_0$ and $r_2 < r_1$. Let's assume that $r_2$ is the highest round +before $r_1$ in which some correct process $q$ locks a value. By Lemma +\ref{lemma:validValue} at the end of round $r_2$ the following holds for all +correct processes $c$: $validValue_c = lockedValue_q$ and $validRound_c = r_2$. +Then in round $r_1$, the conditions for the +Lemma~\ref{lemma:round-synchronisation} holds, so all correct processes decide. +\end{proof} + diff --git a/spec/consensus/consensus-paper/rounddiag.sty b/spec/consensus/consensus-paper/rounddiag.sty new file mode 100644 index 0000000..499e8eb --- /dev/null +++ b/spec/consensus/consensus-paper/rounddiag.sty @@ -0,0 +1,62 @@ +% ROUNDDIAG STYLE +% for LaTeX version 2e +% by -- 2008 Martin Hutle +% +% This style file is free software; you can redistribute it and/or +% modify it under the terms of the GNU Lesser General Public +% License as published by the Free Software Foundation; either +% version 2 of the License, or (at your option) any later version. +% +% This style file is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +% Lesser General Public License for more details. +% +% You should have received a copy of the GNU Lesser General Public +% License along with this style file; if not, write to the +% Free Software Foundation, Inc., 59 Temple Place - Suite 330, +% Boston, MA 02111-1307, USA. +% +\NeedsTeXFormat{LaTeX2e} +\ProvidesPackage{rounddiag} +\typeout{Document Style `rounddiag' - provides simple round diagrams} +% +\RequirePackage{ifthen} +\RequirePackage{calc} +\RequirePackage{tikz} + +\def\rdstretch{3} + +\tikzstyle{msg}=[->,thick,>=latex] +\tikzstyle{rndline}=[dotted] +\tikzstyle{procline}=[dotted] + +\newenvironment{rounddiag}[2]{ +\begin{center} +\begin{tikzpicture} +\foreach \i in {1,...,#1}{ + \draw[procline] (0,#1-\i) node[xshift=-1em]{$p_{\i}$} -- (#2*\rdstretch+1,#1-\i); +} +\foreach \i in {0,...,#2}{ + \draw[rndline] (\i*\rdstretch+0.5,0) -- (\i*\rdstretch+0.5,#1-1); +} +\newcommand{\rdat}[2]{ + (##2*\rdstretch+0.5,#1-##1) +}% +\newcommand{\round}[2]{% + \def\rdround{##1} + \ifthenelse{\equal{##2}{}}{}{ + \node[yshift=-1em] at ({##1*\rdstretch+0.5-0.5*\rdstretch},0) {##2}; + } +}% +\newcommand{\rdmessage}[3]{\draw[msg] + (\rdround*\rdstretch-\rdstretch+0.5,#1-##1) -- node[yshift=1.2ex]{##3} + (\rdround*\rdstretch+0.5,#1-##2);}% +\newcommand{\rdalltoall}{% + \foreach \i in {1,...,#1}{ + \foreach \j in {1,...,#1}{ + { \rdmessage{\i}{\j}{}}}}}% +}{% +\end{tikzpicture} +\end{center} +} diff --git a/spec/consensus/consensus-paper/technote.sty b/spec/consensus/consensus-paper/technote.sty new file mode 100644 index 0000000..ba2b9fc --- /dev/null +++ b/spec/consensus/consensus-paper/technote.sty @@ -0,0 +1,118 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesPackage{technote}[2007/11/09] +\typeout{Template for quick notes with some useful definitions} + +\RequirePackage{ifthen} +\RequirePackage{calc} +\RequirePackage{amsmath,amssymb,amsthm} +\RequirePackage{epsfig} +\RequirePackage{algorithm} +\RequirePackage[noend]{algorithmicplus} + +\newboolean{technote@noedit} +\setboolean{technote@noedit}{false} +\DeclareOption{noedit}{\setboolean{technote@noedit}{true}} + +\newcounter{technote@lang} +\setcounter{technote@lang}{0} +\DeclareOption{german}{\setcounter{technote@lang}{1}} +\DeclareOption{french}{\setcounter{technote@lang}{2}} + +\DeclareOption{fullpage}{ +\oddsidemargin -10mm % Margin on odd side pages (default=0mm) +\evensidemargin -10mm % Margin on even side pages (default=0mm) +\topmargin -10mm % Top margin space (default=16mm) +\headheight \baselineskip % Height of headers (default=0mm) +\headsep \baselineskip % Separation spc btw header and text (d=0mm) +\footskip 30pt % Separation spc btw text and footer (d=30pt) +\textheight 230mm % Total text height (default=200mm) +\textwidth 180mm % Total text width (default=160mm) +} + +\renewcommand{\algorithmiccomment}[1]{\hfill/* #1 */} +\renewcommand{\algorithmiclnosize}{\scriptsize} + +\newboolean{technote@truenumbers} +\setboolean{technote@truenumbers}{false} +\DeclareOption{truenumbers}{\setboolean{technote@truenumbers}{true}} + +\ProcessOptions + +\newcommand{\N}{\ifthenelse{\boolean{technote@truenumbers}}% + {\mbox{\rm I\hspace{-.5em}N}}% + {\mathbb{N}}} + +\newcommand{\R}{\ifthenelse{\boolean{technote@truenumbers}}% + {\mbox{\rm I\hspace{-.2em}R}}% + {\mathbb{R}}} + +\newcommand{\Z}{\mathbb{Z}} + +\newcommand{\set}[1]{\left\{#1\right\}} +\newcommand{\mathsc}[1]{\mbox{\sc #1}} +\newcommand{\li}[1]{\langle#1\rangle} +\newcommand{\st}{\;s.t.\;} +\newcommand{\Real}{\R} +\newcommand{\Natural}{\N} +\newcommand{\Integer}{\Z} + +% edit commands +\newcommand{\newedit}[2]{ + \newcommand{#1}[2][default]{% + \ifthenelse{\boolean{technote@noedit}}{}{ + \par\vspace{2mm} + \noindent + \begin{tabular}{|l|}\hline + \parbox{\linewidth-\tabcolsep*2}{{\bf #2:}\hfill\ifthenelse{\equal{##1}{default}}{}{##1}}\\\hline + \parbox{\linewidth-\tabcolsep*2}{\rule{0pt}{5mm}##2\rule[-2mm]{0pt}{2mm}}\\\hline + \end{tabular} + \par\vspace{2mm} + } + } +} + +\newedit{\note}{Note} +\newedit{\comment}{Comment} +\newedit{\question}{Question} +\newedit{\content}{Content} +\newedit{\problem}{Problem} + +\newcommand{\mnote}[1]{\marginpar{\scriptsize\it + \begin{minipage}[t]{0.8 in} + \raggedright #1 + \end{minipage}}} + +\newcommand{\Insert}[1]{\underline{#1}\marginpar{$|$}} + +\newcommand{\Delete}[1]{\marginpar{$|$} +} + +% lemma, theorem, etc. +\newtheorem{lemma}{Lemma} +\newtheorem{proposition}{Proposition} +\newtheorem{theorem}{Theorem} +\newtheorem{corollary}{Corollary} +\newtheorem{assumption}{Assumption} +\newtheorem{definition}{Definition} + +\gdef\op|{\,|\;} +\gdef\op:{\,:\;} +\newcommand{\assign}{\leftarrow} +\newcommand{\inc}[1]{#1 \assign #1 + 1} +\newcommand{\isdef}{:=} + +\newcommand{\ident}[1]{\mathit{#1}} +\def\newident#1{\expandafter\def\csname #1\endcsname{\ident{#1}}} + +\newcommand{\eg}{{\it e.g.}} +\newcommand{\ie}{{\it i.e.}} +\newcommand{\apriori}{{\it apriori}} +\newcommand{\etal}{{\it et al.}} + +\newcommand\ps@technote{% + \renewcommand\@oddhead{\theheader}% + \let\@evenhead\@oddhead + \renewcommand\@evenfoot + {\hfil\normalfont\textrm{\thepage}\hfil}% + \let\@oddfoot\@evenfoot +} diff --git a/spec/consensus/consensus.md b/spec/consensus/consensus.md new file mode 100644 index 0000000..7cf3223 --- /dev/null +++ b/spec/consensus/consensus.md @@ -0,0 +1,350 @@ +--- +order: 1 +--- +# Byzantine Consensus Algorithm + +## Terms + +- The network is composed of optionally connected _nodes_. Nodes + directly connected to a particular node are called _peers_. +- The consensus process in deciding the next block (at some _height_ + `H`) is composed of one or many _rounds_. +- `NewHeight`, `Propose`, `Prevote`, `Precommit`, and `Commit` + represent state machine states of a round. (aka `RoundStep` or + just "step"). +- A node is said to be _at_ a given height, round, and step, or at + `(H,R,S)`, or at `(H,R)` in short to omit the step. +- To _prevote_ or _precommit_ something means to broadcast a prevote + or precommit [vote](https://github.com/cometbft/cometbft/blob/af3bc47df982e271d4d340a3c5e0d773e440466d/types/vote.go#L50) + for something. +- A vote _at_ `(H,R)` is a vote signed with the bytes for `H` and `R` + included in its [sign-bytes](../core/data_structures.md#vote). +- _+2/3_ is short for "more than 2/3" +- _1/3+_ is short for "1/3 or more" +- A set of +2/3 of prevotes for a particular block or `` at + `(H,R)` is called a _proof-of-lock-change_ or _PoLC_ for short. + +## State Machine Overview + +At each height of the blockchain a round-based protocol is run to +determine the next block. Each round is composed of three _steps_ +(`Propose`, `Prevote`, and `Precommit`), along with two special steps +`Commit` and `NewHeight`. + +In the optimal scenario, the order of steps is: + +```md +NewHeight -> (Propose -> Prevote -> Precommit)+ -> Commit -> NewHeight ->... +``` + +The sequence `(Propose -> Prevote -> Precommit)` is called a _round_. +There may be more than one round required to commit a block at a given +height. Examples for why more rounds may be required include: + +- The designated proposer was not online. +- The block proposed by the designated proposer was not valid. +- The block proposed by the designated proposer did not propagate + in time. +- The block proposed was valid, but +2/3 of prevotes for the proposed + block were not received in time for enough validator nodes by the + time they reached the `Precommit` step. Even though +2/3 of prevotes + are necessary to progress to the next step, at least one validator + may have voted `` or maliciously voted for something else. +- The block proposed was valid, and +2/3 of prevotes were received for + enough nodes, but +2/3 of precommits for the proposed block were not + received for enough validator nodes. + +Some of these problems are resolved by moving onto the next round & +proposer. Others are resolved by increasing certain round timeout +parameters over each successive round. + +## State Machine Diagram + +```md + +-------------------------------------+ + v |(Wait til `CommmitTime+timeoutCommit`) + +-----------+ +-----+-----+ + +----------> | Propose +--------------+ | NewHeight | + | +-----------+ | +-----------+ + | | ^ + |(Else, after timeoutPrecommit) v | ++-----+-----+ +-----------+ | +| Precommit | <------------------------+ Prevote | | ++-----+-----+ +-----------+ | + |(When +2/3 Precommits for block found) | + v | ++--------------------------------------------------------------------+ +| Commit | +| | +| * Set CommitTime = now; | +| * Wait for block, then stage/save/commit block; | ++--------------------------------------------------------------------+ +``` + +# Background Gossip + +A node may not have a corresponding validator private key, but it +nevertheless plays an active role in the consensus process by relaying +relevant meta-data, proposals, blocks, and votes to its peers. A node +that has the private keys of an active validator and is engaged in +signing votes is called a _validator-node_. All nodes (not just +validator-nodes) have an associated state (the current height, round, +and step) and work to make progress. + +Between two nodes there exists a `Connection`, and multiplexed on top of +this connection are fairly throttled `Channel`s of information. An +epidemic gossip protocol is implemented among some of these channels to +bring peers up to speed on the most recent state of consensus. For +example, + +- Nodes gossip `PartSet` parts of the current round's proposer's + proposed block. A LibSwift inspired algorithm is used to quickly + broadcast blocks across the gossip network. +- Nodes gossip prevote/precommit votes. A node `NODE_A` that is ahead + of `NODE_B` can send `NODE_B` prevotes or precommits for `NODE_B`'s + current (or future) round to enable it to progress forward. +- Nodes gossip prevotes for the proposed PoLC (proof-of-lock-change) + round if one is proposed. +- Nodes gossip to nodes lagging in blockchain height with block + [commits](https://github.com/cometbft/cometbft/blob/af3bc47df982e271d4d340a3c5e0d773e440466d/types/block.go#L738) + for older blocks. +- Nodes opportunistically gossip `ReceivedVote` messages to hint peers what + votes it already has. +- Nodes broadcast their current state to all neighboring peers. (but + is not gossiped further) + +There's more, but let's not get ahead of ourselves here. + +## Proposals + +A proposal is signed and published by the designated proposer at each +round. The proposer is chosen by a deterministic and non-choking round +robin selection algorithm that selects proposers in proportion to their +voting power (see +[implementation](https://github.com/cometbft/cometbft/blob/af3bc47df982e271d4d340a3c5e0d773e440466d/types/validator_set.go#L51)). + +A proposal at `(H,R)` is composed of a block and an optional latest +`PoLC-Round < R` which is included iff the proposer knows of one. This +hints the network to allow nodes to unlock (when safe) to ensure the +liveness property. + +## State Machine Spec + +### Propose Step (height:H,round:R) + +Upon entering `Propose`: + +- The designated proposer proposes a block at `(H,R)`. + +The `Propose` step ends: + +- After `timeoutProposeR` after entering `Propose`. --> goto + `Prevote(H,R)` +- After receiving proposal block and all prevotes at `PoLC-Round`. --> + goto `Prevote(H,R)` +- After [common exit conditions](#common-exit-conditions) + +### Prevote Step (height:H,round:R) + +Upon entering `Prevote`, each validator broadcasts its prevote vote. + +- First, if the validator is locked on a block since `LastLockRound` + but now has a PoLC for something else at round `PoLC-Round` where + `LastLockRound < PoLC-Round < R`, then it unlocks. +- If the validator is still locked on a block, it prevotes that. +- Else, if the proposed block from `Propose(H,R)` is good, it + prevotes that. +- Else, if the proposal is invalid or wasn't received on time, it + prevotes ``. + +The `Prevote` step ends: + +- After +2/3 prevotes for a particular block or ``. -->; goto + `Precommit(H,R)` +- After `timeoutPrevote` after receiving any +2/3 prevotes. --> goto + `Precommit(H,R)` +- After [common exit conditions](#common-exit-conditions) + +### Precommit Step (height:H,round:R) + +Upon entering `Precommit`, each validator broadcasts its precommit vote. + +- If the validator has a PoLC at `(H,R)` for a particular block `B`, it + (re)locks (or changes lock to) and precommits `B` and sets + `LastLockRound = R`. +- Else, if the validator has a PoLC at `(H,R)` for ``, it unlocks + and precommits ``. +- Else, it keeps the lock unchanged and precommits ``. + +A precommit for `` means "I didn’t see a PoLC for this round, but I +did get +2/3 prevotes and waited a bit". + +The Precommit step ends: + +- After +2/3 precommits for ``. --> goto `Propose(H,R+1)` +- After `timeoutPrecommit` after receiving any +2/3 precommits. --> goto + `Propose(H,R+1)` +- After [common exit conditions](#common-exit-conditions) + +### Common exit conditions + +- After +2/3 precommits for a particular block. --> goto + `Commit(H)` +- After any +2/3 prevotes received at `(H,R+x)`. --> goto + `Prevote(H,R+x)` +- After any +2/3 precommits received at `(H,R+x)`. --> goto + `Precommit(H,R+x)` + +### Commit Step (height:H) + +- Set `CommitTime = now()` +- Wait until block is received. --> goto `NewHeight(H+1)` + +### NewHeight Step (height:H) + +- Move `Precommits` to `LastCommit` and increment height. +- Set `StartTime = CommitTime+timeoutCommit` +- Wait until `StartTime` to receive straggler commits. --> goto + `Propose(H,0)` + +## Proofs + +### Proof of Safety + +Assume that at most -1/3 of the voting power of validators is byzantine. +If a validator commits block `B` at round `R`, it's because it saw +2/3 +of precommits at round `R`. This implies that 1/3+ of honest nodes are +still locked at round `R' > R`. These locked validators will remain +locked until they see a PoLC at `R' > R`, but this won't happen because +1/3+ are locked and honest, so at most -2/3 are available to vote for +anything other than `B`. + +### Proof of Liveness + +If 1/3+ honest validators are locked on two different blocks from +different rounds, a proposers' `PoLC-Round` will eventually cause nodes +locked from the earlier round to unlock. Eventually, the designated +proposer will be one that is aware of a PoLC at the later round. Also, +`timeoutProposalR` increments with round `R`, while the size of a +proposal are capped, so eventually the network is able to "fully gossip" +the whole proposal (e.g. the block & PoLC). + +### Proof of Fork Accountability + +Define the JSet (justification-vote-set) at height `H` of a validator +`V1` to be all the votes signed by the validator at `H` along with +justification PoLC prevotes for each lock change. For example, if `V1` +signed the following precommits: `Precommit(B1 @ round 0)`, +`Precommit( @ round 1)`, `Precommit(B2 @ round 4)` (note that no +precommits were signed for rounds 2 and 3, and that's ok), +`Precommit(B1 @ round 0)` must be justified by a PoLC at round 0, and +`Precommit(B2 @ round 4)` must be justified by a PoLC at round 4; but +the precommit for `` at round 1 is not a lock-change by definition +so the JSet for `V1` need not include any prevotes at round 1, 2, or 3 +(unless `V1` happened to have prevoted for those rounds). + +Further, define the JSet at height `H` of a set of validators `VSet` to +be the union of the JSets for each validator in `VSet`. For a given +commit by honest validators at round `R` for block `B` we can construct +a JSet to justify the commit for `B` at `R`. We say that a JSet +_justifies_ a commit at `(H,R)` if all the committers (validators in the +commit-set) are each justified in the JSet with no duplicitous vote +signatures (by the committers). + +- **Lemma**: When a fork is detected by the existence of two + conflicting [commits](../core/data_structures.md#commit), the + union of the JSets for both commits (if they can be compiled) must + include double-signing by at least 1/3+ of the validator set. + **Proof**: The commit cannot be at the same round, because that + would immediately imply double-signing by 1/3+. Take the union of + the JSets of both commits. If there is no double-signing by at least + 1/3+ of the validator set in the union, then no honest validator + could have precommitted any different block after the first commit. + Yet, +2/3 did. Reductio ad absurdum. + +As a corollary, when there is a fork, an external process can determine +the blame by requiring each validator to justify all of its round votes. +Either we will find 1/3+ who cannot justify at least one of their votes, +and/or, we will find 1/3+ who had double-signed. + +### Alternative algorithm + +Alternatively, we can take the JSet of a commit to be the "full commit". +That is, if light clients and validators do not consider a block to be +committed unless the JSet of the commit is also known, then we get the +desirable property that if there ever is a fork (e.g. there are two +conflicting "full commits"), then 1/3+ of the validators are immediately +punishable for double-signing. + +There are many ways to ensure that the gossip network efficiently share +the JSet of a commit. One solution is to add a new message type that +tells peers that this node has (or does not have) a +2/3 majority for B +(or) at (H,R), and a bitarray of which votes contributed towards that +majority. Peers can react by responding with appropriate votes. + +We will implement such an algorithm for the next iteration of the +consensus protocol. + +Other potential improvements include adding more data in votes such as +the last known PoLC round that caused a lock change, and the last voted +round/step (or, we may require that validators not skip any votes). This +may make JSet verification/gossip logic easier to implement. + +### Censorship Attacks + +Due to the definition of a block +[commit](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/core/validators.md), any 1/3+ coalition of +validators can halt the blockchain by not broadcasting their votes. Such +a coalition can also censor particular transactions by rejecting blocks +that include these transactions, though this would result in a +significant proportion of block proposals to be rejected, which would +slow down the rate of block commits of the blockchain, reducing its +utility and value. The malicious coalition might also broadcast votes in +a trickle so as to grind blockchain block commits to a near halt, or +engage in any combination of these attacks. + +If a global active adversary were also involved, it can partition the +network in such a way that it may appear that the wrong subset of +validators were responsible for the slowdown. This is not just a +limitation of Tendermint, but rather a limitation of all consensus +protocols whose network is potentially controlled by an active +adversary. + +### Overcoming Forks and Censorship Attacks + +For these types of attacks, a subset of the validators through external +means should coordinate to sign a reorg-proposal that chooses a fork +(and any evidence thereof) and the initial subset of validators with +their signatures. Validators who sign such a reorg-proposal forego its +collateral on all other forks. Clients should verify the signatures on +the reorg-proposal, verify any evidence, and make a judgement or prompt +the end-user for a decision. For example, a phone wallet app may prompt +the user with a security warning, while a refrigerator may accept any +reorg-proposal signed by +1/2 of the original validators. + +No non-synchronous Byzantine fault-tolerant algorithm can come to +consensus when 1/3+ of validators are dishonest, yet a fork assumes that +1/3+ of validators have already been dishonest by double-signing or +lock-changing without justification. So, signing the reorg-proposal is a +coordination problem that cannot be solved by any non-synchronous +protocol (i.e. automatically, and without making assumptions about the +reliability of the underlying network). It must be provided by means +external to the weakly-synchronous Tendermint consensus algorithm. For +now, we leave the problem of reorg-proposal coordination to human +coordination via internet media. Validators must take care to ensure +that there are no significant network partitions, to avoid situations +where two conflicting reorg-proposals are signed. + +Assuming that the external coordination medium and protocol is robust, +it follows that forks are less of a concern than [censorship +attacks](#censorship-attacks). + +### Canonical vs subjective commit + +We distinguish between "canonical" and "subjective" commits. A subjective commit is what +each validator sees locally when they decide to commit a block. The canonical commit is +what is included by the proposer of the next block in the `LastCommit` field of +the block. This is what makes it canonical and ensures every validator agrees on the canonical commit, +even if it is different from the +2/3 votes a validator has seen, which caused the validator to +commit the respective block. Each block contains a canonical +2/3 commit for the previous +block. diff --git a/spec/consensus/creating-proposal.md b/spec/consensus/creating-proposal.md new file mode 100644 index 0000000..7840ef3 --- /dev/null +++ b/spec/consensus/creating-proposal.md @@ -0,0 +1,61 @@ +--- +order: 2 +--- +# Creating a proposal + +A block consists of a header, transactions, votes (the commit), +and a list of evidence of malfeasance (eg. signing conflicting votes). + +Outstanding evidence items get priority over outstanding transactions in the mempool. +All in all, the block MUST NOT exceed `ConsensusParams.Block.MaxBytes`, +or 100MB if `ConsensusParams.Block.MaxBytes == -1`. + +## Reaping transactions from the mempool + +When we reap transactions from the mempool, we calculate maximum data +size by subtracting maximum header size (`MaxHeaderBytes`), the maximum +protobuf overhead for a block (`MaxOverheadForBlock`), the size of +the last commit (if present) and evidence (if present). While reaping +we account for protobuf overhead for each transaction. + +```go +func MaxDataBytes(maxBytes, evidenceBytes int64, valsCount int) int64 { + return maxBytes - + MaxOverheadForBlock - + MaxHeaderBytes - + MaxCommitBytes(valsCount) - + evidenceBytes +} +``` + +If `ConsensusParams.Block.MaxBytes == -1`, we reap *all* outstanding transactions from the mempool + +## Preparing the proposal + +Once the transactions have been reaped from the mempool according to the rules described above, +CometBFT calls `PrepareProposal` to the application with the transaction list that has just been reaped. +As part of this call the application can remove, add, or reorder transactions in the transaction list. + +The `RequestPrepareProposal` contains two important fields: + +* `MaxTxBytes`, which contains the value returned by `MaxDataBytes` described above. + The application MUST NOT return a list of transactions whose size exceeds this number. +* `Txs`, which contains the list of reaped transactions. + +For more details on `PrepareProposal`, please see the +[relevant part of the spec](../abci/abci%2B%2B_methods.md#prepareproposal) + +## Validating transactions in the mempool + +Before we accept a transaction in the mempool, we check if its size is no more +than {MaxDataSize}. {MaxDataSize} is calculated using the same formula as +above, except we assume there is no evidence. + +```go +func MaxDataBytesNoEvidence(maxBytes int64, valsCount int) int64 { + return maxBytes - + MaxOverheadForBlock - + MaxHeaderBytes - + MaxCommitBytes(valsCount) +} +``` diff --git a/spec/consensus/evidence.md b/spec/consensus/evidence.md new file mode 100644 index 0000000..e912b33 --- /dev/null +++ b/spec/consensus/evidence.md @@ -0,0 +1,203 @@ +--- +order: 4 +--- + +# Evidence + +Evidence is an important component of CometBFT's security model. Whilst the core +consensus protocol provides correctness gaurantees for state machine replication +that can tolerate less than 1/3 failures, the evidence system looks to detect and +gossip byzantine faults whose combined power is greater than or equal to 1/3. It is worth noting that +the evidence system is designed purely to detect possible attacks, gossip them, +commit them on chain and inform the application running on top of CometBFT. +Evidence in itself does not punish "bad actors", this is left to the discretion +of the application. A common form of punishment is slashing where the validators +that were caught violating the protocol have all or a portion of their voting +power removed. Evidence, given the assumption that 1/3+ of the network is still +byzantine, is susceptible to censorship and should therefore be considered added +security on a "best effort" basis. + +This document walks through the various forms of evidence, how they are detected, +gossiped, verified and committed. + +> NOTE: Evidence here is internal to CometBFT and should not be confused with +> application evidence + +## Detection + +### Equivocation + +Equivocation is the most fundamental of byzantine faults. Simply put, to prevent +replication of state across all nodes, a validator tries to convince some subset +of nodes to commit one block whilst convincing another subset to commit a +different block. This is achieved by double voting (hence +`DuplicateVoteEvidence`). A successful duplicate vote attack requires greater +than 1/3 voting power and a (temporary) network partition between the aforementioned +subsets. This is because in consensus, votes are gossiped around. When a node +observes two conflicting votes from the same peer, it will use the two votes of +evidence and begin gossiping this evidence to other nodes. [Verification](#duplicatevoteevidence) is addressed further down. + +```go +type DuplicateVoteEvidence struct { + VoteA Vote + VoteB Vote + + // and abci specific fields +} +``` + +### Light Client Attacks + +Light clients also comply with the 1/3+ security model, however, by using a +different, more lightweight verification method they are subject to a +different kind of 1/3+ attack whereby the byzantine validators could sign an +alternative light block that the light client will think is valid. Detection, +explained in greater detail +[here](../light-client/detection/detection_003_reviewed.md), involves comparison +with multiple other nodes in the hope that at least one is "honest". An "honest" +node will return a challenging light block for the light client to validate. If +this challenging light block also meets the +[validation criteria](../light-client/verification/verification_001_published.md) +then the light client sends the "forged" light block to the node. +[Verification](#lightclientattackevidence) is addressed further down. + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 + + // and abci specific fields +} +``` + +## Verification + +If a node receives evidence, it will first try to verify it, then persist it. +Evidence of byzantine behavior should only be committed once (uniqueness) and +should be committed within a certain period from the point that it occurred +(timely). Timelines is defined by the `EvidenceParams`: `MaxAgeNumBlocks` and +`MaxAgeDuration`. In Proof of Stake chains where validators are bonded, evidence +age should be less than the unbonding period so validators still can be +punished. Given these two propoerties the following initial checks are made. + +1. Has the evidence expired? This is done by taking the height of the `Vote` + within `DuplicateVoteEvidence` or `CommonHeight` within + `LightClientAttakEvidence`. The evidence height is then used to retrieve the + header and thus the time of the block that corresponds to the evidence. If + `CurrentHeight - MaxAgeNumBlocks > EvidenceHeight` && `CurrentTime - + MaxAgeDuration > EvidenceTime`, the evidence is considered expired and + ignored. + +2. Has the evidence already been committed? The evidence pool tracks the hash of + all committed evidence and uses this to determine uniqueness. If a new + evidence has the same hash as a committed one, the new evidence will be + ignored. + +### DuplicateVoteEvidence + +Valid `DuplicateVoteEvidence` must adhere to the following rules: + +- Validator Address, Height, Round and Type must be the same for both votes + +- BlockID must be different for both votes (BlockID can be for a nil block) + +- Validator must have been in the validator set at that height + +- Vote signature must be correctly signed. This also uses `ChainID` so we know + that the fault occurred on this chain + +### LightClientAttackEvidence + +Valid Light Client Attack Evidence must adhere to the following rules: + +- If the header of the light block is invalid, thus indicating a lunatic attack, + the node must check that they can use `verifySkipping` from their header at + the common height to the conflicting header + +- If the header is valid, then the validator sets are the same and this is + either a form of equivocation or amnesia. We therefore check that 2/3 of the + validator set also signed the conflicting header. + +- The nodes own header at the same height as the conflicting header must have a + different hash to the conflicting header. + +- If the nodes latest header is less in height to the conflicting header, then + the node must check that the conflicting block has a time that is less than + this latest header (This is a forward lunatic attack). + +## Gossiping + +If a node verifies evidence it then broadcasts it to all peers, continously sending +the same evidence once every 10 seconds until the evidence is seen on chain or +expires. + +## Commiting on Chain + +Evidence takes strict priority over regular transactions, thus a block is filled +with evidence first and transactions take up the remainder of the space. To +mitigate the threat of an already punished node from spamming the network with +more evidence, the size of the evidence in a block can be capped by +`EvidenceParams.MaxBytes`. Nodes receiving blocks with evidence will validate +the evidence before sending `Prevote` and `Precommit` votes. The evidence pool +will usually cache verifications so that this process is much quicker. + +## Sending Evidence to the Application + +After evidence is committed, the block is then processed by the block executor +which delivers the evidence to the application via `EndBlock`. Evidence is +stripped of the actual proof, split up per faulty validator and only the +validator, height, time and evidence type is sent. + +```proto +enum EvidenceType { + UNKNOWN = 0; + DUPLICATE_VOTE = 1; + LIGHT_CLIENT_ATTACK = 2; +} + +message Evidence { + EvidenceType type = 1; + // The offending validator + Validator validator = 2 [(gogoproto.nullable) = false]; + // The height when the offense occurred + int64 height = 3; + // The corresponding time where the offense occurred + google.protobuf.Timestamp time = 4 [ + (gogoproto.nullable) = false, (gogoproto.stdtime) = true]; + // Total voting power of the validator set in case the ABCI application does + // not store historical validators. + // https://github.com/tendermint/tendermint/issues/4581 + int64 total_voting_power = 5; +} +``` + +`DuplicateVoteEvidence` and `LightClientAttackEvidence` are self-contained in +the sense that the evidence can be used to derive the `abci.Evidence` that is +sent to the application. Because of this, extra fields are necessary: + +```go +type DuplicateVoteEvidence struct { + VoteA *Vote + VoteB *Vote + + // abci specific information + TotalVotingPower int64 + ValidatorPower int64 + Timestamp time.Time +} + +type LightClientAttackEvidence struct { + ConflictingBlock *LightBlock + CommonHeight int64 + + // abci specific information + ByzantineValidators []*Validator + TotalVotingPower int64 + Timestamp time.Time +} +``` + +These ABCI specific fields don't affect validity of the evidence itself but must +be consistent amongst nodes and agreed upon on chain. If evidence with the +incorrect abci information is sent, a node will create new evidence from it and +replace the ABCI fields with the correct information. diff --git a/spec/consensus/light-client/README.md b/spec/consensus/light-client/README.md new file mode 100644 index 0000000..1dd9a5b --- /dev/null +++ b/spec/consensus/light-client/README.md @@ -0,0 +1,10 @@ +--- +order: 1 +parent: + title: Light Client + order: false +--- + +# Light Client Protocol + +Deprecated, please see [light-client](../../light-client/README.md). diff --git a/spec/consensus/light-client/accountability.md b/spec/consensus/light-client/accountability.md new file mode 100644 index 0000000..28155b5 --- /dev/null +++ b/spec/consensus/light-client/accountability.md @@ -0,0 +1,3 @@ +# Fork accountability + +Deprecated, please see [light-client/accountability](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/accountability). diff --git a/spec/consensus/light-client/assets/light-node-image.png b/spec/consensus/light-client/assets/light-node-image.png new file mode 100644 index 0000000..c3202e5 Binary files /dev/null and b/spec/consensus/light-client/assets/light-node-image.png differ diff --git a/spec/consensus/light-client/detection.md b/spec/consensus/light-client/detection.md new file mode 100644 index 0000000..79bd496 --- /dev/null +++ b/spec/consensus/light-client/detection.md @@ -0,0 +1,3 @@ +# Detection + +Deprecated, please see [light-client/detection](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection). diff --git a/spec/consensus/light-client/verification.md b/spec/consensus/light-client/verification.md new file mode 100644 index 0000000..57d4982 --- /dev/null +++ b/spec/consensus/light-client/verification.md @@ -0,0 +1,3 @@ +# Core Verification + +Deprecated, please see [light-client/verification](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification). diff --git a/spec/consensus/proposer-based-timestamp/README.md b/spec/consensus/proposer-based-timestamp/README.md new file mode 100644 index 0000000..5440586 --- /dev/null +++ b/spec/consensus/proposer-based-timestamp/README.md @@ -0,0 +1,20 @@ +# Proposer-Based Timestamps + +This section describes a version of the Tendermint consensus algorithm, adopted in CometBFT, +which uses proposer-based timestamps. + +## Contents + +- [Proposer-Based Time][main] (entry point) +- [Part I - System Model and Properties][sysmodel] +- [Part II - Protocol Specification][algorithm] +- [TLA+ Specification][proposertla] + + +[algorithm]: ./pbts-algorithm_001_draft.md + +[sysmodel]: ./pbts-sysmodel_001_draft.md + +[main]: ./pbts_001_draft.md + +[proposertla]: ./tla/TendermintPBT_001_draft.tla diff --git a/spec/consensus/proposer-based-timestamp/pbts-algorithm_001_draft.md b/spec/consensus/proposer-based-timestamp/pbts-algorithm_001_draft.md new file mode 100644 index 0000000..36d03ce --- /dev/null +++ b/spec/consensus/proposer-based-timestamp/pbts-algorithm_001_draft.md @@ -0,0 +1,160 @@ +# Proposer-Based Time - Part II + +## Updated Consensus Algorithm + +### Outline + +The algorithm in the [arXiv paper][arXiv] evaluates rules of the received messages without making explicit how these messages are received. In our solution, we will make some message filtering explicit. We will assume that there are message reception steps (where messages are received and possibly stored locally for later evaluation of rules) and processing steps (the latter roughly as described in a way similar to the pseudo code of the arXiv paper). + +In contrast to the original algorithm the field `proposal` in the `PROPOSE` message is a pair `(v, time)`, of the proposed consensus value `v` and the proposed time `time`. + +#### **[PBTS-RECEPTION-STEP.0]** + +In the reception step at process `p` at local time `now_p`, upon receiving a message `m`: + +- if the message `m` is of type `PROPOSE` and satisfies `now_p - PRECISION < m.time < now_p + PRECISION + MSGDELAY`, then mark the message as `timely` + +> if `m` does not satisfy the constraint consider it `untimely` + + +#### **[PBTS-PROCESSING-STEP.0]** + +In the processing step, based on the messages stored, the rules of the algorithms are +executed. Note that the processing step only operates on messages +for the current height. The consensus algorithm rules are defined by the following updates to arXiv paper. + +#### New `StartRound` + +There are two additions + +- in case the proposer's local time is smaller than the time of the previous block, the proposer waits until this is not the case anymore (to ensure the block time is monotonically increasing) +- the proposer sends its time `now_p` as part of its proposal + +We update the timeout for the `PROPOSE` step according to the following reasoning: + +- If a correct proposer needs to wait to make sure its proposed time is larger than the `blockTime` of the previous block, then it sends by realtime `blockTime + ACCURACY` (By this time, its local clock must exceed `blockTime`) +- the receiver will receive a `PROPOSE` message by `blockTime + ACCURACY + MSGDELAY` +- the receiver's local clock will be `<= blockTime + 2 * ACCURACY + MSGDELAY` +- thus when the receiver `p` enters this round it can set its timeout to a value `waitingTime => blockTime + 2 * ACCURACY + MSGDELAY - now_p` + +So we should set the timeout to `max(timeoutPropose(round_p), waitingTime)`. + +> If, in the future, a block delay parameter `BLOCKDELAY` is introduced, this means +that the proposer should wait for `now_p > blockTime + BLOCKDELAY` before sending a `PROPOSE` message. +Also, `BLOCKDELAY` needs to be added to `waitingTime`. + +#### **[PBTS-ALG-STARTROUND.0]** + +```go +function StartRound(round) { + blockTime ← block time of block h_p - 1 + waitingTime ← blockTime + 2 * ACCURACY + MSGDELAY - now_p + round_p ← round + step_p ← propose + if proposer(h_p, round_p) = p { + wait until now_p > blockTime // new wait condition + if validValue_p != nil { + proposal ← (validValue_p, now_p) // added "now_p" + } + else { + proposal ← (getValue(), now_p) // added "now_p" + } + broadcast ⟨PROPOSAL, h_p, round_p, proposal, validRound_p⟩ + } + else { + schedule OnTimeoutPropose(h_p,round_p) to be executed after max(timeoutPropose(round_p), waitingTime) + } +} +``` + +#### New Rule Replacing Lines 22 - 27 + +- a validator prevotes for the consensus value `v` **and** the time `t` +- the code changes as the `PROPOSAL` message carries time (while `lockedValue` does not) + +#### **[PBTS-ALG-UPON-PROP.0]** + +```go +upon timely(⟨PROPOSAL, h_p, round_p, (v,t), −1⟩) from proposer(h_p, round_p) while step_p = propose do { + if valid(v) ∧ (lockedRound_p = −1 ∨ lockedValue_p = v) { + broadcast ⟨PREVOTE, h_p, round_p, id(v,t)⟩ + } + else { + broadcast ⟨PREVOTE, h_p, round_p, nil⟩ + } + step_p ← prevote +} +``` + +#### New Rule Replacing Lines 28 - 33 + +In case consensus is not reached in round 1, in `StartRound` the proposer of future rounds may propose the same value but with a different time. +Thus, the time `tprop` in the `PROPOSAL` message need not match the time `tvote` in the (old) `PREVOTE` messages. +A validator may send `PREVOTE` for the current round as long as the value `v` matches. +This gives the following rule: + +#### **[PBTS-ALG-OLD-PREVOTE.0]** + +```go +upon timely(⟨PROPOSAL, h_p, round_p, (v, tprop), vr⟩) from proposer(h_p, round_p) AND 2f + 1 ⟨PREVOTE, h_p, vr, id((v, tvote)⟩ +while step_p = propose ∧ (vr ≥ 0 ∧ vr < round_p) do { + if valid(v) ∧ (lockedRound_p ≤ vr ∨ lockedValue_p = v) { + broadcast ⟨PREVOTE, h_p, roundp, id(v, tprop)⟩ + } + else { + broadcast ⟨PREVOTE, hp, roundp, nil⟩ + } + step_p ← prevote +} +``` + +#### New Rule Replacing Lines 36 - 43 + +- As above, in the following `(v,t)` is part of the message rather than `v` +- the stored values (i.e., `lockedValue`, `validValue`) do not contain the time + +#### **[PBTS-ALG-NEW-PREVOTE.0]** + +```go +upon timely(⟨PROPOSAL, h_p, round_p, (v,t), ∗⟩) from proposer(h_p, round_p) AND 2f + 1 ⟨PREVOTE, h_p, round_p, id(v,t)⟩ while valid(v) ∧ step_p ≥ prevote for the first time do { + if step_p = prevote { + lockedValue_p ← v + lockedRound_p ← round_p + broadcast ⟨PRECOMMIT, h_p, round_p, id(v,t))⟩ + step_p ← precommit + } + validValue_p ← v + validRound_p ← round_p +} +``` + +#### New Rule Replacing Lines 49 - 54 + +- we decide on `v` as well as on the time from the proposal message +- here we do not care whether the proposal was received timely. + +> In particular we need to take care of the case where the proposer is untimely to one correct validator only. We need to ensure that this validator decides if all decide. + +#### **[PBTS-ALG-DECIDE.0]** + +```go +upon ⟨PROPOSAL, h_p, r, (v,t), ∗⟩ from proposer(h_p, r) AND 2f + 1 ⟨PRECOMMIT, h_p, r, id(v,t)⟩ while decisionp[h_p] = nil do { + if valid(v) { + decision_p [h_p] = (v,t) // decide on time too + h_p ← h_p + 1 + reset lockedRound_p , lockedValue_p, validRound_p and validValue_p to initial values and empty message log + StartRound(0) + } +} +``` + +**All other rules remains unchanged.** + +Back to [main document][main]. + +[main]: ./pbts_001_draft.md + +[arXiv]: https://arxiv.org/abs/1807.04938 + + + diff --git a/spec/consensus/proposer-based-timestamp/pbts-sysmodel_001_draft.md b/spec/consensus/proposer-based-timestamp/pbts-sysmodel_001_draft.md new file mode 100644 index 0000000..d14a048 --- /dev/null +++ b/spec/consensus/proposer-based-timestamp/pbts-sysmodel_001_draft.md @@ -0,0 +1,191 @@ +# Proposer-Based Time - Part I + +## System Model + +### Time and Clocks + +#### **[PBTS-CLOCK-NEWTON.0]** + +There is a reference Newtonian real-time `t` (UTC). + +Every correct validator `V` maintains a synchronized clock `C_V` that ensures: + +#### **[PBTS-CLOCK-PRECISION.0]** + +There exists a system parameter `PRECISION` such that for any two correct validators `V` and `W`, and at any real-time `t`, +`|C_V(t) - C_W(t)| < PRECISION` + + +### Message Delays + +We do not want to interfere with the timing assumptions of Tendermint consensus algorithm. +We will postulate a timing restriction, which, if satisfied, ensures that liveness is preserved. + +In general the local clock may drift from the global time. (It may progress faster, e.g., one second of clock time might take 1.005 seconds of real-time). As a result the local clock and the global clock may be measured in different time units. Usually, the message delay is measured in global clock time units. To estimate the correct local timeout precisely, we would need to estimate the clock time duration of a message delay taking into account the clock drift. For simplicity we ignore this, and directly postulate the message delay assumption in terms of local time. + + +#### **[PBTS-MSG-D.0]** + +There exists a system parameter `MSGDELAY` for message end-to-end delays **counted in clock-time**. + +> Observe that [PBTS-MSG-D.0] imposes constraints on message delays as well as on the clock. + +#### **[PBTS-MSG-FAIR.0]** + +The message end-to-end delay between a correct proposer and a correct validator (for `PROPOSE` messages) is less than `MSGDELAY`. + + +## Problem Statement + +In this section we define the properties of Tendermint consensus algorithm (cf. the [arXiv paper][arXiv]) in this new system model. + +#### **[PBTS-PROPOSE.0]** + +A proposer proposes a pair `(v,t)` of consensus value `v` and time `t`. + +> We then restrict the allowed decisions along the following lines: + +#### **[PBTS-INV-AGREEMENT.0]** + +[Agreement] No two correct validators decide on different values `v`. + +#### **[PBTS-INV-TIME-VAL.0]** + +[Time-Validity] If a correct validator decides on `t` then `t` is "OK" (we will formalize this below), even if up to `2f` validators are faulty. + +However, the properties of Tendermint consensus algorithm are of more interest with respect to the blocks, that is, what is written into a block and when. We therefore, in the following, will give the safety and liveness properties from this block-centric viewpoint. +For this, observe that the time `t` decided at consensus height `k` will be written in the block of height `k+1`, and will be supported by `2f + 1` `PRECOMMIT` messages of the same consensus round `r`. The time written in the block, we will denote by `b.time` (to distinguish it from the term `bfttime` used for median-based time). For this, it is important to have the following consensus algorithm property: + +#### **[PBTS-INV-TIME-AGR.0]** + +[Time-Agreement] If two correct validators decide in the same round, then they decide on the same `t`. + +#### **[PBTS-DECISION-ROUND.0]** + +Note that the relation between consensus decisions, on the one hand, and blocks, on the other hand, is not immediate; in particular if we consider time: In the proposed solution, +as validators may decide in different rounds, they may decide on different times. +The proposer of the next block, may pick a commit (at least `2f + 1` `PRECOMMIT` messages from one round), and thus it picks a decision round that is going to become "canonic". +As a result, the proposer implicitly has a choice of one of the times that belong to rounds in which validators decided. Observe that this choice was implicitly the case already in the median-based `bfttime`. +However, as most consensus instances terminate within one round on the Cosmos hub, this is hardly ever observed in practice. + + + +Finally, observe that the agreement ([Agreement] and [Time-Agreement]) properties are based on the Cosmos security model [CMBC-FM-2THIRDS.0][CMBC-FM-2THIRDS-link] of more than 2/3 correct validators, while [Time-Validity] is based on more than 1/3 correct validators. + +### SAFETY + +Here we will provide specifications that relate local time to block time. However, since we do not assume (by now) that local time is linked to real-time, these specifications also do not provide a relation between block time and real-time. Such properties are given [later](#real-time-safety). + +For a correct validator `V`, let `beginConsensus(V,k)` be the local time when it sets its height to `k`, and let `endConsensus(V,k)` be the time when it sets its height to `k + 1`. + +Let + +- `beginConsensus(k)` be the minimum over `beginConsensus(V,k)`, and +- `last-beginConsensus(k)` be the maximum over `beginConsensus(V,k)`, and +- `endConsensus(k)` the maximum over `endConsensus(V,k)` + +for all correct validators `V`. + +> Observe that `beginConsensus(k) <= last-beginConsensus(k)` and if local clocks are monotonic, then `last-beginConsensus(k) <= endConsensus(k)`. + +#### **[PBTS-CLOCK-GROW.0]** + +We assume that during one consensus instance, local clocks are not set back, in particular for each correct validator `V` and each height `k`, we have `beginConsensus(V,k) < endConsensus(V,k)`. + + +#### **[PBTS-CONSENSUS-TIME-VALID.0]** + +If + +- there is a valid commit `c` for height `k`, and +- `c` contains a `PRECOMMIT` message by at least one correct validator, + +then the time `b.time` in the block `b` that is signed by `c` satisfies + +- `beginConsensus(k) - PRECISION <= b.time < endConsensus(k) + PRECISION + MSGDELAY`. + + +> [PBTS-CONSENSUS-TIME-VALID.0] is based on an analysis where the proposer is faulty (and does does not count towards `beginConsensus(k)` and `endConsensus(k)`), and we estimate the times at which correct validators receive and `accept` the `propose` message. If the proposer is correct we obtain + +#### **[PBTS-CONSENSUS-LIVE-VALID-CORR-PROP.0]** + +If the proposer of round 1 is correct, and + +- [CMBC-FM-2THIRDS.0] holds for a block of height `k - 1`, and +- [PBTS-MSG-FAIR.0], and +- [PBTS-CLOCK-PRECISION.0], and +- [PBTS-CLOCK-GROW.0] (**TODO:** is that enough?) + +then eventually (within bounded time) every correct validator decides in round 1. + +#### **[PBTS-CONSENSUS-SAFE-VALID-CORR-PROP.0]** + +If the proposer of round 1 is correct, and + +- [CMBC-FM-2THIRDS.0] holds for a block of height `k - 1`, and +- [PBTS-MSG-FAIR.0], and +- [PBTS-CLOCK-PRECISION.0], and +- [PBTS-CLOCK-GROW.0] (**TODO:** is that enough?) + +then `beginConsensus_k <= b.time <= last-beginConsensus_k`. + + +> For the above two properties we will assume that a correct proposer `v` sends its `PROPOSAL` at its local time `beginConsensus(v,k)`. + +### LIVENESS + +If + +- [CMBC-FM-2THIRDS.0] holds for a block of height `k - 1`, and +- [PBTS-MSG-FAIR.0], +- [PBTS-CLOCK.0], and +- [PBTS-CLOCK-GROW.0] (**TODO:** is that enough?) + +then eventually there is a valid commit `c` for height `k`. + + +### REAL-TIME SAFETY + +> We want to give a property that can be exploited from the outside, that is, given a block with some time stored in it, what is the estimate at which real-time the block was generated. To do so, we need to link clock-time to real-time; which is not the case with [PBTS-CLOCK.0]. For this, we introduce the following assumption on the clocks: + +#### **[PBTS-CLOCKSYNC-EXTERNAL.0]** + +There is a system parameter `ACCURACY`, such that for all real-times `t` and all correct validators `V`, + +- `| C_V(t) - t | < ACCURACY`. + +> `ACCURACY` is not necessarily visible at the code level. The properties below just show that the smaller +its value, the closer the block time will be to real-time + +#### **[PBTS-CONSENSUS-PTIME.0]** + +LET `m` be a propose message. We consider the following two real-times `proposalTime(m)` and `propRecvTime(m)`: + +- if the proposer is correct and sends `m` at time `t`, we write `proposalTime(m)` for real-time `t`. +- if first correct validator receives `m` at time `t`, we write `propRecvTime(m)` for real-time `t`. + + +#### **[PBTS-CONSENSUS-REALTIME-VALID.0]** + +Let `b` be a block with a valid commit that contains at least one `precommit` message by a correct validator (and `proposalTime` is the time for the height/round `propose` message `m` that triggered the `precommit`). Then: + +`propRecvTime(m) - ACCURACY - PRECISION < b.time < propRecvTime(m) + ACCURACY + PRECISION + MSGDELAY` + + +#### **[PBTS-CONSENSUS-REALTIME-VALID-CORR.0]** + +Let `b` be a block with a valid commit that contains at least one `precommit` message by a correct validator (and `proposalTime` is the time for the height/round `propose` message `m` that triggered the `precommit`). Then, if the proposer is correct: + +`proposalTime(m) - ACCURACY < b.time < proposalTime(m) + ACCURACY` + +> by the algorithm at time `proposalTime(m)` the proposer fixes `m.time <- now_p(proposalTime(m))` + +> "triggered the `PRECOMMIT`" implies that the data in `m` and `b` are "matching", that is, `m` proposed the values that are actually stored in `b`. + +Back to [main document][main]. + +[main]: ./pbts_001_draft.md + +[arXiv]: https://arxiv.org/abs/1807.04938 + +[CMBC-FM-2THIRDS-link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-fm-2thirds1 diff --git a/spec/consensus/proposer-based-timestamp/pbts_001_draft.md b/spec/consensus/proposer-based-timestamp/pbts_001_draft.md new file mode 100644 index 0000000..6507d04 --- /dev/null +++ b/spec/consensus/proposer-based-timestamp/pbts_001_draft.md @@ -0,0 +1,269 @@ +# Proposer-Based Time + +## Current BFTTime + +### Description + +In CometBFT, the first version of how time is computed and stored in a block works as follows: + +- validators send their current local time as part of `precommit` messages +- upon collecting the `precommit` messages that the proposer uses to build a commit to be put in the next block, the proposer computes the `time` of the next block as the median (weighted over voting power) of the times in the `precommit` messages. + +### Analysis + +1. **Fault tolerance.** The computed median time is called [`bfttime`][bfttime] as it is indeed fault-tolerant: if **less than a third** of the validators is faulty (counted in voting power), it is guaranteed that the computed time lies between the minimum and the maximum times sent by correct validators. +1. **Effect of faulty validators.** If more than `1/2` of the voting power (which is in fact more than one third and less than two thirds of the voting power) is held by faulty validators, then the time is under total control of the faulty validators. (This is particularly challenging in the context of [lightclient][lcspec] security.) +1. **Proposer influence on block time.** The proposer of the next block has a degree of freedom in choosing the `bfttime`, since it computes the median time based on the timestamps from `precommit` messages sent by + `2f + 1` correct validators. + 1. If there are `n` different timestamps in the `precommit` messages, the proposer can use any subset of timestamps that add up to `2f + 1` + of the voting power in order to compute the median. + 1. If the validators decide in different rounds, the proposer can decide on which round the median computation is based. +1. **Liveness.** The liveness of the protocol: + 1. does not depend on clock synchronization, + 1. depends on bounded message delays. +1. **Relation to real time.** There is no clock synchronizaton, which implies that there is **no relation** between the computed block `time` and real time. +1. **Aggregate signatures.** As the `precommit` messages contain the local times, all these `precommit` messages typically differ in the time field, which **prevents** the use of aggregate signatures. + +## Suggested Proposer-Based Time + +### Outline + +An alternative approach to time has been discussed: Rather than having the validators send the time in the `precommit` messages, the proposer in the consensus algorithm sends its time in the `propose` message, and the validators locally check whether the time is OK (by comparing to their local clock). + +This proposed solution adds the requirement of having synchronized clocks, and other implicit assumptions. + +### Comparison of the Suggested Method to the Old One + +1. **Fault tolerance.** Maintained in the suggested protocol. +1. **Effect of faulty validators.** Eliminated in the suggested protocol, + that is, the block `time` can be corrupted only in the extreme case when + `>2/3` of the validators are faulty. +1. **Proposer influence on block time.** The proposer of the next block + has less freedom when choosing the block time. + 1. This scenario is eliminated in the suggested protocol, provided that there are `<1/3` faulty validators. + 1. This scenario is still there. +1. **Liveness.** The liveness of the suggested protocol: + 1. depends on the introduced assumptions on synchronized clocks (see below), + 1. still depends on the message delays (unavoidable). +1. **Relation to real time.** We formalize clock synchronization, and obtain a **well-defined relation** between the block `time` and real time. +1. **Aggregate signatures.** The `precommit` messages free of time, which **allows** for aggregate signatures. + +### Protocol Overview + +#### Proposed Time + +We assume that the field `proposal` in the `PROPOSE` message is a pair `(v, time)`, of the proposed consensus value `v` and the proposed time `time`. + +#### Reception Step + +In the reception step at node `p` at local time `now_p`, upon receiving a message `m`: + +- **if** the message `m` is of type `PROPOSE` and satisfies `now_p - PRECISION < m.time < now_p + PRECISION + MSGDELAY`, then mark the message as `timely`. +(`PRECISION` and `MSGDELAY` being system parameters, see [below](#safety-and-liveness)) + +> after the presentation in the dev session, we realized that different semantics for the reception step is closer aligned to the implementation. Instead of dropping propose messages, we keep all of them, and mark timely ones. + +#### Processing Step + +- Start round + + + + + + + + + + + + +
arXiv paperProposer-based time
+ +```go +function StartRound(round) { + round_p ← round + step_p ← propose + if proposer(h_p, round_p) = p { + + + if validValue_p != nil { + + proposal ← validValue_p + } else { + + proposal ← getValue() + } + broadcast ⟨PROPOSAL, h_p, round_p, proposal, validRound_p⟩ + } else { + schedule OnTimeoutPropose(h_p,round_p) to + be executed after timeoutPropose(round_p) + } +} +``` + + + +```go +function StartRound(round) { + round_p ← round + step_p ← propose + if proposer(h_p, round_p) = p { + // new wait condition + wait until now_p > block time of block h_p - 1 + if validValue_p != nil { + // add "now_p" + proposal ← (validValue_p, now_p) + } else { + // add "now_p" + proposal ← (getValue(), now_p) + } + broadcast ⟨PROPOSAL, h_p, round_p, proposal, validRound_p⟩ + } else { + schedule OnTimeoutPropose(h_p,round_p) to + be executed after timeoutPropose(round_p) + } +} +``` + +
+ +- Rule on lines 28-35 + + + + + + + + + + + + +
arXiv paperProposer-based time
+ +```go +upon timely(⟨PROPOSAL, h_p, round_p, v, vr⟩) + from proposer(h_p, round_p) + AND 2f + 1 ⟨PREVOTE, h_p, vr, id(v)⟩ +while step_p = propose ∧ (vr ≥ 0 ∧ vr < round_p) do { + if valid(v) ∧ (lockedRound_p ≤ vr ∨ lockedValue_p = v) { + + broadcast ⟨PREVOTE, h_p, round_p, id(v)⟩ + } else { + broadcast ⟨PREVOTE, hp, round_p, nil⟩ + } +} +``` + + + +```go +upon timely(⟨PROPOSAL, h_p, round_p, (v, tprop), vr⟩) + from proposer(h_p, round_p) + AND 2f + 1 ⟨PREVOTE, h_p, vr, id(v, tvote)⟩ + while step_p = propose ∧ (vr ≥ 0 ∧ vr < round_p) do { + if valid(v) ∧ (lockedRound_p ≤ vr ∨ lockedValue_p = v) { + // send hash of v and tprop in PREVOTE message + broadcast ⟨PREVOTE, h_p, round_p, id(v, tprop)⟩ + } else { + broadcast ⟨PREVOTE, hp, round_p, nil⟩ + } + } +``` + +
+ +- Rule on lines 49-54 + + + + + + + + + + + + +
arXiv paperProposer-based time
+ +```go +upon ⟨PROPOSAL, h_p, r, v, ∗⟩ from proposer(h_p, r) + AND 2f + 1 ⟨PRECOMMIT, h_p, r, id(v)⟩ + while decisionp[h_p] = nil do { + if valid(v) { + + decision_p [h_p] = v + h_p ← h_p + 1 + reset lockedRound_p , lockedValue_p, validRound_p and + validValue_p to initial values and empty message log + StartRound(0) + } + } +``` + + + +```go +upon ⟨PROPOSAL, h_p, r, (v,t), ∗⟩ from proposer(h_p, r) + AND 2f + 1 ⟨PRECOMMIT, h_p, r, id(v,t)⟩ + while decisionp[h_p] = nil do { + if valid(v) { + // decide on time too + decision_p [h_p] = (v,t) + h_p ← h_p + 1 + reset lockedRound_p , lockedValue_p, validRound_p and + validValue_p to initial values and empty message log + StartRound(0) + } + } +``` + +
+ +- Other rules are extended in a similar way, or remain unchanged + +### Property Overview + +#### Safety and Liveness + +For safety (Point 1, Point 2, Point 3i) and liveness (Point 4) we need +the following assumptions: + +- There exists a system parameter `PRECISION` such that for any two correct validators `V` and `W`, and at any real-time `t`, their local times `C_V(t)` and `C_W(t)` differ by less than `PRECISION` time units, +i.e., `|C_V(t) - C_W(t)| < PRECISION` +- The message end-to-end delay between a correct proposer and a correct validator (for `PROPOSE` messages) is less than `MSGDELAY`. + +#### Relation to Real-Time + +For analyzing real-time safety (Point 5), we use a system parameter `ACCURACY`, such that for all real-times `t` and all correct validators `V`, we have `| C_V(t) - t | < ACCURACY`. + +> `ACCURACY` is not necessarily visible at the code level. We might even view `ACCURACY` as variable over time. The smaller it is during a consensus instance, the closer the block time will be to real-time. +> +> Note that `PRECISION` and `MSGDELAY` show up in the code. + +### Detailed Specification + +This specification describes the changes needed to be done to the Tendermint consensus algorithm as described in the [arXiv paper][arXiv] and the simplified specification in [TLA+][tlatender], and makes precise the underlying assumptions and the required properties. + +- [Part I - System Model and Properties][sysmodel] +- [Part II - Protocol specification][algorithm] +- [TLA+ Specification][proposertla] + +[arXiv]: https://arxiv.org/abs/1807.04938 + +[tlatender]: ../../light-client/accountability/README.md + +[bfttime]: ../bft-time.md + +[lcspec]: ../../light-client/README.md + +[algorithm]: ./pbts-algorithm_001_draft.md + +[sysmodel]: ./pbts-sysmodel_001_draft.md + + +[proposertla]: ./tla/TendermintPBT_001_draft.tla diff --git a/spec/consensus/proposer-based-timestamp/tla/TendermintPBT_001_draft.tla b/spec/consensus/proposer-based-timestamp/tla/TendermintPBT_001_draft.tla new file mode 100644 index 0000000..0b65361 --- /dev/null +++ b/spec/consensus/proposer-based-timestamp/tla/TendermintPBT_001_draft.tla @@ -0,0 +1,597 @@ +-------------------- MODULE TendermintPBT_001_draft --------------------------- +(* + A TLA+ specification of a simplified Tendermint consensus algorithm, with added clocks + and proposer-based timestamps. This TLA+ specification extends and modifies + the Tendermint TLA+ specification for fork accountability: + https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/accountability/TendermintAcc_004_draft.tla + + * Version 1. A preliminary specification. + + Zarko Milosevic, Igor Konnov, Informal Systems, 2019-2020. + Ilina Stoilkovska, Josef Widder, Informal Systems, 2021. + *) + +EXTENDS Integers, FiniteSets + +(********************* PROTOCOL PARAMETERS **********************************) +CONSTANTS + Corr, \* the set of correct processes + Faulty, \* the set of Byzantine processes, may be empty + N, \* the total number of processes: correct, defective, and Byzantine + T, \* an upper bound on the number of Byzantine processes + ValidValues, \* the set of valid values, proposed both by correct and faulty + InvalidValues, \* the set of invalid values, never proposed by the correct ones + MaxRound, \* the maximal round number + MaxTimestamp, \* the maximal value of the clock tick + Delay, \* message delay + Precision, \* clock precision: the maximal difference between two local clocks + Accuracy, \* clock accuracy: the maximal difference between a local clock and the real time + Proposer, \* the proposer function from 0..NRounds to 1..N + ClockDrift \* is there clock drift between the local clocks and the global clock + +ASSUME(N = Cardinality(Corr \union Faulty)) + +(*************************** DEFINITIONS ************************************) +AllProcs == Corr \union Faulty \* the set of all processes +Rounds == 0..MaxRound \* the set of potential rounds +Timestamps == 0..MaxTimestamp \* the set of clock ticks +NilRound == -1 \* a special value to denote a nil round, outside of Rounds +NilTimestamp == -1 \* a special value to denote a nil timestamp, outside of Ticks +RoundsOrNil == Rounds \union {NilRound} +Values == ValidValues \union InvalidValues \* the set of all values +NilValue == "None" \* a special value for a nil round, outside of Values +Proposals == Values \X Timestamps +NilProposal == <> +ValuesOrNil == Values \union {NilValue} +Decisions == Values \X Timestamps \X Rounds +NilDecision == <> + + +\* a value hash is modeled as identity +Id(v) == v + +\* The validity predicate +IsValid(v) == v \in ValidValues + +\* the two thresholds that are used in the algorithm +THRESHOLD1 == T + 1 \* at least one process is not faulty +THRESHOLD2 == 2 * T + 1 \* a quorum when having N > 3 * T + +Min(S) == CHOOSE x \in S : \A y \in S : x <= y + +Max(S) == CHOOSE x \in S : \A y \in S : y <= x + +(********************* TYPE ANNOTATIONS FOR APALACHE **************************) +\* the operator for type annotations +a <: b == a + +\* the type of message records +MT == [type |-> STRING, src |-> STRING, round |-> Int, + proposal |-> <>, validRound |-> Int, id |-> <>] + +RP == <> + +\* a type annotation for a message +AsMsg(m) == m <: MT +\* a type annotation for a set of messages +SetOfMsgs(S) == S <: {MT} +\* a type annotation for an empty set of messages +EmptyMsgSet == SetOfMsgs({}) + +SetOfRcvProp(S) == S <: {RP} +EmptyRcvProp == SetOfRcvProp({}) + +SetOfProc(S) == S <: {STRING} +EmptyProcSet == SetOfProc({}) + +(********************* PROTOCOL STATE VARIABLES ******************************) +VARIABLES + round, \* a process round number: Corr -> Rounds + localClock, \* a process local clock: Corr -> Ticks + realTime, \* a reference Newtonian real time + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + decision, \* process decision: Corr -> ValuesOrNil + lockedValue, \* a locked value: Corr -> ValuesOrNil + lockedRound, \* a locked round: Corr -> RoundsOrNil + validValue, \* a valid value: Corr -> ValuesOrNil + validRound \* a valid round: Corr -> RoundsOrNil + +\* book-keeping variables +VARIABLES + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + receivedTimelyProposal, \* used to keep track when a process receives a timely PROPOSAL message, {<>} + inspectedProposal, \* used to keep track when a process tries to receive a message, [Rounds -> <>] + evidence, \* the messages that were used by the correct processes to make transitions + action, \* we use this variable to see which action was taken + beginConsensus, \* the minimum of the local clocks in the initial state, Int + endConsensus, \* the local time when a decision is made, [Corr -> Int] + lastBeginConsensus, \* the maximum of the local clocks in the initial state, Int + proposalTime, \* the real time when a proposer proposes in a round, [Rounds -> Int] + proposalReceivedTime \* the real time when a correct process first receives a proposal message in a round, [Rounds -> Int] + +(* to see a type invariant, check TendermintAccInv3 *) + +\* a handy definition used in UNCHANGED +vars == <> + +(********************* PROTOCOL INITIALIZATION ******************************) +FaultyProposals(r) == + SetOfMsgs([type: {"PROPOSAL"}, src: Faulty, + round: {r}, proposal: Proposals, validRound: RoundsOrNil]) + +AllFaultyProposals == + SetOfMsgs([type: {"PROPOSAL"}, src: Faulty, + round: Rounds, proposal: Proposals, validRound: RoundsOrNil]) + +FaultyPrevotes(r) == + SetOfMsgs([type: {"PREVOTE"}, src: Faulty, round: {r}, id: Proposals]) + +AllFaultyPrevotes == + SetOfMsgs([type: {"PREVOTE"}, src: Faulty, round: Rounds, id: Proposals]) + +FaultyPrecommits(r) == + SetOfMsgs([type: {"PRECOMMIT"}, src: Faulty, round: {r}, id: Proposals]) + +AllFaultyPrecommits == + SetOfMsgs([type: {"PRECOMMIT"}, src: Faulty, round: Rounds, id: Proposals]) + +AllProposals == + SetOfMsgs([type: {"PROPOSAL"}, src: AllProcs, + round: Rounds, proposal: Proposals, validRound: RoundsOrNil]) + +RoundProposals(r) == + SetOfMsgs([type: {"PROPOSAL"}, src: AllProcs, + round: {r}, proposal: Proposals, validRound: RoundsOrNil]) + +BenignRoundsInMessages(msgfun) == + \* the message function never contains a message for a wrong round + \A r \in Rounds: + \A m \in msgfun[r]: + r = m.round + +\* The initial states of the protocol. Some faults can be in the system already. +Init == + /\ round = [p \in Corr |-> 0] + /\ \/ /\ ~ClockDrift + /\ localClock \in [Corr -> 0..Accuracy] + \/ /\ ClockDrift + /\ localClock = [p \in Corr |-> 0] + /\ realTime = 0 + /\ step = [p \in Corr |-> "PROPOSE"] + /\ decision = [p \in Corr |-> NilDecision] + /\ lockedValue = [p \in Corr |-> NilValue] + /\ lockedRound = [p \in Corr |-> NilRound] + /\ validValue = [p \in Corr |-> NilValue] + /\ validRound = [p \in Corr |-> NilRound] + /\ msgsPropose \in [Rounds -> SUBSET AllFaultyProposals] + /\ msgsPrevote \in [Rounds -> SUBSET AllFaultyPrevotes] + /\ msgsPrecommit \in [Rounds -> SUBSET AllFaultyPrecommits] + /\ receivedTimelyProposal = EmptyRcvProp + /\ inspectedProposal = [r \in Rounds |-> EmptyProcSet] + /\ BenignRoundsInMessages(msgsPropose) + /\ BenignRoundsInMessages(msgsPrevote) + /\ BenignRoundsInMessages(msgsPrecommit) + /\ evidence = EmptyMsgSet + /\ action' = "Init" + /\ beginConsensus = Min({localClock[p] : p \in Corr}) + /\ endConsensus = [p \in Corr |-> NilTimestamp] + /\ lastBeginConsensus = Max({localClock[p] : p \in Corr}) + /\ proposalTime = [r \in Rounds |-> NilTimestamp] + /\ proposalReceivedTime = [r \in Rounds |-> NilTimestamp] + +(************************ MESSAGE PASSING ********************************) +BroadcastProposal(pSrc, pRound, pProposal, pValidRound) == + LET newMsg == + AsMsg([type |-> "PROPOSAL", src |-> pSrc, round |-> pRound, + proposal |-> pProposal, validRound |-> pValidRound]) + IN + msgsPropose' = [msgsPropose EXCEPT ![pRound] = msgsPropose[pRound] \union {newMsg}] + +BroadcastPrevote(pSrc, pRound, pId) == + LET newMsg == AsMsg([type |-> "PREVOTE", + src |-> pSrc, round |-> pRound, id |-> pId]) + IN + msgsPrevote' = [msgsPrevote EXCEPT ![pRound] = msgsPrevote[pRound] \union {newMsg}] + +BroadcastPrecommit(pSrc, pRound, pId) == + LET newMsg == AsMsg([type |-> "PRECOMMIT", + src |-> pSrc, round |-> pRound, id |-> pId]) + IN + msgsPrecommit' = [msgsPrecommit EXCEPT ![pRound] = msgsPrecommit[pRound] \union {newMsg}] + + +(***************************** TIME **************************************) + +\* [PBTS-CLOCK-PRECISION.0] +SynchronizedLocalClocks == + \A p \in Corr : \A q \in Corr : + p /= q => + \/ /\ localClock[p] >= localClock[q] + /\ localClock[p] - localClock[q] < Precision + \/ /\ localClock[p] < localClock[q] + /\ localClock[q] - localClock[p] < Precision + +\* [PBTS-PROPOSE.0] +Proposal(v, t) == + <> + +\* [PBTS-DECISION-ROUND.0] +Decision(v, t, r) == + <> + +(**************** MESSAGE PROCESSING TRANSITIONS *************************) +\* lines 12-13 +StartRound(p, r) == + /\ step[p] /= "DECIDED" \* a decided process does not participate in consensus + /\ round' = [round EXCEPT ![p] = r] + /\ step' = [step EXCEPT ![p] = "PROPOSE"] + +\* lines 14-19, a proposal may be sent later +InsertProposal(p) == + LET r == round[p] IN + /\ p = Proposer[r] + /\ step[p] = "PROPOSE" + \* if the proposer is sending a proposal, then there are no other proposals + \* by the correct processes for the same round + /\ \A m \in msgsPropose[r]: m.src /= p + /\ \E v \in ValidValues: + LET proposal == IF validValue[p] /= NilValue + THEN Proposal(validValue[p], localClock[p]) + ELSE Proposal(v, localClock[p]) IN + + /\ BroadcastProposal(p, round[p], proposal, validRound[p]) + /\ proposalTime' = [proposalTime EXCEPT ![r] = realTime] + /\ UNCHANGED <> + /\ action' = "InsertProposal" + +\* a new action used to filter messages that are not on time +\* [PBTS-RECEPTION-STEP.0] +ReceiveProposal(p) == + \E v \in Values, t \in Timestamps: + /\ LET r == round[p] IN + LET msg == + AsMsg([type |-> "PROPOSAL", src |-> Proposer[round[p]], + round |-> round[p], proposal |-> Proposal(v, t), validRound |-> NilRound]) IN + /\ msg \in msgsPropose[round[p]] + /\ p \notin inspectedProposal[r] + /\ <> \notin receivedTimelyProposal + /\ inspectedProposal' = [inspectedProposal EXCEPT ![r] = @ \union {p}] + /\ \/ /\ localClock[p] - Precision < t + /\ t < localClock[p] + Precision + Delay + /\ receivedTimelyProposal' = receivedTimelyProposal \union {<>} + /\ \/ /\ proposalReceivedTime[r] = NilTimestamp + /\ proposalReceivedTime' = [proposalReceivedTime EXCEPT ![r] = realTime] + \/ /\ proposalReceivedTime[r] /= NilTimestamp + /\ UNCHANGED proposalReceivedTime + \/ /\ \/ localClock[p] - Precision >= t + \/ t >= localClock[p] + Precision + Delay + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ action' = "ReceiveProposal" + +\* lines 22-27 +UponProposalInPropose(p) == + \E v \in Values, t \in Timestamps: + /\ step[p] = "PROPOSE" (* line 22 *) + /\ LET msg == + AsMsg([type |-> "PROPOSAL", src |-> Proposer[round[p]], + round |-> round[p], proposal |-> Proposal(v, t), validRound |-> NilRound]) IN + /\ <> \in receivedTimelyProposal \* updated line 22 + /\ evidence' = {msg} \union evidence + /\ LET mid == (* line 23 *) + IF IsValid(v) /\ (lockedRound[p] = NilRound \/ lockedValue[p] = v) + THEN Id(Proposal(v, t)) + ELSE NilProposal + IN + BroadcastPrevote(p, round[p], mid) \* lines 24-26 + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "UponProposalInPropose" + +\* lines 28-33 +\* [PBTS-ALG-OLD-PREVOTE.0] +UponProposalInProposeAndPrevote(p) == + \E v \in Values, t1 \in Timestamps, t2 \in Timestamps, vr \in Rounds: + /\ step[p] = "PROPOSE" /\ 0 <= vr /\ vr < round[p] \* line 28, the while part + /\ LET msg == + AsMsg([type |-> "PROPOSAL", src |-> Proposer[round[p]], + round |-> round[p], proposal |-> Proposal(v, t1), validRound |-> vr]) + IN + /\ <> \in receivedTimelyProposal \* updated line 28 + /\ LET PV == { m \in msgsPrevote[vr]: m.id = Id(Proposal(v, t2)) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 28 + /\ evidence' = PV \union {msg} \union evidence + /\ LET mid == (* line 29 *) + IF IsValid(v) /\ (lockedRound[p] <= vr \/ lockedValue[p] = v) + THEN Id(Proposal(v, t1)) + ELSE NilProposal + IN + BroadcastPrevote(p, round[p], mid) \* lines 24-26 + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "UponProposalInProposeAndPrevote" + + \* lines 34-35 + lines 61-64 (onTimeoutPrevote) +UponQuorumOfPrevotesAny(p) == + /\ step[p] = "PREVOTE" \* line 34 and 61 + /\ \E MyEvidence \in SUBSET msgsPrevote[round[p]]: + \* find the unique voters in the evidence + LET Voters == { m.src: m \in MyEvidence } IN + \* compare the number of the unique voters against the threshold + /\ Cardinality(Voters) >= THRESHOLD2 \* line 34 + /\ evidence' = MyEvidence \union evidence + /\ BroadcastPrecommit(p, round[p], NilProposal) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + /\ UNCHANGED <> + /\ action' = "UponQuorumOfPrevotesAny" + +\* lines 36-46 +\* [PBTS-ALG-NEW-PREVOTE.0] +UponProposalInPrevoteOrCommitAndPrevote(p) == + \E v \in ValidValues, t \in Timestamps, vr \in RoundsOrNil: + /\ step[p] \in {"PREVOTE", "PRECOMMIT"} \* line 36 + /\ LET msg == + AsMsg([type |-> "PROPOSAL", src |-> Proposer[round[p]], + round |-> round[p], proposal |-> Proposal(v, t), validRound |-> vr]) IN + /\ <> \in receivedTimelyProposal \* updated line 36 + /\ LET PV == { m \in msgsPrevote[round[p]]: m.id = Id(Proposal(v, t)) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 36 + /\ evidence' = PV \union {msg} \union evidence + /\ IF step[p] = "PREVOTE" + THEN \* lines 38-41: + /\ lockedValue' = [lockedValue EXCEPT ![p] = v] + /\ lockedRound' = [lockedRound EXCEPT ![p] = round[p]] + /\ BroadcastPrecommit(p, round[p], Id(Proposal(v, t))) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + ELSE + UNCHANGED <> + \* lines 42-43 + /\ validValue' = [validValue EXCEPT ![p] = v] + /\ validRound' = [validRound EXCEPT ![p] = round[p]] + /\ UNCHANGED <> + /\ action' = "UponProposalInPrevoteOrCommitAndPrevote" + +\* lines 47-48 + 65-67 (onTimeoutPrecommit) +UponQuorumOfPrecommitsAny(p) == + /\ \E MyEvidence \in SUBSET msgsPrecommit[round[p]]: + \* find the unique committers in the evidence + LET Committers == { m.src: m \in MyEvidence } IN + \* compare the number of the unique committers against the threshold + /\ Cardinality(Committers) >= THRESHOLD2 \* line 47 + /\ evidence' = MyEvidence \union evidence + /\ round[p] + 1 \in Rounds + /\ StartRound(p, round[p] + 1) + /\ UNCHANGED <> + /\ action' = "UponQuorumOfPrecommitsAny" + +\* lines 49-54 +\* [PBTS-ALG-DECIDE.0] +UponProposalInPrecommitNoDecision(p) == + /\ decision[p] = NilDecision \* line 49 + /\ \E v \in ValidValues, t \in Timestamps (* line 50*) , r \in Rounds, vr \in RoundsOrNil: + /\ LET msg == AsMsg([type |-> "PROPOSAL", src |-> Proposer[r], + round |-> r, proposal |-> Proposal(v, t), validRound |-> vr]) IN + /\ msg \in msgsPropose[r] \* line 49 + /\ p \in inspectedProposal[r] + /\ LET PV == { m \in msgsPrecommit[r]: m.id = Id(Proposal(v, t)) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 49 + /\ evidence' = PV \union {msg} \union evidence + /\ decision' = [decision EXCEPT ![p] = Decision(v, t, round[p])] \* update the decision, line 51 + \* The original algorithm does not have 'DECIDED', but it increments the height. + \* We introduced 'DECIDED' here to prevent the process from changing its decision. + /\ endConsensus' = [endConsensus EXCEPT ![p] = localClock[p]] + /\ step' = [step EXCEPT ![p] = "DECIDED"] + /\ UNCHANGED <> + /\ action' = "UponProposalInPrecommitNoDecision" + +\* the actions below are not essential for safety, but added for completeness + +\* lines 20-21 + 57-60 +OnTimeoutPropose(p) == + /\ step[p] = "PROPOSE" + /\ p /= Proposer[round[p]] + /\ BroadcastPrevote(p, round[p], NilProposal) + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "OnTimeoutPropose" + +\* lines 44-46 +OnQuorumOfNilPrevotes(p) == + /\ step[p] = "PREVOTE" + /\ LET PV == { m \in msgsPrevote[round[p]]: m.id = Id(NilProposal) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 36 + /\ evidence' = PV \union evidence + /\ BroadcastPrecommit(p, round[p], Id(NilProposal)) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + /\ UNCHANGED <> + /\ action' = "OnQuorumOfNilPrevotes" + +\* lines 55-56 +OnRoundCatchup(p) == + \E r \in {rr \in Rounds: rr > round[p]}: + LET RoundMsgs == msgsPropose[r] \union msgsPrevote[r] \union msgsPrecommit[r] IN + \E MyEvidence \in SUBSET RoundMsgs: + LET Faster == { m.src: m \in MyEvidence } IN + /\ Cardinality(Faster) >= THRESHOLD1 + /\ evidence' = MyEvidence \union evidence + /\ StartRound(p, r) + /\ UNCHANGED <> + /\ action' = "OnRoundCatchup" + + +(********************* PROTOCOL TRANSITIONS ******************************) +\* advance the global clock +AdvanceRealTime == + /\ realTime < MaxTimestamp + /\ realTime' = realTime + 1 + /\ \/ /\ ~ClockDrift + /\ localClock' = [p \in Corr |-> localClock[p] + 1] + \/ /\ ClockDrift + /\ UNCHANGED localClock + /\ UNCHANGED <> + /\ action' = "AdvanceRealTime" + +\* advance the local clock of node p +AdvanceLocalClock(p) == + /\ localClock[p] < MaxTimestamp + /\ localClock' = [localClock EXCEPT ![p] = @ + 1] + /\ UNCHANGED <> + /\ action' = "AdvanceLocalClock" + +\* process timely messages +MessageProcessing(p) == + \* start round + \/ InsertProposal(p) + \* reception step + \/ ReceiveProposal(p) + \* processing step + \/ UponProposalInPropose(p) + \/ UponProposalInProposeAndPrevote(p) + \/ UponQuorumOfPrevotesAny(p) + \/ UponProposalInPrevoteOrCommitAndPrevote(p) + \/ UponQuorumOfPrecommitsAny(p) + \/ UponProposalInPrecommitNoDecision(p) + \* the actions below are not essential for safety, but added for completeness + \/ OnTimeoutPropose(p) + \/ OnQuorumOfNilPrevotes(p) + \/ OnRoundCatchup(p) + +(* + * A system transition. In this specificatiom, the system may eventually deadlock, + * e.g., when all processes decide. This is expected behavior, as we focus on safety. + *) +Next == + \/ AdvanceRealTime + \/ /\ ClockDrift + /\ \E p \in Corr: AdvanceLocalClock(p) + \/ /\ SynchronizedLocalClocks + /\ \E p \in Corr: MessageProcessing(p) + +----------------------------------------------------------------------------- + +(*************************** INVARIANTS *************************************) + +\* [PBTS-INV-AGREEMENT.0] +AgreementOnValue == + \A p, q \in Corr: + /\ decision[p] /= NilDecision + /\ decision[q] /= NilDecision + => \E v \in ValidValues, t1 \in Timestamps, t2 \in Timestamps, r1 \in Rounds, r2 \in Rounds : + /\ decision[p] = Decision(v, t1, r1) + /\ decision[q] = Decision(v, t2, r2) + +\* [PBTS-INV-TIME-AGR.0] +AgreementOnTime == + \A p, q \in Corr: + \A v1 \in ValidValues, v2 \in ValidValues, t1 \in Timestamps, t2 \in Timestamps, r \in Rounds : + /\ decision[p] = Decision(v1, t1, r) + /\ decision[q] = Decision(v2, t2, r) + => t1 = t2 + +\* [PBTS-CONSENSUS-TIME-VALID.0] +ConsensusTimeValid == + \A p \in Corr, t \in Timestamps : + \* if a process decides on v and t + (\E v \in ValidValues, r \in Rounds : decision[p] = Decision(v, t, r)) + \* then + => /\ beginConsensus - Precision <= t + /\ t < endConsensus[p] + Precision + Delay + +\* [PBTS-CONSENSUS-SAFE-VALID-CORR-PROP.0] +ConsensusSafeValidCorrProp == + \A v \in ValidValues, t \in Timestamps : + \* if the proposer in the first round is correct + (/\ Proposer[0] \in Corr + \* and there exists a process that decided on v, t + /\ \E p \in Corr, r \in Rounds : decision[p] = Decision(v, t, r)) + \* then t is between the minimal and maximal initial local time + => /\ beginConsensus <= t + /\ t <= lastBeginConsensus + +\* [PBTS-CONSENSUS-REALTIME-VALID-CORR.0] +ConsensusRealTimeValidCorr == + \A t \in Timestamps, r \in Rounds : + (/\ \E p \in Corr, v \in ValidValues : decision[p] = Decision(v, t, r) + /\ proposalTime[r] /= NilTimestamp) + => /\ proposalTime[r] - Accuracy < t + /\ t < proposalTime[r] + Accuracy + +\* [PBTS-CONSENSUS-REALTIME-VALID.0] +ConsensusRealTimeValid == + \A t \in Timestamps, r \in Rounds : + (\E p \in Corr, v \in ValidValues : decision[p] = Decision(v, t, r)) + => /\ proposalReceivedTime[r] - Accuracy - Precision < t + /\ t < proposalReceivedTime[r] + Accuracy + Precision + Delay + +\* [PBTS-MSG-FAIR.0] +BoundedDelay == + \A r \in Rounds : + (/\ proposalTime[r] /= NilTimestamp + /\ proposalTime[r] + Delay < realTime) + => inspectedProposal[r] = Corr + +\* [PBTS-CONSENSUS-TIME-LIVE.0] +ConsensusTimeLive == + \A r \in Rounds, p \in Corr : + (/\ proposalTime[r] /= NilTimestamp + /\ proposalTime[r] + Delay < realTime + /\ Proposer[r] \in Corr + /\ round[p] <= r) + => \E msg \in RoundProposals(r) : <> \in receivedTimelyProposal + +\* a conjunction of all invariants +Inv == + /\ AgreementOnValue + /\ AgreementOnTime + /\ ConsensusTimeValid + /\ ConsensusSafeValidCorrProp + /\ ConsensusRealTimeValid + /\ ConsensusRealTimeValidCorr + /\ BoundedDelay + +Liveness == + ConsensusTimeLive + +============================================================================= diff --git a/spec/consensus/proposer-selection.md b/spec/consensus/proposer-selection.md new file mode 100644 index 0000000..0693158 --- /dev/null +++ b/spec/consensus/proposer-selection.md @@ -0,0 +1,323 @@ +--- +order: 3 +--- + +# Proposer Selection Procedure + +This document specifies the Proposer Selection Procedure that is used in Tendermint, the consensus algorithm adopted in CometBFT, to choose a round proposer. +As Tendermint is “leader-based consensus protocol”, the proposer selection is critical for its correct functioning. + +At a given block height, the proposer selection algorithm runs with the same validator set at each round . +Between heights, an updated validator set may be specified by the application as part of the ABCIResponses' EndBlock. + +## Requirements for Proposer Selection + +This sections covers the requirements with Rx being mandatory and Ox optional requirements. +The following requirements must be met by the Proposer Selection procedure: + +### R1: Determinism + +Given a validator set `V`, and two honest validators `p` and `q`, for each height `h` and each round `r` the following must hold: + + `proposer_p(h,r) = proposer_q(h,r)` + +where `proposer_p(h,r)` is the proposer returned by the Proposer Selection Procedure at process `p`, at height `h` and round `r`. + +### R2: Fairness + +Given a validator set with total voting power P and a sequence S of elections. In any sub-sequence of S with length C*P, a validator v must be elected as proposer P/VP(v) times, i.e. with frequency: + + f(v) ~ VP(v) / P + +where C is a tolerance factor for validator set changes with following values: + +- C == 1 if there are no validator set changes +- C ~ k when there are validator changes + +*[this needs more work]* + +## Basic Algorithm + +At its core, the proposer selection procedure uses a weighted round-robin algorithm. + +A model that gives a good intuition on how/ why the selection algorithm works and it is fair is that of a priority queue. The validators move ahead in this queue according to their voting power (the higher the voting power the faster a validator moves towards the head of the queue). When the algorithm runs the following happens: + +- all validators move "ahead" according to their powers: for each validator, increase the priority by the voting power +- first in the queue becomes the proposer: select the validator with highest priority +- move the proposer back in the queue: decrease the proposer's priority by the total voting power + +Notation: + +- vset - the validator set +- n - the number of validators +- VP(i) - voting power of validator i +- A(i) - accumulated priority for validator i +- P - total voting power of set +- avg - average of all validator priorities +- prop - proposer + +Simple view at the Selection Algorithm: + +```md + def ProposerSelection (vset): + + // compute priorities and elect proposer + for each validator i in vset: + A(i) += VP(i) + prop = max(A) + A(prop) -= P +``` + +## Stable Set + +Consider the validator set: + +Validator | p1 | p2 +----------|----|--- +VP | 1 | 3 + +Assuming no validator changes, the following table shows the proposer priority computation over a few runs. Four runs of the selection procedure are shown, starting with the 5th the same values are computed. +Each row shows the priority queue and the process place in it. The proposer is the closest to the head, the rightmost validator. As priorities are updated, the validators move right in the queue. The proposer moves left as its priority is reduced after election. + +| Priority Run | -2 | -1 | 0 | 1 | 2 | 3 | 4 | 5 | Alg step | +|----------------|----|----|-------|----|-------|----|----|----|------------------| +| | | | p1,p2 | | | | | | Initialized to 0 | +| run 1 | | | | p1 | | p2 | | | A(i)+=VP(i) | +| | | p2 | | p1 | | | | | A(p2)-= P | +| run 2 | | | | | p1,p2 | | | | A(i)+=VP(i) | +| | p1 | | | | p2 | | | | A(p1)-= P | +| run 3 | | p1 | | | | | | p2 | A(i)+=VP(i) | +| | | p1 | | p2 | | | | | A(p2)-= P | +| run 4 | | | p1 | | | | p2 | | A(i)+=VP(i) | +| | | | p1,p2 | | | | | | A(p2)-= P | + +It can be shown that: + +- At the end of each run k+1 the sum of the priorities is the same as at end of run k. If a new set's priorities are initialized to 0 then the sum of priorities will be 0 at each run while there are no changes. +- The max distance between priorites is (n-1) *P.*[formal proof not finished]* + +## Validator Set Changes + +Between proposer selection runs the validator set may change. Some changes have implications on the proposer election. + +### Voting Power Change + +Consider again the earlier example and assume that the voting power of p1 is changed to 4: + +Validator | p1 | p2 +----------|----|--- +VP | 4 | 3 + +Let's also assume that before this change the proposer priorites were as shown in first row (last run). As it can be seen, the selection could run again, without changes, as before. + +| Priority Run | -2 | -1 | 0 | 1 | 2 | Comment | +|----------------|----|----|---|----|----|-------------------| +| last run | | p2 | | p1 | | __update VP(p1)__ | +| next run | | | | | p2 | A(i)+=VP(i) | +| | p1 | | | | p2 | A(p1)-= P | + +However, when a validator changes power from a high to a low value, some other validator remain far back in the queue for a long time. This scenario is considered again in the Proposer Priority Range section. + +As before: + +- At the end of each run k+1 the sum of the priorities is the same as at run k. +- The max distance between priorites is (n-1) * P. + +### Validator Removal + +Consider a new example with set: + +Validator | p1 | p2 | p3 +----------|----|----|--- +VP | 1 | 2 | 3 + +Let's assume that after the last run the proposer priorities were as shown in first row with their sum being 0. After p2 is removed, at the end of next proposer selection run (penultimate row) the sum of priorities is -2 (minus the priority of the removed process). + +The procedure could continue without modifications. However, after a sufficiently large number of modifications in validator set, the priority values would migrate towards maximum or minimum allowed values causing truncations due to overflow detection. +For this reason, the selection procedure adds another __new step__ that centers the current priority values such that the priority sum remains close to 0. + +| Priority Run | -3 | -2 | -1 | 0 | 1 | 2 | 3 | Comment | +|----------------|----|----|----|---|----|----|----|-----------------------| +| last run | p3 | | | | p1 | p2 | | __remove p2__ | +| nextrun | | | | | | | | | +| __new step__ | | p3 | | | | p1 | | A(i) -= avg, avg = -1 | +| | | | | | p3 | | p1 | A(i)+=VP(i) | +| | | | p1 | | p3 | | | A(p1)-= P | + +The modified selection algorithm is: + +```md + def ProposerSelection (vset): + + // center priorities around zero + avg = sum(A(i) for i in vset)/len(vset) + for each validator i in vset: + A(i) -= avg + + // compute priorities and elect proposer + for each validator i in vset: + A(i) += VP(i) + prop = max(A) + A(prop) -= P +``` + +Observations: + +- The sum of priorities is now close to 0. Due to integer division the sum is an integer in (-n, n), where n is the number of validators. + +### New Validator + +When a new validator is added, same problem as the one described for removal appears, the sum of priorities in the new set is not zero. This is fixed with the centering step introduced above. + +One other issue that needs to be addressed is the following. A validator V that has just been elected is moved to the end of the queue. If the validator set is large and/ or other validators have significantly higher power, V will have to wait many runs to be elected. If V removes and re-adds itself to the set, it would make a significant (albeit unfair) "jump" ahead in the queue. + +In order to prevent this, when a new validator is added, its initial priority is set to: + +```md + A(V) = -1.125 * P +``` + +where P is the total voting power of the set including V. + +Current implementation uses the penalty factor of 1.125 because it provides a small punishment that is efficient to calculate. See [here](https://github.com/tendermint/tendermint/pull/2785#discussion_r235038971) for more details. + +If we consider the validator set where p3 has just been added: + +Validator | p1 | p2 | p3 +----------|----|----|--- +VP | 1 | 3 | 8 + +then p3 will start with proposer priority: + +```md + A(p3) = -1.125 * (1 + 3 + 8) ~ -13 +``` + +Note that since current computation uses integer division there is penalty loss when sum of the voting power is less than 8. + +In the next run, p3 will still be ahead in the queue, elected as proposer and moved back in the queue. + +| Priority Run | -13 | -9 | -5 | -2 | -1 | 0 | 1 | 2 | 5 | 6 | 7 | Alg step | +|----------------|-----|----|----|----|----|---|---|----|----|----|----|-----------------------| +| last run | | | | p2 | | | | p1 | | | | __add p3__ | +| | p3 | | | p2 | | | | p1 | | | | A(p3) = -13 | +| next run | | p3 | | | | | | p2 | | p1 | | A(i) -= avg, avg = -4 | +| | | | | | p3 | | | | p2 | | p1 | A(i)+=VP(i) | +| | | | p1 | | p3 | | | | p2 | | | A(p1)-=P | + +## Proposer Priority Range + +With the introduction of centering, some interesting cases occur. Low power validators that bind early in a set that includes high power validator(s) benefit from subsequent additions to the set. This is because these early validators run through more right shift operations during centering, operations that increase their priority. + +As an example, consider the set where p2 is added after p1, with priority -1.125 * 80k = -90k. After the selection procedure runs once: + +Validator | p1 | p2 | Comment +----------|------|------|------------------ +VP | 80k | 10 | +A | 0 | -90k | __added p2__ +A | 45k | -45k | __run selection__ + +Then execute the following steps: + +1. Add a new validator p3: + + Validator | p1 | p2 | p3 + ----------|-----|----|--- + VP | 80k | 10 | 10 + +2. Run selection once. The notation '..p'/'p..' means very small deviations compared to column priority. + + | Priority Run | -90k.. | -60k | -45k | -15k | 0 | 45k | 75k | 155k | Comment | + |---------------|--------|------|------|------|---|-----|-----|------|--------------| + | last run | p3 | | p2 | | | p1 | | | __added p3__ | + | next run + | *right_shift*| | p3 | | p2 | | | p1 | | A(i) -= avg,avg=-30k + | | | ..p3| | ..p2| | | | p1 | A(i)+=VP(i) + | | | ..p3| | ..p2| | | p1.. | | A(p1)-=P, P=80k+20 + +3. Remove p1 and run selection once: + + Validator | p3 | p2 | Comment + ----------|--------|-------|------------------ + VP | 10 | 10 | + A | -60k | -15k | + A | -22.5k | 22.5k | __run selection__ + +At this point, while the total voting power is 20, the distance between priorities is 45k. It will take 4500 runs for p3 to catch up with p2. + +In order to prevent these types of scenarios, the selection algorithm performs scaling of priorities such that the difference between min and max values is smaller than two times the total voting power. + +The modified selection algorithm is: + +```md + def ProposerSelection (vset): + + // scale the priority values + diff = max(A)-min(A) + threshold = 2 * P + if diff > threshold: + scale = diff/threshold + for each validator i in vset: + A(i) = A(i)/scale + + // center priorities around zero + avg = sum(A(i) for i in vset)/len(vset) + for each validator i in vset: + A(i) -= avg + + // compute priorities and elect proposer + for each validator i in vset: + A(i) += VP(i) + prop = max(A) + A(prop) -= P +``` + +Observations: + +- With this modification, the maximum distance between priorites becomes 2 * P. + +Note also that even during steady state the priority range may increase beyond 2 * P. The scaling introduced here helps to keep the range bounded. + +## Wrinkles + +### Validator Power Overflow Conditions + +The validator voting power is a positive number stored as an int64. When a validator is added the `1.125 * P` computation must not overflow. As a consequence the code handling validator updates (add and update) checks for overflow conditions making sure the total voting power is never larger than the largest int64 `MAX`, with the property that `1.125 * MAX` is still in the bounds of int64. Fatal error is return when overflow condition is detected. + +### Proposer Priority Overflow/ Underflow Handling + +The proposer priority is stored as an int64. The selection algorithm performs additions and subtractions to these values and in the case of overflows and underflows it limits the values to: + +```go + MaxInt64 = 1 << 63 - 1 + MinInt64 = -1 << 63 +``` + +## Requirement Fulfillment Claims + +__[R1]__ + +The proposer algorithm is deterministic giving consistent results across executions with same transactions and validator set modifications. +[WIP - needs more detail] + +__[R2]__ + +Given a set of processes with the total voting power P, during a sequence of elections of length P, the number of times any process is selected as proposer is equal to its voting power. The sequence of the P proposers then repeats. If we consider the validator set: + +Validator | p1 | p2 +----------|----|--- +VP | 1 | 3 + +With no other changes to the validator set, the current implementation of proposer selection generates the sequence: +`p2, p1, p2, p2, p2, p1, p2, p2,...` or [`p2, p1, p2, p2`]* +A sequence that starts with any circular permutation of the [`p2, p1, p2, p2`] sub-sequence would also provide the same degree of fairness. In fact these circular permutations show in the sliding window (over the generated sequence) of size equal to the length of the sub-sequence. + +Assigning priorities to each validator based on the voting power and updating them at each run ensures the fairness of the proposer selection. In addition, every time a validator is elected as proposer its priority is decreased with the total voting power. + +Intuitively, a process v jumps ahead in the queue at most (max(A) - min(A))/VP(v) times until it reaches the head and is elected. The frequency is then: + +```md + f(v) ~ VP(v)/(max(A)-min(A)) = 1/k * VP(v)/P +``` + +For current implementation, this means v should be proposer at least VP(v) times out of k * P runs, with scaling factor k=2. diff --git a/spec/consensus/signing.md b/spec/consensus/signing.md new file mode 100644 index 0000000..d160b00 --- /dev/null +++ b/spec/consensus/signing.md @@ -0,0 +1,233 @@ +--- +order: 5 +--- + +# Validator Signing + +Here we specify the rules for validating a proposal and vote before signing. +First we include some general notes on validating data structures common to both types. +We then provide specific validation rules for each. Finally, we include validation rules to prevent double-sigining. + +## SignedMsgType + +The `SignedMsgType` is a single byte that refers to the type of the message +being signed. It is defined in Go as follows: + +```go +// SignedMsgType is a type of signed message in the consensus. +type SignedMsgType byte + +const ( + // Votes + PrevoteType SignedMsgType = 0x01 + PrecommitType SignedMsgType = 0x02 + + // Proposals + ProposalType SignedMsgType = 0x20 +) +``` + +All signed messages must correspond to one of these types. + +## Timestamp + +Timestamp validation is subtle and there are currently no bounds placed on the +timestamp included in a proposal or vote. It is expected that validators will honestly +report their local clock time. The median of all timestamps +included in a commit is used as the timestamp for the next block height. + +Timestamps are expected to be strictly monotonic for a given validator, though +this is not currently enforced. + +## ChainID + +ChainID is an unstructured string with a max length of 50-bytes. +In the future, the ChainID may become structured, and may take on longer lengths. +For now, it is recommended that signers be configured for a particular ChainID, +and to only sign votes and proposals corresponding to that ChainID. + +## BlockID + +BlockID is the structure used to represent the block: + +```go +type BlockID struct { + Hash []byte + PartsHeader PartSetHeader +} + +type PartSetHeader struct { + Hash []byte + Total int +} +``` + +To be included in a valid vote or proposal, BlockID must either represent a `nil` block, or a complete one. +We introduce two methods, `BlockID.IsZero()` and `BlockID.IsComplete()` for these cases, respectively. + +`BlockID.IsZero()` returns true for BlockID `b` if each of the following +are true: + +```go +b.Hash == nil +b.PartsHeader.Total == 0 +b.PartsHeader.Hash == nil +``` + +`BlockID.IsComplete()` returns true for BlockID `b` if each of the following +are true: + +```go +len(b.Hash) == 32 +b.PartsHeader.Total > 0 +len(b.PartsHeader.Hash) == 32 +``` + +## Proposals + +The structure of a proposal for signing looks like: + +```go +type CanonicalProposal struct { + Type SignedMsgType // type alias for byte + Height int64 `binary:"fixed64"` + Round int64 `binary:"fixed64"` + POLRound int64 `binary:"fixed64"` + BlockID BlockID + Timestamp time.Time + ChainID string +} +``` + +A proposal is valid if each of the following lines evaluates to true for proposal `p`: + +```go +p.Type == 0x20 +p.Height > 0 +p.Round >= 0 +p.POLRound >= -1 +p.BlockID.IsComplete() +``` + +In other words, a proposal is valid for signing if it contains the type of a Proposal +(0x20), has a positive, non-zero height, a +non-negative round, a POLRound not less than -1, and a complete BlockID. + +## Votes + +The structure of a vote for signing looks like: + +```go +type CanonicalVote struct { + Type SignedMsgType // type alias for byte + Height int64 `binary:"fixed64"` + Round int64 `binary:"fixed64"` + BlockID BlockID + Timestamp time.Time + ChainID string +} +``` + +A vote is valid if each of the following lines evaluates to true for vote `v`: + +```go +v.Type == 0x1 || v.Type == 0x2 +v.Height > 0 +v.Round >= 0 +v.BlockID.IsZero() || v.BlockID.IsComplete() +``` + +In other words, a vote is valid for signing if it contains the type of a Prevote +or Precommit (0x1 or 0x2, respectively), has a positive, non-zero height, a +non-negative round, and an empty or valid BlockID. + +## Invalid Votes and Proposals + +Votes and proposals which do not satisfy the above rules are considered invalid. +Peers gossipping invalid votes and proposals may be disconnected from other peers on the network. +Note, however, that there is not currently any explicit mechanism to punish validators signing votes or proposals that fail +these basic validation rules. + +## Double Signing + +Signers must be careful not to sign conflicting messages, also known as "double signing" or "equivocating". +CometBFT has mechanisms to publish evidence of validators that signed conflicting votes, so they can be punished +by the application. Note CometBFT does not currently handle evidence of conflciting proposals, though it may in the future. + +### State + +To prevent such double signing, signers must track the height, round, and type of the last message signed. +Assume the signer keeps the following state, `s`: + +```go +type LastSigned struct { + Height int64 + Round int64 + Type SignedMsgType // byte +} +``` + +After signing a vote or proposal `m`, the signer sets: + +```go +s.Height = m.Height +s.Round = m.Round +s.Type = m.Type +``` + +### Proposals + +A signer should only sign a proposal `p` if any of the following lines are true: + +```go +p.Height > s.Height +p.Height == s.Height && p.Round > s.Round +``` + +In other words, a proposal should only be signed if it's at a higher height, or a higher round for the same height. +Once a proposal or vote has been signed for a given height and round, a proposal should never be signed for the same height and round. + +### Votes + +A signer should only sign a vote `v` if any of the following lines are true: + +```go +v.Height > s.Height +v.Height == s.Height && v.Round > s.Round +v.Height == s.Height && v.Round == s.Round && v.Step == 0x1 && s.Step == 0x20 +v.Height == s.Height && v.Round == s.Round && v.Step == 0x2 && s.Step != 0x2 +``` + +In other words, a vote should only be signed if it's: + +- at a higher height +- at a higher round for the same height +- a prevote for the same height and round where we haven't signed a prevote or precommit (but have signed a proposal) +- a precommit for the same height and round where we haven't signed a precommit (but have signed a proposal and/or a prevote) + +This means that once a validator signs a prevote for a given height and round, the only other message it can sign for that height and round is a precommit. +And once a validator signs a precommit for a given height and round, it must not sign any other message for that same height and round. + +Note this includes votes for `nil`, ie. where `BlockID.IsZero()` is true. If a +signer has already signed a vote where `BlockID.IsZero()` is true, it cannot +sign another vote with the same type for the same height and round where +`BlockID.IsComplete()` is true. Thus only a single vote of a particular type +(ie. 0x01 or 0x02) can be signed for the same height and round. + +### Other Rules + +According to the rules of Tendermint consensus algorithm, adopted in CometBFT, once a validator precommits for +a block, they become "locked" on that block, which means they can't prevote for +another block unless they see sufficient justification (ie. a polka from a +higher round). For more details, see the [consensus +spec](https://arxiv.org/abs/1807.04938). + +Violating this rule is known as "amnesia". In contrast to equivocation, +which is easy to detect, amnesia is difficult to detect without access to votes +from all the validators, as this is what constitutes the justification for +"unlocking". Hence, amnesia is not punished within the protocol, and cannot +easily be prevented by a signer. If enough validators simultaneously commit an +amnesia attack, they may cause a fork of the blockchain, at which point an +off-chain protocol must be engaged to collect votes from all the validators and +determine who misbehaved. For more details, see [fork +detection](https://github.com/tendermint/tendermint/pull/3978). diff --git a/spec/consensus/wal.md b/spec/consensus/wal.md new file mode 100644 index 0000000..ab7e67d --- /dev/null +++ b/spec/consensus/wal.md @@ -0,0 +1,35 @@ +--- +order: 6 +--- +# WAL + +Consensus module writes every message to the WAL (write-ahead log). + +It also issues fsync syscall through +[File#Sync](https://golang.org/pkg/os/#File.Sync) for messages signed by this +node (to prevent double signing). + +Under the hood, it uses +[autofile.Group](https://github.com/cometbft/cometbft/blob/af3bc47df982e271d4d340a3c5e0d773e440466d/libs/autofile/group.go#L54), +which rotates files when those get too big (> 10MB). + +The total maximum size is 1GB. We only need the latest block and the block before it, +but if the former is dragging on across many rounds, we want all those rounds. + +## Replay + +Consensus module will replay all the messages of the last height written to WAL +before a crash (if such occurs). + +The private validator may try to sign messages during replay because it runs +somewhat autonomously and does not know about replay process. + +For example, if we got all the way to precommit in the WAL and then crash, +after we replay the proposal message, the private validator will try to sign a +prevote. But it will fail. That's ok because we’ll see the prevote later in the +WAL. Then it will go to precommit, and that time it will work because the +private validator contains the `LastSignBytes` and then we’ll replay the +precommit from the WAL. + +Make sure to read about [WAL corruption](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/core/running-in-production.md#wal-corruption) +and recovery strategies. diff --git a/spec/core/data_structures.md b/spec/core/data_structures.md new file mode 100644 index 0000000..cad2b91 --- /dev/null +++ b/spec/core/data_structures.md @@ -0,0 +1,501 @@ +--- +order: 1 +--- + +# Data Structures + +Here we describe the data structures in the CometBFT blockchain and the rules for validating them. + +The CometBFT blockchain consists of a short list of data types: + +- [Data Structures](#data-structures) + - [Block](#block) + - [Execution](#execution) + - [Header](#header) + - [Version](#version) + - [BlockID](#blockid) + - [PartSetHeader](#partsetheader) + - [Part](#part) + - [Time](#time) + - [Data](#data) + - [Commit](#commit) + - [CommitSig](#commitsig) + - [BlockIDFlag](#blockidflag) + - [Vote](#vote) + - [CanonicalVote](#canonicalvote) + - [Proposal](#proposal) + - [SignedMsgType](#signedmsgtype) + - [Signature](#signature) + - [EvidenceList](#evidencelist) + - [Evidence](#evidence) + - [DuplicateVoteEvidence](#duplicatevoteevidence) + - [LightClientAttackEvidence](#lightclientattackevidence) + - [LightBlock](#lightblock) + - [SignedHeader](#signedheader) + - [ValidatorSet](#validatorset) + - [Validator](#validator) + - [Address](#address) + - [ConsensusParams](#consensusparams) + - [BlockParams](#blockparams) + - [EvidenceParams](#evidenceparams) + - [ValidatorParams](#validatorparams) + - [VersionParams](#versionparams) + - [Proof](#proof) + + +## Block + +A block consists of a header, transactions, votes (the commit), +and a list of evidence of malfeasance (ie. signing conflicting votes). + +| Name | Type | Description | Validation | +|--------|-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| +| Header | [Header](#header) | Header corresponding to the block. This field contains information used throughout consensus and other areas of the protocol. To find out what it contains, visit [header](#header) | Must adhere to the validation rules of [header](#header) | +| Data | [Data](#data) | Data contains a list of transactions. The contents of the transaction is unknown to CometBFT. | This field can be empty or populated, but no validation is performed. Applications can perform validation on individual transactions prior to block creation using [checkTx](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/abci%2B%2B_methods.md#checktx). +| Evidence | [EvidenceList](#evidencelist) | Evidence contains a list of infractions committed by validators. | Can be empty, but when populated the validations rules from [evidenceList](#evidencelist) apply | +| LastCommit | [Commit](#commit) | `LastCommit` includes one vote for every validator. All votes must either be for the previous block, nil or absent. If a vote is for the previous block it must have a valid signature from the corresponding validator. The sum of the voting power of the validators that voted must be greater than 2/3 of the total voting power of the complete validator set. The number of votes in a commit is limited to 10000 (see `types.MaxVotesCount`). | Must be empty for the initial height and must adhere to the validation rules of [commit](#commit). | + +## Execution + +Once a block is validated, it can be executed against the state. + +The state follows this recursive equation: + +```go +state(initialHeight) = InitialState +state(h+1) <- Execute(state(h), ABCIApp, block(h)) +``` + +where `InitialState` includes the initial consensus parameters and validator set, +and `ABCIApp` is an ABCI application that can return results and changes to the validator +set (TODO). Execute is defined as: + +```go +func Execute(state State, app ABCIApp, block Block) State { + // Fuction ApplyBlock executes block of transactions against the app and returns the new root hash of the app state, + // modifications to the validator set and the changes of the consensus parameters. + AppHash, ValidatorChanges, ConsensusParamChanges := app.ApplyBlock(block) + + nextConsensusParams := UpdateConsensusParams(state.ConsensusParams, ConsensusParamChanges) + return State{ + ChainID: state.ChainID, + InitialHeight: state.InitialHeight, + LastResults: abciResponses.DeliverTxResults, + AppHash: AppHash, + LastValidators: state.Validators, + Validators: state.NextValidators, + NextValidators: UpdateValidators(state.NextValidators, ValidatorChanges), + ConsensusParams: nextConsensusParams, + Version: { + Consensus: { + AppVersion: nextConsensusParams.Version.AppVersion, + }, + }, + } +} +``` + +Validating a new block is first done prior to the `prevote`, `precommit` & `finalizeCommit` stages. + +The steps to validate a new block are: + +- Check the validity rules of the block and its fields. +- Check the versions (Block & App) are the same as in local state. +- Check the chainID's match. +- Check the height is correct. +- Check the `LastBlockID` corresponds to BlockID currently in state. +- Check the hashes in the header match those in state. +- Verify the LastCommit against state, this step is skipped for the initial height. + - This is where checking the signatures correspond to the correct block will be made. +- Make sure the proposer is part of the validator set. +- Validate bock time. + - Make sure the new blocks time is after the previous blocks time. + - Calculate the medianTime and check it against the blocks time. + - If the blocks height is the initial height then check if it matches the genesis time. +- Validate the evidence in the block. Note: Evidence can be empty + +## Header + +A block header contains metadata about the block and about the consensus, as well as commitments to +the data in the current block, the previous block, and the results returned by the application: + +| Name | Type | Description | Validation | +|-------------------|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Version | [Version](#version) | Version defines the application and block versions being used. | Must adhere to the validation rules of [Version](#version) | +| ChainID | String | ChainID is the ID of the chain. This must be unique to your chain. | ChainID must be less than 50 bytes. | +| Height | uint64 | Height is the height for this header. | Must be > 0, >= initialHeight, and == previous Height+1 | +| Time | [Time](#time) | The timestamp is equal to the weighted median of validators present in the last commit. Read more on time in the [BFT-time section](../consensus/bft-time.md). Note: the timestamp of a vote must be greater by at least one millisecond than that of the block being voted on. | Time must be >= previous header timestamp + consensus parameters TimeIotaMs. The timestamp of the first block must be equal to the genesis time (since there's no votes to compute the median). | +| LastBlockID | [BlockID](#blockid) | BlockID of the previous block. | Must adhere to the validation rules of [blockID](#blockid). The first block has `block.Header.LastBlockID == BlockID{}`. | +| LastCommitHash | slice of bytes (`[]byte`) | MerkleRoot of the lastCommit's signatures. The signatures represent the validators that committed to the last block. The first block has an empty slices of bytes for the hash. | Must be of length 32 | +| DataHash | slice of bytes (`[]byte`) | MerkleRoot of the hash of transactions. **Note**: The transactions are hashed before being included in the merkle tree, the leaves of the Merkle tree are the hashes, not the transactions themselves. | Must be of length 32 | +| ValidatorHash | slice of bytes (`[]byte`) | MerkleRoot of the current validator set. The validators are first sorted by voting power (descending), then by address (ascending) prior to computing the MerkleRoot. | Must be of length 32 | +| NextValidatorHash | slice of bytes (`[]byte`) | MerkleRoot of the next validator set. The validators are first sorted by voting power (descending), then by address (ascending) prior to computing the MerkleRoot. | Must be of length 32 | +| ConsensusHash | slice of bytes (`[]byte`) | Hash of the protobuf encoded consensus parameters. | Must be of length 32 | +| AppHash | slice of bytes (`[]byte`) | Arbitrary byte array returned by the application after executing and commiting the previous block. It serves as the basis for validating any merkle proofs that comes from the ABCI application and represents the state of the actual application rather than the state of the blockchain itself. The first block's `block.Header.AppHash` is given by `ResponseInitChain.app_hash`. | This hash is determined by the application, CometBFT can not perform validation on it. | +| LastResultHash | slice of bytes (`[]byte`) | `LastResultsHash` is the root hash of a Merkle tree built from `ResponseDeliverTx` responses (`Log`,`Info`, `Codespace` and `Events` fields are ignored). | Must be of length 32. The first block has `block.Header.ResultsHash == MerkleRoot(nil)`, i.e. the hash of an empty input, for RFC-6962 conformance. | +| EvidenceHash | slice of bytes (`[]byte`) | MerkleRoot of the evidence of Byzantine behavior included in this block. | Must be of length 32 | +| ProposerAddress | slice of bytes (`[]byte`) | Address of the original proposer of the block. Validator must be in the current validatorSet. | Must be of length 20 | + +## Version + +NOTE: that this is more specifically the consensus version and doesn't include information like the +P2P Version. (TODO: we should write a comprehensive document about +versioning that this can refer to) + +| Name | type | Description | Validation | +|-------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| +| Block | uint64 | This number represents the block version and must be the same throughout an operational network | Must be equal to block version being used in a network (`block.Version.Block == state.Version.Consensus.Block`) | +| App | uint64 | App version is decided on by the application. Read [here](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/abci++_app_requirements.md) | `block.Version.App == state.Version.Consensus.App` | + +## BlockID + +The `BlockID` contains two distinct Merkle roots of the block. The `BlockID` includes these two hashes, as well as the number of parts (ie. `len(MakeParts(block))`) + +| Name | Type | Description | Validation | +|---------------|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------| +| Hash | slice of bytes (`[]byte`) | MerkleRoot of all the fields in the header (ie. `MerkleRoot(header)`. | hash must be of length 32 | +| PartSetHeader | [PartSetHeader](#partsetheader) | Used for secure gossiping of the block during consensus, is the MerkleRoot of the complete serialized block cut into parts (ie. `MerkleRoot(MakeParts(block))`). | Must adhere to the validation rules of [PartSetHeader](#partsetheader) | + +See [MerkleRoot](./encoding.md#merkleroot) for details. + +## PartSetHeader + +| Name | Type | Description | Validation | +|-------|---------------------------|-----------------------------------|----------------------| +| Total | int32 | Total amount of parts for a block | Must be > 0 | +| Hash | slice of bytes (`[]byte`) | MerkleRoot of a serialized block | Must be of length 32 | + +## Part + +Part defines a part of a block. In CometBFT blocks are broken into `parts` for gossip. + +| Name | Type | Description | Validation | +|-------|-----------------|-----------------------------------|----------------------| +| index | int32 | Total amount of parts for a block | Must be > 0 | +| bytes | bytes | MerkleRoot of a serialized block | Must be of length 32 | +| proof | [Proof](#proof) | MerkleRoot of a serialized block | Must be of length 32 | + +## Time + +CometBFT uses the [Google.Protobuf.Timestamp](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp) +format, which uses two integers, one 64 bit integer for Seconds and a 32 bit integer for Nanoseconds. + +## Data + +Data is just a wrapper for a list of transactions, where transactions are arbitrary byte arrays: + +| Name | Type | Description | Validation | +|------|----------------------------|------------------------|-----------------------------------------------------------------------------| +| Txs | Matrix of bytes ([][]byte) | Slice of transactions. | Validation does not occur on this field, this data is unknown to CometBFT | + +## Commit + +Commit is a simple wrapper for a list of signatures, with one for each validator. It also contains the relevant BlockID, height and round: + +| Name | Type | Description | Validation | +|------------|----------------------------------|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| +| Height | int64 | Height at which this commit was created. | Must be > 0 | +| Round | int32 | Round that the commit corresponds to. | Must be > 0 | +| BlockID | [BlockID](#blockid) | The blockID of the corresponding block. | Must adhere to the validation rules of [BlockID](#blockid). | +| Signatures | Array of [CommitSig](#commitsig) | Array of commit signatures that correspond to current validator set. | Length of signatures must be > 0 and adhere to the validation of each individual [Commitsig](#commitsig) | + +## ExtendedCommit + +`ExtendedCommit`, similarly to Commit, wraps a list of votes with signatures together with other data needed to verify them. +In addition, it contains the verified vote extensions, one for each non-`nil` vote, along with the extension signatures. + +| Name | Type | Description | Validation | +|--------------------|------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| +| Height | int64 | Height at which this commit was created. | Must be > 0 | +| Round | int32 | Round that the commit corresponds to. | Must be > 0 | +| BlockID | [BlockID](#blockid) | The blockID of the corresponding block. | Must adhere to the validation rules of [BlockID](#blockid). | +| ExtendedSignatures | Array of [ExtendedCommitSig](#commitsig) | The current validator set's commit signatures, extension, and extension signatures. | Length of signatures must be > 0 and adhere to the validation of each individual [ExtendedCommitSig](#extendedcommitsig) | + +## CommitSig + +`CommitSig` represents a signature of a validator, who has voted either for nil, +a particular `BlockID` or was absent. It's a part of the `Commit` and can be used +to reconstruct the vote set given the validator set. + +| Name | Type | Description | Validation | +|------------------|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------| +| BlockIDFlag | [BlockIDFlag](#blockidflag) | Represents the validators participation in consensus: its vote was not received, voted for the block that received the majority, or voted for nil | Must be one of the fields in the [BlockIDFlag](#blockidflag) enum | +| ValidatorAddress | [Address](#address) | Address of the validator | Must be of length 20 | +| Timestamp | [Time](#time) | This field will vary from `CommitSig` to `CommitSig`. It represents the timestamp of the validator. | [Time](#time) | +| Signature | [Signature](#signature) | Signature corresponding to the validators participation in consensus. | The length of the signature must be > 0 and < than 64 | + +NOTE: `ValidatorAddress` and `Timestamp` fields may be removed in the future +(see [ADR-25](https://github.com/cometbft/cometbft/blob/v0.38.x/docs/architecture/tendermint-core/adr-025-commit.md)). + +## ExtendedCommitSig + +`ExtendedCommitSig` represents a signature of a validator that has voted either for `nil`, +a particular `BlockID` or was absent. It is part of the `ExtendedCommit` and can be used +to reconstruct the vote set given the validator set. +Additionally it contains the vote extensions that were attached to each non-`nil` precommit vote. +All these extensions have been verified by the application operating at the signing validator's node. + +| Name | Type | Description | Validation | +|--------------------|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------| +| BlockIDFlag | [BlockIDFlag](#blockidflag) | Represents the validators participation in consensus: its vote was not received, voted for the block that received the majority, or voted for nil | Must be one of the fields in the [BlockIDFlag](#blockidflag) enum | +| ValidatorAddress | [Address](#address) | Address of the validator | Must be of length 20 | +| Timestamp | [Time](#time) | This field will vary from `CommitSig` to `CommitSig`. It represents the timestamp of the validator. | | +| Signature | [Signature](#signature) | Signature corresponding to the validators participation in consensus. | Length must be > 0 and < 64 | +| Extension | bytes | Vote extension provided by the Application running on the sender of the precommit vote, and verified by the local application. | Length must be zero if BlockIDFlag is not `Commit` | +| ExtensionSignature | [Signature](#signature) | Signature of the vote extension. | Length must be > 0 and < than 64 if BlockIDFlag is `Commit`, else 0 | + +## BlockIDFlag + +BlockIDFlag represents which BlockID the [signature](#commitsig) is for. + +```go +enum BlockIDFlag { + BLOCK_ID_FLAG_UNKNOWN = 0; // indicates an error condition + BLOCK_ID_FLAG_ABSENT = 1; // the vote was not received + BLOCK_ID_FLAG_COMMIT = 2; // voted for the block that received the majority + BLOCK_ID_FLAG_NIL = 3; // voted for nil +} +``` + +## Vote + +A vote is a signed message from a validator for a particular block. +The vote includes information about the validator signing it. When stored in the blockchain or propagated over the network, votes are encoded in Protobuf. + +| Name | Type | Description | Validation | +|--------------------|---------------------------------|------------------------------------------------------------------------------------------|------------------------------------------| +| Type | [SignedMsgType](#signedmsgtype) | The type of message the vote refers to | Must be `PrevoteType` or `PrecommitType` | +| Height | int64 | Height for which this vote was created for | Must be > 0 | +| Round | int32 | Round that the commit corresponds to. | Must be > 0 | +| BlockID | [BlockID](#blockid) | The blockID of the corresponding block. | | +| Timestamp | [Time](#time) | Timestamp represents the time at which a validator signed. | | +| ValidatorAddress | bytes | Address of the validator | Length must be equal to 20 | +| ValidatorIndex | int32 | Index at a specific block height corresponding to the Index of the validator in the set. | Must be > 0 | +| Signature | bytes | Signature by the validator if they participated in consensus for the associated block. | Length must be > 0 and < 64 | +| Extension | bytes | Vote extension provided by the Application running at the validator's node. | Length can be 0 | +| ExtensionSignature | bytes | Signature for the extension | Length must be > 0 and < 64 | + +## CanonicalVote + +CanonicalVote is for validator signing. This type will not be present in a block. +Votes are represented via `CanonicalVote` and also encoded using protobuf via `type.SignBytes` which includes the `ChainID`, +and uses a different ordering of the fields. + +| Name | Type | Description | Validation | +|-----------|---------------------------------|-----------------------------------------|------------------------------------------| +| Type | [SignedMsgType](#signedmsgtype) | The type of message the vote refers to | Must be `PrevoteType` or `PrecommitType` | +| Height | int64 | Height in which the vote was provided. | Must be > 0 | +| Round | int64 | Round in which the vote was provided. | Must be > 0 | +| BlockID | string | ID of the block the vote refers to. | | +| Timestamp | string | Time of the vote. | | +| ChainID | string | ID of the blockchain running consensus. | | + +For signing, votes are represented via [`CanonicalVote`](#canonicalvote) and also encoded using protobuf via +`type.SignBytes` which includes the `ChainID`, and uses a different ordering of +the fields. + +We define a method `Verify` that returns `true` if the signature verifies against the pubkey for the `SignBytes` +using the given ChainID: + +```go +func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error { + if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) { + return ErrVoteInvalidValidatorAddress + } + v := vote.ToProto() + if !pubKey.VerifyBytes(types.VoteSignBytes(chainID, v), vote.Signature) { + return ErrVoteInvalidSignature + } + return nil +} +``` + +### CanonicalVoteExtension + +Vote extensions are signed using a representation similar to votes. +This is the structure to marshall in order to obtain the bytes to sign or verify the signature. + +| Name | Type | Description | Validation | +|-----------|--------|---------------------------------------------|----------------------| +| Extension | bytes | Vote extension provided by the Application. | Can have zero length | +| Height | int64 | Height in which the extension was provided. | Must be > 0 | +| Round | int64 | Round in which the extension was provided. | Must be > 0 | +| ChainID | string | ID of the blockchain running consensus. | | + +## Proposal + +Proposal contains height and round for which this proposal is made, BlockID as a unique identifier +of proposed block, timestamp, and POLRound (a so-called Proof-of-Lock (POL) round) that is needed for +termination of the consensus. If POLRound >= 0, then BlockID corresponds to the block that +is locked in POLRound. The message is signed by the validator private key. + +| Name | Type | Description | Validation | +|-----------|---------------------------------|---------------------------------------------------------------------------------------|---------------------------------------------------------| +| Type | [SignedMsgType](#signedmsgtype) | Represents a Proposal [SignedMsgType](#signedmsgtype) | Must be `ProposalType` [signedMsgType](#signedmsgtype) | +| Height | uint64 | Height for which this vote was created for | Must be > 0 | +| Round | int32 | Round that the commit corresponds to. | Must be > 0 | +| POLRound | int64 | Proof of lock | Must be > 0 | +| BlockID | [BlockID](#blockid) | The blockID of the corresponding block. | [BlockID](#blockid) | +| Timestamp | [Time](#time) | Timestamp represents the time at which a validator signed. | [Time](#time) | +| Signature | slice of bytes (`[]byte`) | Signature by the validator if they participated in consensus for the associated bock. | Length of signature must be > 0 and < 64 | + +## SignedMsgType + +Signed message type represents a signed messages in consensus. + +```proto +enum SignedMsgType { + + SIGNED_MSG_TYPE_UNKNOWN = 0; + // Votes + SIGNED_MSG_TYPE_PREVOTE = 1; + SIGNED_MSG_TYPE_PRECOMMIT = 2; + + // Proposal + SIGNED_MSG_TYPE_PROPOSAL = 32; +} +``` + +## Signature + +Signatures in CometBFT are raw bytes representing the underlying signature. + +See the [signature spec](./encoding.md#key-types) for more. + +## EvidenceList + +EvidenceList is a simple wrapper for a list of evidence: + +| Name | Type | Description | Validation | +|----------|--------------------------------|----------------------------------------|-----------------------------------------------------------------| +| Evidence | Array of [Evidence](#evidence) | List of verified [evidence](#evidence) | Validation adheres to individual types of [Evidence](#evidence) | + +## Evidence + +Evidence in CometBFT is used to indicate breaches in the consensus by a validator. + +More information on how evidence works in CometBFT can be found [here](../consensus/evidence.md) + +### DuplicateVoteEvidence + +`DuplicateVoteEvidence` represents a validator that has voted for two different blocks +in the same round of the same height. Votes are lexicographically sorted on `BlockID`. + +| Name | Type | Description | Validation | +|------------------|---------------|--------------------------------------------------------------------|-----------------------------------------------------| +| VoteA | [Vote](#vote) | One of the votes submitted by a validator when they equivocated | VoteA must adhere to [Vote](#vote) validation rules | +| VoteB | [Vote](#vote) | The second vote submitted by a validator when they equivocated | VoteB must adhere to [Vote](#vote) validation rules | +| TotalVotingPower | int64 | The total power of the validator set at the height of equivocation | Must be equal to nodes own copy of the data | +| ValidatorPower | int64 | Power of the equivocating validator at the height | Must be equal to the nodes own copy of the data | +| Timestamp | [Time](#time) | Time of the block where the equivocation occurred | Must be equal to the nodes own copy of the data | + +### LightClientAttackEvidence + +`LightClientAttackEvidence` is a generalized evidence that captures all forms of known attacks on +a light client such that a full node can verify, propose and commit the evidence on-chain for +punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation +and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this [here](../light-client/accountability#the-misbehavior-of-faulty-validators) + +| Name | Type | Description | Validation | +|----------------------|------------------------------------|----------------------------------------------------------------------|------------------------------------------------------------------| +| ConflictingBlock | [LightBlock](#lightblock) | Read Below | Must adhere to the validation rules of [lightBlock](#lightblock) | +| CommonHeight | int64 | Read Below | must be > 0 | +| Byzantine Validators | Array of [Validators](#validator) | validators that acted maliciously | Read Below | +| TotalVotingPower | int64 | The total power of the validator set at the height of the infraction | Must be equal to the nodes own copy of the data | +| Timestamp | [Time](#time) | Time of the block where the infraction occurred | Must be equal to the nodes own copy of the data | + +## LightBlock + +LightBlock is the core data structure of the [light client](../light-client/README.md). It combines two data structures needed for verification ([signedHeader](#signedheader) & [validatorSet](#validatorset)). + +| Name | Type | Description | Validation | +|--------------|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------| +| SignedHeader | [SignedHeader](#signedheader) | The header and commit, these are used for verification purposes. To find out more visit [light client docs](../light-client/README.md) | Must not be nil and adhere to the validation rules of [signedHeader](#signedheader) | +| ValidatorSet | [ValidatorSet](#validatorset) | The validatorSet is used to help with verify that the validators in that committed the infraction were truly in the validator set. | Must not be nil and adhere to the validation rules of [validatorSet](#validatorset) | + +The `SignedHeader` and `ValidatorSet` are linked by the hash of the validator set(`SignedHeader.ValidatorsHash == ValidatorSet.Hash()`. + +## SignedHeader + +The SignedhHeader is the [header](#header) accompanied by the commit to prove it. + +| Name | Type | Description | Validation | +|--------|-------------------|-------------------|-----------------------------------------------------------------------------------| +| Header | [Header](#header) | [Header](#header) | Header cannot be nil and must adhere to the [Header](#header) validation criteria | +| Commit | [Commit](#commit) | [Commit](#commit) | Commit cannot be nil and must adhere to the [Commit](#commit) criteria | + +## ValidatorSet + +| Name | Type | Description | Validation | +|------------|----------------------------------|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------| +| Validators | Array of [validator](#validator) | List of the active validators at a specific height | The list of validators can not be empty or nil and must adhere to the validation rules of [validator](#validator) | +| Proposer | [validator](#validator) | The block proposer for the corresponding block | The proposer cannot be nil and must adhere to the validation rules of [validator](#validator) | + +## Validator + +| Name | Type | Description | Validation | +|------------------|---------------------------|---------------------------------------------------------------------------------------------------|---------------------------------------------------| +| Address | [Address](#address) | Validators Address | Length must be of size 20 | +| Pubkey | slice of bytes (`[]byte`) | Validators Public Key | must be a length greater than 0 | +| VotingPower | int64 | Validators voting power | cannot be < 0 | +| ProposerPriority | int64 | Validators proposer priority. This is used to gauge when a validator is up next to propose blocks | No validation, value can be negative and positive | + +## Address + +Address is a type alias of a slice of bytes. The address is calculated by hashing the public key using sha256 and truncating it to only use the first 20 bytes of the slice. + +```go +const ( + TruncatedSize = 20 +) + +func SumTruncated(bz []byte) []byte { + hash := sha256.Sum256(bz) + return hash[:TruncatedSize] +} +``` + +## ConsensusParams + +| Name | Type | Description | Field Number | +|-----------|-------------------------------------|------------------------------------------------------------------------------|--------------| +| block | [BlockParams](#blockparams) | Parameters limiting the size of a block and time between consecutive blocks. | 1 | +| evidence | [EvidenceParams](#evidenceparams) | Parameters limiting the validity of evidence of byzantine behavior. | 2 | +| validator | [ValidatorParams](#validatorparams) | Parameters limiting the types of public keys validators can use. | 3 | +| version | [BlockParams](#blockparams) | The ABCI application version. | 4 | + +### BlockParams + +| Name | Type | Description | Field Number | +|--------------|-------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------| +| max_bytes | int64 | Max size of a block, in bytes. | 1 | +| max_gas | int64 | Max sum of `GasWanted` in a proposed block. NOTE: blocks that violate this may be committed if there are Byzantine proposers. It's the application's responsibility to handle this when processing a block! | 2 | + +### EvidenceParams + +| Name | Type | Description | Field Number | +|--------------------|------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------| +| max_age_num_blocks | int64 | Max age of evidence, in blocks. | 1 | +| max_age_duration | [google.protobuf.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration) | Max age of evidence, in time. It should correspond with an app's "unbonding period" or other similar mechanism for handling [Nothing-At-Stake attacks](https://vitalik.ca/general/2017/12/31/pos_faq.html#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). | 2 | +| max_bytes | int64 | maximum size in bytes of total evidence allowed to be entered into a block | 3 | + +### ValidatorParams + +| Name | Type | Description | Field Number | +|---------------|-----------------|-----------------------------------------------------------------------|--------------| +| pub_key_types | repeated string | List of accepted public key types. Uses same naming as `PubKey.Type`. | 1 | + +### VersionParams + +| Name | Type | Description | Field Number | +|-------------|--------|-------------------------------|--------------| +| app_version | uint64 | The ABCI application version. | 1 | + +## Proof + +| Name | Type | Description | Field Number | +|-----------|----------------|-----------------------------------------------|--------------| +| total | int64 | Total number of items. | 1 | +| index | int64 | Index item to prove. | 2 | +| leaf_hash | bytes | Hash of item value. | 3 | +| aunts | repeated bytes | Hashes from leaf's sibling to a root's child. | 4 | diff --git a/spec/core/encoding.md b/spec/core/encoding.md new file mode 100644 index 0000000..a41b91b --- /dev/null +++ b/spec/core/encoding.md @@ -0,0 +1,304 @@ +--- +order: 2 +--- + +# Encoding + +## Protocol Buffers + +CometBFT uses [Protocol Buffers](https://developers.google.com/protocol-buffers), specifically proto3, for all data structures. + +Please see the [Proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) for more details. + +## Byte Arrays + +The encoding of a byte array is simply the raw-bytes prefixed with the length of +the array as a `UVarint` (what proto calls a `Varint`). + +For details on varints, see the [protobuf +spec](https://developers.google.com/protocol-buffers/docs/encoding#varints). + +For example, the byte-array `[0xA, 0xB]` would be encoded as `0x020A0B`, +while a byte-array containing 300 entires beginning with `[0xA, 0xB, ...]` would +be encoded as `0xAC020A0B...` where `0xAC02` is the UVarint encoding of 300. + +## Hashing + +CometBFT uses `SHA256` as its hash function. +Objects are always serialized before being hashed. +So `SHA256(obj)` is short for `SHA256(ProtoEncoding(obj))`. + +## Public Key Cryptography + +CometBFT uses Protobuf [Oneof](https://developers.google.com/protocol-buffers/docs/proto3#oneof) +to distinguish between different types public keys, and signatures. +Additionally, for each public key, CometBFT +defines an Address function that can be used as a more compact identifier in +place of the public key. Here we list the concrete types, their names, +and prefix bytes for public keys and signatures, as well as the address schemes +for each PubKey. Note for brevity we don't +include details of the private keys beyond their type and name. + +### Key Types + +Each type specifies it's own pubkey, address, and signature format. + +#### Ed25519 + +The address is the first 20-bytes of the SHA256 hash of the raw 32-byte public key: + +```go +address = SHA256(pubkey)[:20] +``` + +The signature is the raw 64-byte ED25519 signature. + +CometBFT adopts [zip215](https://zips.z.cash/zip-0215) for verification of ed25519 signatures. + +> Note: This change will be released in the next major release of CometBFT. + +#### Secp256k1 + +The address is the first 20-bytes of the SHA256 hash of the raw 32-byte public key: + +```go +address = SHA256(pubkey)[:20] +``` + +## Other Common Types + +### BitArray + +The BitArray is used in some consensus messages to represent votes received from +validators, or parts received in a block. It is represented +with a struct containing the number of bits (`Bits`) and the bit-array itself +encoded in base64 (`Elems`). + +| Name | Type | +|-------|----------------------------| +| bits | int64 | +| elems | slice of int64 (`[]int64`) | + +Note BitArray receives a special JSON encoding in the form of `x` and `_` +representing `1` and `0`. Ie. the BitArray `10110` would be JSON encoded as +`"x_xx_"` + +### Part + +Part is used to break up blocks into pieces that can be gossiped in parallel +and securely verified using a Merkle tree of the parts. + +Part contains the index of the part (`Index`), the actual +underlying data of the part (`Bytes`), and a Merkle proof that the part is contained in +the set (`Proof`). + +| Name | Type | +|-------|---------------------------| +| index | uint32 | +| bytes | slice of bytes (`[]byte`) | +| proof | [proof](#merkle-proof) | + +See details of SimpleProof, below. + +### MakeParts + +Encode an object using Protobuf and slice it into parts. +CometBFT uses a part size of 65536 bytes, and allows a maximum of 1601 parts +(see `types.MaxBlockPartsCount`). This corresponds to the hard-coded block size +limit of 100MB. + +```go +func MakeParts(block Block) []Part +``` + +## Merkle Trees + +For an overview of Merkle trees, see +[wikipedia](https://en.wikipedia.org/wiki/Merkle_tree) + +We use the RFC 6962 specification of a merkle tree, with sha256 as the hash function. +Merkle trees are used throughout CometBFT to compute a cryptographic digest of a data structure. +The differences between RFC 6962 and the simplest form a merkle tree are that: + +1. leaf nodes and inner nodes have different hashes. + This is for "second pre-image resistance", to prevent the proof to an inner node being valid as the proof of a leaf. + The leaf nodes are `SHA256(0x00 || leaf_data)`, and inner nodes are `SHA256(0x01 || left_hash || right_hash)`. + +2. When the number of items isn't a power of two, the left half of the tree is as big as it could be. + (The largest power of two less than the number of items) This allows new leaves to be added with less + recomputation. For example: + +```md + Simple Tree with 6 items Simple Tree with 7 items + + * * + / \ / \ + / \ / \ + / \ / \ + / \ / \ + * * * * + / \ / \ / \ / \ + / \ / \ / \ / \ + / \ / \ / \ / \ + * * h4 h5 * * * h6 + / \ / \ / \ / \ / \ +h0 h1 h2 h3 h0 h1 h2 h3 h4 h5 +``` + +### MerkleRoot + +The function `MerkleRoot` is a simple recursive function defined as follows: + +```go +// SHA256([]byte{}) +func emptyHash() []byte { + return tmhash.Sum([]byte{}) +} + +// SHA256(0x00 || leaf) +func leafHash(leaf []byte) []byte { + return tmhash.Sum(append(0x00, leaf...)) +} + +// SHA256(0x01 || left || right) +func innerHash(left []byte, right []byte) []byte { + return tmhash.Sum(append(0x01, append(left, right...)...)) +} + +// largest power of 2 less than k +func getSplitPoint(k int) { ... } + +func MerkleRoot(items [][]byte) []byte{ + switch len(items) { + case 0: + return empthHash() + case 1: + return leafHash(items[0]) + default: + k := getSplitPoint(len(items)) + left := MerkleRoot(items[:k]) + right := MerkleRoot(items[k:]) + return innerHash(left, right) + } +} +``` + +Note: `MerkleRoot` operates on items which are arbitrary byte arrays, not +necessarily hashes. For items which need to be hashed first, we introduce the +`Hashes` function: + +```go +func Hashes(items [][]byte) [][]byte { + return SHA256 of each item +} +``` + +Note: we will abuse notion and invoke `MerkleRoot` with arguments of type `struct` or type `[]struct`. +For `struct` arguments, we compute a `[][]byte` containing the protobuf encoding of each +field in the struct, in the same order the fields appear in the struct. +For `[]struct` arguments, we compute a `[][]byte` by protobuf encoding the individual `struct` elements. + +### Merkle Proof + +Proof that a leaf is in a Merkle tree is composed as follows: + +| Name | Type | +|----------|----------------------------| +| total | int64 | +| index | int64 | +| leafHash | slice of bytes (`[]byte`) | +| aunts | Matrix of bytes ([][]byte) | + +Which is verified as follows: + +```golang +func (proof Proof) Verify(rootHash []byte, leaf []byte) bool { + assert(proof.LeafHash, leafHash(leaf) + + computedHash := computeHashFromAunts(proof.Index, proof.Total, proof.LeafHash, proof.Aunts) + return computedHash == rootHash +} + +func computeHashFromAunts(index, total int, leafHash []byte, innerHashes [][]byte) []byte{ + assert(index < total && index >= 0 && total > 0) + + if total == 1{ + assert(len(proof.Aunts) == 0) + return leafHash + } + + assert(len(innerHashes) > 0) + + numLeft := getSplitPoint(total) // largest power of 2 less than total + if index < numLeft { + leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1]) + assert(leftHash != nil) + return innerHash(leftHash, innerHashes[len(innerHashes)-1]) + } + rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1]) + assert(rightHash != nil) + return innerHash(innerHashes[len(innerHashes)-1], rightHash) +} +``` + +The number of aunts is limited to 100 (`MaxAunts`) to protect the node against DOS attacks. +This limits the tree size to 2^100 leaves, which should be sufficient for any +conceivable purpose. + +### IAVL+ Tree + +Because CometBFT only uses a Simple Merkle Tree, application developers are expect to use their own Merkle tree in their applications. For example, the IAVL+ Tree - an immutable self-balancing binary tree for persisting application state is used by the [Cosmos SDK](https://github.com/cosmos/cosmos-sdk/blob/ae77f0080a724b159233bd9b289b2e91c0de21b5/docs/interfaces/lite/specification.md) + +## JSON + +CometBFT has its own JSON encoding in order to keep backwards compatibility with the previous RPC layer. + +Registered types are encoded as: + +```json +{ + "type": "", + "value": +} +``` + +For instance, an ED25519 PubKey would look like: + +```json +{ + "type": "tendermint/PubKeyEd25519", + "value": "uZ4h63OFWuQ36ZZ4Bd6NF+/w9fWUwrOncrQsackrsTk=" +} +``` + +Where the `"value"` is the base64 encoding of the raw pubkey bytes, and the +`"type"` is the type name for Ed25519 pubkeys. + +### Signed Messages + +Signed messages (eg. votes, proposals) in the consensus are encoded using protobuf. + +When signing, the elements of a message are re-ordered so the fixed-length fields +are first, making it easy to quickly check the type, height, and round. +The `ChainID` is also appended to the end. +We call this encoding the SignBytes. For instance, SignBytes for a vote is the protobuf encoding of the following struct: + +```protobuf +message CanonicalVote { + SignedMsgType type = 1; + sfixed64 height = 2; // canonicalization requires fixed size encoding here + sfixed64 round = 3; // canonicalization requires fixed size encoding here + CanonicalBlockID block_id = 4; + google.protobuf.Timestamp timestamp = 5; + string chain_id = 6; +} +``` + +The field ordering and the fixed sized encoding for the first three fields is optimized to ease parsing of SignBytes +in HSMs. It creates fixed offsets for relevant fields that need to be read in this context. + +> Note: All canonical messages are length prefixed. + +For more details, see the [signing spec](../consensus/signing.md). +Also, see the motivating discussion in +[#1622](https://github.com/tendermint/tendermint/issues/1622). diff --git a/spec/core/genesis.md b/spec/core/genesis.md new file mode 100644 index 0000000..f8ab76a --- /dev/null +++ b/spec/core/genesis.md @@ -0,0 +1,38 @@ +--- +order: 3 +--- + +# Genesis + +The genesis file is the starting point of a chain. An application will populate the `app_state` field in the genesis with their required fields. CometBFT is not able to validate this section because it is unaware what application state consists of. + +## Genesis Fields + +- `genesis_time`: The genesis time is the time the blockchain started or will start. If nodes are started before this time they will sit idle until the time specified. +- `chain_id`: The chainid is the chain identifier. Every chain should have a unique identifier. When conducting a fork based upgrade, we recommend changing the chainid to avoid network or consensus errors. +- `initial_height`: This field is the starting height of the blockchain. When conducting a chain restart to avoid restarting at height 1, the network is able to start at a specified height. +- `consensus_params` + - `block` + - `max_bytes`: The max amount of bytes a block can be. + - `max_gas`: The maximum amount of gas that a block can have. + - `time_iota_ms`: This parameter has no value anymore in CometBFT. + +- `evidence` + - `max_age_num_blocks`: After this preset amount of blocks has passed a single piece of evidence is considered invalid + - `max_age_duration`: After this preset amount of time has passed a single piece of evidence is considered invalid. + - `max_bytes`: The max amount of bytes of all evidence included in a block. + +> Note: For evidence to be considered invalid, evidence must be older than both `max_age_num_blocks` and `max_age_duration` + +- `validator` + - `pub_key_types`: Defines which curves are to be accepted as a valid validator consensus key. CometBFT supports ed25519, sr25519 and secp256k1. + +- `version` + - `app_version`: The version of the application. This is set by the application and is used to identify which version of the app a user should be using in order to operate a node. + +- `validators` + - This is an array of validators. This validator set is used as the starting validator set of the chain. This field can be empty, if the application sets the validator set in `InitChain`. + +- `app_hash`: The applications state root hash. This field does not need to be populated at the start of the chain, the application may provide the needed information via `Initchain`. + +- `app_state`: This section is filled in by the application and is unknown to CometBFT. diff --git a/spec/core/readme.md b/spec/core/readme.md new file mode 100644 index 0000000..f2bf5b6 --- /dev/null +++ b/spec/core/readme.md @@ -0,0 +1,13 @@ +--- +order: 1 +parent: + title: Core + order: 3 +--- + +This section describes the core types and functionality of the CometBFT protocol implementation. + +- [Core Data Structures](./data_structures.md) +- [Encoding](./encoding.md) +- [Genesis](./genesis.md) +- [State](./state.md) diff --git a/spec/core/state.md b/spec/core/state.md new file mode 100644 index 0000000..1c643e2 --- /dev/null +++ b/spec/core/state.md @@ -0,0 +1,131 @@ +--- +order: 4 +--- + +# State + +The state contains information whose cryptographic digest is included in block headers, and thus is +necessary for validating new blocks. For instance, the validators set and the results of +transactions are never included in blocks, but their Merkle roots are: +the state keeps track of them. + +The `State` object itself is an implementation detail, since it is never +included in a block or gossiped over the network, and we never compute +its hash. The persistence or query interface of the `State` object +is an implementation detail and not included in the specification. +However, the types in the `State` object are part of the specification, since +the Merkle roots of the `State` objects are included in blocks and values are used during +validation. + +```go +type State struct { + ChainID string + InitialHeight int64 + + LastBlockHeight int64 + LastBlockID types.BlockID + LastBlockTime time.Time + + Version Version + LastResults []Result + AppHash []byte + + LastValidators ValidatorSet + Validators ValidatorSet + NextValidators ValidatorSet + + ConsensusParams ConsensusParams +} +``` + +The chain ID and initial height are taken from the genesis file, and not changed again. The +initial height will be `1` in the typical case, `0` is an invalid value. + +Note there is a hard-coded limit of 10000 validators. This is inherited from the +limit on the number of votes in a commit. + +Further information on [`Validator`'s](./data_structures.md#validator), +[`ValidatorSet`'s](./data_structures.md#validatorset) and +[`ConsensusParams`'s](./data_structures.md#consensusparams) can +be found in [data structures](./data_structures.md) + +## Execution + +State gets updated at the end of executing a block. Of specific interest is `ResponseEndBlock` and +`ResponseCommit` + +```go +type ResponseEndBlock struct { + ValidatorUpdates []ValidatorUpdate `protobuf:"bytes,1,rep,name=validator_updates,json=validatorUpdates,proto3" json:"validator_updates"` + ConsensusParamUpdates *types1.ConsensusParams `protobuf:"bytes,2,opt,name=consensus_param_updates,json=consensusParamUpdates,proto3" json:"consensus_param_updates,omitempty"` + Events []Event `protobuf:"bytes,3,rep,name=events,proto3" json:"events,omitempty"` +} +``` + +where + +```go +type ValidatorUpdate struct { + PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` + Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"` +} +``` + +and + +```go +type ResponseCommit struct { + // reserve 1 + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` + RetainHeight int64 `protobuf:"varint,3,opt,name=retain_height,json=retainHeight,proto3" json:"retain_height,omitempty"` +} +``` + +`ValidatorUpdates` are used to add and remove validators to the current set as well as update +validator power. Setting validator power to 0 in `ValidatorUpdate` will cause the validator to be +removed. `ConsensusParams` are safely copied across (i.e. if a field is nil it gets ignored) and the +`Data` from the `ResponseCommit` is used as the `AppHash` + +## Version + +```go +type Version struct { + consensus Consensus + software string +} +``` + +[`Consensus`](./data_structures.md#version) contains the protocol version for the blockchain and the +application. + +## Block + +The total size of a block is limited in bytes by the `ConsensusParams.Block.MaxBytes`. +Proposed blocks must be less than this size, and will be considered invalid +otherwise. + +The Application may set `ConsensusParams.Block.MaxBytes` to -1. +In that case, the actual block limit is set to 100 MB, +and CometBFT will provide all transactions in the mempool as part of `PrepareProposal`. +The application has to be careful to return a list of transactions in `ResponsePrepareProposal` +whose size is less than or equal to `RequestPrepareProposal.MaxTxBytes`. + +Blocks should additionally be limited by the amount of "gas" consumed by the +transactions in the block, though this is not yet implemented. + +## Evidence + +For evidence in a block to be valid, it must satisfy: + +```go +block.Header.Time-evidence.Time < ConsensusParams.Evidence.MaxAgeDuration && + block.Header.Height-evidence.Height < ConsensusParams.Evidence.MaxAgeNumBlocks +``` + +A block must not contain more than `ConsensusParams.Evidence.MaxBytes` of evidence. This is +implemented to mitigate spam attacks. + +## Validator + +Validators from genesis file and `ResponseEndBlock` must have pubkeys of type ∈ +`ConsensusParams.Validator.PubKeyTypes`. diff --git a/spec/ivy-proofs/Dockerfile b/spec/ivy-proofs/Dockerfile new file mode 100644 index 0000000..ab8bc31 --- /dev/null +++ b/spec/ivy-proofs/Dockerfile @@ -0,0 +1,37 @@ +# we need python2 support, which was dropped after buster: +FROM debian:buster + +RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections +RUN apt-get update +RUN apt-get install -y apt-utils + +# Install and configure locale `en_US.UTF-8` +RUN apt-get install -y locales && \ + sed -i -e "s/# $en_US.*/en_US.UTF-8 UTF-8/" /etc/locale.gen && \ + dpkg-reconfigure --frontend=noninteractive locales && \ + update-locale LANG=en_US.UTF-8 +ENV LANG=en_US.UTF-8 + +RUN apt-get update +RUN apt-get install -y git python2 python-pip g++ cmake python-ply python-tk tix pkg-config libssl-dev python-setuptools + +# create a user: +RUN useradd -ms /bin/bash user +USER user +WORKDIR /home/user + +RUN git clone --recurse-submodules https://github.com/kenmcmil/ivy.git +WORKDIR /home/user/ivy/ +RUN git checkout 271ee38980699115508eb90a0dd01deeb750a94b + +RUN python2.7 build_submodules.py +RUN mkdir -p "/home/user/python/lib/python2.7/site-packages" +ENV PYTHONPATH="/home/user/python/lib/python2.7/site-packages" +# need to install pyparsing manually because otherwise wrong version found +RUN pip install pyparsing +RUN python2.7 setup.py install --prefix="/home/user/python/" +ENV PATH=$PATH:"/home/user/python/bin/" +WORKDIR /home/user/tendermint-proof/ + +ENTRYPOINT ["/home/user/tendermint-proof/check_proofs.sh"] + diff --git a/spec/ivy-proofs/README.md b/spec/ivy-proofs/README.md new file mode 100644 index 0000000..2dcbf1f --- /dev/null +++ b/spec/ivy-proofs/README.md @@ -0,0 +1,33 @@ +# Ivy Proofs + +```copyright +Copyright (c) 2020 Galois, Inc. +SPDX-License-Identifier: Apache-2.0 +``` + +## Contents + +This folder contains: + +* `tendermint.ivy`, a specification of Tendermint algorithm as described in *The latest gossip on BFT consensus* by E. Buchman, J. Kwon, Z. Milosevic. +* `abstract_tendermint.ivy`, a more abstract specification of Tendermint that is more verification-friendly. +* `classic_safety.ivy`, a proof that Tendermint satisfies the classic safety property of BFT consensus: if every two quorums have a well-behaved node in common, then no two well-behaved nodes ever disagree. +* `accountable_safety_1.ivy`, a proof that, assuming every quorum contains at least one well-behaved node, if two well-behaved nodes disagree, then there is evidence demonstrating at least f+1 nodes misbehaved. +* `accountable_safety_2.ivy`, a proof that, regardless of any assumption about quorums, well-behaved nodes cannot be framed by malicious nodes. In other words, malicious nodes can never construct evidence that incriminates a well-behaved node. +* `network_shim.ivy`, the network model and a convenience `shim` object to interface with the Tendermint specification. +* `domain_model.ivy`, a specification of the domain model underlying the Tendermint specification, i.e. rounds, value, quorums, etc. + +All specifications and proofs are written in [Ivy](https://github.com/kenmcmil/ivy). + +The license above applies to all files in this folder. + + +## Building and running + +The easiest way to check the proofs is to use [Docker](https://www.docker.com/). + +1. Install [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/). +2. Build a Docker image: `docker-compose build` +3. Run the proofs inside the Docker container: `docker-compose run +tendermint-proof`. This will check all the proofs with the `ivy_check` +command and write the output of `ivy_check` to a subdirectory of `./output/' diff --git a/spec/ivy-proofs/abstract_tendermint.ivy b/spec/ivy-proofs/abstract_tendermint.ivy new file mode 100644 index 0000000..4505805 --- /dev/null +++ b/spec/ivy-proofs/abstract_tendermint.ivy @@ -0,0 +1,178 @@ +#lang ivy1.7 +# --- +# layout: page +# title: Abstract specification of Tendermint in Ivy +# --- + +# Here we define an abstract version of the Tendermint specification. We use +# two main forms of abstraction: a) We abstract over how information is +# transmitted (there is no network). b) We abstract functions using relations. +# For example, we abstract over a node's current round, instead only tracking +# with a relation which rounds the node has left. We do something similar for +# the `lockedRound` variable. This is in order to avoid using a function from +# node to round, and it allows us to emit verification conditions that are +# efficiently solvable by Z3. + +# This specification also defines the observations that are used to adjudicate +# misbehavior. Well-behaved nodes faithfully observe every message that they +# use to take a step, while Byzantine nodes can fake observations about +# themselves (including withholding observations). Misbehavior is defined using +# the collection of all observations made (in reality, those observations must +# be collected first, but we do not model this process). + +include domain_model + +module abstract_tendermint = { + +# Protocol state +# ############## + + relation left_round(N:node, R:round) + relation prevoted(N:node, R:round, V:value) + relation precommitted(N:node, R:round, V:value) + relation decided(N:node, R:round, V:value) + relation locked(N:node, R:round, V:value) + +# Accountability relations +# ######################## + + relation observed_prevoted(N:node, R:round, V:value) + relation observed_precommitted(N:node, R:round, V:value) + +# relations that are defined in terms of the previous two: + relation observed_equivocation(N:node) + relation observed_unlawful_prevote(N:node) + relation agreement + relation accountability_violation + + object defs = { # we hide those definitions and use them only when needed + private { + definition [observed_equivocation_def] observed_equivocation(N) = exists V1,V2,R . + V1 ~= V2 & (observed_precommitted(N,R,V1) & observed_precommitted(N,R,V2) | observed_prevoted(N,R,V1) & observed_prevoted(N,R,V2)) + + definition [observed_unlawful_prevote_def] observed_unlawful_prevote(N) = exists V1,V2,R1,R2 . + V1 ~= value.nil & V2 ~= value.nil & V1 ~= V2 & R1 < R2 & observed_precommitted(N,R1,V1) & observed_prevoted(N,R2,V2) + & forall Q,R . R1 <= R & R < R2 & nset.is_quorum(Q) -> exists N2 . nset.member(N2,Q) & ~observed_prevoted(N2,R,V2) + + definition [agreement_def] agreement = forall N1,N2,R1,R2,V1,V2 . well_behaved(N1) & well_behaved(N2) & decided(N1,R1,V1) & decided(N2,R2,V2) -> V1 = V2 + + definition [accountability_violation_def] accountability_violation = exists Q1,Q2 . nset.is_quorum(Q1) & nset.is_quorum(Q2) & (forall N . nset.member(N,Q1) & nset.member(N,Q2) -> observed_equivocation(N) | observed_unlawful_prevote(N)) + } + } + +# Protocol transitions +# #################### + + after init { + left_round(N,R) := R < 0; + prevoted(N,R,V) := false; + precommitted(N,R,V) := false; + decided(N,R,V) := false; + locked(N,R,V) := false; + + observed_prevoted(N,R,V) := false; + observed_precommitted(N,R,V) := false; + } + +# Actions are named after the corresponding line numbers in the Tendermint +# arXiv paper. + + action l_11(n:node, r:round) = { # start round r + require ~left_round(n,r); + left_round(n,R) := R < r; + } + + action l_22(n:node, rp:round, v:value) = { + require ~left_round(n,rp); + require ~prevoted(n,rp,V) & ~precommitted(n,rp,V); + require (forall R,V . locked(n,R,V) -> V = v) | v = value.nil; + prevoted(n, rp, v) := true; + left_round(n, R) := R < rp; # leave all lower rounds. + + observed_prevoted(n, rp, v) := observed_prevoted(n, rp, v) | well_behaved(n); # the node observes itself + } + + action l_28(n:node, rp:round, v:value, vr:round, q:nset) = { + require ~left_round(n,rp) & ~prevoted(n,rp,V); + require ~prevoted(n,rp,V) & ~precommitted(n,rp,V); + require vr < rp; + require nset.is_quorum(q) & (forall N . nset.member(N,q) -> (prevoted(N,vr,v) | ~well_behaved(N))); + var proposal:value; + if value.valid(v) & ((forall R0,V0 . locked(n,R0,V0) -> R0 <= vr) | (forall R,V . locked(n,R,V) -> V = v)) { + proposal := v; + } + else { + proposal := value.nil; + }; + prevoted(n, rp, proposal) := true; + left_round(n, R) := R < rp; # leave all lower rounds + + observed_prevoted(N, vr, v) := observed_prevoted(N, vr, v) | (well_behaved(n) & nset.member(N,q)); # the node observes the prevotes of quorum q + observed_prevoted(n, rp, proposal) := observed_prevoted(n, rp, proposal) | well_behaved(n); # the node observes itself + } + + action l_36(n:node, rp:round, v:value, q:nset) = { + require v ~= value.nil; + require ~left_round(n,rp); + require exists V . prevoted(n,rp,V); + require ~precommitted(n,rp,V); + require nset.is_quorum(q) & (forall N . nset.member(N,q) -> (prevoted(N,rp,v) | ~well_behaved(N))); + precommitted(n, rp, v) := true; + left_round(n, R) := R < rp; # leave all lower rounds + locked(n,R,V) := R <= rp & V = v; + + observed_prevoted(N, rp, v) := observed_prevoted(N, rp, v) | (well_behaved(n) & nset.member(N,q)); # the node observes the prevotes of quorum q + observed_precommitted(n, rp, v) := observed_precommitted(n, rp, v) | well_behaved(n); # the node observes itself + } + + action l_44(n:node, rp:round, q:nset) = { + require ~left_round(n,rp); + require ~precommitted(n,rp,V); + require nset.is_quorum(q) & (forall N .nset.member(N,q) -> (prevoted(N,rp,value.nil) | ~well_behaved(N))); + precommitted(n, rp, value.nil) := true; + left_round(n, R) := R < rp; # leave all lower rounds + + observed_prevoted(N, rp, value.nil) := observed_prevoted(N, rp, value.nil) | (well_behaved(n) & nset.member(N,q)); # the node observes the prevotes of quorum q + observed_precommitted(n, rp, value.nil) := observed_precommitted(n, rp, value.nil) | well_behaved(n); # the node observes itself + } + + action l_57(n:node, rp:round) = { + require ~left_round(n,rp); + require ~prevoted(n,rp,V); + prevoted(n, rp, value.nil) := true; + left_round(n, R) := R < rp; # leave all lower rounds + + observed_prevoted(n, rp, value.nil) := observed_prevoted(n, rp, value.nil) | well_behaved(n); # the node observes itself + } + + action l_61(n:node, rp:round) = { + require ~left_round(n,rp); + require ~precommitted(n,rp,V); + precommitted(n, rp, value.nil) := true; + left_round(n, R) := R < rp; # leave all lower rounds + + observed_precommitted(n, rp, value.nil) := observed_precommitted(n, rp, value.nil) | well_behaved(n); # the node observes itself + } + + action decide(n:node, r:round, v:value, q:nset) = { + require v ~= value.nil; + require nset.is_quorum(q) & (forall N . nset.member(N, q) -> (precommitted(N, r, v) | ~well_behaved(N))); + decided(n, r, v) := true; + + observed_precommitted(N, r, v) := observed_precommitted(N, r, v) | (well_behaved(n) & nset.member(N,q)); # the node observes the precommits of quorum q + + } + + action misbehave = { +# Byzantine nodes can claim they observed whatever they want about themselves, +# but they cannot remove observations. Note that we use assume because we don't +# want those to be checked; we just want them to be true (that's the model of +# Byzantine behavior). + observed_prevoted(N,R,V) := *; + assume (old observed_prevoted(N,R,V)) -> observed_prevoted(N,R,V); + assume well_behaved(N) -> old observed_prevoted(N,R,V) = observed_prevoted(N,R,V); + observed_precommitted(N,R,V) := *; + assume (old observed_precommitted(N,R,V)) -> observed_precommitted(N,R,V); + assume well_behaved(N) -> old observed_precommitted(N,R,V) = observed_precommitted(N,R,V); + } +} diff --git a/spec/ivy-proofs/accountable_safety_1.ivy b/spec/ivy-proofs/accountable_safety_1.ivy new file mode 100644 index 0000000..9aa7e58 --- /dev/null +++ b/spec/ivy-proofs/accountable_safety_1.ivy @@ -0,0 +1,143 @@ +#lang ivy1.7 +# --- +# layout: page +# title: Proof of Classic Safety +# --- + +include tendermint +include abstract_tendermint + +# Here we prove the first accountability property: if two well-behaved nodes +# disagree, then there are two quorums Q1 and Q2 such that all members of the +# intersection of Q1 and Q2 have violated the accountability properties. + +# The proof is done in two steps: first we prove the abstract specification +# satisfies the property, and then we show by refinement that this property +# also holds in the concrete specification. + +# To see what is checked in the refinement proof, use `ivy_show isolate=accountable_safety_1 accountable_safety_1.ivy` +# To see what is checked in the abstract correctness proof, use `ivy_show isolate=abstract_accountable_safety_1 accountable_safety_1.ivy` +# To check the whole proof, use `ivy_check accountable_safety_1.ivy`. + + +# Proof of the accountability property in the abstract specification +# ================================================================== + +# We prove with tactics (see `lemma_1` and `lemma_2`) that, if some basic +# invariants hold (see `invs` below), then the accountability property holds. + +isolate abstract_accountable_safety = { + + instantiate abstract_tendermint + +# The main property +# ----------------- + +# If there is disagreement, then there is evidence that a third of the nodes +# have violated the protocol: + invariant [accountability] agreement | accountability_violation + proof { + apply lemma_1.thm # this reduces to goal to three subgoals: p1, p2, and p3 (see their definition below) + proof [p1] { + assume invs.inv1 + } + proof [p2] { + assume invs.inv2 + } + proof [p3] { + assume invs.inv3 + } + } + +# The invariants +# -------------- + + isolate invs = { + + # well-behaved nodes observe their own actions faithfully: + invariant [inv1] well_behaved(N) -> (observed_precommitted(N,R,V) = precommitted(N,R,V)) + # if a value is precommitted by a well-behaved node, then a quorum is observed to prevote it: + invariant [inv2] (exists N . well_behaved(N) & precommitted(N,R,V)) & V ~= value.nil -> exists Q . nset.is_quorum(Q) & forall N2 . nset.member(N2,Q) -> observed_prevoted(N2,R,V) + # if a value is decided by a well-behaved node, then a quorum is observed to precommit it: + invariant [inv3] (exists N . well_behaved(N) & decided(N,R,V)) -> 0 <= R & V ~= value.nil & exists Q . nset.is_quorum(Q) & forall N2 . nset.member(N2,Q) -> observed_precommitted(N2,R,V) + private { + invariant (precommitted(N,R,V) | prevoted(N,R,V)) -> 0 <= R + invariant R < 0 -> left_round(N,R) + } + + } with this, nset, round, accountable_bft.max_2f_byzantine + +# The theorems proved with tactics +# -------------------------------- + +# Using complete induction on rounds, we prove that, assuming that the +# invariants inv1, inv2, and inv3 hold, the accountability property holds. + +# For technical reasons, we separate the proof in two steps + isolate lemma_1 = { + + specification { + theorem [thm] { + property [p1] forall N,R,V . well_behaved(N) -> (observed_precommitted(N,R,V) = precommitted(N,R,V)) + property [p2] forall R,V . (exists N . well_behaved(N) & precommitted(N,R,V)) & V ~= value.nil -> exists Q . nset.is_quorum(Q) & forall N2 . nset.member(N2,Q) -> observed_prevoted(N2,R,V) + property [p3] forall R,V. (exists N . well_behaved(N) & decided(N,R,V)) -> 0 <= R & V ~= value.nil & exists Q . nset.is_quorum(Q) & forall N2 . nset.member(N2,Q) -> observed_precommitted(N2,R,V) + #------------------------------------------------------------------------------------------------------------------------------------------- + property agreement | accountability_violation + } + proof { + assume inductive_property # the theorem follows from what we prove by induction below + } + } + + implementation { + # complete induction is not built-in, so we introduce it with an axiom. Note that this only holds for a type where 0 is the smallest element + axiom [complete_induction] { + relation p(X:round) + { # base case + property p(0) + } + { # inductive step: show that if the property is true for all X lower or equal to x and y=x+1, then the property is true of y + individual a:round + individual b:round + property (forall X. 0 <= X & X <= a -> p(X)) & round.succ(a,b) -> p(b) + } + #-------------------------- + property forall X . 0 <= X -> p(X) + } + + # The main lemma: if inv1 and inv2 below hold and a quorum is observed to + # precommit V1 at R1 and another quorum is observed to precommit V2~=V1 at + # R2>=R1, then the intersection of two quorums (i.e. f+1 nodes) is observed to + # violate the protocol. We prove this by complete induction on R2. + theorem [inductive_property] { + property [p1] forall N,R,V . well_behaved(N) -> (observed_precommitted(N,R,V) = precommitted(N,R,V)) + property [p2] forall R,V . (exists N . well_behaved(N) & precommitted(N,R,V)) -> V = value.nil | exists Q . nset.is_quorum(Q) & forall N2 . nset.member(N2,Q) -> observed_prevoted(N2,R,V) + #----------------------------------------------------------------------------------------------------------------------- + property forall R2. 0 <= R2 -> ((exists V2,Q1,R1,V1,Q1 . V1 ~= value.nil & V2 ~= value.nil & V1 ~= V2 & 0 <= R1 & R1 <= R2 & nset.is_quorum(Q1) & (forall N . nset.member(N,Q1) -> observed_precommitted(N,R1,V1)) & (exists Q2 . nset.is_quorum(Q2) & forall N . nset.member(N,Q2) -> observed_prevoted(N,R2,V2))) -> accountability_violation) + } + proof { + apply complete_induction # the two subgoals (base case and inductive case) are then discharged automatically + # NOTE: this can take a long time depending on the SMT random seed (to try a different seed, use `ivy_check seed=$RANDOM` + } + } + } with this, round, nset, accountable_bft.max_2f_byzantine, defs.observed_equivocation_def, defs.observed_unlawful_prevote_def, defs.accountability_violation_def, defs.agreement_def + +} with round + +# The final proof +# =============== + +isolate accountable_safety_1 = { + +# First we instantiate the concrete protocol: + instantiate tendermint(abstract_accountable_safety) + +# We then define what we mean by agreement + relation agreement + definition [agreement_def] agreement = forall N1,N2. well_behaved(N1) & well_behaved(N2) & server.decision(N1) ~= value.nil & server.decision(N2) ~= value.nil -> server.decision(N1) = server.decision(N2) + + invariant abstract_accountable_safety.agreement -> agreement + + invariant [accountability] agreement | abstract_accountable_safety.accountability_violation + +} with value, round, proposers, shim, abstract_accountable_safety, abstract_accountable_safety.defs.agreement_def, accountable_safety_1.agreement_def diff --git a/spec/ivy-proofs/accountable_safety_2.ivy b/spec/ivy-proofs/accountable_safety_2.ivy new file mode 100644 index 0000000..e298112 --- /dev/null +++ b/spec/ivy-proofs/accountable_safety_2.ivy @@ -0,0 +1,52 @@ +#lang ivy1.7 + +include tendermint +include abstract_tendermint + +# Here we prove the second accountability property: no well-behaved node is +# ever observed to violate the accountability properties. + +# The proof is done in two steps: first we prove the the abstract specification +# satisfies the property, and then we show by refinement that this property +# also holds in the concrete specification. + +# To see what is checked in the refinement proof, use `ivy_show isolate=accountable_safety_2 accountable_safety_2.ivy` +# To see what is checked in the abstract correctness proof, use `ivy_show isolate=abstract_accountable_safety_2 accountable_safety_2.ivy` +# To check the whole proof, use `ivy_check complete=fo accountable_safety_2.ivy`. + +# Proof that the property holds in the abstract specification +# ============================================================ + +isolate abstract_accountable_safety_2 = { + + instantiate abstract_tendermint + +# the main property: + invariant [wb_never_punished] well_behaved(N) -> ~(observed_equivocation(N) | observed_unlawful_prevote(N)) + +# the main invariant for proving wb_not_punished: + invariant well_behaved(N) & precommitted(N,R,V) & ~locked(N,R,V) & V ~= value.nil -> exists R2,V2 . V2 ~= value.nil & R < R2 & precommitted(N,R2,V2) & locked(N,R2,V2) + + invariant (exists N . well_behaved(N) & precommitted(N,R,V) & V ~= value.nil) -> exists Q . nset.is_quorum(Q) & forall N . nset.member(N,Q) -> observed_prevoted(N,R,V) + + invariant well_behaved(N) -> (observed_prevoted(N,R,V) <-> prevoted(N,R,V)) + invariant well_behaved(N) -> (observed_precommitted(N,R,V) <-> precommitted(N,R,V)) + +# nodes stop prevoting or precommitting in lower rounds when doing so in a higher round: + invariant well_behaved(N) & prevoted(N,R2,V2) & R1 < R2 -> left_round(N,R1) + invariant well_behaved(N) & locked(N,R2,V2) & R1 < R2 -> left_round(N,R1) + + invariant [precommit_unique_per_round] well_behaved(N) & precommitted(N,R,V1) & precommitted(N,R,V2) -> V1 = V2 + +} with nset, round, abstract_accountable_safety_2.defs.observed_equivocation_def, abstract_accountable_safety_2.defs.observed_unlawful_prevote_def + +# Proof that the property holds in the concrete specification +# =========================================================== + +isolate accountable_safety_2 = { + + instantiate tendermint(abstract_accountable_safety_2) + + invariant well_behaved(N) -> ~(abstract_accountable_safety_2.observed_equivocation(N) | abstract_accountable_safety_2.observed_unlawful_prevote(N)) + +} with round, value, shim, abstract_accountable_safety_2, abstract_accountable_safety_2.defs.observed_equivocation_def, abstract_accountable_safety_2.defs.observed_unlawful_prevote_def diff --git a/spec/ivy-proofs/check_proofs.sh b/spec/ivy-proofs/check_proofs.sh new file mode 100755 index 0000000..002b7af --- /dev/null +++ b/spec/ivy-proofs/check_proofs.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +# returns non-zero error code if any proof fails + +success=0 +log_dir=$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 6) +cmd="ivy_check seed=$RANDOM" +mkdir -p output/$log_dir + +echo "Checking classic safety:" +res=$($cmd classic_safety.ivy | tee "output/$log_dir/classic_safety.txt" | tail -n 1) +if [ "$res" = "OK" ]; then + echo "OK" +else + echo "FAILED" + success=1 +fi + +echo "Checking accountable safety 1:" +res=$($cmd accountable_safety_1.ivy | tee "output/$log_dir/accountable_safety_1.txt" | tail -n 1) +if [ "$res" = "OK" ]; then + echo "OK" +else + echo "FAILED" + success=1 +fi + +echo "Checking accountable safety 2:" +res=$($cmd complete=fo accountable_safety_2.ivy | tee "output/$log_dir/accountable_safety_2.txt" | tail -n 1) +if [ "$res" = "OK" ]; then + echo "OK" +else + echo "FAILED" + success=1 +fi + +echo +echo "See ivy_check output in the output/ folder" +exit $success diff --git a/spec/ivy-proofs/classic_safety.ivy b/spec/ivy-proofs/classic_safety.ivy new file mode 100644 index 0000000..8e6f03b --- /dev/null +++ b/spec/ivy-proofs/classic_safety.ivy @@ -0,0 +1,85 @@ +#lang ivy1.7 +# --- +# layout: page +# title: Proof of Classic Safety +# --- + +include tendermint +include abstract_tendermint + +# Here we prove the classic safety property: assuming that every two quorums +# have a well-behaved node in common, no two well-behaved nodes ever disagree. + +# The proof is done in two steps: first we prove the the abstract specification +# satisfies the property, and then we show by refinement that this property +# also holds in the concrete specification. + +# To see what is checked in the refinement proof, use `ivy_show isolate=classic_safety classic_safety.ivy` +# To see what is checked in the abstract correctness proof, use `ivy_show isolate=abstract_classic_safety classic_safety.ivy` + +# To check the whole proof, use `ivy_check classic_safety.ivy`. + +# Note that all the verification conditions sent to Z3 for this proof are in +# EPR. + +# Classic safety in the abstract model +# ==================================== + +# We start by proving that classic safety holds in the abstract model. + +isolate abstract_classic_safety = { + + instantiate abstract_tendermint + + invariant [classic_safety] classic_bft.quorum_intersection & decided(N1,R1,V1) & decided(N2,R2,V2) -> V1 = V2 + +# The notion of choosable value +# ----------------------------- + + relation choosable(R:round, V:value) + definition choosable(R,V) = exists Q . nset.is_quorum(Q) & forall N . well_behaved(N) & nset.member(N,Q) -> ~left_round(N,R) | precommitted(N,R,V) + +# Main invariants +# --------------- + +# `classic_safety` is inductive relative to those invariants + + invariant [decision_is_quorum_precommit] (exists N1 . decided(N1,R,V)) -> exists Q. nset.is_quorum(Q) & forall N2. well_behaved(N2) & nset.member(N2, Q) -> precommitted(N2,R,V) + + invariant [precommitted_is_quorum_prevote] V ~= value.nil & (exists N1 . precommitted(N1,R,V)) -> exists Q. nset.is_quorum(Q) & forall N2. well_behaved(N2) & nset.member(N2, Q) -> prevoted(N2,R,V) + + invariant [prevote_unique_per_round] prevoted(N,R,V1) & prevoted(N,R,V2) -> V1 = V2 + +# This is the core invariant: as long as a precommitted value is still choosable, it remains protected by a lock and prevents any new value from being prevoted: + invariant [locks] classic_bft.quorum_intersection & V ~= value.nil & precommitted(N,R,V) & choosable(R,V) -> locked(N,R,V) & forall R2,V2 . R < R2 & prevoted(N,R2,V2) -> V2 = V | V2 = value.nil + +# Supporting invariants +# --------------------- + +# The main invariants are inductive relative to those + + invariant decided(N,R,V) -> V ~= value.nil + + invariant left_round(N,R2) & R1 < R2 -> left_round(N,R1) # if a node left round R2>R1, then it also left R1: + + invariant prevoted(N,R2,V2) & R1 < R2 -> left_round(N,R1) + invariant precommitted(N,R2,V2) & R1 < R2 -> left_round(N,R1) + +} with round, nset, classic_bft.quorum_intersection_def + +# The refinement proof +# ==================== + +# Now, thanks to the refinement relation that we establish in +# `concrete_tendermint.ivy`, we prove that classic safety transfers to the +# concrete specification: +isolate classic_safety = { + + # We instantiate the `tendermint` module providing `abstract_classic_safety` as abstract model. + instantiate tendermint(abstract_classic_safety) + + # We prove that if every two quorums have a well-behaved node in common, + # then well-behaved nodes never disagree: + invariant [classic_safety] classic_bft.quorum_intersection & server.decision(N1) ~= value.nil & server.decision(N2) ~= value.nil -> server.decision(N1) = server.decision(N2) + +} with value, round, proposers, shim, abstract_classic_safety # here we list all the specifications that we rely on for this proof diff --git a/spec/ivy-proofs/count_lines.sh b/spec/ivy-proofs/count_lines.sh new file mode 100755 index 0000000..3f51e3b --- /dev/null +++ b/spec/ivy-proofs/count_lines.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +r='^\s*$\|^\s*\#\|^\s*\}\s*$\|^\s*{\s*$' # removes comments and blank lines and lines that contain only { or } +N1=`cat tendermint.ivy domain_model.ivy network_shim.ivy | grep -v $r'\|.*invariant.*' | wc -l` +N2=`cat abstract_tendermint.ivy | grep "observed_" | wc -l` # the observed_* variables specify the observations of the nodes +SPEC_LINES=`expr $N1 + $N2` +echo "spec lines: $SPEC_LINES" +N3=`cat abstract_tendermint.ivy | grep -v $r'\|.*observed_.*' | wc -l` +N4=`cat accountable_safety_1.ivy | grep -v $r | wc -l` +PROOF_LINES=`expr $N3 + $N4` +echo "proof lines: $PROOF_LINES" +RATIO=`bc <<< "scale=2;$PROOF_LINES / $SPEC_LINES"` +echo "proof-to-code ratio for the accountable-safety property: $RATIO" diff --git a/spec/ivy-proofs/docker-compose.yml b/spec/ivy-proofs/docker-compose.yml new file mode 100644 index 0000000..31f5208 --- /dev/null +++ b/spec/ivy-proofs/docker-compose.yml @@ -0,0 +1,7 @@ +version: '3' +services: + tendermint-proof: + build: . + volumes: + - ./:/home/user/tendermint-proof:ro + - ./output:/home/user/tendermint-proof/output:rw diff --git a/spec/ivy-proofs/domain_model.ivy b/spec/ivy-proofs/domain_model.ivy new file mode 100644 index 0000000..d684ffa --- /dev/null +++ b/spec/ivy-proofs/domain_model.ivy @@ -0,0 +1,144 @@ +#lang ivy1.7 + +include order # this is a file from the standard library (`ivy/ivy/include/1.7/order.ivy`) + +isolate round = { + type this + individual minus_one:this + relation succ(R1:round, R2:round) + action incr(i:this) returns (j:this) + specification { +# to simplify verification, we treat rounds as an abstract totally ordered set with a successor relation. + instantiate totally_ordered(this) + property minus_one < 0 + property succ(X,Z) -> (X < Z & ~(X < Y & Y < Z)) + after incr { + ensure succ(i,j) + } + } + implementation { +# here we prove that the abstraction is sound. + interpret this -> int # rounds are integers in the Tendermint specification. + definition minus_one = 0-1 + definition succ(R1,R2) = R2 = R1 + 1 + implement incr { + j := i+1; + } + } +} + +instance node : iterable # nodes are a set with an order, that can be iterated over (see order.ivy in the standard library) + +relation well_behaved(N:node) # whether a node is well-behaved or not. NOTE: Used only in the proof and the Byzantine model; Nodes do know know who is well-behaved and who is not. + +isolate proposers = { + # each round has a unique proposer in Tendermint. In order to avoid a + # function from round to node (which makes verification more difficult), we + # abstract over this function using a relation. + relation is_proposer(N:node, R:round) + export action get_proposer(r:round) returns (n:node) + specification { + property is_proposer(N1,R) & is_proposer(N2,R) -> N1 = N2 + after get_proposer { + ensure is_proposer(n,r); + } + } + implementation { + function f(R:round):node + definition f(r:round) = <<>> + definition is_proposer(N,R) = N = f(R) + implement get_proposer { + n := f(r); + } + } +} + +isolate value = { # the type of values + type this + relation valid(V:value) + individual nil:value + specification { + property ~valid(nil) + } + implementation { + interpret value -> bv[2] + definition nil = <<< -1 >>> # let's say nil is -1 + definition valid(V) = V ~= nil + } +} + +object nset = { # the type of node sets + type this # a set of N=3f+i nodes for 0 + #include + namespace hash_space { + template + class hash > { + public: + size_t operator()(const std::set &s) const { + hash h; + size_t res = 0; + for (const T &e : s) + res += h(e); + return res; + } + }; + } + >>> + interpret nset -> <<< std::set<`node`> >>> + definition member(n:node, s:nset) = <<< `s`.find(`n`) != `s`.end() >>> + definition is_quorum(s:nset) = <<< 3*`s`.size() > 2*`node.size` >>> + definition is_blocking(s:nset) = <<< 3*`s`.size() > `node.size` >>> + implement empty { + <<< + >>> + } + implement insert { + <<< + `t` = `s`; + `t`.insert(`n`); + >>> + } + <<< encode `nset` + + std::ostream &operator <<(std::ostream &s, const `nset` &a) { + s << "{"; + for (auto iter = a.begin(); iter != a.end(); iter++) { + if (iter != a.begin()) s << ", "; + s << *iter; + } + s << "}"; + return s; + } + + template <> + `nset` _arg<`nset`>(std::vector &args, unsigned idx, long long bound) { + throw std::invalid_argument("Not implemented"); // no syntax for nset values in the REPL + } + + >>> + } +} + +object classic_bft = { + relation quorum_intersection + private { + definition [quorum_intersection_def] quorum_intersection = forall Q1,Q2. nset.is_quorum(Q1) & nset.is_quorum(Q2) + -> exists N. well_behaved(N) & nset.member(N, Q1) & nset.member(N, Q2) # every two quorums have a well-behaved node in common + } +} + +trusted isolate accountable_bft = { + # this is our baseline assumption about quorums: + private { + property [max_2f_byzantine] nset.is_quorum(Q) -> exists N . well_behaved(N) & nset.member(N,Q) # every quorum has a well-behaved member + } +} diff --git a/spec/ivy-proofs/network_shim.ivy b/spec/ivy-proofs/network_shim.ivy new file mode 100644 index 0000000..123f73f --- /dev/null +++ b/spec/ivy-proofs/network_shim.ivy @@ -0,0 +1,133 @@ +#lang ivy1.7 +# --- +# layout: page +# title: Network model and network shim +# --- + +# Here we define a network module, which is our model of the network, and a +# shim module that sits on top of the network and which, upon receiving a +# message, calls the appropriate protocol handler. + +include domain_model + +# Here we define an enumeration type for identifying the 3 different types of +# messages that nodes send. +object msg_kind = { # TODO: merge with step_t + type this = {proposal, prevote, precommit} +} + +# Here we define the type of messages `msg`. Its members are structs with the fields described below. +object msg = { + type this = struct { + m_kind : msg_kind, + m_src : node, + m_round : round, + m_value : value, + m_vround : round + } +} + +# This is our model of the network: +isolate net = { + + export action recv(dst:node,v:msg) + action send(src:node,dst:node,v:msg) + # Note that the `recv` action is exported, meaning that it can be called + # non-deterministically by the environment any time it is enabled. In other + # words, a packet that is in flight can be received at any time. In this + # sense, the network is fully asynchronous. Moreover, there is no + # requirement that a given message will be received at all. + + # The state of the network consists of all the packets that have been + # sent so far, along with their destination. + relation sent(V:msg, N:node) + + after init { + sent(V, N) := false + } + + before send { + sent(v,dst) := true + } + + before recv { + require sent(v,dst) # only sent messages can be received. + } +} + +# The network shim sits on top of the network and, upon receiving a message, +# calls the appropriate protocol handler. It also exposes a `broadcast` action +# that sends to all nodes. + +isolate shim = { + + # In order not repeat the same code for each handler, we use a handler + # module parameterized by the type of message it will handle. Below we + # instantiate this module for the 3 types of messages of Tendermint + module handler(p_kind) = { + action handle(dst:node,m:msg) + object spec = { + before handle { + assert sent(m,dst) & m.m_kind = p_kind + } + } + } + + instance proposal_handler : handler(msg_kind.proposal) + instance prevote_handler : handler(msg_kind.prevote) + instance precommit_handler : handler(msg_kind.precommit) + + relation sent(M:msg,N:node) + + action broadcast(src:node,m:msg) + action send(src:node,dst:node,m:msg) + + specification { + after init { + sent(M,D) := false; + } + before broadcast { + sent(m,D) := true + } + before send { + sent(m,dst) := true + } + } + + # Here we give an implementation of it that satisfies its specification: + implementation { + + implement net.recv(dst:node,m:msg) { + + if m.m_kind = msg_kind.proposal { + call proposal_handler.handle(dst,m) + } + else if m.m_kind = msg_kind.prevote { + call prevote_handler.handle(dst,m) + } + else if m.m_kind = msg_kind.precommit { + call precommit_handler.handle(dst,m) + } + } + + implement broadcast { # broadcast sends to all nodes, including the sender. + var iter := node.iter.create(0); + while ~iter.is_end + invariant net.sent(M,D) -> sent(M,D) + { + var n := iter.val; + call net.send(src,n,m); + iter := iter.next; + } + } + + implement send { + call net.send(src,dst,m) + } + + private { + invariant net.sent(M,D) -> sent(M,D) + } + } + +} with net, node # to prove that the shim implementation satisfies the shim specification, we rely on the specification of net and node. diff --git a/spec/ivy-proofs/output/.gitignore b/spec/ivy-proofs/output/.gitignore new file mode 100644 index 0000000..a601d98 --- /dev/null +++ b/spec/ivy-proofs/output/.gitignore @@ -0,0 +1,4 @@ +# Ignore everything in this directory +* +# Except this file +!.gitignore diff --git a/spec/ivy-proofs/tendermint.ivy b/spec/ivy-proofs/tendermint.ivy new file mode 100644 index 0000000..f17e2fa --- /dev/null +++ b/spec/ivy-proofs/tendermint.ivy @@ -0,0 +1,420 @@ +#lang ivy1.7 +# --- +# layout: page +# title: Specification of Tendermint in Ivy +# --- + +# This specification closely follows the pseudo-code given in "The latest +# gossip on BFT consensus" by E. Buchman, J. Kwon, Z. Milosevic +# + +include domain_model +include network_shim + +# We model the Tendermint protocol as an Ivy object. Like in Object-Oriented +# Programming, the basic structuring unit in Ivy is the object. Objects have +# internal state and actions (i.e. methods in OO parlance) that modify their +# state. We model Tendermint as an object whose actions represent steps taken +# by individual nodes in the protocol. Actions in Ivy can have preconditions, +# and a valid execution is a sequence of actions whose preconditions are all +# satisfied in the state in which they are called. + +# For technical reasons, we define below a `tendermint` module instead of an +# object. Ivy modules are a little bit like classes in OO programs, and like +# classes they can be instantiated to obtain objects. To instantiate the +# `tendermint` module, we must provide an abstract-protocol object. This allows +# us to use different abstract-protocol objects for different parts of the +# proof, and to do so without too much notational burden (we could have used +# Ivy monitors, but then we would need to prefix every variable name by the +# name of the object containing it, which clutters things a bit compared to the +# approach we took). + +# The abstract-protocol object is called by the resulting tendermint object so +# as to run the abstract protocol alongside the concrete protocol. This allows +# us to transfer properties proved of the abstract protocol to the concrete +# protocol, as follows. First, we prove that running the abstract protocol in +# this way results in a valid execution of the abstract protocol. This is done +# by checking that all preconditions of the abstract actions are satisfied at +# their call sites. Second, we establish a relation between abstract state and +# concrete state (in the form of invariants of the resulting, two-object +# transition system) that allow us to transfer properties proved in the +# abstract protocol to the concrete protocol (for example, we prove that any +# decision made in the Tendermint protocol is also made in the abstract +# protocol; if the abstract protocol satisfies the agreement property, this +# allows us to conclude that the Tendermint protocol also does). + +# The abstract protocol object that we will use is always the same, and only +# the abstract properties that we prove about it change in the different +# instantiations of the `tendermint` module. Thus we provide common invariants +# that a) allow to prove that the abstract preconditions are met, and b) +# provide a refinement relation (see end of the module) relating the state of +# Tendermint to the state of the abstract protocol. + +# In the model, Byzantine nodes can send whatever messages they want, except +# that they cannot forge sender identities. This reflects the fact that, in +# practice, nodes use public key cryptography to sign their messages. + +# Finally, note that the observations that serve to adjudicate misbehavior are +# defined only in the abstract protocol (they happen in the abstract actions). + +module tendermint(abstract_protocol) = { + + # the initial value of a node: + function init_val(N:node): value + + # the three type of steps + object step_t = { + type this = {propose, prevote, precommit} + } # refer to those e.g. as step_t.propose + + object server(n:node) = { + + # the current round of a node + individual round_p: round + + individual step: step_t + + individual decision: value + + individual lockedValue: value + individual lockedRound: round + + individual validValue: value + individual validRound: round + + + relation done_l34(R:round) + relation done_l36(R:round, V:value) + relation done_l47(R:round) + + # variables for scheduling request + relation propose_timer_scheduled(R:round) + relation prevote_timer_scheduled(R:round) + relation precommit_timer_scheduled(R:round) + + relation _recved_proposal(Sender:node, R:round, V:value, VR:round) + relation _recved_prevote(Sender:node, R:round, V:value) + relation _recved_precommit(Sender:node, R:round, V:value) + + relation _has_started + + after init { + round_p := 0; + step := step_t.propose; + decision := value.nil; + + lockedValue := value.nil; + lockedRound := round.minus_one; + + validValue := value.nil; + validRound := round.minus_one; + + done_l34(R) := false; + done_l36(R, V) := false; + done_l47(R) := false; + + propose_timer_scheduled(R) := false; + prevote_timer_scheduled(R) := false; + precommit_timer_scheduled(R) := false; + + _recved_proposal(Sender, R, V, VR) := false; + _recved_prevote(Sender, R, V) := false; + _recved_precommit(Sender, R, V) := false; + + _has_started := false; + } + + action getValue returns (v:value) = { + v := init_val(n) + } + + export action start = { + require ~_has_started; + _has_started := true; + # line 10 + call startRound(0); + } + + # line 11-21 + action startRound(r:round) = { + # line 12 + round_p := r; + + # line 13 + step := step_t.propose; + + var proposal : value; + + # line 14 + if (proposers.get_proposer(r) = n) { + if validValue ~= value.nil { # line 15 + proposal := validValue; # line 16 + } else { + proposal := getValue(); # line 18 + }; + call broadcast_proposal(r, proposal, validRound); # line 19 + } else { + propose_timer_scheduled(r) := true; # line 21 + }; + + call abstract_protocol.l_11(n, r); + } + + # This action, as not exported, can only be called at specific call sites. + action broadcast_proposal(r:round, v:value, vr:round) = { + var m: msg; + m.m_kind := msg_kind.proposal; + m.m_src := n; + m.m_round := r; + m.m_value := v; + m.m_vround := vr; + call shim.broadcast(n,m); + } + + implement shim.proposal_handler.handle(msg:msg) { + _recved_proposal(msg.m_src, msg.m_round, msg.m_value, msg.m_vround) := true; + } + + # line 22-27 + export action l_22(v:value) = { + require _has_started; + require _recved_proposal(proposers.get_proposer(round_p), round_p, v, round.minus_one); + require step = step_t.propose; + + if (value.valid(v) & (lockedRound = round.minus_one | lockedValue = v)) { + call broadcast_prevote(round_p, v); # line 24 + call abstract_protocol.l_22(n, round_p, v); + } else { + call broadcast_prevote(round_p, value.nil); # line 26 + call abstract_protocol.l_22(n, round_p, value.nil); + }; + + # line 27 + step := step_t.prevote; + } + + # line 28-33 + export action l_28(r:round, v:value, vr:round, q:nset) = { + require _has_started; + require r = round_p; + require _recved_proposal(proposers.get_proposer(r), r, v, vr); + require nset.is_quorum(q); + require nset.member(N,q) -> _recved_prevote(N,vr,v); + require step = step_t.propose; + require vr >= 0 & vr < r; + + # line 29 + if (value.valid(v) & (lockedRound <= vr | lockedValue = v)) { + call broadcast_prevote(r, v); + } else { + call broadcast_prevote(r, value.nil); + }; + + call abstract_protocol.l_28(n,r,v,vr,q); + step := step_t.prevote; + } + + action broadcast_prevote(r:round, v:value) = { + var m: msg; + m.m_kind := msg_kind.prevote; + m.m_src := n; + m.m_round := r; + m.m_value := v; + call shim.broadcast(n,m); + } + + implement shim.prevote_handler.handle(msg:msg) { + _recved_prevote(msg.m_src, msg.m_round, msg.m_value) := true; + } + + # line 34-35 + export action l_34(r:round, q:nset) = { + require _has_started; + require round_p = r; + require nset.is_quorum(q); + require exists V . nset.member(N,q) -> _recved_prevote(N,r,V); + require step = step_t.prevote; + require ~done_l34(r); + done_l34(r) := true; + + prevote_timer_scheduled(r) := true; + } + + + # line 36-43 + export action l_36(r:round, v:value, q:nset) = { + require _has_started; + require r = round_p; + require exists VR . round.minus_one <= VR & VR < r & _recved_proposal(proposers.get_proposer(r), r, v, VR); + require nset.is_quorum(q); + require nset.member(N,q) -> _recved_prevote(N,r,v); + require value.valid(v); + require step = step_t.prevote | step = step_t.precommit; + + require ~done_l36(r,v); + done_l36(r, v) := true; + + if step = step_t.prevote { + lockedValue := v; # line 38 + lockedRound := r; # line 39 + call broadcast_precommit(r, v); # line 40 + step := step_t.precommit; # line 41 + call abstract_protocol.l_36(n, r, v, q); + }; + + validValue := v; # line 42 + validRound := r; # line 43 + } + + # line 44-46 + export action l_44(r:round, q:nset) = { + require _has_started; + require r = round_p; + require nset.is_quorum(q); + require nset.member(N,q) -> _recved_prevote(N,r,value.nil); + require step = step_t.prevote; + + call broadcast_precommit(r, value.nil); # line 45 + step := step_t.precommit; # line 46 + + call abstract_protocol.l_44(n, r, q); + } + + action broadcast_precommit(r:round, v:value) = { + var m: msg; + m.m_kind := msg_kind.precommit; + m.m_src := n; + m.m_round := r; + m.m_value := v; + call shim.broadcast(n,m); + } + + implement shim.precommit_handler.handle(msg:msg) { + _recved_precommit(msg.m_src, msg.m_round, msg.m_value) := true; + } + + + # line 47-48 + export action l_47(r:round, q:nset) = { + require _has_started; + require round_p = r; + require nset.is_quorum(q); + require nset.member(N,q) -> exists V . _recved_precommit(N,r,V); + require ~done_l47(r); + done_l47(r) := true; + + precommit_timer_scheduled(r) := true; + } + + + # line 49-54 + export action l_49_decide(r:round, v:value, q:nset) = { + require _has_started; + require exists VR . round.minus_one <= VR & VR < r & _recved_proposal(proposers.get_proposer(r), r, v, VR); + require nset.is_quorum(q); + require nset.member(N,q) -> _recved_precommit(N,r,v); + require decision = value.nil; + + if value.valid(v) { + decision := v; + # MORE for next height + call abstract_protocol.decide(n, r, v, q); + } + } + + # line 55-56 + export action l_55(r:round, b:nset) = { + require _has_started; + require nset.is_blocking(b); + require nset.member(N,b) -> exists VR . round.minus_one <= VR & VR < r & exists V . _recved_proposal(N,r,V,VR) | _recved_prevote(N,r,V) | _recved_precommit(N,r,V); + require r > round_p; + call startRound(r); # line 56 + } + + # line 57-60 + export action onTimeoutPropose(r:round) = { + require _has_started; + require propose_timer_scheduled(r); + require r = round_p; + require step = step_t.propose; + call broadcast_prevote(r,value.nil); + step := step_t.prevote; + + call abstract_protocol.l_57(n,r); + + propose_timer_scheduled(r) := false; + } + + # line 61-64 + export action onTimeoutPrevote(r:round) = { + require _has_started; + require prevote_timer_scheduled(r); + require r = round_p; + require step = step_t.prevote; + call broadcast_precommit(r,value.nil); + step := step_t.precommit; + + call abstract_protocol.l_61(n,r); + + prevote_timer_scheduled(r) := false; + } + + # line 65-67 + export action onTimeoutPrecommit(r:round) = { + require _has_started; + require precommit_timer_scheduled(r); + require r = round_p; + call startRound(round.incr(r)); + + precommit_timer_scheduled(r) := false; + } + +# The Byzantine actions +# --------------------- + +# Byzantine nodes can send whatever they want, but they cannot send +# messages on behalf of well-behaved nodes. In practice this is implemented +# using cryptography (e.g. public-key cryptography). + + export action byzantine_send(m:msg, dst:node) = { + require ~well_behaved(n); + require ~well_behaved(m.m_src); # cannot forge the identity of well-behaved nodes + call shim.send(n,dst,m); + } + +# Byzantine nodes can also report fake observations, as defined in the abstract protocol. + export action fake_observations = { + call abstract_protocol.misbehave + } + +# Invariants +# ---------- + +# We provide common invariants that a) allow to prove that the abstract +# preconditions are met, and b) provide a refinement relation. + + + specification { + + invariant 0 <= round_p + invariant abstract_protocol.left_round(n,R) <-> R < round_p + + invariant lockedRound ~= round.minus_one -> forall R,V . abstract_protocol.locked(n,R,V) <-> R <= lockedRound & lockedValue = V + invariant lockedRound = round.minus_one -> forall R,V . ~abstract_protocol.locked(n,R,V) + + invariant forall M:msg . well_behaved(M.m_src) & M.m_kind = msg_kind.prevote & shim.sent(M,N) -> abstract_protocol.prevoted(M.m_src,M.m_round,M.m_value) + invariant well_behaved(N) & _recved_prevote(N,R,V) -> abstract_protocol.prevoted(N,R,V) + invariant forall M:msg . well_behaved(M.m_src) & M.m_kind = msg_kind.precommit & shim.sent(M,N) -> abstract_protocol.precommitted(M.m_src,M.m_round,M.m_value) + invariant well_behaved(N) & _recved_precommit(N,R,V) -> abstract_protocol.precommitted(N,R,V) + + invariant (step = step_t.prevote | step = step_t.propose) -> ~abstract_protocol.precommitted(n,round_p,V) + invariant step = step_t.propose -> ~abstract_protocol.prevoted(n,round_p,V) + invariant step = step_t.prevote -> exists V . abstract_protocol.prevoted(n,round_p,V) + + invariant round_p < R -> ~(abstract_protocol.prevoted(n,R,V) | abstract_protocol.precommitted(n,R,V)) + invariant ~_has_started -> step = step_t.propose & ~(abstract_protocol.prevoted(n,R,V) | abstract_protocol.precommitted(n,R,V)) & round_p = 0 + + invariant decision ~= value.nil -> exists R . abstract_protocol.decided(n,R,decision) + } + } +} diff --git a/spec/ivy-proofs/tendermint_test.ivy b/spec/ivy-proofs/tendermint_test.ivy new file mode 100644 index 0000000..b44f19a --- /dev/null +++ b/spec/ivy-proofs/tendermint_test.ivy @@ -0,0 +1,127 @@ +#lang ivy1.7 + +include tendermint +include abstract_tendermint + +isolate ghost_ = { + instantiate abstract_tendermint +} + +isolate protocol = { + instantiate tendermint(ghost_) # here we instantiate the parameter of the tendermint module with `ghost_`; however note that we don't extract any code for `ghost_` (it's not in the list of object in the extract, and it's thus sliced away). + implementation { + definition init_val(n:node) = <<< `n`%2 >>> + } + # attribute test = impl +} with ghost_, shim, value, round, proposers + +# Here we run a simple scenario that exhibits an execution in which nodes make +# a decision. We do this to rule out trivial modeling errors. + +# One option to check that this scenario is valid is to run it in Ivy's REPL. +# For this, first compile the scenario: +#```ivyc target=repl isolate=code trace=true tendermint_test.ivy +# Then, run the produced binary (e.g. for 4 nodes): +#``` ./tendermint_test 4 +# Finally, call the action: +#``` scenarios.scenario_1 +# Note that Ivy will check at runtime that all action preconditions are +# satisfied. For example, runing the scenario twice will cause a violation of +# the precondition of the `start` action, because a node cannot start twice +# (see `require ~_has_started` in action `start`). + +# Another possibility would be to run `ivy_check` on the scenario, but that +# does not seem to work at the moment. + +isolate scenarios = { + individual all:nset # will be used as parameter to actions requiring a quorum + + after init { + var iter := node.iter.create(0); + while ~iter.is_end + { + all := all.insert(iter.val); + iter := iter.next; + }; + assert nset.is_quorum(all); # we can also use asserts to make sure we are getting what we expect + } + + export action scenario_1 = { + # all nodes start: + var iter := node.iter.create(0); + while ~iter.is_end + { + call protocol.server.start(iter.val); + iter := iter.next; + }; + # all nodes receive the leader's proposal: + var m:msg; + m.m_kind := msg_kind.proposal; + m.m_src := 0; + m.m_round := 0; + m.m_value := 0; + m.m_vround := round.minus_one; + iter := node.iter.create(0); + while ~iter.is_end + { + call net.recv(iter.val,m); + iter := iter.next; + }; + # all nodes prevote: + iter := node.iter.create(0); + while ~iter.is_end + { + call protocol.server.l_22(iter.val,0); + iter := iter.next; + }; + # all nodes receive each other's prevote messages; + m.m_kind := msg_kind.prevote; + m.m_vround := 0; + iter := node.iter.create(0); + while ~iter.is_end + { + var iter2 := node.iter.create(0); # the sender + while ~iter2.is_end + { + m.m_src := iter2.val; + call net.recv(iter.val,m); + iter2 := iter2.next; + }; + iter := iter.next; + }; + # all nodes precommit: + iter := node.iter.create(0); + while ~iter.is_end + { + call protocol.server.l_36(iter.val,0,0,all); + iter := iter.next; + }; + # all nodes receive each other's pre-commits + m.m_kind := msg_kind.precommit; + iter := node.iter.create(0); + while ~iter.is_end + { + var iter2 := node.iter.create(0); # the sender + while ~iter2.is_end + { + m.m_src := iter2.val; + call net.recv(iter.val,m); + iter2 := iter2.next; + }; + iter := iter.next; + }; + # now all nodes can decide: + iter := node.iter.create(0); + while ~iter.is_end + { + call protocol.server.l_49_decide(iter.val,0,0,all); + iter := iter.next; + }; + } + + # TODO: add more scenarios + +} with round, node, proposers, value, nset, protocol, shim, net + +# extract code = protocol, shim, round, node +extract code = round, node, proposers, value, nset, protocol, shim, net, scenarios diff --git a/spec/light-client/README.md b/spec/light-client/README.md new file mode 100644 index 0000000..f5902bd --- /dev/null +++ b/spec/light-client/README.md @@ -0,0 +1,205 @@ +--- +order: 1 +parent: + title: Light Client + order: 5 +--- + +# Light Client Specification + +This directory contains work-in-progress English and TLA+ specifications for the Light Client +protocol. Implementations of the light client can be found in +[Rust](https://github.com/informalsystems/tendermint-rs/tree/master/light-client) and +[Go](https://github.com/cometbft/cometbft/tree/v0.38.x/light). + +Light clients are assumed to be initialized once from a trusted source +with a trusted header and validator set. The light client +protocol allows a client to then securely update its trusted state by requesting and +verifying a minimal set of data from a network of full nodes (at least one of which is correct). + +The light client is decomposed into two main components: + +- [Commit Verification](#commit-verification) - verify signed headers and associated validator + set changes from a single full node, called primary +- [Attack Detection](#attack-detection) - verify commits across multiple full nodes (called secondaries) and detect conflicts (ie. the existence of a lightclient attack) + +In case a lightclient attack is detected, the lightclient submits evidence to a full node which is responsible for "accountability", that is, punishing attackers: + +- [Accountability](#accountability) - given evidence for an attack, compute a set of validators that are responsible for it. + +## Commit Verification + +The [English specification](verification/verification_001_published.md) describes the light client +commit verification problem in terms of the temporal properties +[LCV-DIST-SAFE.1](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe1) and +[LCV-DIST-LIVE.1](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-live1). +Commit verification is assumed to operate within the Cosmos Failure Model, where +2/3 of validators are correct for some time period and +validator sets can change arbitrarily at each height. + +A light client protocol is also provided, including all checks that +need to be performed on headers, commits, and validator sets +to satisfy the temporal properties - so a light client can continuously +synchronize with a blockchain. Clients can skip possibly +many intermediate headers by exploiting overlap in trusted and untrusted validator sets. +When there is not enough overlap, a bisection routine can be used to find a +minimal set of headers that do provide the required overlap. + +The [TLA+ specification ver. 001](verification/Lightclient_A_1.tla) +is a formal description of the +commit verification protocol executed by a client, including the safety and +termination, which can be model checked with Apalache. + +A more detailed TLA+ specification of +[Light client verification ver. 003](verification/Lightclient_003_draft.tla) +is currently under peer review. + +The `MC*.tla` files contain concrete parameters for the +[TLA+ specification](verification/Lightclient_A_1.tla), in order to do model checking. +For instance, [MC4_3_faulty.tla](verification/MC4_3_faulty.tla) contains the following parameters +for the nodes, heights, the trusting period, the clock drifts, +correctness of the primary node, and the ratio of the faulty processes: + +```tla +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* the trusting period in some time units +CLOCK_DRIFT = 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT = 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators +``` + +To run a complete set of experiments, clone [apalache](https://github.com/informalsystems/apalache) and [apalache-tests](https://github.com/informalsystems/apalache-tests) into a directory `$DIR` and run the following commands: + +```sh +$DIR/apalache-tests/scripts/mk-run.py --memlimit 28 002bmc-apalache-ok.csv $DIR/apalache . out +./out/run-all.sh +``` + +After the experiments have finished, you can collect the logs by executing the following command: + +```sh +cd ./out +$DIR/apalache-tests/scripts/parse-logs.py --human . +``` + +All lines in `results.csv` should report `Deadlock`, which means that the algorithm +has terminated and no invariant violation was found. + +Similar to [002bmc-apalache-ok.csv](verification/002bmc-apalache-ok.csv), +file [003bmc-apalache-error.csv](verification/003bmc-apalache-error.csv) specifies +the set of experiments that should result in counterexamples: + +```sh +$DIR/apalache-tests/scripts/mk-run.py --memlimit 28 003bmc-apalache-error.csv $DIR/apalache . out +./out/run-all.sh +``` + +All lines in `results.csv` should report `Error`. + +The following table summarizes the experimental results for Light client verification +version 001. The TLA+ properties can be found in the +[TLA+ specification](verification/Lightclient_A_1.tla). + The experiments were run in an AWS instance equipped with 32GB +RAM and a 4-core Intel® Xeon® CPU E5-2686 v4 @ 2.30GHz CPU. +We write “✗=k” when a bug is reported at depth k, and “✓<=k” when +no bug is reported up to depth k. + +![Experimental results](experiments.png) + +The experimental results for version 003 are to be added. + +## Attack Detection + +The [English specification](detection/detection_003_reviewed.md) +defines light client attacks (and how they differ from blockchain +forks), and describes the problem of a light client detecting +these attacks by communicating with a network of full nodes, +where at least one is correct. + +The specification also contains a detection protocol that checks +whether the header obtained from the primary via the verification +protocol matches corresponding headers provided by the secondaries. +If this is not the case, the protocol analyses the verification traces +of the involved full nodes +and generates +[evidence](detection/detection_003_reviewed.md#cmbc-lc-evidence-data1) +of misbehavior that can be submitted to a full node so that +the faulty validators can be punished. + +The [TLA+ specification](detection/LCDetector_003_draft.tla) +is a formal description of the +detection protocol for two peers, including the safety and +termination, which can be model checked with Apalache. + +The `LCD_MC*.tla` files contain concrete parameters for the +[TLA+ specification](detection/LCDetector_003_draft.tla), +in order to run the model checker. +For instance, [LCD_MC4_4_faulty.tla](./verification/MC4_4_faulty.tla) +contains the following parameters +for the nodes, heights, the trusting period, the clock drifts, +correctness of the nodes, and the ratio of the faulty processes: + +```tla +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* the trusting period in some time units +CLOCK_DRIFT = 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT = 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +IS_SECONDARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators +``` + +To run a complete set of experiments, clone [apalache](https://github.com/informalsystems/apalache) and [apalache-tests](https://github.com/informalsystems/apalache-tests) into a directory `$DIR` and run the following commands: + +```sh +$DIR/apalache-tests/scripts/mk-run.py --memlimit 28 004bmc-apalache-ok.csv $DIR/apalache . out +./out/run-all.sh +``` + +After the experiments have finished, you can collect the logs by executing the following command: + +```sh +cd ./out +$DIR/apalache-tests/scripts/parse-logs.py --human . +``` + +All lines in `results.csv` should report `Deadlock`, which means that the algorithm +has terminated and no invariant violation was found. + +Similar to [004bmc-apalache-ok.csv](verification/004bmc-apalache-ok.csv), +file [005bmc-apalache-error.csv](verification/005bmc-apalache-error.csv) specifies +the set of experiments that should result in counterexamples: + +```sh +$DIR/apalache-tests/scripts/mk-run.py --memlimit 28 005bmc-apalache-error.csv $DIR/apalache . out +./out/run-all.sh +``` + +All lines in `results.csv` should report `Error`. + +The detailed experimental results are to be added soon. + +## Accountability + +The [English specification](attacks/isolate-attackers_002_reviewed.md) +defines the protocol that is executed on a full node upon receiving attack [evidence](detection/detection_003_reviewed.md#cmbc-lc-evidence-data1) from a lightclient. In particular, the protocol handles three types of attacks + +- lunatic +- equivocation +- amnesia + +We discussed in the [last part](attacks/isolate-attackers_002_reviewed.md#Part-III---Completeness) of the English specification +that the non-lunatic cases are defined by having the same validator set in the conflicting blocks. For these cases, +computer-aided analysis of [Tendermint Consensus in TLA+](./accountability/README.md) shows that equivocation and amnesia capture all non-lunatic attacks. + +The [TLA+ specification](attacks/Isolation_001_draft.tla) +is a formal description of the +protocol, including the safety property, which can be model checked with Apalache. + +Similar to the other specifications, [MC_5_3.tla](attacks/MC_5_3.tla) contains concrete parameters to run the model checker. The specification can be checked within seconds. + +[tendermint-accountability](./accountability/README.md) diff --git a/spec/light-client/accountability/001indinv-apalache.csv b/spec/light-client/accountability/001indinv-apalache.csv new file mode 100644 index 0000000..0e41fe4 --- /dev/null +++ b/spec/light-client/accountability/001indinv-apalache.csv @@ -0,0 +1,13 @@ +no,filename,tool,timeout,init,inv,next,args +1,MC_n4_f1.tla,apalache,10h,TypedInv,TypedInv,,--length=1 --cinit=ConstInit +2,MC_n4_f2.tla,apalache,10h,TypedInv,TypedInv,,--length=1 --cinit=ConstInit +3,MC_n5_f1.tla,apalache,10h,TypedInv,TypedInv,,--length=1 --cinit=ConstInit +4,MC_n5_f2.tla,apalache,10h,TypedInv,TypedInv,,--length=1 --cinit=ConstInit +5,MC_n4_f1.tla,apalache,20h,Init,TypedInv,,--length=0 --cinit=ConstInit +6,MC_n4_f2.tla,apalache,20h,Init,TypedInv,,--length=0 --cinit=ConstInit +7,MC_n5_f1.tla,apalache,20h,Init,TypedInv,,--length=0 --cinit=ConstInit +8,MC_n5_f2.tla,apalache,20h,Init,TypedInv,,--length=0 --cinit=ConstInit +9,MC_n4_f1.tla,apalache,20h,TypedInv,Agreement,,--length=0 --cinit=ConstInit +10,MC_n4_f2.tla,apalache,20h,TypedInv,Accountability,,--length=0 --cinit=ConstInit +11,MC_n5_f1.tla,apalache,20h,TypedInv,Agreement,,--length=0 --cinit=ConstInit +12,MC_n5_f2.tla,apalache,20h,TypedInv,Accountability,,--length=0 --cinit=ConstInit diff --git a/spec/light-client/accountability/MC_n4_f1.tla b/spec/light-client/accountability/MC_n4_f1.tla new file mode 100644 index 0000000..af46d08 --- /dev/null +++ b/spec/light-client/accountability/MC_n4_f1.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n4_f1 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1", "c2", "c3"}, + Faulty <- {"f1"}, + N <- 4, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n4_f2.tla b/spec/light-client/accountability/MC_n4_f2.tla new file mode 100644 index 0000000..de13fdb --- /dev/null +++ b/spec/light-client/accountability/MC_n4_f2.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n4_f2 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1", "c2"}, + Faulty <- {"f3", "f4"}, + N <- 4, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n4_f2_amnesia.tla b/spec/light-client/accountability/MC_n4_f2_amnesia.tla new file mode 100644 index 0000000..8b080a6 --- /dev/null +++ b/spec/light-client/accountability/MC_n4_f2_amnesia.tla @@ -0,0 +1,66 @@ +---------------------- MODULE MC_n4_f2_amnesia ------------------------------- +EXTENDS Sequences + +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +\* the variable declared in TendermintAccTrace3 +VARIABLE + \* @type: $trace; + toReplay + +INSTANCE TendermintAccTrace_004_draft WITH + Corr <- {"c1", "c2"}, + Faulty <- {"f3", "f4"}, + N <- 4, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2, + Trace <- << + "UponProposalInPropose", + "UponProposalInPrevoteOrCommitAndPrevote", + "UponProposalInPrecommitNoDecision", + "OnRoundCatchup", + "UponProposalInPropose", + "UponProposalInPrevoteOrCommitAndPrevote", + "UponProposalInPrecommitNoDecision" + >> + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n4_f3.tla b/spec/light-client/accountability/MC_n4_f3.tla new file mode 100644 index 0000000..4305352 --- /dev/null +++ b/spec/light-client/accountability/MC_n4_f3.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n4_f3 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1"}, + Faulty <- {"f2", "f3", "f4"}, + N <- 4, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n5_f1.tla b/spec/light-client/accountability/MC_n5_f1.tla new file mode 100644 index 0000000..b46f756 --- /dev/null +++ b/spec/light-client/accountability/MC_n5_f1.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n5_f1 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1", "c2", "c3", "c4"}, + Faulty <- {"f5"}, + N <- 5, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n5_f2.tla b/spec/light-client/accountability/MC_n5_f2.tla new file mode 100644 index 0000000..a2a8566 --- /dev/null +++ b/spec/light-client/accountability/MC_n5_f2.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n5_f2 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1", "c2", "c3"}, + Faulty <- {"f4", "f5"}, + N <- 5, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/MC_n6_f1.tla b/spec/light-client/accountability/MC_n6_f1.tla new file mode 100644 index 0000000..50d3bdf --- /dev/null +++ b/spec/light-client/accountability/MC_n6_f1.tla @@ -0,0 +1,50 @@ +----------------------------- MODULE MC_n6_f1 ------------------------------- +CONSTANT + \* @type: $round -> $process; + Proposer + +\* the variables declared in TendermintAcc3 +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound, \* a valid round: Corr -> RoundsOrNil + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +INSTANCE TendermintAccDebug_004_draft WITH + Corr <- {"c1", "c2", "c3", "c4", "c5"}, + Faulty <- {"f6"}, + N <- 4, + T <- 1, + ValidValues <- { "v0", "v1" }, + InvalidValues <- {"v2"}, + MaxRound <- 2 + +\* run Apalache with --cinit=ConstInit +ConstInit == \* the proposer is arbitrary -- works for safety + Proposer \in [Rounds -> AllProcs] + +============================================================================= diff --git a/spec/light-client/accountability/README.md b/spec/light-client/accountability/README.md new file mode 100644 index 0000000..8b4f605 --- /dev/null +++ b/spec/light-client/accountability/README.md @@ -0,0 +1,305 @@ +--- +order: 1 +parent: + title: Accountability + order: 4 +--- + +# Fork accountability + +## Problem Statement + +Tendermint consensus algorithm guarantees the following specifications for all heights: + +* agreement -- no two correct full nodes decide differently. +* validity -- the decided block satisfies the predefined predicate *valid()*. +* termination -- all correct full nodes eventually decide, + +If the faulty validators have less than 1/3 of voting power in the current validator set. In the case where this assumption +does not hold, each of the specification may be violated. + +The agreement property says that for a given height, any two correct validators that decide on a block for that height decide on the same block. That the block was indeed generated by the blockchain, can be verified starting from a trusted (genesis) block, and checking that all subsequent blocks are properly signed. + +However, faulty nodes may forge blocks and try to convince users (light clients) that the blocks had been correctly generated. In addition, Tendermint agreement might be violated in the case where 1/3 or more of the voting power belongs to faulty validators: Two correct validators decide on different blocks. The latter case motivates the term "fork": as Tendermint consensus also agrees on the next validator set, correct validators may have decided on disjoint next validator sets, and the chain branches into two or more partitions (possibly having faulty validators in common) and each branch continues to generate blocks independently of the other. + +We say that a fork is a case in which there are two commits for different blocks at the same height of the blockchain. The problem is to ensure that in those cases we are able to detect faulty validators (and not mistakenly accuse correct validators), and incentivize therefore validators to behave according to the protocol specification. + +**Conceptual Limit.** In order to prove misbehavior of a node, we have to show that the behavior deviates from correct behavior with respect to a given algorithm. Thus, an algorithm that detects misbehavior of nodes executing some algorithm *A* must be defined with respect to algorithm *A*. In our case, *A* is Tendermint consensus (+ other protocols in the infrastructure; e.g., Cosmos full nodes and the Light Client). If the consensus algorithm is changed/updated/optimized in the future, we have to check whether changes to the accountability algorithm are also required. All the discussions in this document are thus inherently specific to Tendermint consensus and the Light Client specification. + +**Q:** Should we distinguish agreement for validators and full nodes for agreement? The case where all correct validators agree on a block, but a correct full node decides on a different block seems to be slightly less severe that the case where two correct validators decide on different blocks. Still, if a contaminated full node becomes validator that may be problematic later on. Also it is not clear how gossiping is impaired if a contaminated full node is on a different branch. + +*Remark.* In the case 1/3 or more of the voting power belongs to faulty validators, also validity and termination can be broken. Termination can be broken if faulty processes just do not send the messages that are needed to make progress. Due to asynchrony, this is not punishable, because faulty validators can always claim they never received the messages that would have forced them to send messages. + +## The Misbehavior of Faulty Validators + +Forks are the result of faulty validators deviating from the protocol. In principle several such deviations can be detected without a fork actually occurring: + +1. double proposal: A faulty proposer proposes two different values (blocks) for the same height and the same round in Tendermint consensus. + +2. double signing: Tendermint consensus forces correct validators to prevote and precommit for at most one value per round. In case a faulty validator sends multiple prevote and/or precommit messages for different values for the same height/round, this is a misbehavior. + +3. lunatic validator: Tendermint consensus forces correct validators to prevote and precommit only for values *v* that satisfy *valid(v)*. If faulty validators prevote and precommit for *v* although *valid(v)=false* this is misbehavior. + +*Remark.* In isolation, Point 3 is an attack on validity (rather than agreement). However, the prevotes and precommits can then also be used to forge blocks. + +1. amnesia: Tendermint consensus has a locking mechanism. If a validator has some value v locked, then it can only prevote/precommit for v or nil. Sending prevote/precomit message for a different value v' (that is not nil) while holding lock on value v is misbehavior. + +2. spurious messages: In Tendermint consensus most of the message send instructions are guarded by threshold guards, e.g., one needs to receive *2f + 1* prevote messages to send precommit. Faulty validators may send precommit without having received the prevote messages. + +Independently of a fork happening, punishing this behavior might be important to prevent forks altogether. This should keep attackers from misbehaving: if less than 1/3 of the voting power is faulty, this misbehavior is detectable but will not lead to a safety violation. Thus, unless they have 1/3 or more (or in some cases more than 2/3) of the voting power attackers have the incentive to not misbehave. If attackers control too much voting power, we have to deal with forks, as discussed in this document. + +## Two types of forks + +* Fork-Full. Two correct validators decide on different blocks for the same height. Since also the next validator sets are decided upon, the correct validators may be partitioned to participate in two distinct branches of the forked chain. + +As in this case we have two different blocks (both having the same right/no right to exist), a central system invariant (one block per height decided by correct validators) is violated. As full nodes are contaminated in this case, the contamination can spread also to light clients. However, even without breaking this system invariant, light clients can be subject to a fork: + +* Fork-Light. All correct validators decide on the same block for height *h*, but faulty processes (validators or not), forge a different block for that height, in order to fool users (who use the light client). + +# Attack scenarios + +## On-chain attacks + +### Equivocation (one round) + +There are several scenarios in which forks might happen. The first is double signing within a round. + +* F1. Equivocation: faulty validators sign multiple vote messages (prevote and/or precommit) for different values *during the same round r* at a given height h. + +### Flip-flopping + +Tendermint consensus implements a locking mechanism: If a correct validator *p* receives proposal for value v and *2f + 1* prevotes for a value *id(v)* in round *r*, it locks *v* and remembers *r*. In this case, *p* also sends a precommit message for *id(v)*, which later may serve as proof that *p* locked *v*. +In subsequent rounds, *p* only sends prevote messages for a value it had previously locked. However, it is possible to change the locked value if in a future round *r' > r*, if the process receives proposal and *2f + 1* prevotes for a different value *v'*. In this case, *p* could send a prevote/precommit for *id(v')*. This algorithmic feature can be exploited in two ways: + +* F2. Faulty Flip-flopping (Amnesia): faulty validators precommit some value *id(v)* in round *r* (value *v* is locked in round *r*) and then prevote for different value *id(v')* in higher round *r' > r* without previously correctly unlocking value *v*. In this case faulty processes "forget" that they have locked value *v* and prevote some other value in the following rounds. +Some correct validators might have decided on *v* in *r*, and other correct validators decide on *v'* in *r'*. Here we can have branching on the main chain (Fork-Full). + +* F3. Correct Flip-flopping (Back to the past): There are some precommit messages signed by (correct) validators for value *id(v)* in round *r*. Still, *v* is not decided upon, and all processes move on to the next round. Then correct validators (correctly) lock and decide a different value *v'* in some round *r' > r*. And the correct validators continue; there is no branching on the main chain. +However, faulty validators may use the correct precommit messages from round *r* together with a posteriori generated faulty precommit messages for round *r* to forge a block for a value that was not decided on the main chain (Fork-Light). + +## Off-chain attacks + +F1-F3 may contaminate the state of full nodes (and even validators). Contaminated (but otherwise correct) full nodes may thus communicate faulty blocks to light clients. +Similarly, without actually interfering with the main chain, we can have the following: + +* F4. Phantom validators: faulty validators vote (sign prevote and precommit messages) in heights in which they are not part of the validator sets (at the main chain). + +* F5. Lunatic validator: faulty validator that sign vote messages to support (arbitrary) application state that is different from the application state that resulted from valid state transitions. + +## Types of victims + +We consider three types of potential attack victims: + +* FN: full node +* LCS: light client with sequential header verification +* LCB: light client with bisection based header verification + +F1 and F2 can be used by faulty validators to actually create multiple branches on the blockchain. That means that correctly operating full nodes decide on different blocks for the same height. Until a fork is detected locally by a full node (by receiving evidence from others or by some other local check that fails), the full node can spread corrupted blocks to light clients. + +*Remark.* If full nodes take a branch different from the one taken by the validators, it may be that the liveness of the gossip protocol may be affected. We should eventually look at this more closely. However, as it does not influence safety it is not a primary concern. + +F3 is similar to F1, except that no two correct validators decide on different blocks. It may still be the case that full nodes become affected. + +In addition, without creating a fork on the main chain, light clients can be contaminated by more than a third of validators that are faulty and sign a forged header +F4 cannot fool correct full nodes as they know the current validator set. Similarly, LCS know who the validators are. Hence, F4 is an attack against LCB that do not necessarily know the complete prefix of headers (Fork-Light), as they trust a header that is signed by at least one correct validator (trusting period method). + +The following table gives an overview of how the different attacks may affect different nodes. F1-F3 are *on-chain* attacks so they can corrupt the state of full nodes. Then if a light client (LCS or LCB) contacts a full node to obtain headers (or blocks), the corrupted state may propagate to the light client. + +F4 and F5 are *off-chain*, that is, these attacks cannot be used to corrupt the state of full nodes (which have sufficient knowledge on the state of the chain to not be fooled). + +| Attack | FN | LCS | LCB | +|:------:|:------:|:------:|:------:| +| F1 | direct | FN | FN | +| F2 | direct | FN | FN | +| F3 | direct | FN | FN | +| F4 | | | direct | +| F5 | | | direct | + +**Q:** Light clients are more vulnerable than full nodes, because the former do only verify headers but do not execute transactions. What kind of certainty is gained by a full node that executes a transaction? + +As a full node verifies all transactions, it can only be +contaminated by an attack if the blockchain itself violates its invariant (one block per height), that is, in case of a fork that leads to branching. + +## Detailed Attack Scenarios + +### Equivocation based attacks + +In case of equivocation based attacks, faulty validators sign multiple votes (prevote and/or precommit) in the same +round of some height. This attack can be executed on both full nodes and light clients. It requires 1/3 or more of voting power to be executed. + +#### Scenario 1: Equivocation on the main chain + +Validators: + +* CA - a set of correct validators with less than 1/3 of the voting power +* CB - a set of correct validators with less than 1/3 of the voting power +* CA and CB are disjoint +* F - a set of faulty validators with 1/3 or more voting power + +Observe that this setting violates the Cosmos failure model. + +Execution: + +* A faulty proposer proposes block A to CA +* A faulty proposer proposes block B to CB +* Validators from the set CA and CB prevote for A and B, respectively. +* Faulty validators from the set F prevote both for A and B. +* The faulty prevote messages + * for A arrive at CA long before the B messages + * for B arrive at CB long before the A messages +* Therefore correct validators from set CA and CB will observe +more than 2/3 of prevotes for A and B and precommit for A and B, respectively. +* Faulty validators from the set F precommit both values A and B. +* Thus, we have more than 2/3 commits for both A and B. + +Consequences: + +* Creating evidence of misbehavior is simple in this case as we have multiple messages signed by the same faulty processes for different values in the same round. + +* We have to ensure that these different messages reach a correct process (full node, monitor?), which can submit evidence. + +* This is an attack on the full node level (Fork-Full). +* It extends also to the light clients, +* For both we need a detection and recovery mechanism. + +#### Scenario 2: Equivocation to a light client (LCS) + +Validators: + +* a set F of faulty validators with more than 2/3 of the voting power. + +Execution: + +* for the main chain F behaves nicely +* F coordinates to sign a block B that is different from the one on the main chain. +* the light clients obtains B and trusts at as it is signed by more than 2/3 of the voting power. + +Consequences: + +Once equivocation is used to attack light client it opens space +for different kind of attacks as application state can be diverged in any direction. For example, it can modify validator set such that it contains only validators that do not have any stake bonded. Note that after a light client is fooled by a fork, that means that an attacker can change application state and validator set arbitrarily. + +In order to detect such (equivocation-based attack), the light client would need to cross check its state with some correct validator (or to obtain a hash of the state from the main chain using out of band channels). + +*Remark.* The light client would be able to create evidence of misbehavior, but this would require to pull potentially a lot of data from correct full nodes. Maybe we need to figure out different architecture where a light client that is attacked will push all its data for the current unbonding period to a correct node that will inspect this data and submit corresponding evidence. There are also architectures that assumes a special role (sometimes called fisherman) whose goal is to collect as much as possible useful data from the network, to do analysis and create evidence transactions. That functionality is outside the scope of this document. + +*Remark.* The difference between LCS and LCB might only be in the amount of voting power needed to convince light client about arbitrary state. In case of LCB where security threshold is at minimum, an attacker can arbitrarily modify application state with 1/3 or more of voting power, while in case of LCS it requires more than 2/3 of the voting power. + +### Flip-flopping: Amnesia based attacks + +In case of amnesia, faulty validators lock some value *v* in some round *r*, and then vote for different value *v'* in higher rounds without correctly unlocking value *v*. This attack can be used both on full nodes and light clients. + +#### Scenario 3: At most 2/3 of faults + +Validators: + +* a set F of faulty validators with 1/3 or more but at most 2/3 of the voting power +* a set C of correct validators + +Execution: + +* Faulty validators commit (without exposing it on the main chain) a block A in round *r* by collecting more than 2/3 of the + voting power (containing correct and faulty validators). +* All validators (correct and faulty) reach a round *r' > r*. +* Some correct validators in C do not lock any value before round *r'*. +* The faulty validators in F deviate from Tendermint consensus by ignoring that they locked A in *r*, and propose a different block B in *r'*. +* As the validators in C that have not locked any value find B acceptable, they accept the proposal for B and commit a block B. + +*Remark.* In this case, the more than 1/3 of faulty validators do not need to commit an equivocation (F1) as they only vote once per round in the execution. + +If a light client is attacked using this attack with 1/3 or more of voting power (and less than 2/3), the attacker cannot change the application state arbitrarily. Rather, the attacker is limited to a state a correct validator finds acceptable: In the execution above, correct validators still find the value acceptable, however, the block the light client trusts deviates from the one on the main chain. + +#### Scenario 4: More than 2/3 of faults + +In case there is an attack with more than 2/3 of the voting power, an attacker can arbitrarily change application state. + +Validators: + +* a set F1 of faulty validators with 1/3 or more of the voting power +* a set F2 of faulty validators with less than 1/3 of the voting power + +Execution + +* Similar to Scenario 3 (however, messages by correct validators are not needed) +* The faulty validators in F1 lock value A in round *r* +* They sign a different value in follow-up rounds +* F2 does not lock A in round *r* + +Consequences: + +* The validators in F1 will be detectable by the fork accountability mechanisms. +* The validators in F2 cannot be detected using this mechanism. +Only in case they signed something which conflicts with the application this can be used against them. Otherwise, they do not do anything incorrect. + +**Q:** do we need to define a special kind of attack for the case where a validator sign arbitrarily state? It seems that detecting such attack requires a different mechanism that would require as an evidence a sequence of blocks that led to that state. This might be very tricky to implement. + +### Back to the past + +In this kind of attack, faulty validators take advantage of the fact that they did not sign messages in some of the past rounds. Due to the asynchronous network in which Tendermint operates, we cannot easily differentiate between such an attack and delayed message. This kind of attack can be used at both full nodes and light clients. + +#### Scenario 5 + +Validators: + +* C1 - a set of correct validators with over 1/3 of the voting power +* C2 - a set of correct validators with 1/3 of the voting power +* C1 and C2 are disjoint +* F - a set of faulty validators with less than 1/3 voting power +* one additional faulty process *q* +* F and *q* violate the Cosmos failure model. + +Execution: + +* in a round *r* of height *h* we have C1 precommitting a value A, +* C2 precommits nil, +* F does not send any message +* *q* precommits nil. +* In some round *r' > r*, F and *q* and C2 commit some other value B different from A. +* F and *fp* "go back to the past" and sign precommit message for value A in round *r*. +* Together with precomit messages of C1 this is sufficient for a commit for value A. + +Consequences: + +* Only a single faulty validator that previously precommited nil did equivocation, while the other 1/3 of faulty validators actually executed an attack that has exactly the same sequence of messages as part of amnesia attack. Detecting this kind of attack boil down to mechanisms for equivocation and amnesia. + +**Q:** should we keep this as a separate kind of attack? It seems that equivocation, amnesia and phantom validators are the only kind of attack we need to support and this gives us security also in other cases. This would not be surprising as equivocation and amnesia are attacks that followed from the protocol and phantom attack is not really an attack to Tendermint but more to the Cosmos Proof of Stake module. + +### Phantom validators + +In case of phantom validators, processes that are not part of the current validator set but are still bonded (as attack happen during their unbonding period) can be part of the attack by signing vote messages. This attack can be executed against both full nodes and light clients. + +#### Scenario 6 + +Validators: + +* F -- a set of faulty validators that are not part of the validator set on the main chain at height *h + k* + +Execution: + +* There is a fork, and there exist two different headers for height *h + k*, with different validator sets: + * VS2 on the main chain + * forged header VS2', signed by F (and others) + +* a light client has a trust in a header for height *h* (and the corresponding validator set VS1). +* As part of bisection header verification, it verifies the header at height *h + k* with new validator set VS2'. + +Consequences: + +* To detect this, a node needs to see both, the forged header and the canonical header from the chain. +* If this is the case, detecting these kind of attacks is easy as it just requires verifying if processes are signing messages in heights in which they are not part of the validator set. + +**Remark.** We can have phantom-validator-based attacks as a follow up of equivocation or amnesia based attack where forked state contains validators that are not part of the validator set at the main chain. In this case, they keep signing messages contributed to a forked chain (the wrong branch) although they are not part of the validator set on the main chain. This attack can also be used to attack full node during a period of time it is eclipsed. + +**Remark.** Phantom validator evidence has been removed from implementation as it was deemed, although possibly a plausible form of evidence, not relevant. Any attack on +the light client involving a phantom validator will have needed to be initiated by 1/3+ lunatic +validators that can forge a new validator set that includes the phantom validator. Only in +that case will the light client accept the phantom validators vote. We need only worry about +punishing the 1/3+ lunatic cabal, that is the root cause of the attack. + +### Lunatic validator + +Lunatic validator agrees to sign commit messages for arbitrary application state. It is used to attack light clients. +Note that detecting this behavior require application knowledge. Detecting this behavior can probably be done by +referring to the block before the one in which height happen. + +**Q:** can we say that in this case a validator declines to check if a proposed value is valid before voting for it? diff --git a/spec/light-client/accountability/Synopsis.md b/spec/light-client/accountability/Synopsis.md new file mode 100644 index 0000000..19bdd82 --- /dev/null +++ b/spec/light-client/accountability/Synopsis.md @@ -0,0 +1,105 @@ + +# Synopsis + + A TLA+ specification of a simplified Tendermint consensus algorithm, tuned for + fork accountability. The simplifications are as follows: + +- the procotol runs for one height, that is, one-shot consensus + +- this specification focuses on safety, so timeouts are modelled with + with non-determinism + +- the proposer function is non-determinstic, no fairness is assumed + +- the messages by the faulty processes are injected right in the initial states + +- every process has the voting power of 1 + +- hashes are modelled as identity + + Having the above assumptions in mind, the specification follows the pseudo-code + of the Tendermint paper: + + Byzantine processes can demonstrate arbitrary behavior, including + no communication. However, we have to show that under the collective evidence + collected by the correct processes, at least `f+1` Byzantine processes demonstrate + one of the following behaviors: + +- Equivocation: a Byzantine process sends two different values + in the same round. + +- Amnesia: a Byzantine process locks a value, although it has locked + another value in the past. + +# TLA+ modules + +- [TendermintAcc_004_draft](TendermintAcc_004_draft.tla) is the protocol + specification, + +- [TendermintAccInv_004_draft](TendermintAccInv_004_draft.tla) contains an + inductive invariant for establishing the protocol safety as well as the + forking cases, + +- `MC_n_f`, e.g., [MC_n4_f1](MC_n4_f1.tla), contains fixed constants for + model checking with the [Apalache model + checker](https://github.com/informalsystems/apalache), + +- [TendermintAccTrace_004_draft](TendermintAccTrace_004_draft.tla) shows how + to restrict the execution space to a fixed sequence of actions (e.g., to + instantiate a counterexample), + +- [TendermintAccDebug_004_draft](TendermintAccDebug_004_draft.tla) contains + the useful definitions for debugging the protocol specification with TLC and + Apalache. + +# Reasoning about fork scenarios + +The theorem statements can be found in +[TendermintAccInv_004_draft.tla](TendermintAccInv_004_draft.tla). + +First, we would like to show that `TypedInv` is an inductive invariant. +Formally, the statement looks as follows: + +```tla +THEOREM TypedInvIsInductive == + \/ FaultyQuorum + \//\ Init => TypedInv + /\ TypedInv /\ [Next]_vars => TypedInv' +``` + +When over two-thirds of processes are faulty, `TypedInv` is not inductive. +However, there is no hope to repair the protocol in this case. We run +[Apalache](https://github.com/informalsystems/apalache) to prove this theorem +only for fixed instances of 4 to 5 validators. Apalache does not parse theorem +statements at the moment, so we ran Apalache using a shell script. To find a +parameterized argument, one has to use a theorem prover, e.g., TLAPS. + +Second, we would like to show that the invariant implies `Agreement`, that is, +no fork, provided that less than one third of processes is faulty. By combining +this theorem with the previous theorem, we conclude that the protocol indeed +satisfies Agreement under the condition `LessThanThirdFaulty`. + +```tla +THEOREM AgreementWhenLessThanThirdFaulty == + LessThanThirdFaulty /\ TypedInv => Agreement +``` + +Third, in the general case, we either have no fork, or two fork scenarios: + +```tla +THEOREM AgreementOrFork == + ~FaultyQuorum /\ TypedInv => Accountability +``` + +# Model checking results + +Check the report on [model checking with Apalache](./results/001indinv-apalache-report.md). + +To run the model checking experiments, use the script: + +```console +./run.sh +``` + +This script assumes that the apalache build is available in +`~/devl/apalache-unstable`. diff --git a/spec/light-client/accountability/TendermintAccDebug_004_draft.tla b/spec/light-client/accountability/TendermintAccDebug_004_draft.tla new file mode 100644 index 0000000..73e8bfa --- /dev/null +++ b/spec/light-client/accountability/TendermintAccDebug_004_draft.tla @@ -0,0 +1,108 @@ +------------------ MODULE TendermintAccDebug_004_draft ------------------------- +(* + A few definitions that we use for debugging TendermintAcc3, which do not belong + to the specification itself. + + * Version 3. Modular and parameterized definitions. + + Igor Konnov, 2020. + *) + +EXTENDS TendermintAccInv_004_draft + +\* make them parameters? +NFaultyProposals == 0 \* the number of injected faulty PROPOSE messages +NFaultyPrevotes == 6 \* the number of injected faulty PREVOTE messages +NFaultyPrecommits == 6 \* the number of injected faulty PRECOMMIT messages + +\* Given a set of allowed messages Msgs, this operator produces a function from +\* rounds to sets of messages. +\* Importantly, there will be exactly k messages in the image of msgFun. +\* We use this action to produce k faults in an initial state. +\* @type: ($round -> Set({ round: $round, a }), +\* Set({ round: $round, a }), Int) +\* => Bool; +ProduceFaults(msgFun, From, k) == + \E f \in [1..k -> From]: + msgFun = [r \in Rounds |-> {m \in {f[i]: i \in 1..k}: m.round = r}] + +\* As TLC explodes with faults, we may have initial states without faults +InitNoFaults == + /\ round = [p \in Corr |-> 0] + /\ step = [p \in Corr |-> "PROPOSE"] + /\ decision = [p \in Corr |-> NilValue] + /\ lockedValue = [p \in Corr |-> NilValue] + /\ lockedRound = [p \in Corr |-> NilRound] + /\ validValue = [p \in Corr |-> NilValue] + /\ validRound = [p \in Corr |-> NilRound] + /\ msgsPropose = [r \in Rounds |-> {}] + /\ msgsPrevote = [r \in Rounds |-> {}] + /\ msgsPrecommit = [r \in Rounds |-> {}] + /\ evidencePropose = {} + /\ evidencePrevote = {} + /\ evidencePrecommit = {} + +(* + A specialized version of Init that injects NFaultyProposals proposals, + NFaultyPrevotes prevotes, NFaultyPrecommits precommits by the faulty processes + *) +InitFewFaults == + /\ round = [p \in Corr |-> 0] + /\ step = [p \in Corr |-> "PROPOSE"] + /\ decision = [p \in Corr |-> NilValue] + /\ lockedValue = [p \in Corr |-> NilValue] + /\ lockedRound = [p \in Corr |-> NilRound] + /\ validValue = [p \in Corr |-> NilValue] + /\ validRound = [p \in Corr |-> NilRound] + /\ ProduceFaults(msgsPrevote', + [type: {"PREVOTE"}, src: Faulty, round: Rounds, id: Values], + NFaultyPrevotes) + /\ ProduceFaults(msgsPrecommit', + [type: {"PRECOMMIT"}, src: Faulty, round: Rounds, id: Values], + NFaultyPrecommits) + /\ ProduceFaults(msgsPropose', + [type: {"PROPOSAL"}, src: Faulty, round: Rounds, + proposal: Values, validRound: Rounds \cup {NilRound}], + NFaultyProposals) + /\ evidencePropose = {} + /\ evidencePrevote = {} + /\ evidencePrecommit = {} + +\* Add faults incrementally +NextWithFaults == + \* either the protocol makes a step + \/ Next + \* or a faulty process sends a message + \//\ UNCHANGED <> + /\ \E p \in Faulty: + \E r \in Rounds: + \//\ UNCHANGED <> + /\ \E proposal \in ValidValues \union {NilValue}: + \E vr \in RoundsOrNil: + BroadcastProposal(p, r, proposal, vr) + \//\ UNCHANGED <> + /\ \E id \in ValidValues \union {NilValue}: + BroadcastPrevote(p, r, id) + \//\ UNCHANGED <> + /\ \E id \in ValidValues \union {NilValue}: + BroadcastPrecommit(p, r, id) + +(******************************** PROPERTIES ***************************************) +\* simple reachability properties to see that the spec is progressing +NoPrevote == \A p \in Corr: step[p] /= "PREVOTE" + +NoPrecommit == \A p \in Corr: step[p] /= "PRECOMMIT" + +NoValidPrecommit == + \A r \in Rounds: + \A m \in msgsPrecommit[r]: + m.id = NilValue \/ m.src \in Faulty + +NoHigherRounds == \A p \in Corr: round[p] < 1 + +NoDecision == \A p \in Corr: decision[p] = NilValue + +============================================================================= + diff --git a/spec/light-client/accountability/TendermintAccInv_004_draft.tla b/spec/light-client/accountability/TendermintAccInv_004_draft.tla new file mode 100644 index 0000000..fc0e201 --- /dev/null +++ b/spec/light-client/accountability/TendermintAccInv_004_draft.tla @@ -0,0 +1,377 @@ +------------------- MODULE TendermintAccInv_004_draft -------------------------- +(* + An inductive invariant for TendermintAcc3, which capture the forked + and non-forked cases. + + * Version 3. Modular and parameterized definitions. + * Version 2. Bugfixes in the spec and an inductive invariant. + + Igor Konnov, 2020. + *) + +EXTENDS TendermintAcc_004_draft + +(************************** TYPE INVARIANT ***********************************) +(* first, we define the sets of all potential messages *) +AllProposals == + [type: {"PROPOSAL"}, + src: AllProcs, + round: Rounds, + proposal: ValuesOrNil, + validRound: RoundsOrNil] + +AllPrevotes == + [type: {"PREVOTE"}, + src: AllProcs, + round: Rounds, + id: ValuesOrNil] + +AllPrecommits == + [type: {"PRECOMMIT"}, + src: AllProcs, + round: Rounds, + id: ValuesOrNil] + +(* the standard type invariant -- importantly, it is inductive *) +TypeOK == + /\ round \in [Corr -> Rounds] + /\ step \in [Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" }] + /\ decision \in [Corr -> ValidValues \union {NilValue}] + /\ lockedValue \in [Corr -> ValidValues \union {NilValue}] + /\ lockedRound \in [Corr -> RoundsOrNil] + /\ validValue \in [Corr -> ValidValues \union {NilValue}] + /\ validRound \in [Corr -> RoundsOrNil] + /\ msgsPropose \in [Rounds -> SUBSET AllProposals] + /\ BenignRoundsInMessages(msgsPropose) + /\ msgsPrevote \in [Rounds -> SUBSET AllPrevotes] + /\ BenignRoundsInMessages(msgsPrevote) + /\ msgsPrecommit \in [Rounds -> SUBSET AllPrecommits] + /\ BenignRoundsInMessages(msgsPrecommit) + /\ evidencePropose \in SUBSET AllProposals + /\ evidencePrevote \in SUBSET AllPrevotes + /\ evidencePrecommit \in SUBSET AllPrecommits + /\ action \in { + "Init", + "InsertProposal", + "UponProposalInPropose", + "UponProposalInProposeAndPrevote", + "UponQuorumOfPrevotesAny", + "UponProposalInPrevoteOrCommitAndPrevote", + "UponQuorumOfPrecommitsAny", + "UponProposalInPrecommitNoDecision", + "OnTimeoutPropose", + "OnQuorumOfNilPrevotes", + "OnRoundCatchup" + } + +(************************** INDUCTIVE INVARIANT *******************************) +EvidenceContainsMessages == + \* evidence contains only the messages from: + \* msgsPropose, msgsPrevote, and msgsPrecommit + /\ \A m \in evidencePropose: + m \in msgsPropose[m.round] + /\ \A m \in evidencePrevote: + m \in msgsPrevote[m.round] + /\ \A m \in evidencePrecommit: + m \in msgsPrecommit[m.round] + +NoFutureMessagesForLargerRounds(p) == + \* a correct process does not send messages for the future rounds + \A r \in { rr \in Rounds: rr > round[p] }: + /\ \A m \in msgsPropose[r]: m.src /= p + /\ \A m \in msgsPrevote[r]: m.src /= p + /\ \A m \in msgsPrecommit[r]: m.src /= p + +NoFutureMessagesForCurrentRound(p) == + \* a correct process does not send messages in the future + LET r == round[p] IN + /\ Proposer[r] = p \/ \A m \in msgsPropose[r]: m.src /= p + /\ \/ step[p] \in {"PREVOTE", "PRECOMMIT", "DECIDED"} + \/ \A m \in msgsPrevote[r]: m.src /= p + /\ \/ step[p] \in {"PRECOMMIT", "DECIDED"} + \/ \A m \in msgsPrecommit[r]: m.src /= p + +\* the correct processes never send future messages +AllNoFutureMessagesSent == + \A p \in Corr: + /\ NoFutureMessagesForCurrentRound(p) + /\ NoFutureMessagesForLargerRounds(p) + +\* a correct process in the PREVOTE state has sent a PREVOTE message +IfInPrevoteThenSentPrevote(p) == + step[p] = "PREVOTE" => + \E m \in msgsPrevote[round[p]]: + /\ m.id \in ValidValues \cup { NilValue } + /\ m.src = p + +AllIfInPrevoteThenSentPrevote == + \A p \in Corr: IfInPrevoteThenSentPrevote(p) + +\* a correct process in the PRECOMMIT state has sent a PRECOMMIT message +IfInPrecommitThenSentPrecommit(p) == + step[p] = "PRECOMMIT" => + \E m \in msgsPrecommit[round[p]]: + /\ m.id \in ValidValues \cup { NilValue } + /\ m.src = p + +AllIfInPrecommitThenSentPrecommit == + \A p \in Corr: IfInPrecommitThenSentPrecommit(p) + +\* a process in the PRECOMMIT state has sent a PRECOMMIT message +IfInDecidedThenValidDecision(p) == + step[p] = "DECIDED" <=> decision[p] \in ValidValues + +AllIfInDecidedThenValidDecision == + \A p \in Corr: IfInDecidedThenValidDecision(p) + +\* a decided process should have received a proposal on its decision +IfInDecidedThenReceivedProposal(p) == + step[p] = "DECIDED" => + \E r \in Rounds: \* r is not necessarily round[p] + /\ \E m \in msgsPropose[r] \intersect evidencePropose: + /\ m.src = Proposer[r] + /\ m.proposal = decision[p] + \* not inductive: /\ m.src \in Corr => (m.validRound <= r) + +AllIfInDecidedThenReceivedProposal == + \A p \in Corr: + IfInDecidedThenReceivedProposal(p) + +\* a decided process has received two-thirds of precommit messages +IfInDecidedThenReceivedTwoThirds(p) == + step[p] = "DECIDED" => + \E r \in Rounds: + LET PV == { + m \in msgsPrecommit[r] \intersect evidencePrecommit: + m.id = decision[p] + } + IN + Cardinality(PV) >= THRESHOLD2 + +AllIfInDecidedThenReceivedTwoThirds == + \A p \in Corr: + IfInDecidedThenReceivedTwoThirds(p) + +\* for a round r, there is proposal by the round proposer for a valid round vr +ProposalInRound(r, proposedVal, vr) == + \E m \in msgsPropose[r]: + /\ m.src = Proposer[r] + /\ m.proposal = proposedVal + /\ m.validRound = vr + +TwoThirdsPrevotes(vr, v) == + LET PV == { mm \in msgsPrevote[vr] \intersect evidencePrevote: mm.id = v } IN + Cardinality(PV) >= THRESHOLD2 + +\* if a process sends a PREVOTE, then there are three possibilities: +\* 1) the process is faulty, 2) the PREVOTE cotains Nil, +\* 3) there is a proposal in an earlier (valid) round and two thirds of PREVOTES +IfSentPrevoteThenReceivedProposalOrTwoThirds(r) == + \A mpv \in msgsPrevote[r]: + \/ mpv.src \in Faulty + \* lockedRound and lockedValue is beyond my comprehension + \/ mpv.id = NilValue + \//\ mpv.src \in Corr + /\ mpv.id /= NilValue + /\ \/ ProposalInRound(r, mpv.id, NilRound) + \/ \E vr \in { rr \in Rounds: rr < r }: + /\ ProposalInRound(r, mpv.id, vr) + /\ TwoThirdsPrevotes(vr, mpv.id) + +AllIfSentPrevoteThenReceivedProposalOrTwoThirds == + \A r \in Rounds: + IfSentPrevoteThenReceivedProposalOrTwoThirds(r) + +\* if a correct process has sent a PRECOMMIT, then there are two thirds, +\* either on a valid value, or a nil value +IfSentPrecommitThenReceivedTwoThirds == + \A r \in Rounds: + \A mpc \in msgsPrecommit[r]: + mpc.src \in Corr => + \/ /\ mpc.id \in ValidValues + /\ LET PV == { + m \in msgsPrevote[r] \intersect evidencePrevote: m.id = mpc.id + } + IN + Cardinality(PV) >= THRESHOLD2 + \/ /\ mpc.id = NilValue + /\ Cardinality(msgsPrevote[r]) >= THRESHOLD2 + +\* if a correct process has sent a precommit message in a round, it should +\* have sent a prevote +IfSentPrecommitThenSentPrevote == + \A r \in Rounds: + \A mpc \in msgsPrecommit[r]: + mpc.src \in Corr => + \E m \in msgsPrevote[r]: + m.src = mpc.src + +\* there is a locked round if a only if there is a locked value +LockedRoundIffLockedValue(p) == + (lockedRound[p] = NilRound) <=> (lockedValue[p] = NilValue) + +AllLockedRoundIffLockedValue == + \A p \in Corr: + LockedRoundIffLockedValue(p) + +\* when a process locked a round, it must have sent a precommit on the locked value. +IfLockedRoundThenSentCommit(p) == + lockedRound[p] /= NilRound + => \E r \in { rr \in Rounds: rr <= round[p] }: + \E m \in msgsPrecommit[r]: + m.src = p /\ m.id = lockedValue[p] + +AllIfLockedRoundThenSentCommit == + \A p \in Corr: + IfLockedRoundThenSentCommit(p) + +\* a process always locks the latest round, for which it has sent a PRECOMMIT +LatestPrecommitHasLockedRound(p) == + LET pPrecommits == + {mm \in UNION { msgsPrecommit[r]: r \in Rounds }: mm.src = p /\ mm.id /= NilValue } + IN + pPrecommits /= {} + => LET latest == + CHOOSE m \in pPrecommits: + \A m2 \in pPrecommits: + m2.round <= m.round + IN + /\ lockedRound[p] = latest.round + /\ lockedValue[p] = latest.id + +AllLatestPrecommitHasLockedRound == + \A p \in Corr: + LatestPrecommitHasLockedRound(p) + +\* Every correct process sends only one value or NilValue. +\* This test has quantifier alternation -- a threat to all decision procedures. +\* Luckily, the sets Corr and ValidValues are small. +\* @type: ($round, $round -> Set($preMsg)) => Bool; +NoEquivocationByCorrect(r, msgs) == + \A p \in Corr: + \E v \in ValidValues \union {NilValue}: + \A m \in msgs[r]: + \/ m.src /= p + \/ m.id = v + +\* a proposer nevers sends two values +\* @type: ($round, $round -> Set($proposeMsg)) => Bool; +ProposalsByProposer(r, msgs) == + \* if the proposer is not faulty, it sends only one value + \E v \in ValidValues: + \A m \in msgs[r]: + \/ m.src \in Faulty + \/ m.src = Proposer[r] /\ m.proposal = v + +AllNoEquivocationByCorrect == + \A r \in Rounds: + /\ ProposalsByProposer(r, msgsPropose) + /\ NoEquivocationByCorrect(r, msgsPrevote) + /\ NoEquivocationByCorrect(r, msgsPrecommit) + +\* construct the set of the message senders +\* @type: (Set({ src: $process, a })) => Set($process); +Senders(M) == { m.src: m \in M } + +\* The final piece by Josef Widder: +\* if T + 1 processes precommit on the same value in a round, +\* then in the future rounds there are less than 2T + 1 prevotes for another value +PrecommitsLockValue == + \A r \in Rounds: + \A v \in ValidValues \union {NilValue}: + \/ LET Precommits == {m \in msgsPrecommit[r]: m.id = v} + IN + Cardinality(Senders(Precommits)) < THRESHOLD1 + \/ \A fr \in { rr \in Rounds: rr > r }: \* future rounds + \A w \in (ValuesOrNil) \ {v}: + LET Prevotes == {m \in msgsPrevote[fr]: m.id = w} + IN + Cardinality(Senders(Prevotes)) < THRESHOLD2 + +\* a combination of all lemmas +Inv == + /\ EvidenceContainsMessages + /\ AllNoFutureMessagesSent + /\ AllIfInPrevoteThenSentPrevote + /\ AllIfInPrecommitThenSentPrecommit + /\ AllIfInDecidedThenReceivedProposal + /\ AllIfInDecidedThenReceivedTwoThirds + /\ AllIfInDecidedThenValidDecision + /\ AllLockedRoundIffLockedValue + /\ AllIfLockedRoundThenSentCommit + /\ AllLatestPrecommitHasLockedRound + /\ AllIfSentPrevoteThenReceivedProposalOrTwoThirds + /\ IfSentPrecommitThenSentPrevote + /\ IfSentPrecommitThenReceivedTwoThirds + /\ AllNoEquivocationByCorrect + /\ PrecommitsLockValue + +\* this is the inductive invariant we like to check +TypedInv == TypeOK /\ Inv + +\* UNUSED FOR SAFETY +ValidRoundNotSmallerThanLockedRound(p) == + validRound[p] >= lockedRound[p] + +\* UNUSED FOR SAFETY +ValidRoundIffValidValue(p) == + (validRound[p] = NilRound) <=> (validValue[p] = NilValue) + +\* UNUSED FOR SAFETY +AllValidRoundIffValidValue == + \A p \in Corr: ValidRoundIffValidValue(p) + +\* if validRound is defined, then there are two-thirds of PREVOTEs +IfValidRoundThenTwoThirds(p) == + \/ validRound[p] = NilRound + \/ LET PV == { m \in msgsPrevote[validRound[p]]: m.id = validValue[p] } IN + Cardinality(PV) >= THRESHOLD2 + +\* UNUSED FOR SAFETY +AllIfValidRoundThenTwoThirds == + \A p \in Corr: IfValidRoundThenTwoThirds(p) + +\* a valid round can be only set to a valid value that was proposed earlier +IfValidRoundThenProposal(p) == + \/ validRound[p] = NilRound + \/ \E m \in msgsPropose[validRound[p]]: + m.proposal = validValue[p] + +\* UNUSED FOR SAFETY +AllIfValidRoundThenProposal == + \A p \in Corr: IfValidRoundThenProposal(p) + +(******************************** THEOREMS ***************************************) +(* Under this condition, the faulty processes can decide alone *) +FaultyQuorum == Cardinality(Faulty) >= THRESHOLD2 + +(* The standard condition of the Cosmos security model *) +LessThanThirdFaulty == N > 3 * T /\ Cardinality(Faulty) <= T + +(* + TypedInv is an inductive invariant, provided that there is no faulty quorum. + We run Apalache to prove this theorem only for fixed instances of 4 to 10 processes. + (We run Apalache manually, as it does not parse theorem statements at the moment.) + To get a parameterized argument, one has to use a theorem prover, e.g., TLAPS. + *) +THEOREM TypedInvIsInductive == + \/ FaultyQuorum \* if there are 2 * T + 1 faulty processes, we give up + \//\ Init => TypedInv + /\ TypedInv /\ [Next]_vars => TypedInv' + +(* + There should be no fork, when there are less than 1/3 faulty processes. + *) +THEOREM AgreementWhenLessThanThirdFaulty == + LessThanThirdFaulty /\ TypedInv => Agreement + +(* + In a more general case, when there are less than 2/3 faulty processes, + there is either Agreement (no fork), or two scenarios exist: + equivocation by Faulty, or amnesia by Faulty. + *) +THEOREM AgreementOrFork == + ~FaultyQuorum /\ TypedInv => Accountability + +============================================================================= + diff --git a/spec/light-client/accountability/TendermintAccTrace_004_draft.tla b/spec/light-client/accountability/TendermintAccTrace_004_draft.tla new file mode 100644 index 0000000..b49908a --- /dev/null +++ b/spec/light-client/accountability/TendermintAccTrace_004_draft.tla @@ -0,0 +1,37 @@ +------------------ MODULE TendermintAccTrace_004_draft ------------------------- +(* + When Apalache is running too slow and we have an idea of a counterexample, + we use this module to restrict the behaviors only to certain actions. + Once the whole trace is replayed, the system deadlocks. + + Version 1. + + Igor Konnov, 2020. + *) + +EXTENDS Sequences, Apalache, typedefs, TendermintAcc_004_draft + +\* a sequence of action names that should appear in the given order, +\* excluding "Init" +CONSTANT + \* @type: $trace; + Trace + +VARIABLE + \* @type: $trace; + toReplay + +TraceInit == + /\ toReplay = Trace + /\ action' := "Init" + /\ Init + +TraceNext == + /\ Len(toReplay) > 0 + /\ toReplay' = Tail(toReplay) + \* Here is the trick. We restrict the action to the expected one, + \* so the other actions will be pruned + /\ action' := Head(toReplay) + /\ Next + +================================================================================ diff --git a/spec/light-client/accountability/TendermintAcc_004_draft.tla b/spec/light-client/accountability/TendermintAcc_004_draft.tla new file mode 100644 index 0000000..ed9ad9c --- /dev/null +++ b/spec/light-client/accountability/TendermintAcc_004_draft.tla @@ -0,0 +1,601 @@ +-------------------- MODULE TendermintAcc_004_draft --------------------------- +(* + A TLA+ specification of a simplified Tendermint consensus algorithm, tuned for + fork accountability. The simplifications are as follows: + + - the protocol runs for one height, that is, it is one-shot consensus + + - this specification focuses on safety, so timeouts are modelled + with non-determinism + + - the proposer function is non-determinstic, no fairness is assumed + + - the messages by the faulty processes are injected right in the initial states + + - every process has the voting power of 1 + + - hashes are modelled as identity + + Having the above assumptions in mind, the specification follows the pseudo-code + of the Tendermint paper: https://arxiv.org/abs/1807.04938 + + Byzantine processes can demonstrate arbitrary behavior, including + no communication. We show that if agreement is violated, then the Byzantine + processes demonstrate one of the two behaviours: + + - Equivocation: a Byzantine process may send two different values + in the same round. + + - Amnesia: a Byzantine process may lock a value without unlocking + the previous value that it has locked in the past. + + * Version 5. Refactor evidence, migrate to Apalache Type System 1.2. + * Version 4. Remove defective processes, fix bugs, collect global evidence. + * Version 3. Modular and parameterized definitions. + * Version 2. Bugfixes in the spec and an inductive invariant. + * Version 1. A preliminary specification. + + Zarko Milosevic, Igor Konnov, Informal Systems, 2019-2020. + *) + +EXTENDS Integers, FiniteSets, typedefs + +(********************* PROTOCOL PARAMETERS **********************************) +CONSTANTS + \* @type: Set($process); + Corr, \* the set of correct processes + \* @type: Set($process); + Faulty, \* the set of Byzantine processes, may be empty + \* @type: Int; + N, \* the total number of processes: correct, defective, and Byzantine + \* @type: Int; + T, \* an upper bound on the number of Byzantine processes + \* @type: Set($value); + ValidValues, \* the set of valid values, proposed both by correct and faulty + \* @type: Set($value); + InvalidValues, \* the set of invalid values, never proposed by the correct ones + \* @type: $round; + MaxRound, \* the maximal round number + \* @type: $round -> $process; + Proposer \* the proposer function from Rounds to AllProcs + +ASSUME(N = Cardinality(Corr \union Faulty)) + +(*************************** DEFINITIONS ************************************) +AllProcs == Corr \union Faulty \* the set of all processes +\* @type: Set($round); +Rounds == 0..MaxRound \* the set of potential rounds +\* @type: $round; +NilRound == -1 \* a special value to denote a nil round, outside of Rounds +RoundsOrNil == Rounds \union {NilRound} +Values == ValidValues \union InvalidValues \* the set of all values +\* @type: $value; +NilValue == "None" \* a special value for a nil round, outside of Values +ValuesOrNil == Values \union {NilValue} + +\* a value hash is modeled as identity +\* @type: (t) => t; +Id(v) == v + +\* The validity predicate +IsValid(v) == v \in ValidValues + +\* the two thresholds that are used in the algorithm +THRESHOLD1 == T + 1 \* at least one process is not faulty +THRESHOLD2 == 2 * T + 1 \* a quorum when having N > 3 * T + +(********************* PROTOCOL STATE VARIABLES ******************************) +VARIABLES + \* @type: $process -> $round; + round, \* a process round number: Corr -> Rounds + \* @type: $process -> $step; + step, \* a process step: Corr -> { "PROPOSE", "PREVOTE", "PRECOMMIT", "DECIDED" } + \* @type: $process -> $value; + decision, \* process decision: Corr -> ValuesOrNil + \* @type: $process -> $value; + lockedValue, \* a locked value: Corr -> ValuesOrNil + \* @type: $process -> $round; + lockedRound, \* a locked round: Corr -> RoundsOrNil + \* @type: $process -> $value; + validValue, \* a valid value: Corr -> ValuesOrNil + \* @type: $process -> $round; + validRound \* a valid round: Corr -> RoundsOrNil + +\* book-keeping variables +VARIABLES + \* @type: $round -> Set($proposeMsg); + msgsPropose, \* PROPOSE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrevote, \* PREVOTE messages broadcast in the system, Rounds -> Messages + \* @type: $round -> Set($preMsg); + msgsPrecommit, \* PRECOMMIT messages broadcast in the system, Rounds -> Messages + \* @type: Set($proposeMsg); + evidencePropose, \* the PROPOSE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrevote, \* the PREVOTE messages used by some correct processes to make transitions + \* @type: Set($preMsg); + evidencePrecommit, \* the PRECOMMIT messages used by some correct processes to make transitions + \* @type: $action; + action \* we use this variable to see which action was taken + +(* to see a type invariant, check TendermintAccInv3 *) + +\* a handy definition used in UNCHANGED +vars == <> + +(********************* PROTOCOL INITIALIZATION ******************************) +\* @type: ($round) => Set($proposeMsg); +FaultyProposals(r) == + [ + type : {"PROPOSAL"}, + src : Faulty, + round : {r}, + proposal : Values, + validRound: RoundsOrNil + ] + +\* @type: Set($proposeMsg); +AllFaultyProposals == + [ + type : {"PROPOSAL"}, + src : Faulty, + round : Rounds, + proposal : Values, + validRound: RoundsOrNil + ] + +\* @type: ($round) => Set($preMsg); +FaultyPrevotes(r) == + [ + type : {"PREVOTE"}, + src : Faulty, + round: {r}, + id : Values + ] + +\* @type: Set($preMsg); +AllFaultyPrevotes == + [ + type : {"PREVOTE"}, + src : Faulty, + round: Rounds, + id : Values + ] + +\* @type: ($round) => Set($preMsg); +FaultyPrecommits(r) == + [ + type : {"PRECOMMIT"}, + src : Faulty, + round: {r}, + id : Values + ] + +\* @type: Set($preMsg); +AllFaultyPrecommits == + [ + type : {"PRECOMMIT"}, + src : Faulty, + round: Rounds, + id : Values + ] + +\* @type: ($round -> Set({ round: Int, a })) => Bool; +BenignRoundsInMessages(msgfun) == + \* the message function never contains a message for a wrong round + \A r \in Rounds: + \A m \in msgfun[r]: + r = m.round + +\* The initial states of the protocol. Some faults can be in the system already. +Init == + /\ round = [p \in Corr |-> 0] + /\ step = [p \in Corr |-> "PROPOSE"] + /\ decision = [p \in Corr |-> NilValue] + /\ lockedValue = [p \in Corr |-> NilValue] + /\ lockedRound = [p \in Corr |-> NilRound] + /\ validValue = [p \in Corr |-> NilValue] + /\ validRound = [p \in Corr |-> NilRound] + /\ msgsPropose \in [Rounds -> SUBSET AllFaultyProposals] + /\ msgsPrevote \in [Rounds -> SUBSET AllFaultyPrevotes] + /\ msgsPrecommit \in [Rounds -> SUBSET AllFaultyPrecommits] + /\ BenignRoundsInMessages(msgsPropose) + /\ BenignRoundsInMessages(msgsPrevote) + /\ BenignRoundsInMessages(msgsPrecommit) + /\ evidencePropose = {} + /\ evidencePrevote = {} + /\ evidencePrecommit = {} + /\ action = "Init" + +(************************ MESSAGE PASSING ********************************) +\* @type: ($process, $round, $value, $round) => Bool; +BroadcastProposal(pSrc, pRound, pProposal, pValidRound) == + LET newMsg == [ + type |-> "PROPOSAL", + src |-> pSrc, + round |-> pRound, + proposal |-> pProposal, + validRound |-> pValidRound + ] + IN + msgsPropose' = [msgsPropose EXCEPT ![pRound] = msgsPropose[pRound] \union {newMsg}] + +\* @type: ($process, $round, $value) => Bool; +BroadcastPrevote(pSrc, pRound, pId) == + LET newMsg == [ + type |-> "PREVOTE", + src |-> pSrc, + round |-> pRound, + id |-> pId + ] + IN + msgsPrevote' = [msgsPrevote EXCEPT ![pRound] = msgsPrevote[pRound] \union {newMsg}] + +\* @type: ($process, $round, $value) => Bool; +BroadcastPrecommit(pSrc, pRound, pId) == + LET newMsg == [ + type |-> "PRECOMMIT", + src |-> pSrc, + round |-> pRound, + id |-> pId + ] + IN + msgsPrecommit' = [msgsPrecommit EXCEPT ![pRound] = msgsPrecommit[pRound] \union {newMsg}] + + +(********************* PROTOCOL TRANSITIONS ******************************) +\* lines 12-13 +StartRound(p, r) == + /\ step[p] /= "DECIDED" \* a decided process does not participate in consensus + /\ round' = [round EXCEPT ![p] = r] + /\ step' = [step EXCEPT ![p] = "PROPOSE"] + +\* lines 14-19, a proposal may be sent later +\* @type: $process => Bool; +InsertProposal(p) == + LET r == round[p] IN + /\ p = Proposer[r] + /\ step[p] = "PROPOSE" + \* if the proposer is sending a proposal, then there are no other proposals + \* by the correct processes for the same round + /\ \A m \in msgsPropose[r]: m.src /= p + /\ \E v \in ValidValues: + LET proposal == + IF validValue[p] /= NilValue + THEN validValue[p] + ELSE v + IN BroadcastProposal(p, round[p], proposal, validRound[p]) + /\ UNCHANGED <> + /\ action' = "InsertProposal" + +\* lines 22-27 +UponProposalInPropose(p) == + \E v \in Values: + /\ step[p] = "PROPOSE" (* line 22 *) + /\ LET msg == [ + type |-> "PROPOSAL", + src |-> Proposer[round[p]], + round |-> round[p], + proposal |-> v, + validRound |-> NilRound + ] + IN + /\ msg \in msgsPropose[round[p]] \* line 22 + /\ evidencePropose' = {msg} \union evidencePropose + /\ LET mid == (* line 23 *) + IF IsValid(v) /\ (lockedRound[p] = NilRound \/ lockedValue[p] = v) + THEN Id(v) + ELSE NilValue + IN + BroadcastPrevote(p, round[p], mid) \* lines 24-26 + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "UponProposalInPropose" + +\* lines 28-33 +UponProposalInProposeAndPrevote(p) == + \E v \in Values, vr \in Rounds: + /\ step[p] = "PROPOSE" /\ 0 <= vr /\ vr < round[p] \* line 28, the while part + /\ LET msg == [ + type |-> "PROPOSAL", + src |-> Proposer[round[p]], + round |-> round[p], + proposal |-> v, + validRound |-> vr + ] + IN + /\ msg \in msgsPropose[round[p]] \* line 28 + /\ LET PV == { m \in msgsPrevote[vr]: m.id = Id(v) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 28 + /\ evidencePropose' = {msg} \union evidencePropose + /\ evidencePrevote' = PV \union evidencePrevote + /\ LET mid == (* line 29 *) + IF IsValid(v) /\ (lockedRound[p] <= vr \/ lockedValue[p] = v) + THEN Id(v) + ELSE NilValue + IN + BroadcastPrevote(p, round[p], mid) \* lines 24-26 + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "UponProposalInProposeAndPrevote" + + \* lines 34-35 + lines 61-64 (onTimeoutPrevote) +UponQuorumOfPrevotesAny(p) == + /\ step[p] = "PREVOTE" \* line 34 and 61 + /\ \E MyEvidence \in SUBSET msgsPrevote[round[p]]: + \* find the unique voters in the evidence + LET Voters == { m.src: m \in MyEvidence } IN + \* compare the number of the unique voters against the threshold + /\ Cardinality(Voters) >= THRESHOLD2 \* line 34 + /\ evidencePrevote' = MyEvidence \union evidencePrevote + /\ BroadcastPrecommit(p, round[p], NilValue) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + /\ UNCHANGED <> + /\ action' = "UponQuorumOfPrevotesAny" + +\* lines 36-46 +UponProposalInPrevoteOrCommitAndPrevote(p) == + \E v \in ValidValues, vr \in RoundsOrNil: + /\ step[p] \in {"PREVOTE", "PRECOMMIT"} \* line 36 + /\ LET msg == [ + type |-> "PROPOSAL", + src |-> Proposer[round[p]], + round |-> round[p], + proposal |-> v, + validRound |-> vr + ] + IN + /\ msg \in msgsPropose[round[p]] \* line 36 + /\ LET PV == { m \in msgsPrevote[round[p]]: m.id = Id(v) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 36 + /\ evidencePrevote' = PV \union evidencePrevote + /\ evidencePropose' = {msg} \union evidencePropose + /\ IF step[p] = "PREVOTE" + THEN \* lines 38-41: + /\ lockedValue' = [lockedValue EXCEPT ![p] = v] + /\ lockedRound' = [lockedRound EXCEPT ![p] = round[p]] + /\ BroadcastPrecommit(p, round[p], Id(v)) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + ELSE + UNCHANGED <> + \* lines 42-43 + /\ validValue' = [validValue EXCEPT ![p] = v] + /\ validRound' = [validRound EXCEPT ![p] = round[p]] + /\ UNCHANGED <> + /\ action' = "UponProposalInPrevoteOrCommitAndPrevote" + +\* lines 47-48 + 65-67 (onTimeoutPrecommit) +UponQuorumOfPrecommitsAny(p) == + /\ \E MyEvidence \in SUBSET msgsPrecommit[round[p]]: + \* find the unique committers in the evidence + LET Committers == { m.src: m \in MyEvidence } IN + \* compare the number of the unique committers against the threshold + /\ Cardinality(Committers) >= THRESHOLD2 \* line 47 + /\ evidencePrecommit' = MyEvidence \union evidencePrecommit + /\ round[p] + 1 \in Rounds + /\ StartRound(p, round[p] + 1) + /\ UNCHANGED <> + /\ action' = "UponQuorumOfPrecommitsAny" + +\* lines 49-54 +UponProposalInPrecommitNoDecision(p) == + /\ decision[p] = NilValue \* line 49 + /\ \E v \in ValidValues (* line 50*) , r \in Rounds, vr \in RoundsOrNil: + /\ LET msg == [ + type |-> "PROPOSAL", + src |-> Proposer[r], + round |-> r, + proposal |-> v, + validRound |-> vr + ] + IN + /\ msg \in msgsPropose[r] \* line 49 + /\ LET PV == { m \in msgsPrecommit[r]: m.id = Id(v) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 49 + /\ evidencePrecommit' = PV \union evidencePrecommit + /\ evidencePropose' = evidencePropose \union { msg } + /\ decision' = [decision EXCEPT ![p] = v] \* update the decision, line 51 + \* The original algorithm does not have 'DECIDED', but it increments the height. + \* We introduced 'DECIDED' here to prevent the process from changing its decision. + /\ step' = [step EXCEPT ![p] = "DECIDED"] + /\ UNCHANGED <> + /\ action' = "UponProposalInPrecommitNoDecision" + +\* the actions below are not essential for safety, but added for completeness + +\* lines 20-21 + 57-60 +OnTimeoutPropose(p) == + /\ step[p] = "PROPOSE" + /\ p /= Proposer[round[p]] + /\ BroadcastPrevote(p, round[p], NilValue) + /\ step' = [step EXCEPT ![p] = "PREVOTE"] + /\ UNCHANGED <> + /\ action' = "OnTimeoutPropose" + +\* lines 44-46 +OnQuorumOfNilPrevotes(p) == + /\ step[p] = "PREVOTE" + /\ LET PV == { m \in msgsPrevote[round[p]]: m.id = Id(NilValue) } IN + /\ Cardinality(PV) >= THRESHOLD2 \* line 36 + /\ evidencePrevote' = PV \union evidencePrevote + /\ BroadcastPrecommit(p, round[p], Id(NilValue)) + /\ step' = [step EXCEPT ![p] = "PRECOMMIT"] + /\ UNCHANGED <> + /\ action' = "OnQuorumOfNilPrevotes" + +\* lines 55-56 +OnRoundCatchup(p) == + \E r \in {rr \in Rounds: rr > round[p]}: + \E EvPropose \in SUBSET msgsPropose[r], + EvPrevote \in SUBSET msgsPrevote[r], + EvPrecommit \in SUBSET msgsPrecommit[r]: + LET \* @type: Set({ src: $process, a }) => Set($process); + Src(E) == { m.src: m \in E } + IN + LET Faster == + Src(EvPropose) \union Src(EvPrevote) \union Src(EvPrecommit) + IN + /\ Cardinality(Faster) >= THRESHOLD1 + /\ evidencePropose' = EvPropose \union evidencePropose + /\ evidencePrevote' = EvPrevote \union evidencePrevote + /\ evidencePrecommit' = EvPrecommit \union evidencePrecommit + /\ StartRound(p, r) + /\ UNCHANGED <> + /\ action' = "OnRoundCatchup" + +(* + * A system transition. In this specificatiom, the system may eventually deadlock, + * e.g., when all processes decide. This is expected behavior, as we focus on safety. + *) +Next == + \E p \in Corr: + \/ InsertProposal(p) + \/ UponProposalInPropose(p) + \/ UponProposalInProposeAndPrevote(p) + \/ UponQuorumOfPrevotesAny(p) + \/ UponProposalInPrevoteOrCommitAndPrevote(p) + \/ UponQuorumOfPrecommitsAny(p) + \/ UponProposalInPrecommitNoDecision(p) + \* the actions below are not essential for safety, but added for completeness + \/ OnTimeoutPropose(p) + \/ OnQuorumOfNilPrevotes(p) + \/ OnRoundCatchup(p) + + +(**************************** FORK SCENARIOS ***************************) + +\* equivocation by a process p +EquivocationBy(p) == + LET + \* @type: Set({ src: $process, a }) => Bool; + EquivocationIn(S) == + \E m1, m2 \in S: + /\ m1 /= m2 + /\ m1.src = p + /\ m2.src = p + /\ m1.round = m2.round + /\ m1.type = m2.type + IN + \/ EquivocationIn(evidencePropose) + \/ EquivocationIn(evidencePrevote) + \/ EquivocationIn(evidencePrecommit) + +\* amnesic behavior by a process p +AmnesiaBy(p) == + \E r1, r2 \in Rounds: + /\ r1 < r2 + /\ \E v1, v2 \in ValidValues: + /\ v1 /= v2 + /\ [ + type |-> "PRECOMMIT", + src |-> p, + round |-> r1, + id |-> Id(v1) + ] \in evidencePrecommit + /\ [ + type |-> "PREVOTE", + src |-> p, + round |-> r2, + id |-> Id(v2) + ] \in evidencePrevote + /\ \A r \in { rnd \in Rounds: r1 <= rnd /\ rnd < r2 }: + LET prevotes == + { m \in evidencePrevote: m.round = r /\ m.id = Id(v2) } + IN + Cardinality(prevotes) < THRESHOLD2 + +(******************************** PROPERTIES ***************************************) + +\* the safety property -- agreement +Agreement == + \A p, q \in Corr: + \/ decision[p] = NilValue + \/ decision[q] = NilValue + \/ decision[p] = decision[q] + +\* the protocol validity +Validity == + \A p \in Corr: decision[p] \in ValidValues \union {NilValue} + +(* + The protocol safety. Two cases are possible: + 1. There is no fork, that is, Agreement holds true. + 2. A subset of faulty processes demonstrates equivocation or amnesia. + *) +Accountability == + \/ Agreement + \/ \E Detectable \in SUBSET Faulty: + /\ Cardinality(Detectable) >= THRESHOLD1 + /\ \A p \in Detectable: + EquivocationBy(p) \/ AmnesiaBy(p) + +(****************** FALSE INVARIANTS TO PRODUCE EXAMPLES ***********************) + +\* This property is violated. You can check it to see how amnesic behavior +\* appears in the evidence variable. +NoAmnesia == + \A p \in Faulty: ~AmnesiaBy(p) + +\* This property is violated. You can check it to see an example of equivocation. +NoEquivocation == + \A p \in Faulty: ~EquivocationBy(p) + +\* This property is violated. You can check it to see an example of agreement. +\* It is not exactly ~Agreement, as we do not want to see the states where +\* decision[p] = NilValue +NoAgreement == + \A p, q \in Corr: + (p /= q /\ decision[p] /= NilValue /\ decision[q] /= NilValue) + => decision[p] /= decision[q] + +\* Either agreement holds, or the faulty processes indeed demonstrate amnesia. +\* This property is violated. A counterexample should demonstrate equivocation. +AgreementOrAmnesia == + Agreement \/ (\A p \in Faulty: AmnesiaBy(p)) + +\* We expect this property to be violated. It shows us a protocol run, +\* where one faulty process demonstrates amnesia without equivocation. +\* However, the absence of amnesia +\* is a tough constraint for Apalache. It has not reported a counterexample +\* for n=4,f=2, length <= 5. +ShowMeAmnesiaWithoutEquivocation == + (~Agreement /\ \E p \in Faulty: ~EquivocationBy(p)) + => \A p \in Faulty: ~AmnesiaBy(p) + +\* This property is violated on n=4,f=2, length=4 in less than 10 min. +\* Two faulty processes may demonstrate amnesia without equivocation. +AmnesiaImpliesEquivocation == + (\E p \in Faulty: AmnesiaBy(p)) => (\E q \in Faulty: EquivocationBy(q)) + +(* + This property is violated. You can check it to see that all correct processes + may reach MaxRound without making a decision. + *) +NeverUndecidedInMaxRound == + LET AllInMax == \A p \in Corr: round[p] = MaxRound + AllDecided == \A p \in Corr: decision[p] /= NilValue + IN + AllInMax => AllDecided + +============================================================================= + diff --git a/spec/light-client/accountability/results/001indinv-apalache-mem-log.svg b/spec/light-client/accountability/results/001indinv-apalache-mem-log.svg new file mode 100644 index 0000000..8400a31 --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-mem-log.svg @@ -0,0 +1,1063 @@ + + + + + + + + + 2020-12-11T20:07:39.617177 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-mem.svg b/spec/light-client/accountability/results/001indinv-apalache-mem.svg new file mode 100644 index 0000000..e9d14b4 --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-mem.svg @@ -0,0 +1,1141 @@ + + + + + + + + + 2020-12-11T20:07:40.321995 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-ncells.svg b/spec/light-client/accountability/results/001indinv-apalache-ncells.svg new file mode 100644 index 0000000..1a8cc6b --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-ncells.svg @@ -0,0 +1,1015 @@ + + + + + + + + + 2020-12-11T20:07:40.804886 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-nclauses.svg b/spec/light-client/accountability/results/001indinv-apalache-nclauses.svg new file mode 100644 index 0000000..a6be111 --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-nclauses.svg @@ -0,0 +1,1133 @@ + + + + + + + + + 2020-12-11T20:07:41.276750 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-report.md b/spec/light-client/accountability/results/001indinv-apalache-report.md new file mode 100644 index 0000000..bacffcc --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-report.md @@ -0,0 +1,61 @@ +# Results of 001indinv-apalache + +## 1. Awesome plots + +### 1.1. Time (logarithmic scale) + +![time-log](001indinv-apalache-time-log.svg "Time Log") + +### 1.2. Time (linear) + +![time-log](001indinv-apalache-time.svg "Time Log") + +### 1.3. Memory (logarithmic scale) + +![mem-log](001indinv-apalache-mem-log.svg "Memory Log") + +### 1.4. Memory (linear) + +![mem](001indinv-apalache-mem.svg "Memory Log") + +### 1.5. Number of arena cells (linear) + +![ncells](001indinv-apalache-ncells.svg "Number of arena cells") + +### 1.6. Number of SMT clauses (linear) + +![nclauses](001indinv-apalache-nclauses.svg "Number of SMT clauses") + +## 2. Input parameters + +no | filename | tool | timeout | init | inv | next | args +----|----------------|------------|-----------|------------|------------------|--------|------------------------------ +1 | MC_n4_f1.tla | apalache | 10h | TypedInv | TypedInv | | --length=1 --cinit=ConstInit +2 | MC_n4_f2.tla | apalache | 10h | TypedInv | TypedInv | | --length=1 --cinit=ConstInit +3 | MC_n5_f1.tla | apalache | 10h | TypedInv | TypedInv | | --length=1 --cinit=ConstInit +4 | MC_n5_f2.tla | apalache | 10h | TypedInv | TypedInv | | --length=1 --cinit=ConstInit +5 | MC_n4_f1.tla | apalache | 20h | Init | TypedInv | | --length=0 --cinit=ConstInit +6 | MC_n4_f2.tla | apalache | 20h | Init | TypedInv | | --length=0 --cinit=ConstInit +7 | MC_n5_f1.tla | apalache | 20h | Init | TypedInv | | --length=0 --cinit=ConstInit +8 | MC_n5_f2.tla | apalache | 20h | Init | TypedInv | | --length=0 --cinit=ConstInit +9 | MC_n4_f1.tla | apalache | 20h | TypedInv | Agreement | | --length=0 --cinit=ConstInit +10 | MC_n4_f2.tla | apalache | 20h | TypedInv | Accountability | | --length=0 --cinit=ConstInit +11 | MC_n5_f1.tla | apalache | 20h | TypedInv | Agreement | | --length=0 --cinit=ConstInit +12 | MC_n5_f2.tla | apalache | 20h | TypedInv | Accountability | | --length=0 --cinit=ConstInit + +## 3. Detailed results: 001indinv-apalache-unstable.csv + +01:no | 02:tool | 03:status | 04:time_sec | 05:depth | 05:mem_kb | 10:ninit_trans | 11:ninit_trans | 12:ncells | 13:nclauses | 14:navg_clause_len +-------|------------|-------------|---------------|------------|-------------|------------------|------------------|-------------|---------------|-------------------- +1 | apalache | NoError | 11m | 1 | 3.0GB | 0 | 0 | 217K | 1.0M | 89 +2 | apalache | NoError | 11m | 1 | 3.0GB | 0 | 0 | 207K | 1.0M | 88 +3 | apalache | NoError | 16m | 1 | 4.0GB | 0 | 0 | 311K | 2.0M | 101 +4 | apalache | NoError | 14m | 1 | 3.0GB | 0 | 0 | 290K | 1.0M | 103 +5 | apalache | NoError | 9s | 0 | 563MB | 0 | 0 | 2.0K | 14K | 42 +6 | apalache | NoError | 10s | 0 | 657MB | 0 | 0 | 2.0K | 28K | 43 +7 | apalache | NoError | 8s | 0 | 635MB | 0 | 0 | 2.0K | 17K | 44 +8 | apalache | NoError | 10s | 0 | 667MB | 0 | 0 | 3.0K | 32K | 45 +9 | apalache | NoError | 5m05s | 0 | 2.0GB | 0 | 0 | 196K | 889K | 108 +10 | apalache | NoError | 8m08s | 0 | 6.0GB | 0 | 0 | 2.0M | 3.0M | 34 +11 | apalache | NoError | 9m09s | 0 | 3.0GB | 0 | 0 | 284K | 1.0M | 128 +12 | apalache | NoError | 14m | 0 | 7.0GB | 0 | 0 | 4.0M | 5.0M | 38 diff --git a/spec/light-client/accountability/results/001indinv-apalache-time-log.svg b/spec/light-client/accountability/results/001indinv-apalache-time-log.svg new file mode 100644 index 0000000..a2badf1 --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-time-log.svg @@ -0,0 +1,1134 @@ + + + + + + + + + 2020-12-11T20:07:38.347583 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-time.svg b/spec/light-client/accountability/results/001indinv-apalache-time.svg new file mode 100644 index 0000000..b539702 --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-time.svg @@ -0,0 +1,957 @@ + + + + + + + + + 2020-12-11T20:07:39.136767 + image/svg+xml + + + Matplotlib v3.3.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spec/light-client/accountability/results/001indinv-apalache-unstable.csv b/spec/light-client/accountability/results/001indinv-apalache-unstable.csv new file mode 100644 index 0000000..353711b --- /dev/null +++ b/spec/light-client/accountability/results/001indinv-apalache-unstable.csv @@ -0,0 +1,13 @@ +01:no,02:tool,03:status,04:time_sec,05:depth,05:mem_kb,10:ninit_trans,11:ninit_trans,12:ncells,13:nclauses,14:navg_clause_len +1,apalache,NoError,704,1,3215424,0,0,217385,1305718,89 +2,apalache,NoError,699,1,3195020,0,0,207969,1341979,88 +3,apalache,NoError,1018,1,4277060,0,0,311798,2028544,101 +4,apalache,NoError,889,1,4080012,0,0,290989,1951616,103 +5,apalache,NoError,9,0,577100,0,0,2045,14655,42 +6,apalache,NoError,10,0,673772,0,0,2913,28213,43 +7,apalache,NoError,8,0,651008,0,0,2214,17077,44 +8,apalache,NoError,10,0,683188,0,0,3082,32651,45 +9,apalache,NoError,340,0,3053848,0,0,196943,889859,108 +10,apalache,NoError,517,0,6424536,0,0,2856378,3802779,34 +11,apalache,NoError,587,0,4028516,0,0,284369,1343296,128 +12,apalache,NoError,880,0,7881148,0,0,4382556,5778072,38 diff --git a/spec/light-client/accountability/run.sh b/spec/light-client/accountability/run.sh new file mode 100755 index 0000000..8a23f7c --- /dev/null +++ b/spec/light-client/accountability/run.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# +# The script to run all experiments at once + +export SCRIPTS_DIR=~/devl/apalache-tests/scripts +export BUILDS="unstable" +export BENCHMARK=001indinv-apalache +export RUN_SCRIPT=./run-all.sh # alternatively, use ./run-parallel.sh +make -e -f ~/devl/apalache-tests/Makefile.common diff --git a/spec/light-client/accountability/typedefs.tla b/spec/light-client/accountability/typedefs.tla new file mode 100644 index 0000000..9f3c0f3 --- /dev/null +++ b/spec/light-client/accountability/typedefs.tla @@ -0,0 +1,27 @@ +-------------------- MODULE typedefs --------------------------- +(* + @typeAlias: process = Str; + @typeAlias: value = Str; + @typeAlias: step = Str; + @typeAlias: round = Int; + @typeAlias: action = Str; + @typeAlias: trace = Seq(Str); + @typeAlias: proposeMsg = + { + type: $step, + src: $process, + round: $round, + proposal: $value, + validRound: $round + }; + @typeAlias: preMsg = + { + type: $step, + src: $process, + round: $round, + id: $value + }; +*) +TypeAliases == TRUE + +============================================================================= diff --git a/spec/light-client/assets/light-node-image.png b/spec/light-client/assets/light-node-image.png new file mode 100644 index 0000000..c3202e5 Binary files /dev/null and b/spec/light-client/assets/light-node-image.png differ diff --git a/spec/light-client/attacks/Blockchain_003_draft.tla b/spec/light-client/attacks/Blockchain_003_draft.tla new file mode 100644 index 0000000..292d67c --- /dev/null +++ b/spec/light-client/attacks/Blockchain_003_draft.tla @@ -0,0 +1,166 @@ +------------------------ MODULE Blockchain_003_draft ----------------------------- +(* + This is a high-level specification of a Cosmos blockchain + that is designed specifically for the light client. + Validators have the voting power of one. If you like to model various + voting powers, introduce multiple copies of the same validator + (do not forget to give them unique names though). + *) +EXTENDS Integers, FiniteSets, Apalache + +Min(a, b) == IF a < b THEN a ELSE b + +CONSTANT + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + ULTIMATE_HEIGHT, + (* a maximal height that can be ever reached (modelling artifact) *) + TRUSTING_PERIOD + (* the period within which the validators are trusted *) + +Heights == 1..ULTIMATE_HEIGHT (* possible heights *) + +(* A commit is just a set of nodes who have committed the block *) +Commits == SUBSET AllNodes + +(* The set of all block headers that can be on the blockchain. + This is a simplified version of the Block data structure in the actual implementation. *) +BlockHeaders == [ + height: Heights, + \* the block height + time: Int, + \* the block timestamp in some integer units + lastCommit: Commits, + \* the nodes who have voted on the previous block, the set itself instead of a hash + (* in the implementation, only the hashes of V and NextV are stored in a block, + as V and NextV are stored in the application state *) + VS: SUBSET AllNodes, + \* the validators of this bloc. We store the validators instead of the hash. + NextVS: SUBSET AllNodes + \* the validators of the next block. We store the next validators instead of the hash. +] + +(* A signed header is just a header together with a set of commits *) +LightBlocks == [header: BlockHeaders, Commits: Commits] + +VARIABLES + refClock, + (* the current global time in integer units as perceived by the reference chain *) + blockchain, + (* A sequence of BlockHeaders, which gives us a bird view of the blockchain. *) + Faulty + (* A set of faulty nodes, which can act as validators. We assume that the set + of faulty processes is non-decreasing. If a process has recovered, it should + connect using a different id. *) + +(* all variables, to be used with UNCHANGED *) +vars == <> + +(* The set of all correct nodes in a state *) +Corr == AllNodes \ Faulty + +(* APALACHE annotations *) +a <: b == a \* type annotation + +NT == STRING +NodeSet(S) == S <: {NT} +EmptyNodeSet == NodeSet({}) + +BT == [height |-> Int, time |-> Int, lastCommit |-> {NT}, VS |-> {NT}, NextVS |-> {NT}] + +LBT == [header |-> BT, Commits |-> {NT}] +(* end of APALACHE annotations *) + +(****************************** BLOCKCHAIN ************************************) + +(* the header is still within the trusting period *) +InTrustingPeriod(header) == + refClock < header.time + TRUSTING_PERIOD + +(* + Given a function pVotingPower \in D -> Powers for some D \subseteq AllNodes + and pNodes \subseteq D, test whether the set pNodes \subseteq AllNodes has + more than 2/3 of voting power among the nodes in D. + *) +TwoThirds(pVS, pNodes) == + LET TP == Cardinality(pVS) + SP == Cardinality(pVS \intersect pNodes) + IN + 3 * SP > 2 * TP \* when thinking in real numbers, not integers: SP > 2.0 / 3.0 * TP + +(* + Given a set of FaultyNodes, test whether the voting power of the correct nodes in D + is more than 2/3 of the voting power of the faulty nodes in D. + + Parameters: + - pFaultyNodes is a set of nodes that are considered faulty + - pVS is a set of all validators, maybe including Faulty, intersecting with it, etc. + - pMaxFaultRatio is a pair <> that limits the ratio a / b of the faulty + validators from above (exclusive) + *) +FaultyValidatorsFewerThan(pFaultyNodes, pVS, maxRatio) == + LET FN == pFaultyNodes \intersect pVS \* faulty nodes in pNodes + CN == pVS \ pFaultyNodes \* correct nodes in pNodes + CP == Cardinality(CN) \* power of the correct nodes + FP == Cardinality(FN) \* power of the faulty nodes + IN + \* CP + FP = TP is the total voting power + LET TP == CP + FP IN + FP * maxRatio[2] < TP * maxRatio[1] + +(* Can a block be produced by a correct peer, or an authenticated Byzantine peer *) +IsLightBlockAllowedByDigitalSignatures(ht, block) == + \/ block.header = blockchain[ht] \* signed by correct and faulty (maybe) + \/ /\ block.Commits \subseteq Faulty + /\ block.header.height = ht + /\ block.header.time >= 0 \* signed only by faulty + +(* + Initialize the blockchain to the ultimate height right in the initial states. + We pick the faulty validators statically, but that should not affect the light client. + + Parameters: + - pMaxFaultyRatioExclusive is a pair <> that bound the number of + faulty validators in each block by the ratio a / b (exclusive) + *) +InitToHeight(pMaxFaultyRatioExclusive) == + /\ \E Nodes \in SUBSET AllNodes: + Faulty := Nodes \* pick a subset of nodes to be faulty + \* pick the validator sets and last commits + /\ \E vs, lastCommit \in [Heights -> SUBSET AllNodes]: + \E timestamp \in [Heights -> Int]: + \* refClock is at least as early as the timestamp in the last block + /\ \E tm \in Int: + refClock := tm /\ tm >= timestamp[ULTIMATE_HEIGHT] + \* the genesis starts on day 1 + /\ timestamp[1] = 1 + /\ vs[1] = AllNodes + /\ lastCommit[1] = EmptyNodeSet + /\ \A h \in Heights \ {1}: + /\ lastCommit[h] \subseteq vs[h - 1] \* the non-validators cannot commit + /\ TwoThirds(vs[h - 1], lastCommit[h]) \* the commit has >2/3 of validator votes + \* the faulty validators have the power below the threshold + /\ FaultyValidatorsFewerThan(Faulty, vs[h], pMaxFaultyRatioExclusive) + /\ timestamp[h] > timestamp[h - 1] \* the time grows monotonically + /\ timestamp[h] < timestamp[h - 1] + TRUSTING_PERIOD \* but not too fast + \* form the block chain out of validator sets and commits (this makes apalache faster) + /\ blockchain := [h \in Heights |-> + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> IF h < ULTIMATE_HEIGHT THEN vs[h + 1] ELSE AllNodes, + lastCommit |-> lastCommit[h]] + ] \****** + +(********************* BLOCKCHAIN ACTIONS ********************************) +(* + Advance the clock by zero or more time units. + *) +AdvanceTime == + /\ \E tm \in Int: tm >= refClock /\ refClock' = tm + /\ UNCHANGED <> + +============================================================================= +\* Modification History +\* Last modified Wed Jun 10 14:10:54 CEST 2020 by igor +\* Created Fri Oct 11 15:45:11 CEST 2019 by igor diff --git a/spec/light-client/attacks/Isolation_001_draft.tla b/spec/light-client/attacks/Isolation_001_draft.tla new file mode 100644 index 0000000..1d3d968 --- /dev/null +++ b/spec/light-client/attacks/Isolation_001_draft.tla @@ -0,0 +1,159 @@ +----------------------- MODULE Isolation_001_draft ---------------------------- +(** + * The specification of the attackers isolation at full node, + * when it has received an evidence from the light client. + * We check that the isolation spec produces a set of validators + * that have more than 1/3 of the voting power. + * + * It follows the English specification: + * + * https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/attacks/isolate-attackers_001_draft.md + * + * The assumptions made in this specification: + * + * - the voting power of every validator is 1 + * (add more validators, if you need more validators) + * + * - Cosmos security model is violated + * (there are Byzantine validators who signed a conflicting block) + * + * Igor Konnov, Zarko Milosevic, Josef Widder, Informal Systems, 2020 + *) + + +EXTENDS Integers, FiniteSets, Apalache + +\* algorithm parameters +CONSTANTS + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + COMMON_HEIGHT, + (* an index of the block header that two peers agree upon *) + CONFLICT_HEIGHT, + (* an index of the block header that two peers disagree upon *) + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + FAULTY_RATIO + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + +VARIABLES + blockchain, (* the chain at the full node *) + refClock, (* the reference clock at the full node *) + Faulty, (* the set of faulty validators *) + conflictingBlock, (* an evidence that two peers reported conflicting blocks *) + state, (* the state of the attack isolation machine at the full node *) + attackers (* the set of the identified attackers *) + +vars == <> + +\* instantiate the chain at the full node +ULTIMATE_HEIGHT == CONFLICT_HEIGHT + 1 +BC == INSTANCE Blockchain_003_draft + +\* use the light client API +TRUSTING_HEIGHT == COMMON_HEIGHT +TARGET_HEIGHT == CONFLICT_HEIGHT + +LC == INSTANCE LCVerificationApi_003_draft + WITH localClock <- refClock, REAL_CLOCK_DRIFT <- 0, CLOCK_DRIFT <- 0 + +\* old-style type annotations in apalache +a <: b == a + +\* [LCAI-NONVALID-OUTPUT.1::TLA.1] +ViolatesValidity(header1, header2) == + \/ header1.VS /= header2.VS + \/ header1.NextVS /= header2.NextVS + \/ header1.height /= header2.height + \/ header1.time /= header2.time + (* The English specification also checks the fields that we do not have + at this level of abstraction: + - header1.ConsensusHash != header2.ConsensusHash or + - header1.AppHash != header2.AppHash or + - header1.LastResultsHash header2 != ev.LastResultsHash + *) + +Init == + /\ state := "init" + \* Pick an arbitrary blockchain from 1 to COMMON_HEIGHT + 1. + /\ BC!InitToHeight(FAULTY_RATIO) \* initializes blockchain, Faulty, and refClock + /\ attackers := {} <: {STRING} \* attackers are unknown + \* Receive an arbitrary evidence. + \* Instantiate the light block fields one by one, + \* to avoid combinatorial explosion of records. + /\ \E time \in Int: + \E VS, NextVS, lastCommit, Commits \in SUBSET AllNodes: + LET conflicting == + [ Commits |-> Commits, + header |-> + [height |-> CONFLICT_HEIGHT, + time |-> time, + VS |-> VS, + NextVS |-> NextVS, + lastCommit |-> lastCommit] ] + IN + LET refBlock == [ header |-> blockchain[COMMON_HEIGHT], + Commits |-> blockchain[COMMON_HEIGHT + 1].lastCommit ] + IN + /\ "SUCCESS" = LC!ValidAndVerifiedUntimed(refBlock, conflicting) + \* More than third of next validators in the common reference block + \* is faulty. That is a precondition for a fork. + /\ 3 * Cardinality(Faulty \intersect refBlock.header.NextVS) + > Cardinality(refBlock.header.NextVS) + \* correct validators cannot sign an invalid block + /\ ViolatesValidity(conflicting.header, refBlock.header) + => conflicting.Commits \subseteq Faulty + /\ conflictingBlock := conflicting + + +\* This is a specification of isolateMisbehavingProcesses. +\* +\* [LCAI-FUNC-MAIN.1::TLA.1] +Next == + /\ state = "init" + \* Extract the rounds from the reference block and the conflicting block. + \* In this specification, we just pick rounds non-deterministically. + \* The English specification calls RoundOf on the blocks. + /\ \E referenceRound, evidenceRound \in Int: + /\ referenceRound >= 0 /\ evidenceRound >= 0 + /\ LET reference == blockchain[CONFLICT_HEIGHT] + referenceCommit == blockchain[CONFLICT_HEIGHT + 1].lastCommit + evidenceHeader == conflictingBlock.header + evidenceCommit == conflictingBlock.Commits + IN + IF ViolatesValidity(reference, evidenceHeader) + THEN /\ attackers' := blockchain[COMMON_HEIGHT].NextVS \intersect evidenceCommit + /\ state' := "Lunatic" + ELSE IF referenceRound = evidenceRound + THEN /\ attackers' := referenceCommit \intersect evidenceCommit + /\ state' := "Equivocation" + ELSE + \* This property is shown in property + \* Accountability of TendermintAcc3.tla + /\ state' := "Amnesia" + /\ \E Attackers \in SUBSET (Faulty \intersect reference.VS): + /\ 3 * Cardinality(Attackers) > Cardinality(reference.VS) + /\ attackers' := Attackers + /\ blockchain' := blockchain + /\ refClock' := refClock + /\ Faulty' := Faulty + /\ conflictingBlock' := conflictingBlock + +(********************************** INVARIANTS *******************************) + +\* This invariant ensure that the attackers have +\* more than 1/3 of the voting power +\* +\* [LCAI-INV-Output.1::TLA-DETECTION-COMPLETENESS.1] +DetectionCompleteness == + state /= "init" => + 3 * Cardinality(attackers) > Cardinality(blockchain[CONFLICT_HEIGHT].VS) + +\* This invariant ensures that only the faulty validators are detected +\* +\* [LCAI-INV-Output.1::TLA-DETECTION-ACCURACY.1] +DetectionAccuracy == + attackers \subseteq Faulty + +============================================================================== diff --git a/spec/light-client/attacks/LCVerificationApi_003_draft.tla b/spec/light-client/attacks/LCVerificationApi_003_draft.tla new file mode 100644 index 0000000..b995073 --- /dev/null +++ b/spec/light-client/attacks/LCVerificationApi_003_draft.tla @@ -0,0 +1,192 @@ +-------------------- MODULE LCVerificationApi_003_draft -------------------------- +(** + * The common interface of the light client verification and detection. + *) +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + CLOCK_DRIFT, + (* the assumed precision of the clock *) + REAL_CLOCK_DRIFT, + (* the actual clock drift, which under normal circumstances should not + be larger than CLOCK_DRIFT (otherwise, there will be a bug) *) + FAULTY_RATIO + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + +VARIABLES + localClock (* current time as measured by the light client *) + +(* the header is still within the trusting period *) +InTrustingPeriodLocal(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - CLOCK_DRIFT + +(* the header is still within the trusting period, even if the clock can go backwards *) +InTrustingPeriodLocalSurely(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - 2 * CLOCK_DRIFT + +(* ensure that the local clock does not drift far away from the global clock *) +IsLocalClockWithinDrift(local, global) == + /\ global - REAL_CLOCK_DRIFT <= local + /\ local <= global + REAL_CLOCK_DRIFT + +(** + * Check that the commits in an untrusted block form 1/3 of the next validators + * in a trusted header. + *) +SignedByOneThirdOfTrusted(trusted, untrusted) == + LET TP == Cardinality(trusted.header.NextVS) + SP == Cardinality(untrusted.Commits \intersect trusted.header.NextVS) + IN + 3 * SP > TP + +(** + The first part of the precondition of ValidAndVerified, which does not take + the current time into account. + + [LCV-FUNC-VALID.1::TLA-PRE-UNTIMED.1] + *) +ValidAndVerifiedPreUntimed(trusted, untrusted) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ thdr.height < uhdr.height + \* the trusted block has been created earlier + /\ thdr.time < uhdr.time + /\ untrusted.Commits \subseteq uhdr.VS + /\ LET TP == Cardinality(uhdr.VS) + SP == Cardinality(untrusted.Commits) + IN + 3 * SP > 2 * TP + /\ thdr.height + 1 = uhdr.height => thdr.NextVS = uhdr.VS + (* As we do not have explicit hashes we ignore these three checks of the English spec: + + 1. "trusted.Commit is a commit is for the header trusted.Header, + i.e. it contains the correct hash of the header". + 2. untrusted.Validators = hash(untrusted.Header.Validators) + 3. untrusted.NextValidators = hash(untrusted.Header.NextValidators) + *) + +(** + Check the precondition of ValidAndVerified, including the time checks. + + [LCV-FUNC-VALID.1::TLA-PRE.1] + *) +ValidAndVerifiedPre(trusted, untrusted, checkFuture) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ InTrustingPeriodLocal(thdr) + \* The untrusted block is not from the future (modulo clock drift). + \* Do the check, if it is required. + /\ checkFuture => uhdr.time < localClock + CLOCK_DRIFT + /\ ValidAndVerifiedPreUntimed(trusted, untrusted) + + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + This test does take current time into account, but only looks at the block structure. + + [LCV-FUNC-VALID.1::TLA-UNTIMED.1] + *) +ValidAndVerifiedUntimed(trusted, untrusted) == + IF ~ValidAndVerifiedPreUntimed(trusted, untrusted) + THEN "INVALID" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + + [LCV-FUNC-VALID.1::TLA.1] + *) +ValidAndVerified(trusted, untrusted, checkFuture) == + IF ~ValidAndVerifiedPre(trusted, untrusted, checkFuture) + THEN "INVALID" + ELSE IF ~InTrustingPeriodLocal(untrusted.header) + (* We leave the following test for the documentation purposes. + The implementation should do this test, as signature verification may be slow. + In the TLA+ specification, ValidAndVerified happens in no time. + *) + THEN "FAILED_TRUSTING_PERIOD" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + + +(** + The invariant of the light store that is not related to the blockchain + *) +LightStoreInv(fetchedLightBlocks, lightBlockStatus) == + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] /= "StateVerified" + \/ lightBlockStatus[rh] /= "StateVerified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ LET lhdr == fetchedLightBlocks[lh] + rhdr == fetchedLightBlocks[rh] + IN + \* we can verify the right one using the left one + "SUCCESS" = ValidAndVerifiedUntimed(lhdr, rhdr) + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + * When the light client terminates, there are no failed blocks. + * (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +(** + The expected post-condition of VerifyToTarget. + *) +VerifyToTargetPost(blockchain, isPeerCorrect, + fetchedLightBlocks, lightBlockStatus, + trustedHeight, targetHeight, finalState) == + LET trustedHeader == fetchedLightBlocks[trustedHeight].header IN + \* The light client is not lying us on the trusted block. + \* It is straightforward to detect. + /\ lightBlockStatus[trustedHeight] = "StateVerified" + /\ trustedHeight \in DOMAIN fetchedLightBlocks + /\ trustedHeader = blockchain[trustedHeight] + \* the invariants we have found in the light client verification + \* there is a problem with trusting period + /\ isPeerCorrect + => CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) + \* a correct peer should fail the light client, + \* if the trusted block is in the trusting period + /\ isPeerCorrect /\ InTrustingPeriodLocalSurely(trustedHeader) + => finalState = "finishedSuccess" + /\ finalState = "finishedSuccess" => + /\ lightBlockStatus[targetHeight] = "StateVerified" + /\ targetHeight \in DOMAIN fetchedLightBlocks + /\ NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) + /\ LightStoreInv(fetchedLightBlocks, lightBlockStatus) + + +================================================================================== diff --git a/spec/light-client/attacks/MC_5_3.tla b/spec/light-client/attacks/MC_5_3.tla new file mode 100644 index 0000000..7af9b05 --- /dev/null +++ b/spec/light-client/attacks/MC_5_3.tla @@ -0,0 +1,18 @@ +------------------------- MODULE MC_5_3 ------------------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +COMMON_HEIGHT == 1 +CONFLICT_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +FAULTY_RATIO == <<1, 2>> \* < 1 / 2 faulty validators + +VARIABLES + blockchain, \* the reference blockchain + refClock, \* current time in the reference blockchain + Faulty, \* the set of faulty validators + state, \* the state of the light client detector + conflictingBlock, \* an evidence that two peers reported conflicting blocks + attackers + +INSTANCE Isolation_001_draft +============================================================================ diff --git a/spec/light-client/attacks/isolate-attackers_001_draft.md b/spec/light-client/attacks/isolate-attackers_001_draft.md new file mode 100644 index 0000000..0b8f6c5 --- /dev/null +++ b/spec/light-client/attacks/isolate-attackers_001_draft.md @@ -0,0 +1,223 @@ + +# Lightclient Attackers Isolation + +> Warning: This is the beginning of an unfinished draft. Don't continue reading! + +Adversarial nodes may have the incentive to lie to a lightclient about the +state of a Cosmos blockchain, built using Tendermint consensus algorithm. +An attempt to do so is called attack. Light client [verification][verification] checks incoming data by checking a so-called "commit", which is a forwarded set of signed messages that is (supposedly) produced during executing Tendermint consensus. Thus, an attack boils down to creating and signing Tendermint consensus messages in deviation from the Tendermint consensus algorithm rules. + +As Tendermint consensus and light client verification is safe under the assumption of more than 2/3 of correct voting power per block [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link], this implies that if there was an attack then [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link] was violated, that is, there is a block such that + +- validators deviated from the protocol, and +- these validators represent more than 1/3 of the voting power in that block. + +In the case of an [attack][node-based-attack-characterization], the lightclient [attack detection mechanism][detection] computes data, so called evidence [[LC-DATA-EVIDENCE.1]][LC-DATA-EVIDENCE-link], that can be used + +- to proof that there has been attack [[CMBC-LC-EVIDENCE-DATA.1]][CMBC-LC-EVIDENCE-DATA-link] and +- as basis to find the actual nodes that deviated from the Tendermint algorithm. + +This specification considers how a full node in a Cosmos blockchain can isolate a set of attackers that launched the attack. The set should satisfy + +- the set does not contain a correct validator +- the set contains validators that represent more than 1/3 of the voting power of a block that is still within the unbonding period + +# Outline + +**TODO** when preparing a version for broader review. + +# Part I - Basics + +For definitions of data structures used here, in particular LightBlocks [[LCV-DATA-LIGHTBLOCK.1]](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-data-lightblock1), cf. [Light Client Verification][verification]. + +# Part II - Definition of the Problem + +The specification of the [detection mechanism][detection] describes + +- what is a light client attack, +- conditions under which the detector will detect a light client attack, +- and the format of the output data, called evidence, in the case an attack is detected. The format is defined in +[[LC-DATA-EVIDENCE.1]][LC-DATA-EVIDENCE-link] and looks as follows + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 +} +``` + +The isolator is a function that gets as input evidence `ev` +and a prefix of the blockchain `bc` at least up to height `ev.ConflictingBlock.Header.Height + 1`. The output is a set of *peerIDs* of validators. + +We assume that the full node is synchronized with the blockchain and has reached the height `ev.ConflictingBlock.Header.Height + 1`. + +#### **[FN-INV-Output.1]** + +When an output is generated it satisfies the following properties: + +- If + - `bc[CommonHeight].bfttime` is within the unbonding period w.r.t. the time at the full node, + - `ev.ConflictingBlock.Header != bc[ev.ConflictingBlock.Header.Height]` + - Validators in `ev.ConflictingBlock.Commit` represent more than 1/3 of the voting power in `bc[ev.CommonHeight].NextValidators` +- Then: A set of validators in `bc[CommonHeight].NextValidators` that + - represent more than 1/3 of the voting power in `bc[ev.commonHeight].NextValidators` + - signed Tendermint consensus messages for height `ev.ConflictingBlock.Header.Height` by violating the Tendermint consensus algorithm. +- Else: the empty set. + +# Part IV - Protocol + +Here we discuss how to solve the problem of isolating misbehaving processes. We describe the function `isolateMisbehavingProcesses` as well as all the helping functions below. In [Part V](#part-v---Completeness), we discuss why the solution is complete based on result from analysis with automated tools. + +## Isolation + +### Outline + +> Describe solution (in English), decomposition into functions, where communication to other components happens. + +#### **[LCAI-FUNC-MAIN.1]** + +```go +func isolateMisbehavingProcesses(ev LightClientAttackEvidence, bc Blockchain) []ValidatorAddress { + + reference := bc[ev.conflictingBlock.Header.Height].Header + ev_header := ev.conflictingBlock.Header + + ref_commit := bc[ev.conflictingBlock.Header.Height + 1].Header.LastCommit // + 1 !! + ev_commit := ev.conflictingBlock.Commit + + if violatesTMValidity(reference, ev_header) { + // lunatic light client attack + signatories := Signers(ev.ConflictingBlock.Commit) + bonded_vals := Addresses(bc[ev.CommonHeight].NextValidators) + return intersection(signatories,bonded_vals) + + } + // If this point is reached the validator sets in reference and ev_header are identical + else if RoundOf(ref_commit) == RoundOf(ev_commit) { + // equivocation light client attack + return intersection(Signers(ref_commit), Signers(ev_commit)) + } + else { + // amnesia light client attack + return IsolateAmnesiaAttacker(ev, bc) + } +} +``` + +- Implementation comment + - If the full node has only reached height `ev.conflictingBlock.Header.Height` then `bc[ev.conflictingBlock.Header.Height + 1].Header.LastCommit` refers to the locally stored commit for this height. (This commit must be present by the precondition on `length(bc)`.) + - We check in the precondition that the unbonding period is not expired. However, since time moves on, before handing the validators over Cosmos SDK, the time needs to be checked again to satisfy the contract which requires that only bonded validators are reported. This passing of validators to the SDK is out of scope of this specification. +- Expected precondition + - `length(bc) >= ev.conflictingBlock.Header.Height` + - `ValidAndVerifiedUnbonding(bc[ev.CommonHeight], ev.ConflictingBlock) == SUCCESS` + - `ev.ConflictingBlock.Header != bc[ev.ConflictingBlock.Header.Height]` + - TODO: input light blocks pass basic validation +- Expected postcondition + - [[FN-INV-Output.1]](#FN-INV-Output1) holds +- Error condition + - returns an error if precondition is violated. + +### Details of the Functions + +#### **[LCAI-FUNC-VVU.1]** + +```go +func ValidAndVerifiedUnbonding(trusted LightBlock, untrusted LightBlock) Result +``` + +- Conditions are identical to [[LCV-FUNC-VALID.2]][LCV-FUNC-VALID.link] except the precondition "*trusted.Header.Time > now - trustingPeriod*" is substituted with + - `trusted.Header.Time > now - UnbondingPeriod` + +#### **[LCAI-FUNC-NONVALID.1]** + +```go +func violatesTMValidity(ref Header, ev Header) boolean +``` + +- Implementation remarks + - checks whether the evidence header `ev` violates the validity property of Tendermint consensus algorithm, by checking agains a reference header +- Expected precondition + - `ref.Height == ev.Height` +- Expected postcondition + - returns evaluation of the following disjunction + **[[LCAI-NONVALID-OUTPUT.1]]** == + `ref.ValidatorsHash != ev.ValidatorsHash` or + `ref.NextValidatorsHash != ev.NextValidatorsHash` or + `ref.ConsensusHash != ev.ConsensusHash` or + `ref.AppHash != ev.AppHash` or + `ref.LastResultsHash != ev.LastResultsHash` + +```go +func IsolateAmnesiaAttacker(ev LightClientAttackEvidence, bc Blockchain) []ValidatorAddress +``` + +- Implementation remarks + **TODO:** What should we do here? Refer to the accountability doc? +- Expected postcondition + **TODO:** What should we do here? Refer to the accountability doc? + +```go +func RoundOf(commit Commit) []ValidatorAddress +``` + +- Expected precondition + - `commit` is well-formed. In particular all votes are from the same round `r`. +- Expected postcondition + - returns round `r` that is encoded in all the votes of the commit + +```go +func Signers(commit Commit) []ValidatorAddress +``` + +- Expected postcondition + - returns all validator addresses in `commit` + +```go +func Addresses(vals Validator[]) ValidatorAddress[] +``` + +- Expected postcondition + - returns all validator addresses in `vals` + +# Part V - Completeness + +As discussed in the beginning of this document, an attack boils down to creating and signing Tendermint consensus messages in deviation from the Tendermint consensus algorithm rules. +The main function `isolateMisbehavingProcesses` distinguishes three kinds of wrongly signing messages, namely, + +- lunatic: signing invalid blocks +- equivocation: double-signing valid blocks in the same consensus round +- amnesia: signing conflicting blocks in different consensus rounds, without having seen a quorum of messages that would have allowed to do so. + +The question is whether this captures all attacks. +First observe that the first checking in `isolateMisbehavingProcesses` is `violatesTMValidity`. It takes care of lunatic attacks. If this check passes, that is, if `violatesTMValidity` returns `FALSE` this means that [FN-NONVALID-OUTPUT] evaluates to false, which implies that `ref.ValidatorsHash = ev.ValidatorsHash`. Hence after `violatesTMValidity`, all the involved validators are the ones from the blockchain. It is thus sufficient to analyze one instance of Tendermint consensus with a fixed group membership (set of validators). Also it is sufficient to consider two different valid consensus values, that is, binary consensus. + +**TODO** we have analyzed Tendermint consensus algorithm with TLA+ and have accompanied Galois in an independent study of the protocol based on [Ivy proofs](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/ivy-proofs). + +# References + +[[supervisor]] The specification of the light client supervisor. + +[[verification]] The specification of the light client verification protocol + +[[detection]] The specification of the light client attack detection mechanism. + +[supervisor]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/supervisor/supervisor_001_draft.md + +[verification]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md + +[detection]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md + +[LC-DATA-EVIDENCE-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#lc-data-evidence1 + +[CMBC-LC-EVIDENCE-DATA-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#cmbc-lc-evidence-data1 + +[node-based-attack-characterization]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#block-based-characterization-of-attacks + +[CMBC-FM-2THIRDS-link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-fm-2thirds1 + +[LCV-FUNC-VALID.link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-func-valid2 diff --git a/spec/light-client/attacks/isolate-attackers_002_reviewed.md b/spec/light-client/attacks/isolate-attackers_002_reviewed.md new file mode 100644 index 0000000..7c8ab88 --- /dev/null +++ b/spec/light-client/attacks/isolate-attackers_002_reviewed.md @@ -0,0 +1,225 @@ + +# Lightclient Attackers Isolation + +Adversarial nodes may have the incentive to lie to a lightclient about the +state of a Cosmos blockchain, built using Tendermint consensus algorithm. +An attempt to do so is called attack. Light client [verification][verification] checks incoming data by checking a so-called "commit", which is a forwarded set of signed messages that is (supposedly) produced during executing Tendermint consensus. Thus, an attack boils down to creating and signing Tendermint consensus messages in deviation from the Tendermint consensus algorithm rules. + +As Tendermint consensus and light client verification is safe under the assumption of more than 2/3 of correct voting power per block [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link], this implies that if there was an attack then [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link] was violated, that is, there is a block such that + +- validators deviated from the protocol, and +- these validators represent more than 1/3 of the voting power in that block. + +In the case of an [attack][node-based-attack-characterization], the lightclient [attack detection mechanism][detection] computes data, so called evidence [[LC-DATA-EVIDENCE.1]][LC-DATA-EVIDENCE-link], that can be used + +- to proof that there has been attack [[CMBC-LC-EVIDENCE-DATA.1]][CMBC-LC-EVIDENCE-DATA-link] and +- as basis to find the actual nodes that deviated from the Tendermint algorithm. + +This specification considers how a full node in a Cosmos blockchain can isolate a set of attackers that launched the attack. The set should satisfy + +- the set does not contain a correct validator +- the set contains validators that represent more than 1/3 of the voting power of a block that is still within the unbonding period + +# Outline + +After providing the [problem statement](#Part-I---Basics-and-Definition-of-the-Problem), we specify the [isolator function](#Part-II---Protocol) and close with the discussion about its [correctness](#Part-III---Completeness) which is based on computer-aided analysis of Tendermint consensus algorithm. + +# Part I - Basics and Definition of the Problem + +For definitions of data structures used here, in particular LightBlocks [[LCV-DATA-LIGHTBLOCK.1]](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-data-lightblock1), we refer to the specification of [Light Client Verification][verification]. + +The specification of the [detection mechanism][detection] describes + +- what is a light client attack, +- conditions under which the detector will detect a light client attack, +- and the format of the output data, called evidence, in the case an attack is detected. The format is defined in +[[LC-DATA-EVIDENCE.1]][LC-DATA-EVIDENCE-link] and looks as follows + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 +} +``` + +The isolator is a function that gets as input evidence `ev` +and a prefix of the blockchain `bc` at least up to height `ev.ConflictingBlock.Header.Height + 1`. The output is a set of *peerIDs* of validators. + +We assume that the full node is synchronized with the blockchain and has reached the height `ev.ConflictingBlock.Header.Height + 1`. + +#### **[LCAI-INV-Output.1]** + +When an output is generated it satisfies the following properties: + +- If + - `bc[CommonHeight].bfttime` is within the unbonding period w.r.t. the time at the full node, + - `ev.ConflictingBlock.Header != bc[ev.ConflictingBlock.Header.Height]` + - Validators in `ev.ConflictingBlock.Commit` represent more than 1/3 of the voting power in `bc[ev.CommonHeight].NextValidators` +- Then: The output is a set of validators in `bc[CommonHeight].NextValidators` that + - represent more than 1/3 of the voting power in `bc[ev.commonHeight].NextValidators` + - signed Tendermint consensus messages for height `ev.ConflictingBlock.Header.Height` by violating the Tendermint consensus algorithm. +- Else: the empty set. + +# Part II - Protocol + +Here we discuss how to solve the problem of isolating misbehaving processes. We describe the function `isolateMisbehavingProcesses` as well as all the helping functions below. In [Part III](#part-III---Completeness), we discuss why the solution is complete based on result from analysis with automated tools. + +## Isolation + +### Outline + +We first check whether the conflicting block can indeed be verified from the common height. We then first check whether it was a lunatic attack (violating validity). If this is not the case, we check for equivocation. If this also is not the case, we start the on-chain [accountability protocol](https://docs.google.com/document/d/11ZhMsCj3y7zIZz4udO9l25xqb0kl7gmWqNpGVRzOeyY/edit). + +#### **[LCAI-FUNC-MAIN.1]** + +```go +func isolateMisbehavingProcesses(ev LightClientAttackEvidence, bc Blockchain) []ValidatorAddress { + + reference := bc[ev.conflictingBlock.Header.Height].Header + ev_header := ev.conflictingBlock.Header + + ref_commit := bc[ev.conflictingBlock.Header.Height + 1].Header.LastCommit // + 1 !! + ev_commit := ev.conflictingBlock.Commit + + if violatesTMValidity(reference, ev_header) { + // lunatic light client attack + signatories := Signers(ev.ConflictingBlock.Commit) + bonded_vals := Addresses(bc[ev.CommonHeight].NextValidators) + return intersection(signatories,bonded_vals) + + } + // If this point is reached the validator sets in reference and ev_header are identical + else if RoundOf(ref_commit) == RoundOf(ev_commit) { + // equivocation light client attack + return intersection(Signers(ref_commit), Signers(ev_commit)) + } + else { + // amnesia light client attack + return IsolateAmnesiaAttacker(ev, bc) + } +} +``` + +- Implementation comment + - If the full node has only reached height `ev.conflictingBlock.Header.Height` then `bc[ev.conflictingBlock.Header.Height + 1].Header.LastCommit` refers to the locally stored commit for this height. (This commit must be present by the precondition on `length(bc)`.) + - We check in the precondition that the unbonding period is not expired. However, since time moves on, before handing the validators over Cosmos SDK, the time needs to be checked again to satisfy the contract which requires that only bonded validators are reported. This passing of validators to the SDK is out of scope of this specification. +- Expected precondition + - `length(bc) >= ev.conflictingBlock.Header.Height` + - `ValidAndVerifiedUnbonding(bc[ev.CommonHeight], ev.ConflictingBlock) == SUCCESS` + - `ev.ConflictingBlock.Header != bc[ev.ConflictingBlock.Header.Height]` + - `ev.conflictingBlock` satisfies basic validation (in particular all signed messages in the Commit are from the same round) +- Expected postcondition + - [[FN-INV-Output.1]](#FN-INV-Output1) holds +- Error condition + - returns an error if precondition is violated. + +### Details of the Functions + +#### **[LCAI-FUNC-VVU.1]** + +```go +func ValidAndVerifiedUnbonding(trusted LightBlock, untrusted LightBlock) Result +``` + +- Conditions are identical to [[LCV-FUNC-VALID.2]][LCV-FUNC-VALID.link] except the precondition "*trusted.Header.Time > now - trustingPeriod*" is substituted with + - `trusted.Header.Time > now - UnbondingPeriod` + +#### **[LCAI-FUNC-NONVALID.1]** + +```go +func violatesTMValidity(ref Header, ev Header) boolean +``` + +- Implementation remarks + - checks whether the evidence header `ev` violates the validity property of Tendermint consensus algorithm, by checking against a reference header +- Expected precondition + - `ref.Height == ev.Height` +- Expected postcondition + - returns evaluation of the following disjunction + **[LCAI-NONVALID-OUTPUT.1]** == + `ref.ValidatorsHash != ev.ValidatorsHash` or + `ref.NextValidatorsHash != ev.NextValidatorsHash` or + `ref.ConsensusHash != ev.ConsensusHash` or + `ref.AppHash != ev.AppHash` or + `ref.LastResultsHash != ev.LastResultsHash` + +```go +func IsolateAmnesiaAttacker(ev LightClientAttackEvidence, bc Blockchain) []ValidatorAddress +``` + +- Implementation remarks + - This triggers the [query/response protocol](https://docs.google.com/document/d/11ZhMsCj3y7zIZz4udO9l25xqb0kl7gmWqNpGVRzOeyY/edit). +- Expected postcondition + - returns attackers according to [LCAI-INV-Output.1]. + +```go +func RoundOf(commit Commit) []ValidatorAddress +``` + +- Expected precondition + - `commit` is well-formed. In particular all votes are from the same round `r`. +- Expected postcondition + - returns round `r` that is encoded in all the votes of the commit +- Error condition + - reports error if precondition is violated + +```go +func Signers(commit Commit) []ValidatorAddress +``` + +- Expected postcondition + - returns all validator addresses in `commit` + +```go +func Addresses(vals Validator[]) ValidatorAddress[] +``` + +- Expected postcondition + - returns all validator addresses in `vals` + +# Part III - Completeness + +As discussed in the beginning of this document, an attack boils down to creating and signing Tendermint consensus messages in deviation from the Tendermint consensus algorithm rules. +The main function `isolateMisbehavingProcesses` distinguishes three kinds of wrongly signed messages, namely, + +- lunatic: signing invalid blocks +- equivocation: double-signing valid blocks in the same consensus round +- amnesia: signing conflicting blocks in different consensus rounds, without having seen a quorum of messages that would have allowed to do so. + +The question is whether this captures all attacks. +First observe that the first check in `isolateMisbehavingProcesses` is `violatesTMValidity`. It takes care of lunatic attacks. If this check passes, that is, if `violatesTMValidity` returns `FALSE` this means that [[LCAI-NONVALID-OUTPUT.1]](#LCAI-FUNC-NONVALID1]) evaluates to false, which implies that `ref.ValidatorsHash = ev.ValidatorsHash`. Hence, after `violatesTMValidity`, all the involved validators are the ones from the blockchain. It is thus sufficient to analyze one instance of Tendermint consensus with a fixed group membership (set of validators). Also, as we have two different blocks for the same height, it is sufficient to consider two different valid consensus values, that is, binary consensus. + +For this fixed group membership, we have analyzed the attacks using the TLA+ specification of [Tendermint Consensus in TLA+][tendermint-accountability]. We checked that indeed the only possible scenarios that can lead to violation of agreement are **equivocation** and **amnesia**. An independent study by Galois of the protocol based on [Ivy proofs](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/ivy-proofs) led to the same conclusion. + +# References + +[[supervisor]] The specification of the light client supervisor. + +[[verification]] The specification of the light client verification protocol. + +[[detection]] The specification of the light client attack detection mechanism. + + +[tendermint-accountability]: +https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/accountability + +[supervisor]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/supervisor/supervisor_001_draft.md + +[verification]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md + +[detection]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md + +[LC-DATA-EVIDENCE-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#lc-data-evidence1 + +[CMBC-LC-EVIDENCE-DATA-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#cmbc-lc-evidence-data1 + +[node-based-attack-characterization]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#block-based-characterization-of-attacks + +[CMBC-FM-2THIRDS-link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-fm-2thirds1 + +[LCV-FUNC-VALID.link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-func-valid2 diff --git a/spec/light-client/attacks/notes-on-evidence-handling.md b/spec/light-client/attacks/notes-on-evidence-handling.md new file mode 100644 index 0000000..f5ff149 --- /dev/null +++ b/spec/light-client/attacks/notes-on-evidence-handling.md @@ -0,0 +1,219 @@ + +# Light client attacks + +We define a light client attack as detection of conflicting headers for a given height that can be verified +starting from the trusted light block. A light client attack is defined in the context of interactions of +light client with two peers. One of the peers (called primary) defines a trace of verified light blocks +(primary trace) that are being checked against trace of the other peer (called witness) that we call +witness trace. + +A light client attack is defined by the primary and witness traces +that have a common root (the same trusted light block for a common height) but forms +conflicting branches (end of traces is for the same height but with different headers). +Note that conflicting branches could be arbitrarily big as branches continue to diverge after +a bifurcation point. We propose an approach that allows us to define a valid light client attack +only with a common light block and a single conflicting light block. We rely on the fact that +we assume that the primary is under suspicion (therefore not trusted) and that the witness plays +support role to detect and process an attack (therefore trusted). Therefore, once a light client +detects an attack, it needs to send to a witness only missing data (common height +and conflicting light block) as it has its trace. Keeping light client attack data of constant size +saves bandwidth and reduces an attack surface. As we will explain below, although in the context of +light client core +[verification](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/verification) +the roles of primary and witness are clearly defined, +in case of the attack, we run the same attack detection procedure twice where the roles are swapped. +The rationale is that the light client does not know what peer is correct (on a right main branch) +so it tries to create and submit an attack evidence to both peers. + +Light client attack evidence consists of a conflicting light block and a common height. + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 +} +``` + +Full node can validate a light client attack evidence by executing the following procedure: + +```go +func IsValid(lcaEvidence LightClientAttackEvidence, bc Blockchain) boolean { + commonBlock = GetLightBlock(bc, lcaEvidence.CommonHeight) + if commonBlock == nil return false + + // Note that trustingPeriod in ValidAndVerified is set to UNBONDING_PERIOD + verdict = ValidAndVerified(commonBlock, lcaEvidence.ConflictingBlock) + conflictingHeight = lcaEvidence.ConflictingBlock.Header.Height + + return verdict == OK and bc[conflictingHeight].Header != lcaEvidence.ConflictingBlock.Header +} +``` + +## Light client attack creation + +Given a trusted light block `trusted`, a light node executes the bisection algorithm to verify header +`untrusted` at some height `h`. If the bisection algorithm succeeds, then the header `untrusted` is verified. +Headers that are downloaded as part of the bisection algorithm are stored in a store and they are also in +the verified state. Therefore, after the bisection algorithm successfully terminates we have a trace of +the light blocks ([] LightBlock) we obtained from the primary that we call primary trace. + +### Primary trace + +The following invariant holds for the primary trace: + +- Given a `trusted` light block, target height `h`, and `primary_trace` ([] LightBlock): + *primary_trace[0] == trusted* and *primary_trace[len(primary_trace)-1].Height == h* and + successive light blocks are passing light client verification logic. + +### Witness with a conflicting header + +The verified header at height `h` is cross-checked with every witness as part of +[detection](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/detection). +If a witness returns the conflicting header at the height `h` the following procedure is executed to verify +if the conflicting header comes from the valid trace and if that's the case to create an attack evidence: + +#### Helper functions + +We assume the following helper functions: + +```go +// Returns trace of verified light blocks starting from rootHeight and ending with targetHeight. +Trace(lightStore LightStore, rootHeight int64, targetHeight int64) LightBlock[] + +// Returns validator set for the given height +GetValidators(bc Blockchain, height int64) Validator[] + +// Returns validator set for the given height +GetValidators(bc Blockchain, height int64) Validator[] + +// Return validator addresses for the given validators +GetAddresses(vals Validator[]) ValidatorAddress[] +``` + +```go +func DetectLightClientAttacks(primary PeerID, + primary_trace []LightBlock, + witness PeerID) (LightClientAttackEvidence, LightClientAttackEvidence) { + primary_lca_evidence, witness_trace = DetectLightClientAttack(primary_trace, witness) + + witness_lca_evidence = nil + if witness_trace != nil { + witness_lca_evidence, _ = DetectLightClientAttack(witness_trace, primary) + } + return primary_lca_evidence, witness_lca_evidence +} + +func DetectLightClientAttack(trace []LightBlock, peer PeerID) (LightClientAttackEvidence, []LightBlock) { + + lightStore = new LightStore().Update(trace[0], StateTrusted) + + for i in 1..len(trace)-1 { + lightStore, result = VerifyToTarget(peer, lightStore, trace[i].Header.Height) + + if result == ResultFailure then return (nil, nil) + + current = lightStore.Get(trace[i].Header.Height) + + // if obtained header is the same as in the trace we continue with a next height + if current.Header == trace[i].Header continue + + // we have identified a conflicting header + commonBlock = trace[i-1] + conflictingBlock = trace[i] + + return (LightClientAttackEvidence { conflictingBlock, commonBlock.Header.Height }, + Trace(lightStore, trace[i-1].Header.Height, trace[i].Header.Height)) + } + return (nil, nil) +} +``` + +## Evidence handling + +As part of on chain evidence handling, full nodes identifies misbehaving processes and informs +the application, so they can be slashed. Note that only bonded validators should +be reported to the application. There are three types of attacks that can be executed against +light client: + +- lunatic attack +- equivocation attack and +- amnesia attack. + +We now specify the evidence handling logic. + +```go +func detectMisbehavingProcesses(lcAttackEvidence LightClientAttackEvidence, bc Blockchain) []ValidatorAddress { + assume IsValid(lcaEvidence, bc) + + // lunatic light client attack + if !isValidBlock(current.Header, conflictingBlock.Header) { + conflictingCommit = lcAttackEvidence.ConflictingBlock.Commit + bondedValidators = GetNextValidators(bc, lcAttackEvidence.CommonHeight) + + return getSigners(conflictingCommit) intersection GetAddresses(bondedValidators) + + // equivocation light client attack + } else if current.Header.Round == conflictingBlock.Header.Round { + conflictingCommit = lcAttackEvidence.ConflictingBlock.Commit + trustedCommit = bc[conflictingBlock.Header.Height+1].LastCommit + + return getSigners(trustedCommit) intersection getSigners(conflictingCommit) + + // amnesia light client attack + } else { + HandleAmnesiaAttackEvidence(lcAttackEvidence, bc) + } +} + +// Block validity in this context is defined by the trusted header. +func isValidBlock(trusted Header, conflicting Header) boolean { + return trusted.ValidatorsHash == conflicting.ValidatorsHash and + trusted.NextValidatorsHash == conflicting.NextValidatorsHash and + trusted.ConsensusHash == conflicting.ConsensusHash and + trusted.AppHash == conflicting.AppHash and + trusted.LastResultsHash == conflicting.LastResultsHash +} + +func getSigners(commit Commit) []ValidatorAddress { + signers = []ValidatorAddress + for (i, commitSig) in commit.Signatures { + if commitSig.BlockIDFlag == BlockIDFlagCommit { + signers.append(commitSig.ValidatorAddress) + } + } + return signers +} +``` + +Note that amnesia attack evidence handling involves more complex processing, i.e., cannot be +defined simply on amnesia attack evidence. We explain in the following section a protocol +for handling amnesia attack evidence. + +### Amnesia attack evidence handling + +Detecting faulty processes in case of the amnesia attack is more complex and cannot be inferred +purely based on attack evidence data. In this case, in order to detect misbehaving processes we need +access to votes processes sent/received during the conflicting height. Therefore, amnesia handling assumes that +validators persist all votes received and sent during multi-round heights (as amnesia attack +is only possible in heights that executes over multiple rounds, i.e., commit round > 0). + +To simplify description of the algorithm we assume existence of the trusted oracle called monitor that will +drive the algorithm and output faulty processes at the end. Monitor can be implemented in a +distributed setting as on-chain module. The algorithm works as follows: + 1) Monitor sends votesets request to validators of the conflicting height. Validators + are expected to send their votesets within predefined timeout. + 2) Upon receiving votesets request, validators send their votesets to a monitor. + 2) Validators which have not sent its votesets within timeout are considered faulty. + 3) The preprocessing of the votesets is done. That means that the received votesets are analyzed + and each vote (valid) sent by process p is added to the voteset of the sender p. This phase ensures that + votes sent by faulty processes observed by at least one correct validator cannot be excluded from the analysis. + 4) Votesets of every validator are analyzed independently to decide whether the validator is correct or faulty. + A faulty validators is the one where at least one of those invalid transitions is found: + - More than one PREVOTE message is sent in a round + - More than one PRECOMMIT message is sent in a round + - PRECOMMIT message is sent without receiving +2/3 of voting-power equivalent + appropriate PREVOTE messages + - PREVOTE message is sent for the value V’ in round r’ and the PRECOMMIT message had + been sent for the value V in round r by the same process (r’ > r) and there are no + +2/3 of voting-power equivalent PREVOTE(vr, V’) messages (vr ≥ 0 and vr > r and vr < r’) + as the justification for sending PREVOTE(r’, V’) diff --git a/spec/light-client/detection/004bmc-apalache-ok.csv b/spec/light-client/detection/004bmc-apalache-ok.csv new file mode 100644 index 0000000..ad526fa --- /dev/null +++ b/spec/light-client/detection/004bmc-apalache-ok.csv @@ -0,0 +1,10 @@ +no;filename;tool;timeout;init;inv;next;args +1;LCD_MC3_3_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +2;LCD_MC3_3_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +3;LCD_MC3_3_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 +4;LCD_MC3_4_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +5;LCD_MC3_4_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +6;LCD_MC3_4_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 +7;LCD_MC4_4_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +8;LCD_MC4_4_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +9;LCD_MC4_4_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 diff --git a/spec/light-client/detection/005bmc-apalache-error.csv b/spec/light-client/detection/005bmc-apalache-error.csv new file mode 100644 index 0000000..65d03f8 --- /dev/null +++ b/spec/light-client/detection/005bmc-apalache-error.csv @@ -0,0 +1,4 @@ +no;filename;tool;timeout;init;inv;next;args +1;LCD_MC3_3_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 +2;LCD_MC3_4_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 +3;LCD_MC4_4_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 diff --git a/spec/light-client/detection/Blockchain_003_draft.tla b/spec/light-client/detection/Blockchain_003_draft.tla new file mode 100644 index 0000000..d5d3c56 --- /dev/null +++ b/spec/light-client/detection/Blockchain_003_draft.tla @@ -0,0 +1,164 @@ +------------------------ MODULE Blockchain_003_draft ----------------------------- +(* + This is a high-level specification of a Cosmos blockchain + that is designed specifically for the light client. + Validators have the voting power of one. If you like to model various + voting powers, introduce multiple copies of the same validator + (do not forget to give them unique names though). + *) +EXTENDS Integers, FiniteSets + +Min(a, b) == IF a < b THEN a ELSE b + +CONSTANT + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + ULTIMATE_HEIGHT, + (* a maximal height that can be ever reached (modelling artifact) *) + TRUSTING_PERIOD + (* the period within which the validators are trusted *) + +Heights == 1..ULTIMATE_HEIGHT (* possible heights *) + +(* A commit is just a set of nodes who have committed the block *) +Commits == SUBSET AllNodes + +(* The set of all block headers that can be on the blockchain. + This is a simplified version of the Block data structure in the actual implementation. *) +BlockHeaders == [ + height: Heights, + \* the block height + time: Int, + \* the block timestamp in some integer units + lastCommit: Commits, + \* the nodes who have voted on the previous block, the set itself instead of a hash + (* in the implementation, only the hashes of V and NextV are stored in a block, + as V and NextV are stored in the application state *) + VS: SUBSET AllNodes, + \* the validators of this bloc. We store the validators instead of the hash. + NextVS: SUBSET AllNodes + \* the validators of the next block. We store the next validators instead of the hash. +] + +(* A signed header is just a header together with a set of commits *) +LightBlocks == [header: BlockHeaders, Commits: Commits] + +VARIABLES + refClock, + (* the current global time in integer units as perceived by the reference chain *) + blockchain, + (* A sequence of BlockHeaders, which gives us a bird view of the blockchain. *) + Faulty + (* A set of faulty nodes, which can act as validators. We assume that the set + of faulty processes is non-decreasing. If a process has recovered, it should + connect using a different id. *) + +(* all variables, to be used with UNCHANGED *) +vars == <> + +(* The set of all correct nodes in a state *) +Corr == AllNodes \ Faulty + +(* APALACHE annotations *) +a <: b == a \* type annotation + +NT == STRING +NodeSet(S) == S <: {NT} +EmptyNodeSet == NodeSet({}) + +BT == [height |-> Int, time |-> Int, lastCommit |-> {NT}, VS |-> {NT}, NextVS |-> {NT}] + +LBT == [header |-> BT, Commits |-> {NT}] +(* end of APALACHE annotations *) + +(****************************** BLOCKCHAIN ************************************) + +(* the header is still within the trusting period *) +InTrustingPeriod(header) == + refClock < header.time + TRUSTING_PERIOD + +(* + Given a function pVotingPower \in D -> Powers for some D \subseteq AllNodes + and pNodes \subseteq D, test whether the set pNodes \subseteq AllNodes has + more than 2/3 of voting power among the nodes in D. + *) +TwoThirds(pVS, pNodes) == + LET TP == Cardinality(pVS) + SP == Cardinality(pVS \intersect pNodes) + IN + 3 * SP > 2 * TP \* when thinking in real numbers, not integers: SP > 2.0 / 3.0 * TP + +(* + Given a set of FaultyNodes, test whether the voting power of the correct nodes in D + is more than 2/3 of the voting power of the faulty nodes in D. + + Parameters: + - pFaultyNodes is a set of nodes that are considered faulty + - pVS is a set of all validators, maybe including Faulty, intersecting with it, etc. + - pMaxFaultRatio is a pair <> that limits the ratio a / b of the faulty + validators from above (exclusive) + *) +FaultyValidatorsFewerThan(pFaultyNodes, pVS, maxRatio) == + LET FN == pFaultyNodes \intersect pVS \* faulty nodes in pNodes + CN == pVS \ pFaultyNodes \* correct nodes in pNodes + CP == Cardinality(CN) \* power of the correct nodes + FP == Cardinality(FN) \* power of the faulty nodes + IN + \* CP + FP = TP is the total voting power + LET TP == CP + FP IN + FP * maxRatio[2] < TP * maxRatio[1] + +(* Can a block be produced by a correct peer, or an authenticated Byzantine peer *) +IsLightBlockAllowedByDigitalSignatures(ht, block) == + \/ block.header = blockchain[ht] \* signed by correct and faulty (maybe) + \/ /\ block.Commits \subseteq Faulty + /\ block.header.height = ht + /\ block.header.time >= 0 \* signed only by faulty + +(* + Initialize the blockchain to the ultimate height right in the initial states. + We pick the faulty validators statically, but that should not affect the light client. + + Parameters: + - pMaxFaultyRatioExclusive is a pair <> that bound the number of + faulty validators in each block by the ratio a / b (exclusive) + *) +InitToHeight(pMaxFaultyRatioExclusive) == + /\ Faulty \in SUBSET AllNodes \* some nodes may fail + \* pick the validator sets and last commits + /\ \E vs, lastCommit \in [Heights -> SUBSET AllNodes]: + \E timestamp \in [Heights -> Int]: + \* refClock is at least as early as the timestamp in the last block + /\ \E tm \in Int: refClock = tm /\ tm >= timestamp[ULTIMATE_HEIGHT] + \* the genesis starts on day 1 + /\ timestamp[1] = 1 + /\ vs[1] = AllNodes + /\ lastCommit[1] = EmptyNodeSet + /\ \A h \in Heights \ {1}: + /\ lastCommit[h] \subseteq vs[h - 1] \* the non-validators cannot commit + /\ TwoThirds(vs[h - 1], lastCommit[h]) \* the commit has >2/3 of validator votes + \* the faulty validators have the power below the threshold + /\ FaultyValidatorsFewerThan(Faulty, vs[h], pMaxFaultyRatioExclusive) + /\ timestamp[h] > timestamp[h - 1] \* the time grows monotonically + /\ timestamp[h] < timestamp[h - 1] + TRUSTING_PERIOD \* but not too fast + \* form the block chain out of validator sets and commits (this makes apalache faster) + /\ blockchain = [h \in Heights |-> + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> IF h < ULTIMATE_HEIGHT THEN vs[h + 1] ELSE AllNodes, + lastCommit |-> lastCommit[h]] + ] \****** + +(********************* BLOCKCHAIN ACTIONS ********************************) +(* + Advance the clock by zero or more time units. + *) +AdvanceTime == + /\ \E tm \in Int: tm >= refClock /\ refClock' = tm + /\ UNCHANGED <> + +============================================================================= +\* Modification History +\* Last modified Wed Jun 10 14:10:54 CEST 2020 by igor +\* Created Fri Oct 11 15:45:11 CEST 2019 by igor diff --git a/spec/light-client/detection/LCD_MC3_3_faulty.tla b/spec/light-client/detection/LCD_MC3_3_faulty.tla new file mode 100644 index 0000000..486f326 --- /dev/null +++ b/spec/light-client/detection/LCD_MC3_3_faulty.tla @@ -0,0 +1,27 @@ +------------------------- MODULE LCD_MC3_3_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +IS_SECONDARY_CORRECT == TRUE +FAULTY_RATIO == <<2, 3>> \* < 1 / 3 faulty validators + +VARIABLES + blockchain, (* the reference blockchain *) + localClock, (* current time in the light client *) + refClock, (* current time in the reference blockchain *) + Faulty, (* the set of faulty validators *) + state, (* the state of the light client detector *) + fetchedLightBlocks1, (* a function from heights to LightBlocks *) + fetchedLightBlocks2, (* a function from heights to LightBlocks *) + fetchedLightBlocks1b, (* a function from heights to LightBlocks *) + commonHeight, (* the height that is trusted in CreateEvidenceForPeer *) + nextHeightToTry, (* the index in CreateEvidenceForPeer *) + evidences + +INSTANCE LCDetector_003_draft +============================================================================ diff --git a/spec/light-client/detection/LCD_MC3_4_faulty.tla b/spec/light-client/detection/LCD_MC3_4_faulty.tla new file mode 100644 index 0000000..1320ba8 --- /dev/null +++ b/spec/light-client/detection/LCD_MC3_4_faulty.tla @@ -0,0 +1,27 @@ +------------------------- MODULE LCD_MC3_4_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +IS_SECONDARY_CORRECT == TRUE +FAULTY_RATIO == <<2, 3>> \* < 1 / 3 faulty validators + +VARIABLES + blockchain, (* the reference blockchain *) + localClock, (* current time in the light client *) + refClock, (* current time in the reference blockchain *) + Faulty, (* the set of faulty validators *) + state, (* the state of the light client detector *) + fetchedLightBlocks1, (* a function from heights to LightBlocks *) + fetchedLightBlocks2, (* a function from heights to LightBlocks *) + fetchedLightBlocks1b, (* a function from heights to LightBlocks *) + commonHeight, (* the height that is trusted in CreateEvidenceForPeer *) + nextHeightToTry, (* the index in CreateEvidenceForPeer *) + evidences + +INSTANCE LCDetector_003_draft +============================================================================ diff --git a/spec/light-client/detection/LCD_MC4_4_faulty.tla b/spec/light-client/detection/LCD_MC4_4_faulty.tla new file mode 100644 index 0000000..8cbc08e --- /dev/null +++ b/spec/light-client/detection/LCD_MC4_4_faulty.tla @@ -0,0 +1,27 @@ +------------------------- MODULE LCD_MC4_4_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +IS_SECONDARY_CORRECT == TRUE +FAULTY_RATIO == <<2, 3>> \* < 2 / 3 faulty validators + +VARIABLES + blockchain, (* the reference blockchain *) + localClock, (* current time in the light client *) + refClock, (* current time in the reference blockchain *) + Faulty, (* the set of faulty validators *) + state, (* the state of the light client detector *) + fetchedLightBlocks1, (* a function from heights to LightBlocks *) + fetchedLightBlocks2, (* a function from heights to LightBlocks *) + fetchedLightBlocks1b, (* a function from heights to LightBlocks *) + commonHeight, (* the height that is trusted in CreateEvidenceForPeer *) + nextHeightToTry, (* the index in CreateEvidenceForPeer *) + evidences + +INSTANCE LCDetector_003_draft +============================================================================ diff --git a/spec/light-client/detection/LCD_MC5_5_faulty.tla b/spec/light-client/detection/LCD_MC5_5_faulty.tla new file mode 100644 index 0000000..630ba68 --- /dev/null +++ b/spec/light-client/detection/LCD_MC5_5_faulty.tla @@ -0,0 +1,27 @@ +------------------------- MODULE LCD_MC5_5_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +IS_SECONDARY_CORRECT == TRUE +FAULTY_RATIO == <<2, 3>> \* < 1 / 3 faulty validators + +VARIABLES + blockchain, (* the reference blockchain *) + localClock, (* current time in the light client *) + refClock, (* current time in the reference blockchain *) + Faulty, (* the set of faulty validators *) + state, (* the state of the light client detector *) + fetchedLightBlocks1, (* a function from heights to LightBlocks *) + fetchedLightBlocks2, (* a function from heights to LightBlocks *) + fetchedLightBlocks1b, (* a function from heights to LightBlocks *) + commonHeight, (* the height that is trusted in CreateEvidenceForPeer *) + nextHeightToTry, (* the index in CreateEvidenceForPeer *) + evidences + +INSTANCE LCDetector_003_draft +============================================================================ diff --git a/spec/light-client/detection/LCDetector_003_draft.tla b/spec/light-client/detection/LCDetector_003_draft.tla new file mode 100644 index 0000000..de37a65 --- /dev/null +++ b/spec/light-client/detection/LCDetector_003_draft.tla @@ -0,0 +1,373 @@ +-------------------------- MODULE LCDetector_003_draft ----------------------------- +(** + * This is a specification of the light client detector module. + * It follows the English specification: + * + * https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md + * + * The assumptions made in this specification: + * + * - light client connects to one primary and one secondary peer + * + * - the light client has its own local clock that can drift from the reference clock + * within the envelope [refClock - CLOCK_DRIFT, refClock + CLOCK_DRIFT]. + * The local clock may increase as well as decrease in the the envelope + * (similar to clock synchronization). + * + * - the ratio of the faulty validators is set as the parameter. + * + * Igor Konnov, Josef Widder, 2020 + *) + +EXTENDS Integers + +\* the parameters of Light Client +CONSTANTS + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + TRUSTED_HEIGHT, + (* an index of the block header that the light client trusts by social consensus *) + TARGET_HEIGHT, + (* an index of the block header that the light client tries to verify *) + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + CLOCK_DRIFT, + (* the assumed precision of the clock *) + REAL_CLOCK_DRIFT, + (* the actual clock drift, which under normal circumstances should not + be larger than CLOCK_DRIFT (otherwise, there will be a bug) *) + FAULTY_RATIO, + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + IS_PRIMARY_CORRECT, + IS_SECONDARY_CORRECT + +VARIABLES + blockchain, (* the reference blockchain *) + localClock, (* the local clock of the light client *) + refClock, (* the reference clock in the reference blockchain *) + Faulty, (* the set of faulty validators *) + state, (* the state of the light client detector *) + fetchedLightBlocks1, (* a function from heights to LightBlocks *) + fetchedLightBlocks2, (* a function from heights to LightBlocks *) + fetchedLightBlocks1b, (* a function from heights to LightBlocks *) + commonHeight, (* the height that is trusted in CreateEvidenceForPeer *) + nextHeightToTry, (* the index in CreateEvidenceForPeer *) + evidences (* a set of evidences *) + +vars == <> + +\* (old) type annotations in Apalache +a <: b == a + + +\* instantiate a reference chain +ULTIMATE_HEIGHT == TARGET_HEIGHT + 1 +BC == INSTANCE Blockchain_003_draft + WITH ULTIMATE_HEIGHT <- (TARGET_HEIGHT + 1) + +\* use the light client API +LC == INSTANCE LCVerificationApi_003_draft + +\* evidence type +ET == [peer |-> STRING, conflictingBlock |-> BC!LBT, commonHeight |-> Int] + +\* is the algorithm in the terminating state +IsTerminated == + state \in { <<"NoEvidence", "PRIMARY">>, + <<"NoEvidence", "SECONDARY">>, + <<"FaultyPeer", "PRIMARY">>, + <<"FaultyPeer", "SECONDARY">>, + <<"FoundEvidence", "PRIMARY">> } + + +(********************************* Initialization ******************************) + +\* initialization for the light blocks data structure +InitLightBlocks(lb, Heights) == + \* BC!LightBlocks is an infinite set, as time is not restricted. + \* Hence, we initialize the light blocks by picking the sets inside. + \E vs, nextVS, lastCommit, commit \in [Heights -> SUBSET AllNodes]: + \* although [Heights -> Int] is an infinite set, + \* Apalache needs just one instance of this set, so it does not complain. + \E timestamp \in [Heights -> Int]: + LET hdr(h) == + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> nextVS[h], + lastCommit |-> lastCommit[h]] + IN + LET lightHdr(h) == + [header |-> hdr(h), Commits |-> commit[h]] + IN + lb = [ h \in Heights |-> lightHdr(h) ] + +\* initialize the detector algorithm +Init == + \* initialize the blockchain to TARGET_HEIGHT + 1 + /\ BC!InitToHeight(FAULTY_RATIO) + /\ \E tm \in Int: + tm >= 0 /\ LC!IsLocalClockWithinDrift(tm, refClock) /\ localClock = tm + \* start with the secondary looking for evidence + /\ state = <<"Init", "SECONDARY">> /\ commonHeight = 0 /\ nextHeightToTry = 0 + /\ evidences = {} <: {ET} + \* Precompute a possible result of light client verification for the primary. + \* It is the input to the detection algorithm. + /\ \E Heights1 \in SUBSET(TRUSTED_HEIGHT..TARGET_HEIGHT): + /\ TRUSTED_HEIGHT \in Heights1 + /\ TARGET_HEIGHT \in Heights1 + /\ InitLightBlocks(fetchedLightBlocks1, Heights1) + \* As we have a non-deterministic scheduler, for every trace that has + \* an unverified block, there is a filtered trace that only has verified + \* blocks. This is a deep observation. + /\ LET status == [h \in Heights1 |-> "StateVerified"] IN + LC!VerifyToTargetPost(blockchain, IS_PRIMARY_CORRECT, + fetchedLightBlocks1, status, + TRUSTED_HEIGHT, TARGET_HEIGHT, "finishedSuccess") + \* initialize the other data structures to the default values + /\ LET trustedBlock == blockchain[TRUSTED_HEIGHT] + trustedLightBlock == [header |-> trustedBlock, Commits |-> AllNodes] + IN + /\ fetchedLightBlocks2 = [h \in {TRUSTED_HEIGHT} |-> trustedLightBlock] + /\ fetchedLightBlocks1b = [h \in {TRUSTED_HEIGHT} |-> trustedLightBlock] + + +(********************************* Transitions ******************************) + +\* a block should contain a copy of the block from the reference chain, +\* with a matching commit +CopyLightBlockFromChain(block, height) == + LET ref == blockchain[height] + lastCommit == + IF height < ULTIMATE_HEIGHT + THEN blockchain[height + 1].lastCommit + \* for the ultimate block, which we never use, + \* as ULTIMATE_HEIGHT = TARGET_HEIGHT + 1 + ELSE blockchain[height].VS + IN + block = [header |-> ref, Commits |-> lastCommit] + +\* Either the primary is correct and the block comes from the reference chain, +\* or the block is produced by a faulty primary. +\* +\* [LCV-FUNC-FETCH.1::TLA.1] +FetchLightBlockInto(isPeerCorrect, block, height) == + IF isPeerCorrect + THEN CopyLightBlockFromChain(block, height) + ELSE BC!IsLightBlockAllowedByDigitalSignatures(height, block) + + +(** + * Pick the next height, for which there is a block. + *) +PickNextHeight(fetchedBlocks, height) == + LET largerHeights == { h \in DOMAIN fetchedBlocks: h > height } IN + IF largerHeights = ({} <: {Int}) + THEN -1 + ELSE CHOOSE h \in largerHeights: + \A h2 \in largerHeights: h <= h2 + + +(** + * Check, whether the target header matches at the secondary and primary. + *) +CompareLast == + /\ state = <<"Init", "SECONDARY">> + \* fetch a block from the secondary: + \* non-deterministically pick a block that matches the constraints + /\ \E latest \in BC!LightBlocks: + \* for the moment, we ignore the possibility of a timeout when fetching a block + /\ FetchLightBlockInto(IS_SECONDARY_CORRECT, latest, TARGET_HEIGHT) + /\ IF latest.header = fetchedLightBlocks1[TARGET_HEIGHT].header + THEN \* if the headers match, CreateEvidence is not called + /\ state' = <<"NoEvidence", "SECONDARY">> + \* save the retrieved block for further analysis + /\ fetchedLightBlocks2' = + [h \in (DOMAIN fetchedLightBlocks2) \union {TARGET_HEIGHT} |-> + IF h = TARGET_HEIGHT THEN latest ELSE fetchedLightBlocks2[h]] + /\ UNCHANGED <> + ELSE \* prepare the parameters for CreateEvidence + /\ commonHeight' = TRUSTED_HEIGHT + /\ nextHeightToTry' = PickNextHeight(fetchedLightBlocks1, TRUSTED_HEIGHT) + /\ state' = IF nextHeightToTry' >= 0 + THEN <<"CreateEvidence", "SECONDARY">> + ELSE <<"FaultyPeer", "SECONDARY">> + /\ UNCHANGED fetchedLightBlocks2 + + /\ UNCHANGED <> + + +\* the actual loop in CreateEvidence +CreateEvidence(peer, isPeerCorrect, refBlocks, targetBlocks) == + /\ state = <<"CreateEvidence", peer>> + \* precompute a possible result of light client verification for the secondary + \* we have to introduce HeightRange, because Apalache can only handle a..b + \* for constant a and b + /\ LET HeightRange == { h \in TRUSTED_HEIGHT..TARGET_HEIGHT: + commonHeight <= h /\ h <= nextHeightToTry } IN + \E HeightsRange \in SUBSET(HeightRange): + /\ commonHeight \in HeightsRange /\ nextHeightToTry \in HeightsRange + /\ InitLightBlocks(targetBlocks, HeightsRange) + \* As we have a non-deterministic scheduler, for every trace that has + \* an unverified block, there is a filtered trace that only has verified + \* blocks. This is a deep observation. + /\ \E result \in {"finishedSuccess", "finishedFailure"}: + LET targetStatus == [h \in HeightsRange |-> "StateVerified"] IN + \* call VerifyToTarget for (commonHeight, nextHeightToTry). + /\ LC!VerifyToTargetPost(blockchain, isPeerCorrect, + targetBlocks, targetStatus, + commonHeight, nextHeightToTry, result) + \* case 1: the peer has failed (or the trusting period has expired) + /\ \/ /\ result /= "finishedSuccess" + /\ state' = <<"FaultyPeer", peer>> + /\ UNCHANGED <> + \* case 2: success + \/ /\ result = "finishedSuccess" + /\ LET block1 == refBlocks[nextHeightToTry] IN + LET block2 == targetBlocks[nextHeightToTry] IN + IF block1.header /= block2.header + THEN \* the target blocks do not match + /\ state' = <<"FoundEvidence", peer>> + /\ evidences' = evidences \union + {[peer |-> peer, + conflictingBlock |-> block1, + commonHeight |-> commonHeight]} + /\ UNCHANGED <> + ELSE \* the target blocks match + /\ nextHeightToTry' = PickNextHeight(refBlocks, nextHeightToTry) + /\ commonHeight' = nextHeightToTry + /\ state' = IF nextHeightToTry' >= 0 + THEN state + ELSE <<"NoEvidence", peer>> + /\ UNCHANGED evidences + +SwitchToPrimary == + /\ state = <<"FoundEvidence", "SECONDARY">> + /\ nextHeightToTry' = PickNextHeight(fetchedLightBlocks2, commonHeight) + /\ state' = <<"CreateEvidence", "PRIMARY">> + /\ UNCHANGED <> + + +CreateEvidenceForSecondary == + /\ CreateEvidence("SECONDARY", IS_SECONDARY_CORRECT, + fetchedLightBlocks1, fetchedLightBlocks2') + /\ UNCHANGED <> + +CreateEvidenceForPrimary == + /\ CreateEvidence("PRIMARY", IS_PRIMARY_CORRECT, + fetchedLightBlocks2, + fetchedLightBlocks1b') + /\ UNCHANGED <> + +(* + The local and global clocks can be updated. They can also drift from each other. + Note that the local clock can actually go backwards in time. + However, it still stays in the drift envelope + of [refClock - REAL_CLOCK_DRIFT, refClock + REAL_CLOCK_DRIFT]. + *) +AdvanceClocks == + /\ \E tm \in Int: + tm >= refClock /\ refClock' = tm + /\ \E tm \in Int: + /\ tm >= localClock + /\ LC!IsLocalClockWithinDrift(tm, refClock') + /\ localClock' = tm + +(** + Execute AttackDetector for one secondary. + + [LCD-FUNC-DETECTOR.2::LOOP.1] + *) +Next == + /\ AdvanceClocks + /\ \/ CompareLast + \/ CreateEvidenceForSecondary + \/ SwitchToPrimary + \/ CreateEvidenceForPrimary + + +\* simple invariants to see the progress of the detector +NeverNoEvidence == state[1] /= "NoEvidence" +NeverFoundEvidence == state[1] /= "FoundEvidence" +NeverFaultyPeer == state[1] /= "FaultyPeer" +NeverCreateEvidence == state[1] /= "CreateEvidence" + +NeverFoundEvidencePrimary == state /= <<"FoundEvidence", "PRIMARY">> + +NeverReachTargetHeight == nextHeightToTry < TARGET_HEIGHT + +EvidenceWhenFaultyInv == + (state[1] = "FoundEvidence") => (~IS_PRIMARY_CORRECT \/ ~IS_SECONDARY_CORRECT) + +NoEvidenceForCorrectInv == + IS_PRIMARY_CORRECT /\ IS_SECONDARY_CORRECT => evidences = {} <: {ET} + +(** + * If we find an evidence by peer A, peer B has ineded given us a corrupted + * header following the common height. Also, we have a verification trace by peer A. + *) +CommonHeightOnEvidenceInv == + \A e \in evidences: + LET conflicting == e.conflictingBlock IN + LET conflictingHeader == conflicting.header IN + \* the evidence by suspectingPeer can be verified by suspectingPeer in one step + LET SoundEvidence(suspectingPeer, peerBlocks) == + \/ e.peer /= suspectingPeer + \* the conflicting block from another peer verifies against the common height + \/ /\ "SUCCESS" = + LC!ValidAndVerifiedUntimed(peerBlocks[e.commonHeight], conflicting) + \* and the headers of the same height by the two peers do not match + /\ peerBlocks[conflictingHeader.height].header /= conflictingHeader + IN + /\ SoundEvidence("PRIMARY", fetchedLightBlocks1b) + /\ SoundEvidence("SECONDARY", fetchedLightBlocks2) + +(** + * If the light client does not find an evidence, + * then there is no attack on the light client. + *) +AccuracyInv == + (LC!InTrustingPeriodLocal(fetchedLightBlocks1[TARGET_HEIGHT].header) + /\ state = <<"NoEvidence", "SECONDARY">>) + => + (fetchedLightBlocks1[TARGET_HEIGHT].header = blockchain[TARGET_HEIGHT] + /\ fetchedLightBlocks2[TARGET_HEIGHT].header = blockchain[TARGET_HEIGHT]) + +(** + * The primary reports a corrupted block at the target height. If the secondary is + * correct and the algorithm has terminated, we should get the evidence. + * This property is violated due to clock drift. VerifyToTarget may fail with + * the correct secondary within the trusting period (due to clock drift, locally + * we think that we are outside of the trusting period). + *) +PrecisionInvGrayZone == + (/\ fetchedLightBlocks1[TARGET_HEIGHT].header /= blockchain[TARGET_HEIGHT] + /\ BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + /\ IS_SECONDARY_CORRECT + /\ IsTerminated) + => + evidences /= {} <: {ET} + +(** + * The primary reports a corrupted block at the target height. If the secondary is + * correct and the algorithm has terminated, we should get the evidence. + * This invariant does not fail, as we are using the local clock to check the trusting + * period. + *) +PrecisionInvLocal == + (/\ fetchedLightBlocks1[TARGET_HEIGHT].header /= blockchain[TARGET_HEIGHT] + /\ LC!InTrustingPeriodLocalSurely(blockchain[TRUSTED_HEIGHT]) + /\ IS_SECONDARY_CORRECT + /\ IsTerminated) + => + evidences /= {} <: {ET} + +==================================================================================== diff --git a/spec/light-client/detection/LCVerificationApi_003_draft.tla b/spec/light-client/detection/LCVerificationApi_003_draft.tla new file mode 100644 index 0000000..b995073 --- /dev/null +++ b/spec/light-client/detection/LCVerificationApi_003_draft.tla @@ -0,0 +1,192 @@ +-------------------- MODULE LCVerificationApi_003_draft -------------------------- +(** + * The common interface of the light client verification and detection. + *) +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + CLOCK_DRIFT, + (* the assumed precision of the clock *) + REAL_CLOCK_DRIFT, + (* the actual clock drift, which under normal circumstances should not + be larger than CLOCK_DRIFT (otherwise, there will be a bug) *) + FAULTY_RATIO + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + +VARIABLES + localClock (* current time as measured by the light client *) + +(* the header is still within the trusting period *) +InTrustingPeriodLocal(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - CLOCK_DRIFT + +(* the header is still within the trusting period, even if the clock can go backwards *) +InTrustingPeriodLocalSurely(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - 2 * CLOCK_DRIFT + +(* ensure that the local clock does not drift far away from the global clock *) +IsLocalClockWithinDrift(local, global) == + /\ global - REAL_CLOCK_DRIFT <= local + /\ local <= global + REAL_CLOCK_DRIFT + +(** + * Check that the commits in an untrusted block form 1/3 of the next validators + * in a trusted header. + *) +SignedByOneThirdOfTrusted(trusted, untrusted) == + LET TP == Cardinality(trusted.header.NextVS) + SP == Cardinality(untrusted.Commits \intersect trusted.header.NextVS) + IN + 3 * SP > TP + +(** + The first part of the precondition of ValidAndVerified, which does not take + the current time into account. + + [LCV-FUNC-VALID.1::TLA-PRE-UNTIMED.1] + *) +ValidAndVerifiedPreUntimed(trusted, untrusted) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ thdr.height < uhdr.height + \* the trusted block has been created earlier + /\ thdr.time < uhdr.time + /\ untrusted.Commits \subseteq uhdr.VS + /\ LET TP == Cardinality(uhdr.VS) + SP == Cardinality(untrusted.Commits) + IN + 3 * SP > 2 * TP + /\ thdr.height + 1 = uhdr.height => thdr.NextVS = uhdr.VS + (* As we do not have explicit hashes we ignore these three checks of the English spec: + + 1. "trusted.Commit is a commit is for the header trusted.Header, + i.e. it contains the correct hash of the header". + 2. untrusted.Validators = hash(untrusted.Header.Validators) + 3. untrusted.NextValidators = hash(untrusted.Header.NextValidators) + *) + +(** + Check the precondition of ValidAndVerified, including the time checks. + + [LCV-FUNC-VALID.1::TLA-PRE.1] + *) +ValidAndVerifiedPre(trusted, untrusted, checkFuture) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ InTrustingPeriodLocal(thdr) + \* The untrusted block is not from the future (modulo clock drift). + \* Do the check, if it is required. + /\ checkFuture => uhdr.time < localClock + CLOCK_DRIFT + /\ ValidAndVerifiedPreUntimed(trusted, untrusted) + + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + This test does take current time into account, but only looks at the block structure. + + [LCV-FUNC-VALID.1::TLA-UNTIMED.1] + *) +ValidAndVerifiedUntimed(trusted, untrusted) == + IF ~ValidAndVerifiedPreUntimed(trusted, untrusted) + THEN "INVALID" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + + [LCV-FUNC-VALID.1::TLA.1] + *) +ValidAndVerified(trusted, untrusted, checkFuture) == + IF ~ValidAndVerifiedPre(trusted, untrusted, checkFuture) + THEN "INVALID" + ELSE IF ~InTrustingPeriodLocal(untrusted.header) + (* We leave the following test for the documentation purposes. + The implementation should do this test, as signature verification may be slow. + In the TLA+ specification, ValidAndVerified happens in no time. + *) + THEN "FAILED_TRUSTING_PERIOD" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + + +(** + The invariant of the light store that is not related to the blockchain + *) +LightStoreInv(fetchedLightBlocks, lightBlockStatus) == + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] /= "StateVerified" + \/ lightBlockStatus[rh] /= "StateVerified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ LET lhdr == fetchedLightBlocks[lh] + rhdr == fetchedLightBlocks[rh] + IN + \* we can verify the right one using the left one + "SUCCESS" = ValidAndVerifiedUntimed(lhdr, rhdr) + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + * When the light client terminates, there are no failed blocks. + * (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +(** + The expected post-condition of VerifyToTarget. + *) +VerifyToTargetPost(blockchain, isPeerCorrect, + fetchedLightBlocks, lightBlockStatus, + trustedHeight, targetHeight, finalState) == + LET trustedHeader == fetchedLightBlocks[trustedHeight].header IN + \* The light client is not lying us on the trusted block. + \* It is straightforward to detect. + /\ lightBlockStatus[trustedHeight] = "StateVerified" + /\ trustedHeight \in DOMAIN fetchedLightBlocks + /\ trustedHeader = blockchain[trustedHeight] + \* the invariants we have found in the light client verification + \* there is a problem with trusting period + /\ isPeerCorrect + => CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) + \* a correct peer should fail the light client, + \* if the trusted block is in the trusting period + /\ isPeerCorrect /\ InTrustingPeriodLocalSurely(trustedHeader) + => finalState = "finishedSuccess" + /\ finalState = "finishedSuccess" => + /\ lightBlockStatus[targetHeight] = "StateVerified" + /\ targetHeight \in DOMAIN fetchedLightBlocks + /\ NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) + /\ LightStoreInv(fetchedLightBlocks, lightBlockStatus) + + +================================================================================== diff --git a/spec/light-client/detection/README.md b/spec/light-client/detection/README.md new file mode 100644 index 0000000..543177f --- /dev/null +++ b/spec/light-client/detection/README.md @@ -0,0 +1,75 @@ +--- +order: 1 +parent: + title: Fork Detection + order: 2 +--- + +# Cosmos fork detection and IBC fork detection + +## Status + +This is a work in progress. +This directory captures the ongoing work and discussion on fork +detection both in the context of a Cosmos light node and in the +context of IBC. It contains the following files + +### [detection.md](./detection_003_reviewed.md) + +a draft of the light node fork detection including "proof of fork" + definition, that is, the data structure to submit evidence to full + nodes. + +### [discussions.md](./discussions.md) + +A collection of ideas and intuitions from recent discussions + +- the outcome of recent discussion +- a sketch of the light client supervisor to provide the context in + which fork detection happens +- a discussion about lightstore semantics + +### [req-ibc-detection.md](./req-ibc-detection.md) + +- a collection of requirements for fork detection in the IBC + context. In particular it contains a section "Required Changes in + ICS 007" with necessary updates to ICS 007 to support Cosmos + fork detection + +### [draft-functions.md](./draft-functions.md) + +In order to address the collected requirements, we started to sketch +some functions that we will need in the future when we specify in more +detail the + +- fork detections +- proof of fork generation +- proof of fork verification + +on the following components. + +- IBC on-chain components +- Relayer + +### TODOs + +We decided to merge the files while there are still open points to +address to record the current state an move forward. In particular, +the following points need to be addressed: + +- + +- + +- + +- + +Most likely we will write a specification on the light client +supervisor along the outcomes of + +- + +that also addresses initialization + +- diff --git a/spec/light-client/detection/detection_001_reviewed.md b/spec/light-client/detection/detection_001_reviewed.md new file mode 100644 index 0000000..241f2f3 --- /dev/null +++ b/spec/light-client/detection/detection_001_reviewed.md @@ -0,0 +1,785 @@ + +# ***This an unfinished draft. Comments are welcome!*** + +**TODO:** We will need to do small adaptations to the verification +spec to reflect the semantics in the LightStore (verified, trusted, +untrusted, etc. not needed anymore). In more detail: + +- The state of the Lightstore needs to go. Functions like `LatestVerified` can +keep the name but will ignore state as it will not exist anymore. + +- verification spec should be adapted to the second parameter of +`VerifyToTarget` +being a lightblock; new version number of function tag; + +- We should clarify what is the expectation of VerifyToTarget +so if it returns TimeoutError it can be assumed faulty. I guess that +VerifyToTarget with correct full node should never terminate with +TimeoutError. + +- We need to introduce a new version number for the new +specification. So we should decide how + to handle that. + +# Light Client Attack Detector + +In this specification, we strengthen the light client to be resistant +against so-called light client attacks. In a light client attack, all +the correct Cosmos full nodes agree on the sequence of generated +blocks (no fork), but a set of faulty full nodes attack a light client +by generating (signing) a block that deviates from the block of the +same height on the blockchain. In order to do so, some of these faulty +full nodes must have been validators before and violate +[[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link), as otherwise, if +[[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link) would hold, +[verification](verification) would satisfy +[[LCV-SEQ-SAFE.1]](LCV-SEQ-SAFE-link). + +An attack detector (or detector for short) is a mechanism that is used +by the light client [supervisor](supervisor) after +[verification](verification) of a new light block +with the primary, to cross-check the newly learned light block with +other peers (secondaries). It expects as input a light block with some +height *root* (that serves as a root of trust), and a verification +trace (a sequence of lightblocks) that the primary provided. + +In case the detector observes a light client attack, it computes +evidence data that can be used by Cosmos full nodes to isolate a +set of faulty full nodes that are still within the unbonding period +(more than 1/3 of the voting power of the validator set at some block of the chain), +and report them via ABCI to the application of a Cosmos blockchain +in order to punish faulty nodes. + +## Context of this document + +The light client [verification](verification) specification is +designed for the Cosmos failure model (1/3 assumption) +[[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link). It is safe under this +assumption, and live if it can reliably (that is, no message loss, no +duplication, and eventually delivered) and timely communicate with a +correct full node. If [[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link) assumption is violated, the light client +can be fooled to trust a light block that was not generated by +Tendermint consensus. + +This specification, the attack detector, is a "second line of +defense", in case the 1/3 assumption is violated. Its goal is to +detect a light client attack (conflicting light blocks) and collect +evidence. However, it is impractical to probe all full nodes. At this +time we consider a simple scheme of maintaining an address book of +known full nodes from which a small subset (e.g., 4) are chosen +initially to communicate with. More involved book keeping with +probabilistic guarantees can be considered at later stages of the +project. + +The light client maintains a simple address book containing addresses +of full nodes that it can pick as primary and secondaries. To obtain +a new light block, the light client first does +[verification](verification) with the primary, and then cross-checks +the light block (and the trace of light blocks that led to it) with +the secondaries using this specification. + +## Tendermint Consensus and Light Client Attacks + +In this section we will give some mathematical definitions of what we +mean by light client attacks (that are considered in this +specification) and how they differ from main-chain forks. To this end +we start by defining some properties of the sequence of blocks that is +decided upon by Tendermint consensus in normal operation (if the +Cosmos failure model holds +[[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link)), +and then define different +deviations that correspond to attack scenarios. + +#### **[CMBC-GENESIS.1]** + +Let *Genesis* be the agreed-upon initial block (file). + +#### **[CMBC-FUNC-SIGN.1]** + +Let *b* and *c* be two light blocks with *b.Header.Height + 1 = +c.Header.Height*. We define the predicate **signs(b,c)** to hold +iff *c.Header.LastCommit* is in *PossibleCommit(b)*. +[[CMBC-SOUND-DISTR-POSS-COMMIT.1]](CMBC-SOUND-DISTR-POSS-COMMIT-link). + +> The above encodes sequential verification, that is, intuitively, +> b.Header.NextValidators = c.Header.Validators and 2/3 of +> these Validators signed c? + +#### **[CMBC-FUNC-SUPPORT.1]** + +Let *b* and *c* be two light blocks. We define the predicate +**supports(b,c,t)** to hold iff + +- *t - trustingPeriod < b.Header.Time < t* +- the voting power in *b.NextValidators* of nodes in *c.Commit* + is more than 1/3 of *TotalVotingPower(b.Header.NextValidators)* + +> That is, if the [Cosmos failure model](CMBC-FM-2THIRDS-link) +> holds, then *c* has been signed by at least one correct full node, cf. +> [[CMBC-VAL-CONTAINS-CORR.1]](CMBC-VAL-CONTAINS-CORR-link). +> The following formalizes that *b* was properly generated by +> Tendermint; *b* can be traced back to genesis + +#### **[CMBC-SEQ-ROOTED.1]** + +Let *b* be a light block. +We define *sequ-rooted(b)* iff for all *i*, *1 <= i < h = b.Header.Height*, +there exist light blocks *a(i)* s.t. + +- *a(1) = Genesis* and +- *a(h) = b* and +- *signs( a(i) , a(i+1) )*. + +> The following formalizes that *c* is trusted based on *b* in +> skipping verification. Observe that we do not require here (yet) +> that *b* was properly generated. + +#### **[CMBC-SKIP-TRACE.1]** + +Let *b* and *c* be light blocks. We define *skip-trace(b,c,t)* if at +time t there exists an *h* and a sequence *a(1)*, ... *a(h)* s.t. + +- *a(1) = b* and +- *a(h) = c* and +- *supports( a(i), a(i+1), t)*, for all i, *1 <= i < h*. + +We call such a sequence *a(1)*, ... *a(h)* a **verification trace**. + +> The following formalizes that two light blocks of the same height +> should agree on the content of the header. Observe that *b* and *c* +> may disagree on the Commit. This is a special case if the canonical +> commit has not been decided on, that is, if b.Header.Height is the +> maximum height of all blocks decided upon by Tendermint at this +> moment. + +#### **[CMBC-SIGN-SKIP-MATCH.1]** + +Let *a*, *b*, *c*, be light blocks and *t* a time, we define +*sign-skip-match(a,b,c,t) = true* iff the following implication +evaluates to true: + +- *sequ-rooted(a)* and +- *b.Header.Height = c.Header.Height* and +- *skip-trace(a,b,t)* +- *skip-trace(a,c,t)* + +implies *b.Header = c.Header*. + +> Observe that *sign-skip-match* is defined via an implication. If it +> evaluates to false this means that the left-hand-side of the +> implication evaluates to true, and the right-hand-side evaluates to +> false. In particular, there are two **different** headers *b* and +> *c* that both can be verified from a common block *a* from the +> chain. Thus, the following describes an attack. + +#### **[CMBC-ATTACK.1]** + +If there exists three light blocks a, b, and c, with +*sign-skip-match(a,b,c,t) = false* then we have an *attack*. We say +we have **an attack at height** *b.Header.Height* and write +*attack(a,b,c,t)*. + +> The lightblock *a* need not be unique, that is, there may be +> several blocks that satisfy the above requirement for the same +> blocks *b* and *c*. + +[[CMBC-ATTACK.1]](#CMBC-ATTACK1) is a formalization of the violation +of the agreement property based on the result of consensus, that is, +the generated blocks. + +**Remark.** +Violation of agreement is only possible if more than 1/3 of the validators (or +next validators) of some previous block deviated from the protocol. The +upcoming "accountability" specification will describe how to compute +a set of at least 1/3 faulty nodes from two conflicting blocks. [] + +There are different ways to characterize forks +and attack scenarios. This specification uses the "node-based +characterization of attacks" which focuses on what kinds of nodes are +affected (light nodes vs. full nodes). For future reference and +discussion we also provide a +"block-based characterization of attacks" below. + +### Node-based characterization of attacks + +#### **[CMBC-MC-FORK.1]** + +We say there is a (main chain) fork at time *t* if + +- there are two correct full nodes *i* and *j* and +- *i* is different from *j* and +- *i* has decided on *b* and +- *j* has decided on *c* and +- there exist *a* such that *attack(a,b,c,t)*. + +#### **[CMBC-LC-ATTACK.1]** + +We say there is a light client attack at time *t*, if + +- there is **no** (main chain) fork [[CMBC-MC-FORK.1]](#CMBC-MC-FORK1), and +- there exist nodes that have computed light blocks *b* and *c* and +- there exist *a* such that *attack(a,b,c,t)*. + +We say the attack is at height *a.Header.Height*. + +> In this specification we consider detection of light client +> attacks. Intuitively, the case we consider is that +> light block *b* is the one from the +> blockchain, and some attacker has computed *c* and tries to wrongly +> convince +> the light client that *c* is the block from the chain. + +#### **[CMBC-LC-ATTACK-EVIDENCE.1]** + +We consider the following case of a light client attack +[[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1): + +- *attack(a,b,c,t)* +- there is a peer p1 that has a sequence *chain* of blocks from *a* to *b* +- *skip-trace(a,c,t)*: by [[CMBC-SKIP-TRACE.1]](#CMBC-SKIP-TRACE1) there is a + verification trace *v* of the form *a = v(1)*, ... *v(h) = c* + +Evidence for p1 (that proves an attack) consists for index i +of v(i) and v(i+1) such that + +- E1(i). v(i) is equal to the block of *chain* at height v(i).Height, and +- E2(i). v(i+1) that is different from the block of *chain* at + height v(i+1).height + +> Observe p1 can +> +> - check that v(i+1) differs from its block at that height, and +> - verify v(i+1) in one step from v(i) as v is a verification trace. + +**Proposition.** In the case of attack, evidence exists. +*Proof.* First observe that + +- (A). (NOT E2(i)) implies E1(i+1) + +Now by contradiction assume there is no evidence. Thus + +- for all i, we have NOT E1(i) or NOT E2(i) +- for i = 1 we have E1(1) and thus NOT E2(1) + thus by induction on i, by (A) we have for all i that **E1(i)** +- from attack we have E2(h-1), and as there is no evidence for + i = h - 1 we get **NOT E1(h-1)**. Contradiction. +QED. + +#### **[CMBC-LC-EVIDENCE-DATA.1]** + +To prove the attack to p1, because of Point E1, it is sufficient to +submit + +- v(i).Height (rather than v(i)). +- v(i+1) + +This information is *evidence for height v(i).Height*. + +### Block-based characterization of attacks + +In this section we provide a different characterization of attacks. It +is not defined on the nodes that are affected but purely on the +content of the blocks. In that sense these definitions are less +operational. + +> They might be relevant for a closer analysis of fork scenarios on the +> chain, which is out of the scope of this specification. + +#### **[CMBC-SIGN-UNIQUE.1]** + +Let *b* and *c* be light blocks, we define the predicate +*sign-unique(b,c)* to evaluate to true iff the following implication +evaluates to true: + +- *b.Header.Height = c.Header.Height* and +- *sequ-rooted(b)* and +- *sequ-rooted(c)* + +implies *b = c*. + +#### **[CMBC-BLOCKS-MCFORK.1]** + +If there exists two light blocks b and c, with *sign-unique(b,c) = +false* then we have a *fork*. + +> The difference of the above definition to +> [[CMBC-MC-FORK.1]](#CMBC-MC-FORK1) is subtle. The latter requires a +> full node being affected by a bad block while +> [[CMBC-BLOCKS-MCFORK.1]](#CMBC-BLOCKS-MCFORK1) just requires that a +> bad block exists, possibly in memory of an attacker. +> The following captures a light client fork. There is no fork up to +> the height of block b. However, c is of that height, is different, +> and passes skipping verification. It is a stricter property than +> [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1), as +> [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1) requires that no correct full +> node is affected. + +#### **[CMBC-BLOCKS-LCFORK.1]** + +Let *a*, *b*, *c*, be light blocks and *t* a time. We define +*light-client-fork(a,b,c,t)* iff + +- *sign-skip-match(a,b,c,t) = false* and +- *sequ-rooted(b)* and +- *b* is "unique", that is, for all *d*, *sequ-rooted(d)* and + *d.Header.Height = b.Header.Height* implies *d = b* + +> Finally, let us also define bogus blocks that have no support. +> Observe that bogus is even defined if there is a fork. +> Also, for the definition it would be sufficient to restrict *a* to +> *a.height < b.height* (which is implied by the definitions which +> unfold until *supports()*). + +#### **[CMBC-BOGUS.1]** + +Let *b* be a light block and *t* a time. We define *bogus(b,t)* iff + +- *sequ-rooted(b) = false* and +- for all *a*, *sequ-rooted(a)* implies *skip-trace(a,b,t) = false* + +### Informal Problem statement + +There is no sequential specification: the detector only makes sense +in a distributed systems where some nodes misbehave. + +We work under the assumption that full nodes and validators are +responsible for detecting attacks on the main chain, and the evidence +reactor takes care of broadcasting evidence to communicate +misbehaving nodes via ABCI to the application, and halt the chain in +case of a fork. The point of this specification is to shield a light +clients against attacks that cannot be detected by full nodes, and +are fully addressed at light clients (and consequently IBC relayers, +which use the light client protocols to observe the state of a +blockchain). In order to provide full nodes the incentive to follow +the protocols when communicating with the light client, this +specification also considers the generation of evidence that will +also be processed by the Cosmos blockchain. + +#### **[LCD-IP-MODEL.1]** + +The detector is designed under the assumption that + +- [[CMBC-FM-2THIRDS]](CMBC-FM-2THIRDS-link) may be violated +- there is no fork on the main chain. + +> As a result some faulty full nodes may launch an attack on a light +> client. + +The following requirements are operational in that they describe how +things should be done, rather than what should be done. However, they +do not constitute temporal logic verification conditions. For those, +see [LCD-DIST-*] below. + +The detector is called in the [supervisor](supervisor) as follows + +```go +Evidences := AttackDetector(root_of_trust, verifiedLS);` +``` + +where + +- `root-of-trust` is a light block that is trusted (that is, +except upon initialization, the primary and the secondaries +agreed on in the past), and +- `verifiedLS` is a lightstore that contains a verification trace that + starts from a lightblock that can be verified with the + `root-of-trust` in one step and ends with a lightblock of the height + requested by the user +- `Evidences` is a list of evidences for misbehavior + +#### **[LCD-IP-STATEMENT.1]** + +Whenever AttackDetector is called, the detector should for each +secondary try to replay the verification trace `verifiedLS` with the +secondary + +- in case replaying leads to detection of a light client attack + (one of the lightblocks differ from the one in verifiedLS with + the same height), we should return evidence +- if the secondary cannot provide a verification trace, we have no + proof for an attack. Block *b* may be bogus. In this case the + secondary is faulty and it should be replaced. + +## Assumptions/Incentives/Environment + +It is not in the interest of faulty full nodes to talk to the +detector as long as the detector is connected to at least one +correct full node. This would only increase the likelihood of +misbehavior being detected. Also we cannot punish them easily +(cheaply). The absence of a response need not be the fault of the full +node. + +Correct full nodes have the incentive to respond, because the +detector may help them to understand whether their header is a good +one. We can thus base liveness arguments of the detector on +the assumptions that correct full nodes reliably talk to the +detector. + +### Assumptions + +#### **[LCD-A-CorrFull.1]** + +At all times there is at least one correct full +node among the primary and the secondaries. + +> For this version of the detection we take this assumption. It +> allows us to establish the invariant that the lightblock +> `root-of-trust` is always the one from the blockchain, and we can +> use it as starting point for the evidence computation. Moreover, it +> allows us to establish the invariant at the supervisor that any +> lightblock in the (top-level) lightstore is from the blockchain. +> In the future we might design a lightclient based on the assumption +> that at least in regular intervals the lightclient is connected to a +> correct full node. This will require the detector to reconsider +> `root-of-trust`, and remove lightblocks from the top-level +> lightstore. + +#### **[LCD-A-RelComm.1]** + +Communication between the detector and a correct full node is +reliable and bounded in time. Reliable communication means that +messages are not lost, not duplicated, and eventually delivered. There +is a (known) end-to-end delay *Delta*, such that if a message is sent +at time *t* then it is received and processed by time *t + Delta*. +This implies that we need a timeout of at least *2 Delta* for remote +procedure calls to ensure that the response of a correct peer arrives +before the timeout expires. + +## Definitions + +### Evidence + +Following the definition of +[[CMBC-LC-ATTACK-EVIDENCE.1]](#CMBC-LC-ATTACK-EVIDENCE1), by evidence +we refer to a variable of the following type + +#### **[LC-DATA-EVIDENCE.1]** + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 +} +``` + +As the above data is computed for a specific peer, the following +data structure wraps the evidence and adds the peerID. + +#### **[LC-DATA-EVIDENCE-INT.1]** + +```go +type InternalEvidence struct { + Evidence LightClientAttackEvidence + Peer PeerID +} +``` + +#### **[LC-SUMBIT-EVIDENCE.1]** + +```go +func submitEvidence(Evidences []InternalEvidence) +``` + +- Expected postcondition + - for each `ev` in `Evidences`: submit `ev.Evidence` to `ev.Peer` + +--- + +### LightStore + +Lightblocks and LightStores are defined in the verification +specification [LCV-DATA-LIGHTBLOCK.1] and [LCV-DATA-LIGHTSTORE.1]. See +the [verification specification][verification] for details. + +## (Distributed) Problem statement + +> As the attack detector is there to reduce the impact of faulty +> nodes, and faulty nodes imply that there is a distributed system, +> there is no sequential specification to which this distributed +> problem statement may refer to. + +The detector gets as input a trusted lightblock called *root* and an +auxiliary lightstore called *primary_trace* with lightblocks that have +been verified before, and that were provided by the primary. + +#### **[LCD-DIST-INV-ATTACK.1]** + +If the detector returns evidence for height *h* +[[CMBC-LC-EVIDENCE-DATA.1]](#CMBC-LC-EVIDENCE-DATA1), then there is an +attack at height *h*. [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1) + +#### **[LCD-DIST-INV-STORE.1]** + +If the detector does not return evidence, then *primary_trace* +contains only blocks from the blockchain. + +#### **[LCD-DIST-LIVE.1]** + +The detector eventually terminates. + +#### **[LCD-DIST-TERM-NORMAL.1]** + +If + +- the *primary_trace* contains only blocks from the blockchain, and +- there is no attack, and +- *Secondaries* is always non-empty, and +- the age of *root* is always less than the trusting period, + +then the detector does not return evidence. + +#### **[LCD-DIST-TERM-ATTACK.1]** + +If + +- there is an attack, and +- a secondary reports a block that conflicts + with one of the blocks in *primary_trace*, and +- *Secondaries* is always non-empty, and +- the age of *root* is always less than the trusting period, + +then the detector returns evidence. + +> Observe that above we require that "a secondary reports a block that +> conflicts". If there is an attack, but no secondary tries to launch +> it against the detector (or the message from the secondary is lost +> by the network), then there is nothing to detect for us. + +#### **[LCD-DIST-SAFE-SECONDARY.1]** + +No correct secondary is ever replaced. + +#### **[LCD-DIST-SAFE-BOGUS.1]** + +If + +- a secondary reports a bogus lightblock, +- the age of *root* is always less than the trusting period, + +then the secondary is replaced before the detector terminates. + +> The above property is quite operational ("reports"), but it captures +> quite closely the requirement. As the +> detector only makes sense in a distributed setting, and does +> not have a sequential specification, less "pure" +> specification are acceptable. + +# Protocol + +## Functions and Data defined in other Specifications + +### From the supervisor + +```go +Replace_Secondary(addr Address, root-of-trust LightBlock) +``` + +### From the verifier + +```go +func VerifyToTarget(primary PeerID, root LightBlock, + targetHeight Height) (LightStore, Result) +``` + +> Note: the above differs from the current version in the second +> parameter. verification will be revised. + +Observe that `VerifyToTarget` does communication with the secondaries +via the function [FetchLightBlock](fetch). + +### Shared data of the light client + +- a pool of full nodes *FullNodes* that have not been contacted before +- peer set called *Secondaries* +- primary + +> Note that the lightStore is not needed to be shared. + +## Outline + +The problem laid out is solved by calling the function `AttackDetector` +with a lightstore that contains a light block that has just been +verified by the verifier. + +Then `AttackDetector` downloads headers from the secondaries. In case +a conflicting header is downloaded from a secondary, +`CreateEvidenceForPeer` which computes evidence in the case that +indeed an attack is confirmed. It could be that the secondary reports +a bogus block, which means that there need not be an attack, and the +secondary is replaced. + +## Details of the functions + +#### **[LCD-FUNC-DETECTOR.1]:** + +```go +func AttackDetector(root LightBlock, primary_trace []LightBlock) + ([]InternalEvidence) { + + Evidences := new []InternalEvidence; + + for each secondary in Secondaries { + // we replay the primary trace with the secondary, in + // order to generate evidence that we can submit to the + // secodary. We return the evidence + the trace the + // secondary told us that spans the evidence at its local store + + EvidenceForSecondary, newroot, secondary_trace, result := + CreateEvidenceForPeer(secondary, + root, + primary_trace); + if result == FaultyPeer { + Replace_Secondary(root); + } + else if result == FoundEvidence { + // the conflict is not bogus + Evidences.Add(EvidenceForSecondary); + // we replay the secondary trace with the primary, ... + EvidenceForPrimary, _, result := + CreateEvidenceForPeer(primary, + newroot, + secondary_trace); + if result == FoundEvidence { + Evidences.Add(EvidenceForPrimary); + } + // At this point we do not care about the other error + // codes. We already have generated evidence for an + // attack and need to stop the lightclient. It does not + // help to call replace_primary. Also we will use the + // same primary to check with other secondaries in + // later iterations of the loop + } + // In the case where the secondary reports NoEvidence + // we do nothing + } + return Evidences; +} +``` + +- Expected precondition + - root and primary trace are a verification trace +- Expected postcondition + - solves the problem statement (if attack found, then evidence is reported) +- Error condition + - `ErrorTrustExpired`: fails if root expires (outside trusting + period) [[LCV-INV-TP.1]](LCV-INV-TP1-link) + - `ErrorNoPeers`: if no peers are left to replace secondaries, and + no evidence was found before that happened + +--- + +```go +func CreateEvidenceForPeer(peer PeerID, root LightBlock, trace LightStore) + (Evidence, LightBlock, LightStore, result) { + + common := root; + + for i in 1 .. len(trace) { + auxLS, result := VerifyToTarget(peer, common, trace[i].Header.Height) + + if result != ResultSuccess { + // something went wrong; peer did not provide a verifyable block + return (nil, nil, nil, FaultyPeer) + } + else { + if auxLS.LatestVerified().Header != trace[i].Header { + // the header reported by the peer differs from the + // reference header in trace but both could be + // verified from common in one step. + // we can create evidence for submission to the secondary + ev := new InternalEvidence; + ev.Evidence.ConflictingBlock := trace[i]; + ev.Evidence.CommonHeight := common.Height; + ev.Peer := peer + return (ev, common, auxLS, FoundEvidence) + } + else { + // the peer agrees with the trace, we move common forward + // we could delete auxLS as it will be overwritten in + // the next iteration + common := trace[i] + } + } + } + return (nil, nil, nil, NoEvidence) +} +``` + +- Expected precondition + - root and trace are a verification trace +- Expected postcondition + - finds evidence where trace and peer diverge +- Error condition + - `ErrorTrustExpired`: fails if root expires (outside trusting + period) [[LCV-INV-TP.1]](LCV-INV-TP1-link) + - If `VerifyToTarget` returns error but root is not expired then return + `FaultyPeer` + +--- + +## Correctness arguments + +#### Argument for [[LCD-DIST-INV-ATTACK.1]](#LCD-DIST-INV-ATTACK1) + +Under the assumption that root and trace are a verification trace, +when in `CreateEvidenceForPeer` the detector the detector creates +evidence, then the lightclient has seen two different headers (one via +`trace` and one via `VerifyToTarget` for the same height that can both +be verified in one step. + +#### Argument for [[LCD-DIST-INV-STORE.1]](#LCD-DIST-INV-STORE1) + +We assume that there is at least one correct peer, and there is no +fork. As a result the correct peer has the correct sequence of +blocks. Since the primary_trace is checked block-by-block also against +each secondary, and at no point evidence was generated that means at +no point there were conflicting blocks. + +#### Argument for [[LCD-DIST-LIVE.1]](#LCD-DIST-LIVE1) + +At the latest when [[LCV-INV-TP.1]](LCV-INV-TP1-link) is violated, +`AttackDetector` terminates. + +#### Argument for [[LCD-DIST-TERM-NORMAL.1]](#LCD-DIST-TERM-NORMAL1) + +As there are finitely many peers, eventually the main loop +terminates. As there is no attack no evidence can be generated. + +#### Argument for [[LCD-DIST-TERM-ATTACK.1]](#LCD-DIST-TERM-ATTACK1) + +Argument similar to [[LCD-DIST-TERM-NORMAL.1]](#LCD-DIST-TERM-NORMAL1) + +#### Argument for [[LCD-DIST-SAFE-SECONDARY.1]](#LCD-DIST-SAFE-SECONDARY1) + +Secondaries are only replaced if they time-out or if they report bogus +blocks. The former is ruled out by the timing assumption, the latter +by correct peers only reporting blocks from the chain. + +#### Argument for [[LCD-DIST-SAFE-BOGUS.1]](#LCD-DIST-SAFE-BOGUS1) + +Once a bogus block is recognized as such the secondary is removed. + +# References + +> links to other specifications/ADRs this document refers to + +[[verification]] The specification of the light client verification. + +[[supervisor]] The specification of the light client supervisor. + +[verification]: https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/verification + +[supervisor]: https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/supervisor + + + + + +[CMBC-VAL-CONTAINS-CORR-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-val-contains-corr1 + +[fetch]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-func-fetch1 + +[LCV-INV-TP1-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-inv-tp1 diff --git a/spec/light-client/detection/detection_003_reviewed.md b/spec/light-client/detection/detection_003_reviewed.md new file mode 100644 index 0000000..b1bfc50 --- /dev/null +++ b/spec/light-client/detection/detection_003_reviewed.md @@ -0,0 +1,839 @@ + +# Light Client Attack Detector + +In this specification, we strengthen the light client to be resistant +against so-called light client attacks. In a light client attack, all +the correct Cosmos full nodes agree on the sequence of generated +blocks (no fork), but a set of faulty full nodes attack a light client +by generating (signing) a block that deviates from the block of the +same height on the blockchain. In order to do so, some of these faulty +full nodes must have been validators before and violate the assumption +of more than two thirds of "correct voting power" +[[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link], as otherwise, if +[[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link] would hold, +[verification][verification] would satisfy +[[LCV-SEQ-SAFE.1]][LCV-SEQ-SAFE-link]. + +An attack detector (or detector for short) is a mechanism that is used +by the light client [supervisor][supervisor] after +[verification][verification] of a new light block +with the primary, to cross-check the newly learned light block with +other peers (secondaries). It expects as input a light block with some +height *root* (that serves as a root of trust), and a verification +trace (a sequence of lightblocks) that the primary provided. + +In case the detector observes a light client attack, it computes +evidence data that can be used by Cosmos full nodes to isolate a +set of faulty full nodes that are still within the unbonding period +(more than 1/3 of the voting power of the validator set at some block +of the chain), and report them via ABCI (application/blockchain +interface) +to the application of a +Cosmos blockchain in order to punish faulty nodes. + +## Context of this document + +The light client [verification][verification] specification is +designed for the Cosmos failure model (1/3 assumption) +[[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link]. It is safe under this +assumption, and live if it can reliably (that is, no message loss, no +duplication, and eventually delivered) and timely communicate with a +correct full node. If [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link] +assumption is violated, the light client can be fooled to trust a +light block that was not generated by Tendermint consensus. + +This specification, the attack detector, is a "second line of +defense", in case the 1/3 assumption is violated. Its goal is to +detect a light client attack (conflicting light blocks) and collect +evidence. However, it is impractical to probe all full nodes. At this +time we consider a simple scheme of maintaining an address book of +known full nodes from which a small subset (e.g., 4) are chosen +initially to communicate with. More involved book keeping with +probabilistic guarantees can be considered at later stages of the +project. + +The light client maintains a simple address book containing addresses +of full nodes that it can pick as primary and secondaries. To obtain +a new light block, the light client first does +[verification][verification] with the primary, and then cross-checks +the light block (and the trace of light blocks that led to it) with +the secondaries using this specification. + +# Outline + +- [Part I](#part-i---Tendermint-Consensus-and-Light-Client-Attacks): + Formal definitions of lightclient attacks, based on basic + properties of Tendermint consensus. + - [Node-based characterization of + attacks](#Node-based-characterization-of-attacks). The + definition of attacks used in the problem statement of + this specification. + + - [Block-based characterization of attacks](#Block-based-characterization-of-attacks). Alternative definitions + provided for future reference. + +- [Part II](#part-ii---problem-statement): Problem statement of + lightclient attack detection + + - [Informal Problem Statement](#informal-problem-statement) + - [Assumptions](#Assumptions) + - [Definitions](#definitions) + - [Distributed Problem statement](#Distributed-Problem-statement) + +- [Part III](#part-iii---protocol): The protocol + + - [Functions and Data defined in other Specifications](#Functions-and-Data-defined-in-other-Specifications) + - [Outline of Solution](#Outline-of-solution) + - [Details of the functions](#Details-of-the-functions) + - [Correctness arguments](#Correctness-arguments) + +# Part I - Tendermint Consensus and Light Client Attacks + +In this section we will give some mathematical definitions of what we +mean by light client attacks (that are considered in this +specification) and how they differ from main-chain forks. To this end, +we start by defining some properties of the sequence of blocks that is +decided upon by Tendermint consensus in normal operation (if the +Cosmos failure model holds +[[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link]), +and then define different +deviations that correspond to attack scenarios. We consider the notion +of [light blocks][LCV-LB-link] and [headers][LVC-HD-link]. + +#### **[CMBC-GENESIS.1]** + +Let *Genesis* be the agreed-upon initial block (file). + +#### **[CMBC-FUNC-SIGN.1]** + +Let *b* and *c* be two light blocks with *b.Header.Height + 1 = +c.Header.Height*. We define the predicate **signs(b,c)** to hold +iff *c.Header.LastCommit* is in *PossibleCommit(b)*. +[[CMBC-SOUND-DISTR-POSS-COMMIT.1]][CMBC-SOUND-DISTR-POSS-COMMIT-link]. + +> The above encodes sequential verification, that is, intuitively, +> b.Header.NextValidators = c.Header.Validators and 2/3 of +> these Validators signed c. + +#### **[CMBC-FUNC-SUPPORT.1]** + +Let *b* and *c* be two light blocks. We define the predicate +**supports(b,c,t)** to hold iff + +- *t - trustingPeriod < b.Header.Time < t* +- the voting power in *b.NextValidators* of nodes in *c.Commit* + is more than 1/3 of *TotalVotingPower(b.Header.NextValidators)* + +> That is, if the [Cosmos failure model][CMBC-FM-2THIRDS-link] +> holds, then *c* has been signed by at least one correct full node, cf. +> [[CMBC-VAL-CONTAINS-CORR.1]][CMBC-VAL-CONTAINS-CORR-link]. +> The following formalizes that *b* was properly generated by +> Tendermint; *b* can be traced back to genesis. + +#### **[CMBC-SEQ-ROOTED.1]** + +Let *b* be a light block. +We define *sequ-rooted(b)* iff for all *i*, *1 <= i < h = b.Header.Height*, +there exist light blocks *a(i)* s.t. + +- *a(1) = Genesis* and +- *a(h) = b* and +- *signs( a(i) , a(i+1) )*. + +> The following formalizes that *c* is trusted based on *b* in +> skipping verification. Observe that we do not require here (yet) +> that *b* was properly generated. + +#### **[CMBC-SKIP-TRACE.1]** + +Let *b* and *c* be light blocks. We define *skip-trace(b,c,t)* if at +time t there exists an integer *h* and a sequence *a(1)*, ... *a(h)* s.t. + +- *a(1) = b* and +- *a(h) = c* and +- *supports( a(i), a(i+1), t)*, for all i, *1 <= i < h*. + +We call such a sequence *a(1)*, ... *a(h)* a **verification trace**. + +> The following formalizes that two light blocks of the same height +> should agree on the content of the header. Observe that *b* and *c* +> may disagree on the Commit. This is a special case if the canonical +> commit has not been decided on yet, that is, if b.Header.Height is the +> maximum height of all blocks decided upon by Tendermint at this +> moment. + +#### **[CMBC-SIGN-SKIP-MATCH.1]** + +Let *a*, *b*, *c*, be light blocks and *t* a time, we define +*sign-skip-match(a,b,c,t) = true* iff the following implication +evaluates to true: + +- *sequ-rooted(a)* and +- *b.Header.Height = c.Header.Height* and +- *skip-trace(a,b,t)* +- *skip-trace(a,c,t)* + +implies *b.Header = c.Header*. + +> Observe that *sign-skip-match* is defined via an implication. If it +> evaluates to false this means that the left-hand-side of the +> implication evaluates to true, and the right-hand-side evaluates to +> false. In particular, there are two **different** headers *b* and +> *c* that both can be verified from a common block *a* from the +> chain. Thus, the following describes an attack. + +#### **[CMBC-ATTACK.1]** + +If there exists three light blocks a, b, and c, with +*sign-skip-match(a,b,c,t) = false* then we have an *attack*. We say +we have **an attack at height** *b.Header.Height* and write +*attack(a,b,c,t)*. + +> The lightblock *a* need not be unique, that is, there may be +> several blocks that satisfy the above requirement for the same +> blocks *b* and *c*. + +[[CMBC-ATTACK.1]](#CMBC-ATTACK1) is a formalization of the violation +of the agreement property based on the result of consensus, that is, +the generated blocks. + +**Remark.** +Violation of agreement is only possible if more than 1/3 of the validators (or +next validators) of some previous block deviated from the protocol. The +upcoming "accountability" specification will describe how to compute +a set of at least 1/3 faulty nodes from two conflicting blocks. [] + +There are different ways to characterize forks +and attack scenarios. This specification uses the "node-based +characterization of attacks" which focuses on what kinds of nodes are +affected (light nodes vs. full nodes). For future reference and +discussion we also provide a +"block-based characterization of attacks" below. + +## Node-based characterization of attacks + +#### **[CMBC-MC-FORK.1]** + +We say there is a (main chain) fork at time *t* if + +- there are two correct full nodes *i* and *j* and +- *i* is different from *j* and +- *i* has decided on *b* and +- *j* has decided on *c* and +- there exist *a* such that *attack(a,b,c,t)*. + +#### **[CMBC-LC-ATTACK.1]** + +We say there is a light client attack at time *t*, if + +- there is **no** (main chain) fork [[CMBC-MC-FORK.1]](#CMBC-MC-FORK1), and +- there exist nodes that have computed light blocks *b* and *c* and +- there exist *a* such that *attack(a,b,c,t)*. + +We say the attack is at height *a.Header.Height*. + +> In this specification we consider detection of light client +> attacks. Intuitively, the case we consider is that +> light block *b* is the one from the +> blockchain, and some attacker has computed *c* and tries to wrongly +> convince +> the light client that *c* is the block from the chain. + +#### **[CMBC-LC-ATTACK-EVIDENCE.1]** + +We consider the following case of a light client attack +[[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1): + +- *attack(a,b,c,t)* +- there is a peer p1 that has a sequence *chain* of blocks from *a* to *b* +- *skip-trace(a,c,t)*: by [[CMBC-SKIP-TRACE.1]](#CMBC-SKIP-TRACE1) there is a + verification trace *v* of the form *a = v(1)*, ... *v(h) = c* + +Evidence for p1 (that proves an attack to p1) consists for index i +of v(i) and v(i+1) such that + +- E1(i). v(i) is equal to the block of *chain* at height v(i).Height, and +- E2(i). v(i+1) that is different from the block of *chain* at + height v(i+1).height + +> Observe p1 can +> +> - check that v(i+1) differs from its block at that height, and +> - verify v(i+1) in one step from v(i) as v is a verification trace. + +#### **[CMBC-LC-EVIDENCE-DATA.1]** + +To prove the attack to p1, because of Point E1, it is sufficient to +submit + +- v(i).Height (rather than v(i)). +- v(i+1) + +This information is *evidence for height v(i).Height*. + +## Block-based characterization of attacks + +In this section we provide a different characterization of attacks. It +is not defined on the nodes that are affected but purely on the +content of the blocks. In that sense these definitions are less +operational. + +> They might be relevant for a closer analysis of fork scenarios on the +> chain, which is out of the scope of this specification. + +#### **[CMBC-SIGN-UNIQUE.1]** + +Let *b* and *c* be light blocks, we define the predicate +*sign-unique(b,c)* to evaluate to true iff the following implication +evaluates to true: + +- *b.Header.Height = c.Header.Height* and +- *sequ-rooted(b)* and +- *sequ-rooted(c)* + +implies *b = c*. + +#### **[CMBC-BLOCKS-MCFORK.1]** + +If there exists two light blocks b and c, with *sign-unique(b,c) = +false* then we have a *fork*. + +> The difference of the above definition to +> [[CMBC-MC-FORK.1]](#CMBC-MC-FORK1) is subtle. The latter requires a +> full node being affected by a bad block while +> [[CMBC-BLOCKS-MCFORK.1]](#CMBC-BLOCKS-MCFORK1) just requires that a +> bad block exists, possibly in memory of an attacker. +> The following captures a light client fork. There is no fork up to +> the height of block b. However, c is of that height, is different, +> and passes skipping verification. It is a stricter property than +> [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1), as +> [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1) requires that no correct full +> node is affected. + +#### **[CMBC-BLOCKS-LCFORK.1]** + +Let *a*, *b*, *c*, be light blocks and *t* a time. We define +*light-client-fork(a,b,c,t)* iff + +- *sign-skip-match(a,b,c,t) = false* and +- *sequ-rooted(b)* and +- *b* is "unique", that is, for all *d*, *sequ-rooted(d)* and + *d.Header.Height = b.Header.Height* implies *d = b* + +> Finally, let us also define bogus blocks that have no support. +> Observe that bogus is even defined if there is a fork. +> Also, for the definition it would be sufficient to restrict *a* to +> *a.height < b.height* (which is implied by the definitions which +> unfold until *supports()*). + +#### **[CMBC-BOGUS.1]** + +Let *b* be a light block and *t* a time. We define *bogus(b,t)* iff + +- *sequ-rooted(b) = false* and +- for all *a*, *sequ-rooted(a)* implies *skip-trace(a,b,t) = false* + +# Part II - Problem Statement + +## Informal Problem statement + +There is no sequential specification: the detector only makes sense +in a distributed systems where some nodes misbehave. + +We work under the assumption that full nodes and validators are +responsible for detecting attacks on the main chain, and the evidence +reactor takes care of broadcasting evidence to communicate +misbehaving nodes via ABCI to the application, and halt the chain in +case of a fork. The point of this specification is to shield a light +clients against attacks that cannot be detected by full nodes, and +are fully addressed at light clients (and consequently IBC relayers, +which use the light client protocols to observe the state of a +blockchain). In order to provide full nodes the incentive to follow +the protocols when communicating with the light client, this +specification also considers the generation of evidence that will +also be processed by the Cosmos blockchain. + +#### **[LCD-IP-MODEL.1]** + +The detector is designed under the assumption that + +- [[CMBC-FM-2THIRDS]][CMBC-FM-2THIRDS-link] may be violated +- there is no fork on the main chain. + +> As a result some faulty full nodes may launch an attack on a light +> client. + +The following requirements are operational in that they describe how +things should be done, rather than what should be done. However, they +do not constitute temporal logic verification conditions. For those, +see [LCD-DIST-*] below. + +The detector is called in the [supervisor][supervisor] as follows + +```go +Evidences := AttackDetector(root_of_trust, verifiedLS);` +``` + +where + +- `root-of-trust` is a light block that is trusted (that is, +except upon initialization, the primary and the secondaries +agreed on in the past), and +- `verifiedLS` is a lightstore that contains a verification trace that + starts from a lightblock that can be verified with the + `root-of-trust` in one step and ends with a lightblock of the height + requested by the user +- `Evidences` is a list of evidences for misbehavior + +#### **[LCD-IP-STATEMENT.1]** + +Whenever AttackDetector is called, the detector should for each +secondary cross check the largest header in verifiedLS with the +corresponding header of the same height provided by the secondary. If +there is a deviation, the detector should +try to replay the verification trace `verifiedLS` with the +secondary + +- in case replaying leads to detection of a light client attack + (one of the lightblocks differ from the one in verifiedLS with + the same height), we should return evidence +- if the secondary cannot provide a verification trace, we have no + proof for an attack. Block *b* may be bogus. In this case the + secondary is faulty and it should be replaced. + +## Assumptions + +It is not in the interest of faulty full nodes to talk to the +detector as long as the detector is connected to at least one +correct full node. This would only increase the likelihood of +misbehavior being detected. Also we cannot punish them easily +(cheaply). The absence of a response need not be the fault of the full +node. + +Correct full nodes have the incentive to respond, because the +detector may help them to understand whether their header is a good +one. We can thus base liveness arguments of the detector on +the assumptions that correct full nodes reliably talk to the +detector. + +#### **[LCD-A-CorrFull.1]** + +At all times there is at least one correct full +node among the primary and the secondaries. + +> For this version of the detection we take this assumption. It +> allows us to establish the invariant that the lightblock +> `root-of-trust` is always the one from the blockchain, and we can +> use it as starting point for the evidence computation. Moreover, it +> allows us to establish the invariant at the supervisor that any +> lightblock in the (top-level) lightstore is from the blockchain. +> In the future we might design a lightclient based on the assumption +> that at least in regular intervals the lightclient is connected to a +> correct full node. This will require the detector to reconsider +> `root-of-trust`, and remove lightblocks from the top-level +> lightstore. + +#### **[LCD-A-RelComm.1]** + +Communication between the detector and a correct full node is +reliable and bounded in time. Reliable communication means that +messages are not lost, not duplicated, and eventually delivered. There +is a (known) end-to-end delay *Delta*, such that if a message is sent +at time *t* then it is received and processed by time *t + Delta*. +This implies that we need a timeout of at least *2 Delta* for remote +procedure calls to ensure that the response of a correct peer arrives +before the timeout expires. + +## Definitions + +### Evidence + +Following the definition of +[[CMBC-LC-ATTACK-EVIDENCE.1]](#CMBC-LC-ATTACK-EVIDENCE1), by evidence +we refer to a variable of the following type + +#### **[LC-DATA-EVIDENCE.1]** + +```go +type LightClientAttackEvidence struct { + ConflictingBlock LightBlock + CommonHeight int64 + + // Evidence also includes application specific data which is not + // part of verification but is sent to the application once the + // evidence gets committed on chain. +} +``` + +As the above data is computed for a specific peer, the following +data structure wraps the evidence and adds the peerID. + +#### **[LC-DATA-EVIDENCE-INT.1]** + +```go +type InternalEvidence struct { + Evidence LightClientAttackEvidence + Peer PeerID +} +``` + +#### **[LC-SUMBIT-EVIDENCE.1]** + +```go +func submitEvidence(Evidences []InternalEvidence) +``` + +- Expected postcondition + - for each `ev` in `Evidences`: submit `ev.Evidence` to `ev.Peer` + +--- + +### LightStore + +Lightblocks and LightStores are defined in the verification +specification [[LCV-DATA-LIGHTBLOCK.1]][LCV-LB-link] +and [[LCV-DATA-LIGHTSTORE.2]][LCV-LS-link]. See +the [verification specification][verification] for details. + +## Distributed Problem statement + +> As the attack detector is there to reduce the impact of faulty +> nodes, and faulty nodes imply that there is a distributed system, +> there is no sequential specification to which this distributed +> problem statement may refer to. + +The detector gets as input a trusted lightblock called *root* and an +auxiliary lightstore called *primary_trace* with lightblocks that have +been verified before, and that were provided by the primary. + +#### **[LCD-DIST-INV-ATTACK.1]** + +If the detector returns evidence for height *h* +[[CMBC-LC-EVIDENCE-DATA.1]](#CMBC-LC-EVIDENCE-DATA1), then there is an +attack at height *h*. [[CMBC-LC-ATTACK.1]](#CMBC-LC-ATTACK1) + +#### **[LCD-DIST-INV-STORE.1]** + +If the detector does not return evidence, then *primary_trace* +contains only blocks from the blockchain. + +#### **[LCD-DIST-LIVE.1]** + +The detector eventually terminates. + +#### **[LCD-DIST-TERM-NORMAL.1]** + +If + +- the *primary_trace* contains only blocks from the blockchain, and +- there is no attack, and +- *Secondaries* is always non-empty, and +- the age of *root* is always less than the trusting period, + +then the detector does not return evidence. + +#### **[LCD-DIST-TERM-ATTACK.1]** + +If + +- there is an attack, and +- a secondary reports a block that conflicts + with one of the blocks in *primary_trace*, and +- *Secondaries* is always non-empty, and +- the age of *root* is always less than the trusting period, + +then the detector returns evidence. + +> Observe that above we require that "a secondary reports a block that +> conflicts". If there is an attack, but no secondary tries to launch +> it against the detector (or the message from the secondary is lost +> by the network), then there is nothing to detect for us. + +#### **[LCD-DIST-SAFE-SECONDARY.1]** + +No correct secondary is ever replaced. + +#### **[LCD-DIST-SAFE-BOGUS.1]** + +If + +- a secondary reports a bogus lightblock, +- the age of *root* is always less than the trusting period, + +then the secondary is replaced before the detector terminates. + +> The above property is quite operational (e.g., the usage of +> "reports"), but it captures closely the requirement. As the +> detector only makes sense in a distributed setting, and does not +> have a sequential specification, a less "pure" specification are +> acceptable. + +# Part III - Protocol + +## Functions and Data defined in other Specifications + +### From the [supervisor][supervisor] + +[[LC-FUNC-REPLACE-SECONDARY.1]][repl] + +```go +Replace_Secondary(addr Address, root-of-trust LightBlock) +``` + +### From the [verifier][verification] + +[[LCV-FUNC-MAIN.2]][vtt] + +```go +func VerifyToTarget(primary PeerID, root LightBlock, + targetHeight Height) (LightStore, Result) +``` + +Observe that `VerifyToTarget` does communication with the secondaries +via the function [FetchLightBlock][fetch]. + +### Shared data of the light client + +- a pool of full nodes *FullNodes* that have not been contacted before +- peer set called *Secondaries* +- primary + +> Note that the lightStore is not needed to be shared. + +## Outline of solution + +The problem laid out is solved by calling the function `AttackDetector` +with a lightstore that contains a light block that has just been +verified by the verifier. + +Then `AttackDetector` downloads headers from the secondaries. In case +a conflicting header is downloaded from a secondary, it calls +`CreateEvidenceForPeer` which computes evidence in the case that +indeed an attack is confirmed. It could be that the secondary reports +a bogus block, which means that there need not be an attack, and the +secondary is replaced. + +## Details of the functions + +#### **[LCD-FUNC-DETECTOR.2]:** + +```go +func AttackDetector(root LightBlock, primary_trace []LightBlock) + ([]InternalEvidence) { + + Evidences := new []InternalEvidence; + + for each secondary in Secondaries { + lb, result := FetchLightBlock(secondary,primary_trace.Latest().Header.Height); + if result != ResultSuccess { + Replace_Secondary(root); + } + else if lb.Header != primary_trace.Latest().Header { + + // we replay the primary trace with the secondary, in + // order to generate evidence that we can submit to the + // secondary. We return the evidence + the trace the + // secondary told us that spans the evidence at its local store + + EvidenceForSecondary, newroot, secondary_trace, result := + CreateEvidenceForPeer(secondary, + root, + primary_trace); + if result == FaultyPeer { + Replace_Secondary(root); + } + else if result == FoundEvidence { + // the conflict is not bogus + Evidences.Add(EvidenceForSecondary); + // we replay the secondary trace with the primary, ... + EvidenceForPrimary, _, result := + CreateEvidenceForPeer(primary, + newroot, + secondary_trace); + if result == FoundEvidence { + Evidences.Add(EvidenceForPrimary); + } + // At this point we do not care about the other error + // codes. We already have generated evidence for an + // attack and need to stop the lightclient. It does not + // help to call replace_primary. Also we will use the + // same primary to check with other secondaries in + // later iterations of the loop + } + // In the case where the secondary reports NoEvidence + // after initially it reported a conflicting header. + // secondary is faulty + Replace_Secondary(root); + } + } + return Evidences; +} +``` + +- Expected precondition + - root and primary trace are a verification trace +- Expected postcondition + - solves the problem statement (if attack found, then evidence is reported) +- Error condition + - `ErrorTrustExpired`: fails if root expires (outside trusting + period) [[LCV-INV-TP.1]][LCV-INV-TP1-link] + - `ErrorNoPeers`: if no peers are left to replace secondaries, and + no evidence was found before that happened + +--- + +```go +func CreateEvidenceForPeer(peer PeerID, root LightBlock, trace LightStore) + (Evidence, LightBlock, LightStore, result) { + + common := root; + + for i in 1 .. len(trace) { + auxLS, result := VerifyToTarget(peer, common, trace[i].Header.Height) + + if result != ResultSuccess { + // something went wrong; peer did not provide a verifiable block + return (nil, nil, nil, FaultyPeer) + } + else { + if auxLS.LatestVerified().Header != trace[i].Header { + // the header reported by the peer differs from the + // reference header in trace but both could be + // verified from common in one step. + // we can create evidence for submission to the secondary + ev := new InternalEvidence; + ev.Evidence.ConflictingBlock := trace[i]; + // CommonHeight is used to indicate the type of attack + // if the CommonHeight != ConflictingBlock.Height this + // is by definition a lunatic attack else it is an + // equivocation attack + ev.Evidence.CommonHeight := common.Height; + ev.Peer := peer + return (ev, common, auxLS, FoundEvidence) + } + else { + // the peer agrees with the trace, we move common forward. + // we could delete auxLS as it will be overwritten in + // the next iteration + common := trace[i] + } + } + } + return (nil, nil, nil, NoEvidence) +} +``` + +- Expected precondition + - root and trace are a verification trace +- Expected postcondition + - finds evidence where trace and peer diverge +- Error condition + - `ErrorTrustExpired`: fails if root expires (outside trusting + period) [[LCV-INV-TP.1]][LCV-INV-TP1-link] + - If `VerifyToTarget` returns error but root is not expired then return + `FaultyPeer` + +--- + +## Correctness arguments + +#### On the existence of evidence + +**Proposition.** In the case of attack, +evidence [[CMBC-LC-ATTACK-EVIDENCE.1]](#CMBC-LC-ATTACK-EVIDENCE1) + exists. +*Proof.* First observe that + +- (A). (NOT E2(i)) implies E1(i+1) + +Now by contradiction assume there is no evidence. Thus + +- for all i, we have NOT E1(i) or NOT E2(i) +- for i = 1 we have E1(1) and thus NOT E2(1) + thus by induction on i, by (A) we have for all i that **E1(i)** +- from attack we have E2(h-1), and as there is no evidence for + i = h - 1 we get **NOT E1(h-1)**. Contradiction. +QED. + +#### Argument for [[LCD-DIST-INV-ATTACK.1]](#LCD-DIST-INV-ATTACK1) + +Under the assumption that root and trace are a verification trace, +when in `CreateEvidenceForPeer` the detector creates +evidence, then the lightclient has seen two different headers (one via +`trace` and one via `VerifyToTarget`) for the same height that can both +be verified in one step. + +#### Argument for [[LCD-DIST-INV-STORE.1]](#LCD-DIST-INV-STORE1) + +We assume that there is at least one correct peer, and there is no +fork. As a result, the correct peer has the correct sequence of +blocks. Since the primary_trace is checked block-by-block also against +each secondary, and at no point evidence was generated that means at +no point there were conflicting blocks. + +#### Argument for [[LCD-DIST-LIVE.1]](#LCD-DIST-LIVE1) + +At the latest when [[LCV-INV-TP.1]][LCV-INV-TP1-link] is violated, +`AttackDetector` terminates. + +#### Argument for [[LCD-DIST-TERM-NORMAL.1]](#LCD-DIST-TERM-NORMAL1) + +As there are finitely many peers, eventually the main loop +terminates. As there is no attack no evidence can be generated. + +#### Argument for [[LCD-DIST-TERM-ATTACK.1]](#LCD-DIST-TERM-ATTACK1) + +Argument similar to [[LCD-DIST-TERM-NORMAL.1]](#LCD-DIST-TERM-NORMAL1) + +#### Argument for [[LCD-DIST-SAFE-SECONDARY.1]](#LCD-DIST-SAFE-SECONDARY1) + +Secondaries are only replaced if they time-out or if they report bogus +blocks. The former is ruled out by the timing assumption, the latter +by correct peers only reporting blocks from the chain. + +#### Argument for [[LCD-DIST-SAFE-BOGUS.1]](#LCD-DIST-SAFE-BOGUS1) + +Once a bogus block is recognized as such the secondary is removed. + +# References + +> links to other specifications/ADRs this document refers to + +[[verification]] The specification of the light client verification. + +[[supervisor]] The specification of the light client supervisor. + +[verification]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md + +[supervisor]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/supervisor/supervisor_001_draft.md + + +[CMBC-FM-2THIRDS-link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-fm-2thirds1 + +[CMBC-SOUND-DISTR-POSS-COMMIT-link]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-sound-distr-poss-commit1 + +[LCV-SEQ-SAFE-link]:https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-seq-safe1 + +[CMBC-VAL-CONTAINS-CORR-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-val-contains-corr1 + +[fetch]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-func-fetch1 + +[LCV-INV-TP1-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-inv-tp1 + +[LCV-LB-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-data-lightblock1 + +[LCV-LS-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-data-lightstore2 + +[LVC-HD-link]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#cmbc-header-fields2 + +[repl]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/supervisor/supervisor_001_draft.md#lc-func-replace-secondary1 + +[vtt]: +https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_002_draft.md#lcv-func-main2 diff --git a/spec/light-client/detection/discussions.md b/spec/light-client/detection/discussions.md new file mode 100644 index 0000000..9ccb8a6 --- /dev/null +++ b/spec/light-client/detection/discussions.md @@ -0,0 +1,178 @@ +# Results of Discussions and Decisions + +- Generating a minimal proof of fork (as suggested in [Issue #5083](https://github.com/tendermint/tendermint/issues/5083)) is too costly at the light client + - we do not know all lightblocks from the primary + - therefore there are many scenarios. we might even need to ask + the primary again for additional lightblocks to isolate the + branch. + +> For instance, the light node starts with block at height 1 and the +> primary provides a block of height 10 that the light node can +> verify immediately. In cross-checking, a secondary now provides a +> conflicting header b10 of height 10 that needs another header b5 +> of height 5 to +> verify. Now, in order for the light node to convince the primary: +> +> - The light node cannot just sent b5, as it is not clear whether +> the fork happened before or after 5 +> - The light node cannot just send b10, as the primary would also +> need b5 for verification +> - In order to minimize the evidence, the light node may try to +> figure out where the branch happens, e.g., by asking the primary +> for height 5 (it might be that more queries are required, also +> to the secondary. However, assuming that in this scenario the +> primary is faulty it may not respond. + + As the main goal is to catch misbehavior of the primary, + evidence generation and punishment must not depend on their + cooperation. So the moment we have proof of fork (even if it + contains several light blocks) we should submit right away. + +- decision: "full" proof of fork consists of two traces that originate in the + same lightblock and lead to conflicting headers of the same height. + +- For submission of proof of fork, we may do some optimizations, for + instance, we might just submit a trace of lightblocks that verifies a block + different from the one the full node knows (we do not send the trace + the primary gave us back to the primary) + +- The light client attack is via the primary. Thus we try to + catch if the primary installs a bad light block + - We do not check secondary against secondary + - For each secondary, we check the primary against one secondary + +- Observe that just two blocks for the same height are not +sufficient proof of fork. +One of the blocks may be bogus [CMBC-BOGUS.1] which does +not constitute slashable behavior. +Which leads to the question whether the light node should try to do +fork detection on its initial block (from subjective +initialization). This could be done by doing backwards verification +(with the hashes) until a bifurcation block is found. +While there are scenarios where a +fork could be found, there is also the scenario where a faulty full +node feeds the light node with bogus light blocks and forces the light +node to check hashes until a bogus chain is out of the trusting period. +As a result, the light client +should not try to detect a fork for its initial header. **The initial +header must be trusted as is.** + +# Light Client Sequential Supervisor + +**TODO:** decide where (into which specification) to put the +following: + +We describe the context on which the fork detector is called by giving +a sequential version of the supervisor function. +Roughly, it alternates two phases namely: + +- Light Client Verification. As a result, a header of the required + height has been downloaded from and verified with the primary. +- Light Client Fork Detections. As a result the header has been + cross-checked with the secondaries. In case there is a fork we + submit "proof of fork" and exit. + +#### **[LC-FUNC-SUPERVISOR.1]:** + +```go +func Sequential-Supervisor () (Error) { + loop { + // get the next height + nextHeight := input(); + + // Verify + result := NoResult; + while result != ResultSuccess { + lightStore,result := VerifyToTarget(primary, lightStore, nextHeight); + if result == ResultFailure { + // pick new primary (promote a secondary to primary) + /// and delete all lightblocks above + // LastTrusted (they have not been cross-checked) + Replace_Primary(); + } + } + + // Cross-check + PoFs := Forkdetector(lightStore, PoFs); + if PoFs.Empty { + // no fork detected with secondaries, we trust the new + // lightblock + LightStore.Update(testedLB, StateTrusted); + } + else { + // there is a fork, we submit the proofs and exit + for i, p range PoFs { + SubmitProofOfFork(p); + } + return(ErrorFork); + } + } +} +``` + +**TODO:** finish conditions + +- Implementation remark +- Expected precondition + - *lightStore* initialized with trusted header + - *PoFs* empty +- Expected postcondition + - runs forever, or + - is terminated by user and satisfies LightStore invariant, or **TODO** + - has submitted proof of fork upon detecting a fork +- Error condition + - none + +---- + +# Semantics of the LightStore + +Currently, a lightblock in the lightstore can be in one of the +following states: + +- StateUnverified +- StateVerified +- StateFailed +- StateTrusted + +The intuition is that `StateVerified` captures that the lightblock has +been verified with the primary, and `StateTrusted` is the state after +successful cross-checking with the secondaries. + +Assuming there is **always one correct node among primary and +secondaries**, and there is no fork on the blockchain, lightblocks that +are in `StateTrusted` can be used by the user with the guarantee of +"finality". If a block in `StateVerified` is used, it might be that +detection later finds a fork, and a roll-back might be needed. + +**Remark:** The assumption of one correct node, does not render +verification useless. It is true that if the primary and the +secondaries return the same block we may trust it. However, if there +is a node that provides a different block, the light node still needs +verification to understand whether there is a fork, or whether the +different block is just bogus (without any support of some previous +validator set). + +**Remark:** A light node may choose the full nodes it communicates +with (the light node and the full node might even belong to the same +stakeholder) so the assumption might be justified in some cases. + +In the future, we will do the following changes + +- we assume that only from time to time, the light node is + connected to a correct full node +- this means for some limited time, the light node might have no + means to defend against light client attacks +- as a result we do not have finality +- once the light node reconnects with a correct full node, it + should detect the light client attack and submit evidence. + +Under these assumptions, `StateTrusted` loses its meaning. As a +result, it should be removed from the API. We suggest that we replace +it with a flag "trusted" that can be used + +- internally for efficiency reasons (to maintain + [LCD-INV-TRUSTED-AGREED.1] until a fork is detected) +- by light client based on the "one correct full node" assumption + +---- diff --git a/spec/light-client/detection/draft-functions.md b/spec/light-client/detection/draft-functions.md new file mode 100644 index 0000000..a53924b --- /dev/null +++ b/spec/light-client/detection/draft-functions.md @@ -0,0 +1,289 @@ +# Draft of Functions for Fork detection and Proof of Fork Submisstion + +This document collects drafts of function for generating and +submitting proof of fork in the IBC context + +- [IBC](#on-chain-ibc-component) + +- [Relayer](#relayer) + +## On-chain IBC Component + +> The following is a suggestions to change the function defined in ICS 007 + +#### [TAG-IBC-MISBEHAVIOR.1] + +```go +func checkMisbehaviorAndUpdateState(cs: ClientState, PoF: LightNodeProofOfFork) +``` + +**TODO:** finish conditions + +- Implementation remark +- Expected precondition + - PoF.TrustedBlock.Header is equal to lightBlock on store with + same height + - both traces end with header of same height + - headers are different + - both traces are supported by PoF.TrustedBlock (`supports` + defined in [CMBC-FUNC]), that is, for `t = currentTimestamp()` (see + ICS 024) + - supports(PoF.TrustedBlock, PoF.PrimaryTrace[1], t) + - supports(PoF.PrimaryTrace[i], PoF.PrimaryTrace[i+1], t) for + *0 < i < length(PoF.PrimaryTrace)* + - supports(PoF.TrustedBlock, PoF.SecondaryTrace[1], t) + - supports(PoF.SecondaryTrace[i], PoF.SecondaryTrace[i+1], t) for + *0 < i < length(PoF.SecondaryTrace)* +- Expected postcondition + - set cs.FrozenHeight to min(cs.FrozenHeight, PoF.TrustedBlock.Header.Height) +- Error condition + - none + +---- + +> The following is a suggestions to add functionality to ICS 002 and 007. +> I suppose the above is the most efficient way to get the required +> information. Another option is to subscribe to "header install" +> events via CosmosSDK + +#### [TAG-IBC-HEIGHTS.1] + +```go +func QueryHeightsRange(id, from, to) ([]Height) +``` + +- Expected postcondition + - returns all heights *h*, with *from <= h <= to* for which the + IBC component has a consensus state. + +---- + +> This function can be used if the relayer has no information about +> the IBC component. This allows late-joining relayers to also +> participate in fork dection and the generation in proof of +> fork. Alternatively, we may also postulate that relayers are not +> responsible to detect forks for heights before they started (and +> subscribed to the transactions reporting fresh headers being +> installed at the IBC component). + +## Relayer + +### Auxiliary Functions to be implemented in the Light Client + +#### [LCV-LS-FUNC-GET-PREV.1] + +```go +func (ls LightStore) GetPreviousVerified(height Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a verified LightBlock, whose height is maximal among all + verified lightblocks with height smaller than `height` + +---- + +### Relayer Submitting Proof of Fork to the IBC Component + +There are two ways the relayer can detect a fork + +- by the fork detector of one of its lightclients +- be checking the consensus state of the IBC component + +The following function ignores how the proof of fork was generated. +It takes a proof of fork as input and computes a proof of fork that + will be accepted by the IBC component. +The problem addressed here is that both, the relayer's light client + and the IBC component have incomplete light stores, that might + not have all light blocks in common. +Hence the relayer has to figure out what the IBC component knows + (intuitively, a meeting point between the two lightstores + computed in `commonRoot`) and compute a proof of fork + (`extendPoF`) that the IBC component will accept based on its + knowledge. + +The auxiliary functions `commonRoot` and `extendPoF` are +defined below. + +#### [TAG-SUBMIT-POF-IBC.1] + +```go +func SubmitIBCProofOfFork( + lightStore LightStore, + PoF: LightNodeProofOfFork, + ibc IBCComponent) (Error) { + if ibc.queryChainConsensusState(PoF.TrustedBlock.Height) = PoF.TrustedBlock { + // IBC component has root of PoF on store, we can just submit + ibc.submitMisbehaviorToClient(ibc.id,PoF) + return Success + // note sure about the id parameter + } + else { + // the ibc component does not have the TrustedBlock and might + // even be on yet a different branch. We have to compute a PoF + // that the ibc component can verifiy based on its current + // knowledge + + ibcLightBlock, lblock, _, result := commonRoot(lightStore, ibc, PoF.TrustedBlock) + + if result = Success { + newPoF = extendPoF(ibcLightBlock, lblock, lightStore, PoF) + ibc.submitMisbehaviorToClient(ibc.id, newPoF) + return Success + } + else{ + return CouldNotGeneratePoF + } + } +} +``` + +**TODO:** finish conditions + +- Implementation remark +- Expected precondition +- Expected postcondition +- Error condition + - none + +---- + +### Auxiliary Functions at the Relayer + +> If the relayer detects a fork, it has to compute a proof of fork that +> will convince the IBC component. That is it has to compare the +> relayer's local lightstore against the lightstore of the IBC +> component, and find common ancestor lightblocks. + +#### [TAG-COMMON-ROOT.1] + +```go +func commonRoot(lightStore LightStore, ibc IBCComponent, lblock +LightBlock) (LightBlock, LightBlock, LightStore, Result) { + + auxLS.Init + + // first we ask for the heights the ibc component is aware of + ibcHeights = ibc.QueryHeightsRange( + ibc.id, + lightStore.LowestVerified().Height, + lblock.Height - 1); + // this function does not exist yet. Alternatively, we may + // request all transactions that installed headers via CosmosSDK + + + for { + h, result = max(ibcHeights) + if result = Empty { + return (_, _, _, NoRoot) + } + ibcLightBlock = ibc.queryChainConsensusState(h) + auxLS.Update(ibcLightBlock, StateVerified); + connector, result := Connector(lightStore, ibcLightBlock, lblock.Header.Height) + if result = success { + return (ibcLightBlock, connector, auxLS, Success) + } + else{ + ibcHeights.remove(h) + } + } +} +``` + +- Expected postcondition + - returns + - a lightBlock b1 from the IBC component, and + - a lightBlock b2 + from the local lightStore with height less than + lblock.Header.Hight, s.t. b1 supports b2, and + - a lightstore with the blocks downloaded from + the ibc component + +---- + +#### [TAG-LS-FUNC-CONNECT.1] + +```go +func Connector (lightStore LightStore, lb LightBlock, h Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a verified LightBlock from lightStore with height less + than *h* that can be + verified by lb in one step. + +**TODO:** for the above to work we need an invariant that all verified +lightblocks form a chain of trust. Otherwise, we need a lightblock +that has a chain of trust to height. + +> Once the common root is found, a proof of fork that will be accepted +> by the IBC component needs to be generated. This is done in the +> following function. + +#### [TAG-EXTEND-POF.1] + +```go +func extendPoF (root LightBlock, + connector LightBlock, + lightStore LightStore, + Pof LightNodeProofofFork) (LightNodeProofofFork} +``` + +- Implementation remark + - PoF is not sufficient to convince an IBC component, so we extend + the proof of fork farther in the past +- Expected postcondition + - returns a newPOF: + - newPoF.TrustedBlock = root + - let prefix = + connector + + lightStore.Subtrace(connector.Header.Height, PoF.TrustedBlock.Header.Height-1) + + PoF.TrustedBlock + - newPoF.PrimaryTrace = prefix + PoF.PrimaryTrace + - newPoF.SecondaryTrace = prefix + PoF.SecondaryTrace + +### Detection a fork at the IBC component + +The following functions is assumed to be called regularly to check +that latest consensus state of the IBC component. Alternatively, this +logic can be executed whenever the relayer is informed (via an event) +that a new header has been installed. + +#### [TAG-HANDLER-DETECT-FORK.1] + +```go +func DetectIBCFork(ibc IBCComponent, lightStore LightStore) (LightNodeProofOfFork, Error) { + cs = ibc.queryClientState(ibc); + lb, found := lightStore.Get(cs.Header.Height) + if !found { + **TODO:** need verify to target + lb, result = LightClient.Main(primary, lightStore, cs.Header.Height) + // [LCV-FUNC-IBCMAIN.1] + **TODO** decide what to do following the outcome of Issue #499 + + // I guess here we have to get into the light client + + } + if cs != lb { + // IBC component disagrees with my primary. + // I fetch the + ibcLightBlock, lblock, ibcStore, result := commonRoot(lightStore, ibc, lb) + pof = new LightNodeProofOfFork; + pof.TrustedBlock := ibcLightBlock + pof.PrimaryTrace := ibcStore + cs + pof.SecondaryTrace := lightStore.Subtrace(lblock.Header.Height, + lb.Header.Height); + return(pof, Fork) + } + return(nil , NoFork) +} +``` + +**TODO:** finish conditions + +- Implementation remark + - we ask the handler for the lastest check. Cross-check with the + chain. In case they deviate we generate PoF. + - we assume IBC component is correct. It has verified the + consensus state +- Expected precondition +- Expected postcondition diff --git a/spec/light-client/detection/req-ibc-detection.md b/spec/light-client/detection/req-ibc-detection.md new file mode 100644 index 0000000..a689e0f --- /dev/null +++ b/spec/light-client/detection/req-ibc-detection.md @@ -0,0 +1,345 @@ +# Requirements for Fork Detection in the IBC Context + +## What you need to know about IBC + +In the following, I distilled what I considered relevant from + + + +### Components and their interface + +#### Cosmos Blockchains + +> I assume you know what that is. + +#### An IBC/Cosmos correspondence + +| IBC Term | Cosmos Spec Term | Comment | +|----------|-------------------------| --------| +| `CommitmentRoot` | AppState | app hash | +| `ConsensusState` | Lightblock | not all fields are there. NextValidator is definitly needed | +| `ClientState` | latest light block + configuration parameters (e.g., trusting period + `frozenHeight` | NextValidators missing; what is `proofSpecs`?| +| `frozenHeight` | height of fork | set when a fork is detected | +| "would-have-been-fooled" | light node fork detection | light node may submit proof of fork to IBC component to halt it | +| `Height` | (no epochs) | (epoch,height) pair in lexicographical order (`compare`) | +| `Header` | ~signed header | validatorSet explicit (no hash); nextValidators missing | +| `Evidence` | t.b.d. | definition unclear "which the light client would have considered valid". Data structure will need to change | +| `verify` | `ValidAndVerified` | signature does not match perfectly (ClientState vs. LightBlock) + in `checkMisbehaviorAndUpdateState` it is unclear whether it uses traces or goes to h1 and h2 in one step | + +#### Some IBC links + +- [QueryConsensusState](https://github.com/cosmos/cosmos-sdk/blob/2651427ab4c6ea9f81d26afa0211757fc76cf747/x/ibc/02-client/client/utils/utils.go#L68) + +#### Required Changes in ICS 007 + +- `assert(height > 0)` in definition of `initialize` doesn't match + definition of `Height` as *(epoch,height)* pair. + +- `initialize` needs to be updated to new data structures + +- `clientState.frozenHeight` semantics seem not totally consistent in + document. E.g., `min` needs to be defined over optional value in + `checkMisbehaviorAndUpdateState`. Also, if you are frozen, why do + you accept more evidence. + +- `checkValidityAndUpdateState` + - `verify`: it needs to be clarified that checkValidityAndUpdateState + does not perform "bisection" (as currently hinted in the text) but + performs a single step of "skipping verification", called, + `ValidAndVerified` + - `assert (header.height > clientState.latestHeight)`: no old + headers can be installed. This might be OK, but we need to check + interplay with misbehavior + - clienstState needs to be updated according to complete data + structure + +- `checkMisbehaviorAndUpdateState`: as evidence will contain a trace + (or two), the assertion that uses verify will need to change. + +- ICS 002 states w.r.t. `queryChainConsensusState` that "Note that + retrieval of past consensus states by height (as opposed to just the + current consensus state) is convenient but not required." For + Cosmos fork detection, this seems to be a necessity. + +- `Header` should become a lightblock + +- `Evidence` should become `LightNodeProofOfFork` [LCV-DATA-POF.1] + +- `upgradeClientState` what is the semantics (in particular what is + `height` doing?). + +- `checkMisbehaviorAndUpdateState(cs: ClientState, PoF: + LightNodeProofOfFork)` needs to be adapted + +#### Handler + +A blockchain runs a **handler** that passively collects information about + other blockchains. It can be thought of a state machine that takes + input events. + +- the state includes a lightstore (I guess called `ConsensusState` + in IBC) + +- The following function is used to pass a header to a handler + +```go +type checkValidityAndUpdateState = (Header) => Void +``` + + For Cosmos, it will perform + `ValidandVerified`, that is, it does the trusting period check and the + +1/3 check (+2/3 for sequential headers). + If it verifies a header, it adds it to its lightstore, + if it does not pass verification it drops it. + Right now it only accepts a header more recent then the latest + header, + and drops older + ones or ones that could not be verified. + +> The above paragraph captures what I believe what is the current + logic of `checkValidityAndUpdateState`. It may be subject to + change. E.g., maintain a lightstore with state (unverified, verified) + +- The following function is used to pass "evidence" (this we + will need to make precise eventually) to a handler + +```go +type checkMisbehaviorAndUpdateState = (bytes) => Void +``` + + We have to design this, and the data that the handler can use to + check that there was some misbehavior (fork) in order react on + it, e.g., flagging a situation and + stop the protocol. + +- The following function is used to query the light store (`ConsensusState`) + +```go +type queryChainConsensusState = (height: uint64) => ConsensusState +``` + +#### Relayer + +- The active components are called **relayer**. + +- a relayer contains light clients to two (or more?) blockchains + +- the relayer send headers and data to the handler to invoke + `checkValidityAndUpdateState` and + `checkMisbehaviorAndUpdateState`. It may also query + `queryChainConsensusState`. + +- multiple relayers may talk to one handler. Some relayers might be + faulty. We assume existence of at least single correct relayer. + +## Informal Problem Statement: Fork detection in IBC + +### Relayer requirement: Evidence for Handler + +- The relayer should provide the handler with + "evidence" that there was a fork. + +- The relayer can read the handler's consensus state. Thus the relayer can + feed the handler precisely the information the handler needs to detect a + fork. + What is this + information needs to be specified. + +- The information depends on the verification the handler does. It + might be necessary to provide a bisection proof (list of + lightblocks) so that the handler can verify based on its local + lightstore a header *h* that is conflicting with a header *h'* in the + local lightstore, that is, *h != h'* and *h.Height = h'.Height* + +### Relayer requirement: Fork detection + +Let's assume there is a fork at chain A. There are two ways the +relayer can figure that out: + +1. as the relayer contains a light client for A, it also includes a fork + detector that can detect a fork. + +2. the relayer may also detect a fork by observing that the + handler for chain A (on chain B) + is on a different branch than the relayer + +- in both detection scenarios, the relayer should submit evidence to + full nodes of chain A where there is a fork. As we assume a fullnode + has a complete list of blocks, it is sufficient to send "Bucky's + evidence" (), + that is, + - two lightblocks from different branches + + - a lightblock (perhaps just a height) from which both blocks + can be verified. + +- in the scenario 2., the relayer must feed the A-handler (on chain B) + a proof of a fork on A so that chain B can react accordingly + +### Handler requirement + +- there are potentially many relayers, some correct some faulty + +- a handler cannot trust the information provided by the relayer, + but must verify + (Доверя́й, но проверя́й) + +- in case of a fork, we accept that the handler temporarily stores + headers (tagged as verified). + +- eventually, a handler should be informed + (`checkMisbehaviorAndUpdateState`) + by some relayer that it has + verified a header from a fork. Then the handler should do what is + required by IBC in this case (stop?) + +### Challenges in the handler requirement + +- handlers and relayers work on different lightstores. In principle + the lightstore need not intersect in any heights a priori + +- if a relayer sees a header *h* it doesn't know at a handler (`queryChainConsensusState`), the + relayer needs to + verify that header. If it cannot do it locally based on downloaded + and verified (trusted?) light blocks, it might need to use + `VerifyToTarget` (bisection). To call `VerifyToTarget` we might keep + *h* in the lightstore. If verification fails, we need to download the + "alternative" header of height *h.Height* to generate evidence for + the handler. + +- we have to specify what precisely `queryChainConsensusState` + returns. It cannot be the complete lightstore. Is the last header enough? + +- we would like to assume that every now and then (smaller than the + trusting period) a correct relayer checks whether the handler is on a + different branch than the relayer. + And we would like that this is enough to achieve + the Handler requirement. + + - here the correctness argument would be easy if a correct relayer is + based on a light client with a *trusted* state, that is, a light + client who never changes its opinion about trusted. Then if such a + correct relayer checks-in with a handler, it will detect a fork, and + act in time. + + - if the light client does not provide this interface, in the case of + a fork, we need some assumption about a correct relayer being on a + different branch than the handler, and we need such a relayer to + check-in not too late. Also + what happens if the relayer's light client is forced to roll-back + its lightstore? + Does it have to re-check all handlers? + +## On the interconnectedness of things + +In the broader discussion of so-called "fork accountability" there are +several subproblems + +- Fork detection + +- Evidence creation and submission + +- Isolating misbehaving nodes (and report them for punishment over abci) + +### Fork detection + +The preliminary specification ./detection.md formalizes the notion of +a fork. Roughly, a fork exists if there are two conflicting headers +for the same height, where both are supported by bonded full nodes +(that have been validators in the near past, that is, within the +trusting period). We distinguish between *fork on the chain* where two +conflicting blocks are signed by +2/3 of the validators of that +height, and a *light client fork* where one of the conflicting headers +is not signed by +2/3 of the current height, but by +1/3 of the +validators of some smaller height. + +In principle everyone can detect a fork + +- ./detection talks about the Cosmos light client with a focus on + light nodes. A relayer runs such light clients and may detect + forks in this way + +- in IBC, a relayer can see that a handler is on a conflicting branch + - the relayer should feed the handler the necessary information so + that it can halt + - the relayer should report the fork to a full node + +### Evidence creation and submission + +- the information sent from the relayer to the handler could be called + evidence, but this is perhaps a bad idea because the information sent to a + full node can also be called evidence. But this evidence might still + not be enough as the full node might need to run the "fork + accountability" protocol to generate evidence in the form of + consensus messages. So perhaps we should + introduce different terms for: + + - proof of fork for the handler (basically consisting of lightblocks) + - proof of fork for a full node (basically consisting of (fewer) lightblocks) + - proof of misbehavior (consensus messages) + +### Isolating misbehaving nodes + +- this is the job of a full node. + +- might be subjective in the future: the protocol depends on what the + full node believes is the "correct" chain. Right now we postulate + that every full node is on the correct chain, that is, there is no + fork on the chain. + +- The full node figures out which nodes are + - lunatic + - double signing + - amnesic; **using the challenge response protocol** + +- We do not punish "phantom" validators + - currently we understand a phantom validator as a node that + - signs a block for a height in which it is not in the + validator set + - the node is not part of the +1/3 of previous validators that + are used to support the header. Whether we call a validator + phantom might be subjective and depend on the header we + check against. Their formalization actually seems not so + clear. + - they can only do something if there are +1/3 faulty validators + that are either lunatic, double signing, or amnesic. + - abci requires that we only report bonded validators. So if a + node is a "phantom", we would need the check whether the node is + bonded, which currently is expensive, as it requires checking + blocks from the last three weeks. + - in the future, with state sync, a correct node might be + convinced by faulty nodes that it is in the validator set. Then + it might appear to be "phantom" although it behaves correctly + +## Next steps + +> The following points are subject to my limited knowledge of the +> state of the work on IBC. Some/most of it might already exist and we +> will just need to bring everything together. + +- "proof of fork for a full node" defines a clean interface between + fork detection and misbehavior isolation. So it should be produced + by protocols (light client, the relayer). So we should fix that + first. + +- Given the problems of not having a light client architecture spec, + for the relayer we should start with this. E.g. + + - the relayer runs light clients for two chains + - the relayer regularly queries consensus state of a handler + - the relayer needs to check the consensus state + - this involves local checks + - this involves calling the light client + - the relayer uses the light client to do IBC business (channels, + packets, connections, etc.) + - the relayer submits proof of fork to handlers and full nodes + +> the list is definitely not complete. I think part of this +> (perhaps all) is +> covered by what Anca presented recently. + +We will need to define what we expect from these components + +- for the parts where the relayer talks to the handler, we need to fix + the interface, and what the handler does + +- we write specs for these components. diff --git a/spec/light-client/experiments.png b/spec/light-client/experiments.png new file mode 100644 index 0000000..797bb7c Binary files /dev/null and b/spec/light-client/experiments.png differ diff --git a/spec/light-client/supervisor/supervisor_001_draft.md b/spec/light-client/supervisor/supervisor_001_draft.md new file mode 100644 index 0000000..797e653 --- /dev/null +++ b/spec/light-client/supervisor/supervisor_001_draft.md @@ -0,0 +1,637 @@ +# Draft of Light Client Supervisor for discussion + +## TODOs + +This specification in done in parallel with updates on the +verification specification. So some hyperlinks have to be placed to +the correct files eventually. + +# Light Client Sequential Supervisor + +The light client implements a read operation of a +[header](CMBC-HEADER-link) from the [blockchain](CMBC-SEQ-link), by +communicating with full nodes, a so-called primary and several +so-called witnesses. As some full nodes may be faulty, this +functionality must be implemented in a fault-tolerant way. + +In a Cosmos blockchain, the validator set may change with every +new block. The staking and unbonding mechanism induces a [security +model](CMBC-FM-2THIRDS-link): starting at time *Time* of the +[header](CMBC-HEADER-link), +more than two-thirds of the next validators of a new block are correct +for the duration of *TrustedPeriod*. + +[Light Client Verification](https://informal.systems) implements the fault-tolerant read +operation designed for this security model. That is, it is safe if the +model assumptions are satisfied and makes progress if it communicates +to a correct primary. + +However, if the [security model](CMBC-FM-2THIRDS-link) is violated, +faulty peers (that have been validators at some point in the past) may +launch attacks on the Cosmos network, and on the light +client. These attacks as well as an axiomatization of blocks in +general are defined in [a document that contains the definitions that +are currently in detection.md](https://informal.systems). + +If there is a light client attack (but no +successful attack on the network), the safety of the verification step +may be violated (as we operate outside its basic assumption). +The light client also +contains a defense mechanism against light clients attacks, called detection. + +[Light Client Detection](https://informal.systems) implements a cross check of the result +of the verification step. If there is a light client attack, and the +light client is connected to a correct peer, the light client as a +whole is safe, that is, it will not operate on invalid +blocks. However, in this case it cannot successfully read, as +inconsistent blocks are in the system. However, in this case the +detection performs a distributed computation that results in so-called +evidence. Evidence can be used to prove +to a correct full node that there has been a +light client attack. + +[Light Client Evidence Accountability](https://informal.systems) is a protocol run on a +full node to check whether submitted evidence indeed proves the +existence of a light client attack. Further, from the evidence and its +own knowledge about the blockchain, the full node computes a set of +bonded full nodes (that at some point had more than one third of the +voting power) that participated in the attack that will be reported +via ABCI to the application. + +In this document we specify + +- Initialization of the Light Client +- The interaction of [verification](https://informal.systems) and [detection](https://informal.systems) + +The details of these two protocols are captured in their own +documents, as is the [accountability](https://informal.systems) protocol. + +> Another related line is IBC attack detection and submission at the +> relayer, as well as attack verification at the IBC handler. This +> will call for yet another spec. + +# Status + +This document is work in progress. In order to develop the +specification step-by-step, +it assumes certain details of [verification](https://informal.systems) and +[detection](https://informal.systems) that are not specified in the respective current +versions yet. This inconsistencies will be addresses over several +upcoming PRs. + +# Part I - Cosmos Blockchain + +See [verification spec](addLinksWhenDone) + +# Part II - Sequential Problem Definition + +#### **[LC-SEQ-INIT-LIVE.1]** + +Upon initialization, the light client gets as input a header of the +blockchain, or the genesis file of the blockchain, and eventually +stores a header of the blockchain. + +#### **[LC-SEQ-LIVE.1]** + +The light client gets a sequence of heights as inputs. For each input +height *targetHeight*, it eventually stores the header of height +*targetHeight*. + +#### **[LC-SEQ-SAFE.1]** + +The light client never stores a header which is not in the blockchain. + +# Part III - Light Client as Distributed System + +## Computational Model + +The light client communicates with remote processes only via the +[verification](TODO) and the [detection](TODO) protocols. The +respective assumptions are given there. + +## Distributed Problem Statement + +### Two Kinds of Liveness + +In case of light client attacks, the sequential problem statement +cannot always be satisfied. The lightclient cannot decide which block +is from the chain and which is not. As a result, the light client just +creates evidence, submits it, and terminates. +For the liveness property, we thus add the +possibility that instead of adding a lightblock, we also might terminate +in case there is an attack. + +#### **[LC-DIST-TERM.1]** + +The light client either runs forever or it *terminates on attack*. + +### Design choices + +#### [LC-DIST-STORE.1] + +The light client has a local data structure called LightStore +that contains light blocks (that contain a header). + +> The light store exposes functions to query and update it. They are +> specified [here](TODO:onceVerificationIsMerged). + +**TODO:** reference light store invariant [LCV-INV-LS-ROOT.2] once +verification is merged + +#### **[LC-DIST-SAFE.1]** + +It is always the case that every header in *LightStore* was +generated by an instance of Tendermint consensus. + +#### **[LC-DIST-LIVE.1]** + +Whenever the light client gets a new height *h* as input, + +- and there is +no light client attack up to height *h*, then the lightclient +eventually puts the lightblock of height *h* in the lightstore and +wait for another input. +- otherwise, that is, if there +is a light client attack on height *h*, then the light client +must perform one of the following: + - it terminates on attack. + - it eventually puts the lightblock of height *h* in the lightstore and +wait for another input. + +> Observe that the "existence of a lightclient attack" just means that some node has generated a conflicting block. It does not necessarily mean that a (faulty) peer sends such a block to "our" lightclient. Thus, even if there is an attack somewhere in the system, our lightclient might still continue to operate normally. + +### Solving the sequential specification + +[LC-DIST-SAFE.1] is guaranteed by the detector; in particular it +follows from +[[LCD-DIST-INV-STORE.1]](TODO) +[[LCD-DIST-LIVE.1]](TODO) + +# Part IV - Light Client Supervisor Protocol + +We provide a specification for a sequential Light Client Supervisor. +The local code for verification is presented by a sequential function +`Sequential-Supervisor` to highlight the control flow of this +functionality. Each lightblock is first verified with a primary, and then +cross-checked with secondaries, and if all goes well, the lightblock +is +added (with the attribute "trusted") to the +lightstore. Intermiate lightblocks that were used to verify the target +block but were not cross-checked are stored as "verified" + +> We note that if a different concurrency model is considered +> for an implementation, the semantics of the lightstore might change: +> In a concurrent implementation, we might do verification for some +> height *h*, add the +> lightblock to the lightstore, and start concurrent threads that +> +> - do verification for the next height *h' != h* +> - do cross-checking for height *h*. If we find an attack, we remove +> *h* from the lightstore. +> - the user might already start to use *h* +> +> Thus, this concurrency model changes the semantics of the +> lightstore (not all lightblocks that are read by the user are +> trusted; they may be removed if +> we find a problem). Whether this is desirable, and whether the gain in +> performance is worth it, we keep for future versions/discussion of +> lightclient protocols. + +## Definitions + +### Peers + +#### **[LC-DATA-PEERS.1]:** + +A fixed set of full nodes is provided in the configuration upon +initialization. Initially this set is partitioned into + +- one full node that is the *primary* (singleton set), +- a set *Secondaries* (of fixed size, e.g., 3), +- a set *FullNodes*; it excludes *primary* and *Secondaries* nodes. +- A set *FaultyNodes* of nodes that the light client suspects of + being faulty; it is initially empty + +#### **[LC-INV-NODES.1]:** + +The detector shall maintain the following invariants: + +- *FullNodes \intersect Secondaries = {}* +- *FullNodes \intersect FaultyNodes = {}* +- *Secondaries \intersect FaultyNodes = {}* + +and the following transition invariant + +- *FullNodes' \union Secondaries' \union FaultyNodes' = FullNodes + \union Secondaries \union FaultyNodes* + +#### **[LC-FUNC-REPLACE-PRIMARY.1]:** + +```go +Replace_Primary(root-of-trust LightBlock) +``` + +- Implementation remark + - the primary is replaced by a secondary + - to maintain a constant size of secondaries, need to + - pick a new secondary *nsec* while ensuring [LC-INV-ROOT-AGREED.1] + - that is, we need to ensure that root-of-trust = FetchLightBlock(nsec, root-of-trust.Header.Height) +- Expected precondition + - *FullNodes* is nonempty +- Expected postcondition + - *primary* is moved to *FaultyNodes* + - a secondary *s* is moved from *Secondaries* to primary +- Error condition + - if precondition is violated + +#### **[LC-FUNC-REPLACE-SECONDARY.1]:** + +```go +Replace_Secondary(addr Address, root-of-trust LightBlock) +``` + +- Implementation remark + - maintain [LC-INV-ROOT-AGREED.1], that is, + ensure root-of-trust = FetchLightBlock(nsec, root-of-trust.Header.Height) +- Expected precondition + - *FullNodes* is nonempty +- Expected postcondition + - addr is moved from *Secondaries* to *FaultyNodes* + - an address *nsec* is moved from *FullNodes* to *Secondaries* +- Error condition + - if precondition is violated + +### Data Types + +The core data structure of the protocol is the LightBlock. + +#### **[LC-DATA-LIGHTBLOCK.1]** + +```go +type LightBlock struct { + Header Header + Commit Commit + Validators ValidatorSet + NextValidators ValidatorSet + Provider PeerID +} +``` + +#### **[LC-DATA-LIGHTSTORE.1]** + +LightBlocks are stored in a structure which stores all LightBlock from +initialization or received from peers. + +```go +type LightStore struct { + ... +} + +``` + +We use the functions that the LightStore exposes, which +are defined in the [verification specification](TODO). + +### Inputs + +The lightclient is initialized with LCInitData + +#### **[LC-DATA-INIT.1]** + +```go +type LCInitData struct { + lightBlock LightBlock + genesisDoc GenesisDoc +} +``` + +where only one of the components must be provided. `GenesisDoc` is +defined in the [CometBFT +Types](https://github.com/cometbft/cometbft/blob/v0.38.x/types/genesis.go). + +#### **[LC-DATA-GENESIS.1]** + +```go +type GenesisDoc struct { + GenesisTime time.Time `json:"genesis_time"` + ChainID string `json:"chain_id"` + InitialHeight int64 `json:"initial_height"` + ConsensusParams *tmproto.ConsensusParams `json:"consensus_params,omitempty"` + Validators []GenesisValidator `json:"validators,omitempty"` + AppHash tmbytes.HexBytes `json:"app_hash"` + AppState json.RawMessage `json:"app_state,omitempty"` +} +``` + +We use the following function +`makeblock` so that we create a lightblock from the genesis +file in order to do verification based on the data from the genesis +file using the same verification function we use in normal operation. + +#### **[LC-FUNC-MAKEBLOCK.1]** + +```go +func makeblock (genesisDoc GenesisDoc) (lightBlock LightBlock)) +``` + +- Implementation remark + - none +- Expected precondition + - none +- Expected postcondition + - lightBlock.Header.Height = genesisDoc.InitialHeight + - lightBlock.Header.Time = genesisDoc.GenesisTime + - lightBlock.Header.LastBlockID = nil + - lightBlock.Header.LastCommit = nil + - lightBlock.Header.Validators = genesisDoc.Validators + - lightBlock.Header.NextValidators = genesisDoc.Validators + - lightBlock.Header.Data = nil + - lightBlock.Header.AppState = genesisDoc.AppState + - lightBlock.Header.LastResult = nil + - lightBlock.Commit = nil + - lightBlock.Validators = genesisDoc.Validators + - lightBlock.NextValidators = genesisDoc.Validators + - lightBlock.Provider = nil +- Error condition + - none + +---- + +### Configuration Parameters + +#### **[LC-INV-ROOT-AGREED.1]** + +In the Sequential-Supervisor, it is always the case that the primary +and all secondaries agree on lightStore.Latest(). + +### Assumptions + +We have to assume that the initialization data (the lightblock or the +genesis file) are consistent with the blockchain. This is subjective +initialization and it cannot be checked locally. + +### Invariants + +#### **[LC-INV-PEERLIST.1]:** + +The peer list contains a primary and a secondary. + +> If the invariant is violated, the light client does not have enough +> peers to download headers from. As a result, the light client +> needs to terminate in case this invariant is violated. + +## Supervisor + +### Outline + +The supervisor implements the functionality of the lightclient. It is +initialized with a genesis file or with a lightblock the user +trusts. This initialization is subjective, that is, the security of +the lightclient is based on the validity of the input. If the genesis +file or the lightblock deviate from the actual ones on the blockchain, +the lightclient provides no guarantees. + +After initialization, the supervisor awaits an input, that is, the +height of the next lightblock that should be obtained. Then it +downloads, verifies, and cross-checks a lightblock, and if all tests +go through, the light block (and possibly other lightblocks) are added +to the lightstore, which is returned in an output event to the user. + +The following main loop does the interaction with the user (input, +output) and calls the following two functions: + +- `InitLightClient`: it initializes the lightstore either with the + provided lightblock or with the lightblock that corresponds to the + first block generated by the blockchain (by the validators defined + by the genesis file) +- `VerifyAndDetect`: takes as input a lightstore and a height and + returns the updated lightstore. + +#### **[LC-FUNC-SUPERVISOR.1]:** + +```go +func Sequential-Supervisor (initdata LCInitData) (Error) { + + lightStore,result := InitLightClient(initData); + if result != OK { + return result; + } + + loop { + // get the next height + nextHeight := input(); + + lightStore,result := VerifyAndDetect(lightStore, nextHeight); + + if result == OK { + output(LightStore.Get(targetHeight)); + // we only output a trusted lightblock + } + else { + return result + } + // QUESTION: is it OK to generate output event in normal case, + // and terminate with failure in the (light client) attack case? + } +} +``` + +- Implementation remark + - infinite loop unless a light client attack is detected + - In typical implementations (e.g., the one in Rust), + there are mutliple input actions: + `VerifytoLatest`, `LatestTrusted`, and `GetStatus`. The + information can be easily obtained from the lightstore, so that + we do not treat these requests explicitly here but just consider + the request for a block of a given height which requires more + involved computation and communication. +- Expected precondition + - *LCInitData* contains a genesis file or a lightblock. +- Expected postcondition + - if a light client attack is detected: it stops and submits + evidence (in `InitLightClient` or `VerifyAndDetect`) + - otherwise: non. It runs forever. +- Invariant: *lightStore* contains trusted lightblocks only. +- Error condition + - if `InitLightClient` or `VerifyAndDetect` fails (if a attack is + detected, or if [LCV-INV-TP.1] is violated) + +---- + +### Details of the Functions + +#### Initialization + +The light client is based on subjective initialization. It has to +trust the initial data given to it by the user. It cannot do any +detection of attack. So either upon initialization we obtain a +lightblock and just initialize the lightstore with it. Or in case of a +genesis file, we download, verify, and cross-check the first block, to +initialize the lightstore with this first block. The reason is that +we want to maintain [LCV-INV-TP.1] from the beginning. + +> If the lightclient is initialized with a lightblock, one might think +> it may increase trust, when one cross-checks the initial light +> block. However, if a peer provides a conflicting +> lightblock, the question is to distinguish the case of a +> [bogus](https://informal.systems) block (upon which operation should proceed) from a +> [light client attack](https://informal.systems) (upon which operation should stop). In +> case of a bogus block, the lightclient might be forced to do +> backwards verification until the blocks are out of the trusting +> period, to make sure no previous validator set could have generated +> the bogus block, which effectively opens up a DoS attack on the lightclient +> without adding effective robustness. + +#### **[LC-FUNC-INIT.1]:** + +```go +func InitLightClient (initData LCInitData) (LightStore, Error) { + + if LCInitData.LightBlock != nil { + // we trust the provided initial block. + newblock := LCInitData.LightBlock + } + else { + genesisBlock := makeblock(initData.genesisDoc); + + result := NoResult; + while result != ResultSuccess { + current = FetchLightBlock(PeerList.primary(), genesisBlock.Header.Height + 1) + // QUESTION: is the height with "+1" OK? + + if CANNOT_VERIFY = ValidAndVerify(genesisBlock, current) { + Replace_Primary(); + } + else { + result = ResultSuccess + } + } + + // cross-check + auxLS := new LightStore + auxLS.Add(current) + Evidences := AttackDetector(genesisBlock, auxLS) + if Evidences.Empty { + newBlock := current + } + else { + // [LC-SUMBIT-EVIDENCE.1] + submitEvidence(Evidences); + return(nil, ErrorAttack); + } + } + + lightStore := new LightStore; + lightStore.Add(newBlock); + return (lightStore, OK); +} + +``` + +- Implementation remark + - none +- Expected precondition + - *LCInitData* contains either a genesis file of a lightblock + - if genesis it passes `ValidateAndComplete()` see [CometBFT](https://informal.systems) +- Expected postcondition + - *lightStore* initialized with trusted lightblock. It has either been + cross-checked (from genesis) or it has initial trust from the + user. +- Error condition + - if precondition is violated + - empty peerList + +---- + +#### Main verification and detection logic + +#### **[LC-FUNC-MAIN-VERIF-DETECT.1]:** + +```go +func VerifyAndDetect (lightStore LightStore, targetHeight Height) + (LightStore, Result) { + + b1, r1 = lightStore.Get(targetHeight) + if r1 == true { + if b1.State == StateTrusted { + // block already there and trusted + return (lightStore, ResultSuccess) + } + else { + // We have a lightblock in the store, but it has not been + // cross-checked by now. We do that now. + root_of_trust, auxLS := lightstore.TraceTo(b1); + + // Cross-check + Evidences := AttackDetector(root_of_trust, auxLS); + if Evidences.Empty { + // no attack detected, we trust the new lightblock + lightStore.Update(auxLS.Latest(), + StateTrusted, + verfiedLS.Latest().verification-root); + return (lightStore, OK); + } + else { + // there is an attack, we exit + submitEvidence(Evidences); + return(lightStore, ErrorAttack); + } + } + } + + // get the lightblock with maximum height smaller than targetHeight + // would typically be the heighest, if we always move forward + root_of_trust, r2 = lightStore.LatestPrevious(targetHeight); + + if r2 = false { + // there is no lightblock from which we can do forward + // (skipping) verification. Thus we have to go backwards. + // No cross-check needed. We trust hashes. Therefore, we + // directly return the result + return Backwards(primary, lightStore.Lowest(), targetHeight) + } + else { + // Forward verification + detection + result := NoResult; + while result != ResultSuccess { + verifiedLS,result := VerifyToTarget(primary, + root_of_trust, + nextHeight); + if result == ResultFailure { + // pick new primary (promote a secondary to primary) + Replace_Primary(root_of_trust); + } + else if result == ResultExpired { + return (lightStore, result) + } + } + + // Cross-check + Evidences := AttackDetector(root_of_trust, verifiedLS); + if Evidences.Empty { + // no attack detected, we trust the new lightblock + verifiedLS.Update(verfiedLS.Latest(), + StateTrusted, + verfiedLS.Latest().verification-root); + lightStore.store_chain(verifidLS); + return (lightStore, OK); + } + else { + // there is an attack, we exit + return(lightStore, ErrorAttack); + } + } +} +``` + +- Implementation remark + - none +- Expected precondition + - none +- Expected postcondition + - lightblock of height *targetHeight* (and possibly additional blocks) added to *lightStore* +- Error condition + - an attack is detected + - [LC-DATA-PEERLIST-INV.1] is violated + +---- diff --git a/spec/light-client/supervisor/supervisor_001_draft.tla b/spec/light-client/supervisor/supervisor_001_draft.tla new file mode 100644 index 0000000..9627e28 --- /dev/null +++ b/spec/light-client/supervisor/supervisor_001_draft.tla @@ -0,0 +1,71 @@ +------------------------- MODULE supervisor_001_draft ------------------------ +(* +This is the beginning of a spec that will eventually use verification and detector API +*) + +EXTENDS Integers, FiniteSets + +VARIABLES + state, + output + +vars == <> + +CONSTANT + INITDATA + +Init == + /\ state = "Init" + /\ output = "none" + +NextInit == + /\ state = "Init" + /\ \/ state' = "EnterLoop" + \/ state' = "FailedToInitialize" + /\ UNCHANGED output + +NextVerifyToTarget == + /\ state = "EnterLoop" + /\ \/ state' = "EnterLoop" \* replace primary + \/ state' = "EnterDetect" + \/ state' = "ExhaustedPeersPrimary" + /\ UNCHANGED output + +NextAttackDetector == + /\ state = "EnterDetect" + /\ \/ state' = "NoEvidence" + \/ state' = "EvidenceFound" + \/ state' = "ExhaustedPeersSecondaries" + /\ UNCHANGED output + +NextVerifyAndDetect == + \/ NextVerifyToTarget + \/ NextAttackDetector + +NextOutput == + /\ state = "NoEvidence" + /\ state' = "EnterLoop" + /\ output' = "data" \* to generate a trace + +NextTerminated == + /\ \/ state = "FailedToInitialize" + \/ state = "ExhaustedPeersPrimary" + \/ state = "EvidenceFound" + \/ state = "ExhaustedPeersSecondaries" + /\ UNCHANGED vars + +Next == + \/ NextInit + \/ NextVerifyAndDetect + \/ NextOutput + \/ NextTerminated + +InvEnoughPeers == + /\ state /= "ExhaustedPeersPrimary" + /\ state /= "ExhaustedPeersSecondaries" + + +============================================================================= +\* Modification History +\* Last modified Sun Oct 18 11:48:45 CEST 2020 by widder +\* Created Sun Oct 18 11:18:53 CEST 2020 by widder diff --git a/spec/light-client/supervisor/supervisor_002_draft.md b/spec/light-client/supervisor/supervisor_002_draft.md new file mode 100644 index 0000000..3f35344 --- /dev/null +++ b/spec/light-client/supervisor/supervisor_002_draft.md @@ -0,0 +1,131 @@ +# Draft of Light Client Supervisor for discussion + +## Modification to the initialization + +The lightclient is initialized with LCInitData + +### **[LC-DATA-INIT.2]** + +```go +type LCInitData struct { + TrustedBlock LightBlock + Genesis GenesisDoc + TrustedHash []byte + TrustedHeight int64 +} +``` + +where only one of the components must be provided. `GenesisDoc` is +defined in the [CometBFT +Types](https://github.com/cometbft/cometbft/blob/v0.38.x/types/genesis.go). + + +### Initialization + +The light client is based on subjective initialization. It has to +trust the initial data given to it by the user. It cannot perform any +detection of an attack yet instead requires an initial point of trust. +There are three forms of initial data which are used to obtain the +first trusted block: + +- A trusted block from a prior initialization +- A trusted height and hash +- A genesis file + +The golang light client implementation checks this initial data in that +order; first attempting to find a trusted block from the trusted store, +then acquiring a light block from the primary at the trusted height and matching +the hash, or finally checking for a genesis file to verify the initial header. + +The light client doesn't need to check if the trusted block is within the +trusted period because it already trusts it, however, if the light block is +outside the trust period, there is a higher chance the light client won't be +able to verify anything. + +Cross-checking this trusted block with providers upon initialization is helpful +for ensuring that the node is responsive and correctly configured but does not +increase trust since proving a conflicting block is a +[light client attack](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#cmbc-lc-attack1) +and not just a [bogus](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_003_reviewed.md#cmbc-bogus1) block could result in +performing backwards verification beyond the trusted period, thus a fruitless +endeavour. + +However, with the notion of it's better to fail earlier than later, the golang +light client implementation will perform a consistency check on all providers +and will error if one returns a different header, allowing the user +the opportunity to reinitialize. + +#### **[LC-FUNC-INIT.2]:** + +```go +func InitLightClient(initData LCInitData) (LightStore, Error) { + var initialBlock LightBlock + + switch { + case LCInitData.TrustedBlock != nil: + // we trust the block from a prior initialization + initialBlock = LCInitData.TrustedBlock + + case LCInitData.TrustedHash != nil: + untrustedBlock := FetchLightBlock(PeerList.Primary(), LCInitData.TrustedHeight) + + + // verify that the hashes match + if untrustedBlock.Hash() != LCInitData.TrustedHash { + return nil, Error("Primary returned block with different hash") + } + // after checking the hash we now trust the block + initialBlock = untrustedBlock + } + case LCInitData.Genesis != nil: + untrustedBlock := FetchLightBlock(PeerList.Primary(), LCInitData.Genesis.InitialHeight) + + // verify that 2/3+ of the validator set signed the untrustedBlock + if err := VerifyCommitFull(untrustedBlock.Commit, LCInitData.Genesis.Validators); err != nil { + return nil, err + } + + // we can now trust the block + initialBlock = untrustedBlock + default: + return nil, Error("No initial data was provided") + + // This is done in the golang version but is optional and not strictly part of the protocol + if err := CrossCheck(initialBlock, PeerList.Witnesses()); err != nil { + return nil, err + } + + // initialize light store + lightStore := new LightStore; + lightStore.Add(newBlock); + return (lightStore, OK); +} + +func CrossCheck(lb LightBlock, witnesses []Provider) error { + for _, witness := range witnesses { + witnessBlock := FetchLightBlock(witness, lb.Height) + + if witnessBlock.Hash() != lb.Hash() { + return Error("Witness has different block") + } + } + return OK +} + +``` + +- Implementation remark + - none +- Expected precondition + - *LCInitData* contains either a genesis file of a lightblock + - if genesis it passes `ValidateAndComplete()` see [CometBFT](https://informal.systems) +- Expected postcondition + - *lightStore* initialized with trusted lightblock. It has either been + cross-checked (from genesis) or it has initial trust from the + user. +- Error condition + - if precondition is violated + - empty peerList + +---- + diff --git a/spec/light-client/verification/001bmc-apalache.csv b/spec/light-client/verification/001bmc-apalache.csv new file mode 100644 index 0000000..e75e087 --- /dev/null +++ b/spec/light-client/verification/001bmc-apalache.csv @@ -0,0 +1,49 @@ +no,filename,tool,timeout,init,inv,next,args +1,MC4_3_correct.tla,apalache,1h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +2,MC4_3_correct.tla,apalache,1h,,CorrectnessInv,,--length=30 +3,MC4_3_correct.tla,apalache,1h,,PrecisionInv,,--length=30 +4,MC4_3_correct.tla,apalache,1h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +5,MC4_3_correct.tla,apalache,1h,,NoFailedBlocksOnSuccessInv,,--length=30 +6,MC4_3_correct.tla,apalache,1h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +7,MC4_3_correct.tla,apalache,1h,,CorrectPrimaryAndTimeliness,,--length=30 +8,MC4_3_correct.tla,apalache,1h,,Complexity,,--length=30 +9,MC4_3_faulty.tla,apalache,1h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +10,MC4_3_faulty.tla,apalache,1h,,CorrectnessInv,,--length=30 +11,MC4_3_faulty.tla,apalache,1h,,PrecisionInv,,--length=30 +12,MC4_3_faulty.tla,apalache,1h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +13,MC4_3_faulty.tla,apalache,1h,,NoFailedBlocksOnSuccessInv,,--length=30 +14,MC4_3_faulty.tla,apalache,1h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +15,MC4_3_faulty.tla,apalache,1h,,CorrectPrimaryAndTimeliness,,--length=30 +16,MC4_3_faulty.tla,apalache,1h,,Complexity,,--length=30 +17,MC5_5_correct.tla,apalache,1h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +18,MC5_5_correct.tla,apalache,1h,,CorrectnessInv,,--length=30 +19,MC5_5_correct.tla,apalache,1h,,PrecisionInv,,--length=30 +20,MC5_5_correct.tla,apalache,1h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +21,MC5_5_correct.tla,apalache,1h,,NoFailedBlocksOnSuccessInv,,--length=30 +22,MC5_5_correct.tla,apalache,1h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +23,MC5_5_correct.tla,apalache,1h,,CorrectPrimaryAndTimeliness,,--length=30 +24,MC5_5_correct.tla,apalache,1h,,Complexity,,--length=30 +25,MC5_5_faulty.tla,apalache,1h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +26,MC5_5_faulty.tla,apalache,1h,,CorrectnessInv,,--length=30 +27,MC5_5_faulty.tla,apalache,1h,,PrecisionInv,,--length=30 +28,MC5_5_faulty.tla,apalache,1h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +29,MC5_5_faulty.tla,apalache,1h,,NoFailedBlocksOnSuccessInv,,--length=30 +30,MC5_5_faulty.tla,apalache,1h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +31,MC5_5_faulty.tla,apalache,1h,,CorrectPrimaryAndTimeliness,,--length=30 +32,MC5_5_faulty.tla,apalache,1h,,Complexity,,--length=30 +33,MC7_5_faulty.tla,apalache,10h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +34,MC7_5_faulty.tla,apalache,10h,,CorrectnessInv,,--length=30 +35,MC7_5_faulty.tla,apalache,10h,,PrecisionInv,,--length=30 +36,MC7_5_faulty.tla,apalache,10h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +37,MC7_5_faulty.tla,apalache,10h,,NoFailedBlocksOnSuccessInv,,--length=30 +38,MC7_5_faulty.tla,apalache,10h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +39,MC7_5_faulty.tla,apalache,10h,,CorrectPrimaryAndTimeliness,,--length=30 +40,MC7_5_faulty.tla,apalache,10h,,Complexity,,--length=30 +41,MC4_7_faulty.tla,apalache,10h,,PositiveBeforeTrustedHeaderExpires,,--length=30 +42,MC4_7_faulty.tla,apalache,10h,,CorrectnessInv,,--length=30 +43,MC4_7_faulty.tla,apalache,10h,,PrecisionInv,,--length=30 +44,MC4_7_faulty.tla,apalache,10h,,SuccessOnCorrectPrimaryAndChainOfTrust,,--length=30 +45,MC4_7_faulty.tla,apalache,10h,,NoFailedBlocksOnSuccessInv,,--length=30 +46,MC4_7_faulty.tla,apalache,10h,,StoredHeadersAreVerifiedOrNotTrustedInv,,--length=30 +47,MC4_7_faulty.tla,apalache,10h,,CorrectPrimaryAndTimeliness,,--length=30 +48,MC4_7_faulty.tla,apalache,10h,,Complexity,,--length=30 diff --git a/spec/light-client/verification/002bmc-apalache-ok.csv b/spec/light-client/verification/002bmc-apalache-ok.csv new file mode 100644 index 0000000..49c879f --- /dev/null +++ b/spec/light-client/verification/002bmc-apalache-ok.csv @@ -0,0 +1,55 @@ +no;filename;tool;timeout;init;inv;next;args +1;MC4_3_correct.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=5 +2;MC4_3_correct.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=5 +3;MC4_3_correct.tla;apalache;1h;;CorrectnessInv;;--length=5 +4;MC4_3_correct.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=5 +5;MC4_3_correct.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=5 +6;MC4_3_correct.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=5 +7;MC4_3_correct.tla;apalache;1h;;Complexity;;--length=5 +8;MC4_3_correct.tla;apalache;1h;;ApiPostInv;;--length=5 +9;MC4_4_correct.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=7 +10;MC4_4_correct.tla;apalache;1h;;CorrectnessInv;;--length=7 +11;MC4_4_correct.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=7 +12;MC4_4_correct.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=7 +13;MC4_4_correct.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=7 +14;MC4_4_correct.tla;apalache;1h;;Complexity;;--length=7 +15;MC4_4_correct.tla;apalache;1h;;ApiPostInv;;--length=7 +16;MC4_5_correct.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=11 +17;MC4_5_correct.tla;apalache;1h;;CorrectnessInv;;--length=11 +18;MC4_5_correct.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=11 +19;MC4_5_correct.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=11 +20;MC4_5_correct.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=11 +21;MC4_5_correct.tla;apalache;1h;;Complexity;;--length=11 +22;MC4_5_correct.tla;apalache;1h;;ApiPostInv;;--length=11 +23;MC5_5_correct.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=11 +24;MC5_5_correct.tla;apalache;1h;;CorrectnessInv;;--length=11 +25;MC5_5_correct.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=11 +26;MC5_5_correct.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=11 +27;MC5_5_correct.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=11 +28;MC5_5_correct.tla;apalache;1h;;Complexity;;--length=11 +29;MC5_5_correct.tla;apalache;1h;;ApiPostInv;;--length=11 +30;MC4_3_faulty.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=5 +31;MC4_3_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=5 +32;MC4_3_faulty.tla;apalache;1h;;CorrectnessInv;;--length=5 +33;MC4_3_faulty.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=5 +34;MC4_3_faulty.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=5 +35;MC4_3_faulty.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=5 +36;MC4_3_faulty.tla;apalache;1h;;Complexity;;--length=5 +37;MC4_3_faulty.tla;apalache;1h;;ApiPostInv;;--length=5 +38;MC4_4_faulty.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=7 +39;MC4_4_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=7 +40;MC4_4_faulty.tla;apalache;1h;;CorrectnessInv;;--length=7 +41;MC4_4_faulty.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=7 +42;MC4_4_faulty.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=7 +43;MC4_4_faulty.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=7 +44;MC4_4_faulty.tla;apalache;1h;;Complexity;;--length=7 +45;MC4_4_faulty.tla;apalache;1h;;ApiPostInv;;--length=7 +46;MC4_5_faulty.tla;apalache;1h;;TargetHeightOnSuccessInv;;--length=11 +47;MC4_5_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=11 +48;MC4_5_faulty.tla;apalache;1h;;CorrectnessInv;;--length=11 +49;MC4_5_faulty.tla;apalache;1h;;NoTrustOnFaultyBlockInv;;--length=11 +50;MC4_5_faulty.tla;apalache;1h;;ProofOfChainOfTrustInv;;--length=11 +51;MC4_5_faulty.tla;apalache;1h;;NoFailedBlocksOnSuccessInv;;--length=11 +52;MC4_5_faulty.tla;apalache;1h;;Complexity;;--length=11 +53;MC4_5_faulty.tla;apalache;1h;;ApiPostInv;;--length=11 + diff --git a/spec/light-client/verification/003bmc-apalache-error.csv b/spec/light-client/verification/003bmc-apalache-error.csv new file mode 100644 index 0000000..afc9eb6 --- /dev/null +++ b/spec/light-client/verification/003bmc-apalache-error.csv @@ -0,0 +1,45 @@ +no;filename;tool;timeout;init;inv;next;args +1;MC4_3_correct.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=5 +2;MC4_3_correct.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=5 +3;MC4_3_correct.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=5 +4;MC4_3_correct.tla;apalache;1h;;PrecisionInv;;--length=5 +5;MC4_3_correct.tla;apalache;1h;;PrecisionBuggyInv;;--length=5 +6;MC4_3_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=5 +7;MC4_3_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=5 +8;MC4_4_correct.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=7 +9;MC4_4_correct.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=7 +10;MC4_4_correct.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=7 +11;MC4_4_correct.tla;apalache;1h;;PrecisionInv;;--length=7 +12;MC4_4_correct.tla;apalache;1h;;PrecisionBuggyInv;;--length=7 +13;MC4_4_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=7 +14;MC4_4_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=7 +15;MC4_5_correct.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=11 +16;MC4_5_correct.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=11 +17;MC4_5_correct.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=11 +18;MC4_5_correct.tla;apalache;1h;;PrecisionInv;;--length=11 +19;MC4_5_correct.tla;apalache;1h;;PrecisionBuggyInv;;--length=11 +20;MC4_5_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=11 +21;MC4_5_correct.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=11 +22;MC4_5_correct.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=11 +23;MC4_3_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=5 +24;MC4_3_faulty.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=5 +25;MC4_3_faulty.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=5 +26;MC4_3_faulty.tla;apalache;1h;;PrecisionInv;;--length=5 +27;MC4_3_faulty.tla;apalache;1h;;PrecisionBuggyInv;;--length=5 +28;MC4_3_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=5 +29;MC4_3_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=5 +30;MC4_4_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=7 +31;MC4_4_faulty.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=7 +32;MC4_4_faulty.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=7 +33;MC4_4_faulty.tla;apalache;1h;;PrecisionInv;;--length=7 +34;MC4_4_faulty.tla;apalache;1h;;PrecisionBuggyInv;;--length=7 +35;MC4_4_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=7 +36;MC4_4_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=7 +37;MC4_5_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedInv;;--length=11 +38;MC4_5_faulty.tla;apalache;1h;;PositiveBeforeTrustedHeaderExpires;;--length=11 +39;MC4_5_faulty.tla;apalache;1h;;CorrectPrimaryAndTimeliness;;--length=11 +40;MC4_5_faulty.tla;apalache;1h;;PrecisionInv;;--length=11 +41;MC4_5_faulty.tla;apalache;1h;;PrecisionBuggyInv;;--length=11 +42;MC4_5_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustGlobal;;--length=11 +43;MC4_5_faulty.tla;apalache;1h;;SuccessOnCorrectPrimaryAndChainOfTrustLocal;;--length=11 +44;MC4_5_faulty.tla;apalache;1h;;StoredHeadersAreVerifiedOrNotTrustedInv;;--length=11 diff --git a/spec/light-client/verification/004bmc-apalache-ok.csv b/spec/light-client/verification/004bmc-apalache-ok.csv new file mode 100644 index 0000000..ad526fa --- /dev/null +++ b/spec/light-client/verification/004bmc-apalache-ok.csv @@ -0,0 +1,10 @@ +no;filename;tool;timeout;init;inv;next;args +1;LCD_MC3_3_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +2;LCD_MC3_3_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +3;LCD_MC3_3_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 +4;LCD_MC3_4_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +5;LCD_MC3_4_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +6;LCD_MC3_4_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 +7;LCD_MC4_4_faulty.tla;apalache;1h;;CommonHeightOnEvidenceInv;;--length=10 +8;LCD_MC4_4_faulty.tla;apalache;1h;;AccuracyInv;;--length=10 +9;LCD_MC4_4_faulty.tla;apalache;1h;;PrecisionInvLocal;;--length=10 diff --git a/spec/light-client/verification/005bmc-apalache-error.csv b/spec/light-client/verification/005bmc-apalache-error.csv new file mode 100644 index 0000000..65d03f8 --- /dev/null +++ b/spec/light-client/verification/005bmc-apalache-error.csv @@ -0,0 +1,4 @@ +no;filename;tool;timeout;init;inv;next;args +1;LCD_MC3_3_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 +2;LCD_MC3_4_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 +3;LCD_MC4_4_faulty.tla;apalache;1h;;PrecisionInvGrayZone;;--length=10 diff --git a/spec/light-client/verification/Blockchain_002_draft.tla b/spec/light-client/verification/Blockchain_002_draft.tla new file mode 100644 index 0000000..4b2e1df --- /dev/null +++ b/spec/light-client/verification/Blockchain_002_draft.tla @@ -0,0 +1,171 @@ +------------------------ MODULE Blockchain_002_draft ----------------------------- +(* + This is a high-level specification of a Cosmos blockchain + that is designed specifically for the light client. + Validators have the voting power of one. If you like to model various + voting powers, introduce multiple copies of the same validator + (do not forget to give them unique names though). + *) +EXTENDS Integers, FiniteSets + +Min(a, b) == IF a < b THEN a ELSE b + +CONSTANT + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + ULTIMATE_HEIGHT, + (* a maximal height that can be ever reached (modelling artifact) *) + TRUSTING_PERIOD + (* the period within which the validators are trusted *) + +Heights == 1..ULTIMATE_HEIGHT (* possible heights *) + +(* A commit is just a set of nodes who have committed the block *) +Commits == SUBSET AllNodes + +(* The set of all block headers that can be on the blockchain. + This is a simplified version of the Block data structure in the actual implementation. *) +BlockHeaders == [ + height: Heights, + \* the block height + time: Int, + \* the block timestamp in some integer units + lastCommit: Commits, + \* the nodes who have voted on the previous block, the set itself instead of a hash + (* in the implementation, only the hashes of V and NextV are stored in a block, + as V and NextV are stored in the application state *) + VS: SUBSET AllNodes, + \* the validators of this bloc. We store the validators instead of the hash. + NextVS: SUBSET AllNodes + \* the validators of the next block. We store the next validators instead of the hash. +] + +(* A signed header is just a header together with a set of commits *) +LightBlocks == [header: BlockHeaders, Commits: Commits] + +VARIABLES + now, + (* the current global time in integer units *) + blockchain, + (* A sequence of BlockHeaders, which gives us a bird view of the blockchain. *) + Faulty + (* A set of faulty nodes, which can act as validators. We assume that the set + of faulty processes is non-decreasing. If a process has recovered, it should + connect using a different id. *) + +(* all variables, to be used with UNCHANGED *) +vars == <> + +(* The set of all correct nodes in a state *) +Corr == AllNodes \ Faulty + +(* APALACHE annotations *) +a <: b == a \* type annotation + +NT == STRING +NodeSet(S) == S <: {NT} +EmptyNodeSet == NodeSet({}) + +BT == [height |-> Int, time |-> Int, lastCommit |-> {NT}, VS |-> {NT}, NextVS |-> {NT}] + +LBT == [header |-> BT, Commits |-> {NT}] +(* end of APALACHE annotations *) + +(****************************** BLOCKCHAIN ************************************) + +(* the header is still within the trusting period *) +InTrustingPeriod(header) == + now < header.time + TRUSTING_PERIOD + +(* + Given a function pVotingPower \in D -> Powers for some D \subseteq AllNodes + and pNodes \subseteq D, test whether the set pNodes \subseteq AllNodes has + more than 2/3 of voting power among the nodes in D. + *) +TwoThirds(pVS, pNodes) == + LET TP == Cardinality(pVS) + SP == Cardinality(pVS \intersect pNodes) + IN + 3 * SP > 2 * TP \* when thinking in real numbers, not integers: SP > 2.0 / 3.0 * TP + +(* + Given a set of FaultyNodes, test whether the voting power of the correct nodes in D + is more than 2/3 of the voting power of the faulty nodes in D. + *) +IsCorrectPower(pFaultyNodes, pVS) == + LET FN == pFaultyNodes \intersect pVS \* faulty nodes in pNodes + CN == pVS \ pFaultyNodes \* correct nodes in pNodes + CP == Cardinality(CN) \* power of the correct nodes + FP == Cardinality(FN) \* power of the faulty nodes + IN + \* CP + FP = TP is the total voting power, so we write CP > 2.0 / 3 * TP as follows: + CP > 2 * FP \* Note: when FP = 0, this implies CP > 0. + +(* This is what we believe is the assumption about failures in Cosmos *) +FaultAssumption(pFaultyNodes, pNow, pBlockchain) == + \A h \in Heights: + pBlockchain[h].time + TRUSTING_PERIOD > pNow => + IsCorrectPower(pFaultyNodes, pBlockchain[h].NextVS) + +(* Can a block be produced by a correct peer, or an authenticated Byzantine peer *) +IsLightBlockAllowedByDigitalSignatures(ht, block) == + \/ block.header = blockchain[ht] \* signed by correct and faulty (maybe) + \/ block.Commits \subseteq Faulty /\ block.header.height = ht /\ block.header.time >= 0 \* signed only by faulty + +(* + Initialize the blockchain to the ultimate height right in the initial states. + We pick the faulty validators statically, but that should not affect the light client. + *) +InitToHeight == + /\ Faulty \in SUBSET AllNodes \* some nodes may fail + \* pick the validator sets and last commits + /\ \E vs, lastCommit \in [Heights -> SUBSET AllNodes]: + \E timestamp \in [Heights -> Int]: + \* now is at least as early as the timestamp in the last block + /\ \E tm \in Int: now = tm /\ tm >= timestamp[ULTIMATE_HEIGHT] + \* the genesis starts on day 1 + /\ timestamp[1] = 1 + /\ vs[1] = AllNodes + /\ lastCommit[1] = EmptyNodeSet + /\ \A h \in Heights \ {1}: + /\ lastCommit[h] \subseteq vs[h - 1] \* the non-validators cannot commit + /\ TwoThirds(vs[h - 1], lastCommit[h]) \* the commit has >2/3 of validator votes + /\ IsCorrectPower(Faulty, vs[h]) \* the correct validators have >2/3 of power + /\ timestamp[h] > timestamp[h - 1] \* the time grows monotonically + /\ timestamp[h] < timestamp[h - 1] + TRUSTING_PERIOD \* but not too fast + \* form the block chain out of validator sets and commits (this makes apalache faster) + /\ blockchain = [h \in Heights |-> + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> IF h < ULTIMATE_HEIGHT THEN vs[h + 1] ELSE AllNodes, + lastCommit |-> lastCommit[h]] + ] \****** + + +(* is the blockchain in the faulty zone where the Cosmos security model does not apply *) +InFaultyZone == + ~FaultAssumption(Faulty, now, blockchain) + +(********************* BLOCKCHAIN ACTIONS ********************************) +(* + Advance the clock by zero or more time units. + *) +AdvanceTime == + \E tm \in Int: tm >= now /\ now' = tm + /\ UNCHANGED <> + +(* + One more process fails. As a result, the blockchain may move into the faulty zone. + The light client is not using this action, as the faults are picked in the initial state. + However, this action may be useful when reasoning about fork detection. + *) +OneMoreFault == + /\ \E n \in AllNodes \ Faulty: + /\ Faulty' = Faulty \cup {n} + /\ Faulty' /= AllNodes \* at least process remains non-faulty + /\ UNCHANGED <> +============================================================================= +\* Modification History +\* Last modified Wed Jun 10 14:10:54 CEST 2020 by igor +\* Created Fri Oct 11 15:45:11 CEST 2019 by igor diff --git a/spec/light-client/verification/Blockchain_003_draft.tla b/spec/light-client/verification/Blockchain_003_draft.tla new file mode 100644 index 0000000..d5d3c56 --- /dev/null +++ b/spec/light-client/verification/Blockchain_003_draft.tla @@ -0,0 +1,164 @@ +------------------------ MODULE Blockchain_003_draft ----------------------------- +(* + This is a high-level specification of a Cosmos blockchain + that is designed specifically for the light client. + Validators have the voting power of one. If you like to model various + voting powers, introduce multiple copies of the same validator + (do not forget to give them unique names though). + *) +EXTENDS Integers, FiniteSets + +Min(a, b) == IF a < b THEN a ELSE b + +CONSTANT + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + ULTIMATE_HEIGHT, + (* a maximal height that can be ever reached (modelling artifact) *) + TRUSTING_PERIOD + (* the period within which the validators are trusted *) + +Heights == 1..ULTIMATE_HEIGHT (* possible heights *) + +(* A commit is just a set of nodes who have committed the block *) +Commits == SUBSET AllNodes + +(* The set of all block headers that can be on the blockchain. + This is a simplified version of the Block data structure in the actual implementation. *) +BlockHeaders == [ + height: Heights, + \* the block height + time: Int, + \* the block timestamp in some integer units + lastCommit: Commits, + \* the nodes who have voted on the previous block, the set itself instead of a hash + (* in the implementation, only the hashes of V and NextV are stored in a block, + as V and NextV are stored in the application state *) + VS: SUBSET AllNodes, + \* the validators of this bloc. We store the validators instead of the hash. + NextVS: SUBSET AllNodes + \* the validators of the next block. We store the next validators instead of the hash. +] + +(* A signed header is just a header together with a set of commits *) +LightBlocks == [header: BlockHeaders, Commits: Commits] + +VARIABLES + refClock, + (* the current global time in integer units as perceived by the reference chain *) + blockchain, + (* A sequence of BlockHeaders, which gives us a bird view of the blockchain. *) + Faulty + (* A set of faulty nodes, which can act as validators. We assume that the set + of faulty processes is non-decreasing. If a process has recovered, it should + connect using a different id. *) + +(* all variables, to be used with UNCHANGED *) +vars == <> + +(* The set of all correct nodes in a state *) +Corr == AllNodes \ Faulty + +(* APALACHE annotations *) +a <: b == a \* type annotation + +NT == STRING +NodeSet(S) == S <: {NT} +EmptyNodeSet == NodeSet({}) + +BT == [height |-> Int, time |-> Int, lastCommit |-> {NT}, VS |-> {NT}, NextVS |-> {NT}] + +LBT == [header |-> BT, Commits |-> {NT}] +(* end of APALACHE annotations *) + +(****************************** BLOCKCHAIN ************************************) + +(* the header is still within the trusting period *) +InTrustingPeriod(header) == + refClock < header.time + TRUSTING_PERIOD + +(* + Given a function pVotingPower \in D -> Powers for some D \subseteq AllNodes + and pNodes \subseteq D, test whether the set pNodes \subseteq AllNodes has + more than 2/3 of voting power among the nodes in D. + *) +TwoThirds(pVS, pNodes) == + LET TP == Cardinality(pVS) + SP == Cardinality(pVS \intersect pNodes) + IN + 3 * SP > 2 * TP \* when thinking in real numbers, not integers: SP > 2.0 / 3.0 * TP + +(* + Given a set of FaultyNodes, test whether the voting power of the correct nodes in D + is more than 2/3 of the voting power of the faulty nodes in D. + + Parameters: + - pFaultyNodes is a set of nodes that are considered faulty + - pVS is a set of all validators, maybe including Faulty, intersecting with it, etc. + - pMaxFaultRatio is a pair <> that limits the ratio a / b of the faulty + validators from above (exclusive) + *) +FaultyValidatorsFewerThan(pFaultyNodes, pVS, maxRatio) == + LET FN == pFaultyNodes \intersect pVS \* faulty nodes in pNodes + CN == pVS \ pFaultyNodes \* correct nodes in pNodes + CP == Cardinality(CN) \* power of the correct nodes + FP == Cardinality(FN) \* power of the faulty nodes + IN + \* CP + FP = TP is the total voting power + LET TP == CP + FP IN + FP * maxRatio[2] < TP * maxRatio[1] + +(* Can a block be produced by a correct peer, or an authenticated Byzantine peer *) +IsLightBlockAllowedByDigitalSignatures(ht, block) == + \/ block.header = blockchain[ht] \* signed by correct and faulty (maybe) + \/ /\ block.Commits \subseteq Faulty + /\ block.header.height = ht + /\ block.header.time >= 0 \* signed only by faulty + +(* + Initialize the blockchain to the ultimate height right in the initial states. + We pick the faulty validators statically, but that should not affect the light client. + + Parameters: + - pMaxFaultyRatioExclusive is a pair <> that bound the number of + faulty validators in each block by the ratio a / b (exclusive) + *) +InitToHeight(pMaxFaultyRatioExclusive) == + /\ Faulty \in SUBSET AllNodes \* some nodes may fail + \* pick the validator sets and last commits + /\ \E vs, lastCommit \in [Heights -> SUBSET AllNodes]: + \E timestamp \in [Heights -> Int]: + \* refClock is at least as early as the timestamp in the last block + /\ \E tm \in Int: refClock = tm /\ tm >= timestamp[ULTIMATE_HEIGHT] + \* the genesis starts on day 1 + /\ timestamp[1] = 1 + /\ vs[1] = AllNodes + /\ lastCommit[1] = EmptyNodeSet + /\ \A h \in Heights \ {1}: + /\ lastCommit[h] \subseteq vs[h - 1] \* the non-validators cannot commit + /\ TwoThirds(vs[h - 1], lastCommit[h]) \* the commit has >2/3 of validator votes + \* the faulty validators have the power below the threshold + /\ FaultyValidatorsFewerThan(Faulty, vs[h], pMaxFaultyRatioExclusive) + /\ timestamp[h] > timestamp[h - 1] \* the time grows monotonically + /\ timestamp[h] < timestamp[h - 1] + TRUSTING_PERIOD \* but not too fast + \* form the block chain out of validator sets and commits (this makes apalache faster) + /\ blockchain = [h \in Heights |-> + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> IF h < ULTIMATE_HEIGHT THEN vs[h + 1] ELSE AllNodes, + lastCommit |-> lastCommit[h]] + ] \****** + +(********************* BLOCKCHAIN ACTIONS ********************************) +(* + Advance the clock by zero or more time units. + *) +AdvanceTime == + /\ \E tm \in Int: tm >= refClock /\ refClock' = tm + /\ UNCHANGED <> + +============================================================================= +\* Modification History +\* Last modified Wed Jun 10 14:10:54 CEST 2020 by igor +\* Created Fri Oct 11 15:45:11 CEST 2019 by igor diff --git a/spec/light-client/verification/Blockchain_A_1.tla b/spec/light-client/verification/Blockchain_A_1.tla new file mode 100644 index 0000000..eb562cc --- /dev/null +++ b/spec/light-client/verification/Blockchain_A_1.tla @@ -0,0 +1,171 @@ +------------------------ MODULE Blockchain_A_1 ----------------------------- +(* + This is a high-level specification of a Cosmos blockchain + that is designed specifically for the light client. + Validators have the voting power of one. If you like to model various + voting powers, introduce multiple copies of the same validator + (do not forget to give them unique names though). + *) +EXTENDS Integers, FiniteSets + +Min(a, b) == IF a < b THEN a ELSE b + +CONSTANT + AllNodes, + (* a set of all nodes that can act as validators (correct and faulty) *) + ULTIMATE_HEIGHT, + (* a maximal height that can be ever reached (modelling artifact) *) + TRUSTING_PERIOD + (* the period within which the validators are trusted *) + +Heights == 1..ULTIMATE_HEIGHT (* possible heights *) + +(* A commit is just a set of nodes who have committed the block *) +Commits == SUBSET AllNodes + +(* The set of all block headers that can be on the blockchain. + This is a simplified version of the Block data structure in the actual implementation. *) +BlockHeaders == [ + height: Heights, + \* the block height + time: Int, + \* the block timestamp in some integer units + lastCommit: Commits, + \* the nodes who have voted on the previous block, the set itself instead of a hash + (* in the implementation, only the hashes of V and NextV are stored in a block, + as V and NextV are stored in the application state *) + VS: SUBSET AllNodes, + \* the validators of this bloc. We store the validators instead of the hash. + NextVS: SUBSET AllNodes + \* the validators of the next block. We store the next validators instead of the hash. +] + +(* A signed header is just a header together with a set of commits *) +LightBlocks == [header: BlockHeaders, Commits: Commits] + +VARIABLES + now, + (* the current global time in integer units *) + blockchain, + (* A sequence of BlockHeaders, which gives us a bird view of the blockchain. *) + Faulty + (* A set of faulty nodes, which can act as validators. We assume that the set + of faulty processes is non-decreasing. If a process has recovered, it should + connect using a different id. *) + +(* all variables, to be used with UNCHANGED *) +vars == <> + +(* The set of all correct nodes in a state *) +Corr == AllNodes \ Faulty + +(* APALACHE annotations *) +a <: b == a \* type annotation + +NT == STRING +NodeSet(S) == S <: {NT} +EmptyNodeSet == NodeSet({}) + +BT == [height |-> Int, time |-> Int, lastCommit |-> {NT}, VS |-> {NT}, NextVS |-> {NT}] + +LBT == [header |-> BT, Commits |-> {NT}] +(* end of APALACHE annotations *) + +(****************************** BLOCKCHAIN ************************************) + +(* the header is still within the trusting period *) +InTrustingPeriod(header) == + now <= header.time + TRUSTING_PERIOD + +(* + Given a function pVotingPower \in D -> Powers for some D \subseteq AllNodes + and pNodes \subseteq D, test whether the set pNodes \subseteq AllNodes has + more than 2/3 of voting power among the nodes in D. + *) +TwoThirds(pVS, pNodes) == + LET TP == Cardinality(pVS) + SP == Cardinality(pVS \intersect pNodes) + IN + 3 * SP > 2 * TP \* when thinking in real numbers, not integers: SP > 2.0 / 3.0 * TP + +(* + Given a set of FaultyNodes, test whether the voting power of the correct nodes in D + is more than 2/3 of the voting power of the faulty nodes in D. + *) +IsCorrectPower(pFaultyNodes, pVS) == + LET FN == pFaultyNodes \intersect pVS \* faulty nodes in pNodes + CN == pVS \ pFaultyNodes \* correct nodes in pNodes + CP == Cardinality(CN) \* power of the correct nodes + FP == Cardinality(FN) \* power of the faulty nodes + IN + \* CP + FP = TP is the total voting power, so we write CP > 2.0 / 3 * TP as follows: + CP > 2 * FP \* Note: when FP = 0, this implies CP > 0. + +(* This is what we believe is the assumption about failures in Cosmos *) +FaultAssumption(pFaultyNodes, pNow, pBlockchain) == + \A h \in Heights: + pBlockchain[h].time + TRUSTING_PERIOD > pNow => + IsCorrectPower(pFaultyNodes, pBlockchain[h].NextVS) + +(* Can a block be produced by a correct peer, or an authenticated Byzantine peer *) +IsLightBlockAllowedByDigitalSignatures(ht, block) == + \/ block.header = blockchain[ht] \* signed by correct and faulty (maybe) + \/ block.Commits \subseteq Faulty /\ block.header.height = ht \* signed only by faulty + +(* + Initialize the blockchain to the ultimate height right in the initial states. + We pick the faulty validators statically, but that should not affect the light client. + *) +InitToHeight == + /\ Faulty \in SUBSET AllNodes \* some nodes may fail + \* pick the validator sets and last commits + /\ \E vs, lastCommit \in [Heights -> SUBSET AllNodes]: + \E timestamp \in [Heights -> Int]: + \* now is at least as early as the timestamp in the last block + /\ \E tm \in Int: now = tm /\ tm >= timestamp[ULTIMATE_HEIGHT] + \* the genesis starts on day 1 + /\ timestamp[1] = 1 + /\ vs[1] = AllNodes + /\ lastCommit[1] = EmptyNodeSet + /\ \A h \in Heights \ {1}: + /\ lastCommit[h] \subseteq vs[h - 1] \* the non-validators cannot commit + /\ TwoThirds(vs[h - 1], lastCommit[h]) \* the commit has >2/3 of validator votes + /\ IsCorrectPower(Faulty, vs[h]) \* the correct validators have >2/3 of power + /\ timestamp[h] > timestamp[h - 1] \* the time grows monotonically + /\ timestamp[h] < timestamp[h - 1] + TRUSTING_PERIOD \* but not too fast + \* form the block chain out of validator sets and commits (this makes apalache faster) + /\ blockchain = [h \in Heights |-> + [height |-> h, + time |-> timestamp[h], + VS |-> vs[h], + NextVS |-> IF h < ULTIMATE_HEIGHT THEN vs[h + 1] ELSE AllNodes, + lastCommit |-> lastCommit[h]] + ] \****** + + +(* is the blockchain in the faulty zone where the Cosmos security model does not apply *) +InFaultyZone == + ~FaultAssumption(Faulty, now, blockchain) + +(********************* BLOCKCHAIN ACTIONS ********************************) +(* + Advance the clock by zero or more time units. + *) +AdvanceTime == + \E tm \in Int: tm >= now /\ now' = tm + /\ UNCHANGED <> + +(* + One more process fails. As a result, the blockchain may move into the faulty zone. + The light client is not using this action, as the faults are picked in the initial state. + However, this action may be useful when reasoning about fork detection. + *) +OneMoreFault == + /\ \E n \in AllNodes \ Faulty: + /\ Faulty' = Faulty \cup {n} + /\ Faulty' /= AllNodes \* at least process remains non-faulty + /\ UNCHANGED <> +============================================================================= +\* Modification History +\* Last modified Wed Jun 10 14:10:54 CEST 2020 by igor +\* Created Fri Oct 11 15:45:11 CEST 2019 by igor diff --git a/spec/light-client/verification/LCVerificationApi_003_draft.tla b/spec/light-client/verification/LCVerificationApi_003_draft.tla new file mode 100644 index 0000000..b995073 --- /dev/null +++ b/spec/light-client/verification/LCVerificationApi_003_draft.tla @@ -0,0 +1,192 @@ +-------------------- MODULE LCVerificationApi_003_draft -------------------------- +(** + * The common interface of the light client verification and detection. + *) +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + CLOCK_DRIFT, + (* the assumed precision of the clock *) + REAL_CLOCK_DRIFT, + (* the actual clock drift, which under normal circumstances should not + be larger than CLOCK_DRIFT (otherwise, there will be a bug) *) + FAULTY_RATIO + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + +VARIABLES + localClock (* current time as measured by the light client *) + +(* the header is still within the trusting period *) +InTrustingPeriodLocal(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - CLOCK_DRIFT + +(* the header is still within the trusting period, even if the clock can go backwards *) +InTrustingPeriodLocalSurely(header) == + \* note that the assumption about the drift reduces the period of trust + localClock < header.time + TRUSTING_PERIOD - 2 * CLOCK_DRIFT + +(* ensure that the local clock does not drift far away from the global clock *) +IsLocalClockWithinDrift(local, global) == + /\ global - REAL_CLOCK_DRIFT <= local + /\ local <= global + REAL_CLOCK_DRIFT + +(** + * Check that the commits in an untrusted block form 1/3 of the next validators + * in a trusted header. + *) +SignedByOneThirdOfTrusted(trusted, untrusted) == + LET TP == Cardinality(trusted.header.NextVS) + SP == Cardinality(untrusted.Commits \intersect trusted.header.NextVS) + IN + 3 * SP > TP + +(** + The first part of the precondition of ValidAndVerified, which does not take + the current time into account. + + [LCV-FUNC-VALID.1::TLA-PRE-UNTIMED.1] + *) +ValidAndVerifiedPreUntimed(trusted, untrusted) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ thdr.height < uhdr.height + \* the trusted block has been created earlier + /\ thdr.time < uhdr.time + /\ untrusted.Commits \subseteq uhdr.VS + /\ LET TP == Cardinality(uhdr.VS) + SP == Cardinality(untrusted.Commits) + IN + 3 * SP > 2 * TP + /\ thdr.height + 1 = uhdr.height => thdr.NextVS = uhdr.VS + (* As we do not have explicit hashes we ignore these three checks of the English spec: + + 1. "trusted.Commit is a commit is for the header trusted.Header, + i.e. it contains the correct hash of the header". + 2. untrusted.Validators = hash(untrusted.Header.Validators) + 3. untrusted.NextValidators = hash(untrusted.Header.NextValidators) + *) + +(** + Check the precondition of ValidAndVerified, including the time checks. + + [LCV-FUNC-VALID.1::TLA-PRE.1] + *) +ValidAndVerifiedPre(trusted, untrusted, checkFuture) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ InTrustingPeriodLocal(thdr) + \* The untrusted block is not from the future (modulo clock drift). + \* Do the check, if it is required. + /\ checkFuture => uhdr.time < localClock + CLOCK_DRIFT + /\ ValidAndVerifiedPreUntimed(trusted, untrusted) + + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + This test does take current time into account, but only looks at the block structure. + + [LCV-FUNC-VALID.1::TLA-UNTIMED.1] + *) +ValidAndVerifiedUntimed(trusted, untrusted) == + IF ~ValidAndVerifiedPreUntimed(trusted, untrusted) + THEN "INVALID" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + + [LCV-FUNC-VALID.1::TLA.1] + *) +ValidAndVerified(trusted, untrusted, checkFuture) == + IF ~ValidAndVerifiedPre(trusted, untrusted, checkFuture) + THEN "INVALID" + ELSE IF ~InTrustingPeriodLocal(untrusted.header) + (* We leave the following test for the documentation purposes. + The implementation should do this test, as signature verification may be slow. + In the TLA+ specification, ValidAndVerified happens in no time. + *) + THEN "FAILED_TRUSTING_PERIOD" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + + +(** + The invariant of the light store that is not related to the blockchain + *) +LightStoreInv(fetchedLightBlocks, lightBlockStatus) == + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] /= "StateVerified" + \/ lightBlockStatus[rh] /= "StateVerified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ LET lhdr == fetchedLightBlocks[lh] + rhdr == fetchedLightBlocks[rh] + IN + \* we can verify the right one using the left one + "SUCCESS" = ValidAndVerifiedUntimed(lhdr, rhdr) + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + * When the light client terminates, there are no failed blocks. + * (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +(** + The expected post-condition of VerifyToTarget. + *) +VerifyToTargetPost(blockchain, isPeerCorrect, + fetchedLightBlocks, lightBlockStatus, + trustedHeight, targetHeight, finalState) == + LET trustedHeader == fetchedLightBlocks[trustedHeight].header IN + \* The light client is not lying us on the trusted block. + \* It is straightforward to detect. + /\ lightBlockStatus[trustedHeight] = "StateVerified" + /\ trustedHeight \in DOMAIN fetchedLightBlocks + /\ trustedHeader = blockchain[trustedHeight] + \* the invariants we have found in the light client verification + \* there is a problem with trusting period + /\ isPeerCorrect + => CorrectnessInv(blockchain, fetchedLightBlocks, lightBlockStatus) + \* a correct peer should fail the light client, + \* if the trusted block is in the trusting period + /\ isPeerCorrect /\ InTrustingPeriodLocalSurely(trustedHeader) + => finalState = "finishedSuccess" + /\ finalState = "finishedSuccess" => + /\ lightBlockStatus[targetHeight] = "StateVerified" + /\ targetHeight \in DOMAIN fetchedLightBlocks + /\ NoFailedBlocksOnSuccessInv(fetchedLightBlocks, lightBlockStatus) + /\ LightStoreInv(fetchedLightBlocks, lightBlockStatus) + + +================================================================================== diff --git a/spec/light-client/verification/Lightclient_002_draft.tla b/spec/light-client/verification/Lightclient_002_draft.tla new file mode 100644 index 0000000..36fd9d2 --- /dev/null +++ b/spec/light-client/verification/Lightclient_002_draft.tla @@ -0,0 +1,465 @@ +-------------------------- MODULE Lightclient_002_draft ---------------------------- +(** + * A state-machine specification of the lite client, following the English spec: + * + * https://github.com/informalsystems/tendermint-rs/blob/master/docs/spec/lightclient/verification.md + *) + +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTED_HEIGHT, + (* an index of the block header that the light client trusts by social consensus *) + TARGET_HEIGHT, + (* an index of the block header that the light client tries to verify *) + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + IS_PRIMARY_CORRECT + (* is primary correct? *) + +VARIABLES (* see TypeOK below for the variable types *) + state, (* the current state of the light client *) + nextHeight, (* the next height to explore by the light client *) + nprobes (* the lite client iteration, or the number of block tests *) + +(* the light store *) +VARIABLES + fetchedLightBlocks, (* a function from heights to LightBlocks *) + lightBlockStatus, (* a function from heights to block statuses *) + latestVerified (* the latest verified block *) + +(* the variables of the lite client *) +lcvars == <> + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevNow, + prevVerdict + +InitMonitor(verified, current, now, verdict) == + /\ prevVerified = verified + /\ prevCurrent = current + /\ prevNow = now + /\ prevVerdict = verdict + +NextMonitor(verified, current, now, verdict) == + /\ prevVerified' = verified + /\ prevCurrent' = current + /\ prevNow' = now + /\ prevVerdict' = verdict + + +(******************* Blockchain instance ***********************************) + +\* the parameters that are propagated into Blockchain +CONSTANTS + AllNodes + (* a set of all nodes that can act as validators (correct and faulty) *) + +\* the state variables of Blockchain, see Blockchain.tla for the details +VARIABLES now, blockchain, Faulty + +\* All the variables of Blockchain. For some reason, BC!vars does not work +bcvars == <> + +(* Create an instance of Blockchain. + We could write EXTENDS Blockchain, but then all the constants and state variables + would be hidden inside the Blockchain module. + *) +ULTIMATE_HEIGHT == TARGET_HEIGHT + 1 + +BC == INSTANCE Blockchain_002_draft WITH + now <- now, blockchain <- blockchain, Faulty <- Faulty + +(************************** Lite client ************************************) + +(* the heights on which the light client is working *) +HEIGHTS == TRUSTED_HEIGHT..TARGET_HEIGHT + +(* the control states of the lite client *) +States == { "working", "finishedSuccess", "finishedFailure" } + +(** + Check the precondition of ValidAndVerified. + + [LCV-FUNC-VALID.1::TLA-PRE.1] + *) +ValidAndVerifiedPre(trusted, untrusted) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ BC!InTrustingPeriod(thdr) + /\ thdr.height < uhdr.height + \* the trusted block has been created earlier (no drift here) + /\ thdr.time < uhdr.time + \* the untrusted block is not from the future + /\ uhdr.time < now + /\ untrusted.Commits \subseteq uhdr.VS + /\ LET TP == Cardinality(uhdr.VS) + SP == Cardinality(untrusted.Commits) + IN + 3 * SP > 2 * TP + /\ thdr.height + 1 = uhdr.height => thdr.NextVS = uhdr.VS + (* As we do not have explicit hashes we ignore these three checks of the English spec: + + 1. "trusted.Commit is a commit is for the header trusted.Header, + i.e. it contains the correct hash of the header". + 2. untrusted.Validators = hash(untrusted.Header.Validators) + 3. untrusted.NextValidators = hash(untrusted.Header.NextValidators) + *) + +(** + * Check that the commits in an untrusted block form 1/3 of the next validators + * in a trusted header. + *) +SignedByOneThirdOfTrusted(trusted, untrusted) == + LET TP == Cardinality(trusted.header.NextVS) + SP == Cardinality(untrusted.Commits \intersect trusted.header.NextVS) + IN + 3 * SP > TP + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + + [LCV-FUNC-VALID.1::TLA.1] + *) +ValidAndVerified(trusted, untrusted) == + IF ~ValidAndVerifiedPre(trusted, untrusted) + THEN "INVALID" + ELSE IF ~BC!InTrustingPeriod(untrusted.header) + (* We leave the following test for the documentation purposes. + The implementation should do this test, as signature verification may be slow. + In the TLA+ specification, ValidAndVerified happens in no time. + *) + THEN "FAILED_TRUSTING_PERIOD" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "SUCCESS" + ELSE "NOT_ENOUGH_TRUST" + +(* + Initial states of the light client. + Initially, only the trusted light block is present. + *) +LCInit == + /\ state = "working" + /\ nextHeight = TARGET_HEIGHT + /\ nprobes = 0 \* no tests have been done so far + /\ LET trustedBlock == blockchain[TRUSTED_HEIGHT] + trustedLightBlock == [header |-> trustedBlock, Commits |-> AllNodes] + IN + \* initially, fetchedLightBlocks is a function of one element, i.e., TRUSTED_HEIGHT + /\ fetchedLightBlocks = [h \in {TRUSTED_HEIGHT} |-> trustedLightBlock] + \* initially, lightBlockStatus is a function of one element, i.e., TRUSTED_HEIGHT + /\ lightBlockStatus = [h \in {TRUSTED_HEIGHT} |-> "StateVerified"] + \* the latest verified block the the trusted block + /\ latestVerified = trustedLightBlock + /\ InitMonitor(trustedLightBlock, trustedLightBlock, now, "SUCCESS") + +\* block should contain a copy of the block from the reference chain, with a matching commit +CopyLightBlockFromChain(block, height) == + LET ref == blockchain[height] + lastCommit == + IF height < ULTIMATE_HEIGHT + THEN blockchain[height + 1].lastCommit + \* for the ultimate block, which we never use, as ULTIMATE_HEIGHT = TARGET_HEIGHT + 1 + ELSE blockchain[height].VS + IN + block = [header |-> ref, Commits |-> lastCommit] + +\* Either the primary is correct and the block comes from the reference chain, +\* or the block is produced by a faulty primary. +\* +\* [LCV-FUNC-FETCH.1::TLA.1] +FetchLightBlockInto(block, height) == + IF IS_PRIMARY_CORRECT + THEN CopyLightBlockFromChain(block, height) + ELSE BC!IsLightBlockAllowedByDigitalSignatures(height, block) + +\* add a block into the light store +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateBlocks(lightBlocks, block) == + LET ht == block.header.height IN + [h \in DOMAIN lightBlocks \union {ht} |-> + IF h = ht THEN block ELSE lightBlocks[h]] + +\* update the state of a light block +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateStates(statuses, ht, blockState) == + [h \in DOMAIN statuses \union {ht} |-> + IF h = ht THEN blockState ELSE statuses[h]] + +\* Check, whether newHeight is a possible next height for the light client. +\* +\* [LCV-FUNC-SCHEDULE.1::TLA.1] +CanScheduleTo(newHeight, pLatestVerified, pNextHeight, pTargetHeight) == + LET ht == pLatestVerified.header.height IN + \/ /\ ht = pNextHeight + /\ ht < pTargetHeight + /\ pNextHeight < newHeight + /\ newHeight <= pTargetHeight + \/ /\ ht < pNextHeight + /\ ht < pTargetHeight + /\ ht < newHeight + /\ newHeight < pNextHeight + \/ /\ ht = pTargetHeight + /\ newHeight = pTargetHeight + +\* The loop of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOP.1] +VerifyToTargetLoop == + \* the loop condition is true + /\ latestVerified.header.height < TARGET_HEIGHT + \* pick a light block, which will be constrained later + /\ \E current \in BC!LightBlocks: + \* Get next LightBlock for verification + /\ IF nextHeight \in DOMAIN fetchedLightBlocks + THEN \* copy the block from the light store + /\ current = fetchedLightBlocks[nextHeight] + /\ UNCHANGED fetchedLightBlocks + ELSE \* retrieve a light block and save it in the light store + /\ FetchLightBlockInto(current, nextHeight) + /\ fetchedLightBlocks' = LightStoreUpdateBlocks(fetchedLightBlocks, current) + \* Record that one more probe has been done (for complexity and model checking) + /\ nprobes' = nprobes + 1 + \* Verify the current block + /\ LET verdict == ValidAndVerified(latestVerified, current) IN + NextMonitor(latestVerified, current, now, verdict) /\ + \* Decide whether/how to continue + CASE verdict = "SUCCESS" -> + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateVerified") + /\ latestVerified' = current + /\ state' = + IF latestVerified'.header.height < TARGET_HEIGHT + THEN "working" + ELSE "finishedSuccess" + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, current, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + + [] verdict = "NOT_ENOUGH_TRUST" -> + (* + do nothing: the light block current passed validation, but the validator + set is too different to verify it. We keep the state of + current at StateUnverified. For a later iteration, Schedule + might decide to try verification of that light block again. + *) + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateUnverified") + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, latestVerified, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + /\ UNCHANGED <> + + [] OTHER -> + \* verdict is some error code + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateFailed") + /\ state' = "finishedFailure" + /\ UNCHANGED <> + +\* The terminating condition of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOPCOND.1] +VerifyToTargetDone == + /\ latestVerified.header.height >= TARGET_HEIGHT + /\ state' = "finishedSuccess" + /\ UNCHANGED <> + /\ UNCHANGED <> + +(********************* Lite client + Blockchain *******************) +Init == + \* the blockchain is initialized immediately to the ULTIMATE_HEIGHT + /\ BC!InitToHeight + \* the light client starts + /\ LCInit + +(* + The system step is very simple. + The light client is either executing VerifyToTarget, or it has terminated. + (In the latter case, a model checker reports a deadlock.) + Simultaneously, the global clock may advance. + *) +Next == + /\ state = "working" + /\ VerifyToTargetLoop \/ VerifyToTargetDone + /\ BC!AdvanceTime \* the global clock is advanced by zero or more time units + +(************************* Types ******************************************) +TypeOK == + /\ state \in States + /\ nextHeight \in HEIGHTS + /\ latestVerified \in BC!LightBlocks + /\ \E HS \in SUBSET HEIGHTS: + /\ fetchedLightBlocks \in [HS -> BC!LightBlocks] + /\ lightBlockStatus + \in [HS -> {"StateVerified", "StateUnverified", "StateFailed"}] + +(************************* Properties ******************************************) + +(* The properties to check *) +\* this invariant candidate is false +NeverFinish == + state = "working" + +\* this invariant candidate is false +NeverFinishNegative == + state /= "finishedFailure" + +\* This invariant holds true, when the primary is correct. +\* This invariant candidate is false when the primary is faulty. +NeverFinishNegativeWhenTrusted == + (*(minTrustedHeight <= TRUSTED_HEIGHT)*) + BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + => state /= "finishedFailure" + +\* this invariant candidate is false +NeverFinishPositive == + state /= "finishedSuccess" + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + Check that the sequence of the headers in storedLightBlocks satisfies ValidAndVerified = "SUCCESS" pairwise + This property is easily violated, whenever a header cannot be trusted anymore. + *) +StoredHeadersAreVerifiedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "SUCCESS" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + +\* An improved version of StoredHeadersAreSound, assuming that a header may be not trusted. +\* This invariant candidate is also violated, +\* as there may be some unverified blocks left in the middle. +StoredHeadersAreVerifiedOrNotTrustedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "SUCCESS" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + \* or the left header is outside the trusting period, so no guarantees + \/ ~BC!InTrustingPeriod(fetchedLightBlocks[lh].header) + +(** + * An improved version of StoredHeadersAreSoundOrNotTrusted, + * checking the property only for the verified headers. + * This invariant holds true. + *) +ProofOfChainOfTrustInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] = "StateUnverified" + \/ lightBlockStatus[rh] = "StateUnverified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ ~(BC!InTrustingPeriod(fetchedLightBlocks[lh].header)) + \* or we can verify the right one using the left one + \/ "SUCCESS" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + +(** + * When the light client terminates, there are no failed blocks. (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv == + state = "finishedSuccess" => + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +\* This property states that whenever the light client finishes with a positive outcome, +\* the trusted header is still within the trusting period. +\* We expect this property to be violated. And Apalache shows us a counterexample. +PositiveBeforeTrustedHeaderExpires == + (state = "finishedSuccess") => BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + +\* If the primary is correct and the initial trusted block has not expired, +\* then whenever the algorithm terminates, it reports "success" +CorrectPrimaryAndTimeliness == + (BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +(** + If the primary is correct and there is a trusted block that has not expired, + then whenever the algorithm terminates, it reports "success". + + [LCV-DIST-LIVE.1::SUCCESS-CORR-PRIMARY-CHAIN-OF-TRUST.1] + *) +SuccessOnCorrectPrimaryAndChainOfTrust == + (\E h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" /\ BC!InTrustingPeriod(blockchain[h]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +\* Lite Client Completeness: If header h was correctly generated by an instance +\* of Tendermint consensus (and its age is less than the trusting period), +\* then the lite client should eventually set trust(h) to true. +\* +\* Note that Completeness assumes that the lite client communicates with a correct full node. +\* +\* We decompose completeness into Termination (liveness) and Precision (safety). +\* Once again, Precision is an inverse version of the safety property in Completeness, +\* as A => B is logically equivalent to ~B => ~A. +PrecisionInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + \/ lightBlock.header /= blockchain[h] + \* the full node lied to the lite client about the commits + \/ lightBlock.Commits /= lightBlock.header.VS + +\* the old invariant that was found to be buggy by TLC +PrecisionBuggyInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + lightBlock.header /= blockchain[h] + +\* the worst complexity +Complexity == + LET N == TARGET_HEIGHT - TRUSTED_HEIGHT + 1 IN + state /= "working" => + (2 * nprobes <= N * (N - 1)) + +(* + We omit termination, as the algorithm deadlocks in the end. + So termination can be demonstrated by finding a deadlock. + Of course, one has to analyze the deadlocked state and see that + the algorithm has indeed terminated there. +*) +============================================================================= +\* Modification History +\* Last modified Fri Jun 26 12:08:28 CEST 2020 by igor +\* Created Wed Oct 02 16:39:42 CEST 2019 by igor diff --git a/spec/light-client/verification/Lightclient_003_draft.tla b/spec/light-client/verification/Lightclient_003_draft.tla new file mode 100644 index 0000000..8f580fe --- /dev/null +++ b/spec/light-client/verification/Lightclient_003_draft.tla @@ -0,0 +1,493 @@ +-------------------------- MODULE Lightclient_003_draft ---------------------------- +(** + * A state-machine specification of the lite client verification, + * following the English spec: + * + * https://github.com/informalsystems/tendermint-rs/blob/master/docs/spec/lightclient/verification.md + *) + +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTED_HEIGHT, + (* an index of the block header that the light client trusts by social consensus *) + TARGET_HEIGHT, + (* an index of the block header that the light client tries to verify *) + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + CLOCK_DRIFT, + (* the assumed precision of the clock *) + REAL_CLOCK_DRIFT, + (* the actual clock drift, which under normal circumstances should not + be larger than CLOCK_DRIFT (otherwise, there will be a bug) *) + IS_PRIMARY_CORRECT, + (* is primary correct? *) + FAULTY_RATIO + (* a pair <> that limits that ratio of faulty validator in the blockchain + from above (exclusive). Cosmos security model prescribes 1 / 3. *) + +VARIABLES (* see TypeOK below for the variable types *) + localClock, (* the local clock of the light client *) + state, (* the current state of the light client *) + nextHeight, (* the next height to explore by the light client *) + nprobes (* the lite client iteration, or the number of block tests *) + +(* the light store *) +VARIABLES + fetchedLightBlocks, (* a function from heights to LightBlocks *) + lightBlockStatus, (* a function from heights to block statuses *) + latestVerified (* the latest verified block *) + +(* the variables of the lite client *) +lcvars == <> + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +InitMonitor(verified, current, pLocalClock, verdict) == + /\ prevVerified = verified + /\ prevCurrent = current + /\ prevLocalClock = pLocalClock + /\ prevVerdict = verdict + +NextMonitor(verified, current, pLocalClock, verdict) == + /\ prevVerified' = verified + /\ prevCurrent' = current + /\ prevLocalClock' = pLocalClock + /\ prevVerdict' = verdict + + +(******************* Blockchain instance ***********************************) + +\* the parameters that are propagated into Blockchain +CONSTANTS + AllNodes + (* a set of all nodes that can act as validators (correct and faulty) *) + +\* the state variables of Blockchain, see Blockchain.tla for the details +VARIABLES refClock, blockchain, Faulty + +\* All the variables of Blockchain. For some reason, BC!vars does not work +bcvars == <> + +(* Create an instance of Blockchain. + We could write EXTENDS Blockchain, but then all the constants and state variables + would be hidden inside the Blockchain module. + *) +ULTIMATE_HEIGHT == TARGET_HEIGHT + 1 + +BC == INSTANCE Blockchain_003_draft WITH + refClock <- refClock, blockchain <- blockchain, Faulty <- Faulty + +(************************** Lite client ************************************) + +(* the heights on which the light client is working *) +HEIGHTS == TRUSTED_HEIGHT..TARGET_HEIGHT + +(* the control states of the lite client *) +States == { "working", "finishedSuccess", "finishedFailure" } + +\* The verification functions are implemented in the API +API == INSTANCE LCVerificationApi_003_draft + + +(* + Initial states of the light client. + Initially, only the trusted light block is present. + *) +LCInit == + /\ \E tm \in Int: + tm >= 0 /\ API!IsLocalClockWithinDrift(tm, refClock) /\ localClock = tm + /\ state = "working" + /\ nextHeight = TARGET_HEIGHT + /\ nprobes = 0 \* no tests have been done so far + /\ LET trustedBlock == blockchain[TRUSTED_HEIGHT] + trustedLightBlock == [header |-> trustedBlock, Commits |-> AllNodes] + IN + \* initially, fetchedLightBlocks is a function of one element, i.e., TRUSTED_HEIGHT + /\ fetchedLightBlocks = [h \in {TRUSTED_HEIGHT} |-> trustedLightBlock] + \* initially, lightBlockStatus is a function of one element, i.e., TRUSTED_HEIGHT + /\ lightBlockStatus = [h \in {TRUSTED_HEIGHT} |-> "StateVerified"] + \* the latest verified block the the trusted block + /\ latestVerified = trustedLightBlock + /\ InitMonitor(trustedLightBlock, trustedLightBlock, localClock, "SUCCESS") + +\* block should contain a copy of the block from the reference chain, with a matching commit +CopyLightBlockFromChain(block, height) == + LET ref == blockchain[height] + lastCommit == + IF height < ULTIMATE_HEIGHT + THEN blockchain[height + 1].lastCommit + \* for the ultimate block, which we never use, as ULTIMATE_HEIGHT = TARGET_HEIGHT + 1 + ELSE blockchain[height].VS + IN + block = [header |-> ref, Commits |-> lastCommit] + +\* Either the primary is correct and the block comes from the reference chain, +\* or the block is produced by a faulty primary. +\* +\* [LCV-FUNC-FETCH.1::TLA.1] +FetchLightBlockInto(block, height) == + IF IS_PRIMARY_CORRECT + THEN CopyLightBlockFromChain(block, height) + ELSE BC!IsLightBlockAllowedByDigitalSignatures(height, block) + +\* add a block into the light store +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateBlocks(lightBlocks, block) == + LET ht == block.header.height IN + [h \in DOMAIN lightBlocks \union {ht} |-> + IF h = ht THEN block ELSE lightBlocks[h]] + +\* update the state of a light block +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateStates(statuses, ht, blockState) == + [h \in DOMAIN statuses \union {ht} |-> + IF h = ht THEN blockState ELSE statuses[h]] + +\* Check, whether newHeight is a possible next height for the light client. +\* +\* [LCV-FUNC-SCHEDULE.1::TLA.1] +CanScheduleTo(newHeight, pLatestVerified, pNextHeight, pTargetHeight) == + LET ht == pLatestVerified.header.height IN + \/ /\ ht = pNextHeight + /\ ht < pTargetHeight + /\ pNextHeight < newHeight + /\ newHeight <= pTargetHeight + \/ /\ ht < pNextHeight + /\ ht < pTargetHeight + /\ ht < newHeight + /\ newHeight < pNextHeight + \/ /\ ht = pTargetHeight + /\ newHeight = pTargetHeight + +\* The loop of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOP.1] +VerifyToTargetLoop == + \* the loop condition is true + /\ latestVerified.header.height < TARGET_HEIGHT + \* pick a light block, which will be constrained later + /\ \E current \in BC!LightBlocks: + \* Get next LightBlock for verification + /\ IF nextHeight \in DOMAIN fetchedLightBlocks + THEN \* copy the block from the light store + /\ current = fetchedLightBlocks[nextHeight] + /\ UNCHANGED fetchedLightBlocks + ELSE \* retrieve a light block and save it in the light store + /\ FetchLightBlockInto(current, nextHeight) + /\ fetchedLightBlocks' = LightStoreUpdateBlocks(fetchedLightBlocks, current) + \* Record that one more probe has been done (for complexity and model checking) + /\ nprobes' = nprobes + 1 + \* Verify the current block + /\ LET verdict == API!ValidAndVerified(latestVerified, current, TRUE) IN + NextMonitor(latestVerified, current, localClock, verdict) /\ + \* Decide whether/how to continue + CASE verdict = "SUCCESS" -> + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateVerified") + /\ latestVerified' = current + /\ state' = + IF latestVerified'.header.height < TARGET_HEIGHT + THEN "working" + ELSE "finishedSuccess" + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, current, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + + [] verdict = "NOT_ENOUGH_TRUST" -> + (* + do nothing: the light block current passed validation, but the validator + set is too different to verify it. We keep the state of + current at StateUnverified. For a later iteration, Schedule + might decide to try verification of that light block again. + *) + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateUnverified") + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, latestVerified, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + /\ UNCHANGED <> + + [] OTHER -> + \* verdict is some error code + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateFailed") + /\ state' = "finishedFailure" + /\ UNCHANGED <> + +\* The terminating condition of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOPCOND.1] +VerifyToTargetDone == + /\ latestVerified.header.height >= TARGET_HEIGHT + /\ state' = "finishedSuccess" + /\ UNCHANGED <> + /\ UNCHANGED <> + +(* + The local and global clocks can be updated. They can also drift from each other. + Note that the local clock can actually go backwards in time. + However, it still stays in the drift envelope + of [refClock - REAL_CLOCK_DRIFT, refClock + REAL_CLOCK_DRIFT]. + *) +AdvanceClocks == + /\ BC!AdvanceTime + /\ \E tm \in Int: + /\ tm >= 0 + /\ API!IsLocalClockWithinDrift(tm, refClock') + /\ localClock' = tm + \* if you like the clock to always grow monotonically, uncomment the next line: + \*/\ localClock' > localClock + +(********************* Lite client + Blockchain *******************) +Init == + \* the blockchain is initialized immediately to the ULTIMATE_HEIGHT + /\ BC!InitToHeight(FAULTY_RATIO) + \* the light client starts + /\ LCInit + +(* + The system step is very simple. + The light client is either executing VerifyToTarget, or it has terminated. + (In the latter case, a model checker reports a deadlock.) + Simultaneously, the global clock may advance. + *) +Next == + /\ state = "working" + /\ VerifyToTargetLoop \/ VerifyToTargetDone + /\ AdvanceClocks + +(************************* Types ******************************************) +TypeOK == + /\ state \in States + /\ localClock \in Nat + /\ refClock \in Nat + /\ nextHeight \in HEIGHTS + /\ latestVerified \in BC!LightBlocks + /\ \E HS \in SUBSET HEIGHTS: + /\ fetchedLightBlocks \in [HS -> BC!LightBlocks] + /\ lightBlockStatus + \in [HS -> {"StateVerified", "StateUnverified", "StateFailed"}] + +(************************* Properties ******************************************) + +(* The properties to check *) +\* this invariant candidate is false +NeverFinish == + state = "working" + +\* this invariant candidate is false +NeverFinishNegative == + state /= "finishedFailure" + +\* This invariant holds true, when the primary is correct. +\* This invariant candidate is false when the primary is faulty. +NeverFinishNegativeWhenTrusted == + BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + => state /= "finishedFailure" + +\* this invariant candidate is false +NeverFinishPositive == + state /= "finishedSuccess" + + +(** + Check that the target height has been reached upon successful termination. + *) +TargetHeightOnSuccessInv == + state = "finishedSuccess" => + /\ TARGET_HEIGHT \in DOMAIN fetchedLightBlocks + /\ lightBlockStatus[TARGET_HEIGHT] = "StateVerified" + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + No faulty block was used to construct a proof. This invariant holds, + only if FAULTY_RATIO < 1/3. + *) +NoTrustOnFaultyBlockInv == + (state = "finishedSuccess" + /\ fetchedLightBlocks[TARGET_HEIGHT].header = blockchain[TARGET_HEIGHT]) + => CorrectnessInv + +(** + Check that the sequence of the headers in storedLightBlocks satisfies ValidAndVerified = "SUCCESS" pairwise + This property is easily violated, whenever a header cannot be trusted anymore. + *) +StoredHeadersAreVerifiedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "SUCCESS" = API!ValidAndVerified(fetchedLightBlocks[lh], + fetchedLightBlocks[rh], FALSE) + +\* An improved version of StoredHeadersAreVerifiedInv, +\* assuming that a header may be not trusted. +\* This invariant candidate is also violated, +\* as there may be some unverified blocks left in the middle. +\* This property is violated under two conditions: +\* (1) the primary is faulty and there are at least 4 blocks, +\* (2) the primary is correct and there are at least 5 blocks. +StoredHeadersAreVerifiedOrNotTrustedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "SUCCESS" = API!ValidAndVerified(fetchedLightBlocks[lh], + fetchedLightBlocks[rh], FALSE) + \* or the left header is outside the trusting period, so no guarantees + \/ ~API!InTrustingPeriodLocal(fetchedLightBlocks[lh].header) + +(** + * An improved version of StoredHeadersAreSoundOrNotTrusted, + * checking the property only for the verified headers. + * This invariant holds true if CLOCK_DRIFT <= REAL_CLOCK_DRIFT. + *) +ProofOfChainOfTrustInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] = "StateUnverified" + \/ lightBlockStatus[rh] = "StateUnverified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ ~(API!InTrustingPeriodLocal(fetchedLightBlocks[lh].header)) + \* or we can verify the right one using the left one + \/ "SUCCESS" = API!ValidAndVerified(fetchedLightBlocks[lh], + fetchedLightBlocks[rh], FALSE) + +(** + * When the light client terminates, there are no failed blocks. (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv == + state = "finishedSuccess" => + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +\* This property states that whenever the light client finishes with a positive outcome, +\* the trusted header is still within the trusting period. +\* We expect this property to be violated. And Apalache shows us a counterexample. +PositiveBeforeTrustedHeaderExpires == + (state = "finishedSuccess") => + BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + +\* If the primary is correct and the initial trusted block has not expired, +\* then whenever the algorithm terminates, it reports "success". +\* This property fails. +CorrectPrimaryAndTimeliness == + (BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +(** + If the primary is correct and there is a trusted block that has not expired, + then whenever the algorithm terminates, it reports "success". + This property only holds true, if the local clock is always growing monotonically. + If the local clock can go backwards in the envelope + [refClock - CLOCK_DRIFT, refClock + CLOCK_DRIFT], then the property fails. + + [LCV-DIST-LIVE.1::SUCCESS-CORR-PRIMARY-CHAIN-OF-TRUST.1] + *) +SuccessOnCorrectPrimaryAndChainOfTrustLocal == + (\E h \in DOMAIN fetchedLightBlocks: + /\ lightBlockStatus[h] = "StateVerified" + /\ API!InTrustingPeriodLocal(blockchain[h]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +(** + Similar to SuccessOnCorrectPrimaryAndChainOfTrust, but using the blockchain clock. + It fails because the local clock of the client drifted away, so it rejects a block + that has not expired yet (according to the local clock). + *) +SuccessOnCorrectPrimaryAndChainOfTrustGlobal == + (\E h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" /\ BC!InTrustingPeriod(blockchain[h]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +\* Lite Client Completeness: If header h was correctly generated by an instance +\* of Tendermint consensus (and its age is less than the trusting period), +\* then the lite client should eventually set trust(h) to true. +\* +\* Note that Completeness assumes that the lite client communicates with a correct full node. +\* +\* We decompose completeness into Termination (liveness) and Precision (safety). +\* Once again, Precision is an inverse version of the safety property in Completeness, +\* as A => B is logically equivalent to ~B => ~A. +\* +\* This property holds only when CLOCK_DRIFT = 0 and REAL_CLOCK_DRIFT = 0. +PrecisionInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + \/ lightBlock.header /= blockchain[h] + \* the full node lied to the lite client about the commits + \/ lightBlock.Commits /= lightBlock.header.VS + +\* the old invariant that was found to be buggy by TLC +PrecisionBuggyInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + lightBlock.header /= blockchain[h] + +\* the worst complexity +Complexity == + LET N == TARGET_HEIGHT - TRUSTED_HEIGHT + 1 IN + state /= "working" => + (2 * nprobes <= N * (N - 1)) + +(** + If the light client has terminated, then the expected postcondition holds true. + *) +ApiPostInv == + state /= "working" => + API!VerifyToTargetPost(blockchain, IS_PRIMARY_CORRECT, + fetchedLightBlocks, lightBlockStatus, + TRUSTED_HEIGHT, TARGET_HEIGHT, state) + +(* + We omit termination, as the algorithm deadlocks in the end. + So termination can be demonstrated by finding a deadlock. + Of course, one has to analyze the deadlocked state and see that + the algorithm has indeed terminated there. +*) +============================================================================= +\* Modification History +\* Last modified Fri Jun 26 12:08:28 CEST 2020 by igor +\* Created Wed Oct 02 16:39:42 CEST 2019 by igor diff --git a/spec/light-client/verification/Lightclient_A_1.tla b/spec/light-client/verification/Lightclient_A_1.tla new file mode 100644 index 0000000..b7f75a9 --- /dev/null +++ b/spec/light-client/verification/Lightclient_A_1.tla @@ -0,0 +1,441 @@ +-------------------------- MODULE Lightclient_A_1 ---------------------------- + +(** + * A state-machine specification of the lite client, following the English spec: + * + * ./verification_001_published.md + *) + +EXTENDS Integers, FiniteSets + +\* the parameters of Light Client +CONSTANTS + TRUSTED_HEIGHT, + (* an index of the block header that the light client trusts by social consensus *) + TARGET_HEIGHT, + (* an index of the block header that the light client tries to verify *) + TRUSTING_PERIOD, + (* the period within which the validators are trusted *) + IS_PRIMARY_CORRECT + (* is primary correct? *) + +VARIABLES (* see TypeOK below for the variable types *) + state, (* the current state of the light client *) + nextHeight, (* the next height to explore by the light client *) + nprobes (* the lite client iteration, or the number of block tests *) + +(* the light store *) +VARIABLES + fetchedLightBlocks, (* a function from heights to LightBlocks *) + lightBlockStatus, (* a function from heights to block statuses *) + latestVerified (* the latest verified block *) + +(* the variables of the lite client *) +lcvars == <> + +(******************* Blockchain instance ***********************************) + +\* the parameters that are propagated into Blockchain +CONSTANTS + AllNodes + (* a set of all nodes that can act as validators (correct and faulty) *) + +\* the state variables of Blockchain, see Blockchain.tla for the details +VARIABLES now, blockchain, Faulty + +\* All the variables of Blockchain. For some reason, BC!vars does not work +bcvars == <> + +(* Create an instance of Blockchain. + We could write EXTENDS Blockchain, but then all the constants and state variables + would be hidden inside the Blockchain module. + *) +ULTIMATE_HEIGHT == TARGET_HEIGHT + 1 + +BC == INSTANCE Blockchain_A_1 WITH + now <- now, blockchain <- blockchain, Faulty <- Faulty + +(************************** Lite client ************************************) + +(* the heights on which the light client is working *) +HEIGHTS == TRUSTED_HEIGHT..TARGET_HEIGHT + +(* the control states of the lite client *) +States == { "working", "finishedSuccess", "finishedFailure" } + +(** + Check the precondition of ValidAndVerified. + + [LCV-FUNC-VALID.1::TLA-PRE.1] + *) +ValidAndVerifiedPre(trusted, untrusted) == + LET thdr == trusted.header + uhdr == untrusted.header + IN + /\ BC!InTrustingPeriod(thdr) + /\ thdr.height < uhdr.height + \* the trusted block has been created earlier (no drift here) + /\ thdr.time <= uhdr.time + /\ untrusted.Commits \subseteq uhdr.VS + /\ LET TP == Cardinality(uhdr.VS) + SP == Cardinality(untrusted.Commits) + IN + 3 * SP > 2 * TP + /\ thdr.height + 1 = uhdr.height => thdr.NextVS = uhdr.VS + (* As we do not have explicit hashes we ignore these three checks of the English spec: + + 1. "trusted.Commit is a commit is for the header trusted.Header, + i.e. it contains the correct hash of the header". + 2. untrusted.Validators = hash(untrusted.Header.Validators) + 3. untrusted.NextValidators = hash(untrusted.Header.NextValidators) + *) + +(** + * Check that the commits in an untrusted block form 1/3 of the next validators + * in a trusted header. + *) +SignedByOneThirdOfTrusted(trusted, untrusted) == + LET TP == Cardinality(trusted.header.NextVS) + SP == Cardinality(untrusted.Commits \intersect trusted.header.NextVS) + IN + 3 * SP > TP + +(** + Check, whether an untrusted block is valid and verifiable w.r.t. a trusted header. + + [LCV-FUNC-VALID.1::TLA.1] + *) +ValidAndVerified(trusted, untrusted) == + IF ~ValidAndVerifiedPre(trusted, untrusted) + THEN "FAILED_VERIFICATION" + ELSE IF ~BC!InTrustingPeriod(untrusted.header) + (* We leave the following test for the documentation purposes. + The implementation should do this test, as signature verification may be slow. + In the TLA+ specification, ValidAndVerified happens in no time. + *) + THEN "FAILED_TRUSTING_PERIOD" + ELSE IF untrusted.header.height = trusted.header.height + 1 + \/ SignedByOneThirdOfTrusted(trusted, untrusted) + THEN "OK" + ELSE "CANNOT_VERIFY" + +(* + Initial states of the light client. + Initially, only the trusted light block is present. + *) +LCInit == + /\ state = "working" + /\ nextHeight = TARGET_HEIGHT + /\ nprobes = 0 \* no tests have been done so far + /\ LET trustedBlock == blockchain[TRUSTED_HEIGHT] + trustedLightBlock == [header |-> trustedBlock, Commits |-> AllNodes] + IN + \* initially, fetchedLightBlocks is a function of one element, i.e., TRUSTED_HEIGHT + /\ fetchedLightBlocks = [h \in {TRUSTED_HEIGHT} |-> trustedLightBlock] + \* initially, lightBlockStatus is a function of one element, i.e., TRUSTED_HEIGHT + /\ lightBlockStatus = [h \in {TRUSTED_HEIGHT} |-> "StateVerified"] + \* the latest verified block the the trusted block + /\ latestVerified = trustedLightBlock + +\* block should contain a copy of the block from the reference chain, with a matching commit +CopyLightBlockFromChain(block, height) == + LET ref == blockchain[height] + lastCommit == + IF height < ULTIMATE_HEIGHT + THEN blockchain[height + 1].lastCommit + \* for the ultimate block, which we never use, as ULTIMATE_HEIGHT = TARGET_HEIGHT + 1 + ELSE blockchain[height].VS + IN + block = [header |-> ref, Commits |-> lastCommit] + +\* Either the primary is correct and the block comes from the reference chain, +\* or the block is produced by a faulty primary. +\* +\* [LCV-FUNC-FETCH.1::TLA.1] +FetchLightBlockInto(block, height) == + IF IS_PRIMARY_CORRECT + THEN CopyLightBlockFromChain(block, height) + ELSE BC!IsLightBlockAllowedByDigitalSignatures(height, block) + +\* add a block into the light store +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateBlocks(lightBlocks, block) == + LET ht == block.header.height IN + [h \in DOMAIN lightBlocks \union {ht} |-> + IF h = ht THEN block ELSE lightBlocks[h]] + +\* update the state of a light block +\* +\* [LCV-FUNC-UPDATE.1::TLA.1] +LightStoreUpdateStates(statuses, ht, blockState) == + [h \in DOMAIN statuses \union {ht} |-> + IF h = ht THEN blockState ELSE statuses[h]] + +\* Check, whether newHeight is a possible next height for the light client. +\* +\* [LCV-FUNC-SCHEDULE.1::TLA.1] +CanScheduleTo(newHeight, pLatestVerified, pNextHeight, pTargetHeight) == + LET ht == pLatestVerified.header.height IN + \/ /\ ht = pNextHeight + /\ ht < pTargetHeight + /\ pNextHeight < newHeight + /\ newHeight <= pTargetHeight + \/ /\ ht < pNextHeight + /\ ht < pTargetHeight + /\ ht < newHeight + /\ newHeight < pNextHeight + \/ /\ ht = pTargetHeight + /\ newHeight = pTargetHeight + +\* The loop of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOP.1] +VerifyToTargetLoop == + \* the loop condition is true + /\ latestVerified.header.height < TARGET_HEIGHT + \* pick a light block, which will be constrained later + /\ \E current \in BC!LightBlocks: + \* Get next LightBlock for verification + /\ IF nextHeight \in DOMAIN fetchedLightBlocks + THEN \* copy the block from the light store + /\ current = fetchedLightBlocks[nextHeight] + /\ UNCHANGED fetchedLightBlocks + ELSE \* retrieve a light block and save it in the light store + /\ FetchLightBlockInto(current, nextHeight) + /\ fetchedLightBlocks' = LightStoreUpdateBlocks(fetchedLightBlocks, current) + \* Record that one more probe has been done (for complexity and model checking) + /\ nprobes' = nprobes + 1 + \* Verify the current block + /\ LET verdict == ValidAndVerified(latestVerified, current) IN + \* Decide whether/how to continue + CASE verdict = "OK" -> + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateVerified") + /\ latestVerified' = current + /\ state' = + IF latestVerified'.header.height < TARGET_HEIGHT + THEN "working" + ELSE "finishedSuccess" + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, current, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + + [] verdict = "CANNOT_VERIFY" -> + (* + do nothing: the light block current passed validation, but the validator + set is too different to verify it. We keep the state of + current at StateUnverified. For a later iteration, Schedule + might decide to try verification of that light block again. + *) + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateUnverified") + /\ \E newHeight \in HEIGHTS: + /\ CanScheduleTo(newHeight, latestVerified, nextHeight, TARGET_HEIGHT) + /\ nextHeight' = newHeight + /\ UNCHANGED <> + + [] OTHER -> + \* verdict is some error code + /\ lightBlockStatus' = LightStoreUpdateStates(lightBlockStatus, nextHeight, "StateFailed") + /\ state' = "finishedFailure" + /\ UNCHANGED <> + +\* The terminating condition of VerifyToTarget. +\* +\* [LCV-FUNC-MAIN.1::TLA-LOOPCOND.1] +VerifyToTargetDone == + /\ latestVerified.header.height >= TARGET_HEIGHT + /\ state' = "finishedSuccess" + /\ UNCHANGED <> + +(********************* Lite client + Blockchain *******************) +Init == + \* the blockchain is initialized immediately to the ULTIMATE_HEIGHT + /\ BC!InitToHeight + \* the light client starts + /\ LCInit + +(* + The system step is very simple. + The light client is either executing VerifyToTarget, or it has terminated. + (In the latter case, a model checker reports a deadlock.) + Simultaneously, the global clock may advance. + *) +Next == + /\ state = "working" + /\ VerifyToTargetLoop \/ VerifyToTargetDone + /\ BC!AdvanceTime \* the global clock is advanced by zero or more time units + +(************************* Types ******************************************) +TypeOK == + /\ state \in States + /\ nextHeight \in HEIGHTS + /\ latestVerified \in BC!LightBlocks + /\ \E HS \in SUBSET HEIGHTS: + /\ fetchedLightBlocks \in [HS -> BC!LightBlocks] + /\ lightBlockStatus + \in [HS -> {"StateVerified", "StateUnverified", "StateFailed"}] + +(************************* Properties ******************************************) + +(* The properties to check *) +\* this invariant candidate is false +NeverFinish == + state = "working" + +\* this invariant candidate is false +NeverFinishNegative == + state /= "finishedFailure" + +\* This invariant holds true, when the primary is correct. +\* This invariant candidate is false when the primary is faulty. +NeverFinishNegativeWhenTrusted == + (*(minTrustedHeight <= TRUSTED_HEIGHT)*) + BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + => state /= "finishedFailure" + +\* this invariant candidate is false +NeverFinishPositive == + state /= "finishedSuccess" + +(** + Correctness states that all the obtained headers are exactly like in the blockchain. + + It is always the case that every verified header in LightStore was generated by + an instance of Tendermint consensus. + + [LCV-DIST-SAFE.1::CORRECTNESS-INV.1] + *) +CorrectnessInv == + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" => + fetchedLightBlocks[h].header = blockchain[h] + +(** + Check that the sequence of the headers in storedLightBlocks satisfies ValidAndVerified = "OK" pairwise + This property is easily violated, whenever a header cannot be trusted anymore. + *) +StoredHeadersAreVerifiedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "OK" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + +\* An improved version of StoredHeadersAreSound, assuming that a header may be not trusted. +\* This invariant candidate is also violated, +\* as there may be some unverified blocks left in the middle. +StoredHeadersAreVerifiedOrNotTrustedInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: \* for every pair of different stored headers + \/ lh >= rh + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh + \* or we can verify the right one using the left one + \/ "OK" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + \* or the left header is outside the trusting period, so no guarantees + \/ ~BC!InTrustingPeriod(fetchedLightBlocks[lh].header) + +(** + * An improved version of StoredHeadersAreSoundOrNotTrusted, + * checking the property only for the verified headers. + * This invariant holds true. + *) +ProofOfChainOfTrustInv == + state = "finishedSuccess" + => + \A lh, rh \in DOMAIN fetchedLightBlocks: + \* for every pair of stored headers that have been verified + \/ lh >= rh + \/ lightBlockStatus[lh] = "StateUnverified" + \/ lightBlockStatus[rh] = "StateUnverified" + \* either there is a header between them + \/ \E mh \in DOMAIN fetchedLightBlocks: + lh < mh /\ mh < rh /\ lightBlockStatus[mh] = "StateVerified" + \* or the left header is outside the trusting period, so no guarantees + \/ ~(BC!InTrustingPeriod(fetchedLightBlocks[lh].header)) + \* or we can verify the right one using the left one + \/ "OK" = ValidAndVerified(fetchedLightBlocks[lh], fetchedLightBlocks[rh]) + +(** + * When the light client terminates, there are no failed blocks. (Otherwise, someone lied to us.) + *) +NoFailedBlocksOnSuccessInv == + state = "finishedSuccess" => + \A h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] /= "StateFailed" + +\* This property states that whenever the light client finishes with a positive outcome, +\* the trusted header is still within the trusting period. +\* We expect this property to be violated. And Apalache shows us a counterexample. +PositiveBeforeTrustedHeaderExpires == + (state = "finishedSuccess") => BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + +\* If the primary is correct and the initial trusted block has not expired, +\* then whenever the algorithm terminates, it reports "success" +CorrectPrimaryAndTimeliness == + (BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +(** + If the primary is correct and there is a trusted block that has not expired, + then whenever the algorithm terminates, it reports "success". + + [LCV-DIST-LIVE.1::SUCCESS-CORR-PRIMARY-CHAIN-OF-TRUST.1] + *) +SuccessOnCorrectPrimaryAndChainOfTrust == + (\E h \in DOMAIN fetchedLightBlocks: + lightBlockStatus[h] = "StateVerified" /\ BC!InTrustingPeriod(blockchain[h]) + /\ state /= "working" /\ IS_PRIMARY_CORRECT) => + state = "finishedSuccess" + +\* Lite Client Completeness: If header h was correctly generated by an instance +\* of Tendermint consensus (and its age is less than the trusting period), +\* then the lite client should eventually set trust(h) to true. +\* +\* Note that Completeness assumes that the lite client communicates with a correct full node. +\* +\* We decompose completeness into Termination (liveness) and Precision (safety). +\* Once again, Precision is an inverse version of the safety property in Completeness, +\* as A => B is logically equivalent to ~B => ~A. +PrecisionInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + \/ lightBlock.header /= blockchain[h] + \* the full node lied to the lite client about the commits + \/ lightBlock.Commits /= lightBlock.header.VS + +\* the old invariant that was found to be buggy by TLC +PrecisionBuggyInv == + (state = "finishedFailure") + => \/ ~BC!InTrustingPeriod(blockchain[TRUSTED_HEIGHT]) \* outside of the trusting period + \/ \E h \in DOMAIN fetchedLightBlocks: + LET lightBlock == fetchedLightBlocks[h] IN + \* the full node lied to the lite client about the block header + lightBlock.header /= blockchain[h] + +\* the worst complexity +Complexity == + LET N == TARGET_HEIGHT - TRUSTED_HEIGHT + 1 IN + state /= "working" => + (2 * nprobes <= N * (N - 1)) + +(* + We omit termination, as the algorithm deadlocks in the end. + So termination can be demonstrated by finding a deadlock. + Of course, one has to analyze the deadlocked state and see that + the algorithm has indeed terminated there. +*) +============================================================================= +\* Modification History +\* Last modified Fri Jun 26 12:08:28 CEST 2020 by igor +\* Created Wed Oct 02 16:39:42 CEST 2019 by igor diff --git a/spec/light-client/verification/MC4_3_correct.tla b/spec/light-client/verification/MC4_3_correct.tla new file mode 100644 index 0000000..f42ce49 --- /dev/null +++ b/spec/light-client/verification/MC4_3_correct.tla @@ -0,0 +1,26 @@ +---------------------------- MODULE MC4_3_correct --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================== diff --git a/spec/light-client/verification/MC4_3_faulty.tla b/spec/light-client/verification/MC4_3_faulty.tla new file mode 100644 index 0000000..ffcedb0 --- /dev/null +++ b/spec/light-client/verification/MC4_3_faulty.tla @@ -0,0 +1,26 @@ +---------------------------- MODULE MC4_3_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 3 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================== diff --git a/spec/light-client/verification/MC4_4_correct.tla b/spec/light-client/verification/MC4_4_correct.tla new file mode 100644 index 0000000..bf372c8 --- /dev/null +++ b/spec/light-client/verification/MC4_4_correct.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC4_4_correct --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC4_4_correct_drifted.tla b/spec/light-client/verification/MC4_4_correct_drifted.tla new file mode 100644 index 0000000..31f7842 --- /dev/null +++ b/spec/light-client/verification/MC4_4_correct_drifted.tla @@ -0,0 +1,26 @@ +---------------------- MODULE MC4_4_correct_drifted --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 30 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================== diff --git a/spec/light-client/verification/MC4_4_faulty.tla b/spec/light-client/verification/MC4_4_faulty.tla new file mode 100644 index 0000000..5efde52 --- /dev/null +++ b/spec/light-client/verification/MC4_4_faulty.tla @@ -0,0 +1,26 @@ +---------------------------- MODULE MC4_4_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================== diff --git a/spec/light-client/verification/MC4_4_faulty_drifted.tla b/spec/light-client/verification/MC4_4_faulty_drifted.tla new file mode 100644 index 0000000..3e0bffe --- /dev/null +++ b/spec/light-client/verification/MC4_4_faulty_drifted.tla @@ -0,0 +1,26 @@ +---------------------- MODULE MC4_4_faulty_drifted --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 4 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 30 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================== diff --git a/spec/light-client/verification/MC4_5_correct.tla b/spec/light-client/verification/MC4_5_correct.tla new file mode 100644 index 0000000..128298f --- /dev/null +++ b/spec/light-client/verification/MC4_5_correct.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC4_5_correct --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC4_5_faulty.tla b/spec/light-client/verification/MC4_5_faulty.tla new file mode 100644 index 0000000..2e8dd4e --- /dev/null +++ b/spec/light-client/verification/MC4_5_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC4_5_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +IS_PRICLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +MARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC4_6_faulty.tla b/spec/light-client/verification/MC4_6_faulty.tla new file mode 100644 index 0000000..8069a31 --- /dev/null +++ b/spec/light-client/verification/MC4_6_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC4_6_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 6 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +IS_PRCLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC4_7_faulty.tla b/spec/light-client/verification/MC4_7_faulty.tla new file mode 100644 index 0000000..d2836ef --- /dev/null +++ b/spec/light-client/verification/MC4_7_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC4_7_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 7 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC5_5_correct.tla b/spec/light-client/verification/MC5_5_correct.tla new file mode 100644 index 0000000..800fef2 --- /dev/null +++ b/spec/light-client/verification/MC5_5_correct.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC5_5_correct --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC5_5_correct_peer_two_thirds_faulty.tla b/spec/light-client/verification/MC5_5_correct_peer_two_thirds_faulty.tla new file mode 100644 index 0000000..32b6270 --- /dev/null +++ b/spec/light-client/verification/MC5_5_correct_peer_two_thirds_faulty.tla @@ -0,0 +1,26 @@ +------------------- MODULE MC5_5_correct_peer_two_thirds_faulty ---------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == TRUE +FAULTY_RATIO == <<2, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC5_5_faulty.tla b/spec/light-client/verification/MC5_5_faulty.tla new file mode 100644 index 0000000..79caf0f --- /dev/null +++ b/spec/light-client/verification/MC5_5_faulty.tla @@ -0,0 +1,26 @@ +----------------- MODULE MC5_5_faulty --------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<2, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC5_5_faulty_peer_two_thirds_faulty.tla b/spec/light-client/verification/MC5_5_faulty_peer_two_thirds_faulty.tla new file mode 100644 index 0000000..1a8068b --- /dev/null +++ b/spec/light-client/verification/MC5_5_faulty_peer_two_thirds_faulty.tla @@ -0,0 +1,26 @@ +----------------- MODULE MC5_5_faulty_peer_two_thirds_faulty --------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<2, 3>> \* < 2 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC5_7_faulty.tla b/spec/light-client/verification/MC5_7_faulty.tla new file mode 100644 index 0000000..b258c8f --- /dev/null +++ b/spec/light-client/verification/MC5_7_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC5_7_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 7 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC7_5_faulty.tla b/spec/light-client/verification/MC7_5_faulty.tla new file mode 100644 index 0000000..70f52f0 --- /dev/null +++ b/spec/light-client/verification/MC7_5_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC7_5_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5", "n6", "n7"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 5 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/MC7_7_faulty.tla b/spec/light-client/verification/MC7_7_faulty.tla new file mode 100644 index 0000000..5dc452f --- /dev/null +++ b/spec/light-client/verification/MC7_7_faulty.tla @@ -0,0 +1,26 @@ +------------------------- MODULE MC7_7_faulty --------------------------- + +AllNodes == {"n1", "n2", "n3", "n4", "n5", "n6", "n7"} +TRUSTED_HEIGHT == 1 +TARGET_HEIGHT == 7 +TRUSTING_PERIOD == 1400 \* two weeks, one day is 100 time units :-) +CLOCK_DRIFT == 10 \* how much we assume the local clock is drifting +REAL_CLOCK_DRIFT == 3 \* how much the local clock is actually drifting +IS_PRIMARY_CORRECT == FALSE +FAULTY_RATIO == <<1, 3>> \* < 1 / 3 faulty validators + +VARIABLES + state, nextHeight, fetchedLightBlocks, lightBlockStatus, latestVerified, + nprobes, + localClock, + refClock, blockchain, Faulty + +(* the light client previous state components, used for monitoring *) +VARIABLES + prevVerified, + prevCurrent, + prevLocalClock, + prevVerdict + +INSTANCE Lightclient_003_draft +============================================================================ diff --git a/spec/light-client/verification/README.md b/spec/light-client/verification/README.md new file mode 100644 index 0000000..168c764 --- /dev/null +++ b/spec/light-client/verification/README.md @@ -0,0 +1,577 @@ +--- +order: 1 +parent: + title: Verification + order: 2 +--- +# Core Verification + +## Problem statement + +We assume that the light client knows a (base) header `inithead` it trusts (by social consensus or because +the light client has decided to trust the header before). The goal is to check whether another header +`newhead` can be trusted based on the data in `inithead`. + +The correctness of the protocol is based on the assumption that `inithead` was generated by an instance of +Tendermint consensus. + +### Failure Model + +For the purpose of the following definitions we assume that there exists a function +`validators` that returns the corresponding validator set for the given hash. + +The light client protocol is defined with respect to the following failure model: + +Given a known bound `TRUSTED_PERIOD`, and a block `b` with header `h` generated at time `Time` +(i.e. `h.Time = Time`), a set of validators that hold more than 2/3 of the voting power +in `validators(b.Header.NextValidatorsHash)` is correct until time `b.Header.Time + TRUSTED_PERIOD`. + +*Assumption*: "correct" is defined w.r.t. realtime (some Newtonian global notion of time, i.e., wall time), +while `Header.Time` corresponds to the [BFT time](../../consensus/bft-time.md). In this note, we assume that clocks of correct processes +are synchronized (for example using NTP), and therefore there is bounded clock drift (`CLOCK_DRIFT`) between local clocks and +BFT time. More precisely, for every correct light client process and every `header.Time` (i.e. BFT Time, for a header correctly +generated by the Tendermint consensus), the following inequality holds: `Header.Time < now + CLOCK_DRIFT`, +where `now` corresponds to the system clock at the light client process. + +Furthermore, we assume that `TRUSTED_PERIOD` is (several) order of magnitude bigger than `CLOCK_DRIFT` (`TRUSTED_PERIOD >> CLOCK_DRIFT`), +as `CLOCK_DRIFT` (using NTP) is in the order of milliseconds and `TRUSTED_PERIOD` is in the order of weeks. + +We expect a light client process defined in this document to be used in the context in which there is some +larger period during which misbehaving validators can be detected and punished (we normally refer to it as `UNBONDING_PERIOD` +due to the "bonding" mechanism in modern proof of stake systems). Furthermore, we assume that +`TRUSTED_PERIOD < UNBONDING_PERIOD` and that they are normally of the same order of magnitude, for example +`TRUSTED_PERIOD = UNBONDING_PERIOD / 2`. + +The specification in this document considers an implementation of the light client under the Failure Model defined above. +Mechanisms like `fork accountability` and `evidence submission` are defined in the context of `UNBONDING_PERIOD` and +they incentivize validators to follow the protocol specification defined in this document. If they don't, +and we have 1/3 (or more) faulty validators, safety may be violated. Our approach then is +to *detect* these cases (after the fact), and take suitable repair actions (automatic and social). +This is discussed in document on [Fork accountability](../../consensus/light-client/accountability.md). + +The term "trusted" above indicates that the correctness of the protocol depends on +this assumption. It is in the responsibility of the user that runs the light client to make sure that the risk +of trusting a corrupted/forged `inithead` is negligible. + +*Remark*: This failure model might change to a hybrid version that takes heights into account in the future. + +### High Level Solution + +Upon initialization, the light client is given a header `inithead` it trusts (by +social consensus). When a light clients sees a new signed header `snh`, it has to decide whether to trust the new +header. Trust can be obtained by (possibly) the combination of three methods. + +1. **Uninterrupted sequence of headers.** Given a trusted header `h` and an untrusted header `h1`, +the light client trusts a header `h1` if it trusts all headers in between `h` and `h1`. + +2. **Trusted period.** Given a trusted header `h`, an untrusted header `h1 > h` and `TRUSTED_PERIOD` during which +the failure model holds, we can check whether at least one validator, that has been continuously correct +from `h.Time` until now, has signed `h1`. If this is the case, we can trust `h1`. + +3. **Bisection.** If a check according to 2. (trusted period) fails, the light client can try to +obtain a header `hp` whose height lies between `h` and `h1` in order to check whether `h` can be used to +get trust for `hp`, and `hp` can be used to get trust for `snh`. If this is the case we can trust `h1`; +if not, we continue recursively until either we found set of headers that can build (transitively) trust relation +between `h` and `h1`, or we failed as two consecutive headers don't verify against each other. + +## Definitions + +### Data structures + +In the following, only the details of the data structures needed for this specification are given. + + ```go + type Header struct { + Height int64 + Time Time // the chain time when the header (block) was generated + + LastBlockID BlockID // prev block info + ValidatorsHash []byte // hash of the validators for the current block + NextValidatorsHash []byte // hash of the validators for the next block + } + + type SignedHeader struct { + Header Header + Commit Commit // commit for the given header + } + + type ValidatorSet struct { + Validators []Validator + TotalVotingPower int64 + } + + type Validator struct { + Address Address // validator address (we assume validator's addresses are unique) + VotingPower int64 // validator's voting power + } + + type TrustedState { + SignedHeader SignedHeader + ValidatorSet ValidatorSet + } + ``` + +### Functions + +For the purpose of this light client specification, we assume that the Cosmos Full Node +exposes the following functions over RPC: + +```go + // returns signed header: Header with Commit, for the given height + func Commit(height int64) (SignedHeader, error) + + // returns validator set for the given height + func Validators(height int64) (ValidatorSet, error) +``` + +Furthermore, we assume the following auxiliary functions: + +```go + // returns true if the commit is for the header, ie. if it contains + // the correct hash of the header; otherwise false + func matchingCommit(header Header, commit Commit) bool + + // returns the set of validators from the given validator set that + // committed the block (that correctly signed the block) + // it assumes signature verification so it can be computationally expensive + func signers(commit Commit, validatorSet ValidatorSet) []Validator + + // returns the voting power the validators in v1 have according to their voting power in set v2 + // it does not assume signature verification + func votingPowerIn(v1 []Validator, v2 ValidatorSet) int64 + + // returns hash of the given validator set + func hash(v2 ValidatorSet) []byte +``` + +In the functions below we will be using `trustThreshold` as a parameter. For simplicity +we assume that `trustThreshold` is a float between `1/3` and `2/3` and we will not be checking it +in the pseudo-code. + +**VerifySingle.** The function `VerifySingle` attempts to validate given untrusted header and the corresponding validator sets +based on a given trusted state. It ensures that the trusted state is still within its trusted period, +and that the untrusted header is within assumed `clockDrift` bound of the passed time `now`. +Note that this function is not making external (RPC) calls to the full node; the whole logic is +based on the local (given) state. This function is supposed to be used by the IBC handlers. + +```go +func VerifySingle(untrustedSh SignedHeader, + untrustedVs ValidatorSet, + untrustedNextVs ValidatorSet, + trustedState TrustedState, + trustThreshold float, + trustingPeriod Duration, + clockDrift Duration, + now Time) (TrustedState, error) { + + if untrustedSh.Header.Time > now + clockDrift { + return (trustedState, ErrInvalidHeaderTime) + } + + trustedHeader = trustedState.SignedHeader.Header + if !isWithinTrustedPeriod(trustedHeader, trustingPeriod, now) { + return (state, ErrHeaderNotWithinTrustedPeriod) + } + + // we assume that time it takes to execute verifySingle function + // is several order of magnitudes smaller than trustingPeriod + error = verifySingle( + trustedState, + untrustedSh, + untrustedVs, + untrustedNextVs, + trustThreshold) + + if error != nil return (state, error) + + // the untrusted header is now trusted + newTrustedState = TrustedState(untrustedSh, untrustedNextVs) + return (newTrustedState, nil) +} + +// return true if header is within its light client trusted period; otherwise returns false +func isWithinTrustedPeriod(header Header, + trustingPeriod Duration, + now Time) bool { + + return header.Time + trustedPeriod > now +} +``` + +Note that in case `VerifySingle` returns without an error (untrusted header +is successfully verified) then we have a guarantee that the transition of the trust +from `trustedState` to `newTrustedState` happened during the trusted period of +`trustedState.SignedHeader.Header`. + +TODO: Explain what happens in case `VerifySingle` returns with an error. + +**verifySingle.** The function `verifySingle` verifies a single untrusted header +against a given trusted state. It includes all validations and signature verification. +It is not publicly exposed since it does not check for header expiry (time constraints) +and hence it's possible to use it incorrectly. + +```go +func verifySingle(trustedState TrustedState, + untrustedSh SignedHeader, + untrustedVs ValidatorSet, + untrustedNextVs ValidatorSet, + trustThreshold float) error { + + untrustedHeader = untrustedSh.Header + untrustedCommit = untrustedSh.Commit + + trustedHeader = trustedState.SignedHeader.Header + trustedVs = trustedState.ValidatorSet + + if trustedHeader.Height >= untrustedHeader.Height return ErrNonIncreasingHeight + if trustedHeader.Time >= untrustedHeader.Time return ErrNonIncreasingTime + + // validate the untrusted header against its commit, vals, and next_vals + error = validateSignedHeaderAndVals(untrustedSh, untrustedVs, untrustedNextVs) + if error != nil return error + + // check for adjacent headers + if untrustedHeader.Height == trustedHeader.Height + 1 { + if trustedHeader.NextValidatorsHash != untrustedHeader.ValidatorsHash { + return ErrInvalidAdjacentHeaders + } + } else { + error = verifyCommitTrusting(trustedVs, untrustedCommit, untrustedVs, trustThreshold) + if error != nil return error + } + + // verify the untrusted commit + return verifyCommitFull(untrustedVs, untrustedCommit) +} + +// returns nil if header and validator sets are consistent; otherwise returns error +func validateSignedHeaderAndVals(signedHeader SignedHeader, vs ValidatorSet, nextVs ValidatorSet) error { + header = signedHeader.Header + if hash(vs) != header.ValidatorsHash return ErrInvalidValidatorSet + if hash(nextVs) != header.NextValidatorsHash return ErrInvalidNextValidatorSet + if !matchingCommit(header, signedHeader.Commit) return ErrInvalidCommitValue + return nil +} + +// returns nil if at least single correst signer signed the commit; otherwise returns error +func verifyCommitTrusting(trustedVs ValidatorSet, + commit Commit, + untrustedVs ValidatorSet, + trustLevel float) error { + + totalPower := trustedVs.TotalVotingPower + signedPower := votingPowerIn(signers(commit, untrustedVs), trustedVs) + + // check that the signers account for more than max(1/3, trustLevel) of the voting power + // this ensures that there is at least single correct validator in the set of signers + if signedPower < max(1/3, trustLevel) * totalPower return ErrInsufficientVotingPower + return nil +} + +// returns nil if commit is signed by more than 2/3 of voting power of the given validator set +// return error otherwise +func verifyCommitFull(vs ValidatorSet, commit Commit) error { + totalPower := vs.TotalVotingPower; + signedPower := votingPowerIn(signers(commit, vs), vs) + + // check the signers account for +2/3 of the voting power + if signedPower * 3 <= totalPower * 2 return ErrInvalidCommit + return nil +} +``` + +**VerifyHeaderAtHeight.** The function `VerifyHeaderAtHeight` captures high level +logic, i.e., application call to the light client module to download and verify header +for some height. + +```go +func VerifyHeaderAtHeight(untrustedHeight int64, + trustedState TrustedState, + trustThreshold float, + trustingPeriod Duration, + clockDrift Duration) (TrustedState, error)) { + + trustedHeader := trustedState.SignedHeader.Header + + now := System.Time() + if !isWithinTrustedPeriod(trustedHeader, trustingPeriod, now) { + return (trustedState, ErrHeaderNotWithinTrustedPeriod) + } + + newTrustedState, err := VerifyBisection(untrustedHeight, + trustedState, + trustThreshold, + trustingPeriod, + clockDrift, + now) + + if err != nil return (trustedState, err) + + now = System.Time() + if !isWithinTrustedPeriod(trustedHeader, trustingPeriod, now) { + return (trustedState, ErrHeaderNotWithinTrustedPeriod) + } + + return (newTrustedState, err) +} +``` + +Note that in case `VerifyHeaderAtHeight` returns without an error (untrusted header +is successfully verified) then we have a guarantee that the transition of the trust +from `trustedState` to `newTrustedState` happened during the trusted period of +`trustedState.SignedHeader.Header`. + +In case `VerifyHeaderAtHeight` returns with an error, then either (i) the full node we are talking to is faulty +or (ii) the trusted header has expired (it is outside its trusted period). In case (i) the full node is faulty so +light client should disconnect and reinitialize with new peer. In the case (ii) as the trusted header has expired, +we need to reinitialize light client with a new trusted header (that is within its trusted period), +but we don't necessarily need to disconnect from the full node we are talking to (as we haven't observed full node misbehavior in this case). + +**VerifyBisection.** The function `VerifyBisection` implements +recursive logic for checking if it is possible building trust +relationship between `trustedState` and untrusted header at the given height over +finite set of (downloaded and verified) headers. + +```go +func VerifyBisection(untrustedHeight int64, + trustedState TrustedState, + trustThreshold float, + trustingPeriod Duration, + clockDrift Duration, + now Time) (TrustedState, error) { + + untrustedSh, error := Commit(untrustedHeight) + if error != nil return (trustedState, ErrRequestFailed) + + untrustedHeader = untrustedSh.Header + + // note that we pass now during the recursive calls. This is fine as + // all other untrusted headers we download during recursion will be + // for a smaller heights, and therefore should happen before. + if untrustedHeader.Time > now + clockDrift { + return (trustedState, ErrInvalidHeaderTime) + } + + untrustedVs, error := Validators(untrustedHeight) + if error != nil return (trustedState, ErrRequestFailed) + + untrustedNextVs, error := Validators(untrustedHeight + 1) + if error != nil return (trustedState, ErrRequestFailed) + + error = verifySingle( + trustedState, + untrustedSh, + untrustedVs, + untrustedNextVs, + trustThreshold) + + if fatalError(error) return (trustedState, error) + + if error == nil { + // the untrusted header is now trusted. + newTrustedState = TrustedState(untrustedSh, untrustedNextVs) + return (newTrustedState, nil) + } + + // at this point in time we need to do bisection + pivotHeight := ceil((trustedHeader.Height + untrustedHeight) / 2) + + error, newTrustedState = VerifyBisection(pivotHeight, + trustedState, + trustThreshold, + trustingPeriod, + clockDrift, + now) + if error != nil return (newTrustedState, error) + + return VerifyBisection(untrustedHeight, + newTrustedState, + trustThreshold, + trustingPeriod, + clockDrift, + now) +} + +func fatalError(err) bool { + return err == ErrHeaderNotWithinTrustedPeriod OR + err == ErrInvalidAdjacentHeaders OR + err == ErrNonIncreasingHeight OR + err == ErrNonIncreasingTime OR + err == ErrInvalidValidatorSet OR + err == ErrInvalidNextValidatorSet OR + err == ErrInvalidCommitValue OR + err == ErrInvalidCommit +} +``` + +### The case `untrustedHeader.Height < trustedHeader.Height` + +In the use case where someone tells the light client that application data that is relevant for it +can be read in the block of height `k` and the light client trusts a more recent header, we can use the +hashes to verify headers "down the chain." That is, we iterate down the heights and check the hashes in each step. + +*Remark.* For the case were the light client trusts two headers `i` and `j` with `i < k < j`, we should +discuss/experiment whether the forward or the backward method is more effective. + +```go +func VerifyHeaderBackwards(trustedHeader Header, + untrustedHeader Header, + trustingPeriod Duration, + clockDrift Duration) error { + + if untrustedHeader.Height >= trustedHeader.Height return ErrErrNonDecreasingHeight + if untrustedHeader.Time >= trustedHeader.Time return ErrNonDecreasingTime + + now := System.Time() + if !isWithinTrustedPeriod(trustedHeader, trustingPeriod, now) { + return ErrHeaderNotWithinTrustedPeriod + } + + old := trustedHeader + for i := trustedHeader.Height - 1; i > untrustedHeader.Height; i-- { + untrustedSh, error := Commit(i) + if error != nil return ErrRequestFailed + + if (hash(untrustedSh.Header) != old.LastBlockID.Hash) { + return ErrInvalidAdjacentHeaders + } + + old := untrustedSh.Header + } + + if hash(untrustedHeader) != old.LastBlockID.Hash { + return ErrInvalidAdjacentHeaders + } + + now := System.Time() + if !isWithinTrustedPeriod(trustedHeader, trustingPeriod, now) { + return ErrHeaderNotWithinTrustedPeriod + } + + return nil + } +``` + +*Assumption*: In the following, we assume that *untrusted_h.Header.height > trusted_h.Header.height*. We will quickly discuss the other case in the next section. + +We consider the following set-up: + +- the light client communicates with one full node +- the light client locally stores all the headers that has passed basic verification and that are within light client trust period. In the pseudo code below we +write *Store.Add(header)* for this. If a header failed to verify, then +the full node we are talking to is faulty and we should disconnect from it and reinitialize with new peer. +- If `CanTrust` returns *error*, then the light client has seen a forged header or the trusted header has expired (it is outside its trusted period). + - In case of forged header, the full node is faulty so light client should disconnect and reinitialize with new peer. If the trusted header has expired, + we need to reinitialize light client with new trusted header (that is within its trusted period), but we don't necessarily need to disconnect from the full node + we are talking to (as we haven't observed full node misbehavior in this case). + +## Correctness of the Light Client Protocols + +### Definitions + +- `TRUSTED_PERIOD`: trusted period +- for realtime `t`, the predicate `correct(v,t)` is true if the validator `v` + follows the protocol until time `t` (we will see about recovery later). +- Validator fields. We will write a validator as a tuple `(v,p)` such that + - `v` is the identifier (i.e., validator address; we assume identifiers are unique in each validator set) + - `p` is its voting power +- For each header `h`, we write `trust(h) = true` if the light client trusts `h`. + +### Failure Model + +If a block `b` with a header `h` is generated at time `Time` (i.e. `h.Time = Time`), then a set of validators that +hold more than `2/3` of the voting power in `validators(h.NextValidatorsHash)` is correct until time +`h.Time + TRUSTED_PERIOD`. + +Formally, +\[ +\sum_{(v,p) \in validators(h.NextValidatorsHash) \wedge correct(v,h.Time + TRUSTED_PERIOD)} p > +2/3 \sum_{(v,p) \in validators(h.NextValidatorsHash)} p +\] + +The light client communicates with a full node and learns new headers. The goal is to locally decide whether to trust a header. Our implementation needs to ensure the following two properties: + +- *Light Client Completeness*: If a header `h` was correctly generated by an instance of Tendermint consensus (and its age is less than the trusted period), +then the light client should eventually set `trust(h)` to `true`. + +- *Light Client Accuracy*: If a header `h` was *not generated* by an instance of Tendermint consensus, then the light client should never set `trust(h)` to true. + +*Remark*: If in the course of the computation, the light client obtains certainty that some headers were forged by adversaries +(that is were not generated by an instance of Tendermint consensus), it may submit (a subset of) the headers it has seen as evidence of misbehavior. + +*Remark*: In Completeness we use "eventually", while in practice `trust(h)` should be set to true before `h.Time + TRUSTED_PERIOD`. If not, the header +cannot be trusted because it is too old. + +*Remark*: If a header `h` is marked with `trust(h)`, but it is too old at some point in time we denote with `now` (`h.Time + TRUSTED_PERIOD < now`), +then the light client should set `trust(h)` to `false` again at time `now`. + +*Assumption*: Initially, the light client has a header `inithead` that it trusts, that is, `inithead` was correctly generated by the Tendermint consensus. + +To reason about the correctness, we may prove the following invariant. + +*Verification Condition: light Client Invariant.* + For each light client `l` and each header `h`: +if `l` has set `trust(h) = true`, + then validators that are correct until time `h.Time + TRUSTED_PERIOD` have more than two thirds of the voting power in `validators(h.NextValidatorsHash)`. + + Formally, + \[ + \sum_{(v,p) \in validators(h.NextValidatorsHash) \wedge correct(v,h.Time + TRUSTED_PERIOD)} p > + 2/3 \sum_{(v,p) \in validators(h.NextValidatorsHash)} p + \] + +*Remark.* To prove the invariant, we will have to prove that the light client only trusts headers that were correctly generated by Tendermint consensus. +Then the formula above follows from the failure model. + +## Details + +**Observation 1.** If `h.Time + TRUSTED_PERIOD > now`, we trust the validator set `validators(h.NextValidatorsHash)`. + +When we say we trust `validators(h.NextValidatorsHash)` we do `not` trust that each individual validator in `validators(h.NextValidatorsHash)` +is correct, but we only trust the fact that less than `1/3` of them are faulty (more precisely, the faulty ones have less than `1/3` of the total voting power). + +*`VerifySingle` correctness arguments* + +Light Client Accuracy: + +- Assume by contradiction that `untrustedHeader` was not generated correctly and the light client sets trust to true because `verifySingle` returns without error. +- `trustedState` is trusted and sufficiently new +- by the Failure Model, less than `1/3` of the voting power held by faulty validators => at least one correct validator `v` has signed `untrustedHeader`. +- as `v` is correct up to now, it followed the Tendermint consensus protocol at least up to signing `untrustedHeader` => `untrustedHeader` was correctly generated. +We arrive at the required contradiction. + +Light Client Completeness: + +- The check is successful if sufficiently many validators of `trustedState` are still validators in the height `untrustedHeader.Height` and signed `untrustedHeader`. +- If `untrustedHeader.Height = trustedHeader.Height + 1`, and both headers were generated correctly, the test passes. + +*Verification Condition:* We may need an invariant stating that if `untrustedSignedHeader.Header.Height = trustedHeader.Height + 1` then +`signers(untrustedSignedHeader.Commit) \subseteq validators(trustedHeader.NextValidatorsHash)`. + +*Remark*: The variable `trustThreshold` can be used if the user believes that relying on one correct validator is not sufficient. +However, in case of (frequent) changes in the validator set, the higher the `trustThreshold` is chosen, the more unlikely it becomes that +`verifySingle` returns with an error for non-adjacent headers. + +- `VerifyBisection` correctness arguments (sketch)* + +Light Client Accuracy: + +- Assume by contradiction that the header at `untrustedHeight` obtained from the full node was not generated correctly and +the light client sets trust to true because `VerifyBisection` returns without an error. +- `VerifyBisection` returns without error only if all calls to `verifySingle` in the recursion return without error (return `nil`). +- Thus we have a sequence of headers that all satisfied the `verifySingle` +- again a contradiction + +light Client Completeness: + +This is only ensured if upon `Commit(pivot)` the light client is always provided with a correctly generated header. + +*Stalling* + +With `VerifyBisection`, a faulty full node could stall a light client by creating a long sequence of headers that are queried one-by-one by the light client and look OK, +before the light client eventually detects a problem. There are several ways to address this: + +- Each call to `Commit` could be issued to a different full node +- Instead of querying header by header, the light client tells a full node which header it trusts, and the height of the header it needs. The full node responds with +the header along with a proof consisting of intermediate headers that the light client can use to verify. Roughly, `VerifyBisection` would then be executed at the full node. +- We may set a timeout how long `VerifyBisection` may take. diff --git a/spec/light-client/verification/verification_001_published.md b/spec/light-client/verification/verification_001_published.md new file mode 100644 index 0000000..062eb56 --- /dev/null +++ b/spec/light-client/verification/verification_001_published.md @@ -0,0 +1,1170 @@ +# Light Client Verification + +The light client implements a read operation of a +[header][#cmbc-header1] from the [blockchain][cmbc-seq1], by +communicating with full nodes. As some full nodes may be faulty, this +functionality must be implemented in a fault-tolerant way. + +In a Cosmos blockchain, the validator set may change with every +new block. The staking and unbonding mechanism induces a [security +model][CMBC-FM-2THIRDS-link]: starting at time *Time* of the +[header][#cmbc-header1], +more than two-thirds of the next validators of a new block are correct +for the duration of *TrustedPeriod*. The fault-tolerant read +operation is designed for this security model. + +The challenge addressed here is that the light client might have a +block of height *h1* and needs to read the block of height *h2* +greater than *h1*. Checking all headers of heights from *h1* to *h2* +might be too costly (e.g., in terms of energy for mobile devices). +This specification tries to reduce the number of intermediate blocks +that need to be checked, by exploiting the guarantees provided by the +[security model][cmbc-fm-2thirds1]. + +# Status + +This document is thoroughly reviewed, and the protocol has been +formalized in TLA+ and model checked. + +## Issues that need to be addressed + +As it is part of the larger light node, its data structures and +functions interact with the fork dectection functionality of the light +client. As a result of the work on +[Pull Request 479](https://github.com/informalsystems/tendermint-rs/pull/479) we +established the need for an update in the data structures in [Issue 499](https://github.com/informalsystems/tendermint-rs/issues/499). This +will not change the verification logic, but it will record information +about verification that can be used in fork detection (in particular +in computing more efficiently the proof of fork). + +# Outline + +- [Part I](#part-i---cosmos-blockchain): Introduction of + relevant terms of the Cosmos +blockchain. + +- [Part II](#part-ii---sequential-definition-of-the-verification-problem): Introduction +of the problem addressed by the Lightclient Verification protocol. + - [Verification Informal Problem + statement](#verification-informal-problem-statement): For the general + audience, that is, engineers who want to get an overview over what + the component is doing from a bird's eye view. + - [Sequential Problem statement](#sequential-problem-statement): + Provides a mathematical definition of the problem statement in + its sequential form, that is, ignoring the distributed aspect of + the implementation of the blockchain. + +- [Part III](#part-iii---light-client-as-distributed-system): Distributed + aspects of the light client, system assumptions and temporal + logic specifications. + + - [Incentives](#incentives): how faulty full nodes may benefit from + misbehaving and how correct full nodes benefit from cooperating. + + - [Computational Model](#computational-model): + timing and correctness assumptions. + + - [Distributed Problem Statement](#distributed-problem-statement): + temporal properties that formalize safety and liveness + properties in the distributed setting. + +- [Part IV](#part-iv---light-client-verification-protocol): + Specification of the protocols. + + - [Definitions](#definitions): Describes inputs, outputs, + variables used by the protocol, auxiliary functions + + - [Core Verification](#core-verification): gives an outline of the solution, + and details of the functions used (with preconditions, + postconditions, error conditions). + + - [Liveness Scenarios](#liveness-scenarios): when the light + client makes progress depends heavily on the changes in the + validator sets of the blockchain. We discuss some typical scenarios. + +- [Part V](#part-v---supporting-the-ibc-relayer): The above parts + focus on a common case where the last verified block has height *h1* + and the + requested height *h2* satisfies *h2 > h1*. For IBC, there are + scenarios where this might not be the case. In this part, we provide + some preliminaries for supporting this. As not all details of the + IBC requirements are clear by now, we do not provide a complete + specification at this point. We mark with "Open Question" points + that need to be addressed in order to finalize this specification. + It should be noted that the technically + most challenging case is the one specified in Part IV. + +In this document we quite extensively use tags in order to be able to +reference assumptions, invariants, etc. in future communication. In +these tags we frequently use the following short forms: + +- CMBC: Cosmos blockchain +- SEQ: for sequential specifications +- LCV: Lightclient Verification +- LIVE: liveness +- SAFE: safety +- FUNC: function +- INV: invariant +- A: assumption + +# Part I - Cosmos Blockchain + +## Header Fields necessary for the Light Client + +#### **[CMBC-HEADER.1]** + +A set of blockchain transactions is stored in a data structure called +*block*, which contains a field called *header*. (The data structure +*block* is defined [here][block]). As the header contains hashes to +the relevant fields of the block, for the purpose of this +specification, we will assume that the blockchain is a list of +headers, rather than a list of blocks. + +#### **[CMBC-HASH-UNIQUENESS.1]** + +We assume that every hash in the header identifies the data it hashes. +Therefore, in this specification, we do not distinguish between hashes and the +data they represent. + +#### **[CMBC-HEADER-FIELDS.1]** + +A header contains the following fields: + +- `Height`: non-negative integer +- `Time`: time (integer) +- `LastBlockID`: Hashvalue +- `LastCommit` DomainCommit +- `Validators`: DomainVal +- `NextValidators`: DomainVal +- `Data`: DomainTX +- `AppState`: DomainApp +- `LastResults`: DomainRes + +#### **[CMBC-SEQ.1]** + +The Cosmos blockchain is a list *chain* of headers. + +#### **[CMBC-VALIDATOR-PAIR.1]** + +Given a full node, a +*validator pair* is a pair *(peerID, voting_power)*, where + +- *peerID* is the PeerID (public key) of a full node, +- *voting_power* is an integer (representing the full node's + voting power in a certain consensus instance). + +> In the Golang implementation the data type for *validator +pair* is called `Validator` + +#### **[CMBC-VALIDATOR-SET.1]** + +A *validator set* is a set of validator pairs. For a validator set +*vs*, we write *TotalVotingPower(vs)* for the sum of the voting powers +of its validator pairs. + +#### **[CMBC-VOTE.1]** + +A *vote* contains a `prevote` or `precommit` message sent and signed by +a validator node during the execution of [consensus][arXiv]. Each +message contains the following fields + +- `Type`: prevote or precommit +- `Height`: positive integer +- `Round` a positive integer +- `BlockID` a Hashvalue of a block (not necessarily a block of the chain) + +#### **[CMBC-COMMIT.1]** + +A commit is a set of `precommit` message. + +## Cosmos Failure Model + +#### **[CMBC-AUTH-BYZ.1]** + +We assume the authenticated Byzantine fault model in which no node (faulty or +correct) may break digital signatures, but otherwise, no additional +assumption is made about the internal behavior of faulty +nodes. That is, faulty nodes are only limited in that they cannot forge +messages. + +#### **[CMBC-TIME-PARAMS.1]** + +A Cosmos blockchain has the following configuration parameters: + +- *unbondingPeriod*: a time duration. +- *trustingPeriod*: a time duration smaller than *unbondingPeriod*. + +#### **[CMBC-CORRECT.1]** + +We define a predicate *correctUntil(n, t)*, where *n* is a node and *t* is a +time point. +The predicate *correctUntil(n, t)* is true if and only if the node *n* +follows all the protocols (at least) until time *t*. + +#### **[CMBC-FM-2THIRDS.1]** + +If a block *h* is in the chain, +then there exists a subset *CorrV* +of *h.NextValidators*, such that: + +- *TotalVotingPower(CorrV) > 2/3 + TotalVotingPower(h.NextValidators)*; cf. [CMBC-VALIDATOR-SET.1] +- For every validator pair *(n,p)* in *CorrV*, it holds *correctUntil(n, + h.Time + trustingPeriod)*; cf. [CMBC-CORRECT.1] + +> The definition of correct +> [**[CMBC-CORRECT.1]**][CMBC-CORRECT-link] refers to realtime, while it +> is used here with *Time* and *trustingPeriod*, which are "hardware +> times". We do not make a distinction here. + +#### **[CMBC-CORR-FULL.1]** + +Every correct full node locally stores a prefix of the +current list of headers from [**[CMBC-SEQ.1]**][CMBC-SEQ-link]. + +## What the Light Client Checks + +> From [CMBC-FM-2THIRDS.1] we directly derive the following observation: + +#### **[CMBC-VAL-CONTAINS-CORR.1]** + +Given a (trusted) block *tb* of the blockchain, a given set of full nodes +*N* contains a correct node at a real-time *t*, if + +- *t - trustingPeriod < tb.Time < t* +- the voting power in tb.NextValidators of nodes in *N* is more + than 1/3 of *TotalVotingPower(tb.NextValidators)* + +> The following describes how a commit for a given block *b* must look +> like. + +#### **[CMBC-SOUND-DISTR-POSS-COMMIT.1]** + +For a block *b*, each element *pc* of *PossibleCommit(b)* satisfies: + +- *pc* contains only votes (cf. [CMBC-VOTE.1]) + by validators from *b.Validators* +- the sum of the voting powers in *pc* is greater than 2/3 + *TotalVotingPower(b.Validators)* +- and there is an *r* such that each vote *v* in *pc* satisfies + - v.Type = precommit + - v.Height = b.Height + - v.Round = r + - v.blockID = hash(b) + +> The following property comes from the validity of the [consensus][arXiv]: A +> correct validator node only sends `prevote` or `precommit`, if +> `BlockID` of the new (to-be-decided) block is equal to the hash of +> the last block. + +#### **[CMBC-VAL-COMMIT.1]** + +If for a block *b*, a commit *c* + +- contains at least one validator pair *(v,p)* such that *v* is a + **correct** validator node, and +- is contained in *PossibleCommit(b)* + +then the block *b* is on the blockchain. + +## Context of this document + +In this document we specify the light client verification component, +called *Core Verification*. The *Core Verification* communicates with +a full node. As full nodes may be faulty, it cannot trust the +received information, but the light client has to check whether the +header it receives coincides with the one generated by Tendermint +consensus. + +The two + properties [[CMBC-VAL-CONTAINS-CORR.1]][CMBC-VAL-CONTAINS-CORR-link] and +[[CMBC-VAL-COMMIT]][CMBC-VAL-COMMIT-link] formalize the checks done + by this specification: +Given a trusted block *tb* and an untrusted block *ub* with a commit *cub*, +one has to check that *cub* is in *PossibleCommit(ub)*, and that *cub* +contains a correct node using *tb*. + +# Part II - Sequential Definition of the Verification Problem + +## Verification Informal Problem statement + +Given a height *targetHeight* as an input, the *Verifier* eventually +stores a header *h* of height *targetHeight* locally. This header *h* +is generated by the Cosmos [blockchain][block]. In +particular, a header that was not generated by the blockchain should +never be stored. + +## Sequential Problem statement + +#### **[LCV-SEQ-LIVE.1]** + +The *Verifier* gets as input a height *targetHeight*, and eventually stores the +header of height *targetHeight* of the blockchain. + +#### **[LCV-SEQ-SAFE.1]** + +The *Verifier* never stores a header which is not in the blockchain. + +# Part III - Light Client as Distributed System + +## Incentives + +Faulty full nodes may benefit from lying to the light client, by making the +light client accept a block that deviates (e.g., contains additional +transactions) from the one generated by Tendermint consensus. +Users using the light client might be harmed by accepting a forged header. + +The [fork detector][fork-detector] of the light client may help the +correct full nodes to understand whether their header is a good one. +Hence, in combination with the light client detector, the correct full +nodes have the incentive to respond. We can thus base liveness +arguments on the assumption that correct full nodes reliably talk to +the light client. + +## Computational Model + +#### **[LCV-A-PEER.1]** + +The verifier communicates with a full node called *primary*. No assumption is made about the full node (it may be correct or faulty). + +#### **[LCV-A-COMM.1]** + +Communication between the light client and a correct full node is +reliable and bounded in time. Reliable communication means that +messages are not lost, not duplicated, and eventually delivered. There +is a (known) end-to-end delay *Delta*, such that if a message is sent +at time *t* then it is received and processes by time *t + Delta*. +This implies that we need a timeout of at least *2 Delta* for remote +procedure calls to ensure that the response of a correct peer arrives +before the timeout expires. + +#### **[LCV-A-TFM.1]** + +The Cosmos blockchain satisfies the Cosmos failure model [**[CMBC-FM-2THIRDS.1]**][CMBC-FM-2THIRDS-link]. + +#### **[LCV-A-VAL.1]** + +The system satisfies [**[CMBC-AUTH-BYZ.1]**][CMBC-Auth-Byz-link] and +[**[CMBC-FM-2THIRDS.1]**][CMBC-FM-2THIRDS-link]. Thus, there is a +blockchain that satisfies the soundness requirements (that is, the +validation rules in [[block]]). + +## Distributed Problem Statement + +### Two Kinds of Termination + +We do not assume that *primary* is correct. Under this assumption no +protocol can guarantee the combination of the sequential +properties. Thus, in the (unreliable) distributed setting, we consider +two kinds of termination (successful and failure) and we will specify +below under what (favorable) conditions *Core Verification* ensures to +terminate successfully, and satisfy the requirements of the sequential +problem statement: + +#### **[LCV-DIST-TERM.1]** + +*Core Verification* either *terminates +successfully* or it *terminates with failure*. + +### Design choices + +#### **[LCV-DIST-STORE.1]** + +*Core Verification* has a local data structure called *LightStore* that +contains light blocks (that contain a header). For each light block we +record whether it is verified. + +#### **[LCV-DIST-PRIMARY.1]** + +*Core Verification* has a local variable *primary* that contains the PeerID of a full node. + +#### **[LCV-DIST-INIT.1]** + +*LightStore* is initialized with a header *trustedHeader* that was correctly +generated by the Tendermint consensus. We say *trustedHeader* is verified. + +### Temporal Properties + +#### **[LCV-DIST-SAFE.1]** + +It is always the case that every verified header in *LightStore* was +generated by an instance of Tendermint consensus. + +#### **[LCV-DIST-LIVE.1]** + +From time to time, a new instance of *Core Verification* is called with a +height *targetHeight* greater than the height of any header in *LightStore*. +Each instance must eventually terminate. + +- If + - the *primary* is correct (and locally has the block of + *targetHeight*), and + - *LightStore* always contains a verified header whose age is less than the + trusting period, + then *Core Verification* adds a verified header *hd* with height + *targetHeight* to *LightStore* and it **terminates successfully** + +> These definitions imply that if the primary is faulty, a header may or +> may not be added to *LightStore*. In any case, +> [**[LCV-DIST-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe1) must hold. +> The invariant [**[LCV-DIST-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe1) and the liveness +> requirement [**[LCV-DIST-LIVE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-life1) +> allow that verified headers are added to *LightStore* whose +> height was not passed +> to the verifier (e.g., intermediate headers used in bisection; see below). +> Note that for liveness, initially having a *trustedHeader* within +> the *trustinPeriod* is not sufficient. However, as this +> specification will leave some freedom with respect to the strategy +> in which order to download intermediate headers, we do not give a +> more precise liveness specification here. After giving the +> specification of the protocol, we will discuss some liveness +> scenarios [below](#liveness-scenarios). + +### Solving the sequential specification + +This specification provides a partial solution to the sequential specification. +The *Verifier* solves the invariant of the sequential part + +[**[LCV-DIST-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe1) => [**[LCV-SEQ-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-seq-inv) + +In the case the primary is correct, and there is a recent header in *LightStore*, the verifier satisfies the liveness requirements. + +⋀ *primary is correct* +⋀ always ∃ verified header in LightStore. *header.Time* > *now* - *trustingPeriod* +⋀ [**[LCV-A-Comm.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-a-comm) ⋀ ( + ( [**[CMBC-CorrFull.1]**][CMBC-CorrFull-link] ⋀ + [**[LCV-DIST-LIVE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-live1) ) + ⟹ [**[LCV-SEQ-LIVE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-seq-live1) +) + +# Part IV - Light Client Verification Protocol + +We provide a specification for Light Client Verification. The local +code for verification is presented by a sequential function +`VerifyToTarget` to highlight the control flow of this functionality. +We note that if a different concurrency model is considered for +an implementation, the sequential flow of the function may be +implemented with mutexes, etc. However, the light client verification +is partitioned into three blocks that can be implemented and tested +independently: + +- `FetchLightBlock` is called to download a light block (header) of a + given height from a peer. +- `ValidAndVerified` is a local code that checks the header. +- `Schedule` decides which height to try to verify next. We keep this + underspecified as different implementations (currently in Goland and + Rust) may implement different optimizations here. We just provide + necessary conditions on how the height may evolve. + + + + +## Definitions + +### Data Types + +The core data structure of the protocol is the LightBlock. + +#### **[LCV-DATA-LIGHTBLOCK.1]** + +```go +type LightBlock struct { + Header Header + Commit Commit + Validators ValidatorSet +} +``` + +#### **[LCV-DATA-LIGHTSTORE.1]** + +LightBlocks are stored in a structure which stores all LightBlock from +initialization or received from peers. + +```go +type LightStore struct { + ... +} + +``` + +Each LightBlock is in one of the following states: + +```go +type VerifiedState int + +const ( + StateUnverified = iota + 1 + StateVerified + StateFailed + StateTrusted +) +``` + +> Only the detector module sets a lightBlock state to `StateTrusted` +> and only if it was `StateVerified` before. + +The LightStore exposes the following functions to query stored LightBlocks. + +#### **[LCV-FUNC-GET.1]** + +```go +func (ls LightStore) Get(height Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a LightBlock at a given height or false in the second argument if + the LightStore does not contain the specified LightBlock. + +#### **[LCV-FUNC-LATEST-VERIF.1]** + +```go +func (ls LightStore) LatestVerified() LightBlock +``` + +- Expected postcondition + - returns the highest light block whose state is `StateVerified` + or `StateTrusted` + +#### **[LCV-FUNC-UPDATE.2]** + +```go +func (ls LightStore) Update(lightBlock LightBlock, + verfiedState VerifiedState + verifiedBy Height) +``` + +- Expected postcondition + - The state of the LightBlock is set to *verifiedState*. + - verifiedBy of the Lightblock is set to *Height* + +> The following function is used only in the detector specification +> listed here for completeness. + +#### **[LCV-FUNC-LATEST-TRUSTED.1]** + +```go +func (ls LightStore) LatestTrusted() LightBlock +``` + +- Expected postcondition + - returns the highest light block that has been verified and + checked by the detector. + +#### **[LCV-FUNC-FILTER.1]** + +```go +func (ls LightStore) FilterVerified() LightSTore +``` + +- Expected postcondition + - returns only the LightBlocks with state verified. + +### Inputs + +- *lightStore*: stores light blocks that have been downloaded and that + passed verification. Initially it contains a light block with + *trustedHeader*. +- *primary*: peerID +- *targetHeight*: the height of the needed header + +### Configuration Parameters + +- *trustThreshold*: a float. Can be used if correctness should not be based on more voting power and 1/3. +- *trustingPeriod*: a time duration [**[CMBC-TIME_PARAMS.1]**][CMBC-TIME_PARAMS-link]. +- *clockDrift*: a time duration. Correction parameter dealing with only approximately synchronized clocks. + +### Variables + +- *nextHeight*: initially *targetHeight* + > *nextHeight* should be thought of the "height of the next header we need + > to download and verify" + +### Assumptions + +#### **[LCV-A-INIT.1]** + +- *trustedHeader* is from the blockchain + +- *targetHeight > LightStore.LatestVerified.Header.Height* + +### Invariants + +#### **[LCV-INV-TP.1]** + +It is always the case that *LightStore.LatestTrusted.Header.Time > now - trustingPeriod*. + +> If the invariant is violated, the light client does not have a +> header it can trust. A trusted header must be obtained externally, +> its trust can only be based on social consensus. + +### Used Remote Functions + +We use the functions `commit` and `validators` that are provided +by the [RPC client][RPC]. + +```go +func Commit(height int64) (SignedHeader, error) +``` + +- Implementation remark + - RPC to full node *n* + - JSON sent: + +```javascript +// POST /commit +{ + "jsonrpc": "2.0", + "id": "ccc84631-dfdb-4adc-b88c-5291ea3c2cfb", // UUID v4, unique per request + "method": "commit", + "params": { + "height": 1234 + } +} +``` + +- Expected precondition + - header of `height` exists on blockchain +- Expected postcondition + - if *n* is correct: Returns the signed header of height `height` + from the blockchain if communication is timely (no timeout) + - if *n* is faulty: Returns a signed header with arbitrary content +- Error condition + - if *n* is correct: precondition violated or timeout + - if *n* is faulty: arbitrary error + +---- + +```go +func Validators(height int64) (ValidatorSet, error) +``` + +- Implementation remark + - RPC to full node *n* + - JSON sent: + +```javascript +// POST /validators +{ + "jsonrpc": "2.0", + "id": "ccc84631-dfdb-4adc-b88c-5291ea3c2cfb", // UUID v4, unique per request + "method": "validators", + "params": { + "height": 1234 + } +} +``` + +- Expected precondition + - header of `height` exists on blockchain +- Expected postcondition + - if *n* is correct: Returns the validator set of height `height` + from the blockchain if communication is timely (no timeout) + - if *n* is faulty: Returns arbitrary validator set +- Error condition + - if *n* is correct: precondition violated or timeout + - if *n* is faulty: arbitrary error + +---- + +### Communicating Function + +#### **[LCV-FUNC-FETCH.1]** + + ```go +func FetchLightBlock(peer PeerID, height Height) LightBlock +``` + +- Implementation remark + - RPC to peer at *PeerID* + - calls `Commit` for *height* and `Validators` for *height* and *height+1* +- Expected precondition + - `height` is less than or equal to height of the peer **[LCV-IO-PRE-HEIGHT.1]** +- Expected postcondition: + - if *node* is correct: + - Returns the LightBlock *lb* of height `height` + that is consistent with the blockchain + - *lb.provider = peer* **[LCV-IO-POST-PROVIDER.1]** + - *lb.Header* is a header consistent with the blockchain + - *lb.Validators* is the validator set of the blockchain at height *nextHeight* + - *lb.NextValidators* is the validator set of the blockchain at height *nextHeight + 1* + - if *node* is faulty: Returns a LightBlock with arbitrary content + [**[CMBC-AUTH-BYZ.1]**][CMBC-Auth-Byz-link] +- Error condition + - if *n* is correct: precondition violated + - if *n* is faulty: arbitrary error + - if *lb.provider != peer* + - times out after 2 Delta (by assumption *n* is faulty) + +---- + +## Core Verification + +### Outline + +The `VerifyToTarget` is the main function and uses the following functions. + +- `FetchLightBlock` is called to download the next light block. It is + the only function that communicates with other nodes +- `ValidAndVerified` checks whether header is valid and checks if a + new lightBlock should be trusted + based on a previously verified lightBlock. +- `Schedule` decides which height to try to verify next + +In the following description of `VerifyToTarget` we do not deal with error +handling. If any of the above function returns an error, VerifyToTarget just +passes the error on. + +#### **[LCV-FUNC-MAIN.1]** + +```go +func VerifyToTarget(primary PeerID, lightStore LightStore, + targetHeight Height) (LightStore, Result) { + + nextHeight := targetHeight + + for lightStore.LatestVerified.height < targetHeight { + + // Get next LightBlock for verification + current, found := lightStore.Get(nextHeight) + if !found { + current = FetchLightBlock(primary, nextHeight) + lightStore.Update(current, StateUnverified) + } + + // Verify + verdict = ValidAndVerified(lightStore.LatestVerified, current) + + // Decide whether/how to continue + if verdict == SUCCESS { + lightStore.Update(current, StateVerified) + } + else if verdict == NOT_ENOUGH_TRUST { + // do nothing + // the light block current passed validation, but the validator + // set is too different to verify it. We keep the state of + // current at StateUnverified. For a later iteration, Schedule + // might decide to try verification of that light block again. + } + else { + // verdict is some error code + lightStore.Update(current, StateFailed) + // possibly remove all LightBlocks from primary + return (lightStore, ResultFailure) + } + nextHeight = Schedule(lightStore, nextHeight, targetHeight) + } + return (lightStore, ResultSuccess) +} +``` + +- Expected precondition + - *lightStore* contains a LightBlock within the *trustingPeriod* **[LCV-PRE-TP.1]** + - *targetHeight* is greater than the height of all the LightBlocks in *lightStore* +- Expected postcondition: + - returns *lightStore* that contains a LightBlock that corresponds to a block + of the blockchain of height *targetHeight* + (that is, the LightBlock has been added to *lightStore*) **[LCV-POST-LS.1]** +- Error conditions + - if the precondition is violated + - if `ValidAndVerified` or `FetchLightBlock` report an error + - if [**[LCV-INV-TP.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-inv-tp1) is violated + +### Details of the Functions + +#### **[LCV-FUNC-VALID.1]** + +```go +func ValidAndVerified(trusted LightBlock, untrusted LightBlock) Result +``` + +- Expected precondition: + - *untrusted* is valid, that is, satisfies the soundness [checks][block] + - *untrusted* is **well-formed**, that is, + - *untrusted.Header.Time < now + clockDrift* + - *untrusted.Validators = hash(untrusted.Header.Validators)* + - *untrusted.NextValidators = hash(untrusted.Header.NextValidators)* + - *trusted.Header.Time > now - trustingPeriod* + - *trusted.Commit* is a commit for the header + *trusted.Header*, i.e., it contains + the correct hash of the header, and +2/3 of signatures + - the `Height` and `Time` of `trusted` are smaller than the Height and + `Time` of `untrusted`, respectively + - the *untrusted.Header* is well-formed (passes the tests from + [[block]]), and in particular + - if the untrusted header `unstrusted.Header` is the immediate + successor of `trusted.Header`, then it holds that + - *trusted.Header.NextValidators = + untrusted.Header.Validators*, and + moreover, + - *untrusted.Header.Commit* + - contains signatures by more than two-thirds of the validators + - contains no signature from nodes that are not in *trusted.Header.NextValidators* +- Expected postcondition: + - Returns `SUCCESS`: + - if *untrusted* is the immediate successor of *trusted*, or otherwise, + - if the signatures of a set of validators that have more than + *max(1/3,trustThreshold)* of voting power in + *trusted.Nextvalidators* is contained in + *untrusted.Commit* (that is, header passes the tests + [**[CMBC-VAL-CONTAINS-CORR.1]**][CMBC-VAL-CONTAINS-CORR-link] + and [**[CMBC-VAL-COMMIT.1]**][CMBC-VAL-COMMIT-link]) + - Returns `NOT_ENOUGH_TRUST` if: + - *untrusted* is *not* the immediate successor of + *trusted* + and the *max(1/3,trustThreshold)* threshold is not reached + (that is, if + [**[CMBC-VAL-CONTAINS-CORR.1]**][CMBC-VAL-CONTAINS-CORR-link] + fails and header is does not violate the soundness + checks [[block]]). +- Error condition: + - if precondition violated + +---- + +#### **[LCV-FUNC-SCHEDULE.1]** + +```go +func Schedule(lightStore, nextHeight, targetHeight) Height +``` + +- Implementation remark: If picks the next height to be verified. + We keep the precise choice of the next header under-specified. It is + subject to performance optimizations that do not influence the correctness +- Expected postcondition: **[LCV-SCHEDULE-POST.1]** + Return *H* s.t. + 1. if *lightStore.LatestVerified.Height = nextHeight* and + *lightStore.LatestVerified < targetHeight* then + *nextHeight < H <= targetHeight* + 2. if *lightStore.LatestVerified.Height < nextHeight* and + *lightStore.LatestVerified.Height < targetHeight* then + *lightStore.LatestVerified.Height < H < nextHeight* + 3. if *lightStore.LatestVerified.Height = targetHeight* then + *H = targetHeight* + +> Case i. captures the case where the light block at height *nextHeight* +> has been verified, and we can choose a height closer to the *targetHeight*. +> As we get the *lightStore* as parameter, the choice of the next height can +> depend on the *lightStore*, e.g., we can pick a height for which we have +> already downloaded a light block. +> In Case ii. the header of *nextHeight* could not be verified, and we need to pick a smaller height. +> In Case iii. is a special case when we have verified the *targetHeight*. + +### Solving the distributed specification + +*trustedStore* is implemented by the light blocks in lightStore that +have the state *StateVerified*. + +#### Argument for [**[LCV-DIST-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe) + +- `ValidAndVerified` implements the soundness checks and the checks + [**[CMBC-VAL-CONTAINS-CORR.1]**][CMBC-VAL-CONTAINS-CORR-link] and + [**[CMBC-VAL-COMMIT.1]**][CMBC-VAL-COMMIT-link] under + the assumption [**[CMBC-FM-2THIRDS.1]**][CMBC-FM-2THIRDS-link] +- Only if `ValidAndVerified` returns with `SUCCESS`, the state of a light block is + set to *StateVerified*. + +#### Argument for [**[LCV-DIST-LIVE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-life) + +- If *primary* is correct, + - `FetchLightBlock` will always return a light block consistent + with the blockchain + - `ValidAndVerified` either verifies the header using the trusting + period or falls back to sequential + verification + - If [**[LCV-INV-TP.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-inv-tp1) holds, eventually every + header will be verified and core verification **terminates successfully**. + - successful termination depends on the age of *lightStore.LatestVerified* + (for instance, initially on the age of *trustedHeader*) and the + changes of the validator sets on the blockchain. + We will give some examples [below](#liveness-scenarios). +- If *primary* is faulty, + - it either provides headers that pass all the tests, and we + return with the header + - it provides one header that fails a test, core verification + **terminates with failure**. + - it times out and core verification + **terminates with failure**. + +## Liveness Scenarios + +The liveness argument above assumes [**[LCV-INV-TP.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-inv-tp1) + +which requires that there is a header that does not expire before the +target height is reached. Here we discuss scenarios to ensure this. + +Let *startHeader* be *LightStore.LatestVerified* when core +verification is called (*trustedHeader*) and *startTime* be the time +core verification is invoked. + +In order to ensure liveness, *LightStore* always needs to contain a +verified (or initially trusted) header whose time is within the +trusting period. To ensure this, core verification needs to add new +headers to *LightStore* and verify them, before all headers in +*LightStore* expire. + +#### Many changes in validator set + + Let's consider `Schedule` implements + bisection, that is, it halves the distance. + Assume the case where the validator set changes completely in each +block. Then the + method in this specification needs to +sequentially verify all headers. That is, for + +- *W = log_2 (targetHeight - startHeader.Height)*, + +*W* headers need to be downloaded and checked before the +header of height *startHeader.Height + 1* is added to *LightStore*. + +- Let *Comp* + be the local computation time needed to check headers and signatures + for one header. +- Then we need in the worst case *Comp + 2 Delta* to download and + check one header. +- Then the first time a verified header could be added to *LightStore* is + startTime + W * (Comp + 2 Delta) +- [TP.1] However, it can only be added if we still have a header in + *LightStore*, + which is not + expired, that is only the case if + - startHeader.Time > startTime + WCG * (Comp + 2 Delta) - + trustingPeriod, + - that is, if core verification is started at + startTime < startHeader.Time + trustingPeriod - WCG * (Comp + 2 Delta) + +- one may then do an inductive argument from this point on, depending + on the implementation of `Schedule`. We may have to account for the + headers that are already + downloaded, but they are checked against the new *LightStore.LatestVerified*. + +> We observe that +> the worst case time it needs to verify the header of height +> *targetHeight* depends mainly on how frequent the validator set on the +> blockchain changes. That core verification terminates successfully +> crucially depends on the check [TP.1], that is, that the headers in +> *LightStore* do not expire in the time needed to download more +> headers, which depends on the creation time of the headers in +> *LightStore*. That is, termination of core verification is highly +> depending on the data stored in the blockchain. +> The current light client core verification protocol exploits that, in +> practice, changes in the validator set are rare. For instance, +> consider the following scenario. + +#### No change in validator set + +If on the blockchain the validator set of the block at height +*targetHeight* is equal to *startHeader.NextValidators*: + +- there is one round trip in `FetchLightBlock` to download the light + block + of height + *targetHeight*, and *Comp* to check it. +- as the validator sets are equal, `Verify` returns `SUCCESS`, if + *startHeader.Time > now - trustingPeriod*. +- that is, if *startTime < startHeader.Header.Time + trustingPeriod - + 2 Delta - Comp*, then core verification terminates successfully + +# Part V - Supporting the IBC Relayer + +The above specification focuses on the most common case, which also +constitutes the most challenging task: using the Cosmos [security +model][CMBC-FM-2THIRDS-link] to verify light blocks without +downloading all intermediate blocks. To focus on this challenge, above +we have restricted ourselves to the case where *targetHeight* is +greater than the height of any trusted header. This simplified +presentation of the algorithm as initially +`lightStore.LatestVerified()` is less than *targetHeight*, and in the +process of verification `lightStore.LatestVerified()` increases until +*targetHeight* is reached. + +For [IBC][ibc-rs] it might be that some "older" header is +needed, that is, *targetHeight < lightStore.LatestVerified()*. In this section we present a preliminary design, and we mark some +remaining open questions. +If *targetHeight < lightStore.LatestVerified()* our design separates +the following cases: + +- A previous instance of `VerifyToTarget` has already downloaded the + light block of *targetHeight*. There are two cases + - the light block has been verified + - the light block has not been verified yet +- No light block of *targetHeight* had been downloaded before. There + are two cases: + - there exists a verified light block of height less than *targetHeight* + - otherwise. In this case we need to do "backwards verification" + using the hash of the previous block in the `LastBlockID` field + of a header. + +**Open Question:** what are the security assumptions for backward +verification. Should we check that the light block we verify from +(and/or the checked light block) is within the trusting period? + +The design just presents the above case +distinction as a function, and defines some auxiliary functions in the +same way the protocol was presented in +[Part IV](#part-iv---light-client-verification-protocol). + +```go +func (ls LightStore) LatestPrevious(height Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a light block *lb* that satisfies: + - *lb* is in lightStore + - *lb* is verified and not expired + - *lb.Header.Height < height* + - for all *b* in lightStore s.t. *b* is verified and not expired it + holds *lb.Header.Height >= b.Header.Height* + - *false* in the second argument if + the LightStore does not contain such an *lb*. + +```go +func (ls LightStore) MinVerified() (LightBlock, bool) +``` + +- Expected postcondition + - returns a light block *lb* that satisfies: + - *lb* is in lightStore + - *lb* is verified **Open Question:** replace by trusted? + - *lb.Header.Height* is minimal in the lightStore + - **Open Question:** according to this, it might be expired (outside the + trusting period). This approach appears safe. Are there reasons we + should not do that? + - *false* in the second argument if + the LightStore does not contain such an *lb*. + +If a height that is smaller than the smallest height in the lightstore +is required, we check the hashes backwards. This is done with the +following function: + +#### **[LCV-FUNC-BACKWARDS.1]** + +```go +func Backwards (primary PeerID, lightStore LightStore, targetHeight Height) + (LightStore, Result) { + + lb,res = lightStore.MinVerified() + if res = false { + return (lightStore, ResultFailure) + } + + latest := lb.Header + for i := lb.Header.height - 1; i >= targetHeight; i-- { + // here we download height-by-height. We might first download all + // headers down to targetHeight and then check them. + current := FetchLightBlock(primary,i) + if (hash(current) != latest.Header.LastBlockId) { + return (lightStore, ResultFailure) + } + else { + lightStore.Update(current, StateVerified) + // **Open Question:** Do we need a new state type for + // backwards verified light blocks? + } + latest = current + } + return (lightStore, ResultSuccess) +} +``` + +The following function just decided based on the required height which +method should be used. + +#### **[LCV-FUNC-IBCMAIN.1]** + +```go +func Main (primary PeerID, lightStore LightStore, targetHeight Height) + (LightStore, Result) { + + b1, r1 = lightStore.Get(targetHeight) + if r1 = true and b1.State = StateVerified { + // block already there + return (lightStore, ResultSuccess) + } + + if targetHeight > lightStore.LatestVerified.height { + // case of Part IV + return VerifyToTarget(primary, lightStore, targetHeight) + } + else { + b2, r2 = lightStore.LatestPrevious(targetHeight); + if r2 = true { + // make auxiliary lightStore auxLS to call VerifyToTarget. + // VerifyToTarget uses LatestVerified of the given lightStore + // For that we need: + // auxLS.LatestVerified = lightStore.LatestPrevious(targetHeight) + auxLS.Init; + auxLS.Update(b2,StateVerified); + if r1 = true { + // we need to verify a previously downloaded light block. + // we add it to the auxiliary store so that VerifyToTarget + // does not download it again + auxLS.Update(b1,b1.State); + } + auxLS, res2 = VerifyToTarget(primary, auxLS, targetHeight) + // move all lightblocks from auxLS to lightStore, + // maintain state + // we do that whether VerifyToTarget was successful or not + for i, s range auxLS { + lighStore.Update(s,s.State) + } + return (lightStore, res2) + } + else { + return Backwards(primary, lightStore, targetHeight) + } + } +} +``` + + + + + + + + + + + + + + + + + + + +# References + +[[block]] Specification of the block data structure. + +[[RPC]] RPC client + +[[fork-detector]] The specification of the light client fork detector. + +[[fullnode]] Specification of the full node API + +[[ibc-rs]] Rust implementation of IBC modules and relayer. + +[[lightclient]] The light client ADR [77d2651 on Dec 27, 2019]. + +[RPC]: https://docs.cometbft.com/v0.34/rpc/ + +[block]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/data_structures.md + +[CMBC-SEQ-link]: #cmbc-seq1 +[CMBC-CorrFull-link]: #cmbc-corr-full1 +[CMBC-Auth-Byz-link]: #cmbc-auth-byz1 +[CMBC-TIME_PARAMS-link]: #cmbc-time-params1 +[CMBC-FM-2THIRDS-link]: #cmbc-fm-2thirds1 +[CMBC-VAL-CONTAINS-CORR-link]: #cmbc-val-contains-corr1 +[CMBC-VAL-COMMIT-link]: #cmbc-val-commit1 + +[lightclient]: https://github.com/interchainio/tendermint-rs/blob/e2cb9aca0b95430fca2eac154edddc9588038982/docs/architecture/adr-002-lite-client.md +[fork-detector]: https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/detection +[fullnode]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/blockchain + +[ibc-rs]:https://github.com/informalsystems/ibc-rs + + +[arXiv]: https://arxiv.org/abs/1807.04938 diff --git a/spec/light-client/verification/verification_002_draft.md b/spec/light-client/verification/verification_002_draft.md new file mode 100644 index 0000000..d874a1a --- /dev/null +++ b/spec/light-client/verification/verification_002_draft.md @@ -0,0 +1,1056 @@ +# Light Client Verification + +The light client implements a read operation of a +[header][CMBC-HEADER-link] from the [blockchain][CMBC-SEQ-link], by +communicating with full nodes. As some full nodes may be faulty, this +functionality must be implemented in a fault-tolerant way. + +In a Cosmos blockchain, the validator set may change with every +new block. The staking and unbonding mechanism induces a [security +model][CMBC-FM-2THIRDS-link]: starting at time *Time* of the +[header][CMBC-HEADER-link], +more than two-thirds of the next validators of a new block are correct +for the duration of *TrustedPeriod*. The fault-tolerant read +operation is designed for this security model. + +The challenge addressed here is that the light client might have a +block of height *h1* and needs to read the block of height *h2* +greater than *h1*. Checking all headers of heights from *h1* to *h2* +might be too costly (e.g., in terms of energy for mobile devices). +This specification tries to reduce the number of intermediate blocks +that need to be checked, by exploiting the guarantees provided by the +[security model][CMBC-FM-2THIRDS-link]. + +# Status + +## Previous Versions + +- [[001_published]](./verification_001_published.md) + is thoroughly reviewed, and the protocol has been +formalized in TLA+ and model checked. + +## Issues that are addressed in this revision + +As it is part of the larger light node, its data structures and +functions interact with the attack dectection functionality of the light +client. As a result of the work on + +- [attack detection](https://github.com/tendermint/spec/pull/164) for light nodes + +- attack detection for IBC and [relayer requirements](https://github.com/informalsystems/tendermint-rs/issues/497) + +- light client + [supervisor](https://github.com/tendermint/spec/pull/159) (also in + [Rust proposal](https://github.com/informalsystems/tendermint-rs/pull/509)) + +adaptations to the semantics and functions exposed by the LightStore +needed to be made. In contrast to [version +001](./verification_001_published.md) we specify the following: + +- `VerifyToTarget` and `Backwards` are called with a single lightblock + as root of trust in contrast to passing the complete lightstore. + +- During verification, we record for each lightblock which other + lightblock can be used to verify it in one step. This is needed to + generate verification traces that are needed for IBC. + +# Outline + +- [Part I](#part-i---cosmos-blockchain): Introduction of + relevant terms of the Cosmos +blockchain. + +- [Part II](#part-ii---sequential-definition-of-the-verification-problem): Introduction +of the problem addressed by the Lightclient Verification protocol. + - [Verification Informal Problem + statement](#verification-informal-problem-statement): For the general + audience, that is, engineers who want to get an overview over what + the component is doing from a bird's eye view. + - [Sequential Problem statement](#sequential-problem-statement): + Provides a mathematical definition of the problem statement in + its sequential form, that is, ignoring the distributed aspect of + the implementation of the blockchain. + +- [Part III](#part-iii---light-client-as-distributed-system): Distributed + aspects of the light client, system assumptions and temporal + logic specifications. + + - [Incentives](#incentives): how faulty full nodes may benefit from + misbehaving and how correct full nodes benefit from cooperating. + + - [Computational Model](#computational-model): + timing and correctness assumptions. + + - [Distributed Problem Statement](#distributed-problem-statement): + temporal properties that formalize safety and liveness + properties in the distributed setting. + +- [Part IV](#part-iv---light-client-verification-protocol): + Specification of the protocols. + + - [Definitions](#definitions): Describes inputs, outputs, + variables used by the protocol, auxiliary functions + + - [Core Verification](#core-verification): gives an outline of the solution, + and details of the functions used (with preconditions, + postconditions, error conditions). + + - [Liveness Scenarios](#liveness-scenarios): when the light + client makes progress depends heavily on the changes in the + validator sets of the blockchain. We discuss some typical scenarios. + +- [Part V](#part-v---supporting-the-ibc-relayer): The above parts + focus on a common case where the last verified block has height *h1* + and the + requested height *h2* satisfies *h2 > h1*. For IBC, there are + scenarios where this might not be the case. In this part, we provide + some preliminaries for supporting this. As not all details of the + IBC requirements are clear by now, we do not provide a complete + specification at this point. We mark with "Open Question" points + that need to be addressed in order to finalize this specification. + It should be noted that the technically + most challenging case is the one specified in Part IV. + +In this document we quite extensively use tags in order to be able to +reference assumptions, invariants, etc. in future communication. In +these tags we frequently use the following short forms: + +- CMBC: Cosmos blockchain +- SEQ: for sequential specifications +- LCV: Lightclient Verification +- LIVE: liveness +- SAFE: safety +- FUNC: function +- INV: invariant +- A: assumption + +# Part I - Cosmos Blockchain + +## Header Fields necessary for the Light Client + +#### **[CMBC-HEADER.1]** + +A set of blockchain transactions is stored in a data structure called +*block*, which contains a field called *header*. (The data structure +*block* is defined [here][block]). As the header contains hashes to +the relevant fields of the block, for the purpose of this +specification, we will assume that the blockchain is a list of +headers, rather than a list of blocks. + +#### **[CMBC-HASH-UNIQUENESS.1]** + +We assume that every hash in the header identifies the data it hashes. +Therefore, in this specification, we do not distinguish between hashes and the +data they represent. + +#### **[CMBC-HEADER-FIELDS.2]** + +A header contains the following fields: + +- `Height`: non-negative integer +- `Time`: time (non-negative integer) +- `LastBlockID`: Hashvalue +- `LastCommit` DomainCommit +- `Validators`: DomainVal +- `NextValidators`: DomainVal +- `Data`: DomainTX +- `AppState`: DomainApp +- `LastResults`: DomainRes + +#### **[CMBC-SEQ.1]** + +The Cosmos blockchain is a list *chain* of headers. + +#### **[CMBC-VALIDATOR-PAIR.1]** + +Given a full node, a +*validator pair* is a pair *(peerID, voting_power)*, where + +- *peerID* is the PeerID (public key) of a full node, +- *voting_power* is an integer (representing the full node's + voting power in a certain consensus instance). + +> In the Golang implementation the data type for *validator +pair* is called `Validator` + +#### **[CMBC-VALIDATOR-SET.1]** + +A *validator set* is a set of validator pairs. For a validator set +*vs*, we write *TotalVotingPower(vs)* for the sum of the voting powers +of its validator pairs. + +#### **[CMBC-VOTE.1]** + +A *vote* contains a `prevote` or `precommit` message sent and signed by +a validator node during the execution of [consensus][arXiv]. Each +message contains the following fields + +- `Type`: prevote or precommit +- `Height`: positive integer +- `Round` a positive integer +- `BlockID` a Hashvalue of a block (not necessarily a block of the chain) + +#### **[CMBC-COMMIT.1]** + +A commit is a set of `precommit` message. + +## Cosmos Failure Model + +#### **[CMBC-AUTH-BYZ.1]** + +We assume the authenticated Byzantine fault model in which no node (faulty or +correct) may break digital signatures, but otherwise, no additional +assumption is made about the internal behavior of faulty +nodes. That is, faulty nodes are only limited in that they cannot forge +messages. + +#### **[CMBC-TIME-PARAMS.1]** + +A Cosmos blockchain has the following configuration parameters: + +- *unbondingPeriod*: a time duration. +- *trustingPeriod*: a time duration smaller than *unbondingPeriod*. + +#### **[CMBC-CORRECT.1]** + +We define a predicate *correctUntil(n, t)*, where *n* is a node and *t* is a +time point. +The predicate *correctUntil(n, t)* is true if and only if the node *n* +follows all the protocols (at least) until time *t*. + +#### **[CMBC-FM-2THIRDS.1]** + +If a block *h* is in the chain, +then there exists a subset *CorrV* +of *h.NextValidators*, such that: + +- *TotalVotingPower(CorrV) > 2/3 + TotalVotingPower(h.NextValidators)*; cf. [CMBC-VALIDATOR-SET.1] +- For every validator pair *(n,p)* in *CorrV*, it holds *correctUntil(n, + h.Time + trustingPeriod)*; cf. [CMBC-CORRECT.1] + +> The definition of correct +> [**[CMBC-CORRECT.1]**][CMBC-CORRECT-link] refers to realtime, while it +> is used here with *Time* and *trustingPeriod*, which are "hardware +> times". We do not make a distinction here. + +#### **[CMBC-CORR-FULL.1]** + +Every correct full node locally stores a prefix of the +current list of headers from [**[CMBC-SEQ.1]**][CMBC-SEQ-link]. + +## What the Light Client Checks + +> From [CMBC-FM-2THIRDS.1] we directly derive the following observation: + +#### **[CMBC-VAL-CONTAINS-CORR.1]** + +Given a (trusted) block *tb* of the blockchain, a given set of full nodes +*N* contains a correct node at a real-time *t*, if + +- *t - trustingPeriod < tb.Time < t* +- the voting power in tb.NextValidators of nodes in *N* is more + than 1/3 of *TotalVotingPower(tb.NextValidators)* + +> The following describes how a commit for a given block *b* must look +> like. + +#### **[CMBC-SOUND-DISTR-POSS-COMMIT.1]** + +For a block *b*, each element *pc* of *PossibleCommit(b)* satisfies: + +- *pc* contains only votes (cf. [CMBC-VOTE.1]) + by validators from *b.Validators* +- the sum of the voting powers in *pc* is greater than 2/3 + *TotalVotingPower(b.Validators)* +- and there is an *r* such that each vote *v* in *pc* satisfies + - v.Type = precommit + - v.Height = b.Height + - v.Round = r + - v.blockID = hash(b) + +> The following property comes from the validity of the [consensus][arXiv]: A +> correct validator node only sends `prevote` or `precommit`, if +> `BlockID` of the new (to-be-decided) block is equal to the hash of +> the last block. + +#### **[CMBC-VAL-COMMIT.1]** + +If for a block *b*, a commit *c* + +- contains at least one validator pair *(v,p)* such that *v* is a + **correct** validator node, and +- is contained in *PossibleCommit(b)* + +then the block *b* is on the blockchain. + +## Context of this document + +In this document we specify the light client verification component, +called *Core Verification*. The *Core Verification* communicates with +a full node. As full nodes may be faulty, it cannot trust the +received information, but the light client has to check whether the +header it receives coincides with the one generated by Tendermint +consensus. + +The two + properties [[CMBC-VAL-CONTAINS-CORR.1]][CMBC-VAL-CONTAINS-CORR-link] and +[[CMBC-VAL-COMMIT]][CMBC-VAL-COMMIT-link] formalize the checks done + by this specification: +Given a trusted block *tb* and an untrusted block *ub* with a commit *cub*, +one has to check that *cub* is in *PossibleCommit(ub)*, and that *cub* +contains a correct node using *tb*. + +# Part II - Sequential Definition of the Verification Problem + +## Verification Informal Problem statement + +Given a height *targetHeight* as an input, the *Verifier* eventually +stores a header *h* of height *targetHeight* locally. This header *h* +is generated by the Cosmos [blockchain][block]. In +particular, a header that was not generated by the blockchain should +never be stored. + +## Sequential Problem statement + +#### **[LCV-SEQ-LIVE.1]** + +The *Verifier* gets as input a height *targetHeight*, and eventually stores the +header of height *targetHeight* of the blockchain. + +#### **[LCV-SEQ-SAFE.1]** + +The *Verifier* never stores a header which is not in the blockchain. + +# Part III - Light Client as Distributed System + +## Incentives + +Faulty full nodes may benefit from lying to the light client, by making the +light client accept a block that deviates (e.g., contains additional +transactions) from the one generated by Tendermint consensus. +Users using the light client might be harmed by accepting a forged header. + +The [attack detector][attack-detector] of the light client may help the +correct full nodes to understand whether their header is a good one. +Hence, in combination with the light client detector, the correct full +nodes have the incentive to respond. We can thus base liveness +arguments on the assumption that correct full nodes reliably talk to +the light client. + +## Computational Model + +#### **[LCV-A-PEER.1]** + +The verifier communicates with a full node called *primary*. No assumption is made about the full node (it may be correct or faulty). + +#### **[LCV-A-COMM.1]** + +Communication between the light client and a correct full node is +reliable and bounded in time. Reliable communication means that +messages are not lost, not duplicated, and eventually delivered. There +is a (known) end-to-end delay *Delta*, such that if a message is sent +at time *t* then it is received and processes by time *t + Delta*. +This implies that we need a timeout of at least *2 Delta* for remote +procedure calls to ensure that the response of a correct peer arrives +before the timeout expires. + +#### **[LCV-A-TFM.1]** + +The Cosmos blockchain satisfies the Cosmos failure model [**[CMBC-FM-2THIRDS.1]**][CMBC-FM-2THIRDS-link]. + +#### **[LCV-A-VAL.1]** + +The system satisfies [**[CMBC-AUTH-BYZ.1]**][CMBC-Auth-Byz-link] and +[**[CMBC-FM-2THIRDS.1]**][CMBC-FM-2THIRDS-link]. Thus, there is a +blockchain that satisfies the soundness requirements (that is, the +validation rules in [[block]]). + +## Distributed Problem Statement + +### Two Kinds of Termination + +We do not assume that *primary* is correct. Under this assumption no +protocol can guarantee the combination of the sequential +properties. Thus, in the (unreliable) distributed setting, we consider +two kinds of termination (successful and failure) and we will specify +below under what (favorable) conditions *Core Verification* ensures to +terminate successfully, and satisfy the requirements of the sequential +problem statement: + +#### **[LCV-DIST-TERM.1]** + +*Core Verification* either *terminates +successfully* or it *terminates with failure*. + +### Design choices + +#### **[LCV-DIST-STORE.2]** + +*Core Verification* returns a data structure called *LightStore* that +contains light blocks (that contain a header). + +#### **[LCV-DIST-INIT.2]** + +*Core Verification* is called with + +- *primary*: the PeerID of a full node (with verification communicates) +- *root*: a light block (the root of trust) +- *targetHeight*: a height (the height of a header that should be obtained) + +### Temporal Properties + +#### **[LCV-DIST-SAFE.2]** + +It is always the case that every header in *LightStore* was +generated by an instance of Tendermint consensus. + +#### **[LCV-DIST-LIVE.2]** + +If a new instance of *Core Verification* is called with a +height *targetHeight* greater than root.Header.Height it must +must eventually terminate. + +- If + - the *primary* is correct (and locally has the block of + *targetHeight*), and + - the age of root is always less than the trusting period, + then *Core Verification* adds a verified header *hd* with height + *targetHeight* to *LightStore* and it **terminates successfully** + +> These definitions imply that if the primary is faulty, a header may or +> may not be added to *LightStore*. In any case, +> [**[LCV-DIST-SAFE.2]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe2) must hold. +> The invariant [**[LCV-DIST-SAFE.2]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe2) and the liveness +> requirement [**[LCV-DIST-LIVE.2]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-life) +> allow that verified headers are added to *LightStore* whose +> height was not passed +> to the verifier (e.g., intermediate headers used in bisection; see below). +> Note that for liveness, initially having a *root* within +> the *trustinPeriod* is not sufficient. However, as this +> specification will leave some freedom with respect to the strategy +> in which order to download intermediate headers, we do not give a +> more precise liveness specification here. After giving the +> specification of the protocol, we will discuss some liveness +> scenarios [below](#liveness-scenarios). + +### Solving the sequential specification + +This specification provides a partial solution to the sequential specification. +The *Verifier* solves the invariant of the sequential part + +[**[LCV-DIST-SAFE.2]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe2) => [**[LCV-SEQ-SAFE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-safe1) + +In the case the primary is correct, and *root* is a recent header in *LightStore*, the verifier satisfies the liveness requirements. + +⋀ *primary is correct* +⋀ *root.header.Time* > *now* - *trustingPeriod* +⋀ [**[LCV-A-Comm.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-a-comm) ⋀ ( + ( [**[CMBC-CorrFull.1]**][CMBC-CorrFull-link] ⋀ + [**[LCV-DIST-LIVE.2]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-live2) ) + ⟹ [**[LCV-SEQ-LIVE.1]**](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/verification/verification_001_published.md#lcv-dist-live1) +) + +# Part IV - Light Client Verification Protocol + +We provide a specification for Light Client Verification. The local +code for verification is presented by a sequential function +`VerifyToTarget` to highlight the control flow of this functionality. +We note that if a different concurrency model is considered for +an implementation, the sequential flow of the function may be +implemented with mutexes, etc. However, the light client verification +is partitioned into three blocks that can be implemented and tested +independently: + +- `FetchLightBlock` is called to download a light block (header) of a + given height from a peer. +- `ValidAndVerified` is a local code that checks the header. +- `Schedule` decides which height to try to verify next. We keep this + underspecified as different implementations (currently in Goland and + Rust) may implement different optimizations here. We just provide + necessary conditions on how the height may evolve. + + + + +## Definitions + +### Data Types + +The core data structure of the protocol is the LightBlock. + +#### **[LCV-DATA-LIGHTBLOCK.1]** + +```go +type LightBlock struct { + Header Header + Commit Commit + Validators ValidatorSet +} +``` + +#### **[LCV-DATA-LIGHTSTORE.2]** + +LightBlocks are stored in a structure which stores all LightBlock from +initialization or received from peers. + +```go +type LightStore struct { + ... +} + +``` + +#### **[LCV-DATA-LS-ROOT.2]** + +For each lightblock in a lightstore we record in a field `verification-root` of +type Height. + +> `verification-root` records the height of a lightblock that can be used to verify +> the lightblock in one step + +#### **[LCV-INV-LS-ROOT.2]** + +At all times, if a lightblock *b* in a lightstore has *b.verification-root = h*, +then + +- the lightstore contains a lightblock with height *h*, or +- *b* has the minimal height of all lightblocks in lightstore, then + b.verification-root should be nil. + +The LightStore exposes the following functions to query stored LightBlocks. + +#### **[LCV-DATA-LS-STATE.1]** + +Each LightBlock is in one of the following states: + +```go +type VerifiedState int + +const ( + StateUnverified = iota + 1 + StateVerified + StateFailed + StateTrusted +) +``` + +#### **[LCV-FUNC-GET.1]** + +```go +func (ls LightStore) Get(height Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a LightBlock at a given height or false in the second argument if + the LightStore does not contain the specified LightBlock. + +#### **[LCV-FUNC-LATEST.1]** + +```go +func (ls LightStore) Latest() LightBlock +``` + +- Expected postcondition + - returns the highest light block + +#### **[LCV-FUNC-ADD.1]** + +```go +func (ls LightStore) Add(newBlock) +``` + +- Expected precondition + - the lightstore is empty +- Expected postcondition + - adds newBlock into light store + +#### **[LCV-FUNC-STORE.1]** + +```go +func (ls LightStore) store_chain(newLS LightStore) +``` + +- Expected postcondition + - adds `newLS` to the lightStore. + +#### **[LCV-FUNC-LATEST-VERIF.2]** + +```go +func (ls LightStore) LatestVerified() LightBlock +``` + +- Expected postcondition + - returns the highest light block whose state is `StateVerified` + +#### **[LCV-FUNC-FILTER.1]** + +```go +func (ls LightStore) FilterVerified() LightStore +``` + +- Expected postcondition + - returns all the lightblocks of the lightstore with state `StateVerified` + +#### **[LCV-FUNC-UPDATE.2]** + +```go +func (ls LightStore) Update(lightBlock LightBlock, verfiedState +VerifiedState, root-height Height) +``` + +- Expected postcondition + - the lightblock is part of the lightstore + - The state of the LightBlock is set to *verifiedState*. + - The verification-root of the LightBlock is set to *root-height* + +```go +func (ls LightStore) TraceTo(lightBlock LightBlock) (LightBlock, LightStore) +``` + +- Expected postcondition + - returns a **trusted** lightblock `root` from the lightstore with a height + less than `lightBlock` + - returns a lightstore that contains lightblocks that constitute a + [verification trace](https://github.com/cometbft/cometbft/tree/v0.38.x/spec/light-client/detection) from + `root` to `lightBlock` (including `lightBlock`) + +### Inputs + +- *root*: A light block that is trusted +- *primary*: peerID +- *targetHeight*: the height of the needed header + +### Configuration Parameters + +- *trustThreshold*: a float. Can be used if correctness should not be based on more voting power and 1/3. +- *trustingPeriod*: a time duration [**[CMBC-TIME_PARAMS.1]**][CMBC-TIME_PARAMS-link]. +- *clockDrift*: a time duration. Correction parameter dealing with only approximately synchronized clocks. + +### Variables + +- *nextHeight*: initially *targetHeight* + > *nextHeight* should be thought of the "height of the next header we need + > to download and verify" + +### Assumptions + +#### **[LCV-A-INIT.2]** + +- *root* is from the blockchain + +- *targetHeight > root.Header.Height* + +### Invariants + +#### **[LCV-INV-TP.1]** + +It is always the case that *LightStore.LatestTrusted.Header.Time > now - trustingPeriod*. + +> If the invariant is violated, the light client does not have a +> header it can trust. A trusted header must be obtained externally, +> its trust can only be based on social consensus. +> We use the convention that root is assumed to be verified. + +### Used Remote Functions + +We use the functions `commit` and `validators` that are provided +by the [RPC client][RPC]. + +```go +func Commit(height int64) (SignedHeader, error) +``` + +- Implementation remark + - RPC to full node *n* + - JSON sent: + +```javascript +// POST /commit +{ + "jsonrpc": "2.0", + "id": "ccc84631-dfdb-4adc-b88c-5291ea3c2cfb", // UUID v4, unique per request + "method": "commit", + "params": { + "height": 1234 + } +} +``` + +- Expected precondition + - header of `height` exists on blockchain +- Expected postcondition + - if *n* is correct: Returns the signed header of height `height` + from the blockchain if communication is timely (no timeout) + - if *n* is faulty: Returns a signed header with arbitrary content +- Error condition + - if *n* is correct: precondition violated or timeout + - if *n* is faulty: arbitrary error + +----; + +```go +func Validators(height int64) (ValidatorSet, error) +``` + +- Implementation remark + - RPC to full node *n* + - JSON sent: + +```javascript +// POST /validators +{ + "jsonrpc": "2.0", + "id": "ccc84631-dfdb-4adc-b88c-5291ea3c2cfb", // UUID v4, unique per request + "method": "validators", + "params": { + "height": 1234 + } +} +``` + +- Expected precondition + - header of `height` exists on blockchain +- Expected postcondition + - if *n* is correct: Returns the validator set of height `height` + from the blockchain if communication is timely (no timeout) + - if *n* is faulty: Returns arbitrary validator set +- Error condition + - if *n* is correct: precondition violated or timeout + - if *n* is faulty: arbitrary error + +----; + +### Communicating Function + +#### **[LCV-FUNC-FETCH.1]** + + ```go +func FetchLightBlock(peer PeerID, height Height) LightBlock +``` + +- Implementation remark + - RPC to peer at *PeerID* + - calls `Commit` for *height* and `Validators` for *height* and *height+1* +- Expected precondition + - `height` is less than or equal to height of the peer **[LCV-IO-PRE-HEIGHT.1]** +- Expected postcondition: + - if *node* is correct: + - Returns the LightBlock *lb* of height `height` + that is consistent with the blockchain + - *lb.provider = peer* **[LCV-IO-POST-PROVIDER.1]** + - *lb.Header* is a header consistent with the blockchain + - *lb.Validators* is the validator set of the blockchain at height *nextHeight* + - *lb.NextValidators* is the validator set of the blockchain at height *nextHeight + 1* + - if *node* is faulty: Returns a LightBlock with arbitrary content + [**[CMBC-AUTH-BYZ.1]**][CMBC-Auth-Byz-link] +- Error condition + - if *n* is correct: precondition violated + - if *n* is faulty: arbitrary error + - if *lb.provider != peer* + - times out after 2 Delta (by assumption *n* is faulty) + +----; + +## Core Verification + +### Outline + +The `VerifyToTarget` is the main function and uses the following functions. + +- `FetchLightBlock` is called to download the next light block. It is + the only function that communicates with other nodes +- `ValidAndVerified` checks whether header is valid and checks if a + new lightBlock should be trusted + based on a previously verified lightBlock. +- `Schedule` decides which height to try to verify next + +In the following description of `VerifyToTarget` we do not deal with error +handling. If any of the above function returns an error, VerifyToTarget just +passes the error on. + +#### **[LCV-FUNC-MAIN.2]** + +```go +func VerifyToTarget(primary PeerID, root LightBlock, + targetHeight Height) (LightStore, Result) { + + lightStore = new LightStore; + lightStore.Update(root, StateVerified, root.verifiedBy); + nextHeight := targetHeight; + + for lightStore.LatestVerified.height < targetHeight { + + // Get next LightBlock for verification + current, found := lightStore.Get(nextHeight) + if !found { + current = FetchLightBlock(primary, nextHeight) + lightStore.Update(current, StateUnverified, nil) + } + + // Verify + verdict = ValidAndVerified(lightStore.LatestVerified, current) + + // Decide whether/how to continue + if verdict == SUCCESS { + lightStore.Update(current, StateVerified, lightStore.LatestVerified.Height) + } + else if verdict == NOT_ENOUGH_TRUST { + // do nothing + // the light block current passed validation, but the validator + // set is too different to verify it. We keep the state of + // current at StateUnverified. For a later iteration, Schedule + // might decide to try verification of that light block again. + } + else { + // verdict is some error code + lightStore.Update(current, StateFailed, nil) + return (nil, ResultFailure) + } + nextHeight = Schedule(lightStore, nextHeight, targetHeight) + } + return (lightStore.FilterVerified, ResultSuccess) +} +``` + +- Expected precondition + - *root* is within the *trustingPeriod* **[LCV-PRE-TP.1]** + - *targetHeight* is greater than the height of *root* +- Expected postcondition: + - returns *lightStore* that contains a LightBlock that corresponds to a block + of the blockchain of height *targetHeight* + (that is, the LightBlock has been added to *lightStore*) **[LCV-POST-LS.1]** +- Error conditions + - if the precondition is violated + - if `ValidAndVerified` or `FetchLightBlock` report an error + - if [**[LCV-INV-TP.1]**](#lcv-inv-tp1) is violated + +### Details of the Functions + +#### **[LCV-FUNC-VALID.2]** + +```go +func ValidAndVerified(trusted LightBlock, untrusted LightBlock) Result +``` + +- Expected precondition: + - *untrusted* is valid, that is, satisfies the soundness [checks][block] + - *untrusted* is **well-formed**, that is, + - *untrusted.Header.Time < now + clockDrift* + - *untrusted.Validators = hash(untrusted.Header.Validators)* + - *untrusted.NextValidators = hash(untrusted.Header.NextValidators)* + - *trusted.Header.Time > now - trustingPeriod* + - the `Height` and `Time` of `trusted` are smaller than the Height and + `Time` of `untrusted`, respectively + - the *untrusted.Header* is well-formed (passes the tests from + [[block]]), and in particular + - if the untrusted header `unstrusted.Header` is the immediate + successor of `trusted.Header`, then it holds that + - *trusted.Header.NextValidators = + untrusted.Header.Validators*, and + moreover, + - *untrusted.Header.Commit* + - contains signatures by more than two-thirds of the validators + - contains no signature from nodes that are not in *trusted.Header.NextValidators* +- Expected postcondition: + - Returns `SUCCESS`: + - if *untrusted* is the immediate successor of *trusted*, or otherwise, + - if the signatures of a set of validators that have more than + *max(1/3,trustThreshold)* of voting power in + *trusted.Nextvalidators* is contained in + *untrusted.Commit* (that is, header passes the tests + [**[CMBC-VAL-CONTAINS-CORR.1]**][CMBC-VAL-CONTAINS-CORR-link] + and [**[CMBC-VAL-COMMIT.1]**][CMBC-VAL-COMMIT-link]) + - Returns `NOT_ENOUGH_TRUST` if: + - *untrusted* is *not* the immediate successor of + *trusted* + and the *max(1/3,trustThreshold)* threshold is not reached + (that is, if + [**[CMBC-VAL-CONTAINS-CORR.1]**][CMBC-VAL-CONTAINS-CORR-link] + fails and header is does not violate the soundness + checks [[block]]). +- Error condition: + - if precondition violated + +----; + +#### **[LCV-FUNC-SCHEDULE.1]** + +```go +func Schedule(lightStore, nextHeight, targetHeight) Height +``` + +- Implementation remark: If picks the next height to be verified. + We keep the precise choice of the next header under-specified. It is + subject to performance optimizations that do not influence the correctness +- Expected postcondition: **[LCV-SCHEDULE-POST.1]** + Return *H* s.t. + 1. if *lightStore.LatestVerified.Height = nextHeight* and + *lightStore.LatestVerified < targetHeight* then + *nextHeight < H <= targetHeight* + 2. if *lightStore.LatestVerified.Height < nextHeight* and + *lightStore.LatestVerified.Height < targetHeight* then + *lightStore.LatestVerified.Height < H < nextHeight* + 3. if *lightStore.LatestVerified.Height = targetHeight* then + *H = targetHeight* + +> Case i. captures the case where the light block at height *nextHeight* +> has been verified, and we can choose a height closer to the *targetHeight*. +> As we get the *lightStore* as parameter, the choice of the next height can +> depend on the *lightStore*, e.g., we can pick a height for which we have +> already downloaded a light block. +> In Case ii. the header of *nextHeight* could not be verified, and we need to pick a smaller height. +> In Case iii. is a special case when we have verified the *targetHeight*. + +### Solving the distributed specification + +Analogous to [[001_published]](./verification_001_published.md#solving-the-distributed-specification) + +## Liveness Scenarios + +Analogous to [[001_published]](./verification_001_published.md#liveness-scenarios) + +# Part V - Supporting the IBC Relayer + +The above specification focuses on the most common case, which also +constitutes the most challenging task: using the Cosmos [security +model][CMBC-FM-2THIRDS-link] to verify light blocks without +downloading all intermediate blocks. To focus on this challenge, above +we have restricted ourselves to the case where *targetHeight* is +greater than the height of any trusted header. This simplified +presentation of the algorithm as initially +`lightStore.LatestVerified()` is less than *targetHeight*, and in the +process of verification `lightStore.LatestVerified()` increases until +*targetHeight* is reached. + +For [IBC][ibc-rs] there are two additional challenges: + +1. it might be that some "older" header is needed, that is, +*targetHeight < lightStore.LatestVerified()*. The +[supervisor](../supervisor/supervisor_002_draft.md) checks whether it is in this +case by calling `LatestPrevious` and `MinVerified` and if so it calls +`Backwards`. All these functions are specified below. + +2. In order to submit proof of a light client attack, a relayer may + need to submit a verification trace. This it is important to + compute such a trace efficiently. That it can be done is based on + the invariant [[LCV-INV-LS-ROOT.2]](#lcv-inv-ls-root2) that needs + to be maintained by the light client. In particular + `VerifyToTarget` and `Backwards` need to take care of setting + `verification-root`. + +#### **[LCV-FUNC-LATEST-PREV.2]** + +```go +func (ls LightStore) LatestPrevious(height Height) (LightBlock, bool) +``` + +- Expected postcondition + - returns a light block *lb* that satisfies: + - *lb* is in lightStore + - *lb* is in StateTrusted + - *lb* is not expired + - *lb.Header.Height < height* + - for all *b* in lightStore s.t. *b* is trusted and not expired it + holds *lb.Header.Height >= b.Header.Height* + - *false* in the second argument if + the LightStore does not contain such an *lb*. + +----; + +#### **[LCV-FUNC-LOWEST.2]** + +```go +func (ls LightStore) Lowest() (LightBlock) +``` + +- Expected postcondition + - returns the lowest trusted light block within trusting period + +----; + +#### **[LCV-FUNC-MIN.2]** + +```go +func (ls LightStore) MinVerified() (LightBlock, bool) +``` + +- Expected postcondition + - returns a light block *lb* that satisfies: + - *lb* is in lightStore + - *lb.Header.Height* is minimal in the lightStore + - *false* in the second argument if + the LightStore does not contain such an *lb*. + +If a height that is smaller than the smallest height in the lightstore +is required, we check the hashes backwards. This is done with the +following function: + +#### **[LCV-FUNC-BACKWARDS.2]** + +```go +func Backwards (primary PeerID, root LightBlock, targetHeight Height) + (LightStore, Result) { + + lb := root; + lightStore := new LightStore; + lightStore.Update(lb, StateTrusted, lb.verifiedBy) + + latest := lb.Header + for i := lb.Header.height - 1; i >= targetHeight; i-- { + // here we download height-by-height. We might first download all + // headers down to targetHeight and then check them. + current := FetchLightBlock(primary,i) + if (hash(current) != latest.Header.LastBlockId) { + return (nil, ResultFailure) + } + else { + // latest and current are linked together by LastBlockId + // therefore it is not relevant which we verified first + // for consistency, we store latest was veried using + // current so that the verifiedBy is always pointing down + // the chain + lightStore.Update(current, StateTrusted, nil) + lightStore.Update(latest, StateTrusted, current.Header.Height) + } + latest = current + } + return (lightStore, ResultSuccess) +} +``` + +# References + +[[block]] Specification of the block data structure. + +[[RPC]] RPC client + +[[attack-detector]] The specification of the light client attack detector. + +[[fullnode]] Specification of the full node API + +[[ibc-rs]] Rust implementation of IBC modules and relayer. + +[[lightclient]] The light client ADR [77d2651 on Dec 27, 2019]. + +[RPC]: https://docs.cometbft.com/v0.34/rpc/ + +[block]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/core/data_structures.md + +[CMBC-HEADER-link]: #cmbc-header1 +[CMBC-SEQ-link]: #cmbc-seq1 +[CMBC-CorrFull-link]: #cmbc-corr-full1 +[CMBC-Auth-Byz-link]: #cmbc-auth-byz1 +[CMBC-TIME_PARAMS-link]: #cmbc-time-params1 +[CMBC-FM-2THIRDS-link]: #cmbc-fm-2thirds1 +[CMBC-VAL-CONTAINS-CORR-link]: #cmbc-val-contains-corr1 +[CMBC-VAL-COMMIT-link]: #cmbc-val-commit1 + +[lightclient]: https://github.com/interchainio/tendermint-rs/blob/e2cb9aca0b95430fca2eac154edddc9588038982/docs/architecture/adr-002-lite-client.md +[attack-detector]: https://github.com/cometbft/cometbft/blob/v0.38.x/spec/light-client/detection/detection_001_reviewed.md +[fullnode]: https://github.com/cometbft/cometbft/tree/v0.38.x/spec/core + +[ibc-rs]:https://github.com/informalsystems/ibc-rs + + +[arXiv]: https://arxiv.org/abs/1807.04938 diff --git a/spec/light-client/verification/verification_003_draft.md b/spec/light-client/verification/verification_003_draft.md new file mode 100644 index 0000000..e801d71 --- /dev/null +++ b/spec/light-client/verification/verification_003_draft.md @@ -0,0 +1,76 @@ +# Light Client Verificaiton + +#### **[LCV-FUNC-VERIFYCOMMITLIGHT.1]** + +VerifyCommitLight verifies that 2/3+ of the signatures for a validator set were for +a given blockID. The function will finish early and thus may not check all signatures. + +```go +func VerifyCommitLight(chainID string, vals *ValidatorSet, blockID BlockID, +height int64, commit *Commit) error { + // run a basic validation of the arguments + if err := verifyBasicValsAndCommit(vals, commit, height, blockID); err != nil { + return err + } + + // calculate voting power needed + votingPowerNeeded := vals.TotalVotingPower() * 2 / 3 + + var ( + val *Validator + valIdx int32 + seenVals = make(map[int32]int, len(commit.Signatures)) + talliedVotingPower int64 = 0 + voteSignBytes []byte + ) + for idx, commitSig := range commit.Signatures { + // ignore all commit signatures that are not for the block + if !commitSig.ForBlock() { + continue + } + + // If the vals and commit have a 1-to-1 correspondance we can retrieve + // them by index else we need to retrieve them by address + if lookUpByIndex { + val = vals.Validators[idx] + } else { + valIdx, val = vals.GetByAddress(commitSig.ValidatorAddress) + + // if the signature doesn't belong to anyone in the validator set + // then we just skip over it + if val == nil { + continue + } + + // because we are getting validators by address we need to make sure + // that the same validator doesn't commit twice + if firstIndex, ok := seenVals[valIdx]; ok { + secondIndex := idx + return fmt.Errorf("double vote from %v (%d and %d)", val, firstIndex, secondIndex) + } + seenVals[valIdx] = idx + } + + voteSignBytes = commit.VoteSignBytes(chainID, int32(idx)) + + if !val.PubKey.VerifySignature(voteSignBytes, commitSig.Signature) { + return fmt.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature) + } + + // Add the voting power of the validator + // to the tally + talliedVotingPower += val.VotingPower + + // check if we have enough signatures and can thus exit early + if talliedVotingPower > votingPowerNeeded { + return nil + } + } + + if got, needed := talliedVotingPower, votingPowerNeeded; got <= needed { + return ErrNotEnoughVotingPowerSigned{Got: got, Needed: needed} + } + + return nil +} +``` diff --git a/spec/p2p/README.md b/spec/p2p/README.md new file mode 100644 index 0000000..2ce0aa6 --- /dev/null +++ b/spec/p2p/README.md @@ -0,0 +1,46 @@ +--- +order: 1 +parent: + title: P2P + order: 6 +--- + +# Peer-to-Peer Communication + +A CometBFT network is composed of multiple CometBFT instances, hereafter called +`nodes`, that interact by exchanging messages. + +The CometBFT protocols are designed under the assumption of a partially-connected network model. +This means that a node is not assumed to be directly connected to every other +node in the network. +Instead, each node is directly connected to only a subset of other nodes, +hereafter called its `peers`. + +The peer-to-peer (p2p) communication layer is then the component of CometBFT that: + +1. establishes connections between nodes in a CometBFT network +2. manages the communication between a node and the connected peers +3. intermediates the exchange of messages between peers in CometBFT protocols + +The specification the p2p layer is a work in progress, +tracked by [issue #19](https://github.com/cometbft/cometbft/issues/19). +The current content is organized as follows: + +- [`implementation`](./implementation/README.md): documents the current state + of the implementation of the p2p layer, covering the main components of the + `p2p` package. The documentation covers, in a fairly comprehensive way, + the items 1. and 2. from the list above. +- [`reactor-api`](./reactor-api/README.md): specifies the API offered by the + p2p layer to the protocol layer, through the `Reactor` abstraction. + This is a high-level specification (i.e., it should not be implementation-specific) + of the p2p layer API, covering item 3. from the list above. +- [`legacy-docs`](./legacy-docs/): We keep older documentation in + the `legacy-docs` directory, as overall, it contains useful information. + However, part of this content is redundant, + being more comprehensively covered in more recent documents, + and some implementation details might be outdated + (see [issue #981](https://github.com/cometbft/cometbft/issues/981)). + +In addition to this content, some unfinished, work in progress, and auxiliary +material can be found in the +[knowledge-base](https://github.com/cometbft/knowledge-base/tree/main/p2p) repository. diff --git a/spec/p2p/images/p2p-reactors.png b/spec/p2p/images/p2p-reactors.png new file mode 100644 index 0000000..05b6e5e Binary files /dev/null and b/spec/p2p/images/p2p-reactors.png differ diff --git a/spec/p2p/images/p2p_state.png b/spec/p2p/images/p2p_state.png new file mode 100644 index 0000000..9aa47dd Binary files /dev/null and b/spec/p2p/images/p2p_state.png differ diff --git a/spec/p2p/implementation/README.md b/spec/p2p/implementation/README.md new file mode 100644 index 0000000..aed7ca0 --- /dev/null +++ b/spec/p2p/implementation/README.md @@ -0,0 +1,43 @@ +--- +order: 1 +title: Implementation +--- + +# Implementation of the p2p layer + +This section documents the implementation of the peer-to-peer (p2p) +communication layer in CometBFT. + +The documentation was [produced](https://github.com/tendermint/tendermint/pull/9348) +using the `v0.34.*` releases +and the branch [`v0.34.x`](https://github.com/cometbft/cometbft/tree/v0.34.x) +of this repository as reference. +As there were no substancial changes in the p2p implementation, the +documentation also applies to the releases `v0.37.*` and `v0.38.*` [^v35]. + +[^v35]: The releases `v0.35.*` and `v0.36.*`, which included a major + refactoring of the p2p layer implementation, were [discontinued][v35postmorten]. + +[v35postmorten]: https://interchain-io.medium.com/discontinuing-tendermint-v0-35-a-postmortem-on-the-new-networking-layer-3696c811dabc + +## Contents + +The documentation follows the organization of the +[`p2p` package](https://github.com/cometbft/cometbft/tree/v0.34.x/p2p), +which implements the following abstractions: + +- [Transport](./transport.md): establishes secure and authenticated + connections with peers; +- [Switch](./switch.md): responsible for dialing peers and accepting + connections from peers, for managing established connections, and for + routing messages between the reactors and peers, + that is, between local and remote instances of the CometBFT protocols; +- [PEX Reactor](./pex.md): due to the several roles of this component, the + documentation is split in several parts: + - [Peer Exchange protocol](./pex-protocol.md): enables nodes to exchange peer addresses, thus implementing a peer discovery service; + - [Address Book](./addressbook.md): stores discovered peer addresses and + quality metrics associated to peers with which the node has interacted; + - [Peer Manager](./peer_manager.md): defines when and to which peers a node + should dial, in order to establish outbound connections; +- [Types](./types.md) and [Configuration](./configuration.md) provide a list of + existing types and configuration parameters used by the p2p package. diff --git a/spec/p2p/implementation/addressbook.md b/spec/p2p/implementation/addressbook.md new file mode 100644 index 0000000..bea9d23 --- /dev/null +++ b/spec/p2p/implementation/addressbook.md @@ -0,0 +1,368 @@ +# Address Book + +The address book tracks information about peers, i.e., about other nodes in the network. + +The primary information stored in the address book are peer addresses. +A peer address is composed by a node ID and a network address; a network +address is composed by an IP address or a DNS name plus a port number. +The same node ID can be associated to multiple network addresses. + +There are two sources for the addresses stored in the address book. +The [Peer Exchange protocol](./pex-protocol.md) stores in the address book +the peer addresses it discovers, i.e., it learns from connected peers. +And the [Switch](./switch.md) registers the addresses of peers with which it +has interacted: to which it has dialed or from which it has accepted a +connection. + +The address book also records additional information about peers with which the +node has interacted, from which is possible to rank peers. +The Switch reports [connection attempts](#dial-attempts) to a peer address; too +much failed attempts indicate that a peer address is invalid. +Reactors, in they turn, report a peer as [good](#good-peers) when it behaves as +expected, or as a [bad peer](#bad-peers), when it misbehaves. + +There are two entities that retrieve peer addresses from the address book. +The [Peer Manager](./peer_manager.md) retrieves peer addresses to dial, so to +establish outbound connections. +This selection is random, but has a configurable bias towards peers that have +been marked as good peers. +The [Peer Exchange protocol](./pex-protocol.md) retrieves random samples of +addresses to offer (send) to peers. +This selection is also random but it includes, in particular for nodes that +operate in seed mode, some bias toward peers marked as good ones. + +## Buckets + +Peer addresses are stored in buckets. +There are buckets for new addresses and buckets for old addresses. +The buckets for new addresses store addresses of peers about which the node +does not have much information; the first address registered for a peer ID is +always stored in a bucket for new addresses. +The buckets for old addresses store addresses of peers with which the node has +interacted and that were reported as [good peers](#good-peers) by a reactor. +An old address therefore can be seen as an alias for a good address. + +> Note that new addresses does not mean bad addresses. +> The addresses of peers marked as [bad peers](#bad-peers) are removed from the +> buckets where they are stored, and temporarily kept in a table of banned peers. + +The number of buckets is fixed and there are more buckets for new addresses +(`256`) than buckets for old addresses (`64`), a ratio of 4:1. +Each bucket can store up to `64` addresses. +When a bucket becomes full, the peer address with the lowest ranking is removed +from the bucket. +The first choice is to remove bad addresses, with multiple failed attempts +associated. +In the absence of those, the *oldest* address in the bucket is removed, i.e., +the address with the oldest last attempt to dial. + +When a bucket for old addresses becomes full, the lowest-ranked peer address in +the bucket is moved to a bucket of new addresses. +When a bucket for new addresses becomes full, the lowest-ranked peer address in +the bucket is removed from the address book. +In other words, exceeding old or good addresses are downgraded to new +addresses, while exceeding new addresses are dropped. + +The bucket that stores an `address` is defined by the following two methods, +for new and old addresses: + +- `calcNewBucket(address, source) = hash(key + groupKey(source) + hash(key + groupKey(address) + groupKey(source)) % newBucketsPerGroup) % newBucketCount` +- `calcOldBucket(address) = hash(key + groupKey(address) + hash(key + address) % oldBucketsPerGroup) % oldBucketCount` + +The `key` is a fixed random 96-bit (8-byte) string. +The `groupKey` for an address is a string representing its network group. +The `source` of an address is the address of the peer from which we learn the +address.. +The first (internal) hash is reduced to an integer up to `newBucketsPerGroup = +32`, for new addresses, and `oldBucketsPerGroup = 4`, for old addresses. +The second (external) hash is reduced to bucket indexes, in the interval from 0 +to the number of new (`newBucketCount = 256`) or old (`oldBucketCount = 64`) buckets. + +Notice that new addresses with sources from the same network group are more +likely to end up in the same bucket, therefore to competing for it. +For old address, instead, two addresses are more likely to end up in the same +bucket when they belong to the same network group. + +## Adding addresses + +The `AddAddress` method adds the address of a peer to the address book. + +The added address is associated to a *source* address, which identifies the +node from which the peer address was learned. + +Addresses are added to the address book in the following situations: + +1. When a peer address is learned via PEX protocol, having the sender + of the PEX message as its source +2. When an inbound peer is added, in this case the peer itself is set as the + source of its own address +3. When the switch is instructed to dial addresses via the `DialPeersAsync` + method, in this case the node itself is set as the source + +If the added address contains a node ID that is not registered in the address +book, the address is added to a [bucket](#buckets) of new addresses. +Otherwise, the additional address for an existing node ID is **not added** to +the address book when: + +- The last address added with the same node ID is stored in an old bucket, so + it is considered a "good" address +- There are addresses associated to the same node ID stored in + `maxNewBucketsPerAddress = 4` distinct buckets +- Randomly, with a probability that increases exponentially with the number of + buckets in which there is an address with the same node ID. + So, a new address for a node ID which is already present in one bucket is + added with 50% of probability; if the node ID is present in two buckets, the + probability decreases to 25%; and if it is present in three buckets, the + probability is 12.5%. + +The new address is also added to the `addrLookup` table, which stores +`knownAddress` entries indexed by their node IDs. +If the new address is from an unknown peer, a new entry is added to the +`addrLookup` table; otherwise, the existing entry is updated with the new +address. +Entries of this table contain, among other fields, the list of buckets where +addresses of a peer are stored. +The `addrLookup` table is used by most of the address book methods (e.g., +`HasAddress`, `IsGood`, `MarkGood`, `MarkAttempt`), as it provides fast access +to addresses. + +### Errors + +- if the added address or the associated source address are nil +- if the added address is invalid +- if the added address is the local node's address +- if the added address ID is of a [banned](#bad-peers) peer +- if either the added address or the associated source address IDs are configured as private IDs +- if `routabilityStrict` is set and the address is not routable +- in case of failures computing the bucket for the new address (`calcNewBucket` method) +- if the added address instance, which is a new address, is configured as an + old address (sanity check of `addToNewBucket` method) + +## Need for Addresses + +The `NeedMoreAddrs` method verifies whether the address book needs more addresses. + +It is invoked by the PEX reactor to define whether to request peer addresses +to a new outbound peer or to a randomly selected connected peer. + +The address book needs more addresses when it has less than `1000` addresses +registered, counting all buckets for new and old addresses. + +## Pick address + +The `PickAddress` method returns an address stored in the address book, chosen +at random with a configurable bias towards new addresses. + +It is invoked by the Peer Manager to obtain a peer address to dial, as part of +its `ensurePeers` routine. +The bias starts from 10%, when the peer has no outbound peers, increasing by +10% for each outbound peer the node has, up to 90%, when the node has at least +8 outbound peers. + +The configured bias is a parameter that influences the probability of choosing +an address from a bucket of new addresses or from a bucket of old addresses. +A second parameter influencing this choice is the number of new and old +addresses stored in the address book. +In the absence of bias (i.e., if the configured bias is 50%), the probability +of picking a new address is given by the square root of the number of new +addresses divided by the sum of the square roots of the numbers of new and old +addresses. +By adding a bias toward new addresses (i.e., configured bias larger than 50%), +the portion on the sample occupied by the square root of the number of new +addresses increases, while the corresponding portion for old addresses decreases. +As a result, it becomes more likely to pick a new address at random from this sample. + +> The use of the square roots softens the impact of disproportional numbers of +> new and old addresses in the address book. This is actually the expected +> scenario, as there are 4 times more buckets for new addresses than buckets +> for old addresses. + +Once the type of address, new or old, is defined, a non-empty bucket of this +type is selected at random. +From the selected bucket, an address is chosen at random and returned. +If all buckets of the selected type are empty, no address is returned. + +## Random selection + +The `GetSelection` method returns a selection of addresses stored in the +address book, with no bias toward new or old addresses. + +It is invoked by the PEX protocol to obtain a list of peer addresses with two +purposes: + +- To send to a peer in a PEX response, in the case of outbound peers or of + nodes not operating in seed mode +- To crawl, in the case of nodes operating in seed mode, as part of every + interaction of the `crawlPeersRoutine` + +The selection is a random subset of the peer addresses stored in the +`addrLookup` table, which stores the last address added for each peer ID. +The target size of the selection is `23%` (`getSelectionPercent`) of the +number of addresses stored in the address book, but it should not be lower than +`32` (`minGetSelection`) --- if it is, all addresses in the book are returned +--- nor greater than `250` (`maxGetSelection`). + +> The random selection is produced by: +> +> - Retrieving all entries of the `addrLookup` map, which by definition are +> returned in random order. +> - Randomly shuffling the retrieved list, using the Fisher-Yates algorithm + +## Random selection with bias + +The `GetSelectionWithBias` method returns a selection of addresses stored in +the address book, with bias toward new addresses. + +It is invoked by the PEX protocol to obtain a list of peer addresses to be sent +to a peer in a PEX response. +This method is only invoked by seed nodes, when replying to a PEX request +received from an inbound peer (i.e., a peer that dialed the seed node). +The bias used in this scenario is hard-coded to 30%, meaning that 70% of +the returned addresses are expected to be old addresses. + +The number of addresses that compose the selection is computed in the same way +as for the non-biased random selection. +The bias toward new addresses is implemented by requiring that the configured +bias, interpreted as a percentage, of the select addresses come from buckets of +new addresses, while the remaining come from buckets of old addresses. +Since the number of old addresses is typically lower than the number of new +addresses, it is possible that the address book does not have enough old +addresses to include in the selection. +In this case, additional new addresses are included in the selection. +Thus, the configured bias, in practice, is towards old addresses, not towards +new addresses. + +To randomly select addresses of a type, the address book considers all +addresses present in every bucket of that type. +This list of all addresses of a type is randomly shuffled, and the requested +number of addresses are retrieved from the tail of this list. +The returned selection contains, at its beginning, a random selection of new +addresses in random order, followed by a random selection of old addresses, in +random order. + +## Dial Attempts + +The `MarkAttempt` method records a failed attempt to connect to an address. + +It is invoked by the Peer Manager when it fails dialing a peer, but the failure +is not in the authentication step (`ErrSwitchAuthenticationFailure` error). +In case of authentication errors, the peer is instead marked as a [bad peer](#bad-peers). + +The failed connection attempt is recorded in the address registered for the +peer's ID in the `addrLookup` table, which is the last address added with that ID. +The known address' counter of failed `Attempts` is increased and the failure +time is registered in `LastAttempt`. + +The possible effect of recording multiple failed connect attempts to a peer is +to turn its address into a *bad* address (do not confuse with banned addresses). +A known address becomes bad if it is stored in buckets of new addresses, and +when connection attempts: + +- Have not been made over a week, i.e., `LastAttempt` is older than a week +- Have failed 3 times and never succeeded, i.e., `LastSucess` field is unset +- Have failed 10 times in the last week, i.e., `LastSucess` is older than a week + +Addresses marked as *bad* are the first candidates to be removed from a bucket of +new addresses when the bucket becomes full. + +> Note that failed connection attempts are reported for a peer address, but in +> fact the address book records them for a peer. +> +> More precisely, failed connection attempts are recorded in the entry of the +> `addrLookup` table with reported peer ID, which contains the last address +> added for that node ID, which is not necessarily the reported peer address. + +## Good peers + +The `MarkGood` method marks a peer ID as good. + +It is invoked by the consensus reactor, via switch, when the number of useful +messages received from a peer is a multiple of `10000`. +Vote and block part messages are considered for this number, they must be valid +and not be duplicated messages to be considered useful. + +> The `SwitchReporter` type of `behaviour` package also invokes the `MarkGood` +> method when a "reason" associated with consensus votes and block parts is +> reported. +> No reactor, however, currently provides these "reasons" to the `SwitchReporter`. + +The effect of this action is that the address registered for the peer's ID in the +`addrLookup` table, which is the last address added with that ID, is marked as +good and moved to a bucket of old addresses. +An address marked as good has its failed to connect counter and timestamp reset. +If the destination bucket of old addresses is full, the oldest address in the +bucket is moved (downgraded) to a bucket of new addresses. + +Moving the peer address to a bucket of old addresses has the effect of +upgrading, or increasing the ranking of a peer in the address book. + +## Bad peers + +The `MarkBad` method marks a peer as bad and bans it for a period of time. + +This method is only invoked within the PEX reactor, with a banning time of 24 +hours, for the following reasons: + +- A peer misbehaves in the [PEX protocol](./pex-protocol.md#misbehavior) +- When the `maxAttemptsToDial` limit (`16`) is reached for a peer +- If an `ErrSwitchAuthenticationFailure` error is returned when dialing a peer + +The effect of this action is that the address registered for the peer's ID in the +`addrLookup` table, which is the last address added with that ID, is banned for +a period of time. +The banned peer is removed from the `addrLookup` table and from all buckets +where its addresses are stored. + +The information about banned peers, however, is not discarded. +It is maintained in the `badPeers` map, indexed by peer ID. +This allows, in particular, addresses of banned peers to be +[reinstated](#reinstating-addresses), i.e., to be added +back to the address book, when their ban period expires. + +## Reinstating addresses + +The `ReinstateBadPeers` method attempts to re-add banned addresses to the address book. + +It is invoked by the PEX reactor when dialing new peers. +This action is taken before requesting additional addresses to peers, +in the case that the node needs more peer addresses. + +The set of banned peer addresses is retrieved from the `badPeers` map. +Addresses that are not any longer banned, i.e., whose banned period has expired, +are added back to the address book as new addresses, while the corresponding +node IDs are removed from the `badPeers` map. + +## Removing addresses + +The `RemoveAddress` method removes an address from the address book. + +It is invoked by the switch when it dials a peer or accepts a connection from a +peer that ends up being the node itself (`IsSelf` error). +In both cases, the address dialed or accepted is also added to the address book +as a local address, via the `AddOurAddress` method. + +The same logic is also internally used by the address book for removing +addresses of a peer that is [marked as a bad peer](#bad-peers). + +The entry registered with the peer ID of the address in the `addrLookup` table, +which is the last address added with that ID, is removed from all buckets where +it is stored and from the `addrLookup` table. + +> FIXME: is it possible that addresses with the same ID as the removed address, +> but with distinct network addresses, are kept in buckets of the address book? +> While they will not be accessible anymore, as there is no reference to them +> in the `addrLookup`, they will still be there. + +## Persistence + +The `loadFromFile` method, called when the address book is started, reads +address book entries from a file, passed to the address book constructor. +The file, at this point, does not need to exist. + +The `saveRoutine` is started when the address book is started. +It saves the address book to the configured file every `dumpAddressInterval`, +hard-coded to 2 minutes. +It is also possible to save the content of the address book using the `Save` +method. +Saving the address book content to a file acquires the address book lock, also +employed by all other public methods. diff --git a/spec/p2p/implementation/configuration.md b/spec/p2p/implementation/configuration.md new file mode 100644 index 0000000..d6f4b6e --- /dev/null +++ b/spec/p2p/implementation/configuration.md @@ -0,0 +1,49 @@ +# CometBFT p2p configuration + +This document contains configurable parameters a node operator can use to tune the p2p behaviour. + +| Parameter| Default| Description | +| --- | --- | ---| +| ListenAddress | "tcp://0.0.0.0:26656" | Address to listen for incoming connections (0.0.0.0:0 means any interface, any port) | +| ExternalAddress | "" | Address to advertise to peers for them to dial | +| [Seeds](./pex-protocol.md#seed-nodes) | empty | Comma separated list of seed nodes to connect to (ID@host:port )| +| [Persistent peers](./peer_manager.md#persistent-peers) | empty | Comma separated list of nodes to keep persistent connections to (ID@host:port ) | +| [AddrBook](./addressbook.md) | defaultAddrBookPath | Path do address book | +| AddrBookStrict | true | Set true for strict address routability rules and false for private or local networks | +| [MaxNumInboundPeers](./switch.md#accepting-peers) | 40 | Maximum number of inbound peers | +| [MaxNumOutboundPeers](./peer_manager.md#ensure-peers) | 10 | Maximum number of outbound peers to connect to, excluding persistent peers | +| [UnconditionalPeers](./switch.md#accepting-peers) | empty | These are IDs of the peers which are allowed to be (re)connected as both inbound or outbound regardless of whether the node reached `max_num_inbound_peers` or `max_num_outbound_peers` or not. | +| PersistentPeersMaxDialPeriod| 0 * time.Second | Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) | +| FlushThrottleTimeout |100 * time.Millisecond| Time to wait before flushing messages out on the connection | +| MaxPacketMsgPayloadSize | 1024 | Maximum size of a message packet payload, in bytes | +| SendRate | 5120000 (5 mB/s) | Rate at which packets can be sent, in bytes/second | +| RecvRate | 5120000 (5 mB/s) | Rate at which packets can be received, in bytes/second| +| [PexReactor](./pex.md) | true | Set true to enable the peer-exchange reactor | +| SeedMode | false | Seed mode, in which node constantly crawls the network and looks for. Does not work if the peer-exchange reactor is disabled. | +| PrivatePeerIDs | empty | Comma separated list of peer IDsthat we do not add to the address book or gossip to other peers. They stay private to us. | +| AllowDuplicateIP | false | Toggle to disable guard against peers connecting from the same ip.| +| [HandshakeTimeout](./transport.md#connection-upgrade) | 20 * time.Second | Timeout for handshake completion between peers | +| [DialTimeout](./switch.md#dialing-peers) | 3 * time.Second | Timeout for dialing a peer | + + +These parameters can be set using the `$CMTHOME/config/config.toml` file. A subset of them can also be changed via command line using the following command line flags: + +| Parameter | Flag | Example | +| --- | --- | --- | +| Listen address| `p2p.laddr` | "tcp://0.0.0.0:26656" | +| Seed nodes | `p2p.seeds` | `--p2p.seeds “id100000000000000000000000000000000@1.2.3.4:26656,id200000000000000000000000000000000@2.3.4.5:4444”` | +| Persistent peers | `p2p.persistent_peers` | `--p2p.persistent_peers “id100000000000000000000000000000000@1.2.3.4:26656,id200000000000000000000000000000000@2.3.4.5:26656”` | +| Unconditional peers | `p2p.unconditional_peer_ids` | `--p2p.unconditional_peer_ids “id100000000000000000000000000000000,id200000000000000000000000000000000”` | +| PexReactor | `p2p.pex` | `--p2p.pex` | +| Seed mode | `p2p.seed_mode` | `--p2p.seed_mode` | +| Private peer ids | `p2p.private_peer_ids` | `--p2p.private_peer_ids “id100000000000000000000000000000000,id200000000000000000000000000000000”` | + + **Note on persistent peers** + + If `persistent_peers_max_dial_period` is set greater than zero, the +pause between each dial to each persistent peer will not exceed `persistent_peers_max_dial_period` +during exponential backoff and we keep trying again without giving up. + +If `seeds` and `persistent_peers` intersect, +the user will be warned that seeds may auto-close connections +and that the node may not be able to keep the connection persistent. diff --git a/spec/p2p/implementation/peer_manager.md b/spec/p2p/implementation/peer_manager.md new file mode 100644 index 0000000..f181576 --- /dev/null +++ b/spec/p2p/implementation/peer_manager.md @@ -0,0 +1,140 @@ +# Peer Manager + +The peer manager is responsible for establishing connections with peers. +It defines when a node should dial peers and which peers it should dial. +The peer manager is not an implementation abstraction of the p2p layer, +but a role that is played by the [PEX reactor](./pex.md). + +## Outbound peers + +The `ensurePeersRoutine` is a persistent routine intended to ensure that a node +is connected to `MaxNumOutboundPeers` outbound peers. +This routine is continuously executed by regular nodes, i.e. nodes not +operating in seed mode, as part of the PEX reactor implementation. + +The logic defining when the node should dial peers, for selecting peers to dial +and for actually dialing them is implemented in the `ensurePeers` method. +This method is periodically invoked -- every `ensurePeersPeriod`, with default +value to 30 seconds -- by the `ensurePeersRoutine`. + +A node is expected to dial peers whenever the number of outbound peers is lower +than the configured `MaxNumOutboundPeers` parameter. +The current number of outbound peers is retrieved from the switch, using the +`NumPeers` method, which also reports the number of nodes to which the switch +is currently dialing. +If the number of outbound peers plus the number of dialing routines equals to +`MaxNumOutboundPeers`, nothing is done. +Otherwise, the `ensurePeers` method will attempt to dial node addresses in +order to reach the target number of outbound peers. + +Once defined that the node needs additional outbound peers, the node queries +the address book for candidate addresses. +This is done using the [`PickAddress`](./addressbook.md#pick-address) method, +which returns an address selected at random on the address book, with some bias +towards new or old addresses. +When the node has up to 3 outbound peers, the adopted bias is towards old +addresses, i.e., addresses of peers that are believed to be "good". +When the node has from 5 outbound peers, the adopted bias is towards new +addresses, i.e., addresses of peers about which the node has not yet collected +much information. +So, the more outbound peers a node has, the less conservative it will be when +selecting new peers. + +The selected peer addresses are then dialed in parallel, by starting a dialing +routine per peer address. +Dialing a peer address can fail for multiple reasons. +The node might have attempted to dial the peer too many times. +In this case, the peer address is marked as bad and removed from the address book. +The node might have attempted and failed to dial the peer recently +and the exponential `backoffDuration` has not yet passed. +Or the current connection attempt might fail, which is registered in the address book. +None of these errors are explicitly handled by the `ensurePeers` method, which +also does not wait until the connections are established. + +The third step of the `ensurePeers` method is to ensure that the address book +has enough addresses. +This is done, first, by [reinstating banned peers](./addressbook.md#Reinstating-addresses) +whose ban period has expired. +Then, the node randomly selects a connected peer, which can be either an +inbound or outbound peer, to [requests addresses](./pex-protocol.md#Requesting-Addresses) +using the PEX protocol. +Last, and this action is only performed if the node could not retrieve any new +address to dial from the address book, the node dials the configured seed nodes +in order to establish a connection to at least one of them. + +### Fast dialing + +As above described, seed nodes are actually the last source of peer addresses +for regular nodes. +They are contacted by a node when, after an invocation of the `ensurePeers` +method, no suitable peer address to dial is retrieved from the address book +(e.g., because it is empty). + +Once a connection with a seed node is established, the node immediately +[sends a PEX request](./pex-protocol.md#Requesting-Addresses) to it, as it is +added as an outbound peer. +When the corresponding PEX response is received, the addresses provided by the +seed node are added to the address book. +As a result, in the next invocation of the `ensurePeers` method, the node +should be able to dial some of the peer addresses provided by the seed node. + +However, as observed in this [issue](https://github.com/tendermint/tendermint/issues/2093), +it can take some time, up to `ensurePeersPeriod` or 30 seconds, from when the +node receives new peer addresses and when it dials the received addresses. +To avoid this delay, which can be particularly relevant when the node has no +peers, a node immediately attempts to dial peer addresses when they are +received from a peer that is locally configured as a seed node. + +> This was implemented in a rough way, leading to inconsistencies described in +> this [issue](https://github.com/cometbft/cometbft/issues/486), +> fixed by this [PR](https://github.com/cometbft/cometbft/pull/3360). + +### First round + +When the PEX reactor is started, the `ensurePeersRoutine` is created and it +runs thorough the operation of a node, periodically invoking the `ensurePeers` +method. +However, if when the persistent routine is started the node already has some +peers, either inbound or outbound peers, or is dialing some addresses, the +first invocation of `ensurePeers` is delayed by a random amount of time from 0 +to `ensurePeersPeriod`. + +### Persistent peers + +The node configuration can contain a list of *persistent peers*. +Those peers have preferential treatment compared to regular peers and the node +is always trying to connect to them. +Moreover, these peers are not removed from the address book in the case of +multiple failed dial attempts. + +On startup, the node immediately tries to dial the configured persistent peers +by calling the switch's [`DialPeersAsync`](./switch.md#manual-operation) method. +This is not done in the p2p package, but it is part of the procedure to set up a node. + +> TODO: the handling of persistent peers should be described in more detail. + +### Life cycle + +The picture below is a first attempt of illustrating the life cycle of an outbound peer: + + + +A peer can be in the following states: + +- Candidate peers: peer addresses stored in the address boook, that can be + retrieved via the [`PickAddress`](./addressbook.md#pick-address) method +- [Dialing](./switch.md#dialing-peers): peer addresses that are currently being + dialed. This state exists to ensure that a single dialing routine exist per peer. +- [Reconnecting](./switch.md#reconnect-to-peer): persistent peers to which a node + is currently reconnecting, as a previous connection attempt has failed. +- Connected peers: peers that a node has successfully dialed, added as outbound peers. +- [Bad peers](./addressbook.md#bad-peers): peers marked as bad in the address + book due to exhibited [misbehavior](./pex-protocol.md#misbehavior). + Peers can be reinstated after being marked as bad. + +## Pending of documentation + +The `dialSeeds` method of the PEX reactor. + +The `dialPeer` method of the PEX reactor. +This includes `dialAttemptsInfo`, `maxBackoffDurationForPeer` methods. diff --git a/spec/p2p/implementation/pex-protocol.md b/spec/p2p/implementation/pex-protocol.md new file mode 100644 index 0000000..c16e71c --- /dev/null +++ b/spec/p2p/implementation/pex-protocol.md @@ -0,0 +1,240 @@ +# Peer Exchange Protocol + +The Peer Exchange (PEX) protocol enables nodes to exchange peer addresses, thus +implementing a peer discovery mechanism. + +The PEX protocol uses two messages: + +- `PexRequest`: sent by a node to [request](#requesting-addresses) peer + addresses to a peer +- `PexAddrs`: a list of peer addresses [provided](#providing-addresses) to a + peer as response to a `PexRequest` message + +While all nodes, with few exceptions, participate on the PEX protocol, +a subset of nodes, configured as [seed nodes](#seed-nodes) have a particular +role in the protocol. +They crawl the network, connecting to random peers, in order to learn as many +peer addresses as possible to provide to other nodes. + +## Requesting Addresses + +A node requests peer addresses by sending a `PexRequest` message to a peer. + +For regular nodes, not operating in seed mode, a PEX request is sent when +the node *needs* peers addresses, a condition checked: + +1. When an *outbound* peer is added, causing the node to request addresses from + the new peer +2. Periodically, by the `ensurePeersRoutine`, causing the node to request peer + addresses to a randomly selected peer + +A node needs more peer addresses when its addresses book has +[less than 1000 records](./addressbook.md#need-for-addresses). +It is thus reasonable to assume that the common case is that a peer needs more +peer addresses, so that PEX requests are sent whenever the above two situations happen. + +A PEX request is sent when a new *outbound* peer is added. +The same does not happen with new inbound peers because the implementation +considers outbound peers, that the node has chosen for dialing, more +trustworthy than inbound peers, that the node has accepted. +Moreover, when a node is short of peer addresses, it dials the configured seed nodes; +since they are added as outbound peers, the node can immediately request peer addresses. + +The `ensurePeersRoutine` periodically checks, by default every 30 seconds (`ensurePeersPeriod`), +whether the node has enough outbound peers. +If it does not have, the node tries dialing some peer addresses stored in the address book. +As part of this procedure, the node selects a peer at random, +from the set of connected peers retrieved from the switch, +and sends a PEX request to the selected peer. + +Sending a PEX request to a peer is implemented by the `RequestAddrs` method of +the PEX reactor. + +### Responses + +After a PEX request is sent to a peer, the node expects to receive, +as a response, a `PexAddrs` message from the peer. +This message encodes a list of peer addresses that are +[added to address book](./addressbook.md#adding-addresses), +having the peer from which the PEX response was received as their source. + +Received PEX responses are handled by the `ReceiveAddrs` method of the PEX reactor. +In the case of a PEX response received from a peer which is configured as +a seed node, the PEX reactor attempts immediately to dial the provided peer +addresses, as detailed [here](./peer_manager.md#fast-dialing). + +### Misbehavior + +Sending multiple PEX requests to a peer, before receiving a reply from it, +is considered a misbehavior. +To prevent it, the node maintains a `requestsSent` set of outstanding +requests, indexed by destination peers. +While a peer ID is present in the `requestsSent` set, the node does not send +further PEX requests to that peer. +A peer ID is removed from the `requestsSent` set when a PEX response is +received from it. + +Sending a PEX response to a peer that has not requested peer addresses +is also considered a misbehavior. +So, if a PEX response is received from a peer that is not registered in +the `requestsSent` set, a `ErrUnsolicitedList` error is produced. +This leads the peer to be disconnected and [marked as a bad peer](./addressbook.md#bad-peers). + +## Providing Addresses + +When a node receives a `PexRequest` message from a peer, +it replies with a `PexAddrs` message. + +This message encodes a [random selection of peer addresses](./addressbook.md#random-selection) +retrieved from the address book. + +Sending a PEX response to a peer is implemented by the `SendAddrs` method of +the PEX reactor. + +### Misbehavior + +Requesting peer addresses too often is considered a misbehavior. +Since node are expected to send PEX requests every `ensurePeersPeriod`, +the minimum accepted interval between requests from the same peer is set +to `ensurePeersPeriod / 3`, 10 seconds by default. + +The `receiveRequest` method is responsible for verifying this condition. +The node keeps a `lastReceivedRequests` map with the time of the last PEX +request received from every peer. +If the interval between successive requests is less than the minimum accepted +one, the peer is disconnected and [marked as a bad peer](./addressbook.md#bad-peers). +An exception is made for the first two PEX requests received from a peer. + +> The probably reason is that, when a new peer is added, the two conditions for +> a node to request peer addresses can be triggered with an interval lower than +> the minimum accepted interval. +> Since this is a legit behavior, it should not be punished. + +## Seed nodes + +A seed node is a node configured to operate in `SeedMode`. + +### Crawling peers + +Seed nodes crawl the network, connecting to random peers and sending PEX +requests to them, in order to learn as many peer addresses as possible. +More specifically, a node operating in seed mode sends PEX requests in two cases: + +1. When an outbound peer is added, and the seed node needs more peer addresses, + it requests peer addresses to the new peer +2. Periodically, the `crawlPeersRoutine` sends PEX requests to a random set of + peers, whose addresses are registered in the Address Book + +The first case also applies for nodes not operating in seed mode. +The second case replaces the second for regular nodes, as seed nodes do not +run the `ensurePeersRoutine`, as regular nodes, +but run the `crawlPeersRoutine`, which is not run by regular nodes. + +The `crawlPeersRoutine` periodically, every 30 seconds (`crawlPeerPeriod`), +starts a new peer discovery round. +First, the seed node retrieves a random selection of peer addresses from its +Address Book. +This selection is produced in the same way as in the random selection of peer +addresses that are [provided](#providing-addresses) to a requesting peer. +Peers that the seed node has crawled recently, +less than 2 minutes ago (`minTimeBetweenCrawls`), are removed from this selection. +The remaining peer addresses are registered in the `crawlPeerInfos` table. + +The seed node is not necessarily connected to the peer whose address is +selected for each round of crawling. +So, the seed node dials the selected peer addresses. +This is performed in foreground, one peer at a time. +As a result, a round of crawling can take a substantial amount of time. +For each selected peer it succeeds dialing to, this include already connected +peers, the seed node sends a PEX request. + +Dialing a selected peer address can fail for multiple reasons. +The seed node might have attempted to dial the peer too many times. +In this case, the peer address is marked as [bad in the address book](./addressbook.md#bad-peers). +The seed node might have attempted to dial the peer recently, without success, +and the exponential `backoffDuration` has not yet passed. +Or the current connection attempt might fail, which is registered in the address book. + +Failures to dial to a peer address produce an information that is important for +a seed node. +They indicate that a peer is unreachable, or is not operating correctly, and +therefore its address should not be provided to other nodes. +This occurs when, due to multiple failed connection attempts or authentication +failures, the peer address ends up being removed from the address book. +As a result, the periodically crawling of selected peers not only enables the +discovery of new peers, but also allows the seed node to stop providing +addresses of bad peers. + +### Offering addresses + +Nodes operating in seed mode handle PEX requests differently than regular +nodes, whose operation is described [here](#providing-addresses). + +This distinction exists because nodes dial a seed node with the main, if not +exclusive goal of retrieving peer addresses. +In other words, nodes do not dial a seed node because they intend to have it as +a peer in the multiple CometBFT protocols, but because they believe that a +seed node is a good source of addresses of nodes to which they can establish +connections and interact in the multiple CometBFT protocols. + +So, when a seed node receives a `PexRequest` message from an inbound peer, +it sends a `PexAddrs` message, containing a selection of peer +addresses, back to the peer and *disconnects* from it. +Seed nodes therefore treat inbound connections from peers as a short-term +connections, exclusively intended to retrieve peer addresses. +Once the requested peer addresses are sent, the connection with the peer is closed. + +Moreover, the selection of peer addresses provided to inbound peers by a seed +node, although still essentially random, has a [bias toward old +addresses](./addressbook.md#random-selection-with-bias). +The selection bias is defined by `biasToSelectNewPeers`, hard-coded to `30%`, +meaning that `70%` of the peer addresses provided by a seed node are expected +to be old addresses. +Although this nomenclature is not clear, *old* addresses are the addresses that +survived the most in the address book, that is, are addresses that the seed +node believes being from *good* peers (more details [here](./addressbook.md#good-peers)). + +Another distinction is on the handling of potential [misbehavior](#misbehavior-1) +of peers requesting addresses. +A seed node does not enforce, a priori, a minimal interval between PEX requests +from inbound peers. +Instead, it does not reply to more than one PEX request per peer inbound +connection, and, as above mentioned, it disconnects from incoming peers after +responding to them. +If the same peer dials again to the seed node and requests peer addresses, the +seed node will reply to this peer like it was the first time it has requested +peer addresses. + +> This is more an implementation restriction than a desired behavior. +> The `lastReceivedRequests` map stores the last time a PEX request was +> received from a peer, and the entry relative to a peer is removed from this +> map when the peer is disconnected. +> +> It is debatable whether this approach indeed prevents abuse against seed nodes. + +### Disconnecting from peers + +Seed nodes treat connections with peers as short-term connections, which are +mainly, if not exclusively, intended to exchange peer addresses. + +In the case of inbound peers, that have dialed the seed node, the intent of the +connection is achieved once a PEX response is sent to the peer. +The seed node thus disconnects from an inbound peer after sending a `PexAddrs` +message to it. + +In the case of outbound peers, which the seed node has dialed for crawling peer +addresses, the intent of the connection is essentially achieved when a PEX +response is received from the peer. +The seed node, however, does not disconnect from a peer after receiving a +selection of peer addresses from it. +As a result, after some rounds of crawling, a seed node will have established +connections to a substantial amount of peers. + +To couple with the existence of multiple connections with peers that have no +longer purpose for the seed node, the `crawlPeersRoutine` also invokes, after +each round of crawling, the `attemptDisconnects` method. +This method retrieves the list of connected peers from the switch, and +disconnects from peers that are not persistent peers, and with which a +connection is established for more than `SeedDisconnectWaitPeriod`. +This period is a configuration parameter, set to 28 hours when the PEX reactor +is created by the default node constructor. diff --git a/spec/p2p/implementation/pex.md b/spec/p2p/implementation/pex.md new file mode 100644 index 0000000..aea1cb8 --- /dev/null +++ b/spec/p2p/implementation/pex.md @@ -0,0 +1,111 @@ +# PEX Reactor + +The PEX reactor is one of the reactors running in a CometBFT node. + +Its implementation is located in the `p2p/pex` package, and it is considered +part of the implementation of the p2p layer. + +This document overviews the implementation of the PEX reactor, describing how +the methods from the `Reactor` interface are implemented. + +The actual operation of the PEX reactor is presented in documents describing +the roles played by the PEX reactor in the p2p layer: + +- [Address Book](./addressbook.md): stores known peer addresses and information + about peers to which the node is connected or has attempted to connect +- [Peer Manager](./peer_manager.md): manages connections established with peers, + defining when a node should dial peers and which peers it should dial +- [Peer Exchange protocol](./pex-protocol.md): enables nodes to exchange peer + addresses, thus implementing a peer discovery service + +## OnStart + +The `OnStart` method implements `BaseService` and starts the PEX reactor. + +The [address book](./addressbook.md), which is a `Service` is started. +This loads the address book content from disk, +and starts a routine that periodically persists the address book content to disk. + +The PEX reactor is configured with the addresses of a number of seed nodes, +the `Seeds` parameter of the `ReactorConfig`. +The addresses of seed nodes are parsed into `NetAddress` instances and resolved +into IP addresses, which is implemented by the `checkSeeds` method. +Valid seed node addresses are stored in the `seedAddrs` field, +and are used by the `dialSeeds` method to contact the configured seed nodes. + +The last action is to start one of the following persistent routines, based on +the `SeedMode` configuration parameter: + +- Regular nodes run the `ensurePeersRoutine` to check whether the node has + enough outbound peers, dialing peers when necessary +- Seed nodes run the `crawlPeersRoutine` to periodically start a new round + of [crawling](./pex-protocol.md#Crawling-peers) to discover as many peer + addresses as possible + +### Errors + +Errors encountered when loading the address book from disk are returned, +and prevent the reactor from being started. +An exception is made for the `service.ErrAlreadyStarted` error, which is ignored. + +Errors encountered when parsing the configured addresses of seed nodes +are returned and cause the reactor startup to fail. +An exception is made for DNS resolution `ErrNetAddressLookup` errors, +which are not deemed fatal and are only logged as invalid addresses. + +If none of the configured seed node addresses is valid, and the loaded address +book is empty, the reactor is not started and an error is returned. + +## OnStop + +The `OnStop` method implements `BaseService` and stops the PEX reactor. + +The address book routine that periodically saves its content to disk is stopped. + +## GetChannels + +The `GetChannels` method, from the `Reactor` interface, returns the descriptor +of the channel used by the PEX protocol. + +The channel ID is `PexChannel` (0), with priority `1`, send queue capacity of +`10`, and maximum message size of `64000` bytes. + +## AddPeer + +The `AddPeer` method, from the `Reactor` interface, +adds a new peer to the PEX protocol. + +If the new peer is an **inbound peer**, i.e., if the peer has dialed the node, +the peer's address is [added to the address book](./addressbook.md#adding-addresses). +Since the peer was authenticated when establishing a secret connection with it, +the source of the peer address is trusted, and its source is set by the peer itself. +In the case of an outbound peer, the node should already have its address in +the address book, as the switch has dialed the peer. + +If the peer is an **outbound peer**, i.e., if the node has dialed the peer, +and the PEX protocol needs more addresses, +the node [sends a PEX request](./pex-protocol.md#Requesting-Addresses) to the peer. +The same is not done when inbound peers are added because they are deemed least +trustworthy than outbound peers. + +## RemovePeer + +The `RemovePeer` method, from the `Reactor` interface, +removes a peer from the PEX protocol. + +The peer's ID is removed from the tables tracking PEX requests +[sent](./pex-protocol.md#misbehavior) but not yet replied +and PEX requests [received](./pex-protocol.md#misbehavior-1). + +## Receive + +The `Receive` method, from the `Reactor` interface, +handles a message received by the PEX protocol. + +A node receives two type of messages as part of the PEX protocol: + +- `PexRequest`: a request for addresses received from a peer, handled as + described [here](./pex-protocol.md#providing-addresses) +- `PexAddrs`: a list of addresses received from a peer, as a reponse to a PEX + request sent by the node, as described [here](./pex-protocol.md#responses) + diff --git a/spec/p2p/implementation/switch.md b/spec/p2p/implementation/switch.md new file mode 100644 index 0000000..c608c58 --- /dev/null +++ b/spec/p2p/implementation/switch.md @@ -0,0 +1,238 @@ +# Switch + +The switch is a core component of the p2p layer. +It manages the procedures for [dialing peers](#dialing-peers) and +[accepting](#accepting-peers) connections from peers, which are actually +implemented by the [transport](./transport.md). +It also manages the reactors, i.e., protocols implemented by the node that +interact with its peers. +Once a connection with a peer is established, the peer is [added](#add-peer) to +the switch and all registered reactors. +Reactors may also instruct the switch to [stop a peer](#stop-peer), namely +disconnect from it. +The switch, in this case, makes sure that the peer is removed from all +registered reactors. + +## Dialing peers + +Dialing a peer is implemented by the `DialPeerWithAddress` method. + +This method is invoked by the [peer manager](./peer_manager.md#ensure-peers) +to dial a peer address and establish a connection with an outbound peer. + +The switch keeps a single dialing routine per peer ID. +This is ensured by keeping a synchronized map `dialing` with the IDs of peers +to which the peer is dialing. +A peer ID is added to `dialing` when the `DialPeerWithAddress` method is called +for that peer, and it is removed when the method returns for whatever reason. +The method returns immediately when invoked for a peer which ID is already in +the `dialing` structure. + +The actual dialing is implemented by the [`Dial`](./transport.md#dial) method +of the transport configured for the switch, in the `addOutboundPeerWithConfig` +method. +If the transport succeeds establishing a connection, the returned `Peer` is +added to the switch using the [`addPeer`](#add-peer) method. +This operation can fail, returning an error. In this case, the switch invokes +the transport's [`Cleanup`](./transport.md#cleanup) method to clean any resources +associated with the peer. + +If the transport fails to establish a connection with the peer that is configured +as a persistent peer, the switch spawns a routine to [reconnect to the peer](#reconnect-to-peer). +If the peer is already in the `reconnecting` state, the spawned routine has no +effect and returns immediately. +This is in fact a likely scenario, as the `reconnectToPeer` routine relies on +this same `DialPeerWithAddress` method for dialing peers. + +### Manual operation + +The `DialPeersAsync` method receives a list of peer addresses (strings) +and dials all of them in parallel. +It is invoked in two situations: + +- In the [setup](https://github.com/cometbft/cometbft/blob/v0.34.x/node/node.go#L987) +of a node, to establish connections with every configured persistent peer +- In the RPC package, to implement two unsafe RPC commands, not used in production: + [`DialSeeds`](https://github.com/cometbft/cometbft/blob/v0.34.x/rpc/core/net.go#L47) and + [`DialPeers`](https://github.com/cometbft/cometbft/blob/v0.34.x/rpc/core/net.go#L87) + +The received list of peer addresses to dial is parsed into `NetAddress` instances. +In case of parsing errors, the method returns. An exception is made for +DNS resolution `ErrNetAddressLookup` errors, which do not interrupt the procedure. + +As the peer addresses provided to this method are typically not known by the node, +contrarily to the addressed dialed using the `DialPeerWithAddress` method, +they are added to the node's address book, which is persisted to disk. + +The switch dials the provided peers in parallel. +The list of peer addresses is randomly shuffled, and for each peer a routine is +spawned. +Each routine sleeps for a random interval, up to 3 seconds, then invokes the +`DialPeerWithAddress` method that actually dials the peer. + +### Reconnect to peer + +The `reconnectToPeer` method is invoked when a connection attempt to a peer fails, +and the peer is configured as a persistent peer. + +The `reconnecting` synchronized map keeps the peer's in this state, identified +by their IDs (string). +This should ensure that a single instance of this method is running at any time. +The peer is kept in this map while this method is running for it: it is set on +the beginning, and removed when the method returns for whatever reason. +If the peer is already in the `reconnecting` state, nothing is done. + +The remaining of the method performs multiple connection attempts to the peer, +via `DialPeerWithAddress` method. +If a connection attempt succeeds, the methods returns and the routine finishes. +The same applies when an `ErrCurrentlyDialingOrExistingAddress` error is +returned by the dialing method, as it indicates that peer is already connected +or that another routine is attempting to (re)connect to it. + +A first set of connection attempts is done at (about) regular intervals. +More precisely, between two attempts, the switch waits for a interval of +`reconnectInterval`, hard-coded to 5 seconds, plus a random jitter up to +`dialRandomizerIntervalMilliseconds`, hard-coded to 3 seconds. +At most `reconnectAttempts`, hard-coded to 20, are made using this +regular-interval approach. + +A second set of connection attempts is done with exponentially increasing +intervals. +The base interval `reconnectBackOffBaseSeconds` is hard-coded to 3 seconds, +which is also the increasing factor. +The exponentially increasing dialing interval is adjusted as well by a random +jitter up to `dialRandomizerIntervalMilliseconds`. +At most `reconnectBackOffAttempts`, hard-coded to 10, are made using this approach. + +> Note: the first sleep interval, to which a random jitter is applied, is 1, +> not `reconnectBackOffBaseSeconds`, as the first exponent is `0`... + +## Accepting peers + +The `acceptRoutine` method is a persistent routine that handles connections +accepted by the transport configured for the switch. + +The [`Accept`](./transport.md#accept) method of the configured transport +returns a `Peer` with which an inbound connection was established. +The switch accepts a new peer if the maximum number of inbound peers was not +reached, or if the peer was configured as an _unconditional peer_. +The maximum number of inbound peers is determined by the `MaxNumInboundPeers` +configuration parameter, whose default value is `40`. + +If accepted, the peer is added to the switch using the [`addPeer`](#add-peer) method. +If the switch does not accept the established incoming connection, or if the +`addPeer` method returns an error, the switch invokes the transport's +[`Cleanup`](./transport.md#cleanup) method to clean any resources associated +with the peer. + +The transport's `Accept` method can also return a number of errors. +Errors of `ErrRejected` or `ErrFilterTimeout` types are ignored, +an `ErrTransportClosed` causes the accepted routine to be interrupted, +while other errors cause the routine to panic. + +> TODO: which errors can cause the routine to panic? + +## Add peer + +The `addPeer` method adds a peer to the switch, +either after dialing (by `addOutboundPeerWithConfig`, called by `DialPeerWithAddress`) +a peer and establishing an outbound connection, +or after accepting (`acceptRoutine`) a peer and establishing an inbound connection. + +The first step is to invoke the `filterPeer` method. +It checks whether the peer is already in the set of connected peers, +and whether any of the configured `peerFilter` methods reject the peer. +If the peer is already present or it is rejected by any filter, the `addPeer` +method fails and returns an error. + +Then, the new peer is started, added to the set of connected peers, and added +to all reactors. +More precisely, first the new peer's information is first provided to every +reactor (`InitPeer` method). +Next, the peer's sending and receiving routines are started, and the peer is +added to set of connected peers. +These two operations can fail, causing `addPeer` to return an error. +Then, in the absence of previous errors, the peer is added to every reactor (`AddPeer` method). + +> Adding the peer to the peer set returns a `ErrSwitchDuplicatePeerID` error +> when a peer with the same ID is already presented. +> +> TODO: Starting a peer could be reduced as starting the MConn with that peer? + +## Stop peer + +There are two methods for stopping a peer, namely disconnecting from it, and +removing it from the table of connected peers. + +The `StopPeerForError` method is invoked to stop a peer due to an external +error, which is provided to method as a generic "reason". + +The `StopPeerGracefully` method stops a peer in the absence of errors or, more +precisely, not providing to the switch any "reason" for that. + +In both cases the `Peer` instance is stopped, the peer is removed from all +registered reactors, and finally from the list of connected peers. + +> Issue is mentioned in +> the internal `stopAndRemovePeer` method explaining why removing the peer from +> the list of connected peers is the last action taken. + +When there is a "reason" for stopping the peer (`StopPeerForError` method) +and the peer is a persistent peer, the method creates a routine to attempt +reconnecting to the peer address, using the `reconnectToPeer` method. +If the peer is an outbound peer, the peer's address is know, since the switch +has dialed the peer. +Otherwise, the peer address is retrieved from the `NodeInfo` instance from the +connection handshake. + +## Add reactor + +The `AddReactor` method registers a `Reactor` to the switch. + +The reactor is associated to the set of channel ids it employs. +Two reactors (in the same node) cannot share the same channel id. + +There is a call back to the reactor, in which the switch passes itself to the +reactor. + +## Remove reactor + +The `RemoveReactor` method unregisters a `Reactor` from the switch. + +The reactor is disassociated from the set of channel ids it employs. + +There is a call back to the reactor, in which the switch passes `nil` to the +reactor. + +## OnStart + +This is a `BaseService` method. + +All registered reactors are started. + +The switch's `acceptRoutine` is started. + +## OnStop + +This is a `BaseService` method. + +All (connected) peers are stopped and removed from the peer's list using the +`stopAndRemovePeer` method. + +All registered reactors are stopped. + +## Broadcast + +This method broadcasts a message on a channel, by sending the message in +parallel to all connected peers. + +The method spawns a thread for each connected peer, invoking the `Send` method +provided by each `Peer` instance with the provided message and channel ID. +The return value (a boolean) of these calls are redirected to a channel that is +returned by the method. + +> TODO: detail where this method is invoked: +> +> - By the consensus protocol, in `broadcastNewRoundStepMessage`, +> `broadcastNewValidBlockMessage`, and `broadcastHasVoteMessage` +> - By the state sync protocol diff --git a/spec/p2p/implementation/transport.md b/spec/p2p/implementation/transport.md new file mode 100644 index 0000000..761ffea --- /dev/null +++ b/spec/p2p/implementation/transport.md @@ -0,0 +1,222 @@ +# Transport + +The transport establishes secure and authenticated connections with peers. + +The transport [`Dial`](#dial)s peer addresses to establish outbound connections, +and [`Listen`](#listen)s in a configured network address +to [`Accept`](#accept) inbound connections from peers. + +The transport establishes raw TCP connections with peers +and [upgrade](#connection-upgrade) them into authenticated secret connections. +The established secret connection is then wrapped into `Peer` instance, which +is returned to the caller, typically the [switch](./switch.md). + +## Dial + +The `Dial` method is used by the switch to establish an outbound connection with a peer. +It is a synchronous method, which blocks until a connection is established or an error occurs. +The method returns an outbound `Peer` instance wrapping the established connection. + +The transport first dials the provided peer's address to establish a raw TCP connection. +The dialing maximum duration is determined by `dialTimeout`, hard-coded to 1 second. +The established raw connection is then submitted to a set of [filters](#connection-filtering), +which can reject it. +If the connection is not rejected, it is recorded in the table of established connections. + +The established raw TCP connection is then [upgraded](#connection-upgrade) into +an authenticated secret connection. +This procedure should ensure, in particular, that the public key of the remote peer +matches the ID of the dialed peer, which is part of peer address provided to this method. +In the absence of errors, +the established secret connection (`conn.SecretConnection` type) +and the information about the peer (`NodeInfo` record) retrieved and verified +during the version handshake, +are wrapped into an outbound `Peer` instance and returned to the switch. + +## Listen + +The `Listen` method produces a TCP listener instance for the provided network +address, and spawns an `acceptPeers` routine to handle the raw connections +accepted by the listener. +The `NetAddress` method exports the listen address configured for the transport. + +The maximum number of simultaneous incoming connections accepted by the listener +is bound to `MaxNumInboundPeer` plus the configured number of unconditional peers, +using the `MultiplexTransportMaxIncomingConnections` option, +in the node [initialization](https://github.com/cometbft/cometbft/blob/v0.34.x/node/node.go#L563). + +This method is called when a node is [started](https://github.com/cometbft/cometbft/blob/v0.34.x/node/node.go#L974). +In case of errors, the `acceptPeers` routine is not started and the error is returned. + +## Accept + +The `Accept` method returns to the switch inbound connections established with a peer. +It is a synchronous method, which blocks until a connection is accepted or an error occurs. +The method returns an inbound `Peer` instance wrapping the established connection. + +The transport handles incoming connections in the `acceptPeers` persistent routine. +This routine is started by the [`Listen`](#listen) method +and accepts raw connections from a TCP listener. +A new routine is spawned for each accepted connection. +The raw connection is submitted to a set of [filters](#connection-filtering), +which can reject it. +If the connection is not rejected, it is recorded in the table of established connections. + +The established raw TCP connection is then [upgraded](#connection-upgrade) into +an authenticated secret connection. +The established secret connection (`conn.SecretConnection` type), +the information about the peer (`NodeInfo` record) retrieved and verified +during the version handshake, +as well any error returned in this process are added to a queue of accepted connections. +This queue is consumed by the `Accept` method. + +> Handling accepted connection asynchronously was introduced due to this issue: +> + +## Connection Filtering + +The `filterConn` method is invoked for every new raw connection established by the transport. +Its main goal is avoid the transport to maintain duplicated connections with the same peer. +It also runs a set of configured connection filters. + +The transports keeps a table `conns` of established connections. +The table maps the remote address returned by a generic connection to a list of +IP addresses, to which the connection remote address is resolved. +If the remote address of the new connection is already present in the table, +the connection is rejected. +Otherwise, the connection's remote address is resolved into a list of IPs, +which are recorded in the established connections table. + +The connection and the resolved IPs are then passed through a set of connection filters, +configured via the `MultiplexTransportConnFilters` transport option. +The maximum duration for the filters execution, which is performed in parallel, +is determined by `filterTimeout`. +Its default value is 5 seconds, +which can be changed using the `MultiplexTransportFilterTimeout` transport option. + +If the connection and the resolved remote addresses are not filtered out, +the transport registers them into the `conns` table and returns. + +In case of errors, the connection is removed from the table of established +connections and closed. + +### Errors + +If the address of the new connection is already present in the `conns` table, +an `ErrRejected` error with the `isDuplicate` reason is returned. + +If the IP resolution of the connection's remote address fails, +an `AddrError` or `DNSError` error is returned. + +If any of the filters reject the connection, +an `ErrRejected` error with the `isRejected` reason is returned. + +If the filters execution times out, +an `ErrFilterTimeout` error is returned. + +## Connection Upgrade + +The `upgrade` method is invoked for every new raw connection established by the +transport that was not [filtered out](#connection-filtering). +It upgrades an established raw TCP connection into a secret authenticated +connection, and validates the information provided by the peer. + +This is a complex procedure, that can be summarized by the following three +message exchanges between the node and the new peer: + +1. Encryption: the nodes produce ephemeral key pairs and exchange ephemeral + public keys, from which are derived: (i) a pair of secret keys used to + encrypt the data exchanged between the nodes, and (ii) a challenge message. +1. Authentication: the nodes exchange their persistent public keys and a + signature of the challenge message produced with the their persistent + private keys. This allows validating the peer's persistent public key, + which plays the role of node ID. +1. Version handshake: nodes exchange and validate each other `NodeInfo` records. + This records contain, among other fields, their node IDs, the network/chain + ID they are part of, and the list of supported channel IDs. + +Steps (1) and (2) are implemented in the `conn` package. +In case of success, they produce the secret connection that is actually used by +the node to communicate with the peer. +An overview of this procedure, which implements the station-to-station (STS) +[protocol][sts-paper] ([PDF][sts-paper-pdf]), can be found [here][peer-sts]. +The maximum duration for establishing a secret connection with the peer is +defined by `handshakeTimeout`, hard-coded to 3 seconds. + +The established secret connection stores the persistent public key of the peer, +which has been validated via the challenge authentication of step (2). +If the connection being upgraded is an outbound connection, i.e., if the node has +dialed the peer, the dialed peer's ID is compared to the peer's persistent public key: +if they do not match, the connection is rejected. +This verification is not performed in the case of inbound (accepted) connections, +as the node does not know a priori the remote node's ID. + +Step (3), the version handshake, is performed by the transport. +Its maximum duration is also defined by `handshakeTimeout`, hard-coded to 3 seconds. +The version handshake retrieves the `NodeInfo` record of the new peer, +which can be rejected for multiple reasons, listed [here][peer-handshake]. + +If the connection upgrade succeeds, the method returns the established secret +connection, an instance of `conn.SecretConnection` type, +and the `NodeInfo` record of the peer. + +In case of errors, the connection is removed from the table of established +connections and closed. + +### Errors + +The timeouts for steps (1) and (2), and for step (3), are configured as the +deadline for operations on the TCP connection that is being upgraded. +If this deadline it is reached, the connection produces an +`os.ErrDeadlineExceeded` error, returned by the corresponding step. + +Any error produced when establishing a secret connection with the peer (steps 1 and 2) or +during the version handshake (step 3), including timeouts, +is encapsulated into an `ErrRejected` error with reason `isAuthFailure` and returned. + +If the upgraded connection is an outbound connection, and the peer ID learned in step (2) +does not match the dialed peer's ID, +an `ErrRejected` error with reason `isAuthFailure` is returned. + +If the peer's `NodeInfo` record, retrieved in step (3), is invalid, +or if reports a node ID that does not match peer ID learned in step (2), +an `ErrRejected` error with reason `isAuthFailure` is returned. +If it reports a node ID equals to the local node ID, +an `ErrRejected` error with reason `isSelf` is returned. +If it is not compatible with the local `NodeInfo`, +an `ErrRejected` error with reason `isIncompatible` is returned. + +## Close + +The `Close` method closes the TCP listener created by the `Listen` method, +and sends a signal for interrupting the `acceptPeers` routine. + +This method is called when a node is [stopped](https://github.com/cometbft/cometbft/blob/v0.34.x/node/node.go#L1023). + +## Cleanup + +The `Cleanup` method receives a `Peer` instance, +and removes the connection established with a peer from the table of established connections. +It also invokes the `Peer` interface method to close the connection associated with a peer. + +It is invoked when the connection with a peer is closed. + +## Supported channels + +The `AddChannel` method registers a channel in the transport. + +The channel ID is added to the list of supported channel IDs, +stored in the local `NodeInfo` record. + +The `NodeInfo` record is exchanged with peers in the version handshake. +For this reason, this method is not invoked with a started transport. + +> The only call to this method is performed in the `CustomReactors` constructor +> option of a node, i.e., before the node is started. +> Note that the default list of supported channel IDs, including the default reactors, +> is provided to the transport as its original `NodeInfo` record. + +[peer-sts]: ../legacy-docs/peer.md#authenticated-encryption-handshake +[peer-handshake]: ../legacy-docs/peer.md#cometbft-version-handshake +[sts-paper]: https://link.springer.com/article/10.1007/BF00124891 +[sts-paper-pdf]: https://github.com/tendermint/tendermint/blob/0.1/docs/sts-final.pdf diff --git a/spec/p2p/implementation/types.md b/spec/p2p/implementation/types.md new file mode 100644 index 0000000..e8034fb --- /dev/null +++ b/spec/p2p/implementation/types.md @@ -0,0 +1,233 @@ +# Types adopted in the p2p implementation + +This document lists the packages and source files, excluding test units, that +implement the p2p layer, and summarizes the main types they implement. +Types play the role of classes in Go. + +The reference version for this documentation is the branch +[`v0.34.x`](https://github.com/cometbft/cometbft/tree/v0.34.x/p2p). + +State of August 2022. + +## Package `p2p` + +Implementation of the p2p layer of CometBFT. + +### `base_reactor.go` + +`Reactor` interface. + +`BaseReactor` implements `Reactor`. + +**Not documented yet**. + +### `conn_set.go` + +`ConnSet` interface, a "lookup table for connections and their ips". + +Internal type `connSet` implements the `ConnSet` interface. + +Used by the [transport](#transportgo) to store connected peers. + +### `errors.go` + +Defines several error types. + +`ErrRejected` enumerates a number of reason for which a peer was rejected. +Mainly produced by the [transport](#transportgo), +but also by the [switch](#switchgo). + +`ErrSwitchDuplicatePeerID` is produced by the `PeerSet` used by the [switch](#switchgo). + +`ErrSwitchConnectToSelf` is handled by the [switch](#switchgo), +but currently is not produced outside tests. + +`ErrSwitchAuthenticationFailure` is handled by the [PEX reactor](#pex_reactorgo), +but currently is not produced outside tests. + +`ErrTransportClosed` is produced by the [transport](#transportgo) +and handled by the [switch](#switchgo). + +`ErrNetAddressNoID`, `ErrNetAddressInvalid`, and `ErrNetAddressLookup` +are parsing a string to create an instance of `NetAddress`. +It can be returned in the setup of the [switch](#switchgo) +and of the [PEX reactor](#pex_reactorgo), +as well when the [transport](#transportgo) validates a `NodeInfo`, as part of +the connection handshake. + +`ErrCurrentlyDialingOrExistingAddress` is produced by the [switch](#switchgo), +and handled by the switch and the [PEX reactor](#pex_reactorgo). + +### `fuzz.go` + +For testing purposes. + +`FuzzedConnection` wraps a `net.Conn` and injects random delays. + +### `key.go` + +`NodeKey` is the persistent key of a node, namely its private key. + +The `ID` of a node is a string representing the node's public key. + +### `metrics.go` + +Prometheus `Metrics` exposed by the p2p layer. + +### `netaddress.go` + +Type `NetAddress` contains the `ID` and the network address (IP and port) of a node. + +The API of the [address book](#addrbookgo) receives and returns `NetAddress` instances. + +This source file was adapted from [`btcd`](https://github.com/btcsuite/btcd), +a Go implementation of Bitcoin. + +### `node_info.go` + +Interface `NodeInfo` stores the basic information about a node exchanged with a +peer during the handshake. + +It is implemented by `DefaultNodeInfo` type. + +The [switch](#switchgo) stores the local `NodeInfo`. + +The `NodeInfo` of connected peers is produced by the +[transport](#transportgo) during the handshake, and stored in [`Peer`](#peergo) instances. + +### `peer.go` + +Interface `Peer` represents a connected peer. + +It is implemented by the internal `peer` type. + +The [transport](#transportgo) API methods return `Peer` instances, +wrapping established secure connection with peers. + +The [switch](#switchgo) API methods receive `Peer` instances. +The switch stores connected peers in a `PeerSet`. + +The [`Reactor`](#base_reactorgo) methods, invoked by the switch, receive `Peer` instances. + +### `peer_set.go` + +Interface `IPeerSet` offers methods to access a table of [`Peer`](#peergo) instances. + +Type `PeerSet` implements a thread-safe table of [`Peer`](#peergo) instances, +used by the [switch](#switchgo). + +The switch provides limited access to this table by returing a `IPeerSet` +instance, used by the [PEX reactor](#pex_reactorgo). + +### `switch.go` + +Documented in [switch](./switch.md). + +The `Switch` implements the [peer manager](./peer_manager.md) role for inbound peers. + +[`Reactor`](#base_reactorgo)s have access to the `Switch` and may invoke its methods. +This includes the [PEX reactor](#pex_reactorgo). + +### `transport.go` + +Documented in [transport](./transport.md). + +The `Transport` interface is implemented by `MultiplexTransport`. + +The [switch](#switchgo) contains a `Transport` and uses it to establish +connections with peers. + +### `types.go` + +Aliases for p2p's `conn` package types. + +## Package `p2p.conn` + +Implements the connection between CometBFT nodes, +which is encrypted, authenticated, and multiplexed. + +### `connection.go` + +Implements the `MConnection` type and the `Channel` abstraction. + +A `MConnection` multiplexes a generic network connection (`net.Conn`) into +multiple independent `Channel`s, used by different [`Reactor`](#base_reactorgo)s. + +A [`Peer`](#peergo) stores the `MConnection` instance used to interact with a +peer, which multiplex a [`SecretConnection`](#secret_connectiongo). + +### `conn_go110.go` + +Support for go 1.10. + +### `secret_connection.go` + +Implements the `SecretConnection` type, which is an encrypted authenticated +connection built atop a raw network (TCP) connection. + +A [`Peer`](#peergo) stores the `SecretConnection` established by the transport, +which is the underlying connection multiplexed by [`MConnection`](#connectiongo). + +As briefly documented in the [transport](./transport.md#Connection-Upgrade), +a `SecretConnection` implements the Station-To-Station (STS) protocol. + +The `SecretConnection` type implements the `net.Conn` interface, +which is a generic network connection. + +## Package `p2p.mock` + +Mock implementations of [`Peer`](#peergo) and [`Reactor`](#base_reactorgo) interfaces. + +## Package `p2p.mocks` + +Code generated by `mockery`. + +## Package `p2p.pex` + +Implementation of the [PEX reactor](./pex.md). + +### `addrbook.go` + +Documented in [address book](./addressbook.md). + +This source file was adapted from [`btcd`](https://github.com/btcsuite/btcd), +a Go implementation of Bitcoin. + +### `errors.go` + +A number of errors produced and handled by the [address book](#addrbookgo). + +`ErrAddrBookNilAddr` is produced by the address book, but handled (logged) by +the [PEX reactor](#pex_reactorgo). + +`ErrUnsolicitedList` is produced and handled by the [PEX protocol](#pex_reactorgo). + +### `file.go` + +Implements the [address book](#addrbookgo) persistence. + +### `known_address.go` + +Type `knownAddress` represents an address stored in the [address book](#addrbookgo). + +### `params.go` + +Constants used by the [address book](#addrbookgo). + +### `pex_reactor.go` + +Implementation of the [PEX reactor](./pex.md), which is a [`Reactor`](#base_reactorgo). + +This includes the implementation of the [PEX protocol](./pex-protocol.md) +and of the [peer manager](./peer_manager.md) role for outbound peers. + +The PEX reactor also manages an [address book](#addrbookgo) instance. + +## Package `p2p.trust` + +Go documentation of `Metric` type: + +> // Metric - keeps track of peer reliability +> // See cometbft/docs/architecture/adr-006-trust-metric.md for details + +Not imported by any other CometBFT source file. diff --git a/spec/p2p/legacy-docs/README.md b/spec/p2p/legacy-docs/README.md new file mode 100644 index 0000000..d4405d6 --- /dev/null +++ b/spec/p2p/legacy-docs/README.md @@ -0,0 +1,16 @@ +--- +order: 1 +title: Legacy Docs +--- + +# Legacy Docs + +This section contains useful information. However, part of this content is redundant, being more comprehensively covered +in more recent documents, and some implementation details might be outdated +(see issue [#981](https://github.com/cometbft/cometbft/issues/981)). + +- [Messages](./messages) +- [P2P Config](./config.md) +- [P2P Multiplex Connection](./connection.md) +- [Peer Discovery](./node.md) +- [Peers](./peer.md) diff --git a/spec/p2p/legacy-docs/config.md b/spec/p2p/legacy-docs/config.md new file mode 100644 index 0000000..019d7cf --- /dev/null +++ b/spec/p2p/legacy-docs/config.md @@ -0,0 +1,53 @@ +--- +order: 1 +--- + +# P2P Config + +Here we describe configuration options around the Peer Exchange. +These can be set using flags or via the `$CMTHOME/config/config.toml` file. + +## Seed Mode + +`--p2p.seed_mode` + +The node operates in seed mode. In seed mode, a node continuously crawls the network for peers, +and upon incoming connection shares some peers and disconnects. + +## Seeds + +`--p2p.seeds “id100000000000000000000000000000000@1.2.3.4:26656,id200000000000000000000000000000000@2.3.4.5:4444”` + +Dials these seeds when we need more peers. They should return a list of peers and then disconnect. +If we already have enough peers in the address book, we may never need to dial them. + +## Persistent Peers + +`--p2p.persistent_peers “id100000000000000000000000000000000@1.2.3.4:26656,id200000000000000000000000000000000@2.3.4.5:26656”` + +Dial these peers and auto-redial them if the connection fails. +These are intended to be trusted persistent peers that can help +anchor us in the p2p network. The auto-redial uses exponential +backoff and will give up after a day of trying to connect. + +But If `persistent_peers_max_dial_period` is set greater than zero, +pause between each dial to each persistent peer will not exceed `persistent_peers_max_dial_period` +during exponential backoff and we keep trying again without giving up + +**Note:** If `seeds` and `persistent_peers` intersect, +the user will be warned that seeds may auto-close connections +and that the node may not be able to keep the connection persistent. + +## Private Peers + +`--p2p.private_peer_ids “id100000000000000000000000000000000,id200000000000000000000000000000000”` + +These are IDs of the peers that we do not add to the address book or gossip to +other peers. They stay private to us. + +## Unconditional Peers + +`--p2p.unconditional_peer_ids “id100000000000000000000000000000000,id200000000000000000000000000000000”` + +These are IDs of the peers which are allowed to be connected by both inbound or outbound regardless of +`max_num_inbound_peers` or `max_num_outbound_peers` of user's node reached or not. diff --git a/spec/p2p/legacy-docs/connection.md b/spec/p2p/legacy-docs/connection.md new file mode 100644 index 0000000..2187bbd --- /dev/null +++ b/spec/p2p/legacy-docs/connection.md @@ -0,0 +1,115 @@ +--- +order: 1 +--- + +# P2P Multiplex Connection + +## MConnection + +`MConnection` is a multiplex connection that supports multiple independent streams +with distinct quality of service guarantees atop a single TCP connection. +Each stream is known as a `Channel` and each `Channel` has a globally unique _byte id_. +Each `Channel` also has a relative priority that determines the quality of service +of the `Channel` compared to other `Channel`s. +The _byte id_ and the relative priorities of each `Channel` are configured upon +initialization of the connection. + +The `MConnection` supports three packet types: + +- Ping +- Pong +- Msg + +### Ping and Pong + +The ping and pong messages consist of writing a single byte to the connection; 0x1 and 0x2, respectively. + +When we haven't received any messages on an `MConnection` in time `pingTimeout`, we send a ping message. +When a ping is received on the `MConnection`, a pong is sent in response only if there are no other messages +to send and the peer has not sent us too many pings (TODO). + +If a pong or message is not received in sufficient time after a ping, the peer is disconnected from. + +### Msg + +Messages in channels are chopped into smaller `msgPacket`s for multiplexing. + +```go +type msgPacket struct { + ChannelID byte + EOF byte // 1 means message ends here. + Bytes []byte +} +``` + +The `msgPacket` is serialized using [Proto3](https://developers.google.com/protocol-buffers/docs/proto3). +The received `Bytes` of a sequential set of packets are appended together +until a packet with `EOF=1` is received, then the complete serialized message +is returned for processing by the `onReceive` function of the corresponding channel. + +### Multiplexing + +Messages are sent from a single `sendRoutine`, which loops over a select statement and results in the sending +of a ping, a pong, or a batch of data messages. The batch of data messages may include messages from multiple channels. +Message bytes are queued for sending in their respective channel, with each channel holding one unsent message at a time. +Messages are chosen for a batch one at a time from the channel with the lowest ratio of recently sent bytes to channel priority. + +## Sending Messages + +There are two methods for sending messages: + +```go +func (m MConnection) Send(chID byte, msg interface{}) bool {} +func (m MConnection) TrySend(chID byte, msg interface{}) bool {} +``` + +`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued +for the channel with the given id byte `chID`. The message `msg` is serialized +using protobuf marshalling. + +`TrySend(chID, msg)` is a nonblocking call that queues the message msg in the channel +with the given id byte chID if the queue is not full; otherwise it returns false immediately. + +`Send()` and `TrySend()` are also exposed for each `Peer`. + +## Peer + +Each peer has one `MConnection` instance, and includes other information such as whether the connection +was outbound, whether the connection should be recreated if it closes, various identity information about the node, +and other higher level thread-safe data used by the reactors. + +## Switch/Reactor + +The `Switch` handles peer connections and exposes an API to receive incoming messages +on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one +or more `Channels`. So while sending outgoing messages is typically performed on the peer, +incoming messages are received on the reactor. + +```go +// Declare a MyReactor reactor that handles messages on MyChannelID. +type MyReactor struct{} + +func (reactor MyReactor) GetChannels() []*ChannelDescriptor { + return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}} +} + +func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { + r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error) + msgString := ReadString(r, n, err) + fmt.Println(msgString) +} + +// Other Reactor methods omitted for brevity +... + +switch := NewSwitch([]Reactor{MyReactor{}}) + +... + +// Send a random message to all outbound connections +for _, peer := range switch.Peers().List() { + if peer.IsOutbound() { + peer.Send(MyChannelID, "Here's a random message") + } +} +``` diff --git a/spec/p2p/legacy-docs/messages/README.md b/spec/p2p/legacy-docs/messages/README.md new file mode 100644 index 0000000..896d77f --- /dev/null +++ b/spec/p2p/legacy-docs/messages/README.md @@ -0,0 +1,19 @@ +--- +order: 1 +parent: + title: Messages + order: 1 +--- + +# Messages + +An implementation of the spec consists of many components. While many parts of these components are implementation specific, the p2p messages are not. In this section we will be covering all the p2p messages of components. + +There are two parts to the P2P messages, the message and the channel. The channel is message specific and messages are specific to components of CometBFT. When a node connect to a peer it will tell the other node which channels are available. This notifies the peer what services the connecting node offers. You can read more on channels in [connection.md](../connection.md#mconnection) + +- [Block Sync](./block-sync.md) +- [Mempool](./mempool.md) +- [Evidence](./evidence.md) +- [State Sync](./state-sync.md) +- [Pex](./pex.md) +- [Consensus](./consensus.md) diff --git a/spec/p2p/legacy-docs/messages/block-sync.md b/spec/p2p/legacy-docs/messages/block-sync.md new file mode 100644 index 0000000..0a4c4c2 --- /dev/null +++ b/spec/p2p/legacy-docs/messages/block-sync.md @@ -0,0 +1,70 @@ +--- +order: 2 +--- + +# Block Sync + +## Channel + +Block sync has one channel. + +| Name | Number | +|-------------------|--------| +| BlocksyncChannel | 64 | + +## Message Types + +There are multiple message types for Block Sync + +### BlockRequest + +BlockRequest asks a peer for a block at the height specified. + +| Name | Type | Description | Field Number | +|--------|-------|---------------------------|--------------| +| Height | int64 | Height of requested block | 1 | + +### NoBlockResponse + +NoBlockResponse notifies the peer requesting a block that the node does not contain it. + +| Name | Type | Description | Field Number | +|--------|-------|---------------------------|--------------| +| Height | int64 | Height of requested block | 1 | + +### BlockResponse + +BlockResponse contains the block requested. +It also contains an extended commit _iff_ vote extensions are enabled at the block's height. + +| Name | Type | Description | Field Number | +|-----------|----------------------------------------------------------------|---------------------------------|--------------| +| Block | [Block](../../../core/data_structures.md#block) | Requested Block | 1 | +| ExtCommit | [ExtendedCommit](../../../core/data_structures.md#extendedcommit) | Sender's LastCommit information | 2 | + +### StatusRequest + +StatusRequest is an empty message that notifies the peer to respond with the highest and lowest blocks it has stored. + +> Empty message. + +### StatusResponse + +StatusResponse responds to a peer with the highest and lowest heights of any block it has in its blockstore. + +| Name | Type | Description | Field Number | +|--------|-------|-------------------------------------------------------------------|--------------| +| Height | int64 | Current Height of a node | 1 | +| Base | int64 | First known block, if pruning is enabled it will be higher than 1 | 2 | + +### Message + +Message is a [`oneof` protobuf type](https://developers.google.com/protocol-buffers/docs/proto#oneof). The `oneof` consists of five messages. + +| Name | Type | Description | Field Number | +|-------------------|-------------------------------------|--------------------------------------------------------------|--------------| +| block_request | [BlockRequest](#blockrequest) | Request a block from a peer | 1 | +| no_block_response | [NoBlockResponse](#noblockresponse) | Response saying it doe snot have the requested block | 2 | +| block_response | [BlockResponse](#blockresponse) | Response with requested block + (optionally) vote extensions | 3 | +| status_request | [StatusRequest](#statusrequest) | Request the highest and lowest block numbers from a peer | 4 | +| status_response | [StatusResponse](#statusresponse) | Response with the highest and lowest block numbers the store | 5 | diff --git a/spec/p2p/legacy-docs/messages/consensus.md b/spec/p2p/legacy-docs/messages/consensus.md new file mode 100644 index 0000000..093c7eb --- /dev/null +++ b/spec/p2p/legacy-docs/messages/consensus.md @@ -0,0 +1,146 @@ +--- +order: 7 +--- + +# Consensus + +## Channel + +Consensus has four separate channels. The channel identifiers are listed below. + +| Name | Number | +|--------------------|--------| +| StateChannel | 32 | +| DataChannel | 33 | +| VoteChannel | 34 | +| VoteSetBitsChannel | 35 | + +## Message Types + +### Proposal + +Proposal is sent when a new block is proposed. It is a suggestion of what the +next block in the blockchain should be. + +| Name | Type | Description | Field Number | +|----------|----------------------------------------------------|----------------------------------------|--------------| +| proposal | [Proposal](../../../core/data_structures.md#proposal) | Proposed Block to come to consensus on | 1 | + +### Vote + +Vote is sent to vote for some block (or to inform others that a process does not vote in the +current round). Vote contains validator's information (validator address and index), height and +round for which the vote is sent, vote type, blockID if process vote for some block (`nil` otherwise) +and a timestamp when the vote is sent. The message is signed by the validator private key. + +| Name | Type | Description | Field Number | +|------|--------------------------------------------|---------------------------|--------------| +| vote | [Vote](../../../core/data_structures.md#vote) | Vote for a proposed Block | 1 | + +### BlockPart + +BlockPart is sent when gossiping a piece of the proposed block. It contains height, round +and the block part. + +| Name | Type | Description | Field Number | +|--------|--------------------------------------------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block. | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| part | [Part](../../../core/data_structures.md#part) | A part of the block. | 3 | + +### NewRoundStep + +NewRoundStep is sent for every step transition during the core consensus algorithm execution. +It is used in the gossip part of the CometBFT consensus protocol to inform peers about a current +height/round/step a process is in. + +| Name | Type | Description | Field Number | +|--------------------------|--------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| step | uint32 | | 3 | +| seconds_since_start_time | int64 | | 4 | +| last_commit_round | int32 | | 5 | + +### NewValidBlock + +NewValidBlock is sent when a validator observes a valid block B in some round r, +i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r. +It contains height and round in which valid block is observed, block parts header that describes +the valid block and is used to obtain all +block parts, and a bit array of the block parts a process currently has, so its peers can know what +parts it is missing so they can send them. +In case the block is also committed, then IsCommit flag is set to true. + +| Name | Type | Description | Field Number | +|-----------------------|--------------------------------------------------------------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| block_part_set_header | [PartSetHeader](../../../core/data_structures.md#partsetheader) | | 3 | +| block_parts | int32 | | 4 | +| is_commit | bool | | 5 | + +### ProposalPOL + +ProposalPOL is sent when a previous block is re-proposed. +It is used to inform peers in what round the process learned for this block (ProposalPOLRound), +and what prevotes for the re-proposed block the process has. + +| Name | Type | Description | Field Number | +|--------------------|----------|-------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| proposal_pol_round | int32 | | 2 | +| proposal_pol | bitarray | | 3 | + +### ReceivedVote + +ReceivedVote is sent to indicate that a particular vote has been received. It contains height, +round, vote type and the index of the validator that is the originator of the corresponding vote. + +| Name | Type | Description | Field Number | +|--------|------------------------------------------------------------------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| type | [SignedMessageType](../../../core/data_structures.md#signedmsgtype) | | 3 | +| index | int32 | | 4 | + +### VoteSetMaj23 + +VoteSetMaj23 is sent to indicate that a process has seen +2/3 votes for some BlockID. +It contains height, round, vote type and the BlockID. + +| Name | Type | Description | Field Number | +|--------|------------------------------------------------------------------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| type | [SignedMessageType](../../../core/data_structures.md#signedmsgtype) | | 3 | + +### VoteSetBits + +VoteSetBits is sent to communicate the bit-array of votes a process has seen for a given +BlockID. It contains height, round, vote type, BlockID and a bit array of +the votes a process has. + +| Name | Type | Description | Field Number | +|----------|------------------------------------------------------------------|----------------------------------------|--------------| +| height | int64 | Height of corresponding block | 1 | +| round | int32 | Round of voting to finalize the block. | 2 | +| type | [SignedMessageType](../../../core/data_structures.md#signedmsgtype) | | 3 | +| block_id | [BlockID](../../../core/data_structures.md#blockid) | | 4 | +| votes | BitArray | Round of voting to finalize the block. | 5 | + +### Message + +Message is a [`oneof` protobuf type](https://developers.google.com/protocol-buffers/docs/proto#oneof). + +| Name | Type | Description | Field Number | +|-----------------|---------------------------------|----------------------------------------|--------------| +| new_round_step | [NewRoundStep](#newroundstep) | Height of corresponding block | 1 | +| new_valid_block | [NewValidBlock](#newvalidblock) | Round of voting to finalize the block. | 2 | +| proposal | [Proposal](#proposal) | | 3 | +| proposal_pol | [ProposalPOL](#proposalpol) | | 4 | +| block_part | [BlockPart](#blockpart) | | 5 | +| vote | [Vote](#vote) | | 6 | +| received_vote | [ReceivedVote](#receivedvote) | | 7 | +| vote_set_maj23 | [VoteSetMaj23](#votesetmaj23) | | 8 | +| vote_set_bits | [VoteSetBits](#votesetbits) | | 9 | diff --git a/spec/p2p/legacy-docs/messages/evidence.md b/spec/p2p/legacy-docs/messages/evidence.md new file mode 100644 index 0000000..f0dccaa --- /dev/null +++ b/spec/p2p/legacy-docs/messages/evidence.md @@ -0,0 +1,23 @@ +--- +order: 3 +--- + +# Evidence + +## Channel + +Evidence has one channel. The channel identifier is listed below. + +| Name | Number | +|-----------------|--------| +| EvidenceChannel | 56 | + +## Message Types + +### EvidenceList + +EvidenceList consists of a list of verified evidence. This evidence will already have been propagated throughout the network. EvidenceList is used in two places, as a p2p message and within the block [block](../../../core/data_structures.md#block) as well. + +| Name | Type | Description | Field Number | +|----------|-------------------------------------------------------------|------------------------|--------------| +| evidence | repeated [Evidence](../../../core/data_structures.md#evidence) | List of valid evidence | 1 | diff --git a/spec/p2p/legacy-docs/messages/mempool.md b/spec/p2p/legacy-docs/messages/mempool.md new file mode 100644 index 0000000..ecec118 --- /dev/null +++ b/spec/p2p/legacy-docs/messages/mempool.md @@ -0,0 +1,33 @@ +--- +order: 4 +--- +# Mempool + +## Channel + +Mempool has one channel. The channel identifier is listed below. + +| Name | Number | +|----------------|--------| +| MempoolChannel | 48 | + +## Message Types + +There is currently only one message that Mempool broadcasts and receives over +the p2p gossip network (via the reactor): `TxsMessage` + +### Txs + +A list of transactions. These transactions have been checked against the application for validity. This does not mean that the transactions are valid, it is up to the application to check this. + +| Name | Type | Description | Field Number | +|------|----------------|----------------------|--------------| +| txs | repeated bytes | List of transactions | 1 | + +### Message + +Message is a [`oneof` protobuf type](https://developers.google.com/protocol-buffers/docs/proto#oneof). The one of consists of one message [`Txs`](#txs). + +| Name | Type | Description | Field Number | +|------|-------------|-----------------------|--------------| +| txs | [Txs](#txs) | List of transactions | 1 | diff --git a/spec/p2p/legacy-docs/messages/pex.md b/spec/p2p/legacy-docs/messages/pex.md new file mode 100644 index 0000000..9772cd0 --- /dev/null +++ b/spec/p2p/legacy-docs/messages/pex.md @@ -0,0 +1,76 @@ +--- +order: 6 +--- + +# Peer Exchange + +## Channels + +Pex has one channel. The channel identifier is listed below. + +| Name | Number | +|------------|--------| +| PexChannel | 0 | + +## Message Types + +The current PEX service has two versions. The first uses IP/port pair but since the p2p stack is moving towards a transport agnostic approach, +node endpoints require a `Protocol` and `Path` hence the V2 version uses a [url](https://golang.org/pkg/net/url/#URL) instead. + +### PexRequest + +PexRequest is an empty message requesting a list of peers. + +> EmptyRequest + +### PexResponse + +PexResponse is an list of net addresses provided to a peer to dial. + +| Name | Type | Description | Field Number | +|-------|------------------------------------|------------------------------------------|--------------| +| addresses | repeated [PexAddress](#pexaddress) | List of peer addresses available to dial | 1 | + +### PexAddress + +PexAddress provides needed information for a node to dial a peer. + +| Name | Type | Description | Field Number | +|------|--------|------------------|--------------| +| id | string | NodeID of a peer | 1 | +| ip | string | The IP of a node | 2 | +| port | port | Port of a peer | 3 | + + +### PexRequestV2 + +PexRequest is an empty message requesting a list of peers. + +> EmptyRequest + +### PexResponseV2 + +PexResponse is an list of net addresses provided to a peer to dial. + +| Name | Type | Description | Field Number | +|-------|------------------------------------|------------------------------------------|--------------| +| addresses | repeated [PexAddressV2](#pexresponsev2) | List of peer addresses available to dial | 1 | + +### PexAddressV2 + +PexAddress provides needed information for a node to dial a peer. + +| Name | Type | Description | Field Number | +|------|--------|------------------|--------------| +| url | string | See [golang url](https://golang.org/pkg/net/url/#URL) | 1 | + +### Message + +Message is a [`oneof` protobuf type](https://developers.google.com/protocol-buffers/docs/proto#oneof). The one of consists of two messages. + +| Name | Type | Description | Field Number | +|--------------|---------------------------|------------------------------------------------------|--------------| +| pex_request | [PexRequest](#pexrequest) | Empty request asking for a list of addresses to dial | 1 | +| pex_response | [PexResponse](#pexresponse)| List of addresses to dial | 2 | +| pex_request_v2| [PexRequestV2](#pexrequestv2)| Empty request asking for a list of addresses to dial| 3 | +| pex_response_v2| [PexRespinseV2](#pexresponsev2)| List of addresses to dial | 4 | diff --git a/spec/p2p/legacy-docs/messages/state-sync.md b/spec/p2p/legacy-docs/messages/state-sync.md new file mode 100644 index 0000000..8a7411e --- /dev/null +++ b/spec/p2p/legacy-docs/messages/state-sync.md @@ -0,0 +1,132 @@ +--- +order: 5 +--- + +# State Sync + +## Channels + +State sync has four distinct channels. The channel identifiers are listed below. + +| Name | Number | +|-------------------|--------| +| SnapshotChannel | 96 | +| ChunkChannel | 97 | +| LightBlockChannel | 98 | +| ParamsChannel | 99 | + +## Message Types + +### SnapshotRequest + +When a new node begin state syncing, it will ask all peers it encounters if it has any +available snapshots: + +| Name | Type | Description | Field Number | +|----------|--------|-------------|--------------| + +### SnapShotResponse + +The receiver will query the local ABCI application via `ListSnapshots`, and send a message +containing snapshot metadata (limited to 4 MB) for each of the 10 most recent snapshots: and stored at the application layer. When a peer is starting it will request snapshots. + +| Name | Type | Description | Field Number | +|----------|--------|-----------------------------------------------------------|--------------| +| height | uint64 | Height at which the snapshot was taken | 1 | +| format | uint32 | Format of the snapshot. | 2 | +| chunks | uint32 | How many chunks make up the snapshot | 3 | +| hash | bytes | Arbitrary snapshot hash | 4 | +| metadata | bytes | Arbitrary application data. **May be non-deterministic.** | 5 | + +### ChunkRequest + +The node running state sync will offer these snapshots to the local ABCI application via +`OfferSnapshot` ABCI calls, and keep track of which peers contain which snapshots. Once a snapshot +is accepted, the state syncer will request snapshot chunks from appropriate peers: + +| Name | Type | Description | Field Number | +|--------|--------|-------------------------------------------------------------|--------------| +| height | uint64 | Height at which the chunk was created | 1 | +| format | uint32 | Format chosen for the chunk. **May be non-deterministic.** | 2 | +| index | uint32 | Index of the chunk within the snapshot. | 3 | + +### ChunkResponse + +The receiver will load the requested chunk from its local application via `LoadSnapshotChunk`, +and respond with it (limited to 16 MB): + +| Name | Type | Description | Field Number | +|---------|--------|-------------------------------------------------------------|--------------| +| height | uint64 | Height at which the chunk was created | 1 | +| format | uint32 | Format chosen for the chunk. **May be non-deterministic.** | 2 | +| index | uint32 | Index of the chunk within the snapshot. | 3 | +| hash | bytes | Arbitrary snapshot hash | 4 | +| missing | bool | Arbitrary application data. **May be non-deterministic.** | 5 | + +Here, `Missing` is used to signify that the chunk was not found on the peer, since an empty +chunk is a valid (although unlikely) response. + +The returned chunk is given to the ABCI application via `ApplySnapshotChunk` until the snapshot +is restored. If a chunk response is not returned within some time, it will be re-requested, +possibly from a different peer. + +The ABCI application is able to request peer bans and chunk refetching as part of the ABCI protocol. + +### LightBlockRequest + +To verify state and to provide state relevant information for consensus, the node will ask peers for +light blocks at specified heights. + +| Name | Type | Description | Field Number | +|----------|--------|----------------------------|--------------| +| height | uint64 | Height of the light block | 1 | + +### LightBlockResponse + +The receiver will retrieve and construct the light block from both the block and state stores. The +receiver will verify the data by comparing the hashes and store the header, commit and validator set +if necessary. The light block at the height of the snapshot will be used to verify the `AppHash`. + +| Name | Type | Description | Field Number | +|---------------|---------------------------------------------------------|--------------------------------------|--------------| +| light_block | [LightBlock](../../../core/data_structures.md#lightblock) | Light block at the height requested | 1 | + +State sync will use [light client verification](../../../light-client/verification/README.md) to verify +the light blocks. + +If no state sync is in progress (i.e. during normal operation), any unsolicited response messages +are discarded. + +### ParamsRequest + +In order to build the state, the state provider will request the params at the height of the snapshot and use the header to verify it. + +| Name | Type | Description | Field Number | +|----------|--------|----------------------------|--------------| +| height | uint64 | Height of the consensus params | 1 | + + +### ParamsResponse + +A reciever to the request will use the state store to fetch the consensus params at that height and return it to the sender. + +| Name | Type | Description | Field Number | +|----------|--------|---------------------------------|--------------| +| height | uint64 | Height of the consensus params | 1 | +| consensus_params | [ConsensusParams](../../../core/data_structures.md#consensusparams) | Consensus params at the height requested | 2 | + + +### Message + +Message is a [`oneof` protobuf type](https://developers.google.com/protocol-buffers/docs/proto#oneof). The `oneof` consists of eight messages. + +| Name | Type | Description | Field Number | +|----------------------|--------------------------------------------|----------------------------------------------|--------------| +| snapshots_request | [SnapshotRequest](#snapshotrequest) | Request a recent snapshot from a peer | 1 | +| snapshots_response | [SnapshotResponse](#snapshotresponse) | Respond with the most recent snapshot stored | 2 | +| chunk_request | [ChunkRequest](#chunkrequest) | Request chunks of the snapshot. | 3 | +| chunk_response | [ChunkRequest](#chunkresponse) | Response of chunks used to recreate state. | 4 | +| light_block_request | [LightBlockRequest](#lightblockrequest) | Request a light block. | 5 | +| light_block_response | [LightBlockResponse](#lightblockresponse) | Respond with a light block | 6 | +| params_request | [ParamsRequest](#paramsrequest) | Request the consensus params at a height. | 7 | +| params_response | [ParamsResponse](#paramsresponse) | Respond with the consensus params | 8 | diff --git a/spec/p2p/legacy-docs/node.md b/spec/p2p/legacy-docs/node.md new file mode 100644 index 0000000..a6d6d53 --- /dev/null +++ b/spec/p2p/legacy-docs/node.md @@ -0,0 +1,69 @@ +--- +order: 1 +--- + +# Peer Discovery + +A CometBFT P2P network has different kinds of nodes with different requirements for connectivity to one another. +This document describes what kind of nodes CometBFT should enable and how they should work. + +## Seeds + +Seeds are the first point of contact for a new node. +They return a list of known active peers and then disconnect. + +Seeds should operate full nodes with the PEX reactor in a "crawler" mode +that continuously explores to validate the availability of peers. + +Seeds should only respond with some top percentile of the best peers it knows about. + +## New Full Node + +A new node needs a few things to connect to the network: + +- a list of seeds, which can be provided to CometBFT via config file or flags, + or hardcoded into the software by in-process apps +- a `ChainID`, also called `Network` at the p2p layer +- a recent block height, H, and hash, HASH for the blockchain. + +The values `H` and `HASH` must be received and corroborated by means external to CometBFT, and specific to the user - ie. via the user's trusted social consensus. +This requirement to validate `H` and `HASH` out-of-band and via social consensus +is the essential difference in security models between Proof-of-Work and Proof-of-Stake blockchains. + +With the above, the node then queries some seeds for peers for its chain, +dials those peers, and runs the CometBFT protocols with those it successfully connects to. + +When the peer catches up to height H, it ensures the block hash matches HASH. +If not, CometBFT will exit, and the user must try again - either they are connected +to bad peers or their social consensus is invalid. + +## Restarted Full Node + +A node checks its address book on startup and attempts to connect to peers from there. +If it can't connect to any peers after some time, it falls back to the seeds to find more. + +Restarted full nodes can run the `blockchain` or `consensus` reactor protocols to sync up +to the latest state of the blockchain from wherever they were last. +In a Proof-of-Stake context, if they are sufficiently far behind (greater than the length +of the unbonding period), they will need to validate a recent `H` and `HASH` out-of-band again +so they know they have synced the correct chain. + +## Validator Node + +A validator node is a node that interfaces with a validator signing key. +These nodes require the highest security, and should not accept incoming connections. +They should maintain outgoing connections to a controlled set of "Sentry Nodes" that serve +as their proxy shield to the rest of the network. + +Validators that know and trust each other can accept incoming connections from one another and maintain direct private connectivity via VPN. + +## Sentry Node + +Sentry nodes are guardians of a validator node and provide it access to the rest of the network. +They should be well connected to other full nodes on the network. +Sentry nodes may be dynamic, but should maintain persistent connections to some evolving random subset of each other. +They should always expect to have direct incoming connections from the validator node and its backup(s). +They do not report the validator node's address in the PEX and +they may be more strict about the quality of peers they keep. + +Sentry nodes belonging to validators that trust each other may wish to maintain persistent connections via VPN with one another, but only report each other sparingly in the PEX. diff --git a/spec/p2p/legacy-docs/peer.md b/spec/p2p/legacy-docs/peer.md new file mode 100644 index 0000000..d591ba9 --- /dev/null +++ b/spec/p2p/legacy-docs/peer.md @@ -0,0 +1,132 @@ +--- +order: 1 +--- + +# Peers + +This document explains how CometBFT Peers are identified and how they connect to one another. + +## Peer Identity + +CometBFT peers are expected to maintain long-term persistent identities in the form of a public key. +Each peer has an ID defined as `peer.ID == peer.PubKey.Address()`, where `Address` uses the scheme defined in `crypto` package. + +A single peer ID can have multiple IP addresses associated with it, but a node +will only ever connect to one at a time. + +When attempting to connect to a peer, we use the PeerURL: `@:`. +We will attempt to connect to the peer at IP:PORT, and verify, +via authenticated encryption, that it is in possession of the private key +corresponding to ``. This prevents man-in-the-middle attacks on the peer layer. + +## Connections + +All p2p connections use TCP. +Upon establishing a successful TCP connection with a peer, +two handshakes are performed: one for authenticated encryption, and one for CometBFT versioning. +Both handshakes have configurable timeouts (they should complete quickly). + +### Authenticated Encryption Handshake + +CometBFT implements the Station-to-Station protocol +using X25519 keys for Diffie-Helman key-exchange and chacha20poly1305 for encryption. + +Previous versions of this protocol (0.32 and below) suffered from malleability attacks whereas an active man +in the middle attacker could compromise confidentiality as described in [Prime, Order Please! +Revisiting Small Subgroup and Invalid Curve Attacks on +Protocols using Diffie-Hellman](https://eprint.iacr.org/2019/526.pdf). + +We have added dependency on the Merlin a keccak based transcript hashing protocol to ensure non-malleability. + +It goes as follows: + +- generate an ephemeral X25519 keypair +- send the ephemeral public key to the peer +- wait to receive the peer's ephemeral public key +- create a new Merlin Transcript with the string "TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH" +- Sort the ephemeral keys and add the high labeled "EPHEMERAL_UPPER_PUBLIC_KEY" and the low keys labeled "EPHEMERAL_LOWER_PUBLIC_KEY" to the Merlin transcript. +- compute the Diffie-Hellman shared secret using the peers ephemeral public key and our ephemeral private key +- add the DH secret to the transcript labeled DH_SECRET. +- generate two keys to use for encryption (sending and receiving) and a challenge for authentication as follows: + - create a hkdf-sha256 instance with the key being the diffie hellman shared secret, and info parameter as + `TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN` + - get 64 bytes of output from hkdf-sha256 + - if we had the smaller ephemeral pubkey, use the first 32 bytes for the key for receiving, the second 32 bytes for sending; else the opposite. +- use a separate nonce for receiving and sending. Both nonces start at 0, and should support the full 96 bit nonce range +- all communications from now on are encrypted in 1400 byte frames (plus encoding overhead), + using the respective secret and nonce. Each nonce is incremented by one after each use. +- we now have an encrypted channel, but still need to authenticate +- extract a 32 bytes challenge from merlin transcript with the label "SECRET_CONNECTION_MAC" +- sign the common challenge obtained from the hkdf with our persistent private key +- send the amino encoded persistent pubkey and signature to the peer +- wait to receive the persistent public key and signature from the peer +- verify the signature on the challenge using the peer's persistent public key + +If this is an outgoing connection (we dialed the peer) and we used a peer ID, +then finally verify that the peer's persistent public key corresponds to the peer ID we dialed, +ie. `peer.PubKey.Address() == `. + +The connection has now been authenticated. All traffic is encrypted. + +Note: only the dialer can authenticate the identity of the peer, +but this is what we care about since when we join the network we wish to +ensure we have reached the intended peer (and are not being MITMd). + +### Peer Filter + +Before continuing, we check if the new peer has the same ID as ourselves or +an existing peer. If so, we disconnect. + +We also check the peer's address and public key against +an optional whitelist which can be managed through the ABCI app - +if the whitelist is enabled and the peer does not qualify, the connection is +terminated. + +### CometBFT Version Handshake + +The CometBFT Version Handshake allows the peers to exchange their NodeInfo: + +```golang +type NodeInfo struct { + Version p2p.Version + ID p2p.ID + ListenAddr string + + Network string + SoftwareVersion string + Channels []int8 + + Moniker string + Other NodeInfoOther +} + +type Version struct { + P2P uint64 + Block uint64 + App uint64 +} + +type NodeInfoOther struct { + TxIndex string + RPCAddress string +} +``` + +The connection is disconnected if: + +- `peer.NodeInfo.ID` is not equal `peerConn.ID` +- `peer.NodeInfo.Version.Block` does not match ours +- `peer.NodeInfo.Network` is not the same as ours +- `peer.Channels` does not intersect with our known Channels. +- `peer.NodeInfo.ListenAddr` is malformed or is a DNS host that cannot be + resolved + +At this point, if we have not disconnected, the peer is valid. +It is added to the switch and hence all reactors via the `AddPeer` method. +Note that each reactor may handle multiple channels. + +## Connection Activity + +Once a peer is added, incoming messages for a given reactor are handled through +that reactor's `Receive` method, and output messages are sent directly by the Reactors +on each peer. A typical reactor maintains per-peer go-routine(s) that handle this. diff --git a/spec/p2p/reactor-api/README.md b/spec/p2p/reactor-api/README.md new file mode 100644 index 0000000..5c9071c --- /dev/null +++ b/spec/p2p/reactor-api/README.md @@ -0,0 +1,47 @@ +--- +order: 1 +--- + +# Reactors + +Reactor is the generic name for a component that employs the p2p communication layer. + +This section documents the interaction of the p2p communication layer with the +reactors. +The diagram below summarizes this interaction, namely the **northbound interface** +of the p2p communication layer, representing some relevant event flows: + + + +Each of the protocols running a CometBFT node implements a reactor and registers +the implementation with the p2p layer. +The p2p layer provides network events to the registered reactors, the main +two being new connections with peers and received messages. +The reactors provide to the p2p layer messages to be sent to +peers and commands to control the operation of the p2p layer. + +It is worth noting that the components depicted in the diagram below run +multiple routines and that the illustrated actions happen in parallel. +For instance, the connection establishment routines run in parallel, invoking +the depicted `AddPeer` method concurrently. +Once a connection is fully established, each `Peer` instance runs a send and a +receive routines. +The send routine collects messages from multiple reactors to a peer, packaging +then into raw messages which are transmitted to the peer. +The receive routine processes incoming messages and forwards them to the +destination reactors, invoking the depicted `Receive` methods. +In addition, the reactors run multiple routines for interacting +with the peers (for example, to send messages to them) or with the `Switch`. + +The remaining of the documentation is organized as follows: + +- [Reactor API](./reactor.md): documents the [`p2p.Reactor`][reactor-interface] + interface and specifies the behaviour of the p2p layer when interacting with + a reactor. + In other words, the interaction of the p2p layer with the protocol layer (bottom-up). + +- [P2P API](./p2p-api.md): documents the interface provided by the p2p + layer to the reactors, through the `Switch` and `Peer` abstractions. + In other words, the interaction of the protocol layer with the p2p layer (top-down). + +[reactor-interface]: https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/base_reactor.go diff --git a/spec/p2p/reactor-api/p2p-api.md b/spec/p2p/reactor-api/p2p-api.md new file mode 100644 index 0000000..3b15ab3 --- /dev/null +++ b/spec/p2p/reactor-api/p2p-api.md @@ -0,0 +1,315 @@ +--- +order: 3 +--- + +# API for Reactors + +This document describes the API provided by the p2p layer to the protocol +layer, namely to the registered reactors. + +This API consists of two interfaces: the one provided by the `Switch` instance, +and the ones provided by multiple `Peer` instances, one per connected peer. +The `Switch` instance is provided to every reactor as part of the reactor's +[registration procedure][reactor-registration]. +The multiple `Peer` instances are provided to every registered reactor whenever +a [new connection with a peer][reactor-addpeer] is established. + +> **Note** +> +> The practical reasons that lead to the interface to be provided in two parts, +> `Switch` and `Peer` instances are discussed in more datail in the +> [knowledge-base repository](https://github.com/cometbft/knowledge-base/blob/main/p2p/reactors/switch-peer.md). + +## `Switch` API + +The [`Switch`][switch-type] is the central component of the p2p layer +implementation. It manages all the reactors running in a node and keeps track +of the connections with peers. +The table below summarizes the interaction of the standard reactors with the `Switch`: + +| `Switch` API method | consensus | block sync | state sync | mempool | evidence | PEX | +|--------------------------------------------|-----------|------------|------------|---------|-----------|-------| +| `Peers() IPeerSet` | x | x | | | | x | +| `NumPeers() (int, int, int)` | | x | | | | x | +| `Broadcast(Envelope) chan bool` | x | x | x | | | | +| `MarkPeerAsGood(Peer)` | x | | | | | | +| `StopPeerForError(Peer, interface{})` | x | x | x | x | x | x | +| `StopPeerGracefully(Peer)` | | | | | | x | +| `Reactor(string) Reactor` | | x | | | | | + +The above list is not exhaustive as it does not include all the `Switch` methods +invoked by the PEX reactor, a special component that should be considered part +of the p2p layer. This document does not cover the operation of the PEX reactor +as a connection manager. + +### Peers State + +The first two methods in the switch API allow reactors to query the state of +the p2p layer: the set of connected peers. + + func (sw *Switch) Peers() IPeerSet + +The `Peers()` method returns the current set of connected peers. +The returned `IPeerSet` is an immutable concurrency-safe copy of this set. +Observe that the `Peer` handlers returned by this method were previously +[added to the reactor][reactor-addpeer] via the `InitPeer(Peer)` method, +but not yet removed via the `RemovePeer(Peer)` method. +Thus, a priori, reactors should already have this information. + + func (sw *Switch) NumPeers() (outbound, inbound, dialing int) + +The `NumPeers()` method returns the current number of connected peers, +distinguished between `outbound` and `inbound` peers. +An `outbound` peer is a peer the node has dialed to, while an `inbound` peer is +a peer the node has accepted a connection from. +The third field `dialing` reports the number of peers to which the node is +currently attempting to connect, so not (yet) connected peers. + +> **Note** +> +> The third field returned by `NumPeers()`, the number of peers in `dialing` +> state, is not an information that should regard the protocol layer. +> In fact, with the exception of the PEX reactor, which can be considered part +> of the p2p layer implementation, no standard reactor actually uses this +> information, that could be removed when this interface is refactored. + +### Broadcast + +The switch provides, mostly for historical or retro-compatibility reasons, +a method for sending a message to all connected peers: + + func (sw *Switch) Broadcast(e Envelope) chan bool + +The `Broadcast()` method is not blocking and returns a channel of booleans. +For every connected `Peer`, it starts a background thread for sending the +message to that peer, using the `Peer.Send()` method +(which is blocking, as detailed in [Send Methods](#send-methods)). +The result of each unicast send operation (success or failure) is added to the +returned channel, which is closed when all operations are completed. + +> **Note** +> +> - The current _implementation_ of the `Switch.Broadcast(Envelope)` method is +> not efficient, as the marshalling of the provided message is performed as +> part of the `Peer.Send(Envelope)` helper method, that is, once per +> connected peer. +> - The return value of the broadcast method is not considered by any of the +> standard reactors that employ the method. One of the reasons is that is is +> not possible to associate each of the boolean outputs added to the +> returned channel to a peer. + +### Vetting Peers + +The p2p layer relies on the registered reactors to gauge the _quality_ of peers. +The following method can be invoked by a reactor to inform the p2p layer that a +peer has presented a "good" behaviour. +This information is registered in the node's address book and influences the +operation of the Peer Exchange (PEX) protocol, as node discovery adopts a bias +towards "good" peers: + + func (sw *Switch) MarkPeerAsGood(peer Peer) + +At the moment, it is up to the consensus reactor to vet a peer. +In the current logic, a peer is marked as good whenever the consensus protocol +collects a multiple of `votesToContributeToBecomeGoodPeer = 10000` useful votes +or `blocksToContributeToBecomeGoodPeer = 10000` useful block parts from that peer. +By "useful", the consensus implementation considers messages that are valid and +that are received by the node when the node is expected for such information, +which excludes duplicated or late received messages. + +> **Note** +> +> The switch doesn't currently provide a method to mark a peer as a bad peer. +> In fact, the peer quality management is really implemented in the current +> version of the p2p layer. +> This topic is being discussed in the [knowledge-base repository](https://github.com/cometbft/knowledge-base/blob/main/p2p/reactors/peer-quality.md). + +### Stopping Peers + +Reactors can instruct the p2p layer to disconnect from a peer. +Using the p2p layer's nomenclature, the reactor requests a peer to be stopped. +The peer's send and receive routines are in fact stopped, interrupting the +communication with the peer. +The `Peer` is then [removed from every registered reactor][reactor-removepeer], +using the `RemovePeer(Peer)` method, and from the set of connected peers. + + func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) + +All the standard reactors employ the above method for disconnecting from a peer +in case of errors. +These are errors that occur when processing a message received from a `Peer`. +The produced `error` is provided to the method as the `reason`. + +The `StopPeerForError()` method has an important *caveat*: if the peer to be +stopped is configured as a _persistent peer_, the switch will attempt +reconnecting to that same peer. +While this behaviour makes sense when the method is invoked by other components +of the p2p layer (e.g., in the case of communication errors), it does not make +sense when it is invoked by a reactor. + +> **Note** +> +> A more comprehensive discussion regarding this topic can be found on the +> [knowledge-base repository](https://github.com/cometbft/knowledge-base/blob/main/p2p/reactors/stop-peer.md). + + func (sw *Switch) StopPeerGracefully(peer Peer) + +The second method instructs the switch to disconnect from a peer for no +particular reason. +This method is only adopted by the PEX reactor of a node operating in _seed mode_, +as seed nodes disconnect from a peer after exchanging peer addresses with it. + +### Reactors Table + +The switch keeps track of all registered reactors, indexed by unique reactor names. +A reactor can therefore use the switch to access another `Reactor` from its `name`: + + func (sw *Switch) Reactor(name string) Reactor + +This method is currently only used by the Block Sync reactor to access the +Consensus reactor implementation, from which it uses the exported +`SwitchToConsensus()` method. +While available, this inter-reactor interaction approach is discouraged and +should be avoided, as it violates the assumption that reactors are independent. + + +## `Peer` API + +The [`Peer`][peer-interface] interface represents a connected peer. +A `Peer` instance encapsulates a multiplex connection that implements the +actual communication (sending and receiving messages) with a peer. +When a connection is established with a peer, the `Switch` provides the +corresponding `Peer` instance to all registered reactors. +From this point, reactors can use the methods of the new `Peer` instance. + +The table below summarizes the interaction of the standard reactors with +connected peers, with the `Peer` methods used by them: + +| `Peer` API method | consensus | block sync | state sync | mempool | evidence | PEX | +|--------------------------------------------|-----------|------------|------------|---------|-----------|-------| +| `ID() ID` | x | x | x | x | x | x | +| `IsRunning() bool` | x | | | x | x | | +| `Quit() <-chan struct{}` | | | | x | x | | +| `Get(string) interface{}` | x | | | x | x | | +| `Set(string, interface{})` | x | | | | | | +| `Send(Envelope) bool` | x | x | x | x | x | x | +| `TrySend(Envelope) bool` | x | x | | | | | + +The above list is not exhaustive as it does not include all the `Peer` methods +invoked by the PEX reactor, a special component that should be considered part +of the p2p layer. This document does not cover the operation of the PEX reactor +as a connection manager. + +### Identification + +Nodes in the p2p network are configured with a unique cryptographic key pair. +The public part of this key pair is verified when establishing a connection +with the peer, as part of the authentication handshake, and constitutes the +peer's `ID`: + + func (p Peer) ID() p2p.ID + +Observe that each time the node connects to a peer (e.g., after disconnecting +from it), a new (distinct) `Peer` handler is provided to the reactors via +`InitPeer(Peer)` method. +In fact, the `Peer` handler is associated to a _connection_ with a peer, not to +the actual _node_ in the network. +To keep track of actual peers, the unique peer `p2p.ID` provided by the above +method should be employed. + +### Peer state + +The switch starts the peer's send and receive routines before adding the peer +to every registered reactor using the `AddPeer(Peer)` method. +The reactors then usually start routines to interact with the new connected +peer using the received `Peer` handler. +For these routines it is useful to check whether the peer is still connected +and its send and receive routines are still running: + + func (p Peer) IsRunning() bool + func (p Peer) Quit() <-chan struct{} + +The above two methods provide the same information about the state of a `Peer` +instance in two different ways. +Both of them are defined in the [`Service`][service-interface] interface. +The `IsRunning()` method is synchronous and returns whether the peer has been +started and has not been stopped. +The `Quit()` method returns a channel that is closed when the peer is stopped; +it is an asynchronous state query. + +### Key-value store + +Each `Peer` instance provides a synchronized key-value store that allows +sharing peer-specific state between reactors: + + + func (p Peer) Get(key string) interface{} + func (p Peer) Set(key string, data interface{}) + +This key-value store can be seen as an asynchronous mechanism to exchange the +state of a peer between reactors. +In the current use-case of this mechanism, the Consensus reactor populates the +key-value store with a `PeerState` instance for each connected peer. +The Consensus reactor routines interacting with a peer read and update the +shared peer state. +The Evidence and Mempool reactors, in their turn, periodically query the +key-value store of each peer for retrieving, in particular, the last height +reported by the peer. +This information, produced by the Consensus reactor, influences the interaction +of these two reactors with their peers. + +> **Note** +> +> More details of how this key-value store is used to share state between reactors can be found on the +> [knowledge-base repository](https://github.com/cometbft/knowledge-base/blob/main/p2p/reactors/peer-kvstore.md). + +### Send methods + +Finally, a `Peer` instance allows a reactor to send messages to companion +reactors running at that peer. +This is ultimately the goal of the switch when it provides `Peer` instances to +the registered reactors. +There are two methods for sending messages: + + func (p Peer) Send(e Envelope) bool + func (p Peer) TrySend(e Envelope) bool + +The two message-sending methods receive an `Envelope`, whose content should be +set as follows: + +- `ChannelID`: the channel the message should be sent through, which defines + the reactor that will process the message; +- `Src`: this field represents the source of an incoming message, which is + irrelevant for outgoing messages; +- `Message`: the actual message's payload, which is marshalled using protocol buffers. + +The two message-sending methods attempt to add the message (`e.Payload`) to the +send queue of the peer's destination channel (`e.ChannelID`). +There is a send queue for each registered channel supported by the peer, and +each send queue has a capacity. +The capacity of the send queues for each channel are [configured][reactor-channels] +by reactors via the corresponding `ChannelDescriptor`. + +The two message-sending methods return whether it was possible to enqueue +the marshalled message to the channel's send queue. +The most common reason for these methods to return `false` is the channel's +send queue being full. +Further reasons for returning `false` are: the peer being stopped, providing a +non-registered channel ID, or errors when marshalling the message's payload. + +The difference between the two message-sending methods is _when_ they return `false`. +The `Send()` method is a _blocking_ method, it returns `false` if the message +could not be enqueued, because the channel's send queue is still full, after a +10-second _timeout_. +The `TrySend()` method is a _non-blocking_ method, it _immediately_ returns +`false` when the channel's send queue is full. + +[peer-interface]: https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/peer.go +[service-interface]: https://github.com/cometbft/cometbft/blob/v0.38.x/libs/service/service.go +[switch-type]: https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/switch.go + +[reactor-interface]: https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/base_reactor.go +[reactor-registration]: ./reactor.md#registration +[reactor-channels]: ./reactor.md#registration +[reactor-addpeer]: ./reactor.md#peer-management +[reactor-removepeer]: ./reactor.md#stop-peer diff --git a/spec/p2p/reactor-api/reactor.md b/spec/p2p/reactor-api/reactor.md new file mode 100644 index 0000000..388ff02 --- /dev/null +++ b/spec/p2p/reactor-api/reactor.md @@ -0,0 +1,234 @@ +--- +order: 2 +--- + +# Reactor API + +A component has to implement the [`p2p.Reactor` interface][reactor-interface] +in order to use communication services provided by the p2p layer. +This interface is currently the main source of documentation for a reactor. + +The goal of this document is to specify the behaviour of the p2p communication +layer when interacting with a reactor. +So while the [`Reactor interface`][reactor-interface] declares the methods +invoked and determines what the p2p layer expects from a reactor, +this documentation focuses on the **temporal behaviour** that a reactor implementation +should expect from the p2p layer. (That is, in which orders the functions may be called) + +This specification is accompanied by the [`reactor.qnt`](./reactor.qnt) file, +a more comprehensive model of the reactor's operation written in +[Quint][quint-repo], an executable specification language. +The methods declared in the [`Reactor`][reactor-interface] interface are +modeled in Quint, in the form of `pure def` methods, providing some examples of +how they should be implemented. +The behaviour of the p2p layer when interacting with a reactor, by invoking the +interface methods, is modeled in the form of state transitions, or `action`s in +the Quint nomenclature. + +## Overview + +The following _grammar_ is a simplified representation of the expected sequence of calls +from the p2p layer to a reactor. +Note that the grammar represents events referring to a _single reactor_, while +the p2p layer supports the execution of multiple reactors. +For a more detailed representation of the sequence of calls from the p2p layer +to reactors, please refer to the companion Quint model. + +While useful to provide an overview of the operation of a reactor, +grammars have some limitations in terms of the behaviour they can express. +For instance, the following grammar only represents the management of _a single peer_, +namely of a peer with a given ID which can connect, disconnect, and reconnect +multiple times to the node. +The p2p layer and every reactor should be able to handle multiple distinct peers in parallel. +This means that multiple occurrences of non-terminal `peer-management` of the +grammar below can "run" independently and in parallel, each one referring and +producing events associated to a different peer: + +```abnf +start = registration on-start *peer-management on-stop +registration = get-channels set-switch + +; Refers to a single peer, a reactor must support multiple concurrent peers +peer-management = init-peer start-peer stop-peer +start-peer = [*receive] (connected-peer / start-error) +connected-peer = add-peer *receive +stop-peer = [peer-error] remove-peer + +; Service interface +on-start = %s"OnStart()" +on-stop = %s"OnStop()" +; Reactor interface +get-channels = %s"GetChannels()" +set-switch = %s"SetSwitch(*Switch)" +init-peer = %s"InitPeer(Peer)" +add-peer = %s"AddPeer(Peer)" +remove-peer = %s"RemovePeer(Peer, reason)" +receive = %s"Receive(Envelope)" + +; Errors, for reference +start-error = %s"log(Error starting peer)" +peer-error = %s"log(Stopping peer for error)" +``` + +The grammar is written in case-sensitive Augmented Backus–Naur form (ABNF, +specified in [IETF RFC 7405](https://datatracker.ietf.org/doc/html/rfc7405)). +It is inspired on the grammar produced to specify the interaction of CometBFT +with an ABCI++ application, available [here](../../abci/abci%2B%2B_comet_expected_behavior.md). + +## Registration + +To become a reactor, a component has first to implement the +[`Reactor`][reactor-interface] interface, +then to register the implementation with the p2p layer, using the +`Switch.AddReactor(name string, reactor Reactor)` method, +with a global unique `name` for the reactor. + +The registration must happen before the node, in general, and the p2p layer, +in particular, are started. +In other words, there is no support for registering a reactor on a running node: +reactors must be registered as part of the setup of a node. + +```abnf +registration = get-channels set-switch +``` + +The p2p layer retrieves from the reactor a list of channels the reactor is +responsible for, using the `GetChannels()` method. +The reactor implementation should thereafter expect the delivery of every +message received by the p2p layer in the informed channels. + +The second method `SetSwitch(Switch)` concludes the handshake between the +reactor and the p2p layer. +The `Switch` is the main component of the p2p layer, being responsible for +establishing connections with peers and routing messages. +The `Switch` instance provides a number of methods for all registered reactors, +documented in the companion [API for Reactors](./p2p-api.md#switch-api) document. + +## Service interface + +A reactor must implement the [`Service`](https://github.com/cometbft/cometbft/blob/v0.38.x/libs/service/service.go) interface, +in particular, a startup `OnStart()` and a shutdown `OnStop()` methods: + +```abnf +start = registration on-start *peer-management on-stop +``` + +As part of the startup of a node, all registered reactors are started by the p2p layer. +And when the node is shut down, all registered reactors are stopped by the p2p layer. +Observe that the `Service` interface specification establishes that a service +can be started and stopped only once. +So before being started or once stopped by the p2p layer, the reactor should +not expect any interaction. + +## Peer management + +The core of a reactor's operation is the interaction with peers or, more +precisely, with companion reactors operating on the same channels in peers connected to the node. +The grammar extract below represents the interaction of the reactor with a +single peer: + +```abnf +; Refers to a single peer, a reactor must support multiple concurrent peers +peer-management = init-peer start-peer stop-peer +``` + +The p2p layer informs all registered reactors when it establishes a connection +with a `Peer`, using the `InitPeer(Peer)` method. +When this method is invoked, the `Peer` has not yet been started, namely the +routines for sending messages to and receiving messages from the peer are not running. +This method should be used to initialize state or data related to the new +peer, but not to interact with it. + +The next step is to start the communication routines with the new `Peer`. +As detailed in the following, this procedure may or may not succeed. +In any case, the peer is eventually stopped, which concludes the management of +that `Peer` instance. + +## Start peer + +Once `InitPeer(Peer)` is invoked for every registered reactor, the p2p layer starts the peer's +communication routines and adds the `Peer` to the set of connected peers. +If both steps are concluded without errors, the reactor's `AddPeer(Peer)` is invoked: + +```abnf +start-peer = [*receive] (connected-peer / start-error) +connected-peer = add-peer *receive +``` + +In case of errors, a message is logged informing that the p2p layer failed to start the peer. +This is not a common scenario and it is only expected to happen when +interacting with a misbehaving or slow peer. A practical example is reported on this +[issue](https://github.com/tendermint/tendermint/pull/9500). + +It is up to the reactor to define how to process the `AddPeer(Peer)` event. +The typical behavior is to start routines that, given some conditions or events, +send messages to the added peer, using the provided `Peer` instance. +The companion [API for Reactors](./p2p-api.md#peer-api) documents the methods +provided by `Peer` instances, available from when they are added to the reactors. + +## Stop Peer + +The p2p layer informs all registered reactors when it disconnects from a `Peer`, +using the `RemovePeer(Peer, reason)` method: + +```abnf +stop-peer = [peer-error] remove-peer +``` + +This method is invoked after the p2p layer has stopped peer's send and receive routines. +Depending of the `reason` for which the peer was stopped, different log +messages can be produced. +After removing a peer from all reactors, the `Peer` instance is also removed from +the set of connected peers. +This enables the same peer to reconnect and `InitPeer(Peer)` to be invoked for +the new connection. + +From the removal of a `Peer` , the reactor should not receive any further message +from the peer and must not try sending messages to the removed peer. +This usually means stopping the routines that were started by the companion +`Add(Peer)` method. + +## Receive messages + +The main duty of a reactor is to handle incoming messages on the channels it +has registered with the p2p layer. + +The _pre-condition_ for receiving a message from a `Peer` is that the p2p layer +has previously invoked `InitPeer(Peer)`. +This means that the reactor must be able to receive a message from a `Peer` +_before_ `AddPeer(Peer)` is invoked. +This happens because the peer's send and receive routines are started before, +and should be already running when the p2p layer adds the peer to every +registered reactor. + +```abnf +start-peer = [*receive] (connected-peer / start-error) +connected-peer = add-peer *receive +``` + +The most common scenario, however, is to start receiving messages from a peer +after `AddPeer(Peer)` is invoked. +An arbitrary number of messages can be received, until the peer is stopped and +`RemovePeer(Peer)` is invoked. + +When a message is received from a connected peer on any of the channels +registered by the reactor, the p2p layer will deliver the message to the +reactor via the `Receive(Envelope)` method. +The message is packed into an `Envelope` that contains: + +- `ChannelID`: the channel the message belongs to +- `Src`: the source `Peer` handler, from which the message was received +- `Message`: the actual message's payload, unmarshalled using protocol buffers + +Two important observations regarding the implementation of the `Receive` method: + +1. Concurrency: the implementation should consider concurrent invocations of + the `Receive` method carrying messages from different peers, as the + interaction with different peers is independent and messages can be received in parallel. +1. Non-blocking: the implementation of the `Receive` method is expected not to block, + as it is invoked directly by the receive routines. + In other words, while `Receive` does not return, other messages from the + same sender are not delivered to any reactor. + +[reactor-interface]: https://github.com/cometbft/cometbft/blob/v0.38.x/p2p/base_reactor.go +[quint-repo]: https://github.com/informalsystems/quint diff --git a/spec/p2p/reactor-api/reactor.qnt b/spec/p2p/reactor-api/reactor.qnt new file mode 100644 index 0000000..b09e7e5 --- /dev/null +++ b/spec/p2p/reactor-api/reactor.qnt @@ -0,0 +1,276 @@ +// -*- mode: Bluespec; -*- +/* + * Reactor is responsible for handling incoming messages on one or more + * Channel. Switch calls GetChannels when reactor is added to it. When a new + * peer joins our node, InitPeer and AddPeer are called. RemovePeer is called + * when the peer is stopped. Receive is called when a message is received on a + * channel associated with this reactor. + */ +// Code: https://github.com/cometbft/cometbft/blob/main/p2p/base_reactor.go +module reactor { + + // Unique ID of a node. + type NodeID = str + + /* + * Peer is an interface representing a peer connected on a reactor. + */ + type Peer = { + ID: NodeID, + + // Other fields can be added to represent the p2p operation. + } + + // Byte ID used by channels, must be globally unique. + type Byte = str + + // Channel configuration. + type ChannelDescriptor = { + ID: Byte, + Priority: int, + } + + /* + * Envelope contains a message with sender routing info. + */ + type Envelope = { + Src: Peer, // Sender + Message: str, // Payload + ChannelID: Byte, + } + + // A Routine is used to interact with an active Peer. + type Routine = { + name: str, + peer: Peer, + } + + type ReactorState = { + // Peers that have been initialized but not yet removed. + // The reactor should expect receiving messages from them. + peers: Set[NodeID], + + // The reactor runs multiple routines. + routines: Set[Routine], + + // Values: init -> registered -> running -> stopped + state: str, + + // Name with which the reactor was registered. + name: str, + + // Channels the reactor is responsible for. + channels: Set[ChannelDescriptor], + } + + // Produces a new, uninitialized reactor. + pure def NewReactor(): ReactorState = { + { + peers: Set(), + routines: Set(), + state: "init", + name: "", + channels: Set(), + } + } + + // Pure definitions below represent the `p2p.Reactor` interface methods: + + /* + * GetChannels returns the list of MConnection.ChannelDescriptor. Make sure + * that each ID is unique across all the reactors added to the switch. + */ + pure def GetChannels(s: ReactorState): Set[ChannelDescriptor] = { + s.channels // Static list, configured at initialization. + } + + /* + * SetSwitch allows setting a switch. + */ + pure def SetSwitch(s: ReactorState, switch: bool): ReactorState = { + s.with("state", "registered") + } + + /* + * Start the service. + * If it's already started or stopped, will return an error. + */ + pure def OnStart(s: ReactorState): ReactorState = { + // Startup procedures should come here. + s.with("state", "running") + } + + /* + * Stop the service. + * If it's already stopped, will return an error. + */ + pure def OnStop(s: ReactorState): ReactorState = { + // Shutdown procedures should come here. + s.with("state", "stopped") + } + + /* + * InitPeer is called by the switch before the peer is started. Use it to + * initialize data for the peer (e.g. peer state). + */ + pure def InitPeer(s: ReactorState, peer: Peer): (ReactorState, Peer) = { + // This method can update the received peer, which is returned. + val updatedPeer = peer + (s.with("peers", s.peers.union(Set(peer.ID))), updatedPeer) + } + + /* + * AddPeer is called by the switch after the peer is added and successfully + * started. Use it to start goroutines communicating with the peer. + */ + pure def AddPeer(s: ReactorState, peer: Peer): ReactorState = { + // This method can be used to start routines to handle the peer. + // Below an example of an arbitrary 'ioRoutine' routine. + val startedRoutines = Set( {name: "ioRoutine", peer: peer} ) + s.with("routines", s.routines.union(startedRoutines)) + } + + /* + * RemovePeer is called by the switch when the peer is stopped (due to error + * or other reason). + */ + pure def RemovePeer(s: ReactorState, peer: Peer, reason: str): ReactorState = { + // This method should stop routines created by `AddPeer(Peer)`. + val stoppedRoutines = s.routines.filter(r => r.peer.ID == peer.ID) + s.with("peers", s.peers.exclude(Set(peer.ID))) + .with("routines", s.routines.exclude(stoppedRoutines)) + } + + /* + * Receive is called by the switch when an envelope is received from any connected + * peer on any of the channels registered by the reactor. + */ + pure def Receive(s: ReactorState, e: Envelope): ReactorState = { + // This method should process the message payload: e.Message. + s + } + + // Global state + + // Reactors are uniquely identified by their names. + var reactors: str -> ReactorState + + // Reactor (name) assigned to each channel ID. + var reactorsByCh: Byte -> str + + // Helper action to (only) update the state of a given reactor. + action updateReactorTo(reactor: ReactorState): bool = all { + reactors' = reactors.set(reactor.name, reactor), + reactorsByCh' = reactorsByCh + } + + // State transitions performed by the p2p layer, invoking `p2p.Reactor` methods: + + // Code: Switch.AddReactor(name string, reactor Reactor) + action register(name: str, reactor: ReactorState): bool = all { + reactor.state == "init", + // Assign the reactor as responsible for its channel IDs, which + // should not be already assigned to another reactor. + val chIDs = reactor.GetChannels().map(c => c.ID) + all { + size(chIDs.intersect(reactorsByCh.keys())) == 0, + reactorsByCh' = reactorsByCh.keys().union(chIDs). + mapBy(id => if (id.in(chIDs)) name + else reactorsByCh.get(id)), + }, + // Register the reactor by its name, which must be unique. + not(name.in(reactors.keys())), + reactors' = reactors.put(name, + reactor.SetSwitch(true).with("name", name)) + } + + // Code: Switch.OnStart() + action start(reactor: ReactorState): bool = all { + reactor.state == "registered", + updateReactorTo(reactor.OnStart()) + } + + // Code: Switch.addPeer(p Peer): preamble + action initPeer(reactor: ReactorState, peer: Peer): bool = all { + reactor.state == "running", + not(peer.ID.in(reactor.peers)), + updateReactorTo(reactor.InitPeer(peer)._1) + } + + // Code: Switch.addPeer(p Peer): conclusion + action addPeer(reactor: ReactorState, peer: Peer): bool = all { + reactor.state == "running", + peer.ID.in(reactor.peers), // InitPeer(peer) and not RemovePeer(peer) + reactor.routines.filter(r => r.peer.ID == peer.ID).size() == 0, + updateReactorTo(reactor.AddPeer(peer)) + } + + // Code: Switch.stopAndRemovePeer(peer Peer, reason interface{}) + action removePeer(reactor: ReactorState, peer: Peer, reason: str): bool = all { + reactor.state == "running", + peer.ID.in(reactor.peers), // InitPeer(peer) and not RemovePeer(peer) + // Routines might not be started, namely: not AddPeer(peer) + // Routines could also be already stopped if Peer has erroed. + updateReactorTo(reactor.RemovePeer(peer, reason)) + } + + // Code: Peer type, onReceive := func(chID byte, msgBytes []byte) + action receive(reactor: ReactorState, e: Envelope): bool = all { + reactor.state == "running", + // The message's sender is an active peer + e.Src.ID.in(reactor.peers), + // Reactor is assigned to the message's channel ID + e.ChannelID.in(reactorsByCh.keys()), + reactorsByCh.get(e.ChannelID) == reactor.name, + reactor.GetChannels().exists(c => c.ID == e.ChannelID), + updateReactorTo(reactor.Receive(e)) + } + + // Code: Switch.OnStop() + action stop(reactor: ReactorState): bool = all { + reactor.state == "running", + // Either no peer was added or all peers were removed + reactor.peers.size() == 0, + updateReactorTo(reactor.OnStop()) + } + + // Simulation support + + action init = all { + reactors' = Map(), + reactorsByCh' = Map(), + } + + // Modelled reactor configuration + pure val reactorName = "myReactor" + pure val reactorChannels = Set({ID: "3", Priority: 1}, {ID: "7", Priority: 2}) + + // For retro-compatibility: the state of the modelled reactor + def state(): ReactorState = { + reactors.get(reactorName) + } + + pure val samplePeers = Set({ID: "p1"}, {ID: "p3"}) + pure val sampleChIDs = Set("1", "3", "7") // ChannelID 1 not registered + pure val sampleMsgs = Set("ping", "pong") + + action step = any { + register(reactorName, NewReactor.with("channels", reactorChannels)), + val reactor = reactors.get(reactorName) + any { + reactor.start(), + reactor.stop(), + nondet peer = oneOf(samplePeers) + any { + // Peer-specific actions + reactor.initPeer(peer), + reactor.addPeer(peer), + reactor.removePeer(peer, "no reason"), + reactor.receive({Src: peer, + ChannelID: oneOf(sampleChIDs), + Message: oneOf(sampleMsgs)}), + } + } + } + +} diff --git a/spec/rpc/README.md b/spec/rpc/README.md new file mode 100644 index 0000000..a8ce41e --- /dev/null +++ b/spec/rpc/README.md @@ -0,0 +1,1264 @@ +--- +order: 1 +parent: + title: RPC + order: 6 +--- + +# RPC spec + +This file defines the JSON-RPC spec of CometBFT. This is meant to be implemented by all clients. + +## Support + + | | [CometBFT](https://github.com/cometbft/cometbft/) | [Tendermint-Rs](https://github.com/informalsystems/tendermint-rs) | + |--------------|:----------------------------------------------------------:|:----------------------------------------------------------------:| + | JSON-RPC 2.0 | ✅ | ✅ | + | HTTP | ✅ | ✅ | + | HTTPS | ✅ | ❌ | + | WS | ✅ | ✅ | + + | Routes | [CometBFT](https://github.com/cometbft/cometbft/) | [Tendermint-Rs](https://github.com/informalsystems/tendermint-rs) | + |-----------------------------------------|:----------------------------------------------------------:|:-----------------------------------------------------------------:| + | [Health](#health) | ✅ | ✅ | + | [Status](#status) | ✅ | ✅ | + | [NetInfo](#netinfo) | ✅ | ✅ | + | [Blockchain](#blockchain) | ✅ | ✅ | + | [Block](#block) | ✅ | ✅ | + | [BlockByHash](#blockbyhash) | ✅ | ❌ | + | [BlockResults](#blockresults) | ✅ | ✅ | + | [Commit](#commit) | ✅ | ✅ | + | [Validators](#validators) | ✅ | ✅ | + | [Genesis](#genesis) | ✅ | ✅ | + | [GenesisChunked](#genesischunked) | ✅ | ❌ | + | [ConsensusParams](#consensusparams) | ✅ | ❌ | + | [UnconfirmedTxs](#unconfirmedtxs) | ✅ | ❌ | + | [NumUnconfirmedTxs](#numunconfirmedtxs) | ✅ | ❌ | + | [Tx](#tx) | ✅ | ❌ | + | [BroadCastTxSync](#broadcasttxsync) | ✅ | ✅ | + | [BroadCastTxAsync](#broadcasttxasync) | ✅ | ✅ | + | [ABCIInfo](#abciinfo) | ✅ | ✅ | + | [ABCIQuery](#abciquery) | ✅ | ✅ | + | [BroadcastTxAsync](#broadcasttxasync) | ✅ | ✅ | + | [BroadcastEvidence](#broadcastevidence) | ✅ | ✅ | + +## Timestamps + +Timestamps in the RPC layer of CometBFT follows RFC3339Nano. The RFC3339Nano format removes trailing zeros from the seconds field. + +This means if a block has a timestamp like: `1985-04-12T23:20:50.5200000Z`, the value returned in the RPC will be `1985-04-12T23:20:50.52Z`. + + + +## Info Routes + +### Health + +Node heartbeat + +#### Parameters + +None + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/health +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"health\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": -1, + "result": {} +} +``` + +### Status + +Get CometBFT status including node info, pubkey, latest block hash, app hash, block height and time. + +#### Parameters + +None + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/status +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"status\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": -1, + "result": { + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "b93270b358a72a2db30089f3856475bb1f918d6d", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "cosmoshub-4", + "version": "v0.34.8", + "channels": "40202122233038606100", + "moniker": "aib-hub-node", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "50F03C0EAACA8BCA7F9C14189ACE9C05A9A1BBB5268DB63DC6A3C848D1ECFD27", + "latest_app_hash": "2316CFF7644219F4F15BEE456435F280E2B38955EEA6D4617CCB6D7ABF781C22", + "latest_block_height": "5622165", + "latest_block_time": "2021-03-25T14:00:43.356134226Z", + "earliest_block_hash": "1455A0C15AC49BB506992EC85A3CD4D32367E53A087689815E01A524231C3ADF", + "earliest_app_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", + "earliest_block_height": "5200791", + "earliest_block_time": "2019-12-11T16:11:34Z", + "catching_up": false + }, + "validator_info": { + "address": "38FB765D0092470989360ECA1C89CD06C2C1583C", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "Z+8kntVegi1sQiWLYwFSVLNWqdAUGEy7lskL78gxLZI=" + }, + "voting_power": "0" + } + } +} +``` + +### NetInfo + +Network information + +#### Parameters + +None + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/net_info +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"net_info\"}" +``` + +#### Response + +```json +{ + "id": 0, + "jsonrpc": "2.0", + "result": { + "listening": true, + "listeners": [ + "Listener(@)" + ], + "n_peers": "1", + "peers": [ + { + "node_id": "5576458aef205977e18fd50b274e9b5d9014525a", + "url": "tcp://5576458aef205977e18fd50b274e9b5d9014525a@95.179.155.35:26656" + } + ] + } +} +``` + +### Blockchain + +Get block headers. Returned in descending order. May be limited in quantity. + +#### Parameters + +- `minHeight (integer)`: The lowest block to be returned in the response +- `maxHeight (integer)`: The highest block to be returned in the response + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/blockchain + +curl http://127.0.0.1:26657/blockchain?minHeight=1&maxHeight=2 +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"blockchain\",\"params\":{\"minHeight\":\"1\", \"maxHeight\":\"2\"}}" +``` + +#### Response + +```json +{ + "id": 0, + "jsonrpc": "2.0", + "result": { + "last_height": "1276718", + "block_metas": [ + { + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "block_size": 1000000, + "header": { + "version": { + "block": "10", + "app": "0" + }, + "chain_id": "cosmoshub-2", + "height": "12", + "time": "2019-04-22T17:01:51.701356223Z", + "last_block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "last_commit_hash": "21B9BC845AD2CB2C4193CDD17BFC506F1EBE5A7402E84AD96E64171287A34812", + "data_hash": "970886F99E77ED0D60DA8FCE0447C2676E59F2F77302B0C4AA10E1D02F18EF73", + "validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "next_validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "consensus_hash": "0F2908883A105C793B74495EB7D6DF2EEA479ED7FC9349206A65CB0F9987A0B8", + "app_hash": "223BF64D4A01074DC523A80E76B9BBC786C791FB0A1893AC5B14866356FCFD6C", + "last_results_hash": "", + "evidence_hash": "", + "proposer_address": "D540AB022088612AC74B287D076DBFBC4A377A2E" + }, + "num_txs": "54" + } + ] + } +} +``` + +### Block + +Get block at a specified height. + +#### Parameters + +- `height (integer)`: height of the requested block. If no height is specified the latest block will be used. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/block + +curl http://127.0.0.1:26657/block?height=1 +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"block\",\"params\":{\"height\":\"1\"}}" +``` + +#### Response + +```json +{ + "id": 0, + "jsonrpc": "2.0", + "result": { + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "block": { + "header": { + "version": { + "block": "10", + "app": "0" + }, + "chain_id": "cosmoshub-2", + "height": "12", + "time": "2019-04-22T17:01:51.701356223Z", + "last_block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "last_commit_hash": "21B9BC845AD2CB2C4193CDD17BFC506F1EBE5A7402E84AD96E64171287A34812", + "data_hash": "970886F99E77ED0D60DA8FCE0447C2676E59F2F77302B0C4AA10E1D02F18EF73", + "validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "next_validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "consensus_hash": "0F2908883A105C793B74495EB7D6DF2EEA479ED7FC9349206A65CB0F9987A0B8", + "app_hash": "223BF64D4A01074DC523A80E76B9BBC786C791FB0A1893AC5B14866356FCFD6C", + "last_results_hash": "", + "evidence_hash": "", + "proposer_address": "D540AB022088612AC74B287D076DBFBC4A377A2E" + }, + "data": [ + "yQHwYl3uCkKoo2GaChRnd+THLQ2RM87nEZrE19910Z28ABIUWW/t8AtIMwcyU0sT32RcMDI9GF0aEAoFdWF0b20SBzEwMDAwMDASEwoNCgV1YXRvbRIEMzEwMRCd8gEaagom61rphyEDoJPxlcjRoNDtZ9xMdvs+lRzFaHe2dl2P5R2yVCWrsHISQKkqX5H1zXAIJuC57yw0Yb03Fwy75VRip0ZBtLiYsUqkOsPUoQZAhDNP+6LY+RUwz/nVzedkF0S29NZ32QXdGv0=" + ], + "evidence": [ + { + "type": "string", + "height": 0, + "time": 0, + "total_voting_power": 0, + "validator": { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "A6DoBUypNtUAyEHWtQ9bFjfNg8Bo9CrnkUGl6k6OHN4=" + }, + "voting_power": 0, + "address": "string" + } + } + ], + "last_commit": { + "height": 0, + "round": 0, + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "signatures": [ + { + "type": 2, + "height": "1262085", + "round": 0, + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "timestamp": "2019-08-01T11:39:38.867269833Z", + "validator_address": "000001E443FD237E4B616E2FA69DF4EE3D49A94F", + "validator_index": 0, + "signature": "DBchvucTzAUEJnGYpNvMdqLhBAHG4Px8BsOBB3J3mAFCLGeuG7uJqy+nVngKzZdPhPi8RhmE/xcw/M9DOJjEDg==" + } + ] + } + } + } +} +``` + +### BlockByHash + +#### Parameters + +- `hash (string)`: Hash of the block to query for. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/block_by_hash?hash=0xD70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"block_by_hash\",\"params\":{\"hash\":\"0xD70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED\"}}" +``` + +#### Response + +```json +{ + "id": 0, + "jsonrpc": "2.0", + "result": { + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "block": { + "header": { + "version": { + "block": "10", + "app": "0" + }, + "chain_id": "cosmoshub-2", + "height": "12", + "time": "2019-04-22T17:01:51.701356223Z", + "last_block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "last_commit_hash": "21B9BC845AD2CB2C4193CDD17BFC506F1EBE5A7402E84AD96E64171287A34812", + "data_hash": "970886F99E77ED0D60DA8FCE0447C2676E59F2F77302B0C4AA10E1D02F18EF73", + "validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "next_validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "consensus_hash": "0F2908883A105C793B74495EB7D6DF2EEA479ED7FC9349206A65CB0F9987A0B8", + "app_hash": "223BF64D4A01074DC523A80E76B9BBC786C791FB0A1893AC5B14866356FCFD6C", + "last_results_hash": "", + "evidence_hash": "", + "proposer_address": "D540AB022088612AC74B287D076DBFBC4A377A2E" + }, + "data": [ + "yQHwYl3uCkKoo2GaChRnd+THLQ2RM87nEZrE19910Z28ABIUWW/t8AtIMwcyU0sT32RcMDI9GF0aEAoFdWF0b20SBzEwMDAwMDASEwoNCgV1YXRvbRIEMzEwMRCd8gEaagom61rphyEDoJPxlcjRoNDtZ9xMdvs+lRzFaHe2dl2P5R2yVCWrsHISQKkqX5H1zXAIJuC57yw0Yb03Fwy75VRip0ZBtLiYsUqkOsPUoQZAhDNP+6LY+RUwz/nVzedkF0S29NZ32QXdGv0=" + ], + "evidence": [ + { + "type": "string", + "height": 0, + "time": 0, + "total_voting_power": 0, + "validator": { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "A6DoBUypNtUAyEHWtQ9bFjfNg8Bo9CrnkUGl6k6OHN4=" + }, + "voting_power": 0, + "address": "string" + } + } + ], + "last_commit": { + "height": 0, + "round": 0, + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "signatures": [ + { + "type": 2, + "height": "1262085", + "round": 0, + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "timestamp": "2019-08-01T11:39:38.867269833Z", + "validator_address": "000001E443FD237E4B616E2FA69DF4EE3D49A94F", + "validator_index": 0, + "signature": "DBchvucTzAUEJnGYpNvMdqLhBAHG4Px8BsOBB3J3mAFCLGeuG7uJqy+nVngKzZdPhPi8RhmE/xcw/M9DOJjEDg==" + } + ] + } + } + } +} +``` + +### BlockResults + +### Parameters + +- `height (integer)`: Height of the block which contains the results. If no height is specified, the latest block height will be used + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/block_results + + +curl http://127.0.0.1:26657/block_results?height=1 +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"block_results\",\"params\":{\"height\":\"1\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "height": "12", + "total_gas_used": "100", + "txs_results": [ + { + "code": "0", + "data": "", + "log": "not enough gas", + "info": "", + "gas_wanted": "100", + "gas_used": "100", + "events": [ + { + "type": "app", + "attributes": [ + { + "key": "YWN0aW9u", + "value": "c2VuZA==", + "index": false + } + ] + } + ], + "codespace": "ibc" + } + ], + "begin_block_events": [ + { + "type": "app", + "attributes": [ + { + "key": "YWN0aW9u", + "value": "c2VuZA==", + "index": false + } + ] + } + ], + "end_block": [ + { + "type": "app", + "attributes": [ + { + "key": "YWN0aW9u", + "value": "c2VuZA==", + "index": false + } + ] + } + ], + "validator_updates": [ + { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "9tK9IT+FPdf2qm+5c2qaxi10sWP+3erWTKgftn2PaQM=" + }, + "power": "300" + } + ], + "consensus_params_updates": { + "block": { + "max_bytes": "22020096", + "max_gas": "1000", + "time_iota_ms": "1000" + }, + "evidence": { + "max_age": "100000" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + } + } + } +} +``` + +### Commit + +#### Parameters + +- `height (integer)`: Height of the block the requested commit pertains to. If no height is set the latest commit will be returned. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/commit + + +curl http://127.0.0.1:26657/commit?height=1 +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"commit\",\"params\":{\"height\":\"1\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "signed_header": { + "header": { + "version": { + "block": "10", + "app": "0" + }, + "chain_id": "cosmoshub-2", + "height": "12", + "time": "2019-04-22T17:01:51.701356223Z", + "last_block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "last_commit_hash": "21B9BC845AD2CB2C4193CDD17BFC506F1EBE5A7402E84AD96E64171287A34812", + "data_hash": "970886F99E77ED0D60DA8FCE0447C2676E59F2F77302B0C4AA10E1D02F18EF73", + "validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "next_validators_hash": "D658BFD100CA8025CFD3BECFE86194322731D387286FBD26E059115FD5F2BCA0", + "consensus_hash": "0F2908883A105C793B74495EB7D6DF2EEA479ED7FC9349206A65CB0F9987A0B8", + "app_hash": "223BF64D4A01074DC523A80E76B9BBC786C791FB0A1893AC5B14866356FCFD6C", + "last_results_hash": "", + "evidence_hash": "", + "proposer_address": "D540AB022088612AC74B287D076DBFBC4A377A2E" + }, + "commit": { + "height": "1311801", + "round": 0, + "block_id": { + "hash": "112BC173FD838FB68EB43476816CD7B4C6661B6884A9E357B417EE957E1CF8F7", + "parts": { + "total": 1, + "hash": "38D4B26B5B725C4F13571EFE022C030390E4C33C8CF6F88EDD142EA769642DBD" + } + }, + "signatures": [ + { + "block_id_flag": 2, + "validator_address": "000001E443FD237E4B616E2FA69DF4EE3D49A94F", + "timestamp": "2019-04-22T17:01:58.376629719Z", + "signature": "14jaTQXYRt8kbLKEhdHq7AXycrFImiLuZx50uOjs2+Zv+2i7RTG/jnObD07Jo2ubZ8xd7bNBJMqkgtkd0oQHAw==" + } + ] + } + }, + "canonical": true + } +} +``` + +### Validators + +#### Parameters + +- `height (integer)`: Block height at which the validators were present on. If no height is set the latest commit will be returned. +- `page (integer)`: +- `per_page (integer)`: + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/validators +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"validators\",\"params\":{\"height\":\"1\", \"page\":\"1\", \"per_page\":\"20\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "block_height": "55", + "validators": [ + { + "address": "000001E443FD237E4B616E2FA69DF4EE3D49A94F", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "9tK9IT+FPdf2qm+5c2qaxi10sWP+3erWTKgftn2PaQM=" + }, + "voting_power": "239727", + "proposer_priority": "-11896414" + } + ], + "count": "1", + "total": "25" + } +} +``` + +### Genesis + +Get Genesis of the chain. If the response is large, this operation +will return an error: use `genesis_chunked` instead. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/genesis +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"genesis\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "genesis": { + "genesis_time": "2019-04-22T17:00:00Z", + "chain_id": "cosmoshub-2", + "initial_height": "2", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "1000", + "time_iota_ms": "1000" + }, + "evidence": { + "max_age": "100000" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + } + }, + "validators": [ + { + "address": "B00A6323737F321EB0B8D59C6FD497A14B60938A", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "cOQZvh/h9ZioSeUMZB/1Vy1Xo5x2sjrVjlE/qHnYifM=" + }, + "power": "9328525", + "name": "Certus One" + } + ], + "app_hash": "", + "app_state": {} + } + } +} +``` + +### GenesisChunked + +Get the genesis document in a chunks to support easily transfering larger documents. + +#### Parameters + +- `chunk` (integer): the index number of the chunk that you wish to + fetch. These IDs are 0 indexed. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/genesis_chunked?chunk=0 +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"genesis_chunked\",\"params\":{\"chunk\":0}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "chunk": 0, + "total": 10, + "data": "dGVuZGVybWludAo=" + } +} +``` + +### ConsensusParams + +Get the consensus parameters. + +#### Parameters + +- `height (integer)`: Block height at which the consensus params would like to be fetched for. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/consensus_params +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"consensus_params\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "block_height": "1", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "1000", + "time_iota_ms": "1000" + }, + "evidence": { + "max_age": "100000" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + } + } + } +} +``` + +### UnconfirmedTxs + +Get a list of unconfirmed transactions. + +#### Parameters + +- `limit (integer)` The amount of txs to respond with. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/unconfirmed_txs +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"unconfirmed_txs\, \"params\":{\"limit\":\"20\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "n_txs": "82", + "total": "82", + "total_bytes": "19974", + "txs": [ + "gAPwYl3uCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUA75/FmYq9WymsOBJ0XSJ8yV8zmQKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhQbrvwbvlNiT+Yjr86G+YQNx7kRVgowjE1xDQoUjJyJG+WaWBwSiGannBRFdrbma+8SFK2m+1oxgILuQLO55n8mWfnbIzyPCjCMTXENChSMnIkb5ZpYHBKIZqecFEV2tuZr7xIUQNGfkmhTNMis4j+dyMDIWXdIPiYKMIxNcQ0KFIyciRvlmlgcEohmp5wURXa25mvvEhS8sL0D0wwgGCItQwVowak5YB38KRIUCg4KBXVhdG9tEgUxMDA1NBDoxRgaagom61rphyECn8x7emhhKdRCB2io7aS/6Cpuq5NbVqbODmqOT3jWw6kSQKUresk+d+Gw0BhjiggTsu8+1voW+VlDCQ1GRYnMaFOHXhyFv7BCLhFWxLxHSAYT8a5XqoMayosZf9mANKdXArA=" + ] + } +} +``` + +### NumUnconfirmedTxs + +Get data about unconfirmed transactions. + +#### Parameters + +None + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/num_unconfirmed_txs +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"num_unconfirmed_txs\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "n_txs": "31", + "total": "82", + "total_bytes": "19974" + } +} +``` + +### Tx + +#### Parameters + +- `hash (string)`: The hash of the transaction +- `prove (bool)`: If the response should include proof the transaction was included in a block. + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/num_unconfirmed_txs +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"num_unconfirmed_txs\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "hash": "D70952032620CC4E2737EB8AC379806359D8E0B17B0488F627997A0B043ABDED", + "height": "1000", + "index": 0, + "tx_result": { + "log": "[{\"msg_index\":\"0\",\"success\":true,\"log\":\"\"}]", + "gas_wanted": "200000", + "gas_used": "28596", + "tags": [ + { + "key": "YWN0aW9u", + "value": "c2VuZA==", + "index": false + } + ] + }, + "tx": "5wHwYl3uCkaoo2GaChQmSIu8hxpJxLcCuIi8fiHN4TMwrRIU/Af1cEG7Rcs/6LjTl7YjRSymJfYaFAoFdWF0b20SCzE0OTk5OTk1MDAwEhMKDQoFdWF0b20SBDUwMDAQwJoMGmoKJuta6YchAwswBShaB1wkZBctLIhYqBC3JrAI28XGzxP+rVEticGEEkAc+khTkKL9CDE47aDvjEHvUNt+izJfT4KVF2v2JkC+bmlH9K08q3PqHeMI9Z5up+XMusnTqlP985KF+SI5J3ZOIhhNYWRlIGJ5IENpcmNsZSB3aXRoIGxvdmU=" + } +} +``` + +## Transaction Routes + +### BroadCastTxSync + +Returns with the response from CheckTx. Does not wait for DeliverTx result. + +#### Parameters + +- `tx (string)`: The transaction encoded + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/broadcast_tx_sync?tx=encoded_tx +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"broadcast_tx_sync\",\"params\":{\"tx\":\"a/encoded_tx/c\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "code": "0", + "data": "", + "log": "", + "codespace": "ibc", + "hash": "0D33F2F03A5234F38706E43004489E061AC40A2E" + }, + "error": "" +} +``` + +### BroadCastTxAsync + +Returns right away, with no response. Does not wait for CheckTx nor DeliverTx results. + +#### Parameters + +- `tx (string)`: The transaction encoded + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/broadcast_tx_async?tx=encoded_tx +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"broadcast_tx_async\",\"params\":{\"tx\":\"a/encoded_tx/c\"}}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "code": "0", + "data": "", + "log": "", + "codespace": "ibc", + "hash": "0D33F2F03A5234F38706E43004489E061AC40A2E" + }, + "error": "" +} +``` + +### CheckTx + +Checks the transaction without executing it. + +#### Parameters + +- `tx (string)`: String of the encoded transaction + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/check_tx?tx=encoded_tx +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"check_tx\",\"params\":{\"tx\":\"a/encoded_tx/c\"}}" +``` + +#### Response + +```json +{ + "id": 0, + "jsonrpc": "2.0", + "error": "", + "result": { + "code": "0", + "data": "", + "log": "", + "info": "", + "gas_wanted": "1", + "gas_used": "0", + "events": [ + { + "type": "app", + "attributes": [ + { + "key": "YWN0aW9u", + "value": "c2VuZA==", + "index": false + } + ] + } + ], + "codespace": "bank" + } +} +``` + +## ABCI Routes + +### ABCIInfo + +Get some info about the application. + +#### Parameters + +None + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/abci_info +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"abci_info\"}" +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 0, + "result": { + "response": { + "data": "{\"size\":0}", + "version": "0.16.1", + "app_version": "1314126" + } + } +} +``` + +### ABCIQuery + +Query the application for some information. + +#### Parameters + +- `path (string)`: Path to the data. This is defined by the application. +- `data (string)`: The data requested +- `height (integer)`: Height at which the data is being requested for. +- `prove (bool)`: Include proofs of the transactions inclusion in the block + +#### Request + +##### HTTP + +```sh +curl http://127.0.0.1:26657/abci_query?path="a/b/c"=IHAVENOIDEA&height=1&prove=true +``` + +##### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"abci_query\",\"params\":{\"path\":\"a/b/c\", \"height\":\"1\", \"bool\":\"true\"}}" +``` + +#### Response + +```json +{ + "error": "", + "result": { + "response": { + "log": "exists", + "height": "0", + "proof": "010114FED0DAD959F36091AD761C922ABA3CBF1D8349990101020103011406AA2262E2F448242DF2C2607C3CDC705313EE3B0001149D16177BC71E445476174622EA559715C293740C", + "value": "61626364", + "key": "61626364", + "index": "-1", + "code": "0" + } + }, + "id": 0, + "jsonrpc": "2.0" +} +``` + +## Evidence Routes + +### BroadcastEvidence + +Broadcast evidence of the misbehavior. + +#### Parameters + +- `evidence (string)`: + +#### Request + +##### HTTP + +```sh +curl http://localhost:26657/broadcast_evidence?evidence=JSON_EVIDENCE_encoded +``` + +#### JSONRPC + +```sh +curl -X POST https://localhost:26657 -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"broadcast_evidence\",\"params\":{\"evidence\":\"JSON_EVIDENCE_encoded\"}}" +``` + +#### Response + +```json +{ + "error": "", + "result": "", + "id": 0, + "jsonrpc": "2.0" +} +``` diff --git a/state/compatibility_test.go b/state/compatibility_test.go new file mode 100644 index 0000000..c5d6ace --- /dev/null +++ b/state/compatibility_test.go @@ -0,0 +1,281 @@ +package state_test + +import ( + "fmt" + "testing" + "time" + + dbm "github.com/cometbft/cometbft-db" + cmtcrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + + abci "github.com/cometbft/cometbft/abci/types" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + "github.com/stretchr/testify/require" +) + +// Compatibility test across different state proto versions + +func calcABCIResponsesKey(height int64) []byte { + return []byte(fmt.Sprintf("abciResponsesKey:%v", height)) +} + +var lastABCIResponseKey = []byte("lastABCIResponseKey") + +var ( + _ sm.Store = (*MultiStore)(nil) + _ LegacyStore = (*MultiStore)(nil) +) + +// MultiStore represents a state store that implements the Store interface +// and contains additional store and database options. +type MultiStore struct { + sm.Store + db dbm.DB + sm.StoreOptions +} + +// NewMultiStore returns a new MultiStore. +// It sets the store, db, and StoreOptions fields of the MultiStore struct. +func NewMultiStore(db dbm.DB, options sm.StoreOptions, store sm.Store) *MultiStore { + return &MultiStore{ + Store: store, + db: db, + StoreOptions: options, + } +} + +// LegacyStore represents a legacy data store. +type LegacyStore interface { + SaveABCIResponses(height int64, abciResponses *cmtstate.LegacyABCIResponses) error +} + +// SaveABCIResponses saves the ABCIResponses for a given height in the MultiStore. +// It strips out any nil values from the DeliverTxs field, and saves the ABCIResponses to +// disk if the DiscardABCIResponses flag is set to false. It also saves the last ABCI response +// for crash recovery, overwriting the previously saved response. +func (multi MultiStore) SaveABCIResponses(height int64, abciResponses *cmtstate.LegacyABCIResponses) error { + var dtxs []*abci.ExecTxResult + // strip nil values, + for _, tx := range abciResponses.DeliverTxs { + if tx != nil { + dtxs = append(dtxs, tx) + } + } + abciResponses.DeliverTxs = dtxs + + // If the flag is false then we save the ABCIResponse. This can be used for the /block_results + // query or to reindex an event using the command line. + if !multi.DiscardABCIResponses { + bz, err := abciResponses.Marshal() + if err != nil { + return err + } + if err := multi.db.Set(calcABCIResponsesKey(height), bz); err != nil { + return err + } + } + + // We always save the last ABCI response for crash recovery. + // This overwrites the previous saved ABCI Response. + response := &cmtstate.ABCIResponsesInfo{ + LegacyAbciResponses: abciResponses, + Height: height, + } + bz, err := response.Marshal() + if err != nil { + return err + } + + return multi.db.SetSync(lastABCIResponseKey, bz) +} + +// TestLegacySaveAndLoadFinalizeBlock tests saving and loading of ABCIResponses +// using the multiStore. It verifies that the loaded ABCIResponses match the +// original ones and that missing fields are correctly handled. +// This test is important for the LoadFinalizeBlockResponse method in the state store. +func TestLegacySaveAndLoadFinalizeBlock(t *testing.T) { + tearDown, stateDB, _, store := setupTestCaseWithStore(t) + defer tearDown(t) + options := sm.StoreOptions{ + DiscardABCIResponses: false, + } + + height := int64(1) + multiStore := NewMultiStore(stateDB, options, store) + + // try with a complete ABCI Response + legacyABCIResponses := newLegacyABCIResponses() + err := multiStore.SaveABCIResponses(height, &legacyABCIResponses) + require.NoError(t, err) + require.Equal(t, 1, len(legacyABCIResponses.DeliverTxs)) + require.Equal(t, 1, len(legacyABCIResponses.BeginBlock.Events)) + require.Equal(t, 1, len(legacyABCIResponses.EndBlock.Events)) + + responseFinalizeBlock, err := multiStore.LoadFinalizeBlockResponse(height) + require.NoError(t, err) + + // Test for not nil + require.NotNil(t, responseFinalizeBlock.TxResults) + require.NotNil(t, responseFinalizeBlock.Events) + require.NotNil(t, responseFinalizeBlock.ValidatorUpdates) + require.NotNil(t, responseFinalizeBlock.ConsensusParamUpdates) + require.Nil(t, responseFinalizeBlock.AppHash) + + // Test for equality + require.Equal(t, 1, len(responseFinalizeBlock.TxResults)) + require.Equal(t, len(legacyABCIResponses.DeliverTxs), len(responseFinalizeBlock.TxResults)) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Code, responseFinalizeBlock.TxResults[0].Code) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Data, responseFinalizeBlock.TxResults[0].Data) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Log, responseFinalizeBlock.TxResults[0].Log) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].GasWanted, responseFinalizeBlock.TxResults[0].GasWanted) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].GasUsed, responseFinalizeBlock.TxResults[0].GasUsed) + require.Equal(t, len(legacyABCIResponses.DeliverTxs[0].Events), len(responseFinalizeBlock.TxResults[0].Events)) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Events[0].Type, responseFinalizeBlock.TxResults[0].Events[0].Type) + require.Equal(t, len(legacyABCIResponses.DeliverTxs[0].Events[0].Attributes), len(responseFinalizeBlock.TxResults[0].Events[0].Attributes)) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Events[0].Attributes[0].Key, responseFinalizeBlock.TxResults[0].Events[0].Attributes[0].Key) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Events[0].Attributes[0].Value, responseFinalizeBlock.TxResults[0].Events[0].Attributes[0].Value) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].Codespace, responseFinalizeBlock.TxResults[0].Codespace) + + require.Equal(t, 2, len(responseFinalizeBlock.Events)) + require.Equal(t, len(legacyABCIResponses.BeginBlock.Events)+len(legacyABCIResponses.EndBlock.Events), len(responseFinalizeBlock.Events)) + + require.Equal(t, legacyABCIResponses.BeginBlock.Events[0].Type, responseFinalizeBlock.Events[0].Type) + require.Equal(t, len(legacyABCIResponses.BeginBlock.Events[0].Attributes)+1, len(responseFinalizeBlock.Events[0].Attributes)) // +1 for inject 'mode' attribute + require.Equal(t, legacyABCIResponses.BeginBlock.Events[0].Attributes[0].Key, responseFinalizeBlock.Events[0].Attributes[0].Key) + require.Equal(t, legacyABCIResponses.BeginBlock.Events[0].Attributes[0].Value, responseFinalizeBlock.Events[0].Attributes[0].Value) + + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Block.MaxBytes, responseFinalizeBlock.ConsensusParamUpdates.Block.MaxBytes) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Block.MaxGas, responseFinalizeBlock.ConsensusParamUpdates.Block.MaxGas) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Evidence.MaxAgeNumBlocks, responseFinalizeBlock.ConsensusParamUpdates.Evidence.MaxAgeNumBlocks) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Evidence.MaxAgeDuration, responseFinalizeBlock.ConsensusParamUpdates.Evidence.MaxAgeDuration) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Evidence.MaxBytes, responseFinalizeBlock.ConsensusParamUpdates.Evidence.MaxBytes) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Validator.PubKeyTypes, responseFinalizeBlock.ConsensusParamUpdates.Validator.PubKeyTypes) + require.Equal(t, legacyABCIResponses.EndBlock.ConsensusParamUpdates.Version.App, responseFinalizeBlock.ConsensusParamUpdates.Version.App) + + require.Nil(t, responseFinalizeBlock.ConsensusParamUpdates.Abci) + require.Nil(t, responseFinalizeBlock.AppHash) + + require.Equal(t, len(legacyABCIResponses.EndBlock.ValidatorUpdates), len(responseFinalizeBlock.ValidatorUpdates)) + require.Equal(t, legacyABCIResponses.EndBlock.ValidatorUpdates[0].Power, responseFinalizeBlock.ValidatorUpdates[0].Power) + + // skip until an equivalency test is possible + require.Equal(t, legacyABCIResponses.EndBlock.ValidatorUpdates[0].PubKey.GetEd25519(), responseFinalizeBlock.ValidatorUpdates[0].PubKey.GetEd25519()) + + // try with an ABCI Response missing fields + height = int64(2) + legacyABCIResponses = newLegacyABCIResponsesWithNullFields() + require.Equal(t, 1, len(legacyABCIResponses.DeliverTxs)) + require.Equal(t, 1, len(legacyABCIResponses.BeginBlock.Events)) + require.Nil(t, legacyABCIResponses.EndBlock) + err = multiStore.SaveABCIResponses(height, &legacyABCIResponses) + require.NoError(t, err) + responseFinalizeBlock, err = multiStore.LoadFinalizeBlockResponse(height) + require.NoError(t, err) + + require.Equal(t, len(legacyABCIResponses.DeliverTxs), len(responseFinalizeBlock.TxResults)) + require.Equal(t, legacyABCIResponses.DeliverTxs[0].String(), responseFinalizeBlock.TxResults[0].String()) + require.Equal(t, len(legacyABCIResponses.BeginBlock.Events), len(responseFinalizeBlock.Events)) +} + +// Generate a Legacy ABCIResponses with data for all fields. +func newLegacyABCIResponses() cmtstate.LegacyABCIResponses { + eventAttr := abci.EventAttribute{ + Key: "key", + Value: "value", + } + + deliverTxEvent := abci.Event{ + Type: "deliver_tx_event", + Attributes: []abci.EventAttribute{eventAttr}, + } + + endBlockEvent := abci.Event{ + Type: "end_block_event", + Attributes: []abci.EventAttribute{eventAttr}, + } + + beginBlockEvent := abci.Event{ + Type: "begin_block_event", + Attributes: []abci.EventAttribute{eventAttr}, + } + + responseDeliverTx := abci.ExecTxResult{ + Code: abci.CodeTypeOK, + Events: []abci.Event{deliverTxEvent}, + } + + validatorUpdates := []abci.ValidatorUpdate{{ + PubKey: cmtcrypto.PublicKey{Sum: &cmtcrypto.PublicKey_Ed25519{Ed25519: make([]byte, 1)}}, + Power: int64(10), + }} + + consensusParams := &cmtproto.ConsensusParams{ + Block: &cmtproto.BlockParams{ + MaxBytes: int64(100000), + MaxGas: int64(10000), + }, + Evidence: &cmtproto.EvidenceParams{ + MaxAgeNumBlocks: int64(10), + MaxAgeDuration: time.Duration(1000), + MaxBytes: int64(10000), + }, + Validator: &cmtproto.ValidatorParams{ + PubKeyTypes: []string{"ed25519"}, + }, + Version: &cmtproto.VersionParams{ + App: uint64(10), + }, + } + + // Legacy ABCI Responses + legacyABCIResponses := cmtstate.LegacyABCIResponses{ + DeliverTxs: []*abci.ExecTxResult{ + &responseDeliverTx, + }, + EndBlock: &cmtstate.ResponseEndBlock{ + Events: []abci.Event{endBlockEvent}, + ConsensusParamUpdates: consensusParams, + ValidatorUpdates: validatorUpdates, + }, + BeginBlock: &cmtstate.ResponseBeginBlock{ + Events: []abci.Event{beginBlockEvent}, + }, + } + return legacyABCIResponses +} + +// Generate a Legacy ABCIResponses with null data for some fields. +func newLegacyABCIResponsesWithNullFields() cmtstate.LegacyABCIResponses { + eventAttr := abci.EventAttribute{ + Key: "key", + Value: "value", + } + + deliverTxEvent := abci.Event{ + Type: "deliver_tx_event", + Attributes: []abci.EventAttribute{eventAttr}, + } + + beginBlockEvent := abci.Event{ + Type: "begin_block_event", + Attributes: []abci.EventAttribute{eventAttr}, + } + + responseDeliverTx := abci.ExecTxResult{ + Code: abci.CodeTypeOK, + Events: []abci.Event{deliverTxEvent}, + } + + // Legacy ABCI Responses + legacyABCIResponses := cmtstate.LegacyABCIResponses{ + DeliverTxs: []*abci.ExecTxResult{ + &responseDeliverTx, + }, + BeginBlock: &cmtstate.ResponseBeginBlock{ + Events: []abci.Event{beginBlockEvent}, + }, + } + return legacyABCIResponses +} diff --git a/state/errors.go b/state/errors.go new file mode 100644 index 0000000..0801a6c --- /dev/null +++ b/state/errors.go @@ -0,0 +1,127 @@ +package state + +import ( + "errors" + "fmt" +) + +type ( + ErrInvalidBlock error + ErrProxyAppConn error + + ErrUnknownBlock struct { + Height int64 + } + + ErrBlockHashMismatch struct { + CoreHash []byte + AppHash []byte + Height int64 + } + + ErrAppBlockHeightTooHigh struct { + CoreHeight int64 + AppHeight int64 + } + + ErrAppBlockHeightTooLow struct { + AppHeight int64 + StoreBase int64 + } + + ErrLastStateMismatch struct { + Height int64 + Core []byte + App []byte + } + + ErrStateMismatch struct { + Got *State + Expected *State + } + + ErrNoValSetForHeight struct { + Height int64 + } + + ErrNoConsensusParamsForHeight struct { + Height int64 + } + + ErrNoABCIResponsesForHeight struct { + Height int64 + } + + ErrABCIResponseResponseUnmarshalForHeight struct { + Height int64 + } + + ErrABCIResponseCorruptedOrSpecChangeForHeight struct { + Err error + Height int64 + } +) + +func (e ErrUnknownBlock) Error() string { + return fmt.Sprintf("could not find block #%d", e.Height) +} + +func (e ErrBlockHashMismatch) Error() string { + return fmt.Sprintf( + "app block hash (%X) does not match core block hash (%X) for height %d", + e.AppHash, + e.CoreHash, + e.Height, + ) +} + +func (e ErrAppBlockHeightTooHigh) Error() string { + return fmt.Sprintf("app block height (%d) is higher than core (%d)", e.AppHeight, e.CoreHeight) +} + +func (e ErrAppBlockHeightTooLow) Error() string { + return fmt.Sprintf("app block height (%d) is too far below block store base (%d)", e.AppHeight, e.StoreBase) +} + +func (e ErrLastStateMismatch) Error() string { + return fmt.Sprintf( + "latest CometBFT block (%d) LastAppHash (%X) does not match app's AppHash (%X)", + e.Height, + e.Core, + e.App, + ) +} + +func (e ErrStateMismatch) Error() string { + return fmt.Sprintf( + "state after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", + e.Got, + e.Expected, + ) +} + +func (e ErrNoValSetForHeight) Error() string { + return fmt.Sprintf("could not find validator set for height #%d", e.Height) +} + +func (e ErrNoConsensusParamsForHeight) Error() string { + return fmt.Sprintf("could not find consensus params for height #%d", e.Height) +} + +func (e ErrNoABCIResponsesForHeight) Error() string { + return fmt.Sprintf("could not find results for height #%d", e.Height) +} + +func (e ErrABCIResponseResponseUnmarshalForHeight) Error() string { + return fmt.Sprintf("could not decode results for height %d", e.Height) +} + +func (e ErrABCIResponseCorruptedOrSpecChangeForHeight) Error() string { + return fmt.Sprintf("failed to unmarshall FinalizeBlockResponse (also tried as legacy ABCI response) for height %d", e.Height) +} + +func (e ErrABCIResponseCorruptedOrSpecChangeForHeight) Unwrap() error { + return e.Err +} + +var ErrFinalizeBlockResponsesNotPersisted = errors.New("node is not persisting finalize block responses") diff --git a/state/execution.go b/state/execution.go new file mode 100644 index 0000000..ff72340 --- /dev/null +++ b/state/execution.go @@ -0,0 +1,792 @@ +package state + +import ( + "bytes" + "context" + "fmt" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/libs/fail" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/mempool" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------------------------------- +// BlockExecutor handles block execution and state updates. +// It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses, +// then commits and updates the mempool atomically, then saves state. + +// BlockExecutor provides the context and accessories for properly executing a block. +type BlockExecutor struct { + // save state, validators, consensus params, abci responses here + store Store + + // use blockstore for the pruning functions. + blockStore BlockStore + + // execute the app against this + proxyApp proxy.AppConnConsensus + + // events + eventBus types.BlockEventPublisher + + // manage the mempool lock during commit + // and update both with block results after commit. + mempool mempool.Mempool + evpool EvidencePool + + logger log.Logger + + metrics *Metrics +} + +type BlockExecutorOption func(executor *BlockExecutor) + +func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption { + return func(blockExec *BlockExecutor) { + blockExec.metrics = metrics + } +} + +// NewBlockExecutor returns a new BlockExecutor with a NopEventBus. +// Call SetEventBus to provide one. +func NewBlockExecutor( + stateStore Store, + logger log.Logger, + proxyApp proxy.AppConnConsensus, + mempool mempool.Mempool, + evpool EvidencePool, + blockStore BlockStore, + options ...BlockExecutorOption, +) *BlockExecutor { + res := &BlockExecutor{ + store: stateStore, + proxyApp: proxyApp, + eventBus: types.NopEventBus{}, + mempool: mempool, + evpool: evpool, + logger: logger, + metrics: NopMetrics(), + blockStore: blockStore, + } + + for _, option := range options { + option(res) + } + + return res +} + +func (blockExec *BlockExecutor) Store() Store { + return blockExec.store +} + +// SetEventBus - sets the event bus for publishing block related events. +// If not called, it defaults to types.NopEventBus. +func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) { + blockExec.eventBus = eventBus +} + +// CreateProposalBlock calls state.MakeBlock with evidence from the evpool +// and txs from the mempool. The max bytes must be big enough to fit the commit. +// The block space is first allocated to outstanding evidence. +// The rest is given to txs, up to the max gas. +// +// Contract: application will not return more bytes than are sent over the wire. +func (blockExec *BlockExecutor) CreateProposalBlock( + ctx context.Context, + height int64, + state State, + lastExtCommit *types.ExtendedCommit, + proposerAddr []byte, +) (*types.Block, error) { + + maxBytes := state.ConsensusParams.Block.MaxBytes + emptyMaxBytes := maxBytes == -1 + if emptyMaxBytes { + maxBytes = int64(types.MaxBlockSizeBytes) + } + + maxGas := state.ConsensusParams.Block.MaxGas + + evidence, evSize := blockExec.evpool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes) + + // Fetch a limited amount of valid txs + maxDataBytes := types.MaxDataBytes(maxBytes, evSize, state.Validators.Size()) + maxReapBytes := maxDataBytes + if emptyMaxBytes { + maxReapBytes = -1 + } + + txs := blockExec.mempool.ReapMaxBytesMaxGas(maxReapBytes, maxGas) + commit := lastExtCommit.ToCommit() + block, err := state.MakeBlock(height, txs, commit, evidence, proposerAddr) + if err != nil { + return nil, err + } + rpp, err := blockExec.proxyApp.PrepareProposal( + ctx, + &abci.RequestPrepareProposal{ + MaxTxBytes: maxDataBytes, + Txs: block.Txs.ToSliceOfBytes(), + LocalLastCommit: buildExtendedCommitInfoFromStore(lastExtCommit, blockExec.store, state.InitialHeight, state.ConsensusParams.ABCI), + Misbehavior: block.Evidence.Evidence.ToABCI(), + Height: block.Height, + Time: block.Time, + NextValidatorsHash: block.NextValidatorsHash, + ProposerAddress: block.ProposerAddress, + }, + ) + if err != nil { + // The App MUST ensure that only valid (and hence 'processable') transactions + // enter the mempool. Hence, at this point, we can't have any non-processable + // transaction causing an error. + // + // Also, the App can simply skip any transaction that could cause any kind of trouble. + // Either way, we cannot recover in a meaningful way, unless we skip proposing + // this block, repair what caused the error and try again. Hence, we return an + // error for now (the production code calling this function is expected to panic). + return nil, err + } + + txl := types.ToTxs(rpp.Txs) + if err := txl.Validate(maxDataBytes); err != nil { + return nil, err + } + + return state.MakeBlock(height, txl, commit, evidence, proposerAddr) +} + +func (blockExec *BlockExecutor) ProcessProposal( + block *types.Block, + state State, +) (bool, error) { + resp, err := blockExec.proxyApp.ProcessProposal(context.TODO(), &abci.RequestProcessProposal{ + Hash: block.Header.Hash(), + Height: block.Height, + Time: block.Time, + Txs: block.Txs.ToSliceOfBytes(), + ProposedLastCommit: buildLastCommitInfoFromStore(block, blockExec.store, state.InitialHeight), + Misbehavior: block.Evidence.Evidence.ToABCI(), + ProposerAddress: block.ProposerAddress, + NextValidatorsHash: block.NextValidatorsHash, + }) + if err != nil { + return false, err + } + if resp.IsStatusUnknown() { + panic(fmt.Sprintf("ProcessProposal responded with status %s", resp.Status.String())) + } + + return resp.IsAccepted(), nil +} + +// ValidateBlock validates the given block against the given state. +// If the block is invalid, it returns an error. +// Validation does not mutate state, but does require historical information from the stateDB, +// ie. to verify evidence from a validator at an old height. +func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error { + err := validateBlock(state, block) + if err != nil { + return err + } + return blockExec.evpool.CheckEvidence(block.Evidence.Evidence) +} + +// ApplyVerifiedBlock does the same as `ApplyBlock`, but skips verification. +func (blockExec *BlockExecutor) ApplyVerifiedBlock( + state State, blockID types.BlockID, block *types.Block, +) (State, error) { + return blockExec.applyBlock(state, blockID, block) +} + +// ApplyBlock validates the block against the state, executes it against the app, +// fires the relevant events, commits the app, and saves the new state and responses. +// It returns the new state. +// It's the only function that needs to be called +// from outside this package to process and commit an entire block. +// It takes a blockID to avoid recomputing the parts hash. +func (blockExec *BlockExecutor) ApplyBlock( + state State, blockID types.BlockID, block *types.Block, +) (State, error) { + + if err := validateBlock(state, block); err != nil { + return state, ErrInvalidBlock(err) + } + + return blockExec.applyBlock(state, blockID, block) +} + +func (blockExec *BlockExecutor) applyBlock(state State, blockID types.BlockID, block *types.Block) (State, error) { + startTime := time.Now().UnixNano() + abciResponse, err := blockExec.proxyApp.FinalizeBlock(context.TODO(), &abci.RequestFinalizeBlock{ + Hash: block.Hash(), + NextValidatorsHash: block.NextValidatorsHash, + ProposerAddress: block.ProposerAddress, + Height: block.Height, + Time: block.Time, + DecidedLastCommit: buildLastCommitInfoFromStore(block, blockExec.store, state.InitialHeight), + Misbehavior: block.Evidence.Evidence.ToABCI(), + Txs: block.Txs.ToSliceOfBytes(), + }) + endTime := time.Now().UnixNano() + blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000) + if err != nil { + blockExec.logger.Error("error in proxyAppConn.FinalizeBlock", "err", err) + return state, err + } + + blockExec.logger.Info( + "finalized block", + "height", block.Height, + "num_txs_res", len(abciResponse.TxResults), + "num_val_updates", len(abciResponse.ValidatorUpdates), + "block_app_hash", fmt.Sprintf("%X", abciResponse.AppHash), + ) + + // Assert that the application correctly returned tx results for each of the transactions provided in the block + if len(block.Txs) != len(abciResponse.TxResults) { + return state, fmt.Errorf("expected tx results length to match size of transactions in block. Expected %d, got %d", len(block.Txs), len(abciResponse.TxResults)) + } + + blockExec.logger.Info("executed block", "height", block.Height, "app_hash", fmt.Sprintf("%X", abciResponse.AppHash)) + + fail.Fail() // XXX + + // Save the results before we commit. + if err := blockExec.store.SaveFinalizeBlockResponse(block.Height, abciResponse); err != nil { + return state, err + } + + fail.Fail() // XXX + + // validate the validator updates and convert to CometBFT types + err = validateValidatorUpdates(abciResponse.ValidatorUpdates, state.ConsensusParams.Validator) + if err != nil { + return state, fmt.Errorf("error in validator updates: %v", err) + } + + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponse.ValidatorUpdates) + if err != nil { + return state, err + } + if len(validatorUpdates) > 0 { + blockExec.logger.Info("updates to validators", "updates", types.ValidatorListString(validatorUpdates)) + blockExec.metrics.ValidatorSetUpdates.Add(1) + } + if abciResponse.ConsensusParamUpdates != nil { + blockExec.metrics.ConsensusParamUpdates.Add(1) + } + + // Update the state with the block and responses. + state, err = updateState(state, blockID, &block.Header, abciResponse, validatorUpdates) + if err != nil { + return state, fmt.Errorf("commit failed for application: %v", err) + } + + // Lock mempool, commit app state, update mempoool. + retainHeight, err := blockExec.Commit(state, block, abciResponse) + if err != nil { + return state, fmt.Errorf("commit failed for application: %v", err) + } + + // Update evpool with the latest state. + blockExec.evpool.Update(state, block.Evidence.Evidence) + + fail.Fail() // XXX + + // Update the app hash and save the state. + state.AppHash = abciResponse.AppHash + if err := blockExec.store.Save(state); err != nil { + return state, err + } + + fail.Fail() // XXX + + // Prune old heights, if requested by ABCI app. + if retainHeight > 0 { + pruned, err := blockExec.pruneBlocks(retainHeight, state) + if err != nil { + blockExec.logger.Error("failed to prune blocks", "retain_height", retainHeight, "err", err) + } else { + blockExec.logger.Debug("pruned blocks", "pruned", pruned, "retain_height", retainHeight) + } + } + + // Events are fired after everything else. + // NOTE: if we crash between Commit and Save, events wont be fired during replay + fireEvents(blockExec.logger, blockExec.eventBus, block, blockID, abciResponse, validatorUpdates) + + return state, nil +} + +func (blockExec *BlockExecutor) ExtendVote( + ctx context.Context, + vote *types.Vote, + block *types.Block, + state State, +) ([]byte, error) { + if !block.HashesTo(vote.BlockID.Hash) { + panic(fmt.Sprintf("vote's hash does not match the block it is referring to %X!=%X", block.Hash(), vote.BlockID.Hash)) + } + if vote.Height != block.Height { + panic(fmt.Sprintf("vote's and block's heights do not match %d!=%d", block.Height, vote.Height)) + } + + req := abci.RequestExtendVote{ + Hash: vote.BlockID.Hash, + Height: vote.Height, + Time: block.Time, + Txs: block.Txs.ToSliceOfBytes(), + ProposedLastCommit: buildLastCommitInfoFromStore(block, blockExec.store, state.InitialHeight), + Misbehavior: block.Evidence.Evidence.ToABCI(), + NextValidatorsHash: block.NextValidatorsHash, + ProposerAddress: block.ProposerAddress, + } + + resp, err := blockExec.proxyApp.ExtendVote(ctx, &req) + if err != nil { + panic(fmt.Errorf("ExtendVote call failed: %w", err)) + } + return resp.VoteExtension, nil +} + +func (blockExec *BlockExecutor) VerifyVoteExtension(ctx context.Context, vote *types.Vote) error { + req := abci.RequestVerifyVoteExtension{ + Hash: vote.BlockID.Hash, + ValidatorAddress: vote.ValidatorAddress, + Height: vote.Height, + VoteExtension: vote.Extension, + } + + resp, err := blockExec.proxyApp.VerifyVoteExtension(ctx, &req) + if err != nil { + panic(fmt.Errorf("VerifyVoteExtension call failed: %w", err)) + } + if resp.IsStatusUnknown() { + panic(fmt.Sprintf("VerifyVoteExtension responded with status %s", resp.Status.String())) + } + + if !resp.IsAccepted() { + return types.ErrInvalidVoteExtension + } + return nil +} + +// Commit locks the mempool, runs the ABCI Commit message, and updates the +// mempool. +// It returns the result of calling abci.Commit which is the height to retain (if any)). +// The application is expected to have persisted its state (if any) before returning +// from the ABCI Commit call. This is the only place where the application should +// persist its state. +// The Mempool must be locked during commit and update because state is +// typically reset on Commit and old txs must be replayed against committed +// state before new txs are run in the mempool, lest they be invalid. +func (blockExec *BlockExecutor) Commit( + state State, + block *types.Block, + abciResponse *abci.ResponseFinalizeBlock, +) (int64, error) { + blockExec.mempool.Lock() + defer blockExec.mempool.Unlock() + + // while mempool is Locked, flush to ensure all async requests have completed + // in the ABCI app before Commit. + err := blockExec.mempool.FlushAppConn() + if err != nil { + blockExec.logger.Error("client error during mempool.FlushAppConn", "err", err) + return 0, err + } + + // Commit block, get hash back + res, err := blockExec.proxyApp.Commit(context.TODO()) + if err != nil { + blockExec.logger.Error("client error during proxyAppConn.CommitSync", "err", err) + return 0, err + } + + // ResponseCommit has no error code - just data + blockExec.logger.Info( + "committed state", + "height", block.Height, + "block_app_hash", fmt.Sprintf("%X", block.AppHash), + ) + + // Update mempool. + err = blockExec.mempool.Update( + block.Height, + block.Txs, + abciResponse.TxResults, + TxPreCheck(state), + TxPostCheck(state), + ) + + return res.RetainHeight, err +} + +//--------------------------------------------------------- +// Helper functions for executing blocks and updating state + +func buildLastCommitInfoFromStore(block *types.Block, store Store, initialHeight int64) abci.CommitInfo { + if block.Height == initialHeight { // check for initial height before loading validators + // there is no last commit for the initial height. + // return an empty value. + return abci.CommitInfo{} + } + + lastValSet, err := store.LoadValidators(block.Height - 1) + if err != nil { + panic(fmt.Errorf("failed to load validator set at height %d: %w", block.Height-1, err)) + } + + return BuildLastCommitInfo(block, lastValSet, initialHeight) +} + +// BuildLastCommitInfo builds a CommitInfo from the given block and validator set. +// If you want to load the validator set from the store instead of providing it, +// use buildLastCommitInfoFromStore. +func BuildLastCommitInfo(block *types.Block, lastValSet *types.ValidatorSet, initialHeight int64) abci.CommitInfo { + if block.Height == initialHeight { + // there is no last commit for the initial height. + // return an empty value. + return abci.CommitInfo{} + } + + var ( + commitSize = block.LastCommit.Size() + valSetLen = len(lastValSet.Validators) + ) + + // ensure that the size of the validator set in the last commit matches + // the size of the validator set in the state store. + if commitSize != valSetLen { + panic(fmt.Sprintf( + "commit size (%d) doesn't match validator set length (%d) at height %d\n\n%v\n\n%v", + commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators, + )) + } + + votes := make([]abci.VoteInfo, block.LastCommit.Size()) + for i, val := range lastValSet.Validators { + commitSig := block.LastCommit.Signatures[i] + votes[i] = abci.VoteInfo{ + Validator: types.TM2PB.Validator(val), + BlockIdFlag: cmtproto.BlockIDFlag(commitSig.BlockIDFlag), + } + } + + return abci.CommitInfo{ + Round: block.LastCommit.Round, + Votes: votes, + } +} + +// buildExtendedCommitInfoFromStore populates an ABCI extended commit from the +// corresponding CometBFT extended commit ec, using the stored validator set +// from ec. It requires ec to include the original precommit votes along with +// the vote extensions from the last commit. +// +// For heights below the initial height, for which we do not have the required +// data, it returns an empty record. +// +// Assumes that the commit signatures are sorted according to validator index. +func buildExtendedCommitInfoFromStore(ec *types.ExtendedCommit, store Store, initialHeight int64, ap types.ABCIParams) abci.ExtendedCommitInfo { + if ec.Height < initialHeight { + // There are no extended commits for heights below the initial height. + return abci.ExtendedCommitInfo{} + } + + valSet, err := store.LoadValidators(ec.Height) + if err != nil { + panic(fmt.Errorf("failed to load validator set at height %d, initial height %d: %w", ec.Height, initialHeight, err)) + } + + return BuildExtendedCommitInfo(ec, valSet, initialHeight, ap) +} + +// BuildExtendedCommitInfo builds an ExtendedCommitInfo from the given block and validator set. +// If you want to load the validator set from the store instead of providing it, +// use buildExtendedCommitInfoFromStore. +func BuildExtendedCommitInfo(ec *types.ExtendedCommit, valSet *types.ValidatorSet, initialHeight int64, ap types.ABCIParams) abci.ExtendedCommitInfo { + if ec.Height < initialHeight { + // There are no extended commits for heights below the initial height. + return abci.ExtendedCommitInfo{} + } + + var ( + ecSize = ec.Size() + valSetLen = len(valSet.Validators) + ) + + // Ensure that the size of the validator set in the extended commit matches + // the size of the validator set in the state store. + if ecSize != valSetLen { + panic(fmt.Errorf( + "extended commit size (%d) does not match validator set length (%d) at height %d\n\n%v\n\n%v", + ecSize, valSetLen, ec.Height, ec.ExtendedSignatures, valSet.Validators, + )) + } + + votes := make([]abci.ExtendedVoteInfo, ecSize) + for i, val := range valSet.Validators { + ecs := ec.ExtendedSignatures[i] + + // Absent signatures have empty validator addresses, but otherwise we + // expect the validator addresses to be the same. + if ecs.BlockIDFlag != types.BlockIDFlagAbsent && !bytes.Equal(ecs.ValidatorAddress, val.Address) { + panic(fmt.Errorf("validator address of extended commit signature in position %d (%s) does not match the corresponding validator's at height %d (%s)", + i, ecs.ValidatorAddress, ec.Height, val.Address, + )) + } + + // Check if vote extensions were enabled during the commit's height: ec.Height. + // ec is the commit from the previous height, so if extensions were enabled + // during that height, we ensure they are present and deliver the data to + // the proposer. If they were not enabled during this previous height, we + // will not deliver extension data. + if err := ecs.EnsureExtension(ap.VoteExtensionsEnabled(ec.Height)); err != nil { + panic(fmt.Errorf("commit at height %d has problems with vote extension data; err %w", ec.Height, err)) + } + + votes[i] = abci.ExtendedVoteInfo{ + Validator: types.TM2PB.Validator(val), + BlockIdFlag: cmtproto.BlockIDFlag(ecs.BlockIDFlag), + VoteExtension: ecs.Extension, + ExtensionSignature: ecs.ExtensionSignature, + } + } + + return abci.ExtendedCommitInfo{ + Round: ec.Round, + Votes: votes, + } +} + +func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate, + params types.ValidatorParams) error { + for _, valUpdate := range abciUpdates { + if valUpdate.GetPower() < 0 { + return fmt.Errorf("voting power can't be negative %v", valUpdate) + } else if valUpdate.GetPower() == 0 { + // continue, since this is deleting the validator, and thus there is no + // pubkey to check + continue + } + + // Check if validator's pubkey matches an ABCI type in the consensus params + pk, err := cryptoenc.PubKeyFromProto(valUpdate.PubKey) + if err != nil { + return err + } + + if !types.IsValidPubkeyType(params, pk.Type()) { + return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus", + valUpdate, pk.Type()) + } + } + return nil +} + +// updateState returns a new State updated according to the header and responses. +func updateState( + state State, + blockID types.BlockID, + header *types.Header, + abciResponse *abci.ResponseFinalizeBlock, + validatorUpdates []*types.Validator, +) (State, error) { + + // Copy the valset so we can apply changes from EndBlock + // and update s.LastValidators and s.Validators. + nValSet := state.NextValidators.Copy() + + // Update the validator set with the latest abciResponse. + lastHeightValsChanged := state.LastHeightValidatorsChanged + if len(validatorUpdates) > 0 { + err := nValSet.UpdateWithChangeSet(validatorUpdates) + if err != nil { + return state, fmt.Errorf("changing validator set: %w", err) + } + // Change results from this height but only applies to the next next height. + lastHeightValsChanged = header.Height + 1 + 1 + } + + // Update validator proposer priority and set state variables. + nValSet.IncrementProposerPriority(1) + + // Update the params with the latest abciResponse. + nextParams := state.ConsensusParams + lastHeightParamsChanged := state.LastHeightConsensusParamsChanged + if abciResponse.ConsensusParamUpdates != nil { + // NOTE: must not mutate state.ConsensusParams + nextParams = state.ConsensusParams.Update(abciResponse.ConsensusParamUpdates) + err := nextParams.ValidateBasic() + if err != nil { + return state, fmt.Errorf("validating new consensus params: %w", err) + } + + err = state.ConsensusParams.ValidateUpdate(abciResponse.ConsensusParamUpdates, header.Height) + if err != nil { + return state, fmt.Errorf("updating consensus params: %w", err) + } + + state.Version.Consensus.App = nextParams.Version.App + + // Change results from this height but only applies to the next height. + lastHeightParamsChanged = header.Height + 1 + } + + nextVersion := state.Version + + // NOTE: the AppHash and the VoteExtension has not been populated. + // It will be filled on state.Save. + return State{ + Version: nextVersion, + ChainID: state.ChainID, + InitialHeight: state.InitialHeight, + LastBlockHeight: header.Height, + LastBlockID: blockID, + LastBlockTime: header.Time, + NextValidators: nValSet, + Validators: state.NextValidators.Copy(), + LastValidators: state.Validators.Copy(), + LastHeightValidatorsChanged: lastHeightValsChanged, + ConsensusParams: nextParams, + LastHeightConsensusParamsChanged: lastHeightParamsChanged, + LastResultsHash: TxResultsHash(abciResponse.TxResults), + AppHash: nil, + }, nil +} + +// Fire NewBlock, NewBlockHeader. +// Fire TxEvent for every tx. +// NOTE: if CometBFT crashes before commit, some or all of these events may be published again. +func fireEvents( + logger log.Logger, + eventBus types.BlockEventPublisher, + block *types.Block, + blockID types.BlockID, + abciResponse *abci.ResponseFinalizeBlock, + validatorUpdates []*types.Validator, +) { + if err := eventBus.PublishEventNewBlock(types.EventDataNewBlock{ + Block: block, + BlockID: blockID, + ResultFinalizeBlock: *abciResponse, + }); err != nil { + logger.Error("failed publishing new block", "err", err) + } + + if err := eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{ + Header: block.Header, + }); err != nil { + logger.Error("failed publishing new block header", "err", err) + } + + if err := eventBus.PublishEventNewBlockEvents(types.EventDataNewBlockEvents{ + Height: block.Height, + Events: abciResponse.Events, + NumTxs: int64(len(block.Txs)), + }); err != nil { + logger.Error("failed publishing new block events", "err", err) + } + + if len(block.Evidence.Evidence) != 0 { + for _, ev := range block.Evidence.Evidence { + if err := eventBus.PublishEventNewEvidence(types.EventDataNewEvidence{ + Evidence: ev, + Height: block.Height, + }); err != nil { + logger.Error("failed publishing new evidence", "err", err) + } + } + } + + for i, tx := range block.Txs { + if err := eventBus.PublishEventTx(types.EventDataTx{TxResult: abci.TxResult{ + Height: block.Height, + Index: uint32(i), + Tx: tx, + Result: *(abciResponse.TxResults[i]), + }}); err != nil { + logger.Error("failed publishing event TX", "err", err) + } + } + + if len(validatorUpdates) > 0 { + if err := eventBus.PublishEventValidatorSetUpdates( + types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates}); err != nil { + logger.Error("failed publishing event", "err", err) + } + } +} + +//---------------------------------------------------------------------------------------------------- +// Execute block without state. TODO: eliminate + +// ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state. +// It returns the application root hash (result of abci.Commit). +func ExecCommitBlock( + appConnConsensus proxy.AppConnConsensus, + block *types.Block, + logger log.Logger, + store Store, + initialHeight int64, +) ([]byte, error) { + commitInfo := buildLastCommitInfoFromStore(block, store, initialHeight) + + resp, err := appConnConsensus.FinalizeBlock(context.TODO(), &abci.RequestFinalizeBlock{ + Hash: block.Hash(), + NextValidatorsHash: block.NextValidatorsHash, + ProposerAddress: block.ProposerAddress, + Height: block.Height, + Time: block.Time, + DecidedLastCommit: commitInfo, + Misbehavior: block.Evidence.Evidence.ToABCI(), + Txs: block.Txs.ToSliceOfBytes(), + }) + if err != nil { + logger.Error("error in proxyAppConn.FinalizeBlock", "err", err) + return nil, err + } + + // Assert that the application correctly returned tx results for each of the transactions provided in the block + if len(block.Txs) != len(resp.TxResults) { + return nil, fmt.Errorf("expected tx results length to match size of transactions in block. Expected %d, got %d", len(block.Txs), len(resp.TxResults)) + } + + logger.Info("executed block", "height", block.Height, "app_hash", fmt.Sprintf("%X", resp.AppHash)) + + // Commit block + _, err = appConnConsensus.Commit(context.TODO()) + if err != nil { + logger.Error("client error during proxyAppConn.Commit", "err", err) + return nil, err + } + + // ResponseCommit has no error or log + return resp.AppHash, nil +} + +func (blockExec *BlockExecutor) pruneBlocks(retainHeight int64, state State) (uint64, error) { + base := blockExec.blockStore.Base() + if retainHeight <= base { + return 0, nil + } + + amountPruned, prunedHeaderHeight, err := blockExec.blockStore.PruneBlocks(retainHeight, state) + if err != nil { + return 0, fmt.Errorf("failed to prune block store: %w", err) + } + + err = blockExec.Store().PruneStates(base, retainHeight, prunedHeaderHeight) + if err != nil { + return 0, fmt.Errorf("failed to prune state store: %w", err) + } + return amountPruned, nil +} diff --git a/state/execution_test.go b/state/execution_test.go new file mode 100644 index 0000000..c48d109 --- /dev/null +++ b/state/execution_test.go @@ -0,0 +1,1149 @@ +package state_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abciclientmocks "github.com/cometbft/cometbft/abci/client/mocks" + abci "github.com/cometbft/cometbft/abci/types" + abcimocks "github.com/cometbft/cometbft/abci/types/mocks" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + mpmocks "github.com/cometbft/cometbft/mempool/mocks" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/proxy" + pmocks "github.com/cometbft/cometbft/proxy/mocks" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" +) + +var ( + chainID = "execution_chain" + testPartSize uint32 = types.BlockPartSizeBytes +) + +func TestApplyBlock(t *testing.T) { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.Nil(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, _ := makeState(1, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), + mp, sm.EmptyEvidencePool{}, blockStore) + + block, err := makeBlock(state, 1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + state, err = blockExec.ApplyBlock(state, blockID, block) + require.Nil(t, err) + + // TODO check state and mempool + assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated") +} + +// TestFinalizeBlockDecidedLastCommit ensures we correctly send the +// DecidedLastCommit to the application. The test ensures that the +// DecidedLastCommit properly reflects which validators signed the preceding +// block. +func TestFinalizeBlockDecidedLastCommit(t *testing.T) { + app := &testApp{} + baseTime := time.Now() + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(7, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + absentSig := types.NewExtendedCommitSigAbsent() + + testCases := []struct { + name string + absentCommitSigs map[int]bool + }{ + {"none absent", map[int]bool{}}, + {"one absent", map[int]bool{1: true}}, + {"multiple absent", map[int]bool{1: true, 3: true}}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + blockStore := store.NewBlockStore(dbm.NewMemDB()) + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, 0) + evpool.On("Update", mock.Anything, mock.Anything).Return() + evpool.On("CheckEvidence", mock.Anything).Return(nil) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + eventBus := types.NewEventBus() + require.NoError(t, eventBus.Start()) + + blockExec := sm.NewBlockExecutor(stateStore, log.NewNopLogger(), proxyApp.Consensus(), mp, evpool, blockStore) + state, _, lastCommit, err := makeAndCommitGoodBlock(state, 1, new(types.Commit), state.NextValidators.Validators[0].Address, blockExec, privVals, nil) + require.NoError(t, err) + + for idx, isAbsent := range tc.absentCommitSigs { + if isAbsent { + lastCommit.ExtendedSignatures[idx] = absentSig + } + } + + // block for height 2 + block, err := makeBlock(state, 2, lastCommit.ToCommit()) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + _, err = blockExec.ApplyBlock(state, blockID, block) + require.NoError(t, err) + require.True(t, app.LastTime.After(baseTime)) + + // -> app receives a list of validators with a bool indicating if they signed + for i, v := range app.CommitVotes { + _, absent := tc.absentCommitSigs[i] + assert.Equal(t, !absent, v.BlockIdFlag != cmtproto.BlockIDFlagAbsent) + } + }) + } +} + +// TestFinalizeBlockValidators ensures we send absent validators list. +func TestFinalizeBlockValidators(t *testing.T) { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // no need to check error again + + state, stateDB, _ := makeState(2, 2) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + prevHash := state.LastBlockID.Hash + prevParts := types.PartSetHeader{} + prevBlockID := types.BlockID{Hash: prevHash, PartSetHeader: prevParts} + + var ( + now = cmttime.Now() + commitSig0 = types.ExtendedCommitSig{ + CommitSig: types.CommitSig{ + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: state.Validators.Validators[0].Address, + Timestamp: now, + Signature: []byte("Signature1"), + }, + Extension: []byte("extension1"), + ExtensionSignature: []byte("extensionSig1"), + } + + commitSig1 = types.ExtendedCommitSig{ + CommitSig: types.CommitSig{ + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: state.Validators.Validators[1].Address, + Timestamp: now, + Signature: []byte("Signature2"), + }, + Extension: []byte("extension2"), + ExtensionSignature: []byte("extensionSig2"), + } + absentSig = types.NewExtendedCommitSigAbsent() + ) + + testCases := []struct { + desc string + lastCommitSigs []types.ExtendedCommitSig + expectedAbsentValidators []int + shouldHaveTime bool + }{ + {"none absent", []types.ExtendedCommitSig{commitSig0, commitSig1}, []int{}, true}, + {"one absent", []types.ExtendedCommitSig{commitSig0, absentSig}, []int{1}, true}, + {"multiple absent", []types.ExtendedCommitSig{absentSig, absentSig}, []int{0, 1}, false}, + } + + for _, tc := range testCases { + lastCommit := &types.ExtendedCommit{ + Height: 1, + BlockID: prevBlockID, + ExtendedSignatures: tc.lastCommitSigs, + } + + // block for height 2 + block, err := makeBlock(state, 2, lastCommit.ToCommit()) + require.NoError(t, err) + + _, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, log.TestingLogger(), stateStore, 1) + require.NoError(t, err, tc.desc) + require.True(t, + !tc.shouldHaveTime || + app.LastTime.Equal(now) || app.LastTime.After(now), + "'last_time' should be at or after 'now'; tc %v, last_time %v, now %v", tc.desc, app.LastTime, now, + ) + + // -> app receives a list of validators with a bool indicating if they signed + ctr := 0 + for i, v := range app.CommitVotes { + if ctr < len(tc.expectedAbsentValidators) && + tc.expectedAbsentValidators[ctr] == i { + + assert.Equal(t, v.BlockIdFlag, cmtproto.BlockIDFlagAbsent) + ctr++ + } else { + assert.NotEqual(t, v.BlockIdFlag, cmtproto.BlockIDFlagAbsent) + } + } + } +} + +// TestFinalizeBlockMisbehavior ensures we send misbehavior list. +func TestFinalizeBlockMisbehavior(t *testing.T) { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(1, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + privVal := privVals[state.Validators.Validators[0].Address.String()] + blockID := makeBlockID([]byte("headerhash"), 1000, []byte("partshash")) + header := &types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: state.ChainID, + Height: 10, + Time: defaultEvidenceTime, + LastBlockID: blockID, + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: state.Validators.Hash(), + NextValidatorsHash: state.Validators.Hash(), + ConsensusHash: crypto.CRandBytes(tmhash.Size), + AppHash: crypto.CRandBytes(tmhash.Size), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + } + + // we don't need to worry about validating the evidence as long as they pass validate basic + dve, err := types.NewMockDuplicateVoteEvidenceWithValidator(3, defaultEvidenceTime, privVal, state.ChainID) + require.NoError(t, err) + dve.ValidatorPower = 1000 + lcae := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: header, + Commit: &types.Commit{ + Height: 10, + BlockID: makeBlockID(header.Hash(), 100, []byte("partshash")), + Signatures: []types.CommitSig{{ + BlockIDFlag: types.BlockIDFlagNil, + ValidatorAddress: crypto.AddressHash([]byte("validator_address")), + Timestamp: defaultEvidenceTime, + Signature: crypto.CRandBytes(types.MaxSignatureSize)}}, + }, + }, + ValidatorSet: state.Validators, + }, + CommonHeight: 8, + ByzantineValidators: []*types.Validator{state.Validators.Validators[0]}, + TotalVotingPower: 12, + Timestamp: defaultEvidenceTime, + } + + ev := []types.Evidence{dve, lcae} + + abciMb := []abci.Misbehavior{ + { + Type: abci.MisbehaviorType_DUPLICATE_VOTE, + Height: 3, + Time: defaultEvidenceTime, + Validator: types.TM2PB.Validator(state.Validators.Validators[0]), + TotalVotingPower: 10, + }, + { + Type: abci.MisbehaviorType_LIGHT_CLIENT_ATTACK, + Height: 8, + Time: defaultEvidenceTime, + Validator: types.TM2PB.Validator(state.Validators.Validators[0]), + TotalVotingPower: 12, + }, + } + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return(ev, int64(100)) + evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return() + evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), + mp, evpool, blockStore) + + block, err := makeBlock(state, 1, new(types.Commit)) + require.NoError(t, err) + block.Evidence = types.EvidenceData{Evidence: ev} + block.EvidenceHash = block.Evidence.Hash() + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + _, err = blockExec.ApplyBlock(state, blockID, block) + require.NoError(t, err) + + // TODO check state and mempool + assert.Equal(t, abciMb, app.Misbehavior) +} + +func TestProcessProposal(t *testing.T) { + const height = 2 + txs := test.MakeNTxs(height, 10) + + logger := log.NewNopLogger() + app := &abcimocks.Application{} + app.On("ProcessProposal", mock.Anything, mock.Anything).Return(&abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil) + + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + blockStore := store.NewBlockStore(dbm.NewMemDB()) + eventBus := types.NewEventBus() + err = eventBus.Start() + require.NoError(t, err) + + blockExec := sm.NewBlockExecutor( + stateStore, + logger, + proxyApp.Consensus(), + new(mpmocks.Mempool), + sm.EmptyEvidencePool{}, + blockStore, + ) + + block0, err := makeBlock(state, height-1, new(types.Commit)) + require.NoError(t, err) + lastCommitSig := []types.CommitSig{} + partSet, err := block0.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + blockID := types.BlockID{Hash: block0.Hash(), PartSetHeader: partSet.Header()} + voteInfos := []abci.VoteInfo{} + for _, privVal := range privVals { + pk, err := privVal.GetPubKey() + require.NoError(t, err) + idx, _ := state.Validators.GetByAddress(pk.Address()) + vote := types.MakeVoteNoError(t, privVal, block0.ChainID, idx, height-1, 0, 2, blockID, time.Now()) + addr := pk.Address() + voteInfos = append(voteInfos, + abci.VoteInfo{ + BlockIdFlag: cmtproto.BlockIDFlagCommit, + Validator: abci.Validator{ + Address: addr, + Power: 1000, + }, + }) + lastCommitSig = append(lastCommitSig, vote.CommitSig()) + } + + block1, err := makeBlock(state, height, &types.Commit{ + Height: height - 1, + Signatures: lastCommitSig, + }) + require.NoError(t, err) + + block1.Txs = txs + + expectedRpp := &abci.RequestProcessProposal{ + Txs: block1.Txs.ToSliceOfBytes(), + Hash: block1.Hash(), + Height: block1.Height, + Time: block1.Time, + Misbehavior: block1.Evidence.Evidence.ToABCI(), + ProposedLastCommit: abci.CommitInfo{ + Round: 0, + Votes: voteInfos, + }, + NextValidatorsHash: block1.NextValidatorsHash, + ProposerAddress: block1.ProposerAddress, + } + + acceptBlock, err := blockExec.ProcessProposal(block1, state) + require.NoError(t, err) + require.True(t, acceptBlock) + app.AssertExpectations(t) + app.AssertCalled(t, "ProcessProposal", context.TODO(), expectedRpp) +} + +func TestValidateValidatorUpdates(t *testing.T) { + pubkey1 := ed25519.GenPrivKey().PubKey() + pubkey2 := ed25519.GenPrivKey().PubKey() + pk1, err := cryptoenc.PubKeyToProto(pubkey1) + assert.NoError(t, err) + pk2, err := cryptoenc.PubKeyToProto(pubkey2) + assert.NoError(t, err) + + defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}} + + testCases := []struct { + name string + + abciUpdates []abci.ValidatorUpdate + validatorParams types.ValidatorParams + + shouldErr bool + }{ + { + "adding a validator is OK", + []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}}, + defaultValidatorParams, + false, + }, + { + "updating a validator is OK", + []abci.ValidatorUpdate{{PubKey: pk1, Power: 20}}, + defaultValidatorParams, + false, + }, + { + "removing a validator is OK", + []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}}, + defaultValidatorParams, + false, + }, + { + "adding a validator with negative power results in error", + []abci.ValidatorUpdate{{PubKey: pk2, Power: -100}}, + defaultValidatorParams, + true, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + err := sm.ValidateValidatorUpdates(tc.abciUpdates, tc.validatorParams) + if tc.shouldErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestUpdateValidators(t *testing.T) { + pubkey1 := ed25519.GenPrivKey().PubKey() + val1 := types.NewValidator(pubkey1, 10) + pubkey2 := ed25519.GenPrivKey().PubKey() + val2 := types.NewValidator(pubkey2, 20) + + pk, err := cryptoenc.PubKeyToProto(pubkey1) + require.NoError(t, err) + pk2, err := cryptoenc.PubKeyToProto(pubkey2) + require.NoError(t, err) + + testCases := []struct { + name string + + currentSet *types.ValidatorSet + abciUpdates []abci.ValidatorUpdate + + resultingSet *types.ValidatorSet + shouldErr bool + }{ + { + "adding a validator is OK", + types.NewValidatorSet([]*types.Validator{val1}), + []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}}, + types.NewValidatorSet([]*types.Validator{val1, val2}), + false, + }, + { + "updating a validator is OK", + types.NewValidatorSet([]*types.Validator{val1}), + []abci.ValidatorUpdate{{PubKey: pk, Power: 20}}, + types.NewValidatorSet([]*types.Validator{types.NewValidator(pubkey1, 20)}), + false, + }, + { + "removing a validator is OK", + types.NewValidatorSet([]*types.Validator{val1, val2}), + []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}}, + types.NewValidatorSet([]*types.Validator{val1}), + false, + }, + { + "removing a non-existing validator results in error", + types.NewValidatorSet([]*types.Validator{val1}), + []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}}, + types.NewValidatorSet([]*types.Validator{val1}), + true, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + updates, err := types.PB2TM.ValidatorUpdates(tc.abciUpdates) + assert.NoError(t, err) + err = tc.currentSet.UpdateWithChangeSet(updates) + if tc.shouldErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + require.Equal(t, tc.resultingSet.Size(), tc.currentSet.Size()) + + assert.Equal(t, tc.resultingSet.TotalVotingPower(), tc.currentSet.TotalVotingPower()) + + assert.Equal(t, tc.resultingSet.Validators[0].Address, tc.currentSet.Validators[0].Address) + if tc.resultingSet.Size() > 1 { + assert.Equal(t, tc.resultingSet.Validators[1].Address, tc.currentSet.Validators[1].Address) + } + } + }) + } +} + +// TestFinalizeBlockValidatorUpdates ensures we update validator set and send an event. +func TestFinalizeBlockValidatorUpdates(t *testing.T) { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, _ := makeState(1, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(types.Txs{}) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + + eventBus := types.NewEventBus() + err = eventBus.Start() + require.NoError(t, err) + defer eventBus.Stop() //nolint:errcheck // ignore for tests + + blockExec.SetEventBus(eventBus) + + updatesSub, err := eventBus.Subscribe( + context.Background(), + "TestEndBlockValidatorUpdates", + types.EventQueryValidatorSetUpdates, + ) + require.NoError(t, err) + + block, err := makeBlock(state, 1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + pubkey := ed25519.GenPrivKey().PubKey() + pk, err := cryptoenc.PubKeyToProto(pubkey) + require.NoError(t, err) + app.ValidatorUpdates = []abci.ValidatorUpdate{ + {PubKey: pk, Power: 10}, + } + + state, err = blockExec.ApplyBlock(state, blockID, block) + require.NoError(t, err) + // test new validator was added to NextValidators + if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) { + idx, _ := state.NextValidators.GetByAddress(pubkey.Address()) + if idx < 0 { + t.Fatalf("can't find address %v in the set %v", pubkey.Address(), state.NextValidators) + } + } + + // test we threw an event + select { + case msg := <-updatesSub.Out(): + event, ok := msg.Data().(types.EventDataValidatorSetUpdates) + require.True(t, ok, "Expected event of type EventDataValidatorSetUpdates, got %T", msg.Data()) + if assert.NotEmpty(t, event.ValidatorUpdates) { + assert.Equal(t, pubkey, event.ValidatorUpdates[0].PubKey) + assert.EqualValues(t, 10, event.ValidatorUpdates[0].VotingPower) + } + case <-updatesSub.Canceled(): + t.Fatalf("updatesSub was canceled (reason: %v)", updatesSub.Err()) + case <-time.After(1 * time.Second): + t.Fatal("Did not receive EventValidatorSetUpdates within 1 sec.") + } +} + +// TestFinalizeBlockValidatorUpdatesResultingInEmptySet checks that processing validator updates that +// would result in empty set causes no panic, an error is raised and NextValidators is not updated +func TestFinalizeBlockValidatorUpdatesResultingInEmptySet(t *testing.T) { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, _ := makeState(1, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + new(mpmocks.Mempool), + sm.EmptyEvidencePool{}, + blockStore, + ) + + block, err := makeBlock(state, 1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + vp, err := cryptoenc.PubKeyToProto(state.Validators.Validators[0].PubKey) + require.NoError(t, err) + // Remove the only validator + app.ValidatorUpdates = []abci.ValidatorUpdate{ + {PubKey: vp, Power: 0}, + } + + assert.NotPanics(t, func() { state, err = blockExec.ApplyBlock(state, blockID, block) }) + assert.Error(t, err) + assert.NotEmpty(t, state.NextValidators.Validators) +} + +func TestEmptyPrepareProposal(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + app := &abci.BaseApplication{} + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(types.Txs{}) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + _, err = blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.NoError(t, err) +} + +// TestPrepareProposalTxsAllIncluded tests that any transactions included in +// the prepare proposal response are included in the block. +func TestPrepareProposalTxsAllIncluded(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + state, stateDB, privVals := makeState(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, int64(0)) + + txs := test.MakeNTxs(height, 10) + mp := &mpmocks.Mempool{} + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(txs[2:]) + + app := &abcimocks.Application{} + app.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{ + Txs: txs.ToSliceOfBytes(), + }, nil) + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + block, err := blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.NoError(t, err) + + for i, tx := range block.Txs { + require.Equal(t, txs[i], tx) + } + + mp.AssertExpectations(t) +} + +// TestPrepareProposalReorderTxs tests that CreateBlock produces a block with transactions +// in the order matching the order they are returned from PrepareProposal. +func TestPrepareProposalReorderTxs(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + state, stateDB, privVals := makeState(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, int64(0)) + + txs := test.MakeNTxs(height, 10) + mp := &mpmocks.Mempool{} + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(txs) + + txs = txs[2:] + txs = append(txs[len(txs)/2:], txs[:len(txs)/2]...) + + app := &abcimocks.Application{} + app.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{ + Txs: txs.ToSliceOfBytes(), + }, nil) + + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + block, err := blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.NoError(t, err) + for i, tx := range block.Txs { + require.Equal(t, txs[i], tx) + } + + mp.AssertExpectations(t) +} + +// TestPrepareProposalErrorOnTooManyTxs tests that the block creation logic returns +// an error if the ResponsePrepareProposal returned from the application is invalid. +func TestPrepareProposalErrorOnTooManyTxs(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + state, stateDB, privVals := makeState(1, height) + // limit max block size + state.ConsensusParams.Block.MaxBytes = 60 * 1024 + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, int64(0)) + + const nValidators = 1 + var bytesPerTx int64 = 3 + maxDataBytes := types.MaxDataBytes(state.ConsensusParams.Block.MaxBytes, 0, nValidators) + txs := test.MakeNTxs(height, maxDataBytes/bytesPerTx+2) // +2 so that tx don't fit + mp := &mpmocks.Mempool{} + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(txs) + + app := &abcimocks.Application{} + app.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{ + Txs: txs.ToSliceOfBytes(), + }, nil) + + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.NewNopLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + block, err := blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.Nil(t, block) + require.ErrorContains(t, err, "transaction data size exceeds maximum") + + mp.AssertExpectations(t) +} + +// TestPrepareProposalCountSerializationOverhead tests that the block creation logic returns +// an error if the ResponsePrepareProposal returned from the application is at the limit of +// its size and will go beyond the limit upon serialization. +func TestPrepareProposalCountSerializationOverhead(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + state, stateDB, privVals := makeState(1, height) + // limit max block size + var bytesPerTx int64 = 4 + const nValidators = 1 + nonDataSize := 5000 - types.MaxDataBytes(5000, 0, nValidators) + state.ConsensusParams.Block.MaxBytes = bytesPerTx*1024 + nonDataSize + maxDataBytes := types.MaxDataBytes(state.ConsensusParams.Block.MaxBytes, 0, nValidators) + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, int64(0)) + + txs := test.MakeNTxs(height, maxDataBytes/bytesPerTx) + mp := &mpmocks.Mempool{} + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(txs) + + app := &abcimocks.Application{} + app.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{ + Txs: txs.ToSliceOfBytes(), + }, nil) + + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.NewNopLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + block, err := blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.Nil(t, block) + require.ErrorContains(t, err, "transaction data size exceeds maximum") + + mp.AssertExpectations(t) +} + +// TestPrepareProposalErrorOnPrepareProposalError tests when the client returns an error +// upon calling PrepareProposal on it. +func TestPrepareProposalErrorOnPrepareProposalError(t *testing.T) { + const height = 2 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + state, stateDB, privVals := makeState(1, height) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + evpool := &mocks.EvidencePool{} + evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, int64(0)) + + txs := test.MakeNTxs(height, 10) + mp := &mpmocks.Mempool{} + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(txs) + + cm := &abciclientmocks.Client{} + cm.On("SetLogger", mock.Anything).Return() + cm.On("Start").Return(nil) + cm.On("Quit").Return(nil) + cm.On("PrepareProposal", mock.Anything, mock.Anything).Return(nil, errors.New("an injected error")).Once() + cm.On("Stop").Return(nil) + cc := &pmocks.ClientCreator{} + cc.On("NewABCIClient").Return(cm, nil) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.NewNopLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + pa, _ := state.Validators.GetByIndex(0) + commit, _, err := makeValidCommit(height, types.BlockID{}, state.Validators, privVals) + require.NoError(t, err) + block, err := blockExec.CreateProposalBlock(ctx, height, state, commit, pa) + require.Nil(t, block) + require.ErrorContains(t, err, "an injected error") + + mp.AssertExpectations(t) +} + +// TestCreateProposalBlockPanicOnAbsentVoteExtensions ensures that the CreateProposalBlock +// call correctly panics when the vote extension data is missing from the extended commit +// data that the method receives. +func TestCreateProposalAbsentVoteExtensions(t *testing.T) { + for _, testCase := range []struct { + name string + + // The height that is about to be proposed + height int64 + + // The first height during which vote extensions will be required for consensus to proceed. + extensionEnableHeight int64 + expectPanic bool + }{ + { + name: "missing extension data on first required height", + height: 3, + extensionEnableHeight: 2, + expectPanic: true, + }, + { + name: "missing extension during before required height", + height: 3, + extensionEnableHeight: 3, + expectPanic: false, + }, + { + name: "missing extension data and not required", + height: 3, + extensionEnableHeight: 0, + expectPanic: false, + }, + { + name: "missing extension data and required in two heights", + height: 3, + extensionEnableHeight: 4, + expectPanic: false, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + app := abcimocks.NewApplication(t) + if !testCase.expectPanic { + app.On("PrepareProposal", mock.Anything, mock.Anything).Return(&abci.ResponsePrepareProposal{}, nil) + } + cc := proxy.NewLocalClientCreator(app) + proxyApp := proxy.NewAppConns(cc, proxy.NopMetrics()) + err := proxyApp.Start() + require.NoError(t, err) + + state, stateDB, privVals := makeState(1, int(testCase.height-1)) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state.ConsensusParams.ABCI.VoteExtensionsEnableHeight = testCase.extensionEnableHeight + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + mp.On("ReapMaxBytesMaxGas", mock.Anything, mock.Anything).Return(types.Txs{}) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + blockExec := sm.NewBlockExecutor( + stateStore, + log.NewNopLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + block, err := makeBlock(state, testCase.height, new(types.Commit)) + require.NoError(t, err) + + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + pa, _ := state.Validators.GetByIndex(0) + lastCommit, _, _ := makeValidCommit(testCase.height-1, blockID, state.Validators, privVals) + stripSignatures(lastCommit) + if testCase.expectPanic { + require.Panics(t, func() { + _, err := blockExec.CreateProposalBlock(ctx, testCase.height, state, lastCommit, pa) + require.NoError(t, err) + }) + } else { + _, err = blockExec.CreateProposalBlock(ctx, testCase.height, state, lastCommit, pa) + require.NoError(t, err) + } + }) + } +} + +func stripSignatures(ec *types.ExtendedCommit) { + for i, commitSig := range ec.ExtendedSignatures { + commitSig.Extension = nil + commitSig.ExtensionSignature = nil + ec.ExtendedSignatures[i] = commitSig + } +} + +func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID { + var ( + h = make([]byte, tmhash.Size) + psH = make([]byte, tmhash.Size) + ) + copy(h, hash) + copy(psH, partSetHash) + return types.BlockID{ + Hash: h, + PartSetHeader: types.PartSetHeader{ + Total: partSetSize, + Hash: psH, + }, + } +} diff --git a/state/export_test.go b/state/export_test.go new file mode 100644 index 0000000..e554910 --- /dev/null +++ b/state/export_test.go @@ -0,0 +1,63 @@ +package state + +import ( + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/types" +) + +// +// TODO: Remove dependence on all entities exported from this file. +// +// Every entity exported here is dependent on a private entity from the `state` +// package. Currently, these functions are only made available to tests in the +// `state_test` package, but we should not be relying on them for our testing. +// Instead, we should be exclusively relying on exported entities for our +// testing, and should be refactoring exported entities to make them more +// easily testable from outside of the package. +// + +const ValSetCheckpointInterval = valSetCheckpointInterval + +// UpdateState is an alias for updateState exported from execution.go, +// exclusively and explicitly for testing. +func UpdateState( + state State, + blockID types.BlockID, + header *types.Header, + resp *abci.ResponseFinalizeBlock, + validatorUpdates []*types.Validator, +) (State, error) { + return updateState(state, blockID, header, resp, validatorUpdates) +} + +// ValidateValidatorUpdates is an alias for validateValidatorUpdates exported +// from execution.go, exclusively and explicitly for testing. +func ValidateValidatorUpdates(abciUpdates []abci.ValidatorUpdate, params types.ValidatorParams) error { + return validateValidatorUpdates(abciUpdates, params) +} + +// SaveValidatorsInfo is an alias for the private saveValidatorsInfo method in +// store.go, exported exclusively and explicitly for testing. +func SaveValidatorsInfo(db dbm.DB, height, lastHeightChanged int64, valSet *types.ValidatorSet) error { + stateStore := dbStore{db, StoreOptions{DiscardABCIResponses: false}} + batch := stateStore.db.NewBatch() + err := stateStore.saveValidatorsInfo(height, lastHeightChanged, valSet, batch) + if err != nil { + return err + } + err = batch.WriteSync() + if err != nil { + return err + } + return nil +} + +func Int64ToBytes(val int64) []byte { + return int64ToBytes(val) +} + +func Int64FromBytes(val []byte) int64 { + return int64FromBytes(val) +} diff --git a/state/helpers_test.go b/state/helpers_test.go new file mode 100644 index 0000000..b09bcae --- /dev/null +++ b/state/helpers_test.go @@ -0,0 +1,316 @@ +package state_test + +import ( + "bytes" + "context" + "fmt" + "time" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/internal/test" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +type paramsChangeTestCase struct { + height int64 + params types.ConsensusParams +} + +func newTestApp() proxy.AppConns { + app := &testApp{} + cc := proxy.NewLocalClientCreator(app) + return proxy.NewAppConns(cc, proxy.NopMetrics()) +} + +func makeAndCommitGoodBlock( + state sm.State, + height int64, + lastCommit *types.Commit, + proposerAddr []byte, + blockExec *sm.BlockExecutor, + privVals map[string]types.PrivValidator, + evidence []types.Evidence, +) (sm.State, types.BlockID, *types.ExtendedCommit, error) { + // A good block passes + state, blockID, err := makeAndApplyGoodBlock(state, height, lastCommit, proposerAddr, blockExec, evidence) + if err != nil { + return state, types.BlockID{}, nil, err + } + + // Simulate a lastCommit for this block from all validators for the next height + commit, _, err := makeValidCommit(height, blockID, state.Validators, privVals) + if err != nil { + return state, types.BlockID{}, nil, err + } + return state, blockID, commit, nil +} + +func makeAndApplyGoodBlock(state sm.State, height int64, lastCommit *types.Commit, proposerAddr []byte, + blockExec *sm.BlockExecutor, evidence []types.Evidence, +) (sm.State, types.BlockID, error) { + block, err := state.MakeBlock(height, test.MakeNTxs(height, 10), lastCommit, evidence, proposerAddr) + if err != nil { + return state, types.BlockID{}, nil + } + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + if err != nil { + return state, types.BlockID{}, err + } + + if err := blockExec.ValidateBlock(state, block); err != nil { + return state, types.BlockID{}, err + } + blockID := types.BlockID{ + Hash: block.Hash(), + PartSetHeader: partSet.Header(), + } + state, err = blockExec.ApplyBlock(state, blockID, block) + if err != nil { + return state, types.BlockID{}, err + } + return state, blockID, nil +} + +func makeBlock(state sm.State, height int64, c *types.Commit) (*types.Block, error) { + return state.MakeBlock( + height, + test.MakeNTxs(state.LastBlockHeight, 10), + c, + nil, + state.Validators.GetProposer().Address, + ) +} + +func makeValidCommit( + height int64, + blockID types.BlockID, + vals *types.ValidatorSet, + privVals map[string]types.PrivValidator, +) (*types.ExtendedCommit, []*types.Vote, error) { + sigs := make([]types.ExtendedCommitSig, vals.Size()) + votes := make([]*types.Vote, vals.Size()) + for i := 0; i < vals.Size(); i++ { + _, val := vals.GetByIndex(int32(i)) + vote, err := types.MakeVote( + privVals[val.Address.String()], + chainID, + int32(i), + height, + 0, + cmtproto.PrecommitType, + blockID, + time.Now(), + ) + if err != nil { + return nil, nil, err + } + sigs[i] = vote.ExtendedCommitSig() + votes[i] = vote + } + return &types.ExtendedCommit{ + Height: height, + BlockID: blockID, + ExtendedSignatures: sigs, + }, votes, nil +} + +func makeState(nVals, height int) (sm.State, dbm.DB, map[string]types.PrivValidator) { + vals := make([]types.GenesisValidator, nVals) + privVals := make(map[string]types.PrivValidator, nVals) + for i := 0; i < nVals; i++ { + secret := []byte(fmt.Sprintf("test%d", i)) + pk := ed25519.GenPrivKeyFromSecret(secret) + valAddr := pk.PubKey().Address() + vals[i] = types.GenesisValidator{ + Address: valAddr, + PubKey: pk.PubKey(), + Power: 1000, + Name: fmt.Sprintf("test%d", i), + } + privVals[valAddr.String()] = types.NewMockPVWithParams(pk, false, false) + } + s, _ := sm.MakeGenesisState(&types.GenesisDoc{ + ChainID: chainID, + Validators: vals, + AppHash: nil, + }) + + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + if err := stateStore.Save(s); err != nil { + panic(err) + } + + for i := 1; i < height; i++ { + s.LastBlockHeight++ + s.LastValidators = s.Validators.Copy() + if err := stateStore.Save(s); err != nil { + panic(err) + } + } + + return s, stateDB, privVals +} + +func genValSet(size int) *types.ValidatorSet { + vals := make([]*types.Validator, size) + for i := 0; i < size; i++ { + vals[i] = types.NewValidator(ed25519.GenPrivKey().PubKey(), 10) + } + return types.NewValidatorSet(vals) +} + +func makeHeaderPartsResponsesValPubKeyChange( + state sm.State, + pubkey crypto.PubKey, +) (types.Header, types.BlockID, *abci.ResponseFinalizeBlock) { + block, err := makeBlock(state, state.LastBlockHeight+1, new(types.Commit)) + if err != nil { + return types.Header{}, types.BlockID{}, nil + } + abciResponses := &abci.ResponseFinalizeBlock{} + // If the pubkey is new, remove the old and add the new. + _, val := state.NextValidators.GetByIndex(0) + if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) { + abciResponses.ValidatorUpdates = []abci.ValidatorUpdate{ + types.TM2PB.NewValidatorUpdate(val.PubKey, 0), + types.TM2PB.NewValidatorUpdate(pubkey, 10), + } + } + + return block.Header, types.BlockID{Hash: block.Hash(), PartSetHeader: types.PartSetHeader{}}, abciResponses +} + +func makeHeaderPartsResponsesValPowerChange( + state sm.State, + power int64, +) (types.Header, types.BlockID, *abci.ResponseFinalizeBlock) { + block, err := makeBlock(state, state.LastBlockHeight+1, new(types.Commit)) + if err != nil { + return types.Header{}, types.BlockID{}, nil + } + abciResponses := &abci.ResponseFinalizeBlock{} + + // If the pubkey is new, remove the old and add the new. + _, val := state.NextValidators.GetByIndex(0) + if val.VotingPower != power { + abciResponses.ValidatorUpdates = []abci.ValidatorUpdate{ + types.TM2PB.NewValidatorUpdate(val.PubKey, power), + } + } + + return block.Header, types.BlockID{Hash: block.Hash(), PartSetHeader: types.PartSetHeader{}}, abciResponses +} + +func makeHeaderPartsResponsesParams( + state sm.State, + params cmtproto.ConsensusParams, +) (types.Header, types.BlockID, *abci.ResponseFinalizeBlock) { + block, err := makeBlock(state, state.LastBlockHeight+1, new(types.Commit)) + if err != nil { + return types.Header{}, types.BlockID{}, nil + } + abciResponses := &abci.ResponseFinalizeBlock{ + ConsensusParamUpdates: ¶ms, + } + return block.Header, types.BlockID{Hash: block.Hash(), PartSetHeader: types.PartSetHeader{}}, abciResponses +} + +func randomGenesisDoc() *types.GenesisDoc { + pubkey := ed25519.GenPrivKey().PubKey() + return &types.GenesisDoc{ + GenesisTime: cmttime.Now(), + ChainID: "abc", + Validators: []types.GenesisValidator{ + { + Address: pubkey.Address(), + PubKey: pubkey, + Power: 10, + Name: "myval", + }, + }, + ConsensusParams: types.DefaultConsensusParams(), + } +} + +//---------------------------------------------------------------------------- + +type testApp struct { + abci.BaseApplication + + CommitVotes []abci.VoteInfo + Misbehavior []abci.Misbehavior + LastTime time.Time + ValidatorUpdates []abci.ValidatorUpdate + AppHash []byte +} + +var _ abci.Application = (*testApp)(nil) + +func (app *testApp) FinalizeBlock(_ context.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { + app.CommitVotes = req.DecidedLastCommit.Votes + app.Misbehavior = req.Misbehavior + app.LastTime = req.Time + txResults := make([]*abci.ExecTxResult, len(req.Txs)) + for idx := range req.Txs { + txResults[idx] = &abci.ExecTxResult{ + Code: abci.CodeTypeOK, + } + } + + return &abci.ResponseFinalizeBlock{ + ValidatorUpdates: app.ValidatorUpdates, + ConsensusParamUpdates: &cmtproto.ConsensusParams{ + Version: &cmtproto.VersionParams{ + App: 1, + }, + }, + TxResults: txResults, + AppHash: app.AppHash, + }, nil +} + +func (app *testApp) Commit(_ context.Context, _ *abci.RequestCommit) (*abci.ResponseCommit, error) { + return &abci.ResponseCommit{RetainHeight: 1}, nil +} + +func (app *testApp) PrepareProposal( + _ context.Context, + req *abci.RequestPrepareProposal, +) (*abci.ResponsePrepareProposal, error) { + txs := make([][]byte, 0, len(req.Txs)) + var totalBytes int64 + for _, tx := range req.Txs { + if len(tx) == 0 { + continue + } + totalBytes += int64(len(tx)) + if totalBytes > req.MaxTxBytes { + break + } + txs = append(txs, tx) + } + return &abci.ResponsePrepareProposal{Txs: txs}, nil +} + +func (app *testApp) ProcessProposal( + _ context.Context, + req *abci.RequestProcessProposal, +) (*abci.ResponseProcessProposal, error) { + for _, tx := range req.Txs { + if len(tx) == 0 { + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + } + } + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil +} diff --git a/state/indexer/block.go b/state/indexer/block.go new file mode 100644 index 0000000..b00b4be --- /dev/null +++ b/state/indexer/block.go @@ -0,0 +1,27 @@ +package indexer + +import ( + "context" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/types" +) + +//go:generate ../../scripts/mockery_generate.sh BlockIndexer + +// BlockIndexer defines an interface contract for indexing block events. +type BlockIndexer interface { + // Has returns true if the given height has been indexed. An error is returned + // upon database query failure. + Has(height int64) (bool, error) + + // Index indexes FinalizeBlock events for a given block by its height. + Index(types.EventDataNewBlockEvents) error + + // Search performs a query for block heights that match a given FinalizeBlock + // event search criteria. + Search(ctx context.Context, q *query.Query) ([]int64, error) + + SetLogger(l log.Logger) +} diff --git a/state/indexer/block/indexer.go b/state/indexer/block/indexer.go new file mode 100644 index 0000000..210bd67 --- /dev/null +++ b/state/indexer/block/indexer.go @@ -0,0 +1,57 @@ +package block + +import ( + "errors" + "fmt" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/state/indexer" + blockidxkv "github.com/cometbft/cometbft/state/indexer/block/kv" + blockidxnull "github.com/cometbft/cometbft/state/indexer/block/null" + "github.com/cometbft/cometbft/state/indexer/sink/psql" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/state/txindex/kv" + "github.com/cometbft/cometbft/state/txindex/null" +) + +// IndexerFromConfig constructs a slice of indexer.EventSink using the provided +// configuration. +func IndexerFromConfig(cfg *config.Config, dbProvider config.DBProvider, chainID string) ( + txIdx txindex.TxIndexer, blockIdx indexer.BlockIndexer, err error, +) { + txidx, blkidx, _, err := IndexerFromConfigWithDisabledIndexers(cfg, dbProvider, chainID) + return txidx, blkidx, err +} + +// IndexerFromConfigWithDisabledIndexers constructs a slice of indexer.EventSink using the provided +// configuration. If all indexers are disabled in the configuration, it returns null indexers. +// Otherwise, it creates the appropriate indexers based on the configuration. +func IndexerFromConfigWithDisabledIndexers(cfg *config.Config, dbProvider config.DBProvider, chainID string) ( + txIdx txindex.TxIndexer, blockIdx indexer.BlockIndexer, allIndexersDisabled bool, err error, +) { + switch cfg.TxIndex.Indexer { + case "kv": + store, err := dbProvider(&config.DBContext{ID: "tx_index", Config: cfg}) + if err != nil { + return nil, nil, false, err + } + + return kv.NewTxIndex(store), blockidxkv.New(dbm.NewPrefixDB(store, []byte("block_events"))), false, nil + + case "psql": + conn := cfg.TxIndex.PsqlConn + if conn == "" { + return nil, nil, false, errors.New("the psql connection settings cannot be empty") + } + es, err := psql.NewEventSink(cfg.TxIndex.PsqlConn, chainID) + if err != nil { + return nil, nil, false, fmt.Errorf("creating psql indexer: %w", err) + } + return es.TxIndexer(), es.BlockIndexer(), false, nil + + default: + return &null.TxIndex{}, &blockidxnull.BlockerIndexer{}, true, nil + } +} diff --git a/state/indexer/block/kv/kv.go b/state/indexer/block/kv/kv.go new file mode 100644 index 0000000..ed8b706 --- /dev/null +++ b/state/indexer/block/kv/kv.go @@ -0,0 +1,617 @@ +package kv + +import ( + "bytes" + "context" + "errors" + "fmt" + "math/big" + "sort" + "strconv" + "strings" + + "github.com/google/orderedcode" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + idxutil "github.com/cometbft/cometbft/internal/indexer" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/types" +) + +var _ indexer.BlockIndexer = (*BlockerIndexer)(nil) + +// BlockerIndexer implements a block indexer, indexing FinalizeBlock +// events with an underlying KV store. Block events are indexed by their height, +// such that matching search criteria returns the respective block height(s). +type BlockerIndexer struct { + store dbm.DB + + // Add unique event identifier to use when querying + // Matching will be done both on height AND eventSeq + eventSeq int64 + log log.Logger +} + +func New(store dbm.DB) *BlockerIndexer { + return &BlockerIndexer{ + store: store, + } +} + +func (idx *BlockerIndexer) SetLogger(l log.Logger) { + idx.log = l +} + +// Has returns true if the given height has been indexed. An error is returned +// upon database query failure. +func (idx *BlockerIndexer) Has(height int64) (bool, error) { + key, err := heightKey(height) + if err != nil { + return false, fmt.Errorf("failed to create block height index key: %w", err) + } + + return idx.store.Has(key) +} + +// Index indexes FinalizeBlock events for a given block by its height. +// The following is indexed: +// +// primary key: encode(block.height | height) => encode(height) +// FinalizeBlock events: encode(eventType.eventAttr|eventValue|height|finalize_block|eventSeq) => encode(height) +func (idx *BlockerIndexer) Index(bh types.EventDataNewBlockEvents) error { + batch := idx.store.NewBatch() + defer batch.Close() + + height := bh.Height + + // 1. index by height + key, err := heightKey(height) + if err != nil { + return fmt.Errorf("failed to create block height index key: %w", err) + } + if err := batch.Set(key, int64ToBytes(height)); err != nil { + return err + } + + // 2. index block events + if err := idx.indexEvents(batch, bh.Events, height); err != nil { + return fmt.Errorf("failed to index FinalizeBlock events: %w", err) + } + + return batch.WriteSync() +} + +// Search performs a query for block heights that match a given FinalizeBlock +// event search criteria. The given query can match against zero, +// one or more block heights. In the case of height queries, i.e. block.height=H, +// if the height is indexed, that height alone will be returned. An error and +// nil slice is returned. Otherwise, a non-nil slice and nil error is returned. +func (idx *BlockerIndexer) Search(ctx context.Context, q *query.Query) ([]int64, error) { + results := make([]int64, 0) + select { + case <-ctx.Done(): + return results, nil + + default: + } + + conditions := q.Syntax() + + // conditions to skip because they're handled before "everything else" + skipIndexes := make([]int, 0) + + var ok bool + + var heightInfo HeightInfo + // If we are not matching events and block.height occurs more than once, the later value will + // overwrite the first one. + conditions, heightInfo, ok = dedupHeight(conditions) + + // Extract ranges. If both upper and lower bounds exist, it's better to get + // them in order as to not iterate over kvs that are not within range. + ranges, rangeIndexes, heightRange := indexer.LookForRangesWithHeight(conditions) + heightInfo.heightRange = heightRange + + // If we have additional constraints and want to query per event + // attributes, we cannot simply return all blocks for a height. + // But we remember the height we want to find and forward it to + // match(). If we only have the height constraint + // in the query (the second part of the ||), we don't need to query + // per event conditions and return all events within the height range. + if ok && heightInfo.onlyHeightEq { + ok, err := idx.Has(heightInfo.height) + if err != nil { + return nil, err + } + + if ok { + return []int64{heightInfo.height}, nil + } + + return results, nil + } + + var heightsInitialized bool + filteredHeights := make(map[string][]byte) + if heightInfo.heightEqIdx != -1 { + skipIndexes = append(skipIndexes, heightInfo.heightEqIdx) + } + + if len(ranges) > 0 { + skipIndexes = append(skipIndexes, rangeIndexes...) + + for _, qr := range ranges { + // If we have a query range over height and want to still look for + // specific event values we do not want to simply return all + // blocks in this height range. We remember the height range info + // and pass it on to match() to take into account when processing events. + if qr.Key == types.BlockHeightKey && !heightInfo.onlyHeightRange { + // If the query contains ranges other than the height then we need to treat the height + // range when querying the conditions of the other range. + // Otherwise we can just return all the blocks within the height range (as there is no + // additional constraint on events) + + continue + + } + prefix, err := orderedcode.Append(nil, qr.Key) + if err != nil { + return nil, fmt.Errorf("failed to create prefix key: %w", err) + } + + if !heightsInitialized { + filteredHeights, err = idx.matchRange(ctx, qr, prefix, filteredHeights, true, heightInfo) + if err != nil { + return nil, err + } + + heightsInitialized = true + + // Ignore any remaining conditions if the first condition resulted in no + // matches (assuming implicit AND operand). + if len(filteredHeights) == 0 { + break + } + } else { + filteredHeights, err = idx.matchRange(ctx, qr, prefix, filteredHeights, false, heightInfo) + if err != nil { + return nil, err + } + } + } + } + + // for all other conditions + for i, c := range conditions { + if intInSlice(i, skipIndexes) { + continue + } + + startKey, err := orderedcode.Append(nil, c.Tag, c.Arg.Value()) + if err != nil { + return nil, err + } + + if !heightsInitialized { + filteredHeights, err = idx.match(ctx, c, startKey, filteredHeights, true, heightInfo) + if err != nil { + return nil, err + } + + heightsInitialized = true + + // Ignore any remaining conditions if the first condition resulted in no + // matches (assuming implicit AND operand). + if len(filteredHeights) == 0 { + break + } + } else { + filteredHeights, err = idx.match(ctx, c, startKey, filteredHeights, false, heightInfo) + if err != nil { + return nil, err + } + } + } + + // fetch matching heights + results = make([]int64, 0, len(filteredHeights)) + resultMap := make(map[int64]struct{}) + +FOR_LOOP: + for _, hBz := range filteredHeights { + h := int64FromBytes(hBz) + + ok, err := idx.Has(h) + if err != nil { + return nil, err + } + if ok { + if _, ok := resultMap[h]; !ok { + resultMap[h] = struct{}{} + results = append(results, h) + } + } + + select { + case <-ctx.Done(): + break FOR_LOOP + + default: + } + } + + sort.Slice(results, func(i, j int) bool { return results[i] < results[j] }) + + return results, nil +} + +// matchRange returns all matching block heights that match a given QueryRange +// and start key. An already filtered result (filteredHeights) is provided such +// that any non-intersecting matches are removed. +// +// NOTE: The provided filteredHeights may be empty if no previous condition has +// matched. +func (idx *BlockerIndexer) matchRange( + ctx context.Context, + qr indexer.QueryRange, + startKey []byte, + filteredHeights map[string][]byte, + firstRun bool, + heightInfo HeightInfo, +) (map[string][]byte, error) { + // A previous match was attempted but resulted in no matches, so we return + // no matches (assuming AND operand). + if !firstRun && len(filteredHeights) == 0 { + return filteredHeights, nil + } + + tmpHeights := make(map[string][]byte) + + it, err := dbm.IteratePrefix(idx.store, startKey) + if err != nil { + return nil, fmt.Errorf("failed to create prefix iterator: %w", err) + } + defer it.Close() + +LOOP: + for ; it.Valid(); it.Next() { + var ( + eventValue string + err error + ) + + if qr.Key == types.BlockHeightKey { + eventValue, err = parseValueFromPrimaryKey(it.Key()) + } else { + eventValue, err = parseValueFromEventKey(it.Key()) + } + + if err != nil { + continue + } + + if _, ok := qr.AnyBound().(*big.Float); ok { + v := new(big.Int) + v, ok := v.SetString(eventValue, 10) + var vF *big.Float + if !ok { + // The precision here is 125. For numbers bigger than this, the value + // will not be parsed properly + vF, _, err = big.ParseFloat(eventValue, 10, 125, big.ToNearestEven) + if err != nil { + continue LOOP + } + } + + if qr.Key != types.BlockHeightKey { + keyHeight, err := parseHeightFromEventKey(it.Key()) + if err != nil { + idx.log.Error("failure to parse height from key:", err) + continue LOOP + } + withinHeight, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + idx.log.Error("failure checking for height bounds:", err) + continue LOOP + } + if !withinHeight { + continue LOOP + } + } + + var withinBounds bool + var err error + if !ok { + withinBounds, err = idxutil.CheckBounds(qr, vF) + } else { + withinBounds, err = idxutil.CheckBounds(qr, v) + } + if err != nil { + idx.log.Error("failed to parse bounds:", err) + } else { + if withinBounds { + idx.setTmpHeights(tmpHeights, it) + } + } + } + + select { + case <-ctx.Done(): + break LOOP + default: + } + } + + if err := it.Error(); err != nil { + return nil, err + } + + if len(tmpHeights) == 0 || firstRun { + // Either: + // + // 1. Regardless if a previous match was attempted, which may have had + // results, but no match was found for the current condition, then we + // return no matches (assuming AND operand). + // + // 2. A previous match was not attempted, so we return all results. + return tmpHeights, nil + } + + // Remove/reduce matches in filteredHashes that were not found in this + // match (tmpHashes). +FOR_LOOP: + for k, v := range filteredHeights { + tmpHeight := tmpHeights[k] + + // Check whether in this iteration we have not found an overlapping height (tmpHeight == nil) + // or whether the events in which the attributed occurred do not match (first part of the condition) + if tmpHeight == nil || !bytes.Equal(tmpHeight, v) { + delete(filteredHeights, k) + + select { + case <-ctx.Done(): + break FOR_LOOP + default: + } + } + } + + return filteredHeights, nil +} + +func (idx *BlockerIndexer) setTmpHeights(tmpHeights map[string][]byte, it dbm.Iterator) { + // If we return attributes that occur within the same events, then store the + // event sequence in the result map as well. + eventSeq, _ := parseEventSeqFromEventKey(it.Key()) + + // Copy the value because the iterator will be reused. + value := make([]byte, len(it.Value())) + copy(value, it.Value()) + + tmpHeights[string(value)+strconv.FormatInt(eventSeq, 10)] = value + +} + +// match returns all matching heights that meet a given query condition and start +// key. An already filtered result (filteredHeights) is provided such that any +// non-intersecting matches are removed. +// +// NOTE: The provided filteredHeights may be empty if no previous condition has +// matched. +func (idx *BlockerIndexer) match( + ctx context.Context, + c syntax.Condition, + startKeyBz []byte, + filteredHeights map[string][]byte, + firstRun bool, + heightInfo HeightInfo, +) (map[string][]byte, error) { + // A previous match was attempted but resulted in no matches, so we return + // no matches (assuming AND operand). + if !firstRun && len(filteredHeights) == 0 { + return filteredHeights, nil + } + + tmpHeights := make(map[string][]byte) + + switch c.Op { + case syntax.TEq: + it, err := dbm.IteratePrefix(idx.store, startKeyBz) + if err != nil { + return nil, fmt.Errorf("failed to create prefix iterator: %w", err) + } + defer it.Close() + + for ; it.Valid(); it.Next() { + + keyHeight, err := parseHeightFromEventKey(it.Key()) + if err != nil { + idx.log.Error("failure to parse height from key:", err) + continue + } + withinHeight, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + idx.log.Error("failure checking for height bounds:", err) + continue + } + if !withinHeight { + continue + } + + idx.setTmpHeights(tmpHeights, it) + + if err := ctx.Err(); err != nil { + break + } + } + + if err := it.Error(); err != nil { + return nil, err + } + + case syntax.TExists: + prefix, err := orderedcode.Append(nil, c.Tag) + if err != nil { + return nil, err + } + + it, err := dbm.IteratePrefix(idx.store, prefix) + if err != nil { + return nil, fmt.Errorf("failed to create prefix iterator: %w", err) + } + defer it.Close() + + LOOP_EXISTS: + for ; it.Valid(); it.Next() { + + keyHeight, err := parseHeightFromEventKey(it.Key()) + if err != nil { + idx.log.Error("failure to parse height from key:", err) + continue + } + withinHeight, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + idx.log.Error("failure checking for height bounds:", err) + continue + } + if !withinHeight { + continue + } + + idx.setTmpHeights(tmpHeights, it) + + select { + case <-ctx.Done(): + break LOOP_EXISTS + + default: + } + } + + if err := it.Error(); err != nil { + return nil, err + } + + case syntax.TContains: + prefix, err := orderedcode.Append(nil, c.Tag) + if err != nil { + return nil, err + } + + it, err := dbm.IteratePrefix(idx.store, prefix) + if err != nil { + return nil, fmt.Errorf("failed to create prefix iterator: %w", err) + } + defer it.Close() + + LOOP_CONTAINS: + for ; it.Valid(); it.Next() { + eventValue, err := parseValueFromEventKey(it.Key()) + if err != nil { + continue + } + + if strings.Contains(eventValue, c.Arg.Value()) { + keyHeight, err := parseHeightFromEventKey(it.Key()) + if err != nil { + idx.log.Error("failure to parse height from key:", err) + continue + } + withinHeight, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + idx.log.Error("failure checking for height bounds:", err) + continue + } + if !withinHeight { + continue + } + idx.setTmpHeights(tmpHeights, it) + } + + select { + case <-ctx.Done(): + break LOOP_CONTAINS + + default: + } + } + if err := it.Error(); err != nil { + return nil, err + } + + default: + return nil, errors.New("other operators should be handled already") + } + + if len(tmpHeights) == 0 || firstRun { + // Either: + // + // 1. Regardless if a previous match was attempted, which may have had + // results, but no match was found for the current condition, then we + // return no matches (assuming AND operand). + // + // 2. A previous match was not attempted, so we return all results. + return tmpHeights, nil + } + + // Remove/reduce matches in filteredHeights that were not found in this + // match (tmpHeights). +FOR_LOOP: + for k, v := range filteredHeights { + tmpHeight := tmpHeights[k] + if tmpHeight == nil || !bytes.Equal(tmpHeight, v) { + delete(filteredHeights, k) + + select { + case <-ctx.Done(): + break FOR_LOOP + + default: + } + } + } + + return filteredHeights, nil +} + +func (idx *BlockerIndexer) indexEvents(batch dbm.Batch, events []abci.Event, height int64) error { + heightBz := int64ToBytes(height) + + for _, event := range events { + idx.eventSeq = idx.eventSeq + 1 + // only index events with a non-empty type + if len(event.Type) == 0 { + continue + } + + for _, attr := range event.Attributes { + if len(attr.Key) == 0 { + continue + } + + // index iff the event specified index:true and it's not a reserved event + compositeKey := fmt.Sprintf("%s.%s", event.Type, attr.Key) + if compositeKey == types.BlockHeightKey { + return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeKey) + } + + if attr.GetIndex() { + key, err := eventKey(compositeKey, attr.Value, height, idx.eventSeq) + if err != nil { + return fmt.Errorf("failed to create block index key: %w", err) + } + + if err := batch.Set(key, heightBz); err != nil { + return err + } + } + } + } + + return nil +} diff --git a/state/indexer/block/kv/kv_test.go b/state/indexer/block/kv/kv_test.go new file mode 100644 index 0000000..18ce0c9 --- /dev/null +++ b/state/indexer/block/kv/kv_test.go @@ -0,0 +1,439 @@ +package kv_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + db "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + blockidxkv "github.com/cometbft/cometbft/state/indexer/block/kv" + "github.com/cometbft/cometbft/types" +) + +func TestBlockIndexer(t *testing.T) { + store := db.NewPrefixDB(db.NewMemDB(), []byte("block_events")) + indexer := blockidxkv.New(store) + + require.NoError(t, indexer.Index(types.EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{ + { + Type: "begin_event", + Attributes: []abci.EventAttribute{ + { + Key: "proposer", + Value: "FCAA001", + Index: true, + }, + }, + }, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "100", + Index: true, + }, + }, + }, + }, + })) + + for i := 2; i < 12; i++ { + var index bool + if i%2 == 0 { + index = true + } + + require.NoError(t, indexer.Index(types.EventDataNewBlockEvents{ + Height: int64(i), + Events: []abci.Event{ + { + Type: "begin_event", + Attributes: []abci.EventAttribute{ + { + Key: "proposer", + Value: "FCAA001", + Index: true, + }, + }, + }, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: fmt.Sprintf("%d", i), + Index: index, + }, + }, + }, + }, + })) + } + + testCases := map[string]struct { + q *query.Query + results []int64 + }{ + "block.height = 100": { + q: query.MustCompile(`block.height = 100`), + results: []int64{}, + }, + "block.height = 5": { + q: query.MustCompile(`block.height = 5`), + results: []int64{5}, + }, + "begin_event.key1 = 'value1'": { + q: query.MustCompile(`begin_event.key1 = 'value1'`), + results: []int64{}, + }, + "begin_event.proposer = 'FCAA001'": { + q: query.MustCompile(`begin_event.proposer = 'FCAA001'`), + results: []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + }, + "end_event.foo <= 5": { + q: query.MustCompile(`end_event.foo <= 5`), + results: []int64{2, 4}, + }, + "end_event.foo >= 100": { + q: query.MustCompile(`end_event.foo >= 100`), + results: []int64{1}, + }, + "block.height > 2 AND end_event.foo <= 8": { + q: query.MustCompile(`block.height > 2 AND end_event.foo <= 8`), + results: []int64{4, 6, 8}, + }, + "end_event.foo > 100": { + q: query.MustCompile("end_event.foo > 100"), + results: []int64{}, + }, + "block.height >= 2 AND end_event.foo < 8": { + q: query.MustCompile("block.height >= 2 AND end_event.foo < 8"), + results: []int64{2, 4, 6}, + }, + "begin_event.proposer CONTAINS 'FFFFFFF'": { + q: query.MustCompile(`begin_event.proposer CONTAINS 'FFFFFFF'`), + results: []int64{}, + }, + "begin_event.proposer CONTAINS 'FCAA001'": { + q: query.MustCompile(`begin_event.proposer CONTAINS 'FCAA001'`), + results: []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + }, + "end_event.foo CONTAINS '1'": { + q: query.MustCompile("end_event.foo CONTAINS '1'"), + results: []int64{1, 10}, + }, + } + + for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { + results, err := indexer.Search(context.Background(), tc.q) + require.NoError(t, err) + require.Equal(t, tc.results, results) + }) + } +} + +func TestBlockIndexerMulti(t *testing.T) { + store := db.NewPrefixDB(db.NewMemDB(), []byte("block_events")) + indexer := blockidxkv.New(store) + + require.NoError(t, indexer.Index(types.EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{ + {}, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "100", + Index: true, + }, + { + Key: "bar", + Value: "200", + Index: true, + }, + }, + }, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "300", + Index: true, + }, + { + Key: "bar", + Value: "500", + Index: true, + }, + }, + }, + }, + })) + + require.NoError(t, indexer.Index(types.EventDataNewBlockEvents{ + Height: 2, + Events: []abci.Event{ + {}, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "100", + Index: true, + }, + { + Key: "bar", + Value: "200", + Index: true, + }, + }, + }, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "300", + Index: true, + }, + { + Key: "bar", + Value: "400", + Index: true, + }, + }, + }, + }, + })) + + testCases := map[string]struct { + q *query.Query + results []int64 + }{ + + "query return all events from a height - exact": { + q: query.MustCompile("block.height = 1"), + results: []int64{1}, + }, + "query return all events from a height - exact (deduplicate height)": { + q: query.MustCompile("block.height = 1 AND block.height = 2"), + results: []int64{1}, + }, + "query return all events from a height - range": { + q: query.MustCompile("block.height < 2 AND block.height > 0 AND block.height > 0"), + results: []int64{1}, + }, + "query return all events from a height - range 2": { + q: query.MustCompile("block.height < 3 AND block.height < 2 AND block.height > 0 AND block.height > 0"), + results: []int64{1}, + }, + "query return all events from a height - range 3": { + q: query.MustCompile("block.height < 1 AND block.height > 1"), + results: []int64{}, + }, + "query matches fields from same event": { + q: query.MustCompile("end_event.bar < 300 AND end_event.foo = 100 AND block.height > 0 AND block.height <= 2"), + results: []int64{1, 2}, + }, + "query matches fields from multiple events": { + q: query.MustCompile("end_event.foo = 100 AND end_event.bar = 400 AND block.height = 2"), + results: []int64{}, + }, + "query matches fields from multiple events 2": { + q: query.MustCompile("end_event.foo = 100 AND end_event.bar > 200 AND block.height > 0 AND block.height < 3"), + results: []int64{}, + }, + "query matches fields from multiple events allowed": { + q: query.MustCompile("end_event.foo = 100 AND end_event.bar = 400"), + results: []int64{}, + }, + "query matches fields from all events whose attribute is within range": { + q: query.MustCompile("block.height = 2 AND end_event.foo < 300"), + results: []int64{2}, + }, + "match attributes across events with height constraint": { + q: query.MustCompile("end_event.foo = 100 AND end_event.bar = 400 AND block.height = 2"), + results: []int64{}, + }, + "query using CONTAINS matches fields from all events whose attribute is within range": { + q: query.MustCompile("block.height = 2 AND end_event.foo CONTAINS '30'"), + results: []int64{2}, + }, + "query matches all fields from multiple events": { + q: query.MustCompile("end_event.bar > 100 AND end_event.bar <= 500"), + results: []int64{1, 2}, + }, + "query with height range and height equality - should ignore equality": { + q: query.MustCompile("block.height = 2 AND end_event.foo >= 100 AND block.height < 2"), + results: []int64{1}, + }, + "query with non-existent field": { + q: query.MustCompile("end_event.baz = 100"), + results: []int64{}, + }, + "query with non-existent field ": { + q: query.MustCompile("end_event.baz = 100"), + results: []int64{}, + }, + } + + for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { + results, err := indexer.Search(context.Background(), tc.q) + require.NoError(t, err) + require.Equal(t, tc.results, results) + }) + } +} + +func TestBigInt(t *testing.T) { + + bigInt := "10000000000000000000" + bigFloat := bigInt + ".76" + bigFloatLower := bigInt + ".1" + bigIntSmaller := "9999999999999999999" + store := db.NewPrefixDB(db.NewMemDB(), []byte("block_events")) + indexer := blockidxkv.New(store) + + require.NoError(t, indexer.Index(types.EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{ + {}, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: "100", + Index: true, + }, + { + Key: "bar", + Value: bigFloat, + Index: true, + }, + { + Key: "bar_lower", + Value: bigFloatLower, + Index: true, + }, + }, + }, + { + Type: "end_event", + Attributes: []abci.EventAttribute{ + { + Key: "foo", + Value: bigInt, + Index: true, + }, + { + Key: "bar", + Value: "500", + Index: true, + }, + { + Key: "bla", + Value: "500.5", + Index: true, + }, + }, + }, + }, + }, + )) + + testCases := map[string]struct { + q *query.Query + results []int64 + }{ + + "query return all events from a height - exact": { + q: query.MustCompile("block.height = 1"), + results: []int64{1}, + }, + "query return all events from a height - exact (deduplicate height)": { + q: query.MustCompile("block.height = 1 AND block.height = 2"), + results: []int64{1}, + }, + "query return all events from a height - range": { + q: query.MustCompile("block.height < 2 AND block.height > 0 AND block.height > 0"), + results: []int64{1}, + }, + "query matches fields with big int and height - no match": { + q: query.MustCompile("end_event.foo = " + bigInt + " AND end_event.bar = 500 AND block.height = 2"), + results: []int64{}, + }, + "query matches fields with big int with less and height - no match": { + q: query.MustCompile("end_event.foo <= " + bigInt + " AND end_event.bar = 500 AND block.height = 2"), + results: []int64{}, + }, + "query matches fields with big int and height - match": { + q: query.MustCompile("end_event.foo = " + bigInt + " AND end_event.bar = 500 AND block.height = 1"), + results: []int64{1}, + }, + "query matches big int in range": { + q: query.MustCompile("end_event.foo = " + bigInt), + results: []int64{1}, + }, + "query matches big int in range with float with equality ": { + q: query.MustCompile("end_event.bar >= " + bigInt), + results: []int64{1}, + }, + "query matches big int in range with float ": { + q: query.MustCompile("end_event.bar > " + bigInt), + results: []int64{1}, + }, + "query matches big int in range with float lower dec point ": { + q: query.MustCompile("end_event.bar_lower > " + bigInt), + results: []int64{1}, + }, + "query matches big int in range with float with less - found": { + q: query.MustCompile("end_event.foo <= " + bigInt), + results: []int64{1}, + }, + "query matches big int in range with float with less with height range - found": { + q: query.MustCompile("end_event.foo <= " + bigInt + " AND block.height > 0"), + results: []int64{1}, + }, + "query matches big int in range with float with less - not found": { + q: query.MustCompile("end_event.foo < " + bigInt + " AND end_event.foo > 100"), + results: []int64{}, + }, + "query does not parse float": { + q: query.MustCompile("end_event.bla >= 500"), + results: []int64{1}, + }, + "query condition float": { + q: query.MustCompile("end_event.bla < " + bigFloat), + results: []int64{1}, + }, + "query condition big int plus one": { + q: query.MustCompile("end_event.foo > " + bigIntSmaller), + results: []int64{1}, + }, + } + for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { + results, err := indexer.Search(context.Background(), tc.q) + require.NoError(t, err) + require.Equal(t, tc.results, results) + }) + } +} diff --git a/state/indexer/block/kv/util.go b/state/indexer/block/kv/util.go new file mode 100644 index 0000000..d4a353c --- /dev/null +++ b/state/indexer/block/kv/util.go @@ -0,0 +1,211 @@ +package kv + +import ( + "encoding/binary" + "fmt" + "math/big" + "strconv" + + "github.com/google/orderedcode" + + idxutil "github.com/cometbft/cometbft/internal/indexer" + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/types" +) + +type HeightInfo struct { + heightRange indexer.QueryRange + height int64 + heightEqIdx int + onlyHeightRange bool + onlyHeightEq bool +} + +func intInSlice(a int, list []int) bool { + for _, b := range list { + if b == a { + return true + } + } + + return false +} + +func int64FromBytes(bz []byte) int64 { + v, _ := binary.Varint(bz) + return v +} + +func int64ToBytes(i int64) []byte { + buf := make([]byte, binary.MaxVarintLen64) + n := binary.PutVarint(buf, i) + return buf[:n] +} + +func heightKey(height int64) ([]byte, error) { + return orderedcode.Append( + nil, + types.BlockHeightKey, + height, + ) +} + +func eventKey(compositeKey, eventValue string, height int64, eventSeq int64) ([]byte, error) { + return orderedcode.Append( + nil, + compositeKey, + eventValue, + height, + eventSeq, + ) +} + +func parseValueFromPrimaryKey(key []byte) (string, error) { + var ( + compositeKey string + height int64 + ) + + remaining, err := orderedcode.Parse(string(key), &compositeKey, &height) + if err != nil { + return "", fmt.Errorf("failed to parse event key: %w", err) + } + + if len(remaining) != 0 { + return "", fmt.Errorf("unexpected remainder in key: %s", remaining) + } + + return strconv.FormatInt(height, 10), nil +} + +func parseValueFromEventKey(key []byte) (string, error) { + var ( + compositeKey, eventValue string + height int64 + ) + + _, err := orderedcode.Parse(string(key), &compositeKey, &eventValue, &height) + if err != nil { + return "", fmt.Errorf("failed to parse event key: %w", err) + } + + return eventValue, nil +} + +func parseHeightFromEventKey(key []byte) (int64, error) { + var ( + compositeKey, eventValue string + height int64 + ) + + _, err := orderedcode.Parse(string(key), &compositeKey, &eventValue, &height) + if err != nil { + return -1, fmt.Errorf("failed to parse event key: %w", err) + } + + return height, nil +} + +func parseEventSeqFromEventKey(key []byte) (int64, error) { + var ( + compositeKey, eventValue string + height int64 + eventSeq int64 + ) + + remaining, err := orderedcode.Parse(string(key), &compositeKey, &eventValue, &height) + if err != nil { + return 0, fmt.Errorf("failed to parse event sequence: %w", err) + } + + // We either have an event sequence or a function type (potentially) followed by an event sequence. + // Potential scenarios: + // 1. Events indexed with v0.38.x and later, will only have an event sequence + // 2. Events indexed between v0.34.27 and v0.37.x will have a function type and an event sequence + // 3. Events indexed before v0.34.27 will only have a function type + // function_type = 'being_block_event' | 'end_block_event' + + if len(remaining) == 0 { // The event was not properly indexed + return 0, fmt.Errorf("failed to parse event sequence, invalid event format") + } + var typ string + remaining2, err := orderedcode.Parse(remaining, &typ) // Check if we have scenarios 2. or 3. (described above). + if err != nil { // If it cannot parse the event function type, it could be 1. + remaining, err2 := orderedcode.Parse(string(key), &compositeKey, &eventValue, &height, &eventSeq) + if err2 != nil || len(remaining) != 0 { // We should not have anything else after the eventSeq. + return 0, fmt.Errorf("failed to parse event sequence: %w; and %w", err, err2) + } + } else if len(remaining2) != 0 { // Are we in case 2 or 3 + remaining, err2 := orderedcode.Parse(remaining2, &eventSeq) // the event follows the scenario in 2., + // retrieve the eventSeq + // there should be no error + if err2 != nil || len(remaining) != 0 { // We should not have anything else after the eventSeq if in 2. + return 0, fmt.Errorf("failed to parse event sequence: %w", err2) + } + } + return eventSeq, nil +} + +// Remove all occurrences of height equality queries except one. While we are traversing the conditions, check whether the only condition in +// addition to match events is the height equality or height range query. At the same time, if we do have a height range condition +// ignore the height equality condition. If a height equality exists, place the condition index in the query and the desired height +// into the heightInfo struct +func dedupHeight(conditions []syntax.Condition) (dedupConditions []syntax.Condition, heightInfo HeightInfo, found bool) { + heightInfo.heightEqIdx = -1 + heightRangeExists := false + var heightCondition []syntax.Condition + heightInfo.onlyHeightEq = true + heightInfo.onlyHeightRange = true + for _, c := range conditions { + if c.Tag == types.BlockHeightKey { + if c.Op == syntax.TEq { + if found || heightRangeExists { + continue + } + hFloat := c.Arg.Number() + if hFloat != nil { + h, _ := hFloat.Int64() + heightInfo.height = h + heightCondition = append(heightCondition, c) + found = true + } + } else { + heightInfo.onlyHeightEq = false + heightRangeExists = true + dedupConditions = append(dedupConditions, c) + } + } else { + heightInfo.onlyHeightRange = false + heightInfo.onlyHeightEq = false + dedupConditions = append(dedupConditions, c) + } + } + if !heightRangeExists && len(heightCondition) != 0 { + heightInfo.heightEqIdx = len(dedupConditions) + heightInfo.onlyHeightRange = false + dedupConditions = append(dedupConditions, heightCondition...) + } else { + // If we found a range make sure we set the hegiht idx to -1 as the height equality + // will be removed + heightInfo.heightEqIdx = -1 + heightInfo.height = 0 + heightInfo.onlyHeightEq = false + found = false + } + return dedupConditions, heightInfo, found +} + +func checkHeightConditions(heightInfo HeightInfo, keyHeight int64) (bool, error) { + if heightInfo.heightRange.Key != "" { + withinBounds, err := idxutil.CheckBounds(heightInfo.heightRange, big.NewInt(keyHeight)) + if err != nil || !withinBounds { + return false, err + } + } else { + if heightInfo.height != 0 && keyHeight != heightInfo.height { + return false, nil + } + } + return true, nil +} diff --git a/state/indexer/block/null/null.go b/state/indexer/block/null/null.go new file mode 100644 index 0000000..7c50531 --- /dev/null +++ b/state/indexer/block/null/null.go @@ -0,0 +1,31 @@ +package null + +import ( + "context" + "errors" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/types" +) + +var _ indexer.BlockIndexer = (*BlockerIndexer)(nil) + +// TxIndex implements a no-op block indexer. +type BlockerIndexer struct{} + +func (idx *BlockerIndexer) Has(int64) (bool, error) { + return false, errors.New(`indexing is disabled (set 'tx_index = "kv"' in config)`) +} + +func (idx *BlockerIndexer) Index(types.EventDataNewBlockEvents) error { + return nil +} + +func (idx *BlockerIndexer) Search(context.Context, *query.Query) ([]int64, error) { + return []int64{}, nil +} + +func (idx *BlockerIndexer) SetLogger(log.Logger) { +} diff --git a/state/indexer/mocks/block_indexer.go b/state/indexer/mocks/block_indexer.go new file mode 100644 index 0000000..21a2261 --- /dev/null +++ b/state/indexer/mocks/block_indexer.go @@ -0,0 +1,115 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + log "github.com/cometbft/cometbft/libs/log" + + mock "github.com/stretchr/testify/mock" + + query "github.com/cometbft/cometbft/libs/pubsub/query" + + types "github.com/cometbft/cometbft/types" +) + +// BlockIndexer is an autogenerated mock type for the BlockIndexer type +type BlockIndexer struct { + mock.Mock +} + +// Has provides a mock function with given fields: height +func (_m *BlockIndexer) Has(height int64) (bool, error) { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for Has") + } + + var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(int64) (bool, error)); ok { + return rf(height) + } + if rf, ok := ret.Get(0).(func(int64) bool); ok { + r0 = rf(height) + } else { + r0 = ret.Get(0).(bool) + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Index provides a mock function with given fields: _a0 +func (_m *BlockIndexer) Index(_a0 types.EventDataNewBlockEvents) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Index") + } + + var r0 error + if rf, ok := ret.Get(0).(func(types.EventDataNewBlockEvents) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Search provides a mock function with given fields: ctx, q +func (_m *BlockIndexer) Search(ctx context.Context, q *query.Query) ([]int64, error) { + ret := _m.Called(ctx, q) + + if len(ret) == 0 { + panic("no return value specified for Search") + } + + var r0 []int64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *query.Query) ([]int64, error)); ok { + return rf(ctx, q) + } + if rf, ok := ret.Get(0).(func(context.Context, *query.Query) []int64); ok { + r0 = rf(ctx, q) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int64) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *query.Query) error); ok { + r1 = rf(ctx, q) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SetLogger provides a mock function with given fields: l +func (_m *BlockIndexer) SetLogger(l log.Logger) { + _m.Called(l) +} + +// NewBlockIndexer creates a new instance of BlockIndexer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockIndexer(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockIndexer { + mock := &BlockIndexer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/state/indexer/query_range.go b/state/indexer/query_range.go new file mode 100644 index 0000000..80bd0e6 --- /dev/null +++ b/state/indexer/query_range.go @@ -0,0 +1,205 @@ +package indexer + +import ( + "math/big" + "time" + + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" + "github.com/cometbft/cometbft/types" +) + +// QueryRanges defines a mapping between a composite event key and a QueryRange. +// +// e.g.account.number => queryRange{lowerBound: 1, upperBound: 5} +type QueryRanges map[string]QueryRange + +// QueryRange defines a range within a query condition. +type QueryRange struct { + LowerBound interface{} // int || time.Time + UpperBound interface{} // int || time.Time + Key string + IncludeLowerBound bool + IncludeUpperBound bool +} + +// AnyBound returns either the lower bound if non-nil, otherwise the upper bound. +func (qr QueryRange) AnyBound() interface{} { + if qr.LowerBound != nil { + return qr.LowerBound + } + + return qr.UpperBound +} + +// LowerBoundValue returns the value for the lower bound. If the lower bound is +// nil, nil will be returned. +func (qr QueryRange) LowerBoundValue() interface{} { + if qr.LowerBound == nil { + return nil + } + + if qr.IncludeLowerBound { + return qr.LowerBound + } + + switch t := qr.LowerBound.(type) { + case int64: + return t + 1 + case *big.Int: + tmp := new(big.Int) + return tmp.Add(t, big.NewInt(1)) + + case *big.Float: + // For floats we cannot simply add one as the float to float + // comparison is more finegrained. + // When comparing to integers, adding one is also incorrect: + // example: x >100.2 ; x = 101 float increased to 101.2 and condition + // is not satisfied + return t + case time.Time: + return t.Unix() + 1 + + default: + panic("not implemented") + } +} + +// UpperBoundValue returns the value for the upper bound. If the upper bound is +// nil, nil will be returned. +func (qr QueryRange) UpperBoundValue() interface{} { + if qr.UpperBound == nil { + return nil + } + + if qr.IncludeUpperBound { + return qr.UpperBound + } + + switch t := qr.UpperBound.(type) { + case int64: + return t - 1 + case *big.Int: + tmp := new(big.Int) + return tmp.Sub(t, big.NewInt(1)) + case *big.Float: + return t + case time.Time: + return t.Unix() - 1 + + default: + panic("not implemented") + } +} + +// LookForRangesWithHeight returns a mapping of QueryRanges and the matching indexes in +// the provided query conditions. +func LookForRangesWithHeight(conditions []syntax.Condition) (queryRange QueryRanges, indexes []int, heightRange QueryRange) { + queryRange = make(QueryRanges) + for i, c := range conditions { + if IsRangeOperation(c.Op) { + heightKey := c.Tag == types.BlockHeightKey || c.Tag == types.TxHeightKey + r, ok := queryRange[c.Tag] + if !ok { + r = QueryRange{Key: c.Tag} + if c.Tag == types.BlockHeightKey || c.Tag == types.TxHeightKey { + heightRange = QueryRange{Key: c.Tag} + } + } + + switch c.Op { + case syntax.TGt: + if heightKey { + heightRange.LowerBound = conditionArg(c) + } + r.LowerBound = conditionArg(c) + + case syntax.TGeq: + r.IncludeLowerBound = true + r.LowerBound = conditionArg(c) + if heightKey { + heightRange.IncludeLowerBound = true + heightRange.LowerBound = conditionArg(c) + } + + case syntax.TLt: + r.UpperBound = conditionArg(c) + if heightKey { + heightRange.UpperBound = conditionArg(c) + } + + case syntax.TLeq: + r.IncludeUpperBound = true + r.UpperBound = conditionArg(c) + if heightKey { + heightRange.IncludeUpperBound = true + heightRange.UpperBound = conditionArg(c) + } + } + + queryRange[c.Tag] = r + indexes = append(indexes, i) + } + } + + return queryRange, indexes, heightRange +} + +// Deprecated: This function is not used anymore and will be replaced with LookForRangesWithHeight +func LookForRanges(conditions []syntax.Condition) (ranges QueryRanges, indexes []int) { + ranges = make(QueryRanges) + for i, c := range conditions { + if IsRangeOperation(c.Op) { + r, ok := ranges[c.Tag] + if !ok { + r = QueryRange{Key: c.Tag} + } + + switch c.Op { + case syntax.TGt: + r.LowerBound = conditionArg(c) + + case syntax.TGeq: + r.IncludeLowerBound = true + r.LowerBound = conditionArg(c) + + case syntax.TLt: + r.UpperBound = conditionArg(c) + + case syntax.TLeq: + r.IncludeUpperBound = true + r.UpperBound = conditionArg(c) + } + + ranges[c.Tag] = r + indexes = append(indexes, i) + } + } + + return ranges, indexes +} + +// IsRangeOperation returns a boolean signifying if a query Operator is a range +// operation or not. +func IsRangeOperation(op syntax.Token) bool { + switch op { + case syntax.TGt, syntax.TGeq, syntax.TLt, syntax.TLeq: + return true + + default: + return false + } +} + +func conditionArg(c syntax.Condition) interface{} { + if c.Arg == nil { + return nil + } + switch c.Arg.Type { + case syntax.TNumber: + return c.Arg.Number() + case syntax.TTime, syntax.TDate: + return c.Arg.Time() + default: + return c.Arg.Value() // string + } +} diff --git a/state/indexer/sink/psql/backport.go b/state/indexer/sink/psql/backport.go new file mode 100644 index 0000000..3ff4399 --- /dev/null +++ b/state/indexer/sink/psql/backport.go @@ -0,0 +1,93 @@ +package psql + +// This file adds code to the psql package that is needed for integration with +// v0.34, but which is not part of the original implementation. +// +// In v0.35, ADR 65 was implemented in which the TxIndexer and BlockIndexer +// interfaces were merged into a hybrid EventSink interface. The Backport* +// types defined here bridge the psql EventSink (which was built in terms of +// the v0.35 interface) to the old interfaces. +// +// We took this narrower approach to backporting to avoid pulling in a much +// wider-reaching set of changes in v0.35 that would have broken several of the +// v0.34.x APIs. The result is sufficient to work with the node plumbing as it +// exists in the v0.34 branch. + +import ( + "context" + "errors" + + "github.com/cometbft/cometbft/libs/log" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/types" +) + +const ( + eventTypeFinalizeBlock = "finalize_block" +) + +// TxIndexer returns a bridge from es to the CometBFT v0.34 transaction indexer. +func (es *EventSink) TxIndexer() BackportTxIndexer { + return BackportTxIndexer{psql: es} +} + +// BackportTxIndexer implements the txindex.TxIndexer interface by delegating +// indexing operations to an underlying PostgreSQL event sink. +type BackportTxIndexer struct{ psql *EventSink } + +// AddBatch indexes a batch of transactions in Postgres, as part of TxIndexer. +func (b BackportTxIndexer) AddBatch(batch *txindex.Batch) error { + return b.psql.IndexTxEvents(batch.Ops) +} + +// Index indexes a single transaction result in Postgres, as part of TxIndexer. +func (b BackportTxIndexer) Index(txr *abci.TxResult) error { + return b.psql.IndexTxEvents([]*abci.TxResult{txr}) +} + +// Get is implemented to satisfy the TxIndexer interface, but is not supported +// by the psql event sink and reports an error for all inputs. +func (BackportTxIndexer) Get([]byte) (*abci.TxResult, error) { + return nil, errors.New("the TxIndexer.Get method is not supported") +} + +// Search is implemented to satisfy the TxIndexer interface, but it is not +// supported by the psql event sink and reports an error for all inputs. +func (BackportTxIndexer) Search(context.Context, *query.Query) ([]*abci.TxResult, error) { + return nil, errors.New("the TxIndexer.Search method is not supported") +} + +func (BackportTxIndexer) SetLogger(log.Logger) {} + +// BlockIndexer returns a bridge that implements the CometBFT v0.34 block +// indexer interface, using the Postgres event sink as a backing store. +func (es *EventSink) BlockIndexer() BackportBlockIndexer { + return BackportBlockIndexer{psql: es} +} + +// BackportBlockIndexer implements the indexer.BlockIndexer interface by +// delegating indexing operations to an underlying PostgreSQL event sink. +type BackportBlockIndexer struct{ psql *EventSink } + +// Has is implemented to satisfy the BlockIndexer interface, but it is not +// supported by the psql event sink and reports an error for all inputs. +func (BackportBlockIndexer) Has(_ int64) (bool, error) { + return false, errors.New("the BlockIndexer.Has method is not supported") +} + +// Index indexes block begin and end events for the specified block. It is +// part of the BlockIndexer interface. +func (b BackportBlockIndexer) Index(block types.EventDataNewBlockEvents) error { + return b.psql.IndexBlockEvents(block) +} + +// Search is implemented to satisfy the BlockIndexer interface, but it is not +// supported by the psql event sink and reports an error for all inputs. +func (BackportBlockIndexer) Search(context.Context, *query.Query) ([]int64, error) { + return nil, errors.New("the BlockIndexer.Search method is not supported") +} + +func (BackportBlockIndexer) SetLogger(log.Logger) {} diff --git a/state/indexer/sink/psql/backport_test.go b/state/indexer/sink/psql/backport_test.go new file mode 100644 index 0000000..e977896 --- /dev/null +++ b/state/indexer/sink/psql/backport_test.go @@ -0,0 +1,11 @@ +package psql + +import ( + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/txindex" +) + +var ( + _ indexer.BlockIndexer = BackportBlockIndexer{} + _ txindex.TxIndexer = BackportTxIndexer{} +) diff --git a/state/indexer/sink/psql/psql.go b/state/indexer/sink/psql/psql.go new file mode 100644 index 0000000..e379f44 --- /dev/null +++ b/state/indexer/sink/psql/psql.go @@ -0,0 +1,256 @@ +// Package psql implements an event sink backed by a PostgreSQL database. +package psql + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "github.com/cosmos/gogoproto/proto" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/types" +) + +const ( + tableBlocks = "blocks" + tableTxResults = "tx_results" + tableEvents = "events" + tableAttributes = "attributes" + driverName = "postgres" +) + +// EventSink is an indexer backend providing the tx/block index services. This +// implementation stores records in a PostgreSQL database using the schema +// defined in state/indexer/sink/psql/schema.sql. +type EventSink struct { + store *sql.DB + chainID string +} + +// NewEventSink constructs an event sink associated with the PostgreSQL +// database specified by connStr. Events written to the sink are attributed to +// the specified chainID. +func NewEventSink(connStr, chainID string) (*EventSink, error) { + db, err := sql.Open(driverName, connStr) + if err != nil { + return nil, err + } + + return &EventSink{ + store: db, + chainID: chainID, + }, nil +} + +// DB returns the underlying Postgres connection used by the sink. +// This is exported to support testing. +func (es *EventSink) DB() *sql.DB { return es.store } + +// runInTransaction executes query in a fresh database transaction. +// If query reports an error, the transaction is rolled back and the +// error from query is reported to the caller. +// Otherwise, the result of committing the transaction is returned. +func runInTransaction(db *sql.DB, query func(*sql.Tx) error) error { + dbtx, err := db.Begin() + if err != nil { + return err + } + if err := query(dbtx); err != nil { + _ = dbtx.Rollback() // report the initial error, not the rollback + return err + } + return dbtx.Commit() +} + +// queryWithID executes the specified SQL query with the given arguments, +// expecting a single-row, single-column result containing an ID. If the query +// succeeds, the ID from the result is returned. +func queryWithID(tx *sql.Tx, query string, args ...interface{}) (uint32, error) { + var id uint32 + if err := tx.QueryRow(query, args...).Scan(&id); err != nil { + return 0, err + } + return id, nil +} + +// insertEvents inserts a slice of events and any indexed attributes of those +// events into the database associated with dbtx. +// +// If txID > 0, the event is attributed to the transaction with that +// ID; otherwise it is recorded as a block event. +func insertEvents(dbtx *sql.Tx, blockID, txID uint32, evts []abci.Event) error { + // Populate the transaction ID field iff one is defined (> 0). + var txIDArg interface{} + if txID > 0 { + txIDArg = txID + } + + const ( + insertEventQuery = ` + INSERT INTO ` + tableEvents + ` (block_id, tx_id, type) + VALUES ($1, $2, $3) + RETURNING rowid; + ` + insertAttributeQuery = ` + INSERT INTO ` + tableAttributes + ` (event_id, key, composite_key, value) + VALUES ($1, $2, $3, $4); + ` + ) + + // Add each event to the events table, and retrieve its row ID to use when + // adding any attributes the event provides. + for _, evt := range evts { + // Skip events with an empty type. + if evt.Type == "" { + continue + } + + eid, err := queryWithID(dbtx, insertEventQuery, blockID, txIDArg, evt.Type) + if err != nil { + return err + } + + // Add any attributes flagged for indexing. + for _, attr := range evt.Attributes { + if !attr.Index { + continue + } + compositeKey := evt.Type + "." + attr.Key + if _, err := dbtx.Exec(insertAttributeQuery, eid, attr.Key, compositeKey, attr.Value); err != nil { + return err + } + } + } + return nil +} + +// makeIndexedEvent constructs an event from the specified composite key and +// value. If the key has the form "type.name", the event will have a single +// attribute with that name and the value; otherwise the event will have only +// a type and no attributes. +func makeIndexedEvent(compositeKey, value string) abci.Event { + i := strings.Index(compositeKey, ".") + if i < 0 { + return abci.Event{Type: compositeKey} + } + return abci.Event{Type: compositeKey[:i], Attributes: []abci.EventAttribute{ + {Key: compositeKey[i+1:], Value: value, Index: true}, + }} +} + +// IndexBlockEvents indexes the specified block header, part of the +// indexer.EventSink interface. +func (es *EventSink) IndexBlockEvents(h types.EventDataNewBlockEvents) error { + ts := time.Now().UTC() + + return runInTransaction(es.store, func(dbtx *sql.Tx) error { + // Add the block to the blocks table and report back its row ID for use + // in indexing the events for the block. + blockID, err := queryWithID(dbtx, ` +INSERT INTO `+tableBlocks+` (height, chain_id, created_at) + VALUES ($1, $2, $3) + ON CONFLICT DO NOTHING + RETURNING rowid; +`, h.Height, es.chainID, ts) + if err == sql.ErrNoRows { + return nil // we already saw this block; quietly succeed + } else if err != nil { + return fmt.Errorf("indexing block header: %w", err) + } + + // Insert the special block meta-event for height. + if err := insertEvents(dbtx, blockID, 0, []abci.Event{ + makeIndexedEvent(types.BlockHeightKey, fmt.Sprint(h.Height)), + }); err != nil { + return fmt.Errorf("block meta-events: %w", err) + } + // Insert all the block events. Order is important here, + if err := insertEvents(dbtx, blockID, 0, h.Events); err != nil { + return fmt.Errorf("finalizeblock events: %w", err) + } + return nil + }) +} + +func (es *EventSink) IndexTxEvents(txrs []*abci.TxResult) error { + ts := time.Now().UTC() + + for _, txr := range txrs { + // Encode the result message in protobuf wire format for indexing. + resultData, err := proto.Marshal(txr) + if err != nil { + return fmt.Errorf("marshaling tx_result: %w", err) + } + + // Index the hash of the underlying transaction as a hex string. + txHash := fmt.Sprintf("%X", types.Tx(txr.Tx).Hash()) + + if err := runInTransaction(es.store, func(dbtx *sql.Tx) error { + // Find the block associated with this transaction. The block header + // must have been indexed prior to the transactions belonging to it. + blockID, err := queryWithID(dbtx, ` +SELECT rowid FROM `+tableBlocks+` WHERE height = $1 AND chain_id = $2; +`, txr.Height, es.chainID) + if err != nil { + return fmt.Errorf("finding block ID: %w", err) + } + + // Insert a record for this tx_result and capture its ID for indexing events. + txID, err := queryWithID(dbtx, ` +INSERT INTO `+tableTxResults+` (block_id, index, created_at, tx_hash, tx_result) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT DO NOTHING + RETURNING rowid; +`, blockID, txr.Index, ts, txHash, resultData) + if err == sql.ErrNoRows { + return nil // we already saw this transaction; quietly succeed + } else if err != nil { + return fmt.Errorf("indexing tx_result: %w", err) + } + + // Insert the special transaction meta-events for hash and height. + if err := insertEvents(dbtx, blockID, txID, []abci.Event{ + makeIndexedEvent(types.TxHashKey, txHash), + makeIndexedEvent(types.TxHeightKey, fmt.Sprint(txr.Height)), + }); err != nil { + return fmt.Errorf("indexing transaction meta-events: %w", err) + } + // Index any events packaged with the transaction. + if err := insertEvents(dbtx, blockID, txID, txr.Result.Events); err != nil { + return fmt.Errorf("indexing transaction events: %w", err) + } + return nil + }); err != nil { + return err + } + } + return nil +} + +// SearchBlockEvents is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) SearchBlockEvents(_ context.Context, _ *query.Query) ([]int64, error) { + return nil, errors.New("block search is not supported via the postgres event sink") +} + +// SearchTxEvents is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) SearchTxEvents(_ context.Context, _ *query.Query) ([]*abci.TxResult, error) { + return nil, errors.New("tx search is not supported via the postgres event sink") +} + +// GetTxByHash is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) GetTxByHash(_ []byte) (*abci.TxResult, error) { + return nil, errors.New("getTxByHash is not supported via the postgres event sink") +} + +// HasBlock is not implemented by this sink, and reports an error for all queries. +func (es *EventSink) HasBlock(_ int64) (bool, error) { + return false, errors.New("hasBlock is not supported via the postgres event sink") +} + +// Stop closes the underlying PostgreSQL database. +func (es *EventSink) Stop() error { return es.store.Close() } diff --git a/state/indexer/sink/psql/psql_test.go b/state/indexer/sink/psql/psql_test.go new file mode 100644 index 0000000..e545324 --- /dev/null +++ b/state/indexer/sink/psql/psql_test.go @@ -0,0 +1,379 @@ +package psql + +import ( + "context" + "database/sql" + "flag" + "fmt" + "log" + "os" + "os/signal" + "testing" + "time" + + "github.com/adlio/schema" + "github.com/cosmos/gogoproto/proto" + "github.com/ory/dockertest" + "github.com/ory/dockertest/docker" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + tmlog "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/types" + + // Register the Postgres database driver. + _ "github.com/lib/pq" +) + +var ( + doPauseAtExit = flag.Bool("pause-at-exit", false, + "If true, pause the test until interrupted at shutdown, to allow debugging") + + // A hook that test cases can call to obtain the shared database instance + // used for testing the sink. This is initialized in TestMain (see below). + testDB func() *sql.DB +) + +const ( + user = "postgres" + password = "secret" + port = "5432" + dsn = "postgres://%s:%s@localhost:%s/%s?sslmode=disable" + dbName = "postgres" + chainID = "test-chainID" + + viewBlockEvents = "block_events" + viewTxEvents = "tx_events" +) + +func TestMain(m *testing.M) { + flag.Parse() + + // Set up docker and start a container running PostgreSQL. + pool, err := dockertest.NewPool(os.Getenv("DOCKER_URL")) + if err != nil { + log.Fatalf("Creating docker pool: %v", err) + } + + resource, err := pool.RunWithOptions(&dockertest.RunOptions{ + Repository: "postgres", + Tag: "13", + Env: []string{ + "POSTGRES_USER=" + user, + "POSTGRES_PASSWORD=" + password, + "POSTGRES_DB=" + dbName, + "listen_addresses = '*'", + }, + }, func(config *docker.HostConfig) { + // set AutoRemove to true so that stopped container goes away by itself + config.AutoRemove = true + config.RestartPolicy = docker.RestartPolicy{ + Name: "no", + } + }) + if err != nil { + log.Fatalf("Starting docker pool: %v", err) + } + + if *doPauseAtExit { + log.Print("Pause at exit is enabled, containers will not expire") + } else { + const expireSeconds = 60 + _ = resource.Expire(expireSeconds) + log.Printf("Container expiration set to %d seconds", expireSeconds) + } + + // Connect to the database, clear any leftover data, and install the + // indexing schema. + conn := fmt.Sprintf(dsn, user, password, resource.GetPort(port+"/tcp"), dbName) + var db *sql.DB + + if err := pool.Retry(func() error { + sink, err := NewEventSink(conn, chainID) + if err != nil { + return err + } + db = sink.DB() // set global for test use + return db.Ping() + }); err != nil { + log.Fatalf("Connecting to database: %v", err) + } + + if err := resetDatabase(db); err != nil { + log.Fatalf("Flushing database: %v", err) + } + + sm, err := readSchema() + if err != nil { + log.Fatalf("Reading schema: %v", err) + } + migrator := schema.NewMigrator() + if err := migrator.Apply(db, sm); err != nil { + log.Fatalf("Applying schema: %v", err) + } + + // Set up the hook for tests to get the shared database handle. + testDB = func() *sql.DB { return db } + + // Run the selected test cases. + code := m.Run() + + // Clean up and shut down the database container. + if *doPauseAtExit { + log.Print("Testing complete, pausing for inspection. Send SIGINT to resume teardown") + waitForInterrupt() + log.Print("(resuming)") + } + log.Print("Shutting down database") + if err := pool.Purge(resource); err != nil { + log.Printf("WARNING: Purging pool failed: %v", err) + } + if err := db.Close(); err != nil { + log.Printf("WARNING: Closing database failed: %v", err) + } + + os.Exit(code) +} + +func TestIndexing(t *testing.T) { + t.Run("IndexBlockEvents", func(t *testing.T) { + indexer := &EventSink{store: testDB(), chainID: chainID} + require.NoError(t, indexer.IndexBlockEvents(newTestBlockEvents())) + + verifyBlock(t, 1) + verifyBlock(t, 2) + + verifyNotImplemented(t, "hasBlock", func() (bool, error) { return indexer.HasBlock(1) }) + verifyNotImplemented(t, "hasBlock", func() (bool, error) { return indexer.HasBlock(2) }) + + verifyNotImplemented(t, "block search", func() (bool, error) { + v, err := indexer.SearchBlockEvents(context.Background(), nil) + return v != nil, err + }) + + require.NoError(t, verifyTimeStamp(tableBlocks)) + + // Attempting to reindex the same events should gracefully succeed. + require.NoError(t, indexer.IndexBlockEvents(newTestBlockEvents())) + }) + + t.Run("IndexTxEvents", func(t *testing.T) { + indexer := &EventSink{store: testDB(), chainID: chainID} + + txResult := txResultWithEvents([]abci.Event{ + makeIndexedEvent("account.number", "1"), + makeIndexedEvent("account.owner", "Ivan"), + makeIndexedEvent("account.owner", "Yulieta"), + + {Type: "", Attributes: []abci.EventAttribute{ + { + Key: "not_allowed", + Value: "Vlad", + Index: true, + }, + }}, + }) + require.NoError(t, indexer.IndexTxEvents([]*abci.TxResult{txResult})) + + txr, err := loadTxResult(types.Tx(txResult.Tx).Hash()) + require.NoError(t, err) + assert.Equal(t, txResult, txr) + + require.NoError(t, verifyTimeStamp(tableTxResults)) + require.NoError(t, verifyTimeStamp(viewTxEvents)) + + verifyNotImplemented(t, "getTxByHash", func() (bool, error) { + txr, err := indexer.GetTxByHash(types.Tx(txResult.Tx).Hash()) + return txr != nil, err + }) + verifyNotImplemented(t, "tx search", func() (bool, error) { + txr, err := indexer.SearchTxEvents(context.Background(), nil) + return txr != nil, err + }) + + // try to insert the duplicate tx events. + err = indexer.IndexTxEvents([]*abci.TxResult{txResult}) + require.NoError(t, err) + }) + + t.Run("IndexerService", func(t *testing.T) { + indexer := &EventSink{store: testDB(), chainID: chainID} + + // event bus + eventBus := types.NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + service := txindex.NewIndexerService(indexer.TxIndexer(), indexer.BlockIndexer(), eventBus, true) + service.SetLogger(tmlog.TestingLogger()) + err = service.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := service.Stop(); err != nil { + t.Error(err) + } + }) + + // publish block with txs + err = eventBus.PublishEventNewBlockEvents(types.EventDataNewBlockEvents{ + Height: 1, + NumTxs: 2, + }) + require.NoError(t, err) + txResult1 := &abci.TxResult{ + Height: 1, + Index: uint32(0), + Tx: types.Tx("foo"), + Result: abci.ExecTxResult{Code: 0}, + } + err = eventBus.PublishEventTx(types.EventDataTx{TxResult: *txResult1}) + require.NoError(t, err) + txResult2 := &abci.TxResult{ + Height: 1, + Index: uint32(1), + Tx: types.Tx("bar"), + Result: abci.ExecTxResult{Code: 1}, + } + err = eventBus.PublishEventTx(types.EventDataTx{TxResult: *txResult2}) + require.NoError(t, err) + + time.Sleep(100 * time.Millisecond) + require.True(t, service.IsRunning()) + }) +} + +func TestStop(t *testing.T) { + indexer := &EventSink{store: testDB()} + require.NoError(t, indexer.Stop()) +} + +// newTestBlock constructs a fresh copy of a new block event containing +// known test values to exercise the indexer. +func newTestBlockEvents() types.EventDataNewBlockEvents { + return types.EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{ + makeIndexedEvent("begin_event.proposer", "FCAA001"), + makeIndexedEvent("thingy.whatzit", "O.O"), + makeIndexedEvent("end_event.foo", "100"), + makeIndexedEvent("thingy.whatzit", "-.O"), + }, + } +} + +// readSchema loads the indexing database schema file +func readSchema() ([]*schema.Migration, error) { + const filename = "schema.sql" + contents, err := os.ReadFile(filename) + if err != nil { + return nil, fmt.Errorf("failed to read sql file from '%s': %w", filename, err) + } + + return []*schema.Migration{{ + ID: time.Now().Local().String() + " db schema", + Script: string(contents), + }}, nil +} + +// resetDB drops all the data from the test database. +func resetDatabase(db *sql.DB) error { + _, err := db.Exec(`DROP TABLE IF EXISTS blocks,tx_results,events,attributes CASCADE;`) + if err != nil { + return fmt.Errorf("dropping tables: %v", err) + } + _, err = db.Exec(`DROP VIEW IF EXISTS event_attributes,block_events,tx_events CASCADE;`) + if err != nil { + return fmt.Errorf("dropping views: %v", err) + } + return nil +} + +// txResultWithEvents constructs a fresh transaction result with fixed values +// for testing, that includes the specified events. +func txResultWithEvents(events []abci.Event) *abci.TxResult { + return &abci.TxResult{ + Height: 1, + Index: 0, + Tx: types.Tx("HELLO WORLD"), + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, + Log: "", + Events: events, + }, + } +} + +func loadTxResult(hash []byte) (*abci.TxResult, error) { + hashString := fmt.Sprintf("%X", hash) + var resultData []byte + if err := testDB().QueryRow(` +SELECT tx_result FROM `+tableTxResults+` WHERE tx_hash = $1; +`, hashString).Scan(&resultData); err != nil { + return nil, fmt.Errorf("lookup transaction for hash %q failed: %v", hashString, err) + } + + txr := new(abci.TxResult) + if err := proto.Unmarshal(resultData, txr); err != nil { + return nil, fmt.Errorf("unmarshaling txr: %v", err) + } + + return txr, nil +} + +func verifyTimeStamp(tableName string) error { + return testDB().QueryRow(fmt.Sprintf(` +SELECT DISTINCT %[1]s.created_at + FROM %[1]s + WHERE %[1]s.created_at >= $1; +`, tableName), time.Now().Add(-2*time.Second)).Err() +} + +func verifyBlock(t *testing.T, height int64) { + // Check that the blocks table contains an entry for this height. + if err := testDB().QueryRow(` +SELECT height FROM `+tableBlocks+` WHERE height = $1; +`, height).Err(); err == sql.ErrNoRows { + t.Errorf("No block found for height=%d", height) + } else if err != nil { + t.Fatalf("Database query failed: %v", err) + } + + // Verify the presence of begin_block and end_block events. + if err := testDB().QueryRow(` +SELECT type, height, chain_id FROM `+viewBlockEvents+` + WHERE height = $1 AND type = $2 AND chain_id = $3; +`, height, eventTypeFinalizeBlock, chainID).Err(); err == sql.ErrNoRows { + t.Errorf("No %q event found for height=%d", eventTypeFinalizeBlock, height) + } else if err != nil { + t.Fatalf("Database query failed: %v", err) + } +} + +// verifyNotImplemented calls f and verifies that it returns both a +// false-valued flag and a non-nil error whose string matching the expected +// "not supported" message with label prefixed. +func verifyNotImplemented(t *testing.T, label string, f func() (bool, error)) { + t.Helper() + t.Logf("Verifying that %q reports it is not implemented", label) + + want := label + " is not supported via the postgres event sink" + ok, err := f() + assert.False(t, ok) + require.NotNil(t, err) + assert.Equal(t, want, err.Error()) +} + +// waitForInterrupt blocks until a SIGINT is received by the process. +func waitForInterrupt() { + ch := make(chan os.Signal, 1) + signal.Notify(ch, os.Interrupt) + <-ch +} diff --git a/state/indexer/sink/psql/schema.sql b/state/indexer/sink/psql/schema.sql new file mode 100644 index 0000000..868d5bf --- /dev/null +++ b/state/indexer/sink/psql/schema.sql @@ -0,0 +1,85 @@ +/* + This file defines the database schema for the PostgresQL ("psql") event sink + implementation in CometBFT. The operator must create a database and install + this schema before using the database to index events. + */ + +-- The blocks table records metadata about each block. +-- The block record does not include its events or transactions (see tx_results). +CREATE TABLE blocks ( + rowid BIGSERIAL PRIMARY KEY, + + height BIGINT NOT NULL, + chain_id VARCHAR NOT NULL, + + -- When this block header was logged into the sink, in UTC. + created_at TIMESTAMPTZ NOT NULL, + + UNIQUE (height, chain_id) +); + +-- Index blocks by height and chain, since we need to resolve block IDs when +-- indexing transaction records and transaction events. +CREATE INDEX idx_blocks_height_chain ON blocks(height, chain_id); + +-- The tx_results table records metadata about transaction results. Note that +-- the events from a transaction are stored separately. +CREATE TABLE tx_results ( + rowid BIGSERIAL PRIMARY KEY, + + -- The block to which this transaction belongs. + block_id BIGINT NOT NULL REFERENCES blocks(rowid), + -- The sequential index of the transaction within the block. + index INTEGER NOT NULL, + -- When this result record was logged into the sink, in UTC. + created_at TIMESTAMPTZ NOT NULL, + -- The hex-encoded hash of the transaction. + tx_hash VARCHAR NOT NULL, + -- The protobuf wire encoding of the TxResult message. + tx_result BYTEA NOT NULL, + + UNIQUE (block_id, index) +); + +-- The events table records events. All events (both block and transaction) are +-- associated with a block ID; transaction events also have a transaction ID. +CREATE TABLE events ( + rowid BIGSERIAL PRIMARY KEY, + + -- The block and transaction this event belongs to. + -- If tx_id is NULL, this is a block event. + block_id BIGINT NOT NULL REFERENCES blocks(rowid), + tx_id BIGINT NULL REFERENCES tx_results(rowid), + + -- The application-defined type label for the event. + type VARCHAR NOT NULL +); + +-- The attributes table records event attributes. +CREATE TABLE attributes ( + event_id BIGINT NOT NULL REFERENCES events(rowid), + key VARCHAR NOT NULL, -- bare key + composite_key VARCHAR NOT NULL, -- composed type.key + value VARCHAR NULL, + + UNIQUE (event_id, key) +); + +-- A joined view of events and their attributes. Events that do not have any +-- attributes are represented as a single row with empty key and value fields. +CREATE VIEW event_attributes AS + SELECT block_id, tx_id, type, key, composite_key, value + FROM events LEFT JOIN attributes ON (events.rowid = attributes.event_id); + +-- A joined view of all block events (those having tx_id NULL). +CREATE VIEW block_events AS + SELECT blocks.rowid as block_id, height, chain_id, type, key, composite_key, value + FROM blocks JOIN event_attributes ON (blocks.rowid = event_attributes.block_id) + WHERE event_attributes.tx_id IS NULL; + +-- A joined view of all transaction events. +CREATE VIEW tx_events AS + SELECT height, index, chain_id, type, key, composite_key, value, tx_results.created_at + FROM blocks JOIN tx_results ON (blocks.rowid = tx_results.block_id) + JOIN event_attributes ON (tx_results.rowid = event_attributes.tx_id) + WHERE event_attributes.tx_id IS NOT NULL; diff --git a/state/metrics.gen.go b/state/metrics.gen.go new file mode 100644 index 0000000..5dd96a1 --- /dev/null +++ b/state/metrics.gen.go @@ -0,0 +1,46 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package state + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + BlockProcessingTime: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "block_processing_time", + Help: "Time spent processing FinalizeBlock", + + Buckets: stdprometheus.LinearBuckets(1, 10, 10), + }, labels).With(labelsAndValues...), + ConsensusParamUpdates: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "consensus_param_updates", + Help: "Number of consensus parameter updates returned by the application since process start.", + }, labels).With(labelsAndValues...), + ValidatorSetUpdates: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "validator_set_updates", + Help: "Number of validator set updates returned by the application since process start.", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + BlockProcessingTime: discard.NewHistogram(), + ConsensusParamUpdates: discard.NewCounter(), + ValidatorSetUpdates: discard.NewCounter(), + } +} diff --git a/state/metrics.go b/state/metrics.go new file mode 100644 index 0000000..143eef8 --- /dev/null +++ b/state/metrics.go @@ -0,0 +1,29 @@ +package state + +import ( + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "state" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Time spent processing FinalizeBlock + BlockProcessingTime metrics.Histogram `metrics_buckettype:"lin" metrics_bucketsizes:"1, 10, 10"` + + // ConsensusParamUpdates is the total number of times the application has + // updated the consensus params since process start. + //metrics:Number of consensus parameter updates returned by the application since process start. + ConsensusParamUpdates metrics.Counter + + // ValidatorSetUpdates is the total number of times the application has + // updated the validator set since process start. + //metrics:Number of validator set updates returned by the application since process start. + ValidatorSetUpdates metrics.Counter +} diff --git a/state/mocks/block_store.go b/state/mocks/block_store.go new file mode 100644 index 0000000..f66ecfc --- /dev/null +++ b/state/mocks/block_store.go @@ -0,0 +1,344 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + state "github.com/cometbft/cometbft/state" + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/types" +) + +// BlockStore is an autogenerated mock type for the BlockStore type +type BlockStore struct { + mock.Mock +} + +// Base provides a mock function with no fields +func (_m *BlockStore) Base() int64 { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Base") + } + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// Close provides a mock function with no fields +func (_m *BlockStore) Close() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Close") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// DeleteLatestBlock provides a mock function with no fields +func (_m *BlockStore) DeleteLatestBlock() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for DeleteLatestBlock") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Height provides a mock function with no fields +func (_m *BlockStore) Height() int64 { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Height") + } + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// LoadBaseMeta provides a mock function with no fields +func (_m *BlockStore) LoadBaseMeta() *types.BlockMeta { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for LoadBaseMeta") + } + + var r0 *types.BlockMeta + if rf, ok := ret.Get(0).(func() *types.BlockMeta); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockMeta) + } + } + + return r0 +} + +// LoadBlock provides a mock function with given fields: height +func (_m *BlockStore) LoadBlock(height int64) *types.Block { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlock") + } + + var r0 *types.Block + if rf, ok := ret.Get(0).(func(int64) *types.Block); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Block) + } + } + + return r0 +} + +// LoadBlockByHash provides a mock function with given fields: hash +func (_m *BlockStore) LoadBlockByHash(hash []byte) *types.Block { + ret := _m.Called(hash) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockByHash") + } + + var r0 *types.Block + if rf, ok := ret.Get(0).(func([]byte) *types.Block); ok { + r0 = rf(hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Block) + } + } + + return r0 +} + +// LoadBlockCommit provides a mock function with given fields: height +func (_m *BlockStore) LoadBlockCommit(height int64) *types.Commit { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockCommit") + } + + var r0 *types.Commit + if rf, ok := ret.Get(0).(func(int64) *types.Commit); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Commit) + } + } + + return r0 +} + +// LoadBlockExtendedCommit provides a mock function with given fields: height +func (_m *BlockStore) LoadBlockExtendedCommit(height int64) *types.ExtendedCommit { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockExtendedCommit") + } + + var r0 *types.ExtendedCommit + if rf, ok := ret.Get(0).(func(int64) *types.ExtendedCommit); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ExtendedCommit) + } + } + + return r0 +} + +// LoadBlockMeta provides a mock function with given fields: height +func (_m *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockMeta") + } + + var r0 *types.BlockMeta + if rf, ok := ret.Get(0).(func(int64) *types.BlockMeta); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockMeta) + } + } + + return r0 +} + +// LoadBlockMetaByHash provides a mock function with given fields: hash +func (_m *BlockStore) LoadBlockMetaByHash(hash []byte) *types.BlockMeta { + ret := _m.Called(hash) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockMetaByHash") + } + + var r0 *types.BlockMeta + if rf, ok := ret.Get(0).(func([]byte) *types.BlockMeta); ok { + r0 = rf(hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockMeta) + } + } + + return r0 +} + +// LoadBlockPart provides a mock function with given fields: height, index +func (_m *BlockStore) LoadBlockPart(height int64, index int) *types.Part { + ret := _m.Called(height, index) + + if len(ret) == 0 { + panic("no return value specified for LoadBlockPart") + } + + var r0 *types.Part + if rf, ok := ret.Get(0).(func(int64, int) *types.Part); ok { + r0 = rf(height, index) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Part) + } + } + + return r0 +} + +// LoadSeenCommit provides a mock function with given fields: height +func (_m *BlockStore) LoadSeenCommit(height int64) *types.Commit { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for LoadSeenCommit") + } + + var r0 *types.Commit + if rf, ok := ret.Get(0).(func(int64) *types.Commit); ok { + r0 = rf(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Commit) + } + } + + return r0 +} + +// PruneBlocks provides a mock function with given fields: height, _a1 +func (_m *BlockStore) PruneBlocks(height int64, _a1 state.State) (uint64, int64, error) { + ret := _m.Called(height, _a1) + + if len(ret) == 0 { + panic("no return value specified for PruneBlocks") + } + + var r0 uint64 + var r1 int64 + var r2 error + if rf, ok := ret.Get(0).(func(int64, state.State) (uint64, int64, error)); ok { + return rf(height, _a1) + } + if rf, ok := ret.Get(0).(func(int64, state.State) uint64); ok { + r0 = rf(height, _a1) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(int64, state.State) int64); ok { + r1 = rf(height, _a1) + } else { + r1 = ret.Get(1).(int64) + } + + if rf, ok := ret.Get(2).(func(int64, state.State) error); ok { + r2 = rf(height, _a1) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// SaveBlock provides a mock function with given fields: block, blockParts, seenCommit +func (_m *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { + _m.Called(block, blockParts, seenCommit) +} + +// SaveBlockWithExtendedCommit provides a mock function with given fields: block, blockParts, seenCommit +func (_m *BlockStore) SaveBlockWithExtendedCommit(block *types.Block, blockParts *types.PartSet, seenCommit *types.ExtendedCommit) { + _m.Called(block, blockParts, seenCommit) +} + +// Size provides a mock function with no fields +func (_m *BlockStore) Size() int64 { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Size") + } + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// NewBlockStore creates a new instance of BlockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockStore(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockStore { + mock := &BlockStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/state/mocks/evidence_pool.go b/state/mocks/evidence_pool.go new file mode 100644 index 0000000..94606c6 --- /dev/null +++ b/state/mocks/evidence_pool.go @@ -0,0 +1,100 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + state "github.com/cometbft/cometbft/state" + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/types" +) + +// EvidencePool is an autogenerated mock type for the EvidencePool type +type EvidencePool struct { + mock.Mock +} + +// AddEvidence provides a mock function with given fields: _a0 +func (_m *EvidencePool) AddEvidence(_a0 types.Evidence) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for AddEvidence") + } + + var r0 error + if rf, ok := ret.Get(0).(func(types.Evidence) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CheckEvidence provides a mock function with given fields: _a0 +func (_m *EvidencePool) CheckEvidence(_a0 types.EvidenceList) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for CheckEvidence") + } + + var r0 error + if rf, ok := ret.Get(0).(func(types.EvidenceList) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// PendingEvidence provides a mock function with given fields: maxBytes +func (_m *EvidencePool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) { + ret := _m.Called(maxBytes) + + if len(ret) == 0 { + panic("no return value specified for PendingEvidence") + } + + var r0 []types.Evidence + var r1 int64 + if rf, ok := ret.Get(0).(func(int64) ([]types.Evidence, int64)); ok { + return rf(maxBytes) + } + if rf, ok := ret.Get(0).(func(int64) []types.Evidence); ok { + r0 = rf(maxBytes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]types.Evidence) + } + } + + if rf, ok := ret.Get(1).(func(int64) int64); ok { + r1 = rf(maxBytes) + } else { + r1 = ret.Get(1).(int64) + } + + return r0, r1 +} + +// Update provides a mock function with given fields: _a0, _a1 +func (_m *EvidencePool) Update(_a0 state.State, _a1 types.EvidenceList) { + _m.Called(_a0, _a1) +} + +// NewEvidencePool creates a new instance of EvidencePool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEvidencePool(t interface { + mock.TestingT + Cleanup(func()) +}) *EvidencePool { + mock := &EvidencePool{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/state/mocks/store.go b/state/mocks/store.go new file mode 100644 index 0000000..92584e8 --- /dev/null +++ b/state/mocks/store.go @@ -0,0 +1,369 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + abcitypes "github.com/cometbft/cometbft/abci/types" + mock "github.com/stretchr/testify/mock" + + state "github.com/cometbft/cometbft/state" + + types "github.com/cometbft/cometbft/types" +) + +// Store is an autogenerated mock type for the Store type +type Store struct { + mock.Mock +} + +// Bootstrap provides a mock function with given fields: _a0 +func (_m *Store) Bootstrap(_a0 state.State) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Bootstrap") + } + + var r0 error + if rf, ok := ret.Get(0).(func(state.State) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Close provides a mock function with no fields +func (_m *Store) Close() error { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Close") + } + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetOfflineStateSyncHeight provides a mock function with no fields +func (_m *Store) GetOfflineStateSyncHeight() (int64, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOfflineStateSyncHeight") + } + + var r0 int64 + var r1 error + if rf, ok := ret.Get(0).(func() (int64, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Load provides a mock function with no fields +func (_m *Store) Load() (state.State, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Load") + } + + var r0 state.State + var r1 error + if rf, ok := ret.Get(0).(func() (state.State, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() state.State); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(state.State) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadConsensusParams provides a mock function with given fields: _a0 +func (_m *Store) LoadConsensusParams(_a0 int64) (types.ConsensusParams, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadConsensusParams") + } + + var r0 types.ConsensusParams + var r1 error + if rf, ok := ret.Get(0).(func(int64) (types.ConsensusParams, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(int64) types.ConsensusParams); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(types.ConsensusParams) + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadFinalizeBlockResponse provides a mock function with given fields: _a0 +func (_m *Store) LoadFinalizeBlockResponse(_a0 int64) (*abcitypes.ResponseFinalizeBlock, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadFinalizeBlockResponse") + } + + var r0 *abcitypes.ResponseFinalizeBlock + var r1 error + if rf, ok := ret.Get(0).(func(int64) (*abcitypes.ResponseFinalizeBlock, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(int64) *abcitypes.ResponseFinalizeBlock); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*abcitypes.ResponseFinalizeBlock) + } + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadFromDBOrGenesisDoc provides a mock function with given fields: _a0 +func (_m *Store) LoadFromDBOrGenesisDoc(_a0 *types.GenesisDoc) (state.State, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadFromDBOrGenesisDoc") + } + + var r0 state.State + var r1 error + if rf, ok := ret.Get(0).(func(*types.GenesisDoc) (state.State, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(*types.GenesisDoc) state.State); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(state.State) + } + + if rf, ok := ret.Get(1).(func(*types.GenesisDoc) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadFromDBOrGenesisFile provides a mock function with given fields: _a0 +func (_m *Store) LoadFromDBOrGenesisFile(_a0 string) (state.State, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadFromDBOrGenesisFile") + } + + var r0 state.State + var r1 error + if rf, ok := ret.Get(0).(func(string) (state.State, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(string) state.State); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(state.State) + } + + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadLastFinalizeBlockResponse provides a mock function with given fields: _a0 +func (_m *Store) LoadLastFinalizeBlockResponse(_a0 int64) (*abcitypes.ResponseFinalizeBlock, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadLastFinalizeBlockResponse") + } + + var r0 *abcitypes.ResponseFinalizeBlock + var r1 error + if rf, ok := ret.Get(0).(func(int64) (*abcitypes.ResponseFinalizeBlock, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(int64) *abcitypes.ResponseFinalizeBlock); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*abcitypes.ResponseFinalizeBlock) + } + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadValidators provides a mock function with given fields: _a0 +func (_m *Store) LoadValidators(_a0 int64) (*types.ValidatorSet, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for LoadValidators") + } + + var r0 *types.ValidatorSet + var r1 error + if rf, ok := ret.Get(0).(func(int64) (*types.ValidatorSet, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(int64) *types.ValidatorSet); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.ValidatorSet) + } + } + + if rf, ok := ret.Get(1).(func(int64) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PruneStates provides a mock function with given fields: _a0, _a1, _a2 +func (_m *Store) PruneStates(_a0 int64, _a1 int64, _a2 int64) error { + ret := _m.Called(_a0, _a1, _a2) + + if len(ret) == 0 { + panic("no return value specified for PruneStates") + } + + var r0 error + if rf, ok := ret.Get(0).(func(int64, int64, int64) error); ok { + r0 = rf(_a0, _a1, _a2) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Save provides a mock function with given fields: _a0 +func (_m *Store) Save(_a0 state.State) error { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for Save") + } + + var r0 error + if rf, ok := ret.Get(0).(func(state.State) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SaveFinalizeBlockResponse provides a mock function with given fields: _a0, _a1 +func (_m *Store) SaveFinalizeBlockResponse(_a0 int64, _a1 *abcitypes.ResponseFinalizeBlock) error { + ret := _m.Called(_a0, _a1) + + if len(ret) == 0 { + panic("no return value specified for SaveFinalizeBlockResponse") + } + + var r0 error + if rf, ok := ret.Get(0).(func(int64, *abcitypes.ResponseFinalizeBlock) error); ok { + r0 = rf(_a0, _a1) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SetOfflineStateSyncHeight provides a mock function with given fields: height +func (_m *Store) SetOfflineStateSyncHeight(height int64) error { + ret := _m.Called(height) + + if len(ret) == 0 { + panic("no return value specified for SetOfflineStateSyncHeight") + } + + var r0 error + if rf, ok := ret.Get(0).(func(int64) error); ok { + r0 = rf(height) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// NewStore creates a new instance of Store. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStore(t interface { + mock.TestingT + Cleanup(func()) +}) *Store { + mock := &Store{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/state/rollback.go b/state/rollback.go new file mode 100644 index 0000000..b243763 --- /dev/null +++ b/state/rollback.go @@ -0,0 +1,126 @@ +package state + +import ( + "errors" + "fmt" + + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/version" +) + +// Rollback overwrites the current CometBFT state (height n) with the most +// recent previous state (height n - 1). +// Note that this function does not affect application state. +func Rollback(bs BlockStore, ss Store, removeBlock bool) (int64, []byte, error) { + invalidState, err := ss.Load() + if err != nil { + return -1, nil, err + } + if invalidState.IsEmpty() { + return -1, nil, errors.New("no state found") + } + + height := bs.Height() + + // NOTE: persistence of state and blocks don't happen atomically. Therefore it is possible that + // when the user stopped the node the state wasn't updated but the blockstore was. Discard the + // pending block before continuing. + if height == invalidState.LastBlockHeight+1 { + if removeBlock { + if err := bs.DeleteLatestBlock(); err != nil { + return -1, nil, fmt.Errorf("failed to remove final block from blockstore: %w", err) + } + } + return invalidState.LastBlockHeight, invalidState.AppHash, nil + } + + // If the state store isn't one below nor equal to the blockstore height than this violates the + // invariant + if height != invalidState.LastBlockHeight { + return -1, nil, fmt.Errorf("statestore height (%d) is not one below or equal to blockstore height (%d)", + invalidState.LastBlockHeight, height) + } + + // state store height is equal to blockstore height. We're good to proceed with rolling back state + rollbackHeight := invalidState.LastBlockHeight - 1 + rollbackBlock := bs.LoadBlockMeta(rollbackHeight) + if rollbackBlock == nil { + return -1, nil, fmt.Errorf("block at height %d not found", rollbackHeight) + } + // We also need to retrieve the latest block because the app hash and last + // results hash is only agreed upon in the following block. + latestBlock := bs.LoadBlockMeta(invalidState.LastBlockHeight) + if latestBlock == nil { + return -1, nil, fmt.Errorf("block at height %d not found", invalidState.LastBlockHeight) + } + + previousLastValidatorSet, err := ss.LoadValidators(rollbackHeight) + if err != nil { + return -1, nil, err + } + + previousParams, err := ss.LoadConsensusParams(rollbackHeight + 1) + if err != nil { + return -1, nil, err + } + + nextHeight := rollbackHeight + 1 + valChangeHeight := invalidState.LastHeightValidatorsChanged + // this can only happen if the validator set changed since the last block + if valChangeHeight > nextHeight+1 { + valChangeHeight = nextHeight + 1 + } + + paramsChangeHeight := invalidState.LastHeightConsensusParamsChanged + // this can only happen if params changed from the last block + if paramsChangeHeight > rollbackHeight { + paramsChangeHeight = rollbackHeight + 1 + } + + // build the new state from the old state and the prior block + rolledBackState := State{ + Version: cmtstate.Version{ + Consensus: cmtversion.Consensus{ + Block: version.BlockProtocol, + App: previousParams.Version.App, + }, + Software: version.TMCoreSemVer, + }, + // immutable fields + ChainID: invalidState.ChainID, + InitialHeight: invalidState.InitialHeight, + + LastBlockHeight: rollbackBlock.Header.Height, + LastBlockID: rollbackBlock.BlockID, + LastBlockTime: rollbackBlock.Header.Time, + + NextValidators: invalidState.Validators, + Validators: invalidState.LastValidators, + LastValidators: previousLastValidatorSet, + LastHeightValidatorsChanged: valChangeHeight, + + ConsensusParams: previousParams, + LastHeightConsensusParamsChanged: paramsChangeHeight, + + LastResultsHash: latestBlock.Header.LastResultsHash, + AppHash: latestBlock.Header.AppHash, + } + + // persist the new state. This overrides the invalid one. NOTE: this will also + // persist the validator set and consensus params over the existing structures, + // but both should be the same + if err := ss.Save(rolledBackState); err != nil { + return -1, nil, fmt.Errorf("failed to save rolled back state: %w", err) + } + + // If removeBlock is true then also remove the block associated with the previous state. + // This will mean both the last state and last block height is equal to n - 1 + if removeBlock { + if err := bs.DeleteLatestBlock(); err != nil { + return -1, nil, fmt.Errorf("failed to remove final block from blockstore: %w", err) + } + } + + return rolledBackState.LastBlockHeight, rolledBackState.AppHash, nil +} diff --git a/state/rollback_test.go b/state/rollback_test.go new file mode 100644 index 0000000..d56fe67 --- /dev/null +++ b/state/rollback_test.go @@ -0,0 +1,288 @@ +package state_test + +import ( + "crypto/rand" + "testing" + "time" + + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +func TestRollback(t *testing.T) { + var ( + height int64 = 100 + nextHeight int64 = 101 + ) + blockStore := &mocks.BlockStore{} + stateStore := setupStateStore(t, height) + initialState, err := stateStore.Load() + require.NoError(t, err) + + // perform the rollback over a version bump + newParams := types.DefaultConsensusParams() + newParams.Version.App = 11 + newParams.Block.MaxBytes = 1000 + nextState := initialState.Copy() + nextState.LastBlockHeight = nextHeight + nextState.Version.Consensus.App = 11 + nextState.LastBlockID = makeBlockIDRandom() + nextState.AppHash = tmhash.Sum([]byte("app_hash")) + nextState.LastValidators = initialState.Validators + nextState.Validators = initialState.NextValidators + nextState.NextValidators = initialState.NextValidators.CopyIncrementProposerPriority(1) + nextState.ConsensusParams = *newParams + nextState.LastHeightConsensusParamsChanged = nextHeight + 1 + nextState.LastHeightValidatorsChanged = nextHeight + 1 + + // update the state + require.NoError(t, stateStore.Save(nextState)) + + block := &types.BlockMeta{ + BlockID: initialState.LastBlockID, + Header: types.Header{ + Height: initialState.LastBlockHeight, + Time: initialState.LastBlockTime, + AppHash: crypto.CRandBytes(tmhash.Size), + LastBlockID: makeBlockIDRandom(), + LastResultsHash: initialState.LastResultsHash, + }, + } + nextBlock := &types.BlockMeta{ + BlockID: initialState.LastBlockID, + Header: types.Header{ + Height: nextState.LastBlockHeight, + AppHash: initialState.AppHash, + LastBlockID: block.BlockID, + Time: nextState.LastBlockTime, + LastResultsHash: nextState.LastResultsHash, + }, + } + blockStore.On("LoadBlockMeta", height).Return(block) + blockStore.On("LoadBlockMeta", nextHeight).Return(nextBlock) + blockStore.On("Height").Return(nextHeight) + + // rollback the state + rollbackHeight, rollbackHash, err := state.Rollback(blockStore, stateStore, false) + require.NoError(t, err) + require.EqualValues(t, height, rollbackHeight) + require.EqualValues(t, initialState.AppHash, rollbackHash) + blockStore.AssertExpectations(t) + + // assert that we've recovered the prior state + loadedState, err := stateStore.Load() + require.NoError(t, err) + require.EqualValues(t, initialState, loadedState) +} + +func TestRollbackHard(t *testing.T) { + const height int64 = 100 + blockStore := store.NewBlockStore(dbm.NewMemDB()) + stateStore := state.NewStore(dbm.NewMemDB(), state.StoreOptions{DiscardABCIResponses: false}) + + valSet, _ := types.RandValidatorSet(5, 10) + + params := types.DefaultConsensusParams() + params.Version.App = 10 + now := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + + block := &types.Block{ + Header: types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: "test-chain", + Time: now, + Height: height, + AppHash: crypto.CRandBytes(tmhash.Size), + LastBlockID: makeBlockIDRandom(), + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: valSet.Hash(), + NextValidatorsHash: valSet.CopyIncrementProposerPriority(1).Hash(), + ConsensusHash: params.Hash(), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + }, + LastCommit: &types.Commit{Height: height - 1}, + } + + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + blockStore.SaveBlock(block, partSet, &types.Commit{Height: block.Height}) + + currState := state.State{ + Version: cmtstate.Version{ + Consensus: block.Version, + Software: version.TMCoreSemVer, + }, + LastBlockHeight: block.Height, + LastBlockTime: block.Time, + AppHash: crypto.CRandBytes(tmhash.Size), + LastValidators: valSet, + Validators: valSet.CopyIncrementProposerPriority(1), + NextValidators: valSet.CopyIncrementProposerPriority(2), + ConsensusParams: *params, + LastHeightConsensusParamsChanged: height + 1, + LastHeightValidatorsChanged: height + 1, + LastResultsHash: crypto.CRandBytes(tmhash.Size), + } + require.NoError(t, stateStore.Bootstrap(currState)) + + nextBlock := &types.Block{ + Header: types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: block.ChainID, + Time: block.Time, + Height: currState.LastBlockHeight + 1, + AppHash: currState.AppHash, + LastBlockID: types.BlockID{Hash: block.Hash(), PartSetHeader: partSet.Header()}, + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: valSet.CopyIncrementProposerPriority(1).Hash(), + NextValidatorsHash: valSet.CopyIncrementProposerPriority(2).Hash(), + ConsensusHash: params.Hash(), + LastResultsHash: currState.LastResultsHash, + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + }, + LastCommit: &types.Commit{Height: currState.LastBlockHeight}, + } + + nextPartSet, err := nextBlock.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + blockStore.SaveBlock(nextBlock, nextPartSet, &types.Commit{Height: nextBlock.Height}) + + rollbackHeight, rollbackHash, err := state.Rollback(blockStore, stateStore, true) + require.NoError(t, err) + require.Equal(t, rollbackHeight, currState.LastBlockHeight) + require.Equal(t, rollbackHash, currState.AppHash) + + // state should not have been changed + loadedState, err := stateStore.Load() + require.NoError(t, err) + require.Equal(t, currState, loadedState) + + // resave the same block + blockStore.SaveBlock(nextBlock, nextPartSet, &types.Commit{Height: nextBlock.Height}) + + params.Version.App = 11 + + nextState := state.State{ + Version: cmtstate.Version{ + Consensus: block.Version, + Software: version.TMCoreSemVer, + }, + LastBlockHeight: nextBlock.Height, + LastBlockTime: nextBlock.Time, + AppHash: crypto.CRandBytes(tmhash.Size), + LastValidators: valSet.CopyIncrementProposerPriority(1), + Validators: valSet.CopyIncrementProposerPriority(2), + NextValidators: valSet.CopyIncrementProposerPriority(3), + ConsensusParams: *params, + LastHeightConsensusParamsChanged: nextBlock.Height + 1, + LastHeightValidatorsChanged: nextBlock.Height + 1, + LastResultsHash: crypto.CRandBytes(tmhash.Size), + } + require.NoError(t, stateStore.Save(nextState)) + + rollbackHeight, rollbackHash, err = state.Rollback(blockStore, stateStore, true) + require.NoError(t, err) + require.Equal(t, rollbackHeight, currState.LastBlockHeight) + require.Equal(t, rollbackHash, currState.AppHash) +} + +func TestRollbackNoState(t *testing.T) { + stateStore := state.NewStore(dbm.NewMemDB(), + state.StoreOptions{ + DiscardABCIResponses: false, + }) + blockStore := &mocks.BlockStore{} + + _, _, err := state.Rollback(blockStore, stateStore, false) + require.Error(t, err) + require.Contains(t, err.Error(), "no state found") +} + +func TestRollbackNoBlocks(t *testing.T) { + const height = int64(100) + stateStore := setupStateStore(t, height) + blockStore := &mocks.BlockStore{} + blockStore.On("Height").Return(height) + blockStore.On("LoadBlockMeta", height).Return(nil) + blockStore.On("LoadBlockMeta", height-1).Return(nil) + + _, _, err := state.Rollback(blockStore, stateStore, false) + require.Error(t, err) + require.Contains(t, err.Error(), "block at height 99 not found") +} + +func TestRollbackDifferentStateHeight(t *testing.T) { + const height = int64(100) + stateStore := setupStateStore(t, height) + blockStore := &mocks.BlockStore{} + blockStore.On("Height").Return(height + 2) + + _, _, err := state.Rollback(blockStore, stateStore, false) + require.Error(t, err) + require.Equal(t, err.Error(), "statestore height (100) is not one below or equal to blockstore height (102)") +} + +func setupStateStore(t *testing.T, height int64) state.Store { + stateStore := state.NewStore(dbm.NewMemDB(), state.StoreOptions{DiscardABCIResponses: false}) + valSet, _ := types.RandValidatorSet(5, 10) + + params := types.DefaultConsensusParams() + params.Version.App = 10 + + initialState := state.State{ + Version: cmtstate.Version{ + Consensus: cmtversion.Consensus{ + Block: version.BlockProtocol, + App: 10, + }, + Software: version.TMCoreSemVer, + }, + ChainID: "test-chain", + InitialHeight: 10, + LastBlockID: makeBlockIDRandom(), + AppHash: tmhash.Sum([]byte("app_hash")), + LastResultsHash: tmhash.Sum([]byte("last_results_hash")), + LastBlockHeight: height, + LastBlockTime: time.Now(), + LastValidators: valSet, + Validators: valSet.CopyIncrementProposerPriority(1), + NextValidators: valSet.CopyIncrementProposerPriority(2), + LastHeightValidatorsChanged: height + 1 + 1, + ConsensusParams: *params, + LastHeightConsensusParamsChanged: height + 1, + } + require.NoError(t, stateStore.Bootstrap(initialState)) + return stateStore +} + +func makeBlockIDRandom() types.BlockID { + var ( + blockHash = make([]byte, tmhash.Size) + partSetHash = make([]byte, tmhash.Size) + ) + rand.Read(blockHash) //nolint: errcheck // ignore errcheck for read + rand.Read(partSetHash) //nolint: errcheck // ignore errcheck for read + return types.BlockID{ + Hash: blockHash, + PartSetHeader: types.PartSetHeader{ + Total: 123, + Hash: partSetHash, + }, + } +} diff --git a/state/services.go b/state/services.go new file mode 100644 index 0000000..4389a08 --- /dev/null +++ b/state/services.go @@ -0,0 +1,68 @@ +package state + +import ( + "github.com/cometbft/cometbft/types" +) + +//------------------------------------------------------ +// blockchain services types +// NOTE: Interfaces used by RPC must be thread safe! +//------------------------------------------------------ + +//------------------------------------------------------ +// blockstore + +//go:generate ../scripts/mockery_generate.sh BlockStore + +// BlockStore defines the interface used by the ConsensusState. +type BlockStore interface { + Base() int64 + Height() int64 + Size() int64 + + LoadBaseMeta() *types.BlockMeta + LoadBlockMeta(height int64) *types.BlockMeta + LoadBlock(height int64) *types.Block + + SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) + SaveBlockWithExtendedCommit(block *types.Block, blockParts *types.PartSet, seenCommit *types.ExtendedCommit) + + PruneBlocks(height int64, state State) (uint64, int64, error) + + LoadBlockByHash(hash []byte) *types.Block + LoadBlockMetaByHash(hash []byte) *types.BlockMeta + LoadBlockPart(height int64, index int) *types.Part + + LoadBlockCommit(height int64) *types.Commit + LoadSeenCommit(height int64) *types.Commit + LoadBlockExtendedCommit(height int64) *types.ExtendedCommit + + DeleteLatestBlock() error + + Close() error +} + +//----------------------------------------------------------------------------- +// evidence pool + +//go:generate ../scripts/mockery_generate.sh EvidencePool + +// EvidencePool defines the EvidencePool interface used by State. +type EvidencePool interface { + PendingEvidence(maxBytes int64) (ev []types.Evidence, size int64) + AddEvidence(types.Evidence) error + Update(State, types.EvidenceList) + CheckEvidence(types.EvidenceList) error +} + +// EmptyEvidencePool is an empty implementation of EvidencePool, useful for testing. It also complies +// to the consensus evidence pool interface +type EmptyEvidencePool struct{} + +func (EmptyEvidencePool) PendingEvidence(int64) (ev []types.Evidence, size int64) { + return nil, 0 +} +func (EmptyEvidencePool) AddEvidence(types.Evidence) error { return nil } +func (EmptyEvidencePool) Update(State, types.EvidenceList) {} +func (EmptyEvidencePool) CheckEvidence(types.EvidenceList) error { return nil } +func (EmptyEvidencePool) ReportConflictingVotes(*types.Vote, *types.Vote) {} diff --git a/state/state.go b/state/state.go new file mode 100644 index 0000000..2bd5023 --- /dev/null +++ b/state/state.go @@ -0,0 +1,361 @@ +package state + +import ( + "bytes" + "errors" + "fmt" + "os" + "time" + + "github.com/cosmos/gogoproto/proto" + + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" +) + +// database keys +var ( + stateKey = []byte("stateKey") +) + +//----------------------------------------------------------------------------- + +// InitStateVersion sets the Consensus.Block and Software versions, +// but leaves the Consensus.App version blank. +// The Consensus.App version will be set during the Handshake, once +// we hear from the app what protocol version it is running. +var InitStateVersion = cmtstate.Version{ + Consensus: cmtversion.Consensus{ + Block: version.BlockProtocol, + App: 0, + }, + Software: version.TMCoreSemVer, +} + +//----------------------------------------------------------------------------- + +// State is a short description of the latest committed block of the consensus protocol. +// It keeps all information necessary to validate new blocks, +// including the last validator set and the consensus params. +// All fields are exposed so the struct can be easily serialized, +// but none of them should be mutated directly. +// Instead, use state.Copy() or state.NextState(...). +// NOTE: not goroutine-safe. +type State struct { + Version cmtstate.Version + + // immutable + ChainID string + InitialHeight int64 // should be 1, not 0, when starting from height 1 + + // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist) + LastBlockHeight int64 + LastBlockID types.BlockID + LastBlockTime time.Time + + // LastValidators is used to validate block.LastCommit. + // Validators are persisted to the database separately every time they change, + // so we can query for historical validator sets. + // Note that if s.LastBlockHeight causes a valset change, + // we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1 + 1 + // Extra +1 due to nextValSet delay. + NextValidators *types.ValidatorSet + Validators *types.ValidatorSet + LastValidators *types.ValidatorSet + LastHeightValidatorsChanged int64 + + // Consensus parameters used for validating blocks. + // Changes returned by FinalizeBlock and updated after Commit. + ConsensusParams types.ConsensusParams + LastHeightConsensusParamsChanged int64 + + // Merkle root of the results from executing prev block + LastResultsHash []byte + + // the latest AppHash we've received from calling abci.Commit() + AppHash []byte +} + +// Copy makes a copy of the State for mutating. +func (state State) Copy() State { + + return State{ + Version: state.Version, + ChainID: state.ChainID, + InitialHeight: state.InitialHeight, + + LastBlockHeight: state.LastBlockHeight, + LastBlockID: state.LastBlockID, + LastBlockTime: state.LastBlockTime, + + NextValidators: state.NextValidators.Copy(), + Validators: state.Validators.Copy(), + LastValidators: state.LastValidators.Copy(), + LastHeightValidatorsChanged: state.LastHeightValidatorsChanged, + + ConsensusParams: state.ConsensusParams, + LastHeightConsensusParamsChanged: state.LastHeightConsensusParamsChanged, + + AppHash: state.AppHash, + + LastResultsHash: state.LastResultsHash, + } +} + +// Equals returns true if the States are identical. +func (state State) Equals(state2 State) bool { + sbz, s2bz := state.Bytes(), state2.Bytes() + return bytes.Equal(sbz, s2bz) +} + +// Bytes serializes the State using protobuf. +// It panics if either casting to protobuf or serialization fails. +func (state State) Bytes() []byte { + sm, err := state.ToProto() + if err != nil { + panic(err) + } + bz, err := proto.Marshal(sm) + if err != nil { + panic(err) + } + return bz +} + +// IsEmpty returns true if the State is equal to the empty State. +func (state State) IsEmpty() bool { + return state.Validators == nil // XXX can't compare to Empty +} + +// ToProto takes the local state type and returns the equivalent proto type +func (state *State) ToProto() (*cmtstate.State, error) { + if state == nil { + return nil, errors.New("state is nil") + } + + sm := new(cmtstate.State) + + sm.Version = state.Version + sm.ChainID = state.ChainID + sm.InitialHeight = state.InitialHeight + sm.LastBlockHeight = state.LastBlockHeight + + sm.LastBlockID = state.LastBlockID.ToProto() + sm.LastBlockTime = state.LastBlockTime + vals, err := state.Validators.ToProto() + if err != nil { + return nil, err + } + sm.Validators = vals + + nVals, err := state.NextValidators.ToProto() + if err != nil { + return nil, err + } + sm.NextValidators = nVals + + if state.LastBlockHeight >= 1 { // At Block 1 LastValidators is nil + lVals, err := state.LastValidators.ToProto() + if err != nil { + return nil, err + } + sm.LastValidators = lVals + } + + sm.LastHeightValidatorsChanged = state.LastHeightValidatorsChanged + sm.ConsensusParams = state.ConsensusParams.ToProto() + sm.LastHeightConsensusParamsChanged = state.LastHeightConsensusParamsChanged + sm.LastResultsHash = state.LastResultsHash + sm.AppHash = state.AppHash + + return sm, nil +} + +// FromProto takes a state proto message & returns the local state type +func FromProto(pb *cmtstate.State) (*State, error) { //nolint:golint + if pb == nil { + return nil, errors.New("nil State") + } + + state := new(State) + + state.Version = pb.Version + state.ChainID = pb.ChainID + state.InitialHeight = pb.InitialHeight + + bi, err := types.BlockIDFromProto(&pb.LastBlockID) + if err != nil { + return nil, err + } + state.LastBlockID = *bi + state.LastBlockHeight = pb.LastBlockHeight + state.LastBlockTime = pb.LastBlockTime + + vals, err := types.ValidatorSetFromProto(pb.Validators) + if err != nil { + return nil, err + } + state.Validators = vals + + nVals, err := types.ValidatorSetFromProto(pb.NextValidators) + if err != nil { + return nil, err + } + state.NextValidators = nVals + + if state.LastBlockHeight >= 1 { // At Block 1 LastValidators is nil + lVals, err := types.ValidatorSetFromProto(pb.LastValidators) + if err != nil { + return nil, err + } + state.LastValidators = lVals + } else { + state.LastValidators = types.NewValidatorSet(nil) + } + + state.LastHeightValidatorsChanged = pb.LastHeightValidatorsChanged + state.ConsensusParams = types.ConsensusParamsFromProto(pb.ConsensusParams) + state.LastHeightConsensusParamsChanged = pb.LastHeightConsensusParamsChanged + state.LastResultsHash = pb.LastResultsHash + state.AppHash = pb.AppHash + + return state, nil +} + +//------------------------------------------------------------------------ +// Create a block from the latest state + +// MakeBlock builds a block from the current state with the given txs, commit, +// and evidence. Note it also takes a proposerAddress because the state does not +// track rounds, and hence does not know the correct proposer. TODO: fix this! +func (state State) MakeBlock( + height int64, + txs []types.Tx, + lastCommit *types.Commit, + evidence []types.Evidence, + proposerAddress []byte, +) (*types.Block, error) { + + // Build base block with block data. + block := types.MakeBlock(height, txs, lastCommit, evidence) + + // Set time. + var timestamp time.Time + if height == state.InitialHeight { + timestamp = state.LastBlockTime // genesis time + } else { + ts, err := MedianTime(lastCommit, state.LastValidators) + if err != nil { + return nil, fmt.Errorf("error making block while calculating median time: %w", err) + } + timestamp = ts + } + + // Fill rest of header with state data. + block.Populate( + state.Version.Consensus, state.ChainID, + timestamp, state.LastBlockID, + state.Validators.Hash(), state.NextValidators.Hash(), + state.ConsensusParams.Hash(), state.AppHash, state.LastResultsHash, + proposerAddress, + ) + + return block, nil +} + +// MedianTime computes a median time for a given Commit (based on Timestamp field of votes messages) and the +// corresponding validator set. The computed time is always between timestamps of +// the votes sent by honest processes, i.e., a faulty processes can not arbitrarily increase or decrease the +// computed value. +func MedianTime(commit *types.Commit, validators *types.ValidatorSet) (time.Time, error) { + weightedTimes := make([]*cmttime.WeightedTime, len(commit.Signatures)) + totalVotingPower := int64(0) + + for i, commitSig := range commit.Signatures { + if commitSig.BlockIDFlag == types.BlockIDFlagAbsent { + continue + } + _, validator := validators.GetByAddress(commitSig.ValidatorAddress) + // If there's no condition, TestValidateBlockCommit panics; not needed normally. + if validator == nil { + return time.Time{}, fmt.Errorf("commit validator not found in validator set: %X", + commitSig.ValidatorAddress) + } + totalVotingPower += validator.VotingPower + weightedTimes[i] = cmttime.NewWeightedTime(commitSig.Timestamp, validator.VotingPower) + } + + return cmttime.WeightedMedian(weightedTimes, totalVotingPower), nil +} + +//------------------------------------------------------------------------ +// Genesis + +// MakeGenesisStateFromFile reads and unmarshals state from the given +// file. +// +// Used during replay and in tests. +func MakeGenesisStateFromFile(genDocFile string) (State, error) { + genDoc, err := MakeGenesisDocFromFile(genDocFile) + if err != nil { + return State{}, err + } + return MakeGenesisState(genDoc) +} + +// MakeGenesisDocFromFile reads and unmarshals genesis doc from the given file. +func MakeGenesisDocFromFile(genDocFile string) (*types.GenesisDoc, error) { + genDocJSON, err := os.ReadFile(genDocFile) + if err != nil { + return nil, fmt.Errorf("couldn't read GenesisDoc file: %v", err) + } + genDoc, err := types.GenesisDocFromJSON(genDocJSON) + if err != nil { + return nil, fmt.Errorf("error reading GenesisDoc: %v", err) + } + return genDoc, nil +} + +// MakeGenesisState creates state from types.GenesisDoc. +func MakeGenesisState(genDoc *types.GenesisDoc) (State, error) { + err := genDoc.ValidateAndComplete() + if err != nil { + return State{}, fmt.Errorf("error in genesis doc: %w", err) + } + + var validatorSet, nextValidatorSet *types.ValidatorSet + if genDoc.Validators == nil { + validatorSet = types.NewValidatorSet(nil) + nextValidatorSet = types.NewValidatorSet(nil) + } else { + validators := make([]*types.Validator, len(genDoc.Validators)) + for i, val := range genDoc.Validators { + validators[i] = types.NewValidator(val.PubKey, val.Power) + } + validatorSet = types.NewValidatorSet(validators) + nextValidatorSet = types.NewValidatorSet(validators).CopyIncrementProposerPriority(1) + } + + return State{ + Version: InitStateVersion, + ChainID: genDoc.ChainID, + InitialHeight: genDoc.InitialHeight, + + LastBlockHeight: 0, + LastBlockID: types.BlockID{}, + LastBlockTime: genDoc.GenesisTime, + + NextValidators: nextValidatorSet, + Validators: validatorSet, + LastValidators: types.NewValidatorSet(nil), + LastHeightValidatorsChanged: genDoc.InitialHeight, + + ConsensusParams: *genDoc.ConsensusParams, + LastHeightConsensusParamsChanged: genDoc.InitialHeight, + + AppHash: genDoc.AppHash, + }, nil +} diff --git a/state/state_test.go b/state/state_test.go new file mode 100644 index 0000000..b128a91 --- /dev/null +++ b/state/state_test.go @@ -0,0 +1,1210 @@ +package state_test + +import ( + "bytes" + "fmt" + "math" + "math/big" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/internal/test" + cmtrand "github.com/cometbft/cometbft/libs/rand" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +// setupTestCase does setup common to all test cases. +func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) { + t.Helper() + tearDown, stateDB, state, _ := setupTestCaseWithStore(t) + return tearDown, stateDB, state +} + +// setupTestCase does setup common to all test cases. +func setupTestCaseWithStore(t *testing.T) (func(t *testing.T), dbm.DB, sm.State, sm.Store) { + t.Helper() + config := test.ResetTestRoot("state_") + dbType := dbm.BackendType(config.DBBackend) + stateDB, err := dbm.NewDB("state", dbType, config.DBDir()) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + require.NoError(t, err) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + require.NoError(t, err, "expected no error on LoadStateFromDBOrGenesisFile") + err = stateStore.Save(state) + require.NoError(t, err) + + tearDown := func(t *testing.T) { + t.Helper() + os.RemoveAll(config.RootDir) + } + + return tearDown, stateDB, state, stateStore +} + +// TestStateCopy tests the correct copying behavior of State. +func TestStateCopy(t *testing.T) { + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + assert := assert.New(t) + + stateCopy := state.Copy() + + assert.True(state.Equals(stateCopy), + fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", + stateCopy, state)) + + stateCopy.LastBlockHeight++ + stateCopy.LastValidators = state.Validators + assert.False(state.Equals(stateCopy), fmt.Sprintf(`expected states to be different. got same + %v`, state)) +} + +// TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil. +func TestMakeGenesisStateNilValidators(t *testing.T) { + doc := types.GenesisDoc{ + ChainID: "dummy", + Validators: nil, + } + require.Nil(t, doc.ValidateAndComplete()) + state, err := sm.MakeGenesisState(&doc) + require.Nil(t, err) + require.Equal(t, 0, len(state.Validators.Validators)) + require.Equal(t, 0, len(state.NextValidators.Validators)) +} + +// TestStateSaveLoad tests saving and loading State from a db. +func TestStateSaveLoad(t *testing.T) { + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + assert := assert.New(t) + + state.LastBlockHeight++ + state.LastValidators = state.Validators + err := stateStore.Save(state) + require.NoError(t, err) + + loadedState, err := stateStore.Load() + require.NoError(t, err) + assert.True(state.Equals(loadedState), + fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", + loadedState, state)) +} + +// TestFinalizeBlockResponsesSaveLoad1 tests saving and loading ABCIResponses. +func TestFinalizeBlockResponsesSaveLoad1(t *testing.T) { + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + assert := assert.New(t) + + state.LastBlockHeight++ + + // Build mock responses. + block, err := makeBlock(state, 2, new(types.Commit)) + require.NoError(t, err) + + abciResponses := new(abci.ResponseFinalizeBlock) + dtxs := make([]*abci.ExecTxResult, 2) + abciResponses.TxResults = dtxs + + abciResponses.TxResults[0] = &abci.ExecTxResult{Data: []byte("foo"), Events: nil} + abciResponses.TxResults[1] = &abci.ExecTxResult{Data: []byte("bar"), Log: "ok", Events: nil} + abciResponses.ValidatorUpdates = []abci.ValidatorUpdate{ + types.TM2PB.NewValidatorUpdate(ed25519.GenPrivKey().PubKey(), 10), + } + + abciResponses.AppHash = make([]byte, 1) + + err = stateStore.SaveFinalizeBlockResponse(block.Height, abciResponses) + require.NoError(t, err) + loadedABCIResponses, err := stateStore.LoadFinalizeBlockResponse(block.Height) + assert.NoError(err) + assert.Equal(abciResponses, loadedABCIResponses) +} + +// TestResultsSaveLoad tests saving and loading FinalizeBlock results. +func TestFinalizeBlockResponsesSaveLoad2(t *testing.T) { + tearDown, stateDB, _ := setupTestCase(t) + defer tearDown(t) + assert := assert.New(t) + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + cases := [...]struct { + // Height is implied to equal index+2, + // as block 1 is created from genesis. + added []*abci.ExecTxResult + expected []*abci.ExecTxResult + }{ + 0: { + nil, + nil, + }, + 1: { + []*abci.ExecTxResult{ + {Code: 32, Data: []byte("Hello"), Log: "Huh?"}, + }, + []*abci.ExecTxResult{ + {Code: 32, Data: []byte("Hello")}, + }, + }, + 2: { + []*abci.ExecTxResult{ + {Code: 383}, + { + Data: []byte("Gotcha!"), + Events: []abci.Event{ + {Type: "type1", Attributes: []abci.EventAttribute{{Key: "a", Value: "1"}}}, + {Type: "type2", Attributes: []abci.EventAttribute{{Key: "build", Value: "stuff"}}}, + }, + }, + }, + []*abci.ExecTxResult{ + {Code: 383, Data: nil}, + {Code: 0, Data: []byte("Gotcha!"), Events: []abci.Event{ + {Type: "type1", Attributes: []abci.EventAttribute{{Key: "a", Value: "1"}}}, + {Type: "type2", Attributes: []abci.EventAttribute{{Key: "build", Value: "stuff"}}}, + }}, + }, + }, + 3: { + nil, + nil, + }, + 4: { + []*abci.ExecTxResult{nil}, + nil, + }, + } + + // Query all before, this should return error. + for i := range cases { + h := int64(i + 1) + res, err := stateStore.LoadFinalizeBlockResponse(h) + assert.Error(err, "%d: %#v", i, res) + } + + // Add all cases. + for i, tc := range cases { + h := int64(i + 1) // last block height, one below what we save + responses := &abci.ResponseFinalizeBlock{ + TxResults: tc.added, + AppHash: []byte(fmt.Sprintf("%d", h)), + } + err := stateStore.SaveFinalizeBlockResponse(h, responses) + require.NoError(t, err) + } + + // Query all before, should return expected value. + for i, tc := range cases { + h := int64(i + 1) + res, err := stateStore.LoadFinalizeBlockResponse(h) + if assert.NoError(err, "%d", i) { + t.Log(res) + responses := &abci.ResponseFinalizeBlock{ + TxResults: tc.expected, + AppHash: []byte(fmt.Sprintf("%d", h)), + } + assert.Equal(sm.TxResultsHash(responses.TxResults), sm.TxResultsHash(res.TxResults), "%d", i) + } + } +} + +// TestValidatorSimpleSaveLoad tests saving and loading validators. +func TestValidatorSimpleSaveLoad(t *testing.T) { + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + assert := assert.New(t) + + statestore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + // Can't load anything for height 0. + _, err := statestore.LoadValidators(0) + assert.IsType(sm.ErrNoValSetForHeight{}, err, "expected err at height 0") + + // Should be able to load for height 1. + v, err := statestore.LoadValidators(1) + assert.Nil(err, "expected no err at height 1") + assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match") + + // Should be able to load for height 2. + v, err = statestore.LoadValidators(2) + assert.Nil(err, "expected no err at height 2") + assert.Equal(v.Hash(), state.NextValidators.Hash(), "expected validator hashes to match") + + // Increment height, save; should be able to load for next & next next height. + state.LastBlockHeight++ + nextHeight := state.LastBlockHeight + 1 + err = statestore.Save(state) + require.NoError(t, err) + vp0, err := statestore.LoadValidators(nextHeight + 0) + assert.Nil(err, "expected no err") + vp1, err := statestore.LoadValidators(nextHeight + 1) + assert.Nil(err, "expected no err") + assert.Equal(vp0.Hash(), state.Validators.Hash(), "expected validator hashes to match") + assert.Equal(vp1.Hash(), state.NextValidators.Hash(), "expected next validator hashes to match") +} + +// TestValidatorChangesSaveLoad tests saving and loading a validator set with changes. +func TestOneValidatorChangesSaveLoad(t *testing.T) { + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + // Change vals at these heights. + changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20} + N := len(changeHeights) + + // Build the validator history by running updateState + // with the right validator set for each height. + highestHeight := changeHeights[N-1] + 5 + changeIndex := 0 + _, val := state.Validators.GetByIndex(0) + power := val.VotingPower + var err error + var validatorUpdates []*types.Validator + for i := int64(1); i < highestHeight; i++ { + // When we get to a change height, use the next pubkey. + if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] { + changeIndex++ + power++ + } + header, blockID, responses := makeHeaderPartsResponsesValPowerChange(state, power) + validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.ValidatorUpdates) + require.NoError(t, err) + state, err = sm.UpdateState(state, blockID, &header, responses, validatorUpdates) + require.NoError(t, err) + err = stateStore.Save(state) + require.NoError(t, err) + } + + // On each height change, increment the power by one. + testCases := make([]int64, highestHeight) + changeIndex = 0 + power = val.VotingPower + for i := int64(1); i < highestHeight+1; i++ { + // We get to the height after a change height use the next pubkey (note + // our counter starts at 0 this time). + if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 { + changeIndex++ + power++ + } + testCases[i-1] = power + } + + for i, power := range testCases { + v, err := stateStore.LoadValidators(int64(i + 1 + 1)) // +1 because vset changes delayed by 1 block. + assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", i)) + assert.Equal(t, v.Size(), 1, "validator set size is greater than 1: %d", v.Size()) + _, val := v.GetByIndex(0) + + assert.Equal(t, val.VotingPower, power, fmt.Sprintf(`unexpected powerat + height %d`, i)) + } +} + +func TestProposerFrequency(t *testing.T) { + // some explicit test cases + testCases := []struct { + powers []int64 + }{ + // 2 vals + {[]int64{1, 1}}, + {[]int64{1, 2}}, + {[]int64{1, 100}}, + {[]int64{5, 5}}, + {[]int64{5, 100}}, + {[]int64{50, 50}}, + {[]int64{50, 100}}, + {[]int64{1, 1000}}, + + // 3 vals + {[]int64{1, 1, 1}}, + {[]int64{1, 2, 3}}, + {[]int64{1, 2, 3}}, + {[]int64{1, 1, 10}}, + {[]int64{1, 1, 100}}, + {[]int64{1, 10, 100}}, + {[]int64{1, 1, 1000}}, + {[]int64{1, 10, 1000}}, + {[]int64{1, 100, 1000}}, + + // 4 vals + {[]int64{1, 1, 1, 1}}, + {[]int64{1, 2, 3, 4}}, + {[]int64{1, 1, 1, 10}}, + {[]int64{1, 1, 1, 100}}, + {[]int64{1, 1, 1, 1000}}, + {[]int64{1, 1, 10, 100}}, + {[]int64{1, 1, 10, 1000}}, + {[]int64{1, 1, 100, 1000}}, + {[]int64{1, 10, 100, 1000}}, + } + + for caseNum, testCase := range testCases { + // run each case 5 times to sample different + // initial priorities + for i := 0; i < 5; i++ { + valSet := genValSetWithPowers(testCase.powers) + testProposerFreq(t, caseNum, valSet) + } + } + + // some random test cases with up to 100 validators + maxVals := 100 + maxPower := 1000 + nTestCases := 5 + for i := 0; i < nTestCases; i++ { + N := cmtrand.Int()%maxVals + 1 + vals := make([]*types.Validator, N) + totalVotePower := int64(0) + for j := 0; j < N; j++ { + // make sure votePower > 0 + votePower := int64(cmtrand.Int()%maxPower) + 1 + totalVotePower += votePower + privVal := types.NewMockPV() + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) + val := types.NewValidator(pubKey, votePower) + val.ProposerPriority = cmtrand.Int64() + vals[j] = val + } + valSet := types.NewValidatorSet(vals) + valSet.RescalePriorities(totalVotePower) + testProposerFreq(t, i, valSet) + } +} + +// new val set with given powers and random initial priorities +func genValSetWithPowers(powers []int64) *types.ValidatorSet { + size := len(powers) + vals := make([]*types.Validator, size) + totalVotePower := int64(0) + for i := 0; i < size; i++ { + totalVotePower += powers[i] + val := types.NewValidator(ed25519.GenPrivKey().PubKey(), powers[i]) + val.ProposerPriority = cmtrand.Int64() + vals[i] = val + } + valSet := types.NewValidatorSet(vals) + valSet.RescalePriorities(totalVotePower) + return valSet +} + +// test a proposer appears as frequently as expected +func testProposerFreq(t *testing.T, caseNum int, valSet *types.ValidatorSet) { + N := valSet.Size() + totalPower := valSet.TotalVotingPower() + + // run the proposer selection and track frequencies + runMult := 1 + runs := int(totalPower) * runMult + freqs := make([]int, N) + for i := 0; i < runs; i++ { + prop := valSet.GetProposer() + idx, _ := valSet.GetByAddress(prop.Address) + freqs[idx]++ + valSet.IncrementProposerPriority(1) + } + + // assert frequencies match expected (max off by 1) + for i, freq := range freqs { + _, val := valSet.GetByIndex(int32(i)) + expectFreq := int(val.VotingPower) * runMult + gotFreq := freq + abs := int(math.Abs(float64(expectFreq - gotFreq))) + + // max bound on expected vs seen freq was proven + // to be 1 for the 2 validator case in + // https://github.com/cwgoes/tm-proposer-idris + // and inferred to generalize to N-1 + bound := N - 1 + require.True( + t, + abs <= bound, + fmt.Sprintf("Case %d val %d (%d): got %d, expected %d", caseNum, i, N, gotFreq, expectFreq), + ) + } +} + +// TestProposerPriorityDoesNotGetResetToZero assert that we preserve accum when calling updateState +// see https://github.com/tendermint/tendermint/issues/2718 +func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) { + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + val1VotingPower := int64(10) + val1PubKey := ed25519.GenPrivKey().PubKey() + val1 := &types.Validator{Address: val1PubKey.Address(), PubKey: val1PubKey, VotingPower: val1VotingPower} + + state.Validators = types.NewValidatorSet([]*types.Validator{val1}) + state.NextValidators = state.Validators + + // NewValidatorSet calls IncrementProposerPriority but uses on a copy of val1 + assert.EqualValues(t, 0, val1.ProposerPriority) + + block, err := makeBlock(state, state.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + updatedState, err := sm.UpdateState(state, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + curTotal := val1VotingPower + // one increment step and one validator: 0 + power - total_power == 0 + assert.Equal(t, 0+val1VotingPower-curTotal, updatedState.NextValidators.Validators[0].ProposerPriority) + + // add a validator + val2PubKey := ed25519.GenPrivKey().PubKey() + val2VotingPower := int64(100) + fvp, err := cryptoenc.PubKeyToProto(val2PubKey) + require.NoError(t, err) + + updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val2VotingPower} + validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal}) + assert.NoError(t, err) + updatedState2, err := sm.UpdateState(updatedState, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + + require.Equal(t, len(updatedState2.NextValidators.Validators), 2) + _, updatedVal1 := updatedState2.NextValidators.GetByAddress(val1PubKey.Address()) + _, addedVal2 := updatedState2.NextValidators.GetByAddress(val2PubKey.Address()) + + // adding a validator should not lead to a ProposerPriority equal to zero (unless the combination of averaging and + // incrementing would cause so; which is not the case here) + // Steps from adding new validator: + // 0 - val1 prio is 0, TVP after add: + wantVal1Prio := int64(0) + totalPowerAfter := val1VotingPower + val2VotingPower + // 1. Add - Val2 should be initially added with (-123) => + wantVal2Prio := -(totalPowerAfter + (totalPowerAfter >> 3)) + // 2. Scale - noop + // 3. Center - with avg, resulting val2:-61, val1:62 + avg := big.NewInt(0).Add(big.NewInt(wantVal1Prio), big.NewInt(wantVal2Prio)) + avg.Div(avg, big.NewInt(2)) + wantVal2Prio -= avg.Int64() // -61 + wantVal1Prio -= avg.Int64() // 62 + + // 4. Steps from IncrementProposerPriority + wantVal1Prio += val1VotingPower // 72 + wantVal2Prio += val2VotingPower // 39 + wantVal1Prio -= totalPowerAfter // -38 as val1 is proposer + + assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority) + assert.Equal(t, wantVal2Prio, addedVal2.ProposerPriority) + + // Updating a validator does not reset the ProposerPriority to zero: + // 1. Add - Val2 VotingPower change to 1 => + updatedVotingPowVal2 := int64(1) + updateVal := abci.ValidatorUpdate{PubKey: fvp, Power: updatedVotingPowVal2} + validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateVal}) + assert.NoError(t, err) + + // this will cause the diff of priorities (77) + // to be larger than threshold == 2*totalVotingPower (22): + updatedState3, err := sm.UpdateState(updatedState2, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + + require.Equal(t, len(updatedState3.NextValidators.Validators), 2) + _, prevVal1 := updatedState3.Validators.GetByAddress(val1PubKey.Address()) + _, prevVal2 := updatedState3.Validators.GetByAddress(val2PubKey.Address()) + _, updatedVal1 = updatedState3.NextValidators.GetByAddress(val1PubKey.Address()) + _, updatedVal2 := updatedState3.NextValidators.GetByAddress(val2PubKey.Address()) + + // 2. Scale + // old prios: v1(10):-38, v2(1):39 + wantVal1Prio = prevVal1.ProposerPriority + wantVal2Prio = prevVal2.ProposerPriority + // scale to diffMax = 22 = 2 * tvp, diff=39-(-38)=77 + // new totalPower + totalPower := updatedVal1.VotingPower + updatedVal2.VotingPower + dist := wantVal2Prio - wantVal1Prio + // ratio := (dist + 2*totalPower - 1) / 2*totalPower = 98/22 = 4 + ratio := (dist + 2*totalPower - 1) / (2 * totalPower) + // v1(10):-38/4, v2(1):39/4 + wantVal1Prio /= ratio // -9 + wantVal2Prio /= ratio // 9 + + // 3. Center - noop + // 4. IncrementProposerPriority() -> + // v1(10):-9+10, v2(1):9+1 -> v2 proposer so subsract tvp(11) + // v1(10):1, v2(1):-1 + wantVal2Prio += updatedVal2.VotingPower // 10 -> prop + wantVal1Prio += updatedVal1.VotingPower // 1 + wantVal2Prio -= totalPower // -1 + + assert.Equal(t, wantVal2Prio, updatedVal2.ProposerPriority) + assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority) +} + +func TestProposerPriorityProposerAlternates(t *testing.T) { + // Regression test that would fail if the inner workings of + // IncrementProposerPriority change. + // Additionally, make sure that same power validators alternate if both + // have the same voting power (and the 2nd was added later). + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + val1VotingPower := int64(10) + val1PubKey := ed25519.GenPrivKey().PubKey() + val1 := &types.Validator{Address: val1PubKey.Address(), PubKey: val1PubKey, VotingPower: val1VotingPower} + + // reset state validators to above validator + state.Validators = types.NewValidatorSet([]*types.Validator{val1}) + state.NextValidators = state.Validators + // we only have one validator: + assert.Equal(t, val1PubKey.Address(), state.Validators.Proposer.Address) + + block, err := makeBlock(state, state.LastBlockHeight+1, new(types.Commit)) + assert.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + // no updates: + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + updatedState, err := sm.UpdateState(state, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + + // 0 + 10 (initial prio) - 10 (avg) - 10 (mostest - total) = -10 + totalPower := val1VotingPower + wantVal1Prio := 0 + val1VotingPower - totalPower + assert.Equal(t, wantVal1Prio, updatedState.NextValidators.Validators[0].ProposerPriority) + assert.Equal(t, val1PubKey.Address(), updatedState.NextValidators.Proposer.Address) + + // add a validator with the same voting power as the first + val2PubKey := ed25519.GenPrivKey().PubKey() + fvp, err := cryptoenc.PubKeyToProto(val2PubKey) + require.NoError(t, err) + updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val1VotingPower} + validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal}) + assert.NoError(t, err) + + updatedState2, err := sm.UpdateState(updatedState, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + + require.Equal(t, len(updatedState2.NextValidators.Validators), 2) + assert.Equal(t, updatedState2.Validators, updatedState.NextValidators) + + // val1 will still be proposer as val2 just got added: + assert.Equal(t, val1PubKey.Address(), updatedState.NextValidators.Proposer.Address) + assert.Equal(t, updatedState2.Validators.Proposer.Address, updatedState2.NextValidators.Proposer.Address) + assert.Equal(t, updatedState2.Validators.Proposer.Address, val1PubKey.Address()) + assert.Equal(t, updatedState2.NextValidators.Proposer.Address, val1PubKey.Address()) + + _, updatedVal1 := updatedState2.NextValidators.GetByAddress(val1PubKey.Address()) + _, oldVal1 := updatedState2.Validators.GetByAddress(val1PubKey.Address()) + _, updatedVal2 := updatedState2.NextValidators.GetByAddress(val2PubKey.Address()) + + // 1. Add + val2VotingPower := val1VotingPower + totalPower = val1VotingPower + val2VotingPower // 20 + v2PrioWhenAddedVal2 := -(totalPower + (totalPower >> 3)) // -22 + // 2. Scale - noop + // 3. Center + avgSum := big.NewInt(0).Add(big.NewInt(v2PrioWhenAddedVal2), big.NewInt(oldVal1.ProposerPriority)) + avg := avgSum.Div(avgSum, big.NewInt(2)) // -11 + expectedVal2Prio := v2PrioWhenAddedVal2 - avg.Int64() // -11 + expectedVal1Prio := oldVal1.ProposerPriority - avg.Int64() // 11 + // 4. Increment + expectedVal2Prio += val2VotingPower // -11 + 10 = -1 + expectedVal1Prio += val1VotingPower // 11 + 10 == 21 + expectedVal1Prio -= totalPower // 1, val1 proposer + + assert.EqualValues(t, expectedVal1Prio, updatedVal1.ProposerPriority) + assert.EqualValues( + t, + expectedVal2Prio, + updatedVal2.ProposerPriority, + "unexpected proposer priority for validator: %v", + updatedVal2, + ) + + validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + updatedState3, err := sm.UpdateState(updatedState2, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + + assert.Equal(t, updatedState3.Validators.Proposer.Address, updatedState3.NextValidators.Proposer.Address) + + assert.Equal(t, updatedState3.Validators, updatedState2.NextValidators) + _, updatedVal1 = updatedState3.NextValidators.GetByAddress(val1PubKey.Address()) + _, updatedVal2 = updatedState3.NextValidators.GetByAddress(val2PubKey.Address()) + + // val1 will still be proposer: + assert.Equal(t, val1PubKey.Address(), updatedState3.NextValidators.Proposer.Address) + + // check if expected proposer prio is matched: + // Increment + expectedVal2Prio2 := expectedVal2Prio + val2VotingPower // -1 + 10 = 9 + expectedVal1Prio2 := expectedVal1Prio + val1VotingPower // 1 + 10 == 11 + expectedVal1Prio2 -= totalPower // -9, val1 proposer + + assert.EqualValues( + t, + expectedVal1Prio2, + updatedVal1.ProposerPriority, + "unexpected proposer priority for validator: %v", + updatedVal2, + ) + assert.EqualValues( + t, + expectedVal2Prio2, + updatedVal2.ProposerPriority, + "unexpected proposer priority for validator: %v", + updatedVal2, + ) + + // no changes in voting power and both validators have same voting power + // -> proposers should alternate: + oldState := updatedState3 + abciResponses = &abci.ResponseFinalizeBlock{} + validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + oldState, err = sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + expectedVal1Prio2 = 1 + expectedVal2Prio2 = -1 + expectedVal1Prio = -9 + expectedVal2Prio = 9 + + for i := 0; i < 1000; i++ { + // no validator updates: + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + updatedState, err := sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates) + assert.NoError(t, err) + // alternate (and cyclic priorities): + assert.NotEqual( + t, + updatedState.Validators.Proposer.Address, + updatedState.NextValidators.Proposer.Address, + "iter: %v", + i, + ) + assert.Equal(t, oldState.Validators.Proposer.Address, updatedState.NextValidators.Proposer.Address, "iter: %v", i) + + _, updatedVal1 = updatedState.NextValidators.GetByAddress(val1PubKey.Address()) + _, updatedVal2 = updatedState.NextValidators.GetByAddress(val2PubKey.Address()) + + if i%2 == 0 { + assert.Equal(t, updatedState.Validators.Proposer.Address, val2PubKey.Address()) + assert.Equal(t, expectedVal1Prio, updatedVal1.ProposerPriority) // -19 + assert.Equal(t, expectedVal2Prio, updatedVal2.ProposerPriority) // 0 + } else { + assert.Equal(t, updatedState.Validators.Proposer.Address, val1PubKey.Address()) + assert.Equal(t, expectedVal1Prio2, updatedVal1.ProposerPriority) // -9 + assert.Equal(t, expectedVal2Prio2, updatedVal2.ProposerPriority) // -10 + } + // update for next iteration: + oldState = updatedState + } +} + +func TestLargeGenesisValidator(t *testing.T) { + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + + genesisVotingPower := types.MaxTotalVotingPower / 1000 + genesisPubKey := ed25519.GenPrivKey().PubKey() + // fmt.Println("genesis addr: ", genesisPubKey.Address()) + genesisVal := &types.Validator{ + Address: genesisPubKey.Address(), + PubKey: genesisPubKey, + VotingPower: genesisVotingPower, + } + // reset state validators to above validator + state.Validators = types.NewValidatorSet([]*types.Validator{genesisVal}) + state.NextValidators = state.Validators + require.True(t, len(state.Validators.Validators) == 1) + + // update state a few times with no validator updates + // asserts that the single validator's ProposerPrio stays the same + oldState := state + for i := 0; i < 10; i++ { + // no updates: + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + block, err := makeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + updatedState, err := sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + // no changes in voting power (ProposerPrio += VotingPower == Voting in 1st round; than shiftByAvg == 0, + // than -Total == -Voting) + // -> no change in ProposerPrio (stays zero): + assert.EqualValues(t, oldState.NextValidators, updatedState.NextValidators) + assert.EqualValues(t, 0, updatedState.NextValidators.Proposer.ProposerPriority) + + oldState = updatedState + } + // add another validator, do a few iterations (create blocks), + // add more validators with same voting power as the 2nd + // let the genesis validator "unbond", + // see how long it takes until the effect wears off and both begin to alternate + // see: https://github.com/tendermint/tendermint/issues/2960 + firstAddedValPubKey := ed25519.GenPrivKey().PubKey() + firstAddedValVotingPower := int64(10) + fvp, err := cryptoenc.PubKeyToProto(firstAddedValPubKey) + require.NoError(t, err) + firstAddedVal := abci.ValidatorUpdate{PubKey: fvp, Power: firstAddedValVotingPower} + validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{firstAddedVal}) + assert.NoError(t, err) + abciResponses := &abci.ResponseFinalizeBlock{ + ValidatorUpdates: []abci.ValidatorUpdate{firstAddedVal}, + } + block, err := makeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + updatedState, err := sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + + lastState := updatedState + for i := 0; i < 200; i++ { + // no updates: + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + block, err := makeBlock(lastState, lastState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + + bps, err = block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + updatedStateInner, err := sm.UpdateState(lastState, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + lastState = updatedStateInner + } + // set state to last state of above iteration + state = lastState + + // set oldState to state before above iteration + oldState = updatedState + _, oldGenesisVal := oldState.NextValidators.GetByAddress(genesisVal.Address) + _, newGenesisVal := state.NextValidators.GetByAddress(genesisVal.Address) + _, addedOldVal := oldState.NextValidators.GetByAddress(firstAddedValPubKey.Address()) + _, addedNewVal := state.NextValidators.GetByAddress(firstAddedValPubKey.Address()) + // expect large negative proposer priority for both (genesis validator decreased, 2nd validator increased): + assert.True(t, oldGenesisVal.ProposerPriority > newGenesisVal.ProposerPriority) + assert.True(t, addedOldVal.ProposerPriority < addedNewVal.ProposerPriority) + + // add 10 validators with the same voting power as the one added directly after genesis: + for i := 0; i < 10; i++ { + addedPubKey := ed25519.GenPrivKey().PubKey() + ap, err := cryptoenc.PubKeyToProto(addedPubKey) + require.NoError(t, err) + addedVal := abci.ValidatorUpdate{PubKey: ap, Power: firstAddedValVotingPower} + validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{addedVal}) + assert.NoError(t, err) + + abciResponses := &abci.ResponseFinalizeBlock{ + ValidatorUpdates: []abci.ValidatorUpdate{addedVal}, + } + block, err := makeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + state, err = sm.UpdateState(state, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + } + require.Equal(t, 10+2, len(state.NextValidators.Validators)) + + // remove genesis validator: + gp, err := cryptoenc.PubKeyToProto(genesisPubKey) + require.NoError(t, err) + removeGenesisVal := abci.ValidatorUpdate{PubKey: gp, Power: 0} + abciResponses = &abci.ResponseFinalizeBlock{ + ValidatorUpdates: []abci.ValidatorUpdate{removeGenesisVal}, + } + + block, err = makeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + + bps, err = block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + updatedState, err = sm.UpdateState(state, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + // only the first added val (not the genesis val) should be left + assert.Equal(t, 11, len(updatedState.NextValidators.Validators)) + + // call update state until the effect for the 3rd added validator + // being proposer for a long time after the genesis validator left wears off: + curState := updatedState + count := 0 + isProposerUnchanged := true + for isProposerUnchanged { + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + block, err = makeBlock(curState, curState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + curState, err = sm.UpdateState(curState, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + if !bytes.Equal(curState.Validators.Proposer.Address, curState.NextValidators.Proposer.Address) { + isProposerUnchanged = false + } + count++ + } + updatedState = curState + // the proposer changes after this number of blocks + firstProposerChangeExpectedAfter := 1 + assert.Equal(t, firstProposerChangeExpectedAfter, count) + // store proposers here to see if we see them again in the same order: + numVals := len(updatedState.Validators.Validators) + proposers := make([]*types.Validator, numVals) + for i := 0; i < 100; i++ { + // no updates: + abciResponses := &abci.ResponseFinalizeBlock{} + validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.ValidatorUpdates) + require.NoError(t, err) + + block, err := makeBlock(updatedState, updatedState.LastBlockHeight+1, new(types.Commit)) + require.NoError(t, err) + + bps, err := block.MakePartSet(testPartSize) + require.NoError(t, err) + + blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} + + updatedState, err = sm.UpdateState(updatedState, blockID, &block.Header, abciResponses, validatorUpdates) + require.NoError(t, err) + if i > numVals { // expect proposers to cycle through after the first iteration (of numVals blocks): + if proposers[i%numVals] == nil { + proposers[i%numVals] = updatedState.NextValidators.Proposer + } else { + assert.Equal(t, proposers[i%numVals], updatedState.NextValidators.Proposer) + } + } + } +} + +func TestStoreLoadValidatorsIncrementsProposerPriority(t *testing.T) { + const valSetSize = 2 + tearDown, stateDB, state := setupTestCase(t) + t.Cleanup(func() { tearDown(t) }) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state.Validators = genValSet(valSetSize) + state.NextValidators = state.Validators.CopyIncrementProposerPriority(1) + err := stateStore.Save(state) + require.NoError(t, err) + + nextHeight := state.LastBlockHeight + 1 + + v0, err := stateStore.LoadValidators(nextHeight) + assert.Nil(t, err) + acc0 := v0.Validators[0].ProposerPriority + + v1, err := stateStore.LoadValidators(nextHeight + 1) + assert.Nil(t, err) + acc1 := v1.Validators[0].ProposerPriority + + assert.NotEqual(t, acc1, acc0, "expected ProposerPriority value to change between heights") +} + +// TestValidatorChangesSaveLoad tests saving and loading a validator set with +// changes. +func TestManyValidatorChangesSaveLoad(t *testing.T) { + const valSetSize = 7 + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + require.Equal(t, int64(0), state.LastBlockHeight) + state.Validators = genValSet(valSetSize) + state.NextValidators = state.Validators.CopyIncrementProposerPriority(1) + err := stateStore.Save(state) + require.NoError(t, err) + + _, valOld := state.Validators.GetByIndex(0) + pubkeyOld := valOld.PubKey + pubkey := ed25519.GenPrivKey().PubKey() + + // Swap the first validator with a new one (validator set size stays the same). + header, blockID, responses := makeHeaderPartsResponsesValPubKeyChange(state, pubkey) + + // Save state etc. + var validatorUpdates []*types.Validator + validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.ValidatorUpdates) + require.NoError(t, err) + state, err = sm.UpdateState(state, blockID, &header, responses, validatorUpdates) + require.Nil(t, err) + nextHeight := state.LastBlockHeight + 1 + err = stateStore.Save(state) + require.NoError(t, err) + + // Load nextheight, it should be the oldpubkey. + v0, err := stateStore.LoadValidators(nextHeight) + assert.Nil(t, err) + assert.Equal(t, valSetSize, v0.Size()) + index, val := v0.GetByAddress(pubkeyOld.Address()) + assert.NotNil(t, val) + if index < 0 { + t.Fatal("expected to find old validator") + } + + // Load nextheight+1, it should be the new pubkey. + v1, err := stateStore.LoadValidators(nextHeight + 1) + assert.Nil(t, err) + assert.Equal(t, valSetSize, v1.Size()) + index, val = v1.GetByAddress(pubkey.Address()) + assert.NotNil(t, val) + if index < 0 { + t.Fatal("expected to find newly added validator") + } +} + +func TestStateMakeBlock(t *testing.T) { + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + + proposerAddress := state.Validators.GetProposer().Address + stateVersion := state.Version.Consensus + block, err := makeBlock(state, 2, new(types.Commit)) + require.NoError(t, err) + + // test we set some fields + assert.Equal(t, stateVersion, block.Version) + assert.Equal(t, proposerAddress, block.ProposerAddress) +} + +// TestConsensusParamsChangesSaveLoad tests saving and loading consensus params +// with changes. +func TestConsensusParamsChangesSaveLoad(t *testing.T) { + tearDown, stateDB, state := setupTestCase(t) + defer tearDown(t) + + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + + // Change vals at these heights. + changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20} + N := len(changeHeights) + + // Each valset is just one validator. + // create list of them. + params := make([]types.ConsensusParams, N+1) + params[0] = state.ConsensusParams + for i := 1; i < N+1; i++ { + params[i] = *types.DefaultConsensusParams() + params[i].Block.MaxBytes += int64(i) + + } + + // Build the params history by running updateState + // with the right params set for each height. + highestHeight := changeHeights[N-1] + 5 + changeIndex := 0 + cp := params[changeIndex] + var err error + var validatorUpdates []*types.Validator + for i := int64(1); i < highestHeight; i++ { + // When we get to a change height, use the next params. + if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] { + changeIndex++ + cp = params[changeIndex] + } + header, blockID, responses := makeHeaderPartsResponsesParams(state, cp.ToProto()) + validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.ValidatorUpdates) + require.NoError(t, err) + state, err = sm.UpdateState(state, blockID, &header, responses, validatorUpdates) + + require.NoError(t, err) + err = stateStore.Save(state) + require.NoError(t, err) + } + + // Make all the test cases by using the same params until after the change. + testCases := make([]paramsChangeTestCase, highestHeight) + changeIndex = 0 + cp = params[changeIndex] + for i := int64(1); i < highestHeight+1; i++ { + // We get to the height after a change height use the next pubkey (note + // our counter starts at 0 this time). + if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 { + changeIndex++ + cp = params[changeIndex] + } + testCases[i-1] = paramsChangeTestCase{i, cp} + } + + for _, testCase := range testCases { + p, err := stateStore.LoadConsensusParams(testCase.height) + assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", testCase.height)) + assert.EqualValues(t, testCase.params, p, fmt.Sprintf(`unexpected consensus params at + height %d`, testCase.height)) + } +} + +func TestStateProto(t *testing.T) { + tearDown, _, state := setupTestCase(t) + defer tearDown(t) + + tc := []struct { + testName string + state *sm.State + expPass1 bool + expPass2 bool + }{ + {"empty state", &sm.State{}, true, false}, + {"nil failure state", nil, false, false}, + {"success state", &state, true, true}, + } + + for _, tt := range tc { + tt := tt + pbs, err := tt.state.ToProto() + if !tt.expPass1 { + assert.Error(t, err) + } else { + assert.NoError(t, err, tt.testName) + } + + smt, err := sm.FromProto(pbs) + if tt.expPass2 { + require.NoError(t, err, tt.testName) + require.Equal(t, tt.state, smt, tt.testName) + } else { + require.Error(t, err, tt.testName) + } + } +} + +func TestMedianTime(t *testing.T) { + val1 := types.NewValidator(ed25519.GenPrivKey().PubKey(), 30) + val2 := types.NewValidator(ed25519.GenPrivKey().PubKey(), 30) + val3 := types.NewValidator(ed25519.GenPrivKey().PubKey(), 30) + + vals := types.NewValidatorSet([]*types.Validator{val1, val2, val3}) + + t.Run("all validators present", func(t *testing.T) { + now := time.Now() + commit := &types.Commit{ + Height: 1, + Signatures: []types.CommitSig{ + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val1.Address, + Timestamp: now, + }, + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val2.Address, + Timestamp: now.Add(1 * time.Minute), + }, + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val3.Address, + Timestamp: now.Add(2 * time.Minute), + }, + }, + } + + medianTime, err := sm.MedianTime(commit, vals) + require.NoError(t, err) + require.Equal(t, medianTime, now.Add(1*time.Minute)) + }) + + t.Run("validator not in validator set", func(t *testing.T) { + unknownVal := ed25519.GenPrivKey().PubKey().Address() + now := time.Now() + commit := &types.Commit{ + Height: 1, + Signatures: []types.CommitSig{ + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val1.Address, + Timestamp: now, + }, + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: unknownVal, + Timestamp: now.Add(1 * time.Minute), + }, + }, + } + + _, err := sm.MedianTime(commit, vals) + require.Error(t, err) + require.Contains(t, err.Error(), "commit validator not found in validator set") + }) + + t.Run("not all validators present", func(t *testing.T) { + now := time.Now() + commit := &types.Commit{ + Height: 1, + Signatures: []types.CommitSig{ + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val1.Address, + Timestamp: now, + }, + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: val2.Address, + Timestamp: now.Add(1 * time.Minute), + }, + }, + } + + medianTime, err := sm.MedianTime(commit, vals) + require.NoError(t, err) + require.Equal(t, medianTime, now) + }) +} diff --git a/state/store.go b/state/store.go new file mode 100644 index 0000000..6463dc3 --- /dev/null +++ b/state/store.go @@ -0,0 +1,827 @@ +package state + +import ( + "encoding/binary" + "errors" + "fmt" + + "github.com/cosmos/gogoproto/proto" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtos "github.com/cometbft/cometbft/libs/os" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cometbft/cometbft/types" +) + +const ( + // persist validators every valSetCheckpointInterval blocks to avoid + // LoadValidators taking too much time. + // https://github.com/tendermint/tendermint/pull/3438 + // 100000 results in ~ 100ms to get 100 validators (see BenchmarkLoadValidators) + valSetCheckpointInterval = 100000 +) + +//------------------------------------------------------------------------ + +func calcValidatorsKey(height int64) []byte { + return []byte(fmt.Sprintf("validatorsKey:%v", height)) +} + +func calcConsensusParamsKey(height int64) []byte { + return []byte(fmt.Sprintf("consensusParamsKey:%v", height)) +} + +func calcABCIResponsesKey(height int64) []byte { + return []byte(fmt.Sprintf("abciResponsesKey:%v", height)) +} + +//---------------------- + +var lastABCIResponseKey = []byte("lastABCIResponseKey") +var offlineStateSyncHeight = []byte("offlineStateSyncHeightKey") + +//go:generate ../scripts/mockery_generate.sh Store + +// Store defines the state store interface +// +// It is used to retrieve current state and save and load ABCI responses, +// validators and consensus parameters +type Store interface { + // LoadFromDBOrGenesisFile loads the most recent state. + // If the chain is new it will use the genesis file from the provided genesis file path as the current state. + LoadFromDBOrGenesisFile(string) (State, error) + // LoadFromDBOrGenesisDoc loads the most recent state. + // If the chain is new it will use the genesis doc as the current state. + LoadFromDBOrGenesisDoc(*types.GenesisDoc) (State, error) + // Load loads the current state of the blockchain + Load() (State, error) + // LoadValidators loads the validator set at a given height + LoadValidators(int64) (*types.ValidatorSet, error) + // LoadFinalizeBlockResponse loads the abciResponse for a given height + LoadFinalizeBlockResponse(int64) (*abci.ResponseFinalizeBlock, error) + // LoadLastFinalizeBlockResponse loads the last abciResponse for a given height + LoadLastFinalizeBlockResponse(int64) (*abci.ResponseFinalizeBlock, error) + // LoadConsensusParams loads the consensus params for a given height + LoadConsensusParams(int64) (types.ConsensusParams, error) + // Save overwrites the previous state with the updated one + Save(State) error + // SaveFinalizeBlockResponse saves ABCIResponses for a given height + SaveFinalizeBlockResponse(int64, *abci.ResponseFinalizeBlock) error + // Bootstrap is used for bootstrapping state when not starting from a initial height. + Bootstrap(State) error + // PruneStates takes the height from which to start pruning and which height stop at + PruneStates(int64, int64, int64) error + // Saves the height at which the store is bootstrapped after out of band statesync + SetOfflineStateSyncHeight(height int64) error + // Gets the height at which the store is bootstrapped after out of band statesync + GetOfflineStateSyncHeight() (int64, error) + // Close closes the connection with the database + Close() error +} + +// dbStore wraps a db (github.com/cometbft/cometbft-db) +type dbStore struct { + db dbm.DB + + StoreOptions +} + +type StoreOptions struct { + // DiscardABCIResponses determines whether or not the store + // retains all ABCIResponses. If DiscardABCIResponses is enabled, + // the store will maintain only the response object from the latest + // height. + DiscardABCIResponses bool +} + +var _ Store = (*dbStore)(nil) + +func IsEmpty(store dbStore) (bool, error) { + state, err := store.Load() + if err != nil { + return false, err + } + return state.IsEmpty(), nil +} + +// NewStore creates the dbStore of the state pkg. +func NewStore(db dbm.DB, options StoreOptions) Store { + return dbStore{db, options} +} + +// LoadStateFromDBOrGenesisFile loads the most recent state from the database, +// or creates a new one from the given genesisFilePath. +func (store dbStore) LoadFromDBOrGenesisFile(genesisFilePath string) (State, error) { + state, err := store.Load() + if err != nil { + return State{}, err + } + if state.IsEmpty() { + var err error + state, err = MakeGenesisStateFromFile(genesisFilePath) + if err != nil { + return state, err + } + } + + return state, nil +} + +// LoadStateFromDBOrGenesisDoc loads the most recent state from the database, +// or creates a new one from the given genesisDoc. +func (store dbStore) LoadFromDBOrGenesisDoc(genesisDoc *types.GenesisDoc) (State, error) { + state, err := store.Load() + if err != nil { + return State{}, err + } + + if state.IsEmpty() { + var err error + state, err = MakeGenesisState(genesisDoc) + if err != nil { + return state, err + } + } + + return state, nil +} + +// LoadState loads the State from the database. +func (store dbStore) Load() (State, error) { + return store.loadState(stateKey) +} + +func (store dbStore) loadState(key []byte) (state State, err error) { + buf, err := store.db.Get(key) + if err != nil { + return state, err + } + if len(buf) == 0 { + return state, nil + } + + sp := new(cmtstate.State) + + err = proto.Unmarshal(buf, sp) + if err != nil { + // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED + cmtos.Exit(fmt.Sprintf(`LoadState: Data has been corrupted or its spec has changed: + %v\n`, err)) + } + + sm, err := FromProto(sp) + if err != nil { + return state, err + } + return *sm, nil +} + +// Save persists the State, the ValidatorsInfo, and the ConsensusParamsInfo to the database. +// This flushes the writes (e.g. calls SetSync). +func (store dbStore) Save(state State) error { + return store.save(state, stateKey) +} + +func (store dbStore) save(state State, key []byte) error { + batch := store.db.NewBatch() + defer func(batch dbm.Batch) { + err := batch.Close() + if err != nil { + panic(err) + } + }(batch) + nextHeight := state.LastBlockHeight + 1 + // If first block, save validators for the block. + if nextHeight == 1 { + nextHeight = state.InitialHeight + // This extra logic due to validator set changes being delayed 1 block. + // It may get overwritten due to InitChain validator updates. + if err := store.saveValidatorsInfo(nextHeight, nextHeight, state.Validators, batch); err != nil { + return err + } + } + // Save next validators. + if err := store.saveValidatorsInfo(nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators, batch); err != nil { + return err + } + // Save next consensus params. + if err := store.saveConsensusParamsInfo(nextHeight, + state.LastHeightConsensusParamsChanged, state.ConsensusParams, batch); err != nil { + return err + } + if err := batch.Set(key, state.Bytes()); err != nil { + return err + } + if err := batch.WriteSync(); err != nil { + panic(err) + } + return nil +} + +// BootstrapState saves a new state, used e.g. by state sync when starting from non-zero height. +func (store dbStore) Bootstrap(state State) error { + batch := store.db.NewBatch() + defer func(batch dbm.Batch) { + err := batch.Close() + if err != nil { + panic(err) + } + }(batch) + height := state.LastBlockHeight + 1 + if height == 1 { + height = state.InitialHeight + } + + if height > 1 && !state.LastValidators.IsNilOrEmpty() { + if err := store.saveValidatorsInfo(height-1, height-1, state.LastValidators, batch); err != nil { + return err + } + } + + if err := store.saveValidatorsInfo(height, height, state.Validators, batch); err != nil { + return err + } + + if err := store.saveValidatorsInfo(height+1, height+1, state.NextValidators, batch); err != nil { + return err + } + + if err := store.saveConsensusParamsInfo(height, + state.LastHeightConsensusParamsChanged, state.ConsensusParams, batch); err != nil { + return err + } + + if err := batch.Set(stateKey, state.Bytes()); err != nil { + return err + } + + if err := batch.WriteSync(); err != nil { + panic(err) + } + + return batch.Close() +} + +// PruneStates deletes states between the given heights (including from, excluding to). It is not +// guaranteed to delete all states, since the last checkpointed state and states being pointed to by +// e.g. `LastHeightChanged` must remain. The state at to must also exist. +// +// The from parameter is necessary since we can't do a key scan in a performant way due to the key +// encoding not preserving ordering: https://github.com/tendermint/tendermint/issues/4567 +// This will cause some old states to be left behind when doing incremental partial prunes, +// specifically older checkpoints and LastHeightChanged targets. +func (store dbStore) PruneStates(from int64, to int64, evidenceThresholdHeight int64) error { + if from <= 0 || to <= 0 { + return fmt.Errorf("from height %v and to height %v must be greater than 0", from, to) + } + if from >= to { + return fmt.Errorf("from height %v must be lower than to height %v", from, to) + } + + valInfo, err := loadValidatorsInfo(store.db, min(to, evidenceThresholdHeight)) + if err != nil { + return fmt.Errorf("validators at height %v not found: %w", to, err) + } + paramsInfo, err := store.loadConsensusParamsInfo(to) + if err != nil { + return fmt.Errorf("consensus params at height %v not found: %w", to, err) + } + + keepVals := make(map[int64]bool) + if valInfo.ValidatorSet == nil { + keepVals[valInfo.LastHeightChanged] = true + keepVals[lastStoredHeightFor(to, valInfo.LastHeightChanged)] = true // keep last checkpoint too + } + keepParams := make(map[int64]bool) + if paramsInfo.ConsensusParams.Equal(&cmtproto.ConsensusParams{}) { + keepParams[paramsInfo.LastHeightChanged] = true + } + + batch := store.db.NewBatch() + defer batch.Close() + pruned := uint64(0) + + // We have to delete in reverse order, to avoid deleting previous heights that have validator + // sets and consensus params that we may need to retrieve. + for h := to - 1; h >= from; h-- { + // For heights we keep, we must make sure they have the full validator set or consensus + // params, otherwise they will panic if they're retrieved directly (instead of + // indirectly via a LastHeightChanged pointer). + if keepVals[h] { + v, err := loadValidatorsInfo(store.db, h) + if err != nil || v.ValidatorSet == nil { + vip, err := store.LoadValidators(h) + if err != nil { + return err + } + + pvi, err := vip.ToProto() + if err != nil { + return err + } + + v.ValidatorSet = pvi + v.LastHeightChanged = h + + bz, err := v.Marshal() + if err != nil { + return err + } + err = batch.Set(calcValidatorsKey(h), bz) + if err != nil { + return err + } + } + } else if h < evidenceThresholdHeight { + err = batch.Delete(calcValidatorsKey(h)) + if err != nil { + return err + } + } + // else we keep the validator set because we might need + // it later on for evidence verification + + if keepParams[h] { + p, err := store.loadConsensusParamsInfo(h) + if err != nil { + return err + } + + if p.ConsensusParams.Equal(&cmtproto.ConsensusParams{}) { + params, err := store.LoadConsensusParams(h) + if err != nil { + return err + } + p.ConsensusParams = params.ToProto() + + p.LastHeightChanged = h + bz, err := p.Marshal() + if err != nil { + return err + } + + err = batch.Set(calcConsensusParamsKey(h), bz) + if err != nil { + return err + } + } + } else { + err = batch.Delete(calcConsensusParamsKey(h)) + if err != nil { + return err + } + } + + err = batch.Delete(calcABCIResponsesKey(h)) + if err != nil { + return err + } + pruned++ + + // avoid batches growing too large by flushing to database regularly + if pruned%1000 == 0 && pruned > 0 { + err := batch.Write() + if err != nil { + return err + } + batch.Close() + batch = store.db.NewBatch() + defer batch.Close() + } + } + + err = batch.WriteSync() + if err != nil { + return err + } + + return nil +} + +//------------------------------------------------------------------------ + +// TxResultsHash returns the root hash of a Merkle tree of +// ExecTxResulst responses (see ABCIResults.Hash) +// +// See merkle.SimpleHashFromByteSlices +func TxResultsHash(txResults []*abci.ExecTxResult) []byte { + return types.NewResults(txResults).Hash() +} + +// LoadFinalizeBlockResponse loads the DiscardABCIResponses for the given height from the +// database. If the node has D set to true, ErrABCIResponsesNotPersisted +// is persisted. If not found, ErrNoABCIResponsesForHeight is returned. +func (store dbStore) LoadFinalizeBlockResponse(height int64) (*abci.ResponseFinalizeBlock, error) { + if store.DiscardABCIResponses { + return nil, ErrFinalizeBlockResponsesNotPersisted + } + + buf, err := store.db.Get(calcABCIResponsesKey(height)) + if err != nil { + return nil, err + } + if len(buf) == 0 { + return nil, ErrNoABCIResponsesForHeight{height} + } + + resp := new(abci.ResponseFinalizeBlock) + err = resp.Unmarshal(buf) + // Check for an error or if the resp.AppHash is nil if so + // this means the unmarshalling should be a LegacyABCIResponses + // Depending on a source message content (serialized as ABCIResponses) + // there are instances where it can be deserialized as a FinalizeBlockResponse + // without causing an error. But the values will not be deserialized properly + // and, it will contain zero values, and one of them is an AppHash == nil + // This can be verified in the /state/compatibility_test.go file + if err != nil || resp.AppHash == nil { + // The data might be of the legacy ABCI response type, so + // we try to unmarshal that + legacyResp := new(cmtstate.LegacyABCIResponses) + if err := legacyResp.Unmarshal(buf); err != nil { + // only return an error, this method is only invoked through the `/block_results` not for state logic and + // some tests, so no need to exit cometbft if there's an error, just return it. + return nil, ErrABCIResponseCorruptedOrSpecChangeForHeight{Height: height, Err: err} + } + // The state store contains the old format. Migrate to + // the new ResponseFinalizeBlock format. Note that the + // new struct expects the AppHash which we don't have. + return responseFinalizeBlockFromLegacy(legacyResp), nil + } + + // TODO: ensure that buf is completely read. + + return resp, nil +} + +// LoadLastFinalizeBlockResponse loads the FinalizeBlockResponses from the most recent height. +// The height parameter is used to ensure that the response corresponds to the latest height. +// If not, an error is returned. +// +// This method is used for recovering in the case that we called the Commit ABCI +// method on the application but crashed before persisting the results. +func (store dbStore) LoadLastFinalizeBlockResponse(height int64) (*abci.ResponseFinalizeBlock, error) { + bz, err := store.db.Get(lastABCIResponseKey) + if err != nil { + return nil, err + } + + if len(bz) == 0 { + return nil, errors.New("no last ABCI response has been persisted") + } + + info := new(cmtstate.ABCIResponsesInfo) + err = info.Unmarshal(bz) + if err != nil { + cmtos.Exit(fmt.Sprintf(`LoadLastFinalizeBlockResponse: Data has been corrupted or its spec has + changed: %v\n`, err)) + } + + // Here we validate the result by comparing its height to the expected height. + if height != info.GetHeight() { + return nil, fmt.Errorf("expected height %d but last stored abci responses was at height %d", height, info.GetHeight()) + } + + // It is possible if this is called directly after an upgrade that + // ResponseFinalizeBlock is nil. In which case we use the legacy + // ABCI responses + if info.ResponseFinalizeBlock == nil { + // sanity check + if info.LegacyAbciResponses == nil { + panic("state store contains last abci response but it is empty") + } + return responseFinalizeBlockFromLegacy(info.LegacyAbciResponses), nil + } + + return info.ResponseFinalizeBlock, nil +} + +// SaveFinalizeBlockResponse persists the ResponseFinalizeBlock to the database. +// This is useful in case we crash after app.Commit and before s.Save(). +// Responses are indexed by height so they can also be loaded later to produce +// Merkle proofs. +// +// CONTRACT: height must be monotonically increasing every time this is called. +func (store dbStore) SaveFinalizeBlockResponse(height int64, resp *abci.ResponseFinalizeBlock) error { + var dtxs []*abci.ExecTxResult + // strip nil values, + for _, tx := range resp.TxResults { + if tx != nil { + dtxs = append(dtxs, tx) + } + } + resp.TxResults = dtxs + + // If the flag is false then we save the ABCIResponse. This can be used for the /BlockResults + // query or to reindex an event using the command line. + if !store.DiscardABCIResponses { + bz, err := resp.Marshal() + if err != nil { + return err + } + if err := store.db.Set(calcABCIResponsesKey(height), bz); err != nil { + return err + } + } + + // We always save the last ABCI response for crash recovery. + // This overwrites the previous saved ABCI Response. + response := &cmtstate.ABCIResponsesInfo{ + ResponseFinalizeBlock: resp, + Height: height, + } + bz, err := response.Marshal() + if err != nil { + return err + } + + return store.db.SetSync(lastABCIResponseKey, bz) +} + +//----------------------------------------------------------------------------- + +// LoadValidators loads the ValidatorSet for a given height. +// Returns ErrNoValSetForHeight if the validator set can't be found for this height. +func (store dbStore) LoadValidators(height int64) (*types.ValidatorSet, error) { + valInfo, err := loadValidatorsInfo(store.db, height) + if err != nil { + return nil, ErrNoValSetForHeight{height} + } + if valInfo.ValidatorSet == nil { + lastStoredHeight := lastStoredHeightFor(height, valInfo.LastHeightChanged) + valInfo2, err := loadValidatorsInfo(store.db, lastStoredHeight) + if err != nil || valInfo2.ValidatorSet == nil { + return nil, + fmt.Errorf("couldn't find validators at height %d (height %d was originally requested): %w", + lastStoredHeight, + height, + err, + ) + } + + vs, err := types.ValidatorSetFromProto(valInfo2.ValidatorSet) + if err != nil { + return nil, err + } + + vs.IncrementProposerPriority(cmtmath.SafeConvertInt32(height - lastStoredHeight)) // mutate + vi2, err := vs.ToProto() + if err != nil { + return nil, err + } + + valInfo2.ValidatorSet = vi2 + valInfo = valInfo2 + } + + vip, err := types.ValidatorSetFromProto(valInfo.ValidatorSet) + if err != nil { + return nil, err + } + + return vip, nil +} + +func lastStoredHeightFor(height, lastHeightChanged int64) int64 { + checkpointHeight := height - height%valSetCheckpointInterval + return cmtmath.MaxInt64(checkpointHeight, lastHeightChanged) +} + +// CONTRACT: Returned ValidatorsInfo can be mutated. +func loadValidatorsInfo(db dbm.DB, height int64) (*cmtstate.ValidatorsInfo, error) { + buf, err := db.Get(calcValidatorsKey(height)) + if err != nil { + return nil, err + } + + if len(buf) == 0 { + return nil, errors.New("value retrieved from db is empty") + } + + v := new(cmtstate.ValidatorsInfo) + err = v.Unmarshal(buf) + if err != nil { + // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED + cmtos.Exit(fmt.Sprintf(`LoadValidators: Data has been corrupted or its spec has changed: + %v\n`, err)) + } + // TODO: ensure that buf is completely read. + + return v, nil +} + +// saveValidatorsInfo persists the validator set. +// +// `height` is the effective height for which the validator is responsible for +// signing. It should be called from s.Save(), right before the state itself is +// persisted. +func (store dbStore) saveValidatorsInfo(height, lastHeightChanged int64, valSet *types.ValidatorSet, batch dbm.Batch) error { + if lastHeightChanged > height { + return errors.New("lastHeightChanged cannot be greater than ValidatorsInfo height") + } + valInfo := &cmtstate.ValidatorsInfo{ + LastHeightChanged: lastHeightChanged, + } + // Only persist validator set if it was updated or checkpoint height (see + // valSetCheckpointInterval) is reached. + if height == lastHeightChanged || height%valSetCheckpointInterval == 0 { + pv, err := valSet.ToProto() + if err != nil { + return err + } + valInfo.ValidatorSet = pv + } + + bz, err := valInfo.Marshal() + if err != nil { + return err + } + + err = batch.Set(calcValidatorsKey(height), bz) + if err != nil { + return err + } + + return nil +} + +//----------------------------------------------------------------------------- + +// ConsensusParamsInfo represents the latest consensus params, or the last height it changed + +// LoadConsensusParams loads the ConsensusParams for a given height. +func (store dbStore) LoadConsensusParams(height int64) (types.ConsensusParams, error) { + var ( + empty = types.ConsensusParams{} + emptypb = cmtproto.ConsensusParams{} + ) + paramsInfo, err := store.loadConsensusParamsInfo(height) + if err != nil { + return empty, fmt.Errorf("could not find consensus params for height #%d: %w", height, err) + } + + if paramsInfo.ConsensusParams.Equal(&emptypb) { + paramsInfo2, err := store.loadConsensusParamsInfo(paramsInfo.LastHeightChanged) + if err != nil { + return empty, fmt.Errorf( + "couldn't find consensus params at height %d as last changed from height %d: %w", + paramsInfo.LastHeightChanged, + height, + err, + ) + } + + paramsInfo = paramsInfo2 + } + + return types.ConsensusParamsFromProto(paramsInfo.ConsensusParams), nil +} + +func (store dbStore) loadConsensusParamsInfo(height int64) (*cmtstate.ConsensusParamsInfo, error) { + buf, err := store.db.Get(calcConsensusParamsKey(height)) + if err != nil { + return nil, err + } + if len(buf) == 0 { + return nil, errors.New("value retrieved from db is empty") + } + + paramsInfo := new(cmtstate.ConsensusParamsInfo) + if err = paramsInfo.Unmarshal(buf); err != nil { + // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED + cmtos.Exit(fmt.Sprintf(`LoadConsensusParams: Data has been corrupted or its spec has changed: + %v\n`, err)) + } + // TODO: ensure that buf is completely read. + + return paramsInfo, nil +} + +// saveConsensusParamsInfo persists the consensus params for the next block to disk. +// It should be called from s.Save(), right before the state itself is persisted. +// If the consensus params did not change after processing the latest block, +// only the last height for which they changed is persisted. +func (store dbStore) saveConsensusParamsInfo(nextHeight, changeHeight int64, params types.ConsensusParams, batch dbm.Batch) error { + paramsInfo := &cmtstate.ConsensusParamsInfo{ + LastHeightChanged: changeHeight, + } + + if changeHeight == nextHeight { + paramsInfo.ConsensusParams = params.ToProto() + } + bz, err := paramsInfo.Marshal() + if err != nil { + return err + } + + err = batch.Set(calcConsensusParamsKey(nextHeight), bz) + if err != nil { + return err + } + + return nil +} + +func (store dbStore) SetOfflineStateSyncHeight(height int64) error { + err := store.db.SetSync(offlineStateSyncHeight, int64ToBytes(height)) + if err != nil { + return err + } + return nil + +} + +// Gets the height at which the store is bootstrapped after out of band statesync +func (store dbStore) GetOfflineStateSyncHeight() (int64, error) { + + buf, err := store.db.Get(offlineStateSyncHeight) + if err != nil { + return 0, err + } + + if len(buf) == 0 { + return 0, errors.New("value empty") + } + + height := int64FromBytes(buf) + if height < 0 { + return 0, errors.New("invalid value for height: height cannot be negative") + } + return height, nil +} + +func (store dbStore) Close() error { + return store.db.Close() +} + +func min(a int64, b int64) int64 { + if a < b { + return a + } + return b +} + +// responseFinalizeBlockFromLegacy is a convenience function that takes the old abci responses and morphs +// it to the finalize block response. Note that the app hash is missing +func responseFinalizeBlockFromLegacy(legacyResp *cmtstate.LegacyABCIResponses) *abci.ResponseFinalizeBlock { + var response abci.ResponseFinalizeBlock + events := make([]abci.Event, 0) + + if legacyResp.DeliverTxs != nil { + response.TxResults = legacyResp.DeliverTxs + } + + // Check for begin block and end block and only append events or assign values if they are not nil + if legacyResp.BeginBlock != nil { + if legacyResp.BeginBlock.Events != nil { + // Add BeginBlock attribute to BeginBlock events + for idx := range legacyResp.BeginBlock.Events { + legacyResp.BeginBlock.Events[idx].Attributes = append(legacyResp.BeginBlock.Events[idx].Attributes, abci.EventAttribute{ + Key: "mode", + Value: "BeginBlock", + Index: false, + }) + } + events = append(events, legacyResp.BeginBlock.Events...) + } + } + if legacyResp.EndBlock != nil { + if legacyResp.EndBlock.ValidatorUpdates != nil { + response.ValidatorUpdates = legacyResp.EndBlock.ValidatorUpdates + } + if legacyResp.EndBlock.ConsensusParamUpdates != nil { + response.ConsensusParamUpdates = legacyResp.EndBlock.ConsensusParamUpdates + } + if legacyResp.EndBlock.Events != nil { + // Add EndBlock attribute to BeginBlock events + for idx := range legacyResp.EndBlock.Events { + legacyResp.EndBlock.Events[idx].Attributes = append(legacyResp.EndBlock.Events[idx].Attributes, abci.EventAttribute{ + Key: "mode", + Value: "EndBlock", + Index: false, + }) + } + events = append(events, legacyResp.EndBlock.Events...) + } + } + + response.Events = events + + // NOTE: AppHash is missing in the response but will + // be caught and filled in consensus/replay.go + return &response +} + +func int64FromBytes(bz []byte) int64 { + v, _ := binary.Varint(bz) + return v +} + +func int64ToBytes(i int64) []byte { + buf := make([]byte, binary.MaxVarintLen64) + n := binary.PutVarint(buf, i) + return buf[:n] +} diff --git a/state/store_test.go b/state/store_test.go new file mode 100644 index 0000000..dbb8551 --- /dev/null +++ b/state/store_test.go @@ -0,0 +1,358 @@ +package state_test + +import ( + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/internal/test" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +func TestStoreLoadValidators(t *testing.T) { + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + val, _ := types.RandValidator(true, 10) + vals := types.NewValidatorSet([]*types.Validator{val}) + + // 1) LoadValidators loads validators using a height where they were last changed + err := sm.SaveValidatorsInfo(stateDB, 1, 1, vals) + require.NoError(t, err) + err = sm.SaveValidatorsInfo(stateDB, 2, 1, vals) + require.NoError(t, err) + loadedVals, err := stateStore.LoadValidators(2) + require.NoError(t, err) + assert.NotZero(t, loadedVals.Size()) + + // 2) LoadValidators loads validators using a checkpoint height + + err = sm.SaveValidatorsInfo(stateDB, sm.ValSetCheckpointInterval, 1, vals) + require.NoError(t, err) + + loadedVals, err = stateStore.LoadValidators(sm.ValSetCheckpointInterval) + require.NoError(t, err) + assert.NotZero(t, loadedVals.Size()) +} + +func BenchmarkLoadValidators(b *testing.B) { + const valSetSize = 100 + + config := test.ResetTestRoot("state_") + defer os.RemoveAll(config.RootDir) + dbType := dbm.BackendType(config.DBBackend) + stateDB, err := dbm.NewDB("state", dbType, config.DBDir()) + require.NoError(b, err) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + if err != nil { + b.Fatal(err) + } + + state.Validators = genValSet(valSetSize) + state.NextValidators = state.Validators.CopyIncrementProposerPriority(1) + err = stateStore.Save(state) + require.NoError(b, err) + + for i := 10; i < 10000000000; i *= 10 { // 10, 100, 1000, ... + i := i + if err := sm.SaveValidatorsInfo(stateDB, + int64(i), state.LastHeightValidatorsChanged, state.NextValidators); err != nil { + b.Fatal(err) + } + + b.Run(fmt.Sprintf("height=%d", i), func(b *testing.B) { + for n := 0; n < b.N; n++ { + _, err := stateStore.LoadValidators(int64(i)) + if err != nil { + b.Fatal(err) + } + } + }) + } +} + +func TestPruneStates(t *testing.T) { + testcases := map[string]struct { + makeHeights int64 + pruneFrom int64 + pruneTo int64 + evidenceThresholdHeight int64 + expectErr bool + expectVals []int64 + expectParams []int64 + expectABCI []int64 + }{ + "error on pruning from 0": {100, 0, 5, 100, true, nil, nil, nil}, + "error when from > to": {100, 3, 2, 2, true, nil, nil, nil}, + "error when from == to": {100, 3, 3, 3, true, nil, nil, nil}, + "error when to does not exist": {100, 1, 101, 101, true, nil, nil, nil}, + "prune all": {100, 1, 100, 100, false, []int64{93, 100}, []int64{95, 100}, []int64{100}}, + "prune some": { + 10, 2, 8, 8, false, + []int64{1, 3, 8, 9, 10}, + []int64{1, 5, 8, 9, 10}, + []int64{1, 8, 9, 10}, + }, + "prune across checkpoint": { + 100001, 1, 100001, 100001, false, + []int64{99993, 100000, 100001}, + []int64{99995, 100001}, + []int64{100001}, + }, + "prune when evidence height < height": {20, 1, 18, 17, false, []int64{13, 17, 18, 19, 20}, []int64{15, 18, 19, 20}, []int64{18, 19, 20}}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + db := dbm.NewMemDB() + stateStore := sm.NewStore(db, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + pk := ed25519.GenPrivKey().PubKey() + + // Generate a bunch of state data. Validators change for heights ending with 3, and + // parameters when ending with 5. + validator := &types.Validator{Address: pk.Address(), VotingPower: 100, PubKey: pk} + validatorSet := &types.ValidatorSet{ + Validators: []*types.Validator{validator}, + Proposer: validator, + } + valsChanged := int64(0) + paramsChanged := int64(0) + + for h := int64(1); h <= tc.makeHeights; h++ { + if valsChanged == 0 || h%10 == 2 { + valsChanged = h + 1 // Have to add 1, since NextValidators is what's stored + } + if paramsChanged == 0 || h%10 == 5 { + paramsChanged = h + } + + state := sm.State{ + InitialHeight: 1, + LastBlockHeight: h - 1, + Validators: validatorSet, + NextValidators: validatorSet, + ConsensusParams: types.ConsensusParams{ + Block: types.BlockParams{MaxBytes: 10e6}, + }, + LastHeightValidatorsChanged: valsChanged, + LastHeightConsensusParamsChanged: paramsChanged, + } + + if state.LastBlockHeight >= 1 { + state.LastValidators = state.Validators + } + + err := stateStore.Save(state) + require.NoError(t, err) + + err = stateStore.SaveFinalizeBlockResponse(h, &abci.ResponseFinalizeBlock{ + TxResults: []*abci.ExecTxResult{ + {Data: []byte{1}}, + {Data: []byte{2}}, + {Data: []byte{3}}, + }, + AppHash: make([]byte, 1), + }) + require.NoError(t, err) + } + + // Test assertions + err := stateStore.PruneStates(tc.pruneFrom, tc.pruneTo, tc.evidenceThresholdHeight) + if tc.expectErr { + require.Error(t, err) + return + } + require.NoError(t, err) + + expectVals := sliceToMap(tc.expectVals) + expectParams := sliceToMap(tc.expectParams) + expectABCI := sliceToMap(tc.expectABCI) + + for h := int64(1); h <= tc.makeHeights; h++ { + vals, err := stateStore.LoadValidators(h) + if expectVals[h] { + require.NoError(t, err, "validators height %v", h) + require.NotNil(t, vals) + } else { + require.Error(t, err, "validators height %v", h) + require.Equal(t, sm.ErrNoValSetForHeight{Height: h}, err) + } + + params, err := stateStore.LoadConsensusParams(h) + if expectParams[h] { + require.NoError(t, err, "params height %v", h) + require.NotEmpty(t, params) + } else { + require.Error(t, err, "params height %v", h) + require.Empty(t, params) + } + + abci, err := stateStore.LoadFinalizeBlockResponse(h) + if expectABCI[h] { + require.NoError(t, err, "abci height %v", h) + require.NotNil(t, abci) + } else { + require.Error(t, err, "abci height %v", h) + require.Equal(t, sm.ErrNoABCIResponsesForHeight{Height: h}, err) + } + } + }) + } +} + +func TestTxResultsHash(t *testing.T) { + txResults := []*abci.ExecTxResult{ + {Code: 32, Data: []byte("Hello"), Log: "Huh?"}, + } + + root := sm.TxResultsHash(txResults) + + // root should be Merkle tree root of ExecTxResult responses + results := types.NewResults(txResults) + assert.Equal(t, root, results.Hash()) + + // test we can prove first ExecTxResult + proof := results.ProveResult(0) + bz, err := results[0].Marshal() + require.NoError(t, err) + assert.NoError(t, proof.Verify(root, bz)) +} + +func sliceToMap(s []int64) map[int64]bool { + m := make(map[int64]bool, len(s)) + for _, i := range s { + m[i] = true + } + return m +} + +func TestLastFinalizeBlockResponses(t *testing.T) { + // create an empty state store. + t.Run("Not persisting responses", func(t *testing.T) { + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + responses, err := stateStore.LoadFinalizeBlockResponse(1) + require.Error(t, err) + require.Nil(t, responses) + // stub the abciresponses. + response1 := &abci.ResponseFinalizeBlock{ + TxResults: []*abci.ExecTxResult{ + {Code: 32, Data: []byte("Hello"), Log: "Huh?"}, + }, + AppHash: make([]byte, 1), + } + // create new db and state store and set discard abciresponses to false. + stateDB = dbm.NewMemDB() + stateStore = sm.NewStore(stateDB, sm.StoreOptions{DiscardABCIResponses: false}) + height := int64(10) + // save the last abci response. + err = stateStore.SaveFinalizeBlockResponse(height, response1) + require.NoError(t, err) + // search for the last finalize block response and check if it has saved. + lastResponse, err := stateStore.LoadLastFinalizeBlockResponse(height) + require.NoError(t, err) + // check to see if the saved response height is the same as the loaded height. + assert.Equal(t, lastResponse, response1) + // use an incorret height to make sure the state store errors. + _, err = stateStore.LoadLastFinalizeBlockResponse(height + 1) + assert.Error(t, err) + // check if the abci response didnt save in the abciresponses. + responses, err = stateStore.LoadFinalizeBlockResponse(height) + require.NoError(t, err, responses) + require.Equal(t, response1, responses) + }) + + t.Run("persisting responses", func(t *testing.T) { + stateDB := dbm.NewMemDB() + height := int64(10) + // stub the second abciresponse. + response2 := &abci.ResponseFinalizeBlock{ + TxResults: []*abci.ExecTxResult{ + {Code: 44, Data: []byte("Hello again"), Log: "????"}, + }, + } + // create a new statestore with the responses on. + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: true, + }) + // save an additional response. + err := stateStore.SaveFinalizeBlockResponse(height+1, response2) + require.NoError(t, err) + // check to see if the response saved by calling the last response. + lastResponse2, err := stateStore.LoadLastFinalizeBlockResponse(height + 1) + require.NoError(t, err) + // check to see if the saved response height is the same as the loaded height. + assert.Equal(t, response2, lastResponse2) + // should error as we are no longer saving the response. + _, err = stateStore.LoadFinalizeBlockResponse(height + 1) + assert.Equal(t, sm.ErrFinalizeBlockResponsesNotPersisted, err) + }) +} + +func TestFinalizeBlockRecoveryUsingLegacyABCIResponses(t *testing.T) { + var ( + height int64 = 10 + lastABCIResponseKey = []byte("lastABCIResponseKey") + memDB = dbm.NewMemDB() + cp = types.DefaultConsensusParams().ToProto() + legacyResp = cmtstate.ABCIResponsesInfo{ + LegacyAbciResponses: &cmtstate.LegacyABCIResponses{ + BeginBlock: &cmtstate.ResponseBeginBlock{ + Events: []abci.Event{{ + Type: "begin_block", + Attributes: []abci.EventAttribute{{ + Key: "key", + Value: "value", + }}, + }}, + }, + DeliverTxs: []*abci.ExecTxResult{{ + Events: []abci.Event{{ + Type: "tx", + Attributes: []abci.EventAttribute{{ + Key: "key", + Value: "value", + }}, + }}, + }}, + EndBlock: &cmtstate.ResponseEndBlock{ + ConsensusParamUpdates: &cp, + }, + }, + Height: height, + } + ) + bz, err := legacyResp.Marshal() + require.NoError(t, err) + // should keep this in parity with state/store.go + require.NoError(t, memDB.Set(lastABCIResponseKey, bz)) + stateStore := sm.NewStore(memDB, sm.StoreOptions{DiscardABCIResponses: false}) + resp, err := stateStore.LoadLastFinalizeBlockResponse(height) + require.NoError(t, err) + require.Equal(t, resp.ConsensusParamUpdates, &cp) + require.Equal(t, len(resp.Events), len(legacyResp.LegacyAbciResponses.BeginBlock.Events)) + require.Equal(t, resp.TxResults[0], legacyResp.LegacyAbciResponses.DeliverTxs[0]) +} + +func TestIntConversion(t *testing.T) { + x := int64(10) + b := sm.Int64ToBytes(x) + require.Equal(t, x, sm.Int64FromBytes(b)) +} diff --git a/state/tx_filter.go b/state/tx_filter.go new file mode 100644 index 0000000..9527cb8 --- /dev/null +++ b/state/tx_filter.go @@ -0,0 +1,26 @@ +package state + +import ( + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/types" +) + +// TxPreCheck returns a function to filter transactions before processing. +// The function limits the size of a transaction to the block's maximum data size. +func TxPreCheck(state State) mempl.PreCheckFunc { + maxBytes := state.ConsensusParams.Block.MaxBytes + if maxBytes == -1 { + maxBytes = int64(types.MaxBlockSizeBytes) + } + maxDataBytes := types.MaxDataBytesNoEvidence( + maxBytes, + state.Validators.Size(), + ) + return mempl.PreCheckMaxBytes(maxDataBytes) +} + +// TxPostCheck returns a function to filter transactions after processing. +// The function limits the gas wanted by a transaction to the block's maximum total gas. +func TxPostCheck(state State) mempl.PostCheckFunc { + return mempl.PostCheckMaxGas(state.ConsensusParams.Block.MaxGas) +} diff --git a/state/tx_filter_test.go b/state/tx_filter_test.go new file mode 100644 index 0000000..367fe52 --- /dev/null +++ b/state/tx_filter_test.go @@ -0,0 +1,49 @@ +package state_test + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + cmtrand "github.com/cometbft/cometbft/libs/rand" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +func TestTxFilter(t *testing.T) { + genDoc := randomGenesisDoc() + genDoc.ConsensusParams.Block.MaxBytes = 3000 + genDoc.ConsensusParams.Evidence.MaxBytes = 1500 + + // Max size of Txs is much smaller than size of block, + // since we need to account for commits and evidence. + testCases := []struct { + tx types.Tx + isErr bool + }{ + {types.Tx(cmtrand.Bytes(2155)), false}, + {types.Tx(cmtrand.Bytes(2156)), true}, + {types.Tx(cmtrand.Bytes(3000)), true}, + } + + for i, tc := range testCases { + stateDB, err := dbm.NewDB("state", "memdb", os.TempDir()) + require.NoError(t, err) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc) + require.NoError(t, err) + + f := sm.TxPreCheck(state) + if tc.isErr { + assert.NotNil(t, f(tc.tx), "#%v", i) + } else { + assert.Nil(t, f(tc.tx), "#%v", i) + } + } +} diff --git a/state/txindex/indexer.go b/state/txindex/indexer.go new file mode 100644 index 0000000..fcf37d4 --- /dev/null +++ b/state/txindex/indexer.go @@ -0,0 +1,61 @@ +package txindex + +import ( + "context" + "errors" + + "github.com/cometbft/cometbft/libs/log" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" +) + +// XXX/TODO: These types should be moved to the indexer package. + +//go:generate ../../scripts/mockery_generate.sh TxIndexer + +// TxIndexer interface defines methods to index and search transactions. +type TxIndexer interface { + // AddBatch analyzes, indexes and stores a batch of transactions. + AddBatch(b *Batch) error + + // Index analyzes, indexes and stores a single transaction. + Index(result *abci.TxResult) error + + // Get returns the transaction specified by hash or nil if the transaction is not indexed + // or stored. + Get(hash []byte) (*abci.TxResult, error) + + // Search allows you to query for transactions. + Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) + + //Set Logger + SetLogger(l log.Logger) +} + +// Batch groups together multiple Index operations to be performed at the same time. +// NOTE: Batch is NOT thread-safe and must not be modified after starting its execution. +type Batch struct { + Ops []*abci.TxResult +} + +// NewBatch creates a new Batch. +func NewBatch(n int64) *Batch { + return &Batch{ + Ops: make([]*abci.TxResult, n), + } +} + +// Add or update an entry for the given result.Index. +func (b *Batch) Add(result *abci.TxResult) error { + b.Ops[result.Index] = result + return nil +} + +// Size returns the total number of operations inside the batch. +func (b *Batch) Size() int { + return len(b.Ops) +} + +// ErrorEmptyHash indicates empty hash +var ErrorEmptyHash = errors.New("transaction hash cannot be empty") diff --git a/state/txindex/indexer_service.go b/state/txindex/indexer_service.go new file mode 100644 index 0000000..d927913 --- /dev/null +++ b/state/txindex/indexer_service.go @@ -0,0 +1,127 @@ +package txindex + +import ( + "context" + + "github.com/cometbft/cometbft/libs/service" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/types" +) + +// XXX/TODO: These types should be moved to the indexer package. + +const ( + subscriber = "IndexerService" +) + +// IndexerService connects event bus, transaction and block indexers together in +// order to index transactions and blocks coming from the event bus. +type IndexerService struct { + service.BaseService + + txIdxr TxIndexer + blockIdxr indexer.BlockIndexer + eventBus *types.EventBus + terminateOnError bool +} + +// NewIndexerService returns a new service instance. +func NewIndexerService( + txIdxr TxIndexer, + blockIdxr indexer.BlockIndexer, + eventBus *types.EventBus, + terminateOnError bool, +) *IndexerService { + + is := &IndexerService{txIdxr: txIdxr, blockIdxr: blockIdxr, eventBus: eventBus, terminateOnError: terminateOnError} + is.BaseService = *service.NewBaseService(nil, "IndexerService", is) + return is +} + +// OnStart implements service.Service by subscribing for all transactions +// and indexing them by events. +func (is *IndexerService) OnStart() error { + // Use SubscribeUnbuffered here to ensure both subscriptions does not get + // canceled due to not pulling messages fast enough. Cause this might + // sometimes happen when there are no other subscribers. + blockSub, err := is.eventBus.SubscribeUnbuffered( + context.Background(), + subscriber, + types.EventQueryNewBlockEvents) + if err != nil { + return err + } + + txsSub, err := is.eventBus.SubscribeUnbuffered(context.Background(), subscriber, types.EventQueryTx) + if err != nil { + return err + } + + go func() { + for { + select { + case <-blockSub.Canceled(): + return + case msg := <-blockSub.Out(): + eventNewBlockEvents := msg.Data().(types.EventDataNewBlockEvents) + height := eventNewBlockEvents.Height + numTxs := eventNewBlockEvents.NumTxs + + batch := NewBatch(numTxs) + + for i := int64(0); i < numTxs; i++ { + msg2 := <-txsSub.Out() + txResult := msg2.Data().(types.EventDataTx).TxResult + + if err = batch.Add(&txResult); err != nil { + is.Logger.Error( + "failed to add tx to batch", + "height", height, + "index", txResult.Index, + "err", err, + ) + + if is.terminateOnError { + if err := is.Stop(); err != nil { + is.Logger.Error("failed to stop", "err", err) + } + return + } + } + } + + if err := is.blockIdxr.Index(eventNewBlockEvents); err != nil { + is.Logger.Error("failed to index block", "height", height, "err", err) + if is.terminateOnError { + if err := is.Stop(); err != nil { + is.Logger.Error("failed to stop", "err", err) + } + return + } + } else { + is.Logger.Info("indexed block events", "height", height) + } + + if err = is.txIdxr.AddBatch(batch); err != nil { + is.Logger.Error("failed to index block txs", "height", height, "err", err) + if is.terminateOnError { + if err := is.Stop(); err != nil { + is.Logger.Error("failed to stop", "err", err) + } + return + } + } else { + is.Logger.Debug("indexed transactions", "height", height, "num_txs", numTxs) + } + } + } + }() + return nil +} + +// OnStop implements service.Service by unsubscribing from all transactions. +func (is *IndexerService) OnStop() { + if is.eventBus.IsRunning() { + _ = is.eventBus.UnsubscribeAll(context.Background(), subscriber) + } +} diff --git a/state/txindex/indexer_service_test.go b/state/txindex/indexer_service_test.go new file mode 100644 index 0000000..6727c96 --- /dev/null +++ b/state/txindex/indexer_service_test.go @@ -0,0 +1,94 @@ +package txindex_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + db "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + blockidxkv "github.com/cometbft/cometbft/state/indexer/block/kv" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/state/txindex/kv" + "github.com/cometbft/cometbft/types" +) + +func TestIndexerServiceIndexesBlocks(t *testing.T) { + // event bus + eventBus := types.NewEventBus() + eventBus.SetLogger(log.TestingLogger()) + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + // tx indexer + store := db.NewMemDB() + txIndexer := kv.NewTxIndex(store) + blockIndexer := blockidxkv.New(db.NewPrefixDB(store, []byte("block_events"))) + + service := txindex.NewIndexerService(txIndexer, blockIndexer, eventBus, false) + service.SetLogger(log.TestingLogger()) + err = service.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := service.Stop(); err != nil { + t.Error(err) + } + }) + + // publish block with events + err = eventBus.PublishEventNewBlockEvents(types.EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{ + { + Type: "begin_event", + Attributes: []abci.EventAttribute{ + { + Key: "proposer", + Value: "FCAA001", + Index: true, + }, + }, + }, + }, + NumTxs: int64(2), + }) + require.NoError(t, err) + txResult1 := &abci.TxResult{ + Height: 1, + Index: uint32(0), + Tx: types.Tx("foo"), + Result: abci.ExecTxResult{Code: 0}, + } + err = eventBus.PublishEventTx(types.EventDataTx{TxResult: *txResult1}) + require.NoError(t, err) + txResult2 := &abci.TxResult{ + Height: 1, + Index: uint32(1), + Tx: types.Tx("bar"), + Result: abci.ExecTxResult{Code: 0}, + } + err = eventBus.PublishEventTx(types.EventDataTx{TxResult: *txResult2}) + require.NoError(t, err) + + time.Sleep(100 * time.Millisecond) + + res, err := txIndexer.Get(types.Tx("foo").Hash()) + require.NoError(t, err) + require.Equal(t, txResult1, res) + + ok, err := blockIndexer.Has(1) + require.NoError(t, err) + require.True(t, ok) + + res, err = txIndexer.Get(types.Tx("bar").Hash()) + require.NoError(t, err) + require.Equal(t, txResult2, res) +} diff --git a/state/txindex/kv/kv.go b/state/txindex/kv/kv.go new file mode 100644 index 0000000..fb6b6e3 --- /dev/null +++ b/state/txindex/kv/kv.go @@ -0,0 +1,768 @@ +package kv + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "math/big" + "strconv" + "strings" + + "github.com/cometbft/cometbft/libs/log" + + "github.com/cosmos/gogoproto/proto" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + idxutil "github.com/cometbft/cometbft/internal/indexer" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/libs/pubsub/query/syntax" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/types" +) + +const ( + tagKeySeparator = "/" + tagKeySeparatorRune = '/' + eventSeqSeparator = "$es$" +) + +var _ txindex.TxIndexer = (*TxIndex)(nil) + +// TxIndex is the simplest possible indexer, backed by key-value storage (levelDB). +type TxIndex struct { + store dbm.DB + // Number the events in the event list + eventSeq int64 + + log log.Logger +} + +// NewTxIndex creates new KV indexer. +func NewTxIndex(store dbm.DB) *TxIndex { + return &TxIndex{ + store: store, + } +} + +func (txi *TxIndex) SetLogger(l log.Logger) { + txi.log = l +} + +// Get gets transaction from the TxIndex storage and returns it or nil if the +// transaction is not found. +func (txi *TxIndex) Get(hash []byte) (*abci.TxResult, error) { + if len(hash) == 0 { + return nil, txindex.ErrorEmptyHash + } + + rawBytes, err := txi.store.Get(hash) + if err != nil { + panic(err) + } + if rawBytes == nil { + return nil, nil + } + + txResult := new(abci.TxResult) + err = proto.Unmarshal(rawBytes, txResult) + if err != nil { + return nil, fmt.Errorf("error reading TxResult: %v", err) + } + + return txResult, nil +} + +// AddBatch indexes a batch of transactions using the given list of events. Each +// key that indexed from the tx's events is a composite of the event type and +// the respective attribute's key delimited by a "." (eg. "account.number"). +// Any event with an empty type is not indexed. +func (txi *TxIndex) AddBatch(b *txindex.Batch) error { + storeBatch := txi.store.NewBatch() + defer storeBatch.Close() + + for _, result := range b.Ops { + hash := types.Tx(result.Tx).Hash() + + // index tx by events + err := txi.indexEvents(result, hash, storeBatch) + if err != nil { + return err + } + + // index by height (always) + err = storeBatch.Set(keyForHeight(result), hash) + if err != nil { + return err + } + + rawBytes, err := proto.Marshal(result) + if err != nil { + return err + } + // index by hash (always) + err = storeBatch.Set(hash, rawBytes) + if err != nil { + return err + } + } + + return storeBatch.WriteSync() +} + +// Index indexes a single transaction using the given list of events. Each key +// that indexed from the tx's events is a composite of the event type and the +// respective attribute's key delimited by a "." (eg. "account.number"). +// Any event with an empty type is not indexed. +// +// If a transaction is indexed with the same hash as a previous transaction, it will +// be overwritten unless the tx result was NOT OK and the prior result was OK i.e. +// more transactions that successfully executed overwrite transactions that failed +// or successful yet older transactions. +func (txi *TxIndex) Index(result *abci.TxResult) error { + b := txi.store.NewBatch() + defer b.Close() + + hash := types.Tx(result.Tx).Hash() + + if !result.Result.IsOK() { + oldResult, err := txi.Get(hash) + if err != nil { + return err + } + + // if the new transaction failed and it's already indexed in an older block and was successful + // we skip it as we want users to get the older successful transaction when they query. + if oldResult != nil && oldResult.Result.Code == abci.CodeTypeOK { + return nil + } + } + + // index tx by events + err := txi.indexEvents(result, hash, b) + if err != nil { + return err + } + + // index by height (always) + err = b.Set(keyForHeight(result), hash) + if err != nil { + return err + } + + rawBytes, err := proto.Marshal(result) + if err != nil { + return err + } + // index by hash (always) + err = b.Set(hash, rawBytes) + if err != nil { + return err + } + + return b.WriteSync() +} + +func (txi *TxIndex) indexEvents(result *abci.TxResult, hash []byte, store dbm.Batch) error { + for _, event := range result.Result.Events { + txi.eventSeq = txi.eventSeq + 1 + // only index events with a non-empty type + if len(event.Type) == 0 { + continue + } + + for _, attr := range event.Attributes { + if len(attr.Key) == 0 { + continue + } + + // index if `index: true` is set + compositeTag := fmt.Sprintf("%s.%s", event.Type, attr.Key) + // ensure event does not conflict with a reserved prefix key + if compositeTag == types.TxHashKey || compositeTag == types.TxHeightKey { + return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeTag) + } + if attr.GetIndex() { + err := store.Set(keyForEvent(compositeTag, attr.Value, result, txi.eventSeq), hash) + if err != nil { + return err + } + } + } + } + + return nil +} + +// Search performs a search using the given query. +// +// It breaks the query into conditions (like "tx.height > 5"). For each +// condition, it queries the DB index. One special use cases here: (1) if +// "tx.hash" is found, it returns tx result for it (2) for range queries it is +// better for the client to provide both lower and upper bounds, so we are not +// performing a full scan. Results from querying indexes are then intersected +// and returned to the caller, in no particular order. +// +// Search will exit early and return any result fetched so far, +// when a message is received on the context chan. +func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) { + select { + case <-ctx.Done(): + return make([]*abci.TxResult, 0), nil + + default: + } + + var hashesInitialized bool + filteredHashes := make(map[string][]byte) + + // get a list of conditions (like "tx.height > 5") + conditions := q.Syntax() + + // if there is a hash condition, return the result immediately + hash, ok, err := lookForHash(conditions) + if err != nil { + return nil, fmt.Errorf("error during searching for a hash in the query: %w", err) + } else if ok { + res, err := txi.Get(hash) + switch { + case err != nil: + return []*abci.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err) + case res == nil: + return []*abci.TxResult{}, nil + default: + return []*abci.TxResult{res}, nil + } + } + + // conditions to skip because they're handled before "everything else" + skipIndexes := make([]int, 0) + var heightInfo HeightInfo + + // If we are not matching events and tx.height = 3 occurs more than once, the later value will + // overwrite the first one. + conditions, heightInfo = dedupHeight(conditions) + + if !heightInfo.onlyHeightEq { + skipIndexes = append(skipIndexes, heightInfo.heightEqIdx) + } + + // extract ranges + // if both upper and lower bounds exist, it's better to get them in order not + // no iterate over kvs that are not within range. + ranges, rangeIndexes, heightRange := indexer.LookForRangesWithHeight(conditions) + heightInfo.heightRange = heightRange + if len(ranges) > 0 { + skipIndexes = append(skipIndexes, rangeIndexes...) + + for _, qr := range ranges { + + // If we have a query range over height and want to still look for + // specific event values we do not want to simply return all + // transactios in this height range. We remember the height range info + // and pass it on to match() to take into account when processing events. + if qr.Key == types.TxHeightKey && !heightInfo.onlyHeightRange { + continue + } + if !hashesInitialized { + filteredHashes = txi.matchRange(ctx, qr, startKey(qr.Key), filteredHashes, true, heightInfo) + hashesInitialized = true + + // Ignore any remaining conditions if the first condition resulted + // in no matches (assuming implicit AND operand). + if len(filteredHashes) == 0 { + break + } + } else { + filteredHashes = txi.matchRange(ctx, qr, startKey(qr.Key), filteredHashes, false, heightInfo) + } + } + } + + // if there is a height condition ("tx.height=3"), extract it + + // for all other conditions + for i, c := range conditions { + if intInSlice(i, skipIndexes) { + continue + } + + if !hashesInitialized { + filteredHashes = txi.match(ctx, c, startKeyForCondition(c, heightInfo.height), filteredHashes, true, heightInfo) + hashesInitialized = true + + // Ignore any remaining conditions if the first condition resulted + // in no matches (assuming implicit AND operand). + if len(filteredHashes) == 0 { + break + } + } else { + filteredHashes = txi.match(ctx, c, startKeyForCondition(c, heightInfo.height), filteredHashes, false, heightInfo) + } + } + + results := make([]*abci.TxResult, 0, len(filteredHashes)) + resultMap := make(map[string]struct{}) +RESULTS_LOOP: + for _, h := range filteredHashes { + + res, err := txi.Get(h) + if err != nil { + return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err) + } + hashString := string(h) + if _, ok := resultMap[hashString]; !ok { + resultMap[hashString] = struct{}{} + results = append(results, res) + } + // Potentially exit early. + select { + case <-ctx.Done(): + break RESULTS_LOOP + default: + } + } + + return results, nil +} + +func lookForHash(conditions []syntax.Condition) (hash []byte, ok bool, err error) { + for _, c := range conditions { + if c.Tag == types.TxHashKey { + decoded, err := hex.DecodeString(c.Arg.Value()) + return decoded, true, err + } + } + return +} + +func (*TxIndex) setTmpHashes(tmpHeights map[string][]byte, key, value []byte) { + eventSeq := extractEventSeqFromKey(key) + + // Copy the value because the iterator will be reused. + valueCopy := make([]byte, len(value)) + copy(valueCopy, value) + + tmpHeights[string(valueCopy)+eventSeq] = valueCopy +} + +// match returns all matching txs by hash that meet a given condition and start +// key. An already filtered result (filteredHashes) is provided such that any +// non-intersecting matches are removed. +// +// NOTE: filteredHashes may be empty if no previous condition has matched. +func (txi *TxIndex) match( + ctx context.Context, + c syntax.Condition, + startKeyBz []byte, + filteredHashes map[string][]byte, + firstRun bool, + heightInfo HeightInfo, +) map[string][]byte { + // A previous match was attempted but resulted in no matches, so we return + // no matches (assuming AND operand). + if !firstRun && len(filteredHashes) == 0 { + return filteredHashes + } + + tmpHashes := make(map[string][]byte) + + switch c.Op { + case syntax.TEq: + it, err := dbm.IteratePrefix(txi.store, startKeyBz) + if err != nil { + panic(err) + } + defer it.Close() + + EQ_LOOP: + for ; it.Valid(); it.Next() { + + // If we have a height range in a query, we need only transactions + // for this height + key := it.Key() + keyHeight, err := extractHeightFromKey(key) + if err != nil { + txi.log.Error("failure to parse height from key:", err) + continue + } + withinBounds, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + txi.log.Error("failure checking for height bounds:", err) + continue + } + if !withinBounds { + continue + } + txi.setTmpHashes(tmpHashes, key, it.Value()) + // Potentially exit early. + select { + case <-ctx.Done(): + break EQ_LOOP + default: + } + } + if err := it.Error(); err != nil { + panic(err) + } + + case syntax.TExists: + // XXX: can't use startKeyBz here because c.Operand is nil + // (e.g. "account.owner//" won't match w/ a single row) + it, err := dbm.IteratePrefix(txi.store, startKey(c.Tag)) + if err != nil { + panic(err) + } + defer it.Close() + + EXISTS_LOOP: + for ; it.Valid(); it.Next() { + key := it.Key() + keyHeight, err := extractHeightFromKey(key) + if err != nil { + txi.log.Error("failure to parse height from key:", err) + continue + } + withinBounds, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + txi.log.Error("failure checking for height bounds:", err) + continue + } + if !withinBounds { + continue + } + txi.setTmpHashes(tmpHashes, key, it.Value()) + + // Potentially exit early. + select { + case <-ctx.Done(): + break EXISTS_LOOP + default: + } + } + if err := it.Error(); err != nil { + panic(err) + } + + case syntax.TContains: + // XXX: startKey does not apply here. + // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an" + // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/" + it, err := dbm.IteratePrefix(txi.store, startKey(c.Tag)) + if err != nil { + panic(err) + } + defer it.Close() + + CONTAINS_LOOP: + for ; it.Valid(); it.Next() { + if !isTagKey(it.Key()) { + continue + } + + if strings.Contains(extractValueFromKey(it.Key()), c.Arg.Value()) { + key := it.Key() + keyHeight, err := extractHeightFromKey(key) + if err != nil { + txi.log.Error("failure to parse height from key:", err) + continue + } + withinBounds, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + txi.log.Error("failure checking for height bounds:", err) + continue + } + if !withinBounds { + continue + } + txi.setTmpHashes(tmpHashes, key, it.Value()) + } + + // Potentially exit early. + select { + case <-ctx.Done(): + break CONTAINS_LOOP + default: + } + } + if err := it.Error(); err != nil { + panic(err) + } + default: + panic("other operators should be handled already") + } + + if len(tmpHashes) == 0 || firstRun { + // Either: + // + // 1. Regardless if a previous match was attempted, which may have had + // results, but no match was found for the current condition, then we + // return no matches (assuming AND operand). + // + // 2. A previous match was not attempted, so we return all results. + return tmpHashes + } + + // Remove/reduce matches in filteredHashes that were not found in this + // match (tmpHashes). +REMOVE_LOOP: + for k, v := range filteredHashes { + tmpHash := tmpHashes[k] + if tmpHash == nil || !bytes.Equal(tmpHash, v) { + delete(filteredHashes, k) + + // Potentially exit early. + select { + case <-ctx.Done(): + break REMOVE_LOOP + default: + } + } + } + + return filteredHashes +} + +// matchRange returns all matching txs by hash that meet a given queryRange and +// start key. An already filtered result (filteredHashes) is provided such that +// any non-intersecting matches are removed. +// +// NOTE: filteredHashes may be empty if no previous condition has matched. +func (txi *TxIndex) matchRange( + ctx context.Context, + qr indexer.QueryRange, + startKey []byte, + filteredHashes map[string][]byte, + firstRun bool, + heightInfo HeightInfo, +) map[string][]byte { + // A previous match was attempted but resulted in no matches, so we return + // no matches (assuming AND operand). + if !firstRun && len(filteredHashes) == 0 { + return filteredHashes + } + + tmpHashes := make(map[string][]byte) + + it, err := dbm.IteratePrefix(txi.store, startKey) + if err != nil { + panic(err) + } + defer it.Close() + bigIntValue := new(big.Int) + +LOOP: + for ; it.Valid(); it.Next() { + // TODO: We need to make a function for getting it.Key() as a byte slice with no copies. + // It currently copies the source data (which can change on a subsequent .Next() call) but that + // is not an issue for us. + key := it.Key() + if !isTagKey(key) { + continue + } + + if _, ok := qr.AnyBound().(*big.Float); ok { + value := extractValueFromKey(key) + v, ok := bigIntValue.SetString(value, 10) + var vF *big.Float + if !ok { + vF, _, err = big.ParseFloat(value, 10, 125, big.ToNearestEven) + if err != nil { + continue LOOP + } + + } + if qr.Key != types.TxHeightKey { + keyHeight, err := extractHeightFromKey(key) + if err != nil { + txi.log.Error("failure to parse height from key:", err) + continue + } + withinBounds, err := checkHeightConditions(heightInfo, keyHeight) + if err != nil { + txi.log.Error("failure checking for height bounds:", err) + continue + } + if !withinBounds { + continue + } + } + var withinBounds bool + var err error + if !ok { + withinBounds, err = idxutil.CheckBounds(qr, vF) + } else { + withinBounds, err = idxutil.CheckBounds(qr, v) + } + if err != nil { + txi.log.Error("failed to parse bounds:", err) + } else if withinBounds { + txi.setTmpHashes(tmpHashes, key, it.Value()) + } + + // XXX: passing time in a ABCI Events is not yet implemented + // case time.Time: + // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64) + // if v == r.upperBound { + // break + // } + } + + // Potentially exit early. + select { + case <-ctx.Done(): + break LOOP + default: + } + } + if err := it.Error(); err != nil { + panic(err) + } + + if len(tmpHashes) == 0 || firstRun { + // Either: + // + // 1. Regardless if a previous match was attempted, which may have had + // results, but no match was found for the current condition, then we + // return no matches (assuming AND operand). + // + // 2. A previous match was not attempted, so we return all results. + return tmpHashes + } + + // Remove/reduce matches in filteredHashes that were not found in this + // match (tmpHashes). +REMOVE_LOOP: + for k, v := range filteredHashes { + tmpHash := tmpHashes[k] + if tmpHash == nil || !bytes.Equal(tmpHashes[k], v) { + delete(filteredHashes, k) + + // Potentially exit early. + select { + case <-ctx.Done(): + break REMOVE_LOOP + default: + } + } + } + + return filteredHashes +} + +// Keys + +func isTagKey(key []byte) bool { + // Normally, if the event was indexed with an event sequence, the number of + // tags should 4. Alternatively it should be 3 if the event was not indexed + // with the corresponding event sequence. However, some attribute values in + // production can contain the tag separator. Therefore, the condition is >= 3. + numTags := 0 + for i := 0; i < len(key); i++ { + if key[i] == tagKeySeparatorRune { + numTags++ + if numTags >= 3 { + return true + } + } + } + return false +} + +func extractHeightFromKey(key []byte) (int64, error) { + // the height is the second last element in the key. + // Find the position of the last occurrence of tagKeySeparator + endPos := bytes.LastIndexByte(key, tagKeySeparatorRune) + if endPos == -1 { + return 0, errors.New("separator not found") + } + + // Find the position of the second last occurrence of tagKeySeparator + startPos := bytes.LastIndexByte(key[:endPos-1], tagKeySeparatorRune) + if startPos == -1 { + return 0, errors.New("second last separator not found") + } + + // Extract the height part of the key + height, err := strconv.ParseInt(string(key[startPos+1:endPos]), 10, 64) + if err != nil { + return 0, err + } + return height, nil +} + +func extractValueFromKey(key []byte) string { + // Find the positions of tagKeySeparator in the byte slice + var indices []int + for i, b := range key { + if b == tagKeySeparatorRune { + indices = append(indices, i) + } + } + + // If there are less than 2 occurrences of tagKeySeparator, return an empty string + if len(indices) < 2 { + return "" + } + + // Extract the value between the first and second last occurrence of tagKeySeparator + value := key[indices[0]+1 : indices[len(indices)-2]] + + // Trim any leading or trailing whitespace + value = bytes.TrimSpace(value) + + // TODO: Do an unsafe cast to avoid an extra allocation here + return string(value) +} + +func extractEventSeqFromKey(key []byte) string { + parts := strings.Split(string(key), tagKeySeparator) + + lastEl := parts[len(parts)-1] + + if strings.Contains(lastEl, eventSeqSeparator) { + return strings.SplitN(lastEl, eventSeqSeparator, 2)[1] + } + return "0" +} + +func keyForEvent(key string, value string, result *abci.TxResult, eventSeq int64) []byte { + return []byte(fmt.Sprintf("%s/%s/%d/%d%s", + key, + value, + result.Height, + result.Index, + eventSeqSeparator+strconv.FormatInt(eventSeq, 10), + )) +} + +func keyForHeight(result *abci.TxResult) []byte { + return []byte(fmt.Sprintf("%s/%d/%d/%d%s", + types.TxHeightKey, + result.Height, + result.Height, + result.Index, + // Added to facilitate having the eventSeq in event keys + // Otherwise queries break expecting 5 entries + eventSeqSeparator+"0", + )) +} + +func startKeyForCondition(c syntax.Condition, height int64) []byte { + if height > 0 { + return startKey(c.Tag, c.Arg.Value(), height) + } + return startKey(c.Tag, c.Arg.Value()) +} + +func startKey(fields ...interface{}) []byte { + var b bytes.Buffer + for _, f := range fields { + b.Write([]byte(fmt.Sprintf("%v", f) + tagKeySeparator)) + } + return b.Bytes() +} diff --git a/state/txindex/kv/kv_bench_test.go b/state/txindex/kv/kv_bench_test.go new file mode 100644 index 0000000..92baa11 --- /dev/null +++ b/state/txindex/kv/kv_bench_test.go @@ -0,0 +1,74 @@ +package kv + +import ( + "context" + "crypto/rand" + "fmt" + "os" + "testing" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/types" +) + +func BenchmarkTxSearch(b *testing.B) { + dbDir, err := os.MkdirTemp("", "benchmark_tx_search_test") + if err != nil { + b.Errorf("failed to create temporary directory: %s", err) + } + + db, err := dbm.NewGoLevelDB("benchmark_tx_search_test", dbDir) + if err != nil { + b.Errorf("failed to create database: %s", err) + } + + indexer := NewTxIndex(db) + + for i := 0; i < 35000; i++ { + events := []abci.Event{ + { + Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: "address", Value: fmt.Sprintf("address_%d", i%100), Index: true}, + {Key: "amount", Value: "50", Index: true}, + }, + }, + } + + txBz := make([]byte, 8) + if _, err := rand.Read(txBz); err != nil { + b.Errorf("failed produce random bytes: %s", err) + } + + txResult := &abci.TxResult{ + Height: int64(i), + Index: 0, + Tx: types.Tx(string(txBz)), + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, + Log: "", + Events: events, + }, + } + + if err := indexer.Index(txResult); err != nil { + b.Errorf("failed to index tx: %s", err) + } + } + + txQuery := query.MustCompile(`transfer.address = 'address_43' AND transfer.amount = 50`) + + b.ResetTimer() + + ctx := context.Background() + + for i := 0; i < b.N; i++ { + if _, err := indexer.Search(ctx, txQuery); err != nil { + b.Errorf("failed to query for txs: %s", err) + } + } +} diff --git a/state/txindex/kv/kv_test.go b/state/txindex/kv/kv_test.go new file mode 100644 index 0000000..3595d9a --- /dev/null +++ b/state/txindex/kv/kv_test.go @@ -0,0 +1,802 @@ +package kv + +import ( + "context" + "fmt" + "os" + "testing" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + db "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + cmtrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/state/txindex" + "github.com/cometbft/cometbft/types" +) + +func TestTxIndex(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + tx := types.Tx("HELLO WORLD") + txResult := &abci.TxResult{ + Height: 1, + Index: 0, + Tx: tx, + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, Log: "", Events: nil, + }, + } + hash := tx.Hash() + + batch := txindex.NewBatch(1) + if err := batch.Add(txResult); err != nil { + t.Error(err) + } + err := indexer.AddBatch(batch) + require.NoError(t, err) + + loadedTxResult, err := indexer.Get(hash) + require.NoError(t, err) + assert.True(t, proto.Equal(txResult, loadedTxResult)) + + tx2 := types.Tx("BYE BYE WORLD") + txResult2 := &abci.TxResult{ + Height: 1, + Index: 0, + Tx: tx2, + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, Log: "", Events: nil, + }, + } + hash2 := tx2.Hash() + + err = indexer.Index(txResult2) + require.NoError(t, err) + + loadedTxResult2, err := indexer.Get(hash2) + require.NoError(t, err) + assert.True(t, proto.Equal(txResult2, loadedTxResult2)) +} + +func TestTxSearch(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "owner", Value: "/Ivan/", Index: true}}}, + {Type: "", Attributes: []abci.EventAttribute{{Key: "not_allowed", Value: "Vlad", Index: true}}}, + }) + hash := types.Tx(txResult.Tx).Hash() + + err := indexer.Index(txResult) + require.NoError(t, err) + + testCases := []struct { + q string + resultsLength int + }{ + // search by hash + {fmt.Sprintf("tx.hash = '%X'", hash), 1}, + // search by hash (lower) + {fmt.Sprintf("tx.hash = '%x'", hash), 1}, + // search by exact match (one key) + {"account.number = 1", 1}, + // search by exact match (two keys) + {"account.number = 1 AND account.owner = 'Ivan'", 0}, + {"account.owner = 'Ivan' AND account.number = 1", 0}, + {"account.owner = '/Ivan/'", 1}, + // search by exact match (two keys) + {"account.number = 1 AND account.owner = 'Vlad'", 0}, + {"account.owner = 'Vlad' AND account.number = 1", 0}, + {"account.number >= 1 AND account.owner = 'Vlad'", 0}, + {"account.owner = 'Vlad' AND account.number >= 1", 0}, + {"account.number <= 0", 0}, + {"account.number <= 0 AND account.owner = 'Ivan'", 0}, + {"account.number < 10000 AND account.owner = 'Ivan'", 0}, + // search using a prefix of the stored value + {"account.owner = 'Iv'", 0}, + // search by range + {"account.number >= 1 AND account.number <= 5", 1}, + // search by range and another key + {"account.number >= 1 AND account.owner = 'Ivan' AND account.number <= 5", 0}, + // search by range (lower bound) + {"account.number >= 1", 1}, + // search by range (upper bound) + {"account.number <= 5", 1}, + {"account.number <= 1", 1}, + // search using not allowed key + {"not_allowed = 'boom'", 0}, + {"not_allowed = 'Vlad'", 0}, + // search for not existing tx result + {"account.number >= 2 AND account.number <= 5 AND tx.height > 0", 0}, + // search using not existing key + {"account.date >= TIME 2013-05-03T14:45:00Z", 0}, + // search using CONTAINS + {"account.owner CONTAINS 'an'", 1}, + // search for non existing value using CONTAINS + {"account.owner CONTAINS 'Vlad'", 0}, + {"account.owner CONTAINS 'Ivann'", 0}, + {"account.owner CONTAINS 'IIvan'", 0}, + {"account.owner CONTAINS 'Iva n'", 0}, + {"account.owner CONTAINS ' Ivan'", 0}, + {"account.owner CONTAINS 'Ivan '", 0}, + // search using the wrong key (of numeric type) using CONTAINS + {"account.number CONTAINS 'Iv'", 0}, + // search using EXISTS + {"account.number EXISTS", 1}, + // search using EXISTS for non existing key + {"account.date EXISTS", 0}, + {"not_allowed EXISTS", 0}, + } + + ctx := context.Background() + + for _, tc := range testCases { + tc := tc + t.Run(tc.q, func(t *testing.T) { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + assert.NoError(t, err) + + assert.Len(t, results, tc.resultsLength) + if tc.resultsLength > 0 { + for _, txr := range results { + assert.True(t, proto.Equal(txResult, txr)) + } + } + }) + } +} + +func TestTxSearchEventMatch(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}, {Key: "owner", Value: "Ana", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "2", Index: true}, {Key: "owner", Value: "/Ivan/.test", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "3", Index: false}, {Key: "owner", Value: "Mickey", Index: false}}}, + {Type: "", Attributes: []abci.EventAttribute{{Key: "not_allowed", Value: "Vlad", Index: true}}}, + }) + + err := indexer.Index(txResult) + require.NoError(t, err) + + testCases := map[string]struct { + q string + resultsLength int + }{ + "Return all events from a height": { + q: "tx.height = 1", + resultsLength: 1, + }, + "Don't match non-indexed events": { + q: "account.number = 3 AND account.owner = 'Mickey'", + resultsLength: 0, + }, + "Return all events from a height with range": { + q: "tx.height > 0", + resultsLength: 1, + }, + "Return all events from a height with range 2": { + q: "tx.height <= 1", + resultsLength: 1, + }, + "Return all events from a height (deduplicate height)": { + q: "tx.height = 1 AND tx.height = 1", + resultsLength: 1, + }, + "Match attributes with height range and event": { + q: "tx.height < 2 AND tx.height > 0 AND account.number > 0 AND account.number <= 1 AND account.owner CONTAINS 'Ana'", + resultsLength: 1, + }, + "Match attributes with multiple CONTAIN and height range": { + q: "tx.height < 2 AND tx.height > 0 AND account.number = 1 AND account.owner CONTAINS 'Ana' AND account.owner CONTAINS 'An'", + resultsLength: 1, + }, + "Match attributes with height range and event - no match": { + q: "tx.height < 2 AND tx.height > 0 AND account.number = 2 AND account.owner = 'Ana'", + resultsLength: 0, + }, + "Match attributes with event": { + q: "account.number = 2 AND account.owner = 'Ana' AND tx.height = 1", + resultsLength: 0, + }, + "Deduplication test - should return nothing if attribute repeats multiple times": { + q: "tx.height < 2 AND account.number = 3 AND account.number = 2 AND account.number = 5", + resultsLength: 0, + }, + " Match range with special character": { + q: "account.number < 2 AND account.owner = '/Ivan/.test'", + resultsLength: 0, + }, + " Match range with special character 2": { + q: "account.number <= 2 AND account.owner = '/Ivan/.test' AND tx.height > 0", + resultsLength: 1, + }, + " Match range with contains with multiple items": { + q: "account.number <= 2 AND account.owner CONTAINS '/Iv' AND account.owner CONTAINS 'an' AND tx.height = 1", + resultsLength: 1, + }, + " Match range with contains": { + q: "account.number <= 2 AND account.owner CONTAINS 'an' AND tx.height > 0", + resultsLength: 1, + }, + } + + ctx := context.Background() + + for _, tc := range testCases { + tc := tc + t.Run(tc.q, func(t *testing.T) { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + assert.NoError(t, err) + + assert.Len(t, results, tc.resultsLength) + if tc.resultsLength > 0 { + for _, txr := range results { + assert.True(t, proto.Equal(txResult, txr)) + } + } + }) + } +} + +func TestTxSearchEventMatchByHeight(t *testing.T) { + + indexer := NewTxIndex(db.NewMemDB()) + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}, {Key: "owner", Value: "Ana", Index: true}}}, + }) + + err := indexer.Index(txResult) + require.NoError(t, err) + + txResult10 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}, {Key: "owner", Value: "/Ivan/.test", Index: true}}}, + }) + txResult10.Tx = types.Tx("HELLO WORLD 10") + txResult10.Height = 10 + + err = indexer.Index(txResult10) + require.NoError(t, err) + + testCases := map[string]struct { + q string + resultsLength int + }{ + "Return all events from a height 1": { + q: "tx.height = 1", + resultsLength: 1, + }, + "Return all events from a height 10": { + q: "tx.height = 10", + resultsLength: 1, + }, + "Return all events from a height 5": { + q: "tx.height = 5", + resultsLength: 0, + }, + "Return all events from a height in [2; 5]": { + q: "tx.height >= 2 AND tx.height <= 5", + resultsLength: 0, + }, + "Return all events from a height in [1; 5]": { + q: "tx.height >= 1 AND tx.height <= 5", + resultsLength: 1, + }, + "Return all events from a height in [1; 10]": { + q: "tx.height >= 1 AND tx.height <= 10", + resultsLength: 2, + }, + "Return all events from a height in [1; 5] by account.number": { + q: "tx.height >= 1 AND tx.height <= 5 AND account.number=1", + resultsLength: 1, + }, + "Return all events from a height in [1; 10] by account.number 2": { + q: "tx.height >= 1 AND tx.height <= 10 AND account.number=1", + resultsLength: 2, + }, + } + + ctx := context.Background() + + for _, tc := range testCases { + tc := tc + t.Run(tc.q, func(t *testing.T) { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + assert.NoError(t, err) + + assert.Len(t, results, tc.resultsLength) + if tc.resultsLength > 0 { + for _, txr := range results { + switch txr.Height { + case 1: + assert.True(t, proto.Equal(txResult, txr)) + case 10: + assert.True(t, proto.Equal(txResult10, txr)) + default: + assert.True(t, false) + } + } + } + }) + } +} + +func TestTxSearchWithCancelation(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "owner", Value: "Ivan", Index: true}}}, + {Type: "", Attributes: []abci.EventAttribute{{Key: "not_allowed", Value: "Vlad", Index: true}}}, + }) + err := indexer.Index(txResult) + require.NoError(t, err) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + results, err := indexer.Search(ctx, query.MustCompile(`account.number = 1`)) + assert.NoError(t, err) + assert.Empty(t, results) +} + +func TestTxSearchDeprecatedIndexing(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + // index tx using events indexing (composite key) + txResult1 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}}, + }) + hash1 := types.Tx(txResult1.Tx).Hash() + + err := indexer.Index(txResult1) + require.NoError(t, err) + + // index tx also using deprecated indexing (event as key) + txResult2 := txResultWithEvents(nil) + txResult2.Tx = types.Tx("HELLO WORLD 2") + + hash2 := types.Tx(txResult2.Tx).Hash() + b := indexer.store.NewBatch() + + rawBytes, err := proto.Marshal(txResult2) + require.NoError(t, err) + + depKey := []byte(fmt.Sprintf("%s/%s/%d/%d", + "sender", + "addr1", + txResult2.Height, + txResult2.Index, + )) + + err = b.Set(depKey, hash2) + require.NoError(t, err) + err = b.Set(keyForHeight(txResult2), hash2) + require.NoError(t, err) + err = b.Set(hash2, rawBytes) + require.NoError(t, err) + err = b.Write() + require.NoError(t, err) + + testCases := []struct { + q string + results []*abci.TxResult + }{ + // search by hash + {fmt.Sprintf("tx.hash = '%X'", hash1), []*abci.TxResult{txResult1}}, + // search by hash + {fmt.Sprintf("tx.hash = '%X'", hash2), []*abci.TxResult{txResult2}}, + // search by exact match (one key) + {"account.number = 1", []*abci.TxResult{txResult1}}, + {"account.number >= 1 AND account.number <= 5", []*abci.TxResult{txResult1}}, + // search by range (lower bound) + {"account.number >= 1", []*abci.TxResult{txResult1}}, + // search by range (upper bound) + {"account.number <= 5", []*abci.TxResult{txResult1}}, + // search using not allowed key + {"not_allowed = 'boom'", []*abci.TxResult{}}, + // search for not existing tx result + {"account.number >= 2 AND account.number <= 5", []*abci.TxResult{}}, + // search using not existing key + {"account.date >= TIME 2013-05-03T14:45:00Z", []*abci.TxResult{}}, + // search by deprecated key + {"sender = 'addr1'", []*abci.TxResult{txResult2}}, + } + + ctx := context.Background() + + for _, tc := range testCases { + tc := tc + t.Run(tc.q, func(t *testing.T) { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + require.NoError(t, err) + for _, txr := range results { + for _, tr := range tc.results { + assert.True(t, proto.Equal(tr, txr)) + } + } + }) + } +} + +func TestTxSearchOneTxWithMultipleSameTagsButDifferentValues(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "2", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "3", Index: false}}}, + }) + + err := indexer.Index(txResult) + require.NoError(t, err) + + testCases := []struct { + name string + q string + found bool + }{ + { + q: "account.number >= 1", + found: true, + }, + { + q: "account.number > 2", + found: false, + }, + { + q: "account.number >= 1 AND tx.height = 3 AND tx.height > 0", + found: true, + }, + { + q: "account.number >= 1 AND tx.height > 0 AND tx.height = 3", + found: true, + }, + + { + q: "account.number >= 1 AND tx.height = 1 AND tx.height = 2 AND tx.height = 3", + found: true, + }, + + { + q: "account.number >= 1 AND tx.height = 3 AND tx.height = 2 AND tx.height = 1", + found: false, + }, + { + q: "account.number >= 1 AND tx.height = 3", + found: false, + }, + { + q: "account.number > 1 AND tx.height < 2", + found: true, + }, + { + q: "account.number >= 2", + found: true, + }, + { + q: "account.number <= 1", + found: true, + }, + { + q: "account.number = 'something'", + found: false, + }, + { + q: "account.number CONTAINS 'bla'", + found: false, + }, + } + + ctx := context.Background() + + for _, tc := range testCases { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + assert.NoError(t, err) + n := 0 + if tc.found { + n = 1 + } + assert.Len(t, results, n) + assert.True(t, !tc.found || proto.Equal(txResult, results[0])) + + } +} + +func TestTxIndexDuplicatePreviouslySuccessful(t *testing.T) { + mockTx := types.Tx("MOCK_TX_HASH") + + testCases := []struct { + name string + tx1 *abci.TxResult + tx2 *abci.TxResult + expOverwrite bool // do we expect the second tx to overwrite the first tx + }{ + { + "don't overwrite as a non-zero code was returned and the previous tx was successful", + &abci.TxResult{ + Height: 1, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK, + }, + }, + &abci.TxResult{ + Height: 2, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK + 1, + }, + }, + false, + }, + { + "overwrite as the previous tx was also unsuccessful", + &abci.TxResult{ + Height: 1, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK + 1, + }, + }, + &abci.TxResult{ + Height: 2, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK + 1, + }, + }, + true, + }, + { + "overwrite as the most recent tx was successful", + &abci.TxResult{ + Height: 1, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK, + }, + }, + &abci.TxResult{ + Height: 2, + Index: 0, + Tx: mockTx, + Result: abci.ExecTxResult{ + Code: abci.CodeTypeOK, + }, + }, + true, + }, + } + + hash := mockTx.Hash() + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + // index the first tx + err := indexer.Index(tc.tx1) + require.NoError(t, err) + + // index the same tx with different results + err = indexer.Index(tc.tx2) + require.NoError(t, err) + + res, err := indexer.Get(hash) + require.NoError(t, err) + + if tc.expOverwrite { + require.Equal(t, tc.tx2, res) + } else { + require.Equal(t, tc.tx1, res) + } + }) + } +} + +func TestTxSearchMultipleTxs(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + // indexed first, but bigger height (to test the order of transactions) + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}}, + }) + + txResult.Tx = types.Tx("Bob's account") + txResult.Height = 2 + txResult.Index = 1 + err := indexer.Index(txResult) + require.NoError(t, err) + + // indexed second, but smaller height (to test the order of transactions) + txResult2 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "2", Index: true}}}, + }) + txResult2.Tx = types.Tx("Alice's account") + txResult2.Height = 1 + txResult2.Index = 2 + + err = indexer.Index(txResult2) + require.NoError(t, err) + + // indexed third (to test the order of transactions) + txResult3 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "3", Index: true}}}, + }) + txResult3.Tx = types.Tx("Jack's account") + txResult3.Height = 1 + txResult3.Index = 1 + err = indexer.Index(txResult3) + require.NoError(t, err) + + // indexed fourth (to test we don't include txs with similar events) + // https://github.com/tendermint/tendermint/issues/2908 + txResult4 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number.id", Value: "1", Index: true}}}, + }) + txResult4.Tx = types.Tx("Mike's account") + txResult4.Height = 2 + txResult4.Index = 2 + err = indexer.Index(txResult4) + require.NoError(t, err) + + ctx := context.Background() + + results, err := indexer.Search(ctx, query.MustCompile(`account.number >= 1`)) + assert.NoError(t, err) + + require.Len(t, results, 3) +} + +func txResultWithEvents(events []abci.Event) *abci.TxResult { + tx := types.Tx("HELLO WORLD") + return &abci.TxResult{ + Height: 1, + Index: 0, + Tx: tx, + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, + Log: "", + Events: events, + }, + } +} + +func benchmarkTxIndex(txsCount int64, b *testing.B) { + dir, err := os.MkdirTemp("", "tx_index_db") + require.NoError(b, err) + defer os.RemoveAll(dir) + + store, err := db.NewDB("tx_index", "goleveldb", dir) + require.NoError(b, err) + indexer := NewTxIndex(store) + + batch := txindex.NewBatch(txsCount) + txIndex := uint32(0) + for i := int64(0); i < txsCount; i++ { + tx := cmtrand.Bytes(250) + txResult := &abci.TxResult{ + Height: 1, + Index: txIndex, + Tx: tx, + Result: abci.ExecTxResult{ + Data: []byte{0}, + Code: abci.CodeTypeOK, + Log: "", + Events: []abci.Event{}, + }, + } + if err := batch.Add(txResult); err != nil { + b.Fatal(err) + } + txIndex++ + } + + b.ResetTimer() + + for n := 0; n < b.N; n++ { + err = indexer.AddBatch(batch) + } + if err != nil { + b.Fatal(err) + } +} + +func TestBigInt(t *testing.T) { + indexer := NewTxIndex(db.NewMemDB()) + + bigInt := "10000000000000000000" + bigIntPlus1 := "10000000000000000001" + bigFloat := bigInt + ".76" + bigFloatLower := bigInt + ".1" + bigFloatSmaller := "9999999999999999999" + ".1" + bigIntSmaller := "9999999999999999999" + + txResult := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigInt, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigFloatSmaller, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigIntPlus1, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigFloatLower, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "owner", Value: "/Ivan/", Index: true}}}, + {Type: "", Attributes: []abci.EventAttribute{{Key: "not_allowed", Value: "Vlad", Index: true}}}, + }) + hash := types.Tx(txResult.Tx).Hash() + + err := indexer.Index(txResult) + + require.NoError(t, err) + + txResult2 := txResultWithEvents([]abci.Event{ + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigFloat, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigFloat, Index: true}, {Key: "amount", Value: "5", Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigIntSmaller, Index: true}}}, + {Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: bigInt, Index: true}, {Key: "amount", Value: "3", Index: true}}}}) + + txResult2.Tx = types.Tx("NEW TX") + txResult2.Height = 2 + txResult2.Index = 2 + + hash2 := types.Tx(txResult2.Tx).Hash() + + err = indexer.Index(txResult2) + require.NoError(t, err) + testCases := []struct { + q string + txRes *abci.TxResult + resultsLength int + }{ + // search by hash + {fmt.Sprintf("tx.hash = '%X'", hash), txResult, 1}, + // search by hash (lower) + {fmt.Sprintf("tx.hash = '%x'", hash), txResult, 1}, + {fmt.Sprintf("tx.hash = '%x'", hash2), txResult2, 1}, + // search by exact match (one key) - bigint + {"account.number >= " + bigInt, nil, 2}, + // search by exact match (one key) - bigint range + {"account.number >= " + bigInt + " AND tx.height > 0", nil, 2}, + {"account.number >= " + bigInt + " AND tx.height > 0 AND account.owner = '/Ivan/'", nil, 0}, + // Floats are not parsed + {"account.number >= " + bigInt + " AND tx.height > 0 AND account.amount > 4", txResult2, 1}, + {"account.number >= " + bigInt + " AND tx.height > 0 AND account.amount = 5", txResult2, 1}, + {"account.number >= " + bigInt + " AND account.amount <= 5", txResult2, 1}, + {"account.number > " + bigFloatSmaller + " AND account.amount = 3", txResult2, 1}, + {"account.number < " + bigInt + " AND tx.height >= 1", nil, 2}, + {"account.number < " + bigInt + " AND tx.height = 1", nil, 1}, + {"account.number < " + bigInt + " AND tx.height = 2", nil, 1}, + } + + ctx := context.Background() + + for _, tc := range testCases { + tc := tc + t.Run(tc.q, func(t *testing.T) { + results, err := indexer.Search(ctx, query.MustCompile(tc.q)) + assert.NoError(t, err) + assert.Len(t, results, tc.resultsLength) + if tc.resultsLength > 0 && tc.txRes != nil { + assert.True(t, proto.Equal(results[0], tc.txRes)) + } + }) + } +} + +func BenchmarkTxIndex1(b *testing.B) { benchmarkTxIndex(1, b) } +func BenchmarkTxIndex500(b *testing.B) { benchmarkTxIndex(500, b) } +func BenchmarkTxIndex1000(b *testing.B) { benchmarkTxIndex(1000, b) } +func BenchmarkTxIndex2000(b *testing.B) { benchmarkTxIndex(2000, b) } +func BenchmarkTxIndex10000(b *testing.B) { benchmarkTxIndex(10000, b) } diff --git a/state/txindex/kv/utils.go b/state/txindex/kv/utils.go new file mode 100644 index 0000000..f96c2d7 --- /dev/null +++ b/state/txindex/kv/utils.go @@ -0,0 +1,108 @@ +package kv + +import ( + "fmt" + "math/big" + + idxutil "github.com/cometbft/cometbft/internal/indexer" + cmtsyntax "github.com/cometbft/cometbft/libs/pubsub/query/syntax" + "github.com/cometbft/cometbft/state/indexer" + "github.com/cometbft/cometbft/types" + "github.com/google/orderedcode" +) + +type HeightInfo struct { + heightRange indexer.QueryRange + height int64 + heightEqIdx int + onlyHeightRange bool + onlyHeightEq bool +} + +// IntInSlice returns true if a is found in the list. +func intInSlice(a int, list []int) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} + +func ParseEventSeqFromEventKey(key []byte) (int64, error) { + var ( + compositeKey, typ, eventValue string + height int64 + eventSeq int64 + ) + + remaining, err := orderedcode.Parse(string(key), &compositeKey, &eventValue, &height, &typ, &eventSeq) + if err != nil { + return 0, fmt.Errorf("failed to parse event key: %w", err) + } + + if len(remaining) != 0 { + return 0, fmt.Errorf("unexpected remainder in key: %s", remaining) + } + + return eventSeq, nil +} + +func dedupHeight(conditions []cmtsyntax.Condition) (dedupConditions []cmtsyntax.Condition, heightInfo HeightInfo) { + heightInfo.heightEqIdx = -1 + heightRangeExists := false + found := false + var heightCondition []cmtsyntax.Condition + heightInfo.onlyHeightEq = true + heightInfo.onlyHeightRange = true + for _, c := range conditions { + if c.Tag == types.TxHeightKey { + if c.Op == cmtsyntax.TEq { + if heightRangeExists || found { + continue + } + hFloat := c.Arg.Number() + if hFloat != nil { + h, _ := hFloat.Int64() + heightInfo.height = h + found = true + heightCondition = append(heightCondition, c) + } + } else { + heightInfo.onlyHeightEq = false + heightRangeExists = true + dedupConditions = append(dedupConditions, c) + } + } else { + heightInfo.onlyHeightRange = false + heightInfo.onlyHeightEq = false + dedupConditions = append(dedupConditions, c) + } + } + if !heightRangeExists && len(heightCondition) != 0 { + heightInfo.heightEqIdx = len(dedupConditions) + heightInfo.onlyHeightRange = false + dedupConditions = append(dedupConditions, heightCondition...) + } else { + // If we found a range make sure we set the height idx to -1 as the height equality + // will be removed + heightInfo.heightEqIdx = -1 + heightInfo.height = 0 + heightInfo.onlyHeightEq = false + } + return dedupConditions, heightInfo +} + +func checkHeightConditions(heightInfo HeightInfo, keyHeight int64) (bool, error) { + if heightInfo.heightRange.Key != "" { + withinBounds, err := idxutil.CheckBounds(heightInfo.heightRange, big.NewInt(keyHeight)) + if err != nil || !withinBounds { + return false, err + } + } else { + if heightInfo.height != 0 && keyHeight != heightInfo.height { + return false, nil + } + } + return true, nil +} diff --git a/state/txindex/kv/utils_test.go b/state/txindex/kv/utils_test.go new file mode 100644 index 0000000..6fa3a40 --- /dev/null +++ b/state/txindex/kv/utils_test.go @@ -0,0 +1,14 @@ +package kv + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIntInSlice(t *testing.T) { + assert.True(t, intInSlice(1, []int{1, 2, 3})) + assert.False(t, intInSlice(4, []int{1, 2, 3})) + assert.True(t, intInSlice(0, []int{0})) + assert.False(t, intInSlice(0, []int{})) +} diff --git a/state/txindex/mocks/tx_indexer.go b/state/txindex/mocks/tx_indexer.go new file mode 100644 index 0000000..6627e4d --- /dev/null +++ b/state/txindex/mocks/tx_indexer.go @@ -0,0 +1,136 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + log "github.com/cometbft/cometbft/libs/log" + mock "github.com/stretchr/testify/mock" + + query "github.com/cometbft/cometbft/libs/pubsub/query" + + txindex "github.com/cometbft/cometbft/state/txindex" + + types "github.com/cometbft/cometbft/abci/types" +) + +// TxIndexer is an autogenerated mock type for the TxIndexer type +type TxIndexer struct { + mock.Mock +} + +// AddBatch provides a mock function with given fields: b +func (_m *TxIndexer) AddBatch(b *txindex.Batch) error { + ret := _m.Called(b) + + if len(ret) == 0 { + panic("no return value specified for AddBatch") + } + + var r0 error + if rf, ok := ret.Get(0).(func(*txindex.Batch) error); ok { + r0 = rf(b) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Get provides a mock function with given fields: hash +func (_m *TxIndexer) Get(hash []byte) (*types.TxResult, error) { + ret := _m.Called(hash) + + if len(ret) == 0 { + panic("no return value specified for Get") + } + + var r0 *types.TxResult + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (*types.TxResult, error)); ok { + return rf(hash) + } + if rf, ok := ret.Get(0).(func([]byte) *types.TxResult); ok { + r0 = rf(hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.TxResult) + } + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Index provides a mock function with given fields: result +func (_m *TxIndexer) Index(result *types.TxResult) error { + ret := _m.Called(result) + + if len(ret) == 0 { + panic("no return value specified for Index") + } + + var r0 error + if rf, ok := ret.Get(0).(func(*types.TxResult) error); ok { + r0 = rf(result) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Search provides a mock function with given fields: ctx, q +func (_m *TxIndexer) Search(ctx context.Context, q *query.Query) ([]*types.TxResult, error) { + ret := _m.Called(ctx, q) + + if len(ret) == 0 { + panic("no return value specified for Search") + } + + var r0 []*types.TxResult + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *query.Query) ([]*types.TxResult, error)); ok { + return rf(ctx, q) + } + if rf, ok := ret.Get(0).(func(context.Context, *query.Query) []*types.TxResult); ok { + r0 = rf(ctx, q) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*types.TxResult) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *query.Query) error); ok { + r1 = rf(ctx, q) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SetLogger provides a mock function with given fields: l +func (_m *TxIndexer) SetLogger(l log.Logger) { + _m.Called(l) +} + +// NewTxIndexer creates a new instance of TxIndexer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTxIndexer(t interface { + mock.TestingT + Cleanup(func()) +}) *TxIndexer { + mock := &TxIndexer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/state/txindex/null/null.go b/state/txindex/null/null.go new file mode 100644 index 0000000..4bee6fc --- /dev/null +++ b/state/txindex/null/null.go @@ -0,0 +1,40 @@ +package null + +import ( + "context" + "errors" + + "github.com/cometbft/cometbft/libs/log" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/pubsub/query" + "github.com/cometbft/cometbft/state/txindex" +) + +var _ txindex.TxIndexer = (*TxIndex)(nil) + +// TxIndex acts as a /dev/null. +type TxIndex struct{} + +// Get on a TxIndex is disabled and panics when invoked. +func (txi *TxIndex) Get(_ []byte) (*abci.TxResult, error) { + return nil, errors.New(`indexing is disabled (set 'tx_index = "kv"' in config)`) +} + +// AddBatch is a noop and always returns nil. +func (txi *TxIndex) AddBatch(_ *txindex.Batch) error { + return nil +} + +// Index is a noop and always returns nil. +func (txi *TxIndex) Index(_ *abci.TxResult) error { + return nil +} + +func (txi *TxIndex) Search(_ context.Context, _ *query.Query) ([]*abci.TxResult, error) { + return []*abci.TxResult{}, nil +} + +func (txi *TxIndex) SetLogger(log.Logger) { + +} diff --git a/state/validation.go b/state/validation.go new file mode 100644 index 0000000..0bfe62a --- /dev/null +++ b/state/validation.go @@ -0,0 +1,154 @@ +package state + +import ( + "bytes" + "errors" + "fmt" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/types" +) + +//----------------------------------------------------- +// Validate block + +func validateBlock(state State, block *types.Block) error { + // Validate internal consistency. + if err := block.ValidateBasic(); err != nil { + return err + } + + // Validate basic info. + if block.Version.App != state.Version.Consensus.App || + block.Version.Block != state.Version.Consensus.Block { + return fmt.Errorf("wrong Block.Header.Version. Expected %v, got %v", + state.Version.Consensus, + block.Version, + ) + } + if block.ChainID != state.ChainID { + return fmt.Errorf("wrong Block.Header.ChainID. Expected %v, got %v", + state.ChainID, + block.ChainID, + ) + } + if state.LastBlockHeight == 0 && block.Height != state.InitialHeight { + return fmt.Errorf("wrong Block.Header.Height. Expected %v for initial block, got %v", + block.Height, state.InitialHeight) + } + if state.LastBlockHeight > 0 && block.Height != state.LastBlockHeight+1 { + return fmt.Errorf("wrong Block.Header.Height. Expected %v, got %v", + state.LastBlockHeight+1, + block.Height, + ) + } + // Validate prev block info. + if !block.LastBlockID.Equals(state.LastBlockID) { + return fmt.Errorf("wrong Block.Header.LastBlockID. Expected %v, got %v", + state.LastBlockID, + block.LastBlockID, + ) + } + + // Validate app info + if !bytes.Equal(block.AppHash, state.AppHash) { + return fmt.Errorf("wrong Block.Header.AppHash. Expected %X, got %v", + state.AppHash, + block.AppHash, + ) + } + if !bytes.Equal(block.ConsensusHash, state.ConsensusParams.Hash()) { + return fmt.Errorf("wrong Block.Header.ConsensusHash. Expected %X, got %v", + state.ConsensusParams.Hash(), + block.ConsensusHash, + ) + } + if !bytes.Equal(block.LastResultsHash, state.LastResultsHash) { + return fmt.Errorf("wrong Block.Header.LastResultsHash. Expected %X, got %v", + state.LastResultsHash, + block.LastResultsHash, + ) + } + if !bytes.Equal(block.ValidatorsHash, state.Validators.Hash()) { + return fmt.Errorf("wrong Block.Header.ValidatorsHash. Expected %X, got %v", + state.Validators.Hash(), + block.ValidatorsHash, + ) + } + if !bytes.Equal(block.NextValidatorsHash, state.NextValidators.Hash()) { + return fmt.Errorf("wrong Block.Header.NextValidatorsHash. Expected %X, got %v", + state.NextValidators.Hash(), + block.NextValidatorsHash, + ) + } + + // Validate block LastCommit. + if block.Height == state.InitialHeight { + if len(block.LastCommit.Signatures) != 0 { + return errors.New("initial block can't have LastCommit signatures") + } + } else { + // LastCommit.Signatures length is checked in VerifyCommit. + if err := state.LastValidators.VerifyCommit( + state.ChainID, state.LastBlockID, block.Height-1, block.LastCommit); err != nil { + return err + } + } + + // NOTE: We can't actually verify it's the right proposer because we don't + // know what round the block was first proposed. So just check that it's + // a legit address and a known validator. + if len(block.ProposerAddress) != crypto.AddressSize { + return fmt.Errorf("expected ProposerAddress size %d, got %d", + crypto.AddressSize, + len(block.ProposerAddress), + ) + } + if !state.Validators.HasAddress(block.ProposerAddress) { + return fmt.Errorf("block.Header.ProposerAddress %X is not a validator", + block.ProposerAddress, + ) + } + + // Validate block Time + switch { + case block.Height > state.InitialHeight: + if !block.Time.After(state.LastBlockTime) { + return fmt.Errorf("block time %v not greater than last block time %v", + block.Time, + state.LastBlockTime, + ) + } + + medianTime, err := MedianTime(block.LastCommit, state.LastValidators) + if err != nil { + return fmt.Errorf("error validating block while calculating median time: %w", err) + } + if !block.Time.Equal(medianTime) { + return fmt.Errorf("invalid block time. Expected %v, got %v", + medianTime, + block.Time, + ) + } + + case block.Height == state.InitialHeight: + genesisTime := state.LastBlockTime + if !block.Time.Equal(genesisTime) { + return fmt.Errorf("block time %v is not equal to genesis time %v", + block.Time, + genesisTime, + ) + } + + default: + return fmt.Errorf("block height %v lower than initial height %v", + block.Height, state.InitialHeight) + } + + // Check evidence doesn't exceed the limit amount of bytes. + if max, got := state.ConsensusParams.Evidence.MaxBytes, block.Evidence.ByteSize(); got > max { + return types.NewErrEvidenceOverflow(max, got) + } + + return nil +} diff --git a/state/validation_test.go b/state/validation_test.go new file mode 100644 index 0000000..7f04a56 --- /dev/null +++ b/state/validation_test.go @@ -0,0 +1,513 @@ +package state_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" + mpmocks "github.com/cometbft/cometbft/mempool/mocks" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/state/mocks" + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const validationTestsStopHeight int64 = 10 + +func TestValidateBlockHeader(t *testing.T) { + proxyApp := newTestApp() + require.NoError(t, proxyApp.Start()) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(3, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + lastCommit := &types.Commit{} + var lastExtCommit *types.ExtendedCommit + + // some bad values + wrongHash := tmhash.Sum([]byte("this hash is wrong")) + wrongVersion1 := state.Version.Consensus + wrongVersion1.Block += 2 + wrongVersion2 := state.Version.Consensus + wrongVersion2.App += 2 + + // Manipulation of any header field causes failure. + testCases := []struct { + name string + malleateBlock func(block *types.Block) + }{ + {"Version wrong1", func(block *types.Block) { block.Version = wrongVersion1 }}, + {"Version wrong2", func(block *types.Block) { block.Version = wrongVersion2 }}, + {"ChainID wrong", func(block *types.Block) { block.ChainID = "not-the-real-one" }}, + {"Height wrong", func(block *types.Block) { block.Height += 10 }}, + {"Time wrong", func(block *types.Block) { block.Time = block.Time.Add(-time.Second * 1) }}, + + {"LastBlockID wrong", func(block *types.Block) { block.LastBlockID.PartSetHeader.Total += 10 }}, + {"LastCommitHash wrong", func(block *types.Block) { block.LastCommitHash = wrongHash }}, + {"DataHash wrong", func(block *types.Block) { block.DataHash = wrongHash }}, + + {"ValidatorsHash wrong", func(block *types.Block) { block.ValidatorsHash = wrongHash }}, + {"NextValidatorsHash wrong", func(block *types.Block) { block.NextValidatorsHash = wrongHash }}, + {"ConsensusHash wrong", func(block *types.Block) { block.ConsensusHash = wrongHash }}, + {"AppHash wrong", func(block *types.Block) { block.AppHash = wrongHash }}, + {"LastResultsHash wrong", func(block *types.Block) { block.LastResultsHash = wrongHash }}, + + {"EvidenceHash wrong", func(block *types.Block) { block.EvidenceHash = wrongHash }}, + {"Proposer wrong", func(block *types.Block) { block.ProposerAddress = ed25519.GenPrivKey().PubKey().Address() }}, + {"Proposer invalid", func(block *types.Block) { block.ProposerAddress = []byte("wrong size") }}, + } + + // Build up state for multiple heights + for height := int64(1); height < validationTestsStopHeight; height++ { + /* + Invalid blocks don't pass + */ + for _, tc := range testCases { + block, err := makeBlock(state, height, lastCommit) + require.NoError(t, err) + tc.malleateBlock(block) + err = blockExec.ValidateBlock(state, block) + require.Error(t, err, tc.name) + } + + /* + A good block passes + */ + var err error + state, _, lastExtCommit, err = makeAndCommitGoodBlock( + state, height, lastCommit, state.Validators.GetProposer().Address, blockExec, privVals, nil) + require.NoError(t, err, "height %d", height) + lastCommit = lastExtCommit.ToCommit() + } + + nextHeight := validationTestsStopHeight + block, err := makeBlock(state, nextHeight, lastCommit) + require.NoError(t, err) + state.InitialHeight = nextHeight + 1 + err = blockExec.ValidateBlock(state, block) + require.Error(t, err, "expected an error when state is ahead of block") + assert.Contains(t, err.Error(), "lower than initial height") +} + +func TestValidateBlockCommit(t *testing.T) { + proxyApp := newTestApp() + require.NoError(t, proxyApp.Start()) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(1, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + lastCommit := &types.Commit{} + var lastExtCommit *types.ExtendedCommit + wrongSigsCommit := &types.Commit{Height: 1} + badPrivVal := types.NewMockPV() + + for height := int64(1); height < validationTestsStopHeight; height++ { + proposerAddr := state.Validators.GetProposer().Address + if height > 1 { + /* + #2589: ensure state.LastValidators.VerifyCommit fails here + */ + // should be height-1 instead of height + idx, _ := state.Validators.GetByAddress(proposerAddr) + wrongHeightVote := types.MakeVoteNoError( + t, + privVals[proposerAddr.String()], + chainID, + idx, + height, + 0, + 2, + state.LastBlockID, + time.Now(), + ) + wrongHeightCommit := &types.Commit{ + Height: wrongHeightVote.Height, + Round: wrongHeightVote.Round, + BlockID: state.LastBlockID, + Signatures: []types.CommitSig{wrongHeightVote.CommitSig()}, + } + block, err := makeBlock(state, height, wrongHeightCommit) + require.NoError(t, err) + err = blockExec.ValidateBlock(state, block) + _, isErrInvalidCommitHeight := err.(types.ErrInvalidCommitHeight) + require.True(t, isErrInvalidCommitHeight, "expected ErrInvalidCommitHeight at height %d but got: %v", height, err) + + /* + #2589: test len(block.LastCommit.Signatures) == state.LastValidators.Size() + */ + _, err = makeBlock(state, height, wrongSigsCommit) + require.Error(t, err) + require.ErrorContains(t, err, "error making block") + } + + /* + A good block passes + */ + var err error + var blockID types.BlockID + state, blockID, lastExtCommit, err = makeAndCommitGoodBlock( + state, + height, + lastCommit, + proposerAddr, + blockExec, + privVals, + nil, + ) + require.NoError(t, err, "height %d", height) + lastCommit = lastExtCommit.ToCommit() + + /* + wrongSigsCommit is fine except for the extra bad precommit + */ + idx, _ := state.Validators.GetByAddress(proposerAddr) + goodVote := types.MakeVoteNoError( + t, + privVals[proposerAddr.String()], + chainID, + idx, + height, + 0, + cmtproto.PrecommitType, + blockID, + time.Now(), + ) + + bpvPubKey, err := badPrivVal.GetPubKey() + require.NoError(t, err) + + badVote := &types.Vote{ + ValidatorAddress: bpvPubKey.Address(), + ValidatorIndex: 0, + Height: height, + Round: 0, + Timestamp: cmttime.Now(), + Type: cmtproto.PrecommitType, + BlockID: blockID, + } + + g := goodVote.ToProto() + b := badVote.ToProto() + + err = badPrivVal.SignVote(chainID, g) + require.NoError(t, err, "height %d", height) + err = badPrivVal.SignVote(chainID, b) + require.NoError(t, err, "height %d", height) + + goodVote.Signature, badVote.Signature = g.Signature, b.Signature + + wrongSigsCommit = &types.Commit{ + Height: goodVote.Height, + Round: goodVote.Round, + BlockID: blockID, + Signatures: []types.CommitSig{goodVote.CommitSig(), badVote.CommitSig()}, + } + } +} + +func TestValidateBlockEvidence(t *testing.T) { + proxyApp := newTestApp() + require.NoError(t, proxyApp.Start()) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(4, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + + evpool := &mocks.EvidencePool{} + evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil) + evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return() + evpool.On("ABCIEvidence", mock.AnythingOfType("int64"), mock.AnythingOfType("[]types.Evidence")).Return( + []abci.Misbehavior{}) + + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + state.ConsensusParams.Evidence.MaxBytes = 1000 + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + evpool, + blockStore, + ) + lastCommit := &types.Commit{} + var lastExtCommit *types.ExtendedCommit + + for height := int64(1); height < validationTestsStopHeight; height++ { + proposerAddr := state.Validators.GetProposer().Address + maxBytesEvidence := state.ConsensusParams.Evidence.MaxBytes + if height > 1 { + /* + A block with too much evidence fails + */ + evidence := make([]types.Evidence, 0) + var currentBytes int64 + // more bytes than the maximum allowed for evidence + for currentBytes <= maxBytesEvidence { + newEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, time.Now(), + privVals[proposerAddr.String()], chainID) + require.NoError(t, err) + evidence = append(evidence, newEv) + currentBytes += int64(len(newEv.Bytes())) + } + block, err := state.MakeBlock(height, test.MakeNTxs(height, 10), lastCommit, evidence, proposerAddr) + require.NoError(t, err) + + err = blockExec.ValidateBlock(state, block) + if assert.Error(t, err) { + _, ok := err.(*types.ErrEvidenceOverflow) + require.True(t, ok, "expected error to be of type ErrEvidenceOverflow at height %d but got %v", height, err) + } + } + + /* + A good block with several pieces of good evidence passes + */ + evidence := make([]types.Evidence, 0) + var currentBytes int64 + // precisely the amount of allowed evidence + for { + newEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, + privVals[proposerAddr.String()], chainID) + require.NoError(t, err) + currentBytes += int64(len(newEv.Bytes())) + if currentBytes >= maxBytesEvidence { + break + } + evidence = append(evidence, newEv) + } + + var err error + state, _, lastExtCommit, err = makeAndCommitGoodBlock( + state, + height, + lastCommit, + proposerAddr, + blockExec, + privVals, + evidence, + ) + require.NoError(t, err, "height %d", height) + lastCommit = lastExtCommit.ToCommit() + + } +} + +func TestValidateBlockTime(t *testing.T) { + proxyApp := newTestApp() + require.NoError(t, proxyApp.Start()) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(3, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + lastCommit := &types.Commit{} + var lastExtCommit *types.ExtendedCommit + + // Build up state for test + for height := int64(1); height < 3; height++ { + var err error + state, _, lastExtCommit, err = makeAndCommitGoodBlock( + state, height, lastCommit, state.Validators.GetProposer().Address, blockExec, privVals, nil) + require.NoError(t, err, "height %d", height) + lastCommit = lastExtCommit.ToCommit() + } + + t.Run("block time before last block time", func(t *testing.T) { + height := int64(3) + block, err := makeBlock(state, height, lastCommit) + require.NoError(t, err) + + // Set time to before last block time + block.Time = block.Time.Add(-time.Millisecond * 10) + err = blockExec.ValidateBlock(state, block) + + require.ErrorContains(t, err, "not greater than last block time") + }) + + t.Run("block time after last block time, different than median time", func(t *testing.T) { + height := int64(3) + block, err := makeBlock(state, height, lastCommit) + require.NoError(t, err) + // Set time to after the median time + block.Time = block.Time.Add(time.Second) + err = blockExec.ValidateBlock(state, block) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid block time") + }) + + t.Run("block time after last block time, same as median time", func(t *testing.T) { + height := int64(3) + block, err := makeBlock(state, height, lastCommit) + require.NoError(t, err) + err = blockExec.ValidateBlock(state, block) + require.NoError(t, err) + }) +} + +func TestValidateBlockInvalidCommit(t *testing.T) { + proxyApp := newTestApp() + require.NoError(t, proxyApp.Start()) + defer proxyApp.Stop() //nolint:errcheck // ignore for tests + + state, stateDB, privVals := makeState(3, 1) + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + mp := &mpmocks.Mempool{} + mp.On("Lock").Return() + mp.On("Unlock").Return() + mp.On("FlushAppConn", mock.Anything).Return(nil) + mp.On("Update", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything).Return(nil) + + blockStore := store.NewBlockStore(dbm.NewMemDB()) + + blockExec := sm.NewBlockExecutor( + stateStore, + log.TestingLogger(), + proxyApp.Consensus(), + mp, + sm.EmptyEvidencePool{}, + blockStore, + ) + lastCommit := &types.Commit{} + var lastExtCommit *types.ExtendedCommit + + // Build up state for test + for height := int64(1); height < 3; height++ { + var err error + state, _, lastExtCommit, err = makeAndCommitGoodBlock( + state, height, lastCommit, state.Validators.GetProposer().Address, blockExec, privVals, nil) + require.NoError(t, err, "height %d", height) + lastCommit = lastExtCommit.ToCommit() + } + + t.Run("commit with unknown validator flagged as commit", func(t *testing.T) { + height := int64(3) + + // Create a commit where only unknown validators have BlockIDFlagCommit + unknownVal := ed25519.GenPrivKey() + now := time.Now() + + invalidCommit := &types.Commit{ + Height: height - 1, + Round: 0, + BlockID: state.LastBlockID, + Signatures: []types.CommitSig{ + { + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: unknownVal.PubKey().Address(), + Timestamp: now, + Signature: []byte("dummy"), + }, + }, + } + + _, err := makeBlock(state, height, invalidCommit) + require.Error(t, err) + require.Contains(t, err.Error(), "commit validator not found in validator set") + }) +} diff --git a/statesync/chunks.go b/statesync/chunks.go new file mode 100644 index 0000000..054467f --- /dev/null +++ b/statesync/chunks.go @@ -0,0 +1,320 @@ +package statesync + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "time" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" +) + +// errDone is returned by chunkQueue.Next() when all chunks have been returned. +var errDone = errors.New("chunk queue has completed") + +// chunk contains data for a chunk. +type chunk struct { + Height uint64 + Format uint32 + Index uint32 + Chunk []byte + Sender p2p.ID +} + +// chunkQueue manages chunks for a state sync process, ordering them if requested. It acts as an +// iterator over all chunks, but callers can request chunks to be retried, optionally after +// refetching. +type chunkQueue struct { + cmtsync.Mutex + snapshot *snapshot // if this is nil, the queue has been closed + dir string // temp dir for on-disk chunk storage + chunkFiles map[uint32]string // path to temporary chunk file + chunkSenders map[uint32]p2p.ID // the peer who sent the given chunk + chunkAllocated map[uint32]bool // chunks that have been allocated via Allocate() + chunkReturned map[uint32]bool // chunks returned via Next() + waiters map[uint32][]chan<- uint32 // signals WaitFor() waiters about chunk arrival +} + +// newChunkQueue creates a new chunk queue for a snapshot, using a temp dir for storage. +// Callers must call Close() when done. +func newChunkQueue(snapshot *snapshot, tempDir string) (*chunkQueue, error) { + dir, err := os.MkdirTemp(tempDir, "tm-statesync") + if err != nil { + return nil, fmt.Errorf("unable to create temp dir for state sync chunks: %w", err) + } + if snapshot.Chunks == 0 { + return nil, errors.New("snapshot has no chunks") + } + return &chunkQueue{ + snapshot: snapshot, + dir: dir, + chunkFiles: make(map[uint32]string, snapshot.Chunks), + chunkSenders: make(map[uint32]p2p.ID, snapshot.Chunks), + chunkAllocated: make(map[uint32]bool, snapshot.Chunks), + chunkReturned: make(map[uint32]bool, snapshot.Chunks), + waiters: make(map[uint32][]chan<- uint32), + }, nil +} + +// Add adds a chunk to the queue. It ignores chunks that already exist, returning false. +func (q *chunkQueue) Add(chunk *chunk) (bool, error) { + if chunk == nil || chunk.Chunk == nil { + return false, errors.New("cannot add nil chunk") + } + q.Lock() + defer q.Unlock() + if q.snapshot == nil { + return false, nil // queue is closed + } + if chunk.Height != q.snapshot.Height { + return false, fmt.Errorf("invalid chunk height %v, expected %v", chunk.Height, q.snapshot.Height) + } + if chunk.Format != q.snapshot.Format { + return false, fmt.Errorf("invalid chunk format %v, expected %v", chunk.Format, q.snapshot.Format) + } + if chunk.Index >= q.snapshot.Chunks { + return false, fmt.Errorf("received unexpected chunk %v", chunk.Index) + } + if q.chunkFiles[chunk.Index] != "" { + return false, nil + } + + path := filepath.Join(q.dir, strconv.FormatUint(uint64(chunk.Index), 10)) + err := os.WriteFile(path, chunk.Chunk, 0600) + if err != nil { + return false, fmt.Errorf("failed to save chunk %v to file %v: %w", chunk.Index, path, err) + } + q.chunkFiles[chunk.Index] = path + q.chunkSenders[chunk.Index] = chunk.Sender + + // Signal any waiters that the chunk has arrived. + for _, waiter := range q.waiters[chunk.Index] { + waiter <- chunk.Index + close(waiter) + } + delete(q.waiters, chunk.Index) + + return true, nil +} + +// Allocate allocates a chunk to the caller, making it responsible for fetching it. Returns +// errDone once no chunks are left or the queue is closed. +func (q *chunkQueue) Allocate() (uint32, error) { + q.Lock() + defer q.Unlock() + if q.snapshot == nil { + return 0, errDone + } + if uint32(len(q.chunkAllocated)) >= q.snapshot.Chunks { + return 0, errDone + } + for i := uint32(0); i < q.snapshot.Chunks; i++ { + if !q.chunkAllocated[i] { + q.chunkAllocated[i] = true + return i, nil + } + } + return 0, errDone +} + +// Close closes the chunk queue, cleaning up all temporary files. +func (q *chunkQueue) Close() error { + q.Lock() + defer q.Unlock() + if q.snapshot == nil { + return nil + } + for _, waiters := range q.waiters { + for _, waiter := range waiters { + close(waiter) + } + } + q.waiters = nil + q.snapshot = nil + err := os.RemoveAll(q.dir) + if err != nil { + return fmt.Errorf("failed to clean up state sync tempdir %v: %w", q.dir, err) + } + return nil +} + +// Discard discards a chunk. It will be removed from the queue, available for allocation, and can +// be added and returned via Next() again. If the chunk is not already in the queue this does +// nothing, to avoid it being allocated to multiple fetchers. +func (q *chunkQueue) Discard(index uint32) error { + q.Lock() + defer q.Unlock() + return q.discard(index) +} + +// discard discards a chunk, scheduling it for refetching. The caller must hold the mutex lock. +func (q *chunkQueue) discard(index uint32) error { + if q.snapshot == nil { + return nil + } + path := q.chunkFiles[index] + if path == "" { + return nil + } + err := os.Remove(path) + if err != nil { + return fmt.Errorf("failed to remove chunk %v: %w", index, err) + } + delete(q.chunkFiles, index) + delete(q.chunkReturned, index) + delete(q.chunkAllocated, index) + return nil +} + +// DiscardSender discards all *unreturned* chunks from a given sender. If the caller wants to +// discard already returned chunks, this can be done via Discard(). +func (q *chunkQueue) DiscardSender(peerID p2p.ID) error { + q.Lock() + defer q.Unlock() + + for index, sender := range q.chunkSenders { + if sender == peerID && !q.chunkReturned[index] { + err := q.discard(index) + if err != nil { + return err + } + delete(q.chunkSenders, index) + } + } + return nil +} + +// GetSender returns the sender of the chunk with the given index, or empty if not found. +func (q *chunkQueue) GetSender(index uint32) p2p.ID { + q.Lock() + defer q.Unlock() + return q.chunkSenders[index] +} + +// Has checks whether a chunk exists in the queue. +func (q *chunkQueue) Has(index uint32) bool { + q.Lock() + defer q.Unlock() + return q.chunkFiles[index] != "" +} + +// load loads a chunk from disk, or nil if the chunk is not in the queue. The caller must hold the +// mutex lock. +func (q *chunkQueue) load(index uint32) (*chunk, error) { + path, ok := q.chunkFiles[index] + if !ok { + return nil, nil + } + body, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failed to load chunk %v: %w", index, err) + } + return &chunk{ + Height: q.snapshot.Height, + Format: q.snapshot.Format, + Index: index, + Chunk: body, + Sender: q.chunkSenders[index], + }, nil +} + +// Next returns the next chunk from the queue, or errDone if all chunks have been returned. It +// blocks until the chunk is available. Concurrent Next() calls may return the same chunk. +func (q *chunkQueue) Next() (*chunk, error) { + q.Lock() + var chunk *chunk + index, err := q.nextUp() + if err == nil { + chunk, err = q.load(index) + if err == nil { + q.chunkReturned[index] = true + } + } + q.Unlock() + if chunk != nil || err != nil { + return chunk, err + } + + select { + case _, ok := <-q.WaitFor(index): + if !ok { + return nil, errDone // queue closed + } + case <-time.After(chunkTimeout): + return nil, errTimeout + } + + q.Lock() + defer q.Unlock() + chunk, err = q.load(index) + if err != nil { + return nil, err + } + q.chunkReturned[index] = true + return chunk, nil +} + +// nextUp returns the next chunk to be returned, or errDone if all chunks have been returned. The +// caller must hold the mutex lock. +func (q *chunkQueue) nextUp() (uint32, error) { + if q.snapshot == nil { + return 0, errDone + } + for i := uint32(0); i < q.snapshot.Chunks; i++ { + if !q.chunkReturned[i] { + return i, nil + } + } + return 0, errDone +} + +// Retry schedules a chunk to be retried, without refetching it. +func (q *chunkQueue) Retry(index uint32) { + q.Lock() + defer q.Unlock() + delete(q.chunkReturned, index) +} + +// RetryAll schedules all chunks to be retried, without refetching them. +func (q *chunkQueue) RetryAll() { + q.Lock() + defer q.Unlock() + q.chunkReturned = make(map[uint32]bool) +} + +// Size returns the total number of chunks for the snapshot and queue, or 0 when closed. +func (q *chunkQueue) Size() uint32 { + q.Lock() + defer q.Unlock() + if q.snapshot == nil { + return 0 + } + return q.snapshot.Chunks +} + +// WaitFor returns a channel that receives a chunk index when it arrives in the queue, or +// immediately if it has already arrived. The channel is closed without a value if the queue is +// closed or if the chunk index is not valid. +func (q *chunkQueue) WaitFor(index uint32) <-chan uint32 { + q.Lock() + defer q.Unlock() + ch := make(chan uint32, 1) + switch { + case q.snapshot == nil: + close(ch) + case index >= q.snapshot.Chunks: + close(ch) + case q.chunkFiles[index] != "": + ch <- index + close(ch) + default: + if q.waiters[index] == nil { + q.waiters[index] = make([]chan<- uint32, 0) + } + q.waiters[index] = append(q.waiters[index], ch) + } + return ch +} diff --git a/statesync/chunks_test.go b/statesync/chunks_test.go new file mode 100644 index 0000000..1b9382d --- /dev/null +++ b/statesync/chunks_test.go @@ -0,0 +1,550 @@ +package statesync + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/p2p" +) + +func setupChunkQueue(t *testing.T) (*chunkQueue, func()) { + snapshot := &snapshot{ + Height: 3, + Format: 1, + Chunks: 5, + Hash: []byte{7}, + Metadata: nil, + } + queue, err := newChunkQueue(snapshot, "") + require.NoError(t, err) + teardown := func() { + err := queue.Close() + require.NoError(t, err) + } + return queue, teardown +} + +func TestNewChunkQueue_TempDir(t *testing.T) { + snapshot := &snapshot{ + Height: 3, + Format: 1, + Chunks: 5, + Hash: []byte{7}, + Metadata: nil, + } + dir, err := os.MkdirTemp("", "newchunkqueue") + require.NoError(t, err) + defer os.RemoveAll(dir) + queue, err := newChunkQueue(snapshot, dir) + require.NoError(t, err) + + files, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Len(t, files, 1) + + err = queue.Close() + require.NoError(t, err) + + files, err = os.ReadDir(dir) + require.NoError(t, err) + assert.Len(t, files, 0) +} + +func TestChunkQueue(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Adding the first chunk should be fine + added, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}) + require.NoError(t, err) + assert.True(t, added) + + // Adding the last chunk should also be fine + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 4, Chunk: []byte{3, 1, 4}}) + require.NoError(t, err) + assert.True(t, added) + + // Adding the first or last chunks again should return false + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}) + require.NoError(t, err) + assert.False(t, added) + + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 4, Chunk: []byte{3, 1, 4}}) + require.NoError(t, err) + assert.False(t, added) + + // Adding the remaining chunks in reverse should be fine + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 3, Chunk: []byte{3, 1, 3}}) + require.NoError(t, err) + assert.True(t, added) + + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 2, Chunk: []byte{3, 1, 2}}) + require.NoError(t, err) + assert.True(t, added) + + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{3, 1, 1}}) + require.NoError(t, err) + assert.True(t, added) + + // At this point, we should be able to retrieve them all via Next + for i := 0; i < 5; i++ { + c, err := queue.Next() + require.NoError(t, err) + assert.Equal(t, &chunk{Height: 3, Format: 1, Index: uint32(i), Chunk: []byte{3, 1, byte(i)}}, c) + } + _, err = queue.Next() + require.Error(t, err) + assert.Equal(t, errDone, err) + + // It should still be possible to try to add chunks (which will be ignored) + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}) + require.NoError(t, err) + assert.False(t, added) + + // After closing the queue it will also return false + err = queue.Close() + require.NoError(t, err) + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}) + require.NoError(t, err) + assert.False(t, added) + + // Closing the queue again should also be fine + err = queue.Close() + require.NoError(t, err) +} + +func TestChunkQueue_Add_ChunkErrors(t *testing.T) { + testcases := map[string]struct { + chunk *chunk + }{ + "nil chunk": {nil}, + "nil body": {&chunk{Height: 3, Format: 1, Index: 0, Chunk: nil}}, + "wrong height": {&chunk{Height: 9, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}}, + "wrong format": {&chunk{Height: 3, Format: 9, Index: 0, Chunk: []byte{3, 1, 0}}}, + "invalid index": {&chunk{Height: 3, Format: 1, Index: 5, Chunk: []byte{3, 1, 0}}}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + _, err := queue.Add(tc.chunk) + require.Error(t, err) + }) + } +} + +func TestChunkQueue_Allocate(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + for i := uint32(0); i < queue.Size(); i++ { + index, err := queue.Allocate() + require.NoError(t, err) + assert.EqualValues(t, i, index) + } + + _, err := queue.Allocate() + require.Error(t, err) + assert.Equal(t, errDone, err) + + for i := uint32(0); i < queue.Size(); i++ { + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: i, Chunk: []byte{byte(i)}}) + require.NoError(t, err) + } + + // After all chunks have been allocated and retrieved, discarding a chunk will reallocate it. + err = queue.Discard(2) + require.NoError(t, err) + + index, err := queue.Allocate() + require.NoError(t, err) + assert.EqualValues(t, 2, index) + _, err = queue.Allocate() + require.Error(t, err) + assert.Equal(t, errDone, err) + + // Discarding a chunk the closing the queue will return errDone. + err = queue.Discard(2) + require.NoError(t, err) + err = queue.Close() + require.NoError(t, err) + _, err = queue.Allocate() + require.Error(t, err) + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_Discard(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Add a few chunks to the queue and fetch a couple + _, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{byte(0)}}) + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{byte(1)}}) + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 2, Chunk: []byte{byte(2)}}) + require.NoError(t, err) + + c, err := queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 0, c.Index) + c, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 1, c.Index) + + // Discarding the first chunk and re-adding it should cause it to be returned + // immediately by Next(), before procceeding with chunk 2 + err = queue.Discard(0) + require.NoError(t, err) + added, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{byte(0)}}) + require.NoError(t, err) + assert.True(t, added) + c, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 0, c.Index) + c, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 2, c.Index) + + // Discard then allocate, add and fetch all chunks + for i := uint32(0); i < queue.Size(); i++ { + err := queue.Discard(i) + require.NoError(t, err) + } + for i := uint32(0); i < queue.Size(); i++ { + _, err := queue.Allocate() + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: i, Chunk: []byte{byte(i)}}) + require.NoError(t, err) + c, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, i, c.Index) + } + + // Discarding a non-existent chunk does nothing. + err = queue.Discard(99) + require.NoError(t, err) + + // When discard a couple of chunks, we should be able to allocate, add, and fetch them again. + err = queue.Discard(3) + require.NoError(t, err) + err = queue.Discard(1) + require.NoError(t, err) + + index, err := queue.Allocate() + require.NoError(t, err) + assert.EqualValues(t, 1, index) + index, err = queue.Allocate() + require.NoError(t, err) + assert.EqualValues(t, 3, index) + + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 3, Chunk: []byte{3}}) + require.NoError(t, err) + assert.True(t, added) + added, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{1}}) + require.NoError(t, err) + assert.True(t, added) + + chunk, err := queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 1, chunk.Index) + + chunk, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 3, chunk.Index) + + _, err = queue.Next() + require.Error(t, err) + assert.Equal(t, errDone, err) + + // After closing the queue, discarding does nothing + err = queue.Close() + require.NoError(t, err) + err = queue.Discard(2) + require.NoError(t, err) +} + +func TestChunkQueue_DiscardSender(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Allocate and add all chunks to the queue + senders := []p2p.ID{"a", "b", "c"} + for i := uint32(0); i < queue.Size(); i++ { + _, err := queue.Allocate() + require.NoError(t, err) + _, err = queue.Add(&chunk{ + Height: 3, + Format: 1, + Index: i, + Chunk: []byte{byte(i)}, + Sender: senders[int(i)%len(senders)], + }) + require.NoError(t, err) + } + + // Fetch the first three chunks + for i := uint32(0); i < 3; i++ { + _, err := queue.Next() + require.NoError(t, err) + } + + // Discarding an unknown sender should do nothing + err := queue.DiscardSender("x") + require.NoError(t, err) + _, err = queue.Allocate() + assert.Equal(t, errDone, err) + + // Discarding sender b should discard chunk 4, but not chunk 1 which has already been + // returned. + err = queue.DiscardSender("b") + require.NoError(t, err) + index, err := queue.Allocate() + require.NoError(t, err) + assert.EqualValues(t, 4, index) + _, err = queue.Allocate() + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_GetSender(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + _, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{1}, Sender: p2p.ID("a")}) + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{2}, Sender: p2p.ID("b")}) + require.NoError(t, err) + + assert.EqualValues(t, "a", queue.GetSender(0)) + assert.EqualValues(t, "b", queue.GetSender(1)) + assert.EqualValues(t, "", queue.GetSender(2)) + + // After the chunk has been processed, we should still know who the sender was + chunk, err := queue.Next() + require.NoError(t, err) + require.NotNil(t, chunk) + require.EqualValues(t, 0, chunk.Index) + assert.EqualValues(t, "a", queue.GetSender(0)) +} + +func TestChunkQueue_Next(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Next should block waiting for the next chunks, even when given out of order. + chNext := make(chan *chunk, 10) + go func() { + for { + c, err := queue.Next() + if err == errDone { + close(chNext) + break + } + require.NoError(t, err) + chNext <- c + } + }() + + assert.Empty(t, chNext) + _, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{3, 1, 1}, Sender: p2p.ID("b")}) + require.NoError(t, err) + select { + case <-chNext: + assert.Fail(t, "channel should be empty") + default: + } + + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}, Sender: p2p.ID("a")}) + require.NoError(t, err) + + assert.Equal(t, + &chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}, Sender: p2p.ID("a")}, + <-chNext) + assert.Equal(t, + &chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{3, 1, 1}, Sender: p2p.ID("b")}, + <-chNext) + + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 4, Chunk: []byte{3, 1, 4}, Sender: p2p.ID("e")}) + require.NoError(t, err) + select { + case <-chNext: + assert.Fail(t, "channel should be empty") + default: + } + + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 2, Chunk: []byte{3, 1, 2}, Sender: p2p.ID("c")}) + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 3, Chunk: []byte{3, 1, 3}, Sender: p2p.ID("d")}) + require.NoError(t, err) + + assert.Equal(t, + &chunk{Height: 3, Format: 1, Index: 2, Chunk: []byte{3, 1, 2}, Sender: p2p.ID("c")}, + <-chNext) + assert.Equal(t, + &chunk{Height: 3, Format: 1, Index: 3, Chunk: []byte{3, 1, 3}, Sender: p2p.ID("d")}, + <-chNext) + assert.Equal(t, + &chunk{Height: 3, Format: 1, Index: 4, Chunk: []byte{3, 1, 4}, Sender: p2p.ID("e")}, + <-chNext) + + _, ok := <-chNext + assert.False(t, ok, "channel should be closed") + + // Calling next on a finished queue should return done + _, err = queue.Next() + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_Next_Closed(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Calling Next on a closed queue should return done + _, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{3, 1, 1}}) + require.NoError(t, err) + err = queue.Close() + require.NoError(t, err) + + _, err = queue.Next() + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_Retry(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Allocate and add all chunks to the queue + for i := uint32(0); i < queue.Size(); i++ { + _, err := queue.Allocate() + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: i, Chunk: []byte{byte(i)}}) + require.NoError(t, err) + _, err = queue.Next() + require.NoError(t, err) + } + + // Retrying a couple of chunks makes Next() return them, but they are not allocatable + queue.Retry(3) + queue.Retry(1) + + _, err := queue.Allocate() + assert.Equal(t, errDone, err) + + chunk, err := queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 1, chunk.Index) + + chunk, err = queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 3, chunk.Index) + + _, err = queue.Next() + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_RetryAll(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + // Allocate and add all chunks to the queue + for i := uint32(0); i < queue.Size(); i++ { + _, err := queue.Allocate() + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: i, Chunk: []byte{byte(i)}}) + require.NoError(t, err) + _, err = queue.Next() + require.NoError(t, err) + } + + _, err := queue.Next() + assert.Equal(t, errDone, err) + + queue.RetryAll() + + _, err = queue.Allocate() + assert.Equal(t, errDone, err) + + for i := uint32(0); i < queue.Size(); i++ { + chunk, err := queue.Next() + require.NoError(t, err) + assert.EqualValues(t, i, chunk.Index) + } + + _, err = queue.Next() + assert.Equal(t, errDone, err) +} + +func TestChunkQueue_Size(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + assert.EqualValues(t, 5, queue.Size()) + + err := queue.Close() + require.NoError(t, err) + assert.EqualValues(t, 0, queue.Size()) +} + +func TestChunkQueue_WaitFor(t *testing.T) { + queue, teardown := setupChunkQueue(t) + defer teardown() + + waitFor1 := queue.WaitFor(1) + waitFor4 := queue.WaitFor(4) + + // Adding 0 and 2 should not trigger waiters + _, err := queue.Add(&chunk{Height: 3, Format: 1, Index: 0, Chunk: []byte{3, 1, 0}}) + require.NoError(t, err) + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 2, Chunk: []byte{3, 1, 2}}) + require.NoError(t, err) + select { + case <-waitFor1: + require.Fail(t, "WaitFor(1) should not trigger on 0 or 2") + case <-waitFor4: + require.Fail(t, "WaitFor(4) should not trigger on 0 or 2") + default: + } + + // Adding 1 should trigger WaitFor(1), but not WaitFor(4). The channel should be closed. + _, err = queue.Add(&chunk{Height: 3, Format: 1, Index: 1, Chunk: []byte{3, 1, 1}}) + require.NoError(t, err) + assert.EqualValues(t, 1, <-waitFor1) + _, ok := <-waitFor1 + assert.False(t, ok) + select { + case <-waitFor4: + require.Fail(t, "WaitFor(4) should not trigger on 0 or 2") + default: + } + + // Fetch the first chunk. At this point, waiting for either 0 (retrieved from pool) or 1 + // (queued in pool) should immediately return true. + c, err := queue.Next() + require.NoError(t, err) + assert.EqualValues(t, 0, c.Index) + + w := queue.WaitFor(0) + assert.EqualValues(t, 0, <-w) + _, ok = <-w + assert.False(t, ok) + + w = queue.WaitFor(1) + assert.EqualValues(t, 1, <-w) + _, ok = <-w + assert.False(t, ok) + + // Close the queue. This should cause the waiter for 4 to close, and also cause any future + // waiters to get closed channels. + err = queue.Close() + require.NoError(t, err) + _, ok = <-waitFor4 + assert.False(t, ok) + + w = queue.WaitFor(3) + _, ok = <-w + assert.False(t, ok) +} diff --git a/statesync/messages.go b/statesync/messages.go new file mode 100644 index 0000000..94c0f68 --- /dev/null +++ b/statesync/messages.go @@ -0,0 +1,61 @@ +package statesync + +import ( + "errors" + "fmt" + + "github.com/cosmos/gogoproto/proto" + + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" +) + +const ( + // snapshotMsgSize is the maximum size of a snapshotResponseMessage + snapshotMsgSize = int(4e6) + // chunkMsgSize is the maximum size of a chunkResponseMessage + chunkMsgSize = int(16e6) +) + +var ( + ErrExceedsMaxSnapshotChunks = errors.New("amount of chunks in the snapshot exceeds the maximum allowed number of chunks") +) + +// validateMsg validates a message. +func validateMsg(pb proto.Message, maxSnapshotChunks uint32) error { + if pb == nil { + return errors.New("message cannot be nil") + } + switch msg := pb.(type) { + case *ssproto.ChunkRequest: + if msg.Height == 0 { + return errors.New("height cannot be 0") + } + case *ssproto.ChunkResponse: + if msg.Height == 0 { + return errors.New("height cannot be 0") + } + if msg.Missing && len(msg.Chunk) > 0 { + return errors.New("missing chunk cannot have contents") + } + if !msg.Missing && msg.Chunk == nil { + return errors.New("chunk cannot be nil") + } + case *ssproto.SnapshotsRequest: + case *ssproto.SnapshotsResponse: + if msg.Height == 0 { + return errors.New("height cannot be 0") + } + if len(msg.Hash) == 0 { + return errors.New("snapshot has no hash") + } + if msg.Chunks == 0 { + return errors.New("snapshot has no chunks") + } + if msg.Chunks > maxSnapshotChunks { + return fmt.Errorf("%w: snapshot response chunk count: %d, maximum chunks: %d", ErrExceedsMaxSnapshotChunks, msg.Chunks, maxSnapshotChunks) + } + default: + return fmt.Errorf("unknown message type %T", msg) + } + return nil +} diff --git a/statesync/messages_test.go b/statesync/messages_test.go new file mode 100644 index 0000000..a1ea7a2 --- /dev/null +++ b/statesync/messages_test.go @@ -0,0 +1,112 @@ +package statesync + +import ( + "encoding/hex" + "testing" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/p2p" + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +func TestValidateMsg(t *testing.T) { + testcases := map[string]struct { + msg proto.Message + valid bool + }{ + "nil": {nil, false}, + "unrelated": {&cmtproto.Block{}, false}, + + "ChunkRequest valid": {&ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, true}, + "ChunkRequest 0 height": {&ssproto.ChunkRequest{Height: 0, Format: 1, Index: 1}, false}, + "ChunkRequest 0 format": {&ssproto.ChunkRequest{Height: 1, Format: 0, Index: 1}, true}, + "ChunkRequest 0 chunk": {&ssproto.ChunkRequest{Height: 1, Format: 1, Index: 0}, true}, + + "ChunkResponse valid": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}}, + true}, + "ChunkResponse 0 height": { + &ssproto.ChunkResponse{Height: 0, Format: 1, Index: 1, Chunk: []byte{1}}, + false}, + "ChunkResponse 0 format": { + &ssproto.ChunkResponse{Height: 1, Format: 0, Index: 1, Chunk: []byte{1}}, + true}, + "ChunkResponse 0 chunk": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 0, Chunk: []byte{1}}, + true}, + "ChunkResponse empty body": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{}}, + true}, + "ChunkResponse nil body": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: nil}, + false}, + "ChunkResponse missing": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true}, + true}, + "ChunkResponse missing with empty": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true, Chunk: []byte{}}, + true}, + "ChunkResponse missing with body": { + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true, Chunk: []byte{1}}, + false}, + + "SnapshotsRequest valid": {&ssproto.SnapshotsRequest{}, true}, + + "SnapshotsResponse valid": { + &ssproto.SnapshotsResponse{Height: 1, Format: 1, Chunks: 2, Hash: []byte{1}}, + true}, + "SnapshotsResponse 0 height": { + &ssproto.SnapshotsResponse{Height: 0, Format: 1, Chunks: 2, Hash: []byte{1}}, + false}, + "SnapshotsResponse 0 format": { + &ssproto.SnapshotsResponse{Height: 1, Format: 0, Chunks: 2, Hash: []byte{1}}, + true}, + "SnapshotsResponse 0 chunks": { + &ssproto.SnapshotsResponse{Height: 1, Format: 1, Hash: []byte{1}}, + false}, + "SnapshotsResponse no hash": { + &ssproto.SnapshotsResponse{Height: 1, Format: 1, Chunks: 2, Hash: []byte{}}, + false}, + "SnapshotsResponse exceeds max chunks": { + &ssproto.SnapshotsResponse{Height: 1, Format: 1, Chunks: 100001, Hash: []byte{1}}, + false}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + err := validateMsg(tc.msg, 100000) + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} + +//nolint:lll // ignore line length +func TestStateSyncVectors(t *testing.T) { + + testCases := []struct { + testName string + msg proto.Message + expBytes string + }{ + {"SnapshotsRequest", &ssproto.SnapshotsRequest{}, "0a00"}, + {"SnapshotsResponse", &ssproto.SnapshotsResponse{Height: 1, Format: 2, Chunks: 3, Hash: []byte("chuck hash"), Metadata: []byte("snapshot metadata")}, "1225080110021803220a636875636b20686173682a11736e617073686f74206d65746164617461"}, + {"ChunkRequest", &ssproto.ChunkRequest{Height: 1, Format: 2, Index: 3}, "1a06080110021803"}, + {"ChunkResponse", &ssproto.ChunkResponse{Height: 1, Format: 2, Index: 3, Chunk: []byte("it's a chunk")}, "2214080110021803220c697427732061206368756e6b"}, + } + + for _, tc := range testCases { + tc := tc + w := tc.msg.(p2p.Wrapper).Wrap() + bz, err := proto.Marshal(w) + require.NoError(t, err) + + require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) + } +} diff --git a/statesync/metrics.gen.go b/statesync/metrics.gen.go new file mode 100644 index 0000000..3ac428f --- /dev/null +++ b/statesync/metrics.gen.go @@ -0,0 +1,30 @@ +// Code generated by metricsgen. DO NOT EDIT. + +package statesync + +import ( + "github.com/go-kit/kit/metrics/discard" + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics { + labels := []string{} + for i := 0; i < len(labelsAndValues); i += 2 { + labels = append(labels, labelsAndValues[i]) + } + return &Metrics{ + Syncing: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: MetricsSubsystem, + Name: "syncing", + Help: "Whether or not a node is state syncing. 1 if yes, 0 if no.", + }, labels).With(labelsAndValues...), + } +} + +func NopMetrics() *Metrics { + return &Metrics{ + Syncing: discard.NewGauge(), + } +} diff --git a/statesync/metrics.go b/statesync/metrics.go new file mode 100644 index 0000000..6398035 --- /dev/null +++ b/statesync/metrics.go @@ -0,0 +1,19 @@ +package statesync + +import ( + "github.com/go-kit/kit/metrics" +) + +const ( + // MetricsSubsystem is a subsystem shared by all metrics exposed by this + // package. + MetricsSubsystem = "statesync" +) + +//go:generate go run ../scripts/metricsgen -struct=Metrics + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Whether or not a node is state syncing. 1 if yes, 0 if no. + Syncing metrics.Gauge +} diff --git a/statesync/mocks/state_provider.go b/statesync/mocks/state_provider.go new file mode 100644 index 0000000..1f648a5 --- /dev/null +++ b/statesync/mocks/state_provider.go @@ -0,0 +1,119 @@ +// Code generated by mockery v2.53.0. DO NOT EDIT. + +package mocks + +import ( + context "context" + + state "github.com/cometbft/cometbft/state" + mock "github.com/stretchr/testify/mock" + + types "github.com/cometbft/cometbft/types" +) + +// StateProvider is an autogenerated mock type for the StateProvider type +type StateProvider struct { + mock.Mock +} + +// AppHash provides a mock function with given fields: ctx, height +func (_m *StateProvider) AppHash(ctx context.Context, height uint64) ([]byte, error) { + ret := _m.Called(ctx, height) + + if len(ret) == 0 { + panic("no return value specified for AppHash") + } + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { + return rf(ctx, height) + } + if rf, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Commit provides a mock function with given fields: ctx, height +func (_m *StateProvider) Commit(ctx context.Context, height uint64) (*types.Commit, error) { + ret := _m.Called(ctx, height) + + if len(ret) == 0 { + panic("no return value specified for Commit") + } + + var r0 *types.Commit + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, uint64) (*types.Commit, error)); ok { + return rf(ctx, height) + } + if rf, ok := ret.Get(0).(func(context.Context, uint64) *types.Commit); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Commit) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// State provides a mock function with given fields: ctx, height +func (_m *StateProvider) State(ctx context.Context, height uint64) (state.State, error) { + ret := _m.Called(ctx, height) + + if len(ret) == 0 { + panic("no return value specified for State") + } + + var r0 state.State + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, uint64) (state.State, error)); ok { + return rf(ctx, height) + } + if rf, ok := ret.Get(0).(func(context.Context, uint64) state.State); ok { + r0 = rf(ctx, height) + } else { + r0 = ret.Get(0).(state.State) + } + + if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewStateProvider creates a new instance of StateProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStateProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *StateProvider { + mock := &StateProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/statesync/reactor.go b/statesync/reactor.go new file mode 100644 index 0000000..a2ec0e1 --- /dev/null +++ b/statesync/reactor.go @@ -0,0 +1,296 @@ +package statesync + +import ( + "context" + "errors" + "sort" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +const ( + // SnapshotChannel exchanges snapshot metadata + SnapshotChannel = byte(0x60) + // ChunkChannel exchanges chunk contents + ChunkChannel = byte(0x61) + // recentSnapshots is the number of recent snapshots to send and receive per peer. + recentSnapshots = 10 +) + +// Reactor handles state sync, both restoring snapshots for the local node and serving snapshots +// for other nodes. +type Reactor struct { + p2p.BaseReactor + + cfg config.StateSyncConfig + conn proxy.AppConnSnapshot + connQuery proxy.AppConnQuery + tempDir string + metrics *Metrics + + // This will only be set when a state sync is in progress. It is used to feed received + // snapshots and chunks into the sync. + mtx cmtsync.RWMutex + syncer *syncer +} + +// NewReactor creates a new state sync reactor. +func NewReactor( + cfg config.StateSyncConfig, + conn proxy.AppConnSnapshot, + connQuery proxy.AppConnQuery, + metrics *Metrics, +) *Reactor { + r := &Reactor{ + cfg: cfg, + conn: conn, + connQuery: connQuery, + metrics: metrics, + } + r.BaseReactor = *p2p.NewBaseReactor("StateSync", r) + + return r +} + +// GetChannels implements p2p.Reactor. +func (r *Reactor) GetChannels() []*p2p.ChannelDescriptor { + return []*p2p.ChannelDescriptor{ + { + ID: SnapshotChannel, + Priority: 5, + SendQueueCapacity: 10, + RecvMessageCapacity: snapshotMsgSize, + MessageType: &ssproto.Message{}, + }, + { + ID: ChunkChannel, + Priority: 3, + SendQueueCapacity: 10, + RecvMessageCapacity: chunkMsgSize, + MessageType: &ssproto.Message{}, + }, + } +} + +// OnStart implements p2p.Reactor. +func (r *Reactor) OnStart() error { + return nil +} + +// AddPeer implements p2p.Reactor. +func (r *Reactor) AddPeer(peer p2p.Peer) { + r.mtx.RLock() + defer r.mtx.RUnlock() + if r.syncer != nil { + r.syncer.AddPeer(peer) + } +} + +// RemovePeer implements p2p.Reactor. +func (r *Reactor) RemovePeer(peer p2p.Peer, _ interface{}) { + r.mtx.RLock() + defer r.mtx.RUnlock() + if r.syncer != nil { + r.syncer.RemovePeer(peer) + } +} + +// Receive implements p2p.Reactor. +func (r *Reactor) Receive(e p2p.Envelope) { + if !r.IsRunning() { + return + } + + err := validateMsg(e.Message, r.cfg.MaxSnapshotChunks) + if err != nil { + if errors.Is(err, ErrExceedsMaxSnapshotChunks) { + r.syncer.RejectPeer(e.Src) + } + r.Logger.Error("Invalid message", "peer", e.Src, "msg", e.Message, "err", err) + r.Switch.StopPeerForError(e.Src, err) + return + } + + switch e.ChannelID { + case SnapshotChannel: + switch msg := e.Message.(type) { + case *ssproto.SnapshotsRequest: + snapshots, err := r.recentSnapshots(recentSnapshots) + if err != nil { + r.Logger.Error("Failed to fetch snapshots", "err", err) + return + } + for _, snapshot := range snapshots { + r.Logger.Debug("Advertising snapshot", "height", snapshot.Height, + "format", snapshot.Format, "peer", e.Src.ID()) + e.Src.Send(p2p.Envelope{ + ChannelID: e.ChannelID, + Message: &ssproto.SnapshotsResponse{ + Height: snapshot.Height, + Format: snapshot.Format, + Chunks: snapshot.Chunks, + Hash: snapshot.Hash, + Metadata: snapshot.Metadata, + }, + }) + } + + case *ssproto.SnapshotsResponse: + r.mtx.RLock() + defer r.mtx.RUnlock() + if r.syncer == nil { + r.Logger.Debug("Received unexpected snapshot, no state sync in progress") + return + } + r.Logger.Debug("Received snapshot", "height", msg.Height, "format", msg.Format, "peer", e.Src.ID()) + _, err := r.syncer.AddSnapshot(e.Src, &snapshot{ + Height: msg.Height, + Format: msg.Format, + Chunks: msg.Chunks, + Hash: msg.Hash, + Metadata: msg.Metadata, + }) + // TODO: We may want to consider punishing the peer for certain errors + if err != nil { + r.Logger.Error("Failed to add snapshot", "height", msg.Height, "format", msg.Format, + "peer", e.Src.ID(), "err", err) + return + } + + default: + r.Logger.Error("Received unknown message %T", msg) + } + + case ChunkChannel: + switch msg := e.Message.(type) { + case *ssproto.ChunkRequest: + r.Logger.Debug("Received chunk request", "height", msg.Height, "format", msg.Format, + "chunk", msg.Index, "peer", e.Src.ID()) + resp, err := r.conn.LoadSnapshotChunk(context.TODO(), &abci.RequestLoadSnapshotChunk{ + Height: msg.Height, + Format: msg.Format, + Chunk: msg.Index, + }) + if err != nil { + r.Logger.Error("Failed to load chunk", "height", msg.Height, "format", msg.Format, + "chunk", msg.Index, "err", err) + return + } + r.Logger.Debug("Sending chunk", "height", msg.Height, "format", msg.Format, + "chunk", msg.Index, "peer", e.Src.ID()) + e.Src.Send(p2p.Envelope{ + ChannelID: ChunkChannel, + Message: &ssproto.ChunkResponse{ + Height: msg.Height, + Format: msg.Format, + Index: msg.Index, + Chunk: resp.Chunk, + Missing: resp.Chunk == nil, + }, + }) + + case *ssproto.ChunkResponse: + r.mtx.RLock() + defer r.mtx.RUnlock() + if r.syncer == nil { + r.Logger.Debug("Received unexpected chunk, no state sync in progress", "peer", e.Src.ID()) + return + } + r.Logger.Debug("Received chunk, adding to sync", "height", msg.Height, "format", msg.Format, + "chunk", msg.Index, "peer", e.Src.ID()) + _, err := r.syncer.AddChunk(&chunk{ + Height: msg.Height, + Format: msg.Format, + Index: msg.Index, + Chunk: msg.Chunk, + Sender: e.Src.ID(), + }) + if err != nil { + r.Logger.Error("Failed to add chunk", "height", msg.Height, "format", msg.Format, + "chunk", msg.Index, "err", err) + return + } + + default: + r.Logger.Error("Received unknown message %T", msg) + } + + default: + r.Logger.Error("Received message on invalid channel %x", e.ChannelID) + } +} + +// recentSnapshots fetches the n most recent snapshots from the app +func (r *Reactor) recentSnapshots(n uint32) ([]*snapshot, error) { + resp, err := r.conn.ListSnapshots(context.TODO(), &abci.RequestListSnapshots{}) + if err != nil { + return nil, err + } + sort.Slice(resp.Snapshots, func(i, j int) bool { + a := resp.Snapshots[i] + b := resp.Snapshots[j] + switch { + case a.Height > b.Height: + return true + case a.Height == b.Height && a.Format > b.Format: + return true + default: + return false + } + }) + snapshots := make([]*snapshot, 0, n) + for i, s := range resp.Snapshots { + if i >= recentSnapshots { + break + } + snapshots = append(snapshots, &snapshot{ + Height: s.Height, + Format: s.Format, + Chunks: s.Chunks, + Hash: s.Hash, + Metadata: s.Metadata, + }) + } + return snapshots, nil +} + +// Sync runs a state sync, returning the new state and last commit at the snapshot height. +// The caller must store the state and commit in the state database and block store. +func (r *Reactor) Sync(stateProvider StateProvider, discoveryTime time.Duration) (sm.State, *types.Commit, error) { + r.mtx.Lock() + if r.syncer != nil { + r.mtx.Unlock() + return sm.State{}, nil, errors.New("a state sync is already in progress") + } + r.metrics.Syncing.Set(1) + r.syncer = newSyncer(r.cfg, r.Logger, r.conn, r.connQuery, stateProvider, r.tempDir) + r.mtx.Unlock() + + hook := func() { + r.Logger.Debug("Requesting snapshots from known peers") + // Request snapshots from all currently connected peers + + r.Switch.Broadcast(p2p.Envelope{ + ChannelID: SnapshotChannel, + Message: &ssproto.SnapshotsRequest{}, + }) + } + + hook() + + state, commit, err := r.syncer.SyncAny(discoveryTime, hook) + + r.mtx.Lock() + r.syncer = nil + r.metrics.Syncing.Set(0) + r.mtx.Unlock() + return state, commit, err +} diff --git a/statesync/reactor_test.go b/statesync/reactor_test.go new file mode 100644 index 0000000..af24d75 --- /dev/null +++ b/statesync/reactor_test.go @@ -0,0 +1,187 @@ +package statesync + +import ( + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/p2p" + p2pmocks "github.com/cometbft/cometbft/p2p/mocks" + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" + proxymocks "github.com/cometbft/cometbft/proxy/mocks" +) + +func TestReactor_Receive_ChunkRequest(t *testing.T) { + testcases := map[string]struct { + request *ssproto.ChunkRequest + chunk []byte + expectResponse *ssproto.ChunkResponse + }{ + "chunk is returned": { + &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, + []byte{1, 2, 3}, + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 2, 3}}, + }, + "empty chunk is returned, as nil": { + &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, + []byte{}, + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: nil}, + }, + "nil (missing) chunk is returned as missing": { + &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, + nil, + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true}, + }, + } + + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + // Mock ABCI connection to return local snapshots + conn := &proxymocks.AppConnSnapshot{} + conn.On("LoadSnapshotChunk", mock.Anything, &abci.RequestLoadSnapshotChunk{ + Height: tc.request.Height, + Format: tc.request.Format, + Chunk: tc.request.Index, + }).Return(&abci.ResponseLoadSnapshotChunk{Chunk: tc.chunk}, nil) + + // Mock peer to store response, if found + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID("id")) + var response *ssproto.ChunkResponse + if tc.expectResponse != nil { + peer.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + return ok && e.ChannelID == ChunkChannel + })).Run(func(args mock.Arguments) { + e := args[0].(p2p.Envelope) + + // Marshal to simulate a wire roundtrip. + bz, err := proto.Marshal(e.Message) + require.NoError(t, err) + err = proto.Unmarshal(bz, e.Message) + require.NoError(t, err) + response = e.Message.(*ssproto.ChunkResponse) + }).Return(true) + } + + // Start a reactor and send a ssproto.ChunkRequest, then wait for and check response + cfg := config.DefaultStateSyncConfig() + r := NewReactor(*cfg, conn, nil, NopMetrics()) + err := r.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := r.Stop(); err != nil { + t.Error(err) + } + }) + + r.Receive(p2p.Envelope{ + ChannelID: ChunkChannel, + Src: peer, + Message: tc.request, + }) + time.Sleep(100 * time.Millisecond) + assert.Equal(t, tc.expectResponse, response) + + conn.AssertExpectations(t) + peer.AssertExpectations(t) + }) + } +} + +func TestReactor_Receive_SnapshotsRequest(t *testing.T) { + testcases := map[string]struct { + snapshots []*abci.Snapshot + expectResponses []*ssproto.SnapshotsResponse + }{ + "no snapshots": {nil, []*ssproto.SnapshotsResponse{}}, + ">10 unordered snapshots": { + []*abci.Snapshot{ + {Height: 1, Format: 2, Chunks: 7, Hash: []byte{1, 2}, Metadata: []byte{1}}, + {Height: 2, Format: 2, Chunks: 7, Hash: []byte{2, 2}, Metadata: []byte{2}}, + {Height: 3, Format: 2, Chunks: 7, Hash: []byte{3, 2}, Metadata: []byte{3}}, + {Height: 1, Format: 1, Chunks: 7, Hash: []byte{1, 1}, Metadata: []byte{4}}, + {Height: 2, Format: 1, Chunks: 7, Hash: []byte{2, 1}, Metadata: []byte{5}}, + {Height: 3, Format: 1, Chunks: 7, Hash: []byte{3, 1}, Metadata: []byte{6}}, + {Height: 1, Format: 4, Chunks: 7, Hash: []byte{1, 4}, Metadata: []byte{7}}, + {Height: 2, Format: 4, Chunks: 7, Hash: []byte{2, 4}, Metadata: []byte{8}}, + {Height: 3, Format: 4, Chunks: 7, Hash: []byte{3, 4}, Metadata: []byte{9}}, + {Height: 1, Format: 3, Chunks: 7, Hash: []byte{1, 3}, Metadata: []byte{10}}, + {Height: 2, Format: 3, Chunks: 7, Hash: []byte{2, 3}, Metadata: []byte{11}}, + {Height: 3, Format: 3, Chunks: 7, Hash: []byte{3, 3}, Metadata: []byte{12}}, + }, + []*ssproto.SnapshotsResponse{ + {Height: 3, Format: 4, Chunks: 7, Hash: []byte{3, 4}, Metadata: []byte{9}}, + {Height: 3, Format: 3, Chunks: 7, Hash: []byte{3, 3}, Metadata: []byte{12}}, + {Height: 3, Format: 2, Chunks: 7, Hash: []byte{3, 2}, Metadata: []byte{3}}, + {Height: 3, Format: 1, Chunks: 7, Hash: []byte{3, 1}, Metadata: []byte{6}}, + {Height: 2, Format: 4, Chunks: 7, Hash: []byte{2, 4}, Metadata: []byte{8}}, + {Height: 2, Format: 3, Chunks: 7, Hash: []byte{2, 3}, Metadata: []byte{11}}, + {Height: 2, Format: 2, Chunks: 7, Hash: []byte{2, 2}, Metadata: []byte{2}}, + {Height: 2, Format: 1, Chunks: 7, Hash: []byte{2, 1}, Metadata: []byte{5}}, + {Height: 1, Format: 4, Chunks: 7, Hash: []byte{1, 4}, Metadata: []byte{7}}, + {Height: 1, Format: 3, Chunks: 7, Hash: []byte{1, 3}, Metadata: []byte{10}}, + }, + }, + } + + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + // Mock ABCI connection to return local snapshots + conn := &proxymocks.AppConnSnapshot{} + conn.On("ListSnapshots", mock.Anything, &abci.RequestListSnapshots{}).Return(&abci.ResponseListSnapshots{ + Snapshots: tc.snapshots, + }, nil) + + // Mock peer to catch responses and store them in a slice + responses := []*ssproto.SnapshotsResponse{} + peer := &p2pmocks.Peer{} + if len(tc.expectResponses) > 0 { + peer.On("ID").Return(p2p.ID("id")) + peer.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + return ok && e.ChannelID == SnapshotChannel + })).Run(func(args mock.Arguments) { + e := args[0].(p2p.Envelope) + + // Marshal to simulate a wire roundtrip. + bz, err := proto.Marshal(e.Message) + require.NoError(t, err) + err = proto.Unmarshal(bz, e.Message) + require.NoError(t, err) + responses = append(responses, e.Message.(*ssproto.SnapshotsResponse)) + }).Return(true) + } + + // Start a reactor and send a SnapshotsRequestMessage, then wait for and check responses + cfg := config.DefaultStateSyncConfig() + r := NewReactor(*cfg, conn, nil, NopMetrics()) + err := r.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := r.Stop(); err != nil { + t.Error(err) + } + }) + + r.Receive(p2p.Envelope{ + ChannelID: SnapshotChannel, + Src: peer, + Message: &ssproto.SnapshotsRequest{}, + }) + time.Sleep(100 * time.Millisecond) + assert.Equal(t, tc.expectResponses, responses) + + conn.AssertExpectations(t) + peer.AssertExpectations(t) + }) + } +} diff --git a/statesync/snapshots.go b/statesync/snapshots.go new file mode 100644 index 0000000..f0e3c79 --- /dev/null +++ b/statesync/snapshots.go @@ -0,0 +1,255 @@ +package statesync + +import ( + "crypto/sha256" + "fmt" + "math/rand" + "sort" + + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" +) + +// snapshotKey is a snapshot key used for lookups. +type snapshotKey [sha256.Size]byte + +// snapshot contains data about a snapshot. +type snapshot struct { + Height uint64 + Format uint32 + Chunks uint32 + Hash []byte + Metadata []byte + + trustedAppHash []byte // populated by light client +} + +// Key generates a snapshot key, used for lookups. It takes into account not only the height and +// format, but also the chunks, hash, and metadata in case peers have generated snapshots in a +// non-deterministic manner. All fields must be equal for the snapshot to be considered the same. +func (s *snapshot) Key() snapshotKey { + // Hash.Write() never returns an error. + hasher := sha256.New() + fmt.Fprintf(hasher, "%v:%v:%v", s.Height, s.Format, s.Chunks) + hasher.Write(s.Hash) + hasher.Write(s.Metadata) + var key snapshotKey + copy(key[:], hasher.Sum(nil)) + return key +} + +// snapshotPool discovers and aggregates snapshots across peers. +type snapshotPool struct { + cmtsync.Mutex + snapshots map[snapshotKey]*snapshot + snapshotPeers map[snapshotKey]map[p2p.ID]p2p.Peer + + // indexes for fast searches + formatIndex map[uint32]map[snapshotKey]bool + heightIndex map[uint64]map[snapshotKey]bool + peerIndex map[p2p.ID]map[snapshotKey]bool + + // blacklists for rejected items + formatBlacklist map[uint32]bool + peerBlacklist map[p2p.ID]bool + snapshotBlacklist map[snapshotKey]bool +} + +// newSnapshotPool creates a new snapshot pool. The state source is used for +func newSnapshotPool() *snapshotPool { + return &snapshotPool{ + snapshots: make(map[snapshotKey]*snapshot), + snapshotPeers: make(map[snapshotKey]map[p2p.ID]p2p.Peer), + formatIndex: make(map[uint32]map[snapshotKey]bool), + heightIndex: make(map[uint64]map[snapshotKey]bool), + peerIndex: make(map[p2p.ID]map[snapshotKey]bool), + formatBlacklist: make(map[uint32]bool), + peerBlacklist: make(map[p2p.ID]bool), + snapshotBlacklist: make(map[snapshotKey]bool), + } +} + +// Add adds a snapshot to the pool, unless the peer has already sent recentSnapshots snapshots. It +// returns true if this was a new, non-blacklisted snapshot. The snapshot height is verified using +// the light client, and the expected app hash is set for the snapshot. +func (p *snapshotPool) Add(peer p2p.Peer, snapshot *snapshot) (bool, error) { + key := snapshot.Key() + + p.Lock() + defer p.Unlock() + + switch { + case p.formatBlacklist[snapshot.Format]: + return false, nil + case p.peerBlacklist[peer.ID()]: + return false, nil + case p.snapshotBlacklist[key]: + return false, nil + case len(p.peerIndex[peer.ID()]) >= recentSnapshots: + return false, nil + } + + if p.snapshotPeers[key] == nil { + p.snapshotPeers[key] = make(map[p2p.ID]p2p.Peer) + } + p.snapshotPeers[key][peer.ID()] = peer + + if p.peerIndex[peer.ID()] == nil { + p.peerIndex[peer.ID()] = make(map[snapshotKey]bool) + } + p.peerIndex[peer.ID()][key] = true + + if p.snapshots[key] != nil { + return false, nil + } + p.snapshots[key] = snapshot + + if p.formatIndex[snapshot.Format] == nil { + p.formatIndex[snapshot.Format] = make(map[snapshotKey]bool) + } + p.formatIndex[snapshot.Format][key] = true + + if p.heightIndex[snapshot.Height] == nil { + p.heightIndex[snapshot.Height] = make(map[snapshotKey]bool) + } + p.heightIndex[snapshot.Height][key] = true + + return true, nil +} + +// Best returns the "best" currently known snapshot, if any. +func (p *snapshotPool) Best() *snapshot { + ranked := p.Ranked() + if len(ranked) == 0 { + return nil + } + return ranked[0] +} + +// GetPeer returns a random peer for a snapshot, if any. +func (p *snapshotPool) GetPeer(snapshot *snapshot) p2p.Peer { + peers := p.GetPeers(snapshot) + if len(peers) == 0 { + return nil + } + return peers[rand.Intn(len(peers))] //nolint:gosec // G404: Use of weak random number generator +} + +// GetPeers returns the peers for a snapshot. +func (p *snapshotPool) GetPeers(snapshot *snapshot) []p2p.Peer { + key := snapshot.Key() + p.Lock() + defer p.Unlock() + + peers := make([]p2p.Peer, 0, len(p.snapshotPeers[key])) + for _, peer := range p.snapshotPeers[key] { + peers = append(peers, peer) + } + // sort results, for testability (otherwise order is random, so tests randomly fail) + sort.Slice(peers, func(a int, b int) bool { + return peers[a].ID() < peers[b].ID() + }) + return peers +} + +// Ranked returns a list of snapshots ranked by preference. The current heuristic is very naïve, +// preferring the snapshot with the greatest height, then greatest format, then greatest number of +// peers. This can be improved quite a lot. +func (p *snapshotPool) Ranked() []*snapshot { + p.Lock() + defer p.Unlock() + + candidates := make([]*snapshot, 0, len(p.snapshots)) + for key := range p.snapshots { + candidates = append(candidates, p.snapshots[key]) + } + + sort.Slice(candidates, func(i, j int) bool { + a := candidates[i] + b := candidates[j] + + switch { + case a.Height > b.Height: + return true + case a.Height < b.Height: + return false + case a.Format > b.Format: + return true + case a.Format < b.Format: + return false + case len(p.snapshotPeers[a.Key()]) > len(p.snapshotPeers[b.Key()]): + return true + default: + return false + } + }) + + return candidates +} + +// Reject rejects a snapshot. Rejected snapshots will never be used again. +func (p *snapshotPool) Reject(snapshot *snapshot) { + key := snapshot.Key() + p.Lock() + defer p.Unlock() + + p.snapshotBlacklist[key] = true + p.removeSnapshot(key) +} + +// RejectFormat rejects a snapshot format. It will never be used again. +func (p *snapshotPool) RejectFormat(format uint32) { + p.Lock() + defer p.Unlock() + + p.formatBlacklist[format] = true + for key := range p.formatIndex[format] { + p.removeSnapshot(key) + } +} + +// RejectPeer rejects a peer. It will never be used again. +func (p *snapshotPool) RejectPeer(peerID p2p.ID) { + if peerID == "" { + return + } + p.Lock() + defer p.Unlock() + + p.removePeer(peerID) + p.peerBlacklist[peerID] = true +} + +// RemovePeer removes a peer from the pool, and any snapshots that no longer have peers. +func (p *snapshotPool) RemovePeer(peerID p2p.ID) { + p.Lock() + defer p.Unlock() + p.removePeer(peerID) +} + +// removePeer removes a peer. The caller must hold the mutex lock. +func (p *snapshotPool) removePeer(peerID p2p.ID) { + for key := range p.peerIndex[peerID] { + delete(p.snapshotPeers[key], peerID) + if len(p.snapshotPeers[key]) == 0 { + p.removeSnapshot(key) + } + } + delete(p.peerIndex, peerID) +} + +// removeSnapshot removes a snapshot. The caller must hold the mutex lock. +func (p *snapshotPool) removeSnapshot(key snapshotKey) { + snapshot := p.snapshots[key] + if snapshot == nil { + return + } + + delete(p.snapshots, key) + delete(p.formatIndex[snapshot.Format], key) + delete(p.heightIndex[snapshot.Height], key) + for peerID := range p.snapshotPeers[key] { + delete(p.peerIndex[peerID], key) + } + delete(p.snapshotPeers, key) +} diff --git a/statesync/snapshots_test.go b/statesync/snapshots_test.go new file mode 100644 index 0000000..36665ae --- /dev/null +++ b/statesync/snapshots_test.go @@ -0,0 +1,303 @@ +package statesync + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/p2p" + p2pmocks "github.com/cometbft/cometbft/p2p/mocks" +) + +func TestSnapshot_Key(t *testing.T) { + testcases := map[string]struct { + modify func(*snapshot) + }{ + "new height": {func(s *snapshot) { s.Height = 9 }}, + "new format": {func(s *snapshot) { s.Format = 9 }}, + "new chunk count": {func(s *snapshot) { s.Chunks = 9 }}, + "new hash": {func(s *snapshot) { s.Hash = []byte{9} }}, + "no metadata": {func(s *snapshot) { s.Metadata = nil }}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + s := snapshot{ + Height: 3, + Format: 1, + Chunks: 7, + Hash: []byte{1, 2, 3}, + Metadata: []byte{255}, + } + before := s.Key() + tc.modify(&s) + after := s.Key() + assert.NotEqual(t, before, after) + }) + } +} + +func TestSnapshotPool_Add(t *testing.T) { + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID("id")) + + // Adding to the pool should work + pool := newSnapshotPool() + added, err := pool.Add(peer, &snapshot{ + Height: 1, + Format: 1, + Chunks: 1, + Hash: []byte{1}, + }) + require.NoError(t, err) + assert.True(t, added) + + // Adding again from a different peer should return false + otherPeer := &p2pmocks.Peer{} + otherPeer.On("ID").Return(p2p.ID("other")) + added, err = pool.Add(peer, &snapshot{ + Height: 1, + Format: 1, + Chunks: 1, + Hash: []byte{1}, + }) + require.NoError(t, err) + assert.False(t, added) + + // The pool should have populated the snapshot with the trusted app hash + snapshot := pool.Best() + require.NotNil(t, snapshot) +} + +func TestSnapshotPool_GetPeer(t *testing.T) { + pool := newSnapshotPool() + + s := &snapshot{Height: 1, Format: 1, Chunks: 1, Hash: []byte{1}} + peerA := &p2pmocks.Peer{} + peerA.On("ID").Return(p2p.ID("a")) + peerB := &p2pmocks.Peer{} + peerB.On("ID").Return(p2p.ID("b")) + + _, err := pool.Add(peerA, s) + require.NoError(t, err) + _, err = pool.Add(peerB, s) + require.NoError(t, err) + _, err = pool.Add(peerA, &snapshot{Height: 2, Format: 1, Chunks: 1, Hash: []byte{1}}) + require.NoError(t, err) + + // GetPeer currently picks a random peer, so lets run it until we've seen both. + seenA := false + seenB := false + for !seenA || !seenB { + peer := pool.GetPeer(s) + switch peer.ID() { + case p2p.ID("a"): + seenA = true + case p2p.ID("b"): + seenB = true + } + } + + // GetPeer should return nil for an unknown snapshot + peer := pool.GetPeer(&snapshot{Height: 9, Format: 9}) + assert.Nil(t, peer) +} + +func TestSnapshotPool_GetPeers(t *testing.T) { + pool := newSnapshotPool() + + s := &snapshot{Height: 1, Format: 1, Chunks: 1, Hash: []byte{1}} + peerA := &p2pmocks.Peer{} + peerA.On("ID").Return(p2p.ID("a")) + peerB := &p2pmocks.Peer{} + peerB.On("ID").Return(p2p.ID("b")) + + _, err := pool.Add(peerA, s) + require.NoError(t, err) + _, err = pool.Add(peerB, s) + require.NoError(t, err) + _, err = pool.Add(peerA, &snapshot{Height: 2, Format: 1, Chunks: 1, Hash: []byte{2}}) + require.NoError(t, err) + + peers := pool.GetPeers(s) + assert.Len(t, peers, 2) + assert.EqualValues(t, "a", peers[0].ID()) + assert.EqualValues(t, "b", peers[1].ID()) +} + +func TestSnapshotPool_Ranked_Best(t *testing.T) { + pool := newSnapshotPool() + + // snapshots in expected order (best to worst). Highest height wins, then highest format. + // Snapshots with different chunk hashes are considered different, and the most peers is + // tie-breaker. + expectSnapshots := []struct { + snapshot *snapshot + peers []string + }{ + {&snapshot{Height: 2, Format: 2, Chunks: 4, Hash: []byte{1, 3}}, []string{"a", "b", "c"}}, + {&snapshot{Height: 2, Format: 2, Chunks: 5, Hash: []byte{1, 2}}, []string{"a"}}, + {&snapshot{Height: 2, Format: 1, Chunks: 3, Hash: []byte{1, 2}}, []string{"a", "b"}}, + {&snapshot{Height: 1, Format: 2, Chunks: 5, Hash: []byte{1, 2}}, []string{"a", "b"}}, + {&snapshot{Height: 1, Format: 1, Chunks: 4, Hash: []byte{1, 2}}, []string{"a", "b", "c"}}, + } + + // Add snapshots in reverse order, to make sure the pool enforces some order. + for i := len(expectSnapshots) - 1; i >= 0; i-- { + for _, peerID := range expectSnapshots[i].peers { + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID(peerID)) + _, err := pool.Add(peer, expectSnapshots[i].snapshot) + require.NoError(t, err) + } + } + + // Ranked should return the snapshots in the same order + ranked := pool.Ranked() + assert.Len(t, ranked, len(expectSnapshots)) + for i := range ranked { + assert.Equal(t, expectSnapshots[i].snapshot, ranked[i]) + } + + // Check that best snapshots are returned in expected order + for i := range expectSnapshots { + snapshot := expectSnapshots[i].snapshot + require.Equal(t, snapshot, pool.Best()) + pool.Reject(snapshot) + } + assert.Nil(t, pool.Best()) +} + +func TestSnapshotPool_Reject(t *testing.T) { + pool := newSnapshotPool() + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID("id")) + + snapshots := []*snapshot{ + {Height: 2, Format: 2, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 2, Format: 1, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 1, Format: 2, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 1, Format: 1, Chunks: 1, Hash: []byte{1, 2}}, + } + for _, s := range snapshots { + _, err := pool.Add(peer, s) + require.NoError(t, err) + } + + pool.Reject(snapshots[0]) + assert.Equal(t, snapshots[1:], pool.Ranked()) + + added, err := pool.Add(peer, snapshots[0]) + require.NoError(t, err) + assert.False(t, added) + + added, err = pool.Add(peer, &snapshot{Height: 3, Format: 3, Chunks: 1, Hash: []byte{1}}) + require.NoError(t, err) + assert.True(t, added) +} + +func TestSnapshotPool_RejectFormat(t *testing.T) { + pool := newSnapshotPool() + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID("id")) + + snapshots := []*snapshot{ + {Height: 2, Format: 2, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 2, Format: 1, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 1, Format: 2, Chunks: 1, Hash: []byte{1, 2}}, + {Height: 1, Format: 1, Chunks: 1, Hash: []byte{1, 2}}, + } + for _, s := range snapshots { + _, err := pool.Add(peer, s) + require.NoError(t, err) + } + + pool.RejectFormat(1) + assert.Equal(t, []*snapshot{snapshots[0], snapshots[2]}, pool.Ranked()) + + added, err := pool.Add(peer, &snapshot{Height: 3, Format: 1, Chunks: 1, Hash: []byte{1}}) + require.NoError(t, err) + assert.False(t, added) + assert.Equal(t, []*snapshot{snapshots[0], snapshots[2]}, pool.Ranked()) + + added, err = pool.Add(peer, &snapshot{Height: 3, Format: 3, Chunks: 1, Hash: []byte{1}}) + require.NoError(t, err) + assert.True(t, added) +} + +func TestSnapshotPool_RejectPeer(t *testing.T) { + pool := newSnapshotPool() + + peerA := &p2pmocks.Peer{} + peerA.On("ID").Return(p2p.ID("a")) + peerB := &p2pmocks.Peer{} + peerB.On("ID").Return(p2p.ID("b")) + + s1 := &snapshot{Height: 1, Format: 1, Chunks: 1, Hash: []byte{1}} + s2 := &snapshot{Height: 2, Format: 1, Chunks: 1, Hash: []byte{2}} + s3 := &snapshot{Height: 3, Format: 1, Chunks: 1, Hash: []byte{2}} + + _, err := pool.Add(peerA, s1) + require.NoError(t, err) + _, err = pool.Add(peerA, s2) + require.NoError(t, err) + + _, err = pool.Add(peerB, s2) + require.NoError(t, err) + _, err = pool.Add(peerB, s3) + require.NoError(t, err) + + pool.RejectPeer(peerA.ID()) + + assert.Empty(t, pool.GetPeers(s1)) + + peers2 := pool.GetPeers(s2) + assert.Len(t, peers2, 1) + assert.EqualValues(t, "b", peers2[0].ID()) + + peers3 := pool.GetPeers(s2) + assert.Len(t, peers3, 1) + assert.EqualValues(t, "b", peers3[0].ID()) + + // it should no longer be possible to add the peer back + _, err = pool.Add(peerA, s1) + require.NoError(t, err) + assert.Empty(t, pool.GetPeers(s1)) +} + +func TestSnapshotPool_RemovePeer(t *testing.T) { + pool := newSnapshotPool() + + peerA := &p2pmocks.Peer{} + peerA.On("ID").Return(p2p.ID("a")) + peerB := &p2pmocks.Peer{} + peerB.On("ID").Return(p2p.ID("b")) + + s1 := &snapshot{Height: 1, Format: 1, Chunks: 1, Hash: []byte{1}} + s2 := &snapshot{Height: 2, Format: 1, Chunks: 1, Hash: []byte{2}} + + _, err := pool.Add(peerA, s1) + require.NoError(t, err) + _, err = pool.Add(peerA, s2) + require.NoError(t, err) + _, err = pool.Add(peerB, s1) + require.NoError(t, err) + + pool.RemovePeer(peerA.ID()) + + peers1 := pool.GetPeers(s1) + assert.Len(t, peers1, 1) + assert.EqualValues(t, "b", peers1[0].ID()) + + peers2 := pool.GetPeers(s2) + assert.Empty(t, peers2) + + // it should still be possible to add the peer back + _, err = pool.Add(peerA, s1) + require.NoError(t, err) + peers1 = pool.GetPeers(s1) + assert.Len(t, peers1, 2) + assert.EqualValues(t, "a", peers1[0].ID()) + assert.EqualValues(t, "b", peers1[1].ID()) +} diff --git a/statesync/stateprovider.go b/statesync/stateprovider.go new file mode 100644 index 0000000..924dd29 --- /dev/null +++ b/statesync/stateprovider.go @@ -0,0 +1,204 @@ +package statesync + +import ( + "context" + "fmt" + "strings" + "time" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/light" + lightprovider "github.com/cometbft/cometbft/light/provider" + lighthttp "github.com/cometbft/cometbft/light/provider/http" + lightrpc "github.com/cometbft/cometbft/light/rpc" + lightdb "github.com/cometbft/cometbft/light/store/db" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +//go:generate ../scripts/mockery_generate.sh StateProvider + +// StateProvider is a provider of trusted state data for bootstrapping a node. This refers +// to the state.State object, not the state machine. +type StateProvider interface { + // AppHash returns the app hash after the given height has been committed. + AppHash(ctx context.Context, height uint64) ([]byte, error) + // Commit returns the commit at the given height. + Commit(ctx context.Context, height uint64) (*types.Commit, error) + // State returns a state object at the given height. + State(ctx context.Context, height uint64) (sm.State, error) +} + +// lightClientStateProvider is a state provider using the light client. +type lightClientStateProvider struct { + cmtsync.Mutex // light.Client is not concurrency-safe + lc *light.Client + version cmtstate.Version + initialHeight int64 + providers map[lightprovider.Provider]string +} + +// NewLightClientStateProvider creates a new StateProvider using a light client and RPC clients. +func NewLightClientStateProvider( + ctx context.Context, + chainID string, + version cmtstate.Version, + initialHeight int64, + servers []string, + trustOptions light.TrustOptions, + logger log.Logger, +) (StateProvider, error) { + if len(servers) < 2 { + return nil, fmt.Errorf("at least 2 RPC servers are required, got %v", len(servers)) + } + + providers := make([]lightprovider.Provider, 0, len(servers)) + providerRemotes := make(map[lightprovider.Provider]string) + for _, server := range servers { + client, err := rpcClient(server) + if err != nil { + return nil, fmt.Errorf("failed to set up RPC client: %w", err) + } + provider := lighthttp.NewWithClient(chainID, client) + providers = append(providers, provider) + // We store the RPC addresses keyed by provider, so we can find the address of the primary + // provider used by the light client and use it to fetch consensus parameters. + providerRemotes[provider] = server + } + + lc, err := light.NewClient(ctx, chainID, trustOptions, providers[0], providers[1:], + lightdb.New(dbm.NewMemDB(), ""), light.Logger(logger), light.MaxRetryAttempts(5)) + if err != nil { + return nil, err + } + return &lightClientStateProvider{ + lc: lc, + version: version, + initialHeight: initialHeight, + providers: providerRemotes, + }, nil +} + +// AppHash implements StateProvider. +func (s *lightClientStateProvider) AppHash(ctx context.Context, height uint64) ([]byte, error) { + s.Lock() + defer s.Unlock() + + // We have to fetch the next height, which contains the app hash for the previous height. + header, err := s.lc.VerifyLightBlockAtHeight(ctx, int64(height+1), time.Now()) + if err != nil { + return nil, err + } + // We also try to fetch the blocks at height H and H+2, since we need these + // when building the state while restoring the snapshot. This avoids the race + // condition where we try to restore a snapshot before H+2 exists. + // + // FIXME This is a hack, since we can't add new methods to the interface without + // breaking it. We should instead have a Has(ctx, height) method which checks + // that the state provider has access to the necessary data for the height. + // We piggyback on AppHash() since it's called when adding snapshots to the pool. + _, err = s.lc.VerifyLightBlockAtHeight(ctx, int64(height+2), time.Now()) + if err != nil { + return nil, err + } + return header.AppHash, nil +} + +// Commit implements StateProvider. +func (s *lightClientStateProvider) Commit(ctx context.Context, height uint64) (*types.Commit, error) { + s.Lock() + defer s.Unlock() + header, err := s.lc.VerifyLightBlockAtHeight(ctx, int64(height), time.Now()) + if err != nil { + return nil, err + } + return header.Commit, nil +} + +// State implements StateProvider. +func (s *lightClientStateProvider) State(ctx context.Context, height uint64) (sm.State, error) { + s.Lock() + defer s.Unlock() + + state := sm.State{ + ChainID: s.lc.ChainID(), + Version: s.version, + InitialHeight: s.initialHeight, + } + if state.InitialHeight == 0 { + state.InitialHeight = 1 + } + + // The snapshot height maps onto the state heights as follows: + // + // height: last block, i.e. the snapshotted height + // height+1: current block, i.e. the first block we'll process after the snapshot + // height+2: next block, i.e. the second block after the snapshot + // + // We need to fetch the NextValidators from height+2 because if the application changed + // the validator set at the snapshot height then this only takes effect at height+2. + lastLightBlock, err := s.lc.VerifyLightBlockAtHeight(ctx, int64(height), time.Now()) + if err != nil { + return sm.State{}, err + } + currentLightBlock, err := s.lc.VerifyLightBlockAtHeight(ctx, int64(height+1), time.Now()) + if err != nil { + return sm.State{}, err + } + nextLightBlock, err := s.lc.VerifyLightBlockAtHeight(ctx, int64(height+2), time.Now()) + if err != nil { + return sm.State{}, err + } + + state.Version = cmtstate.Version{ + Consensus: currentLightBlock.Version, + Software: version.TMCoreSemVer, + } + state.LastBlockHeight = lastLightBlock.Height + state.LastBlockTime = lastLightBlock.Time + state.LastBlockID = lastLightBlock.Commit.BlockID + state.AppHash = currentLightBlock.AppHash + state.LastResultsHash = currentLightBlock.LastResultsHash + state.LastValidators = lastLightBlock.ValidatorSet + state.Validators = currentLightBlock.ValidatorSet + state.NextValidators = nextLightBlock.ValidatorSet + state.LastHeightValidatorsChanged = nextLightBlock.Height + + // We'll also need to fetch consensus params via RPC, using light client verification. + primaryURL, ok := s.providers[s.lc.Primary()] + if !ok || primaryURL == "" { + return sm.State{}, fmt.Errorf("could not find address for primary light client provider") + } + primaryRPC, err := rpcClient(primaryURL) + if err != nil { + return sm.State{}, fmt.Errorf("unable to create RPC client: %w", err) + } + rpcclient := lightrpc.NewClient(primaryRPC, s.lc) + result, err := rpcclient.ConsensusParams(ctx, ¤tLightBlock.Height) + if err != nil { + return sm.State{}, fmt.Errorf("unable to fetch consensus parameters for height %v: %w", + nextLightBlock.Height, err) + } + state.ConsensusParams = result.ConsensusParams + state.LastHeightConsensusParamsChanged = currentLightBlock.Height + + return state, nil +} + +// rpcClient sets up a new RPC client +func rpcClient(server string) (*rpchttp.HTTP, error) { + if !strings.Contains(server, "://") { + server = "http://" + server + } + c, err := rpchttp.New(server, "/websocket") + if err != nil { + return nil, err + } + return c, nil +} diff --git a/statesync/syncer.go b/statesync/syncer.go new file mode 100644 index 0000000..dc471a7 --- /dev/null +++ b/statesync/syncer.go @@ -0,0 +1,522 @@ +package statesync + +import ( + "bytes" + "context" + "errors" + "fmt" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/light" + "github.com/cometbft/cometbft/p2p" + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" + "github.com/cometbft/cometbft/proxy" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +const ( + // chunkTimeout is the timeout while waiting for the next chunk from the chunk queue. + chunkTimeout = 2 * time.Minute + + // minimumDiscoveryTime is the lowest allowable time for a + // SyncAny discovery time. + minimumDiscoveryTime = 5 * time.Second +) + +var ( + // errAbort is returned by Sync() when snapshot restoration is aborted. + errAbort = errors.New("state sync aborted") + // errRetrySnapshot is returned by Sync() when the snapshot should be retried. + errRetrySnapshot = errors.New("retry snapshot") + // errRejectSnapshot is returned by Sync() when the snapshot is rejected. + errRejectSnapshot = errors.New("snapshot was rejected") + // errRejectFormat is returned by Sync() when the snapshot format is rejected. + errRejectFormat = errors.New("snapshot format was rejected") + // errRejectSender is returned by Sync() when the snapshot sender is rejected. + errRejectSender = errors.New("snapshot sender was rejected") + // errVerifyFailed is returned by Sync() when app hash or last height verification fails. + errVerifyFailed = errors.New("verification failed") + // errTimeout is returned by Sync() when we've waited too long to receive a chunk. + errTimeout = errors.New("timed out waiting for chunk") + // errNoSnapshots is returned by SyncAny() if no snapshots are found and discovery is disabled. + errNoSnapshots = errors.New("no suitable snapshots found") +) + +// syncer runs a state sync against an ABCI app. Use either SyncAny() to automatically attempt to +// sync all snapshots in the pool (pausing to discover new ones), or Sync() to sync a specific +// snapshot. Snapshots and chunks are fed via AddSnapshot() and AddChunk() as appropriate. +type syncer struct { + logger log.Logger + stateProvider StateProvider + conn proxy.AppConnSnapshot + connQuery proxy.AppConnQuery + snapshots *snapshotPool + tempDir string + chunkFetchers int32 + retryTimeout time.Duration + + mtx cmtsync.RWMutex + chunks *chunkQueue +} + +// newSyncer creates a new syncer. +func newSyncer( + cfg config.StateSyncConfig, + logger log.Logger, + conn proxy.AppConnSnapshot, + connQuery proxy.AppConnQuery, + stateProvider StateProvider, + tempDir string, +) *syncer { + + return &syncer{ + logger: logger, + stateProvider: stateProvider, + conn: conn, + connQuery: connQuery, + snapshots: newSnapshotPool(), + tempDir: tempDir, + chunkFetchers: cfg.ChunkFetchers, + retryTimeout: cfg.ChunkRequestTimeout, + } +} + +// AddChunk adds a chunk to the chunk queue, if any. It returns false if the chunk has already +// been added to the queue, or an error if there's no sync in progress. +func (s *syncer) AddChunk(chunk *chunk) (bool, error) { + s.mtx.RLock() + defer s.mtx.RUnlock() + if s.chunks == nil { + return false, errors.New("no state sync in progress") + } + added, err := s.chunks.Add(chunk) + if err != nil { + return false, err + } + if added { + s.logger.Debug("Added chunk to queue", "height", chunk.Height, "format", chunk.Format, + "chunk", chunk.Index) + } else { + s.logger.Debug("Ignoring duplicate chunk in queue", "height", chunk.Height, "format", chunk.Format, + "chunk", chunk.Index) + } + return added, nil +} + +// AddSnapshot adds a snapshot to the snapshot pool. It returns true if a new, previously unseen +// snapshot was accepted and added. +func (s *syncer) AddSnapshot(peer p2p.Peer, snapshot *snapshot) (bool, error) { + added, err := s.snapshots.Add(peer, snapshot) + if err != nil { + return false, err + } + if added { + s.logger.Info("Discovered new snapshot", "height", snapshot.Height, "format", snapshot.Format, + "hash", log.NewLazySprintf("%X", snapshot.Hash)) + } + return added, nil +} + +// AddPeer adds a peer to the pool. For now we just keep it simple and send a single request +// to discover snapshots, later we may want to do retries and stuff. +func (s *syncer) AddPeer(peer p2p.Peer) { + s.logger.Debug("Requesting snapshots from peer", "peer", peer.ID()) + e := p2p.Envelope{ + ChannelID: SnapshotChannel, + Message: &ssproto.SnapshotsRequest{}, + } + peer.Send(e) +} + +// RemovePeer removes a peer from the pool. +func (s *syncer) RemovePeer(peer p2p.Peer) { + s.logger.Debug("Removing peer from sync", "peer", peer.ID()) + s.snapshots.RemovePeer(peer.ID()) +} + +// RejectPeer rejects a peer from the pool. +func (s *syncer) RejectPeer(peer p2p.Peer) { + s.logger.Debug("Rejecting peer from sync", "peer", peer.ID()) + s.snapshots.RejectPeer(peer.ID()) +} + +// SyncAny tries to sync any of the snapshots in the snapshot pool, waiting to discover further +// snapshots if none were found and discoveryTime > 0. It returns the latest state and block commit +// which the caller must use to bootstrap the node. +func (s *syncer) SyncAny(discoveryTime time.Duration, retryHook func()) (sm.State, *types.Commit, error) { + if discoveryTime != 0 && discoveryTime < minimumDiscoveryTime { + discoveryTime = 5 * minimumDiscoveryTime + } + + if discoveryTime > 0 { + s.logger.Info("Discovering snapshots", "discoverTime", discoveryTime) + time.Sleep(discoveryTime) + } + + // The app may ask us to retry a snapshot restoration, in which case we need to reuse + // the snapshot and chunk queue from the previous loop iteration. + var ( + snapshot *snapshot + chunks *chunkQueue + err error + ) + for { + // If not nil, we're going to retry restoration of the same snapshot. + if snapshot == nil { + snapshot = s.snapshots.Best() + chunks = nil + } + if snapshot == nil { + if discoveryTime == 0 { + return sm.State{}, nil, errNoSnapshots + } + retryHook() + s.logger.Info("sync any", "msg", log.NewLazySprintf("Discovering snapshots for %v", discoveryTime)) + time.Sleep(discoveryTime) + continue + } + if chunks == nil { + chunks, err = newChunkQueue(snapshot, s.tempDir) + if err != nil { + return sm.State{}, nil, fmt.Errorf("failed to create chunk queue: %w", err) + } + defer chunks.Close() // in case we forget to close it elsewhere + } + + newState, commit, err := s.Sync(snapshot, chunks) + switch { + case err == nil: + return newState, commit, nil + + case errors.Is(err, errAbort): + return sm.State{}, nil, err + + case errors.Is(err, errRetrySnapshot): + chunks.RetryAll() + s.logger.Info("Retrying snapshot", "height", snapshot.Height, "format", snapshot.Format, + "hash", log.NewLazySprintf("%X", snapshot.Hash)) + continue + + case errors.Is(err, errTimeout): + s.snapshots.Reject(snapshot) + s.logger.Error("Timed out waiting for snapshot chunks, rejected snapshot", + "height", snapshot.Height, "format", snapshot.Format, "hash", log.NewLazySprintf("%X", snapshot.Hash)) + + case errors.Is(err, errRejectSnapshot): + s.snapshots.Reject(snapshot) + s.logger.Info("Snapshot rejected", "height", snapshot.Height, "format", snapshot.Format, + "hash", log.NewLazySprintf("%X", snapshot.Hash)) + + case errors.Is(err, errRejectFormat): + s.snapshots.RejectFormat(snapshot.Format) + s.logger.Info("Snapshot format rejected", "format", snapshot.Format) + + case errors.Is(err, errRejectSender): + s.logger.Info("Snapshot senders rejected", "height", snapshot.Height, "format", snapshot.Format, + "hash", log.NewLazySprintf("%X", snapshot.Hash)) + for _, peer := range s.snapshots.GetPeers(snapshot) { + s.snapshots.RejectPeer(peer.ID()) + s.logger.Info("Snapshot sender rejected", "peer", peer.ID()) + } + + case errors.Is(err, context.DeadlineExceeded): + s.logger.Info("Timed out validating snapshot, rejecting", "height", snapshot.Height, "err", err) + s.snapshots.Reject(snapshot) + + default: + return sm.State{}, nil, fmt.Errorf("snapshot restoration failed: %w", err) + } + + // Discard snapshot and chunks for next iteration + err = chunks.Close() + if err != nil { + s.logger.Error("Failed to clean up chunk queue", "err", err) + } + snapshot = nil + chunks = nil + } +} + +// Sync executes a sync for a specific snapshot, returning the latest state and block commit which +// the caller must use to bootstrap the node. +func (s *syncer) Sync(snapshot *snapshot, chunks *chunkQueue) (sm.State, *types.Commit, error) { + s.mtx.Lock() + if s.chunks != nil { + s.mtx.Unlock() + return sm.State{}, nil, errors.New("a state sync is already in progress") + } + s.chunks = chunks + s.mtx.Unlock() + defer func() { + s.mtx.Lock() + s.chunks = nil + s.mtx.Unlock() + }() + + hctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second) + defer cancel() + + appHash, err := s.stateProvider.AppHash(hctx, snapshot.Height) + if err != nil { + s.logger.Info("failed to fetch and verify app hash", "err", err) + if err == light.ErrNoWitnesses { + return sm.State{}, nil, err + } + return sm.State{}, nil, errRejectSnapshot + } + snapshot.trustedAppHash = appHash + + // Offer snapshot to ABCI app. + err = s.offerSnapshot(snapshot) + if err != nil { + return sm.State{}, nil, err + } + + // Spawn chunk fetchers. They will terminate when the chunk queue is closed or context canceled. + fetchCtx, cancel := context.WithCancel(context.TODO()) + defer cancel() + for i := int32(0); i < s.chunkFetchers; i++ { + go s.fetchChunks(fetchCtx, snapshot, chunks) + } + + pctx, pcancel := context.WithTimeout(context.TODO(), 30*time.Second) + defer pcancel() + + // Optimistically build new state, so we don't discover any light client failures at the end. + state, err := s.stateProvider.State(pctx, snapshot.Height) + if err != nil { + s.logger.Info("failed to fetch and verify CometBFT state", "err", err) + if err == light.ErrNoWitnesses { + return sm.State{}, nil, err + } + return sm.State{}, nil, errRejectSnapshot + } + commit, err := s.stateProvider.Commit(pctx, snapshot.Height) + if err != nil { + s.logger.Info("failed to fetch and verify commit", "err", err) + if err == light.ErrNoWitnesses { + return sm.State{}, nil, err + } + return sm.State{}, nil, errRejectSnapshot + } + + // Restore snapshot + err = s.applyChunks(chunks) + if err != nil { + return sm.State{}, nil, err + } + + // Verify app and app version + if err := s.verifyApp(snapshot, state.Version.Consensus.App); err != nil { + return sm.State{}, nil, err + } + + // Done! 🎉 + s.logger.Info("Snapshot restored", "height", snapshot.Height, "format", snapshot.Format, + "hash", log.NewLazySprintf("%X", snapshot.Hash)) + + return state, commit, nil +} + +// offerSnapshot offers a snapshot to the app. It returns various errors depending on the app's +// response, or nil if the snapshot was accepted. +func (s *syncer) offerSnapshot(snapshot *snapshot) error { + s.logger.Info("Offering snapshot to ABCI app", "height", snapshot.Height, + "format", snapshot.Format, "hash", log.NewLazySprintf("%X", snapshot.Hash)) + resp, err := s.conn.OfferSnapshot(context.TODO(), &abci.RequestOfferSnapshot{ + Snapshot: &abci.Snapshot{ + Height: snapshot.Height, + Format: snapshot.Format, + Chunks: snapshot.Chunks, + Hash: snapshot.Hash, + Metadata: snapshot.Metadata, + }, + AppHash: snapshot.trustedAppHash, + }) + if err != nil { + return fmt.Errorf("failed to offer snapshot: %w", err) + } + switch resp.Result { + case abci.ResponseOfferSnapshot_ACCEPT: + s.logger.Info("Snapshot accepted, restoring", "height", snapshot.Height, + "format", snapshot.Format, "hash", log.NewLazySprintf("%X", snapshot.Hash)) + return nil + case abci.ResponseOfferSnapshot_ABORT: + return errAbort + case abci.ResponseOfferSnapshot_REJECT: + return errRejectSnapshot + case abci.ResponseOfferSnapshot_REJECT_FORMAT: + return errRejectFormat + case abci.ResponseOfferSnapshot_REJECT_SENDER: + return errRejectSender + default: + return fmt.Errorf("unknown ResponseOfferSnapshot result %v", resp.Result) + } +} + +// applyChunks applies chunks to the app. It returns various errors depending on the app's +// response, or nil once the snapshot is fully restored. +func (s *syncer) applyChunks(chunks *chunkQueue) error { + for { + chunk, err := chunks.Next() + if err == errDone { + return nil + } else if err != nil { + return fmt.Errorf("failed to fetch chunk: %w", err) + } + + resp, err := s.conn.ApplySnapshotChunk(context.TODO(), &abci.RequestApplySnapshotChunk{ + Index: chunk.Index, + Chunk: chunk.Chunk, + Sender: string(chunk.Sender), + }) + if err != nil { + return fmt.Errorf("failed to apply chunk %v: %w", chunk.Index, err) + } + s.logger.Info("Applied snapshot chunk to ABCI app", "height", chunk.Height, + "format", chunk.Format, "chunk", chunk.Index, "total", chunks.Size()) + + // Discard and refetch any chunks as requested by the app + for _, index := range resp.RefetchChunks { + err := chunks.Discard(index) + if err != nil { + return fmt.Errorf("failed to discard chunk %v: %w", index, err) + } + } + + // Reject any senders as requested by the app + for _, sender := range resp.RejectSenders { + if sender != "" { + s.snapshots.RejectPeer(p2p.ID(sender)) + err := chunks.DiscardSender(p2p.ID(sender)) + if err != nil { + return fmt.Errorf("failed to reject sender: %w", err) + } + } + } + + switch resp.Result { + case abci.ResponseApplySnapshotChunk_ACCEPT: + case abci.ResponseApplySnapshotChunk_ABORT: + return errAbort + case abci.ResponseApplySnapshotChunk_RETRY: + chunks.Retry(chunk.Index) + case abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT: + return errRetrySnapshot + case abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT: + return errRejectSnapshot + default: + return fmt.Errorf("unknown ResponseApplySnapshotChunk result %v", resp.Result) + } + } +} + +// fetchChunks requests chunks from peers, receiving allocations from the chunk queue. Chunks +// will be received from the reactor via syncer.AddChunks() to chunkQueue.Add(). +func (s *syncer) fetchChunks(ctx context.Context, snapshot *snapshot, chunks *chunkQueue) { + var ( + next = true + index uint32 + err error + ) + + for { + if next { + index, err = chunks.Allocate() + if errors.Is(err, errDone) { + // Keep checking until the context is canceled (restore is done), in case any + // chunks need to be refetched. + select { + case <-ctx.Done(): + return + default: + } + time.Sleep(2 * time.Second) + continue + } + if err != nil { + s.logger.Error("Failed to allocate chunk from queue", "err", err) + return + } + } + s.logger.Info("Fetching snapshot chunk", "height", snapshot.Height, + "format", snapshot.Format, "chunk", index, "total", chunks.Size()) + + ticker := time.NewTicker(s.retryTimeout) + defer ticker.Stop() + + s.requestChunk(snapshot, index) + + select { + case <-chunks.WaitFor(index): + next = true + + case <-ticker.C: + next = false + + case <-ctx.Done(): + return + } + + ticker.Stop() + } +} + +// requestChunk requests a chunk from a peer. +func (s *syncer) requestChunk(snapshot *snapshot, chunk uint32) { + peer := s.snapshots.GetPeer(snapshot) + if peer == nil { + s.logger.Error("No valid peers found for snapshot", "height", snapshot.Height, + "format", snapshot.Format, "hash", log.NewLazySprintf("%X", snapshot.Hash)) + return + } + s.logger.Debug("Requesting snapshot chunk", "height", snapshot.Height, + "format", snapshot.Format, "chunk", chunk, "peer", peer.ID()) + peer.Send(p2p.Envelope{ + ChannelID: ChunkChannel, + Message: &ssproto.ChunkRequest{ + Height: snapshot.Height, + Format: snapshot.Format, + Index: chunk, + }, + }) +} + +// verifyApp verifies the sync, checking the app hash, last block height and app version +func (s *syncer) verifyApp(snapshot *snapshot, appVersion uint64) error { + resp, err := s.connQuery.Info(context.TODO(), proxy.RequestInfo) + if err != nil { + return fmt.Errorf("failed to query ABCI app for appHash: %w", err) + } + + // sanity check that the app version in the block matches the application's own record + // of its version + if resp.AppVersion != appVersion { + // An error here most likely means that the app hasn't inplemented state sync + // or the Info call correctly + return fmt.Errorf("app version mismatch. Expected: %d, got: %d", + appVersion, resp.AppVersion) + } + if !bytes.Equal(snapshot.trustedAppHash, resp.LastBlockAppHash) { + s.logger.Error("appHash verification failed", + "expected", fmt.Sprintf("%X", snapshot.trustedAppHash), + "actual", fmt.Sprintf("%X", resp.LastBlockAppHash)) + return errVerifyFailed + } + if uint64(resp.LastBlockHeight) != snapshot.Height { + s.logger.Error( + "ABCI app reported unexpected last block height", + "expected", snapshot.Height, + "actual", resp.LastBlockHeight, + ) + return errVerifyFailed + } + + s.logger.Info("Verified ABCI app", "height", snapshot.Height, "appHash", log.NewLazySprintf("%X", snapshot.trustedAppHash)) + return nil +} diff --git a/statesync/syncer_test.go b/statesync/syncer_test.go new file mode 100644 index 0000000..4238038 --- /dev/null +++ b/statesync/syncer_test.go @@ -0,0 +1,697 @@ +package statesync + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" + cmtsync "github.com/cometbft/cometbft/libs/sync" + "github.com/cometbft/cometbft/p2p" + p2pmocks "github.com/cometbft/cometbft/p2p/mocks" + cmtstate "github.com/cometbft/cometbft/proto/tendermint/state" + ssproto "github.com/cometbft/cometbft/proto/tendermint/statesync" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/proxy" + proxymocks "github.com/cometbft/cometbft/proxy/mocks" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/statesync/mocks" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +const testAppVersion = 9 + +// Sets up a basic syncer that can be used to test OfferSnapshot requests +func setupOfferSyncer() (*syncer, *proxymocks.AppConnSnapshot) { + connQuery := &proxymocks.AppConnQuery{} + connSnapshot := &proxymocks.AppConnSnapshot{} + stateProvider := &mocks.StateProvider{} + stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil) + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + return syncer, connSnapshot +} + +// Sets up a simple peer mock with an ID +func simplePeer(id string) *p2pmocks.Peer { + peer := &p2pmocks.Peer{} + peer.On("ID").Return(p2p.ID(id)) + return peer +} + +func TestSyncer_SyncAny(t *testing.T) { + state := sm.State{ + ChainID: "chain", + Version: cmtstate.Version{ + Consensus: cmtversion.Consensus{ + Block: version.BlockProtocol, + App: testAppVersion, + }, + Software: version.TMCoreSemVer, + }, + + LastBlockHeight: 1, + LastBlockID: types.BlockID{Hash: []byte("blockhash")}, + LastBlockTime: time.Now(), + LastResultsHash: []byte("last_results_hash"), + AppHash: []byte("app_hash"), + + LastValidators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val1")}}, + Validators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val2")}}, + NextValidators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val3")}}, + + ConsensusParams: *types.DefaultConsensusParams(), + LastHeightConsensusParamsChanged: 1, + } + commit := &types.Commit{BlockID: types.BlockID{Hash: []byte("blockhash")}} + + chunks := []*chunk{ + {Height: 1, Format: 1, Index: 0, Chunk: []byte{1, 1, 0}}, + {Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 1, 1}}, + {Height: 1, Format: 1, Index: 2, Chunk: []byte{1, 1, 2}}, + } + s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + + stateProvider := &mocks.StateProvider{} + stateProvider.On("AppHash", mock.Anything, uint64(1)).Return(state.AppHash, nil) + stateProvider.On("AppHash", mock.Anything, uint64(2)).Return([]byte("app_hash_2"), nil) + stateProvider.On("Commit", mock.Anything, uint64(1)).Return(commit, nil) + stateProvider.On("State", mock.Anything, uint64(1)).Return(state, nil) + connSnapshot := &proxymocks.AppConnSnapshot{} + connQuery := &proxymocks.AppConnQuery{} + + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + // Adding a chunk should error when no sync is in progress + _, err := syncer.AddChunk(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{1}}) + require.Error(t, err) + + // Adding a couple of peers should trigger snapshot discovery messages + peerA := &p2pmocks.Peer{} + peerA.On("ID").Return(p2p.ID("a")) + peerA.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + if !ok { + return false + } + req, ok := e.Message.(*ssproto.SnapshotsRequest) + return ok && e.ChannelID == SnapshotChannel && req != nil + })).Return(true) + syncer.AddPeer(peerA) + peerA.AssertExpectations(t) + + peerB := &p2pmocks.Peer{} + peerB.On("ID").Return(p2p.ID("b")) + peerB.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + if !ok { + return false + } + req, ok := e.Message.(*ssproto.SnapshotsRequest) + return ok && e.ChannelID == SnapshotChannel && req != nil + })).Return(true) + syncer.AddPeer(peerB) + peerB.AssertExpectations(t) + + // Both peers report back with snapshots. One of them also returns a snapshot we don't want, in + // format 2, which will be rejected by the ABCI application. + isNew, err := syncer.AddSnapshot(peerA, s) + require.NoError(t, err) + assert.True(t, isNew) + + isNew, err = syncer.AddSnapshot(peerB, s) + require.NoError(t, err) + assert.False(t, isNew) + + isNew, err = syncer.AddSnapshot(peerB, &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1}}) + require.NoError(t, err) + assert.True(t, isNew) + + // We start a sync, with peers sending back chunks when requested. We first reject the snapshot + // with height 2 format 2, and accept the snapshot at height 1. + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: &abci.Snapshot{ + Height: 2, + Format: 2, + Chunks: 3, + Hash: []byte{1}, + }, + AppHash: []byte("app_hash_2"), + }).Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_FORMAT}, nil) + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: &abci.Snapshot{ + Height: s.Height, + Format: s.Format, + Chunks: s.Chunks, + Hash: s.Hash, + Metadata: s.Metadata, + }, + AppHash: []byte("app_hash"), + }).Times(2).Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}, nil) + + chunkRequests := make(map[uint32]int) + chunkRequestsMtx := cmtsync.Mutex{} + onChunkRequest := func(args mock.Arguments) { + e, ok := args[0].(p2p.Envelope) + require.True(t, ok) + msg := e.Message.(*ssproto.ChunkRequest) + require.EqualValues(t, 1, msg.Height) + require.EqualValues(t, 1, msg.Format) + require.LessOrEqual(t, msg.Index, uint32(len(chunks))) + + added, err := syncer.AddChunk(chunks[msg.Index]) + require.NoError(t, err) + assert.True(t, added) + + chunkRequestsMtx.Lock() + chunkRequests[msg.Index]++ + chunkRequestsMtx.Unlock() + } + peerA.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + return ok && e.ChannelID == ChunkChannel + })).Maybe().Run(onChunkRequest).Return(true) + peerB.On("Send", mock.MatchedBy(func(i interface{}) bool { + e, ok := i.(p2p.Envelope) + return ok && e.ChannelID == ChunkChannel + })).Maybe().Run(onChunkRequest).Return(true) + + // The first time we're applying chunk 2 we tell it to retry the snapshot and discard chunk 1, + // which should cause it to keep the existing chunk 0 and 2, and restart restoration from + // beginning. We also wait for a little while, to exercise the retry logic in fetchChunks(). + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 2, Chunk: []byte{1, 1, 2}, + }).Once().Run(func(args mock.Arguments) { time.Sleep(2 * time.Second) }).Return( + &abci.ResponseApplySnapshotChunk{ + Result: abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT, + RefetchChunks: []uint32{1}, + }, nil) + + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 0, Chunk: []byte{1, 1, 0}, + }).Times(2).Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 1, Chunk: []byte{1, 1, 1}, + }).Times(2).Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 2, Chunk: []byte{1, 1, 2}, + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connQuery.On("Info", mock.Anything, proxy.RequestInfo).Return(&abci.ResponseInfo{ + AppVersion: testAppVersion, + LastBlockHeight: 1, + LastBlockAppHash: []byte("app_hash"), + }, nil) + + newState, lastCommit, err := syncer.SyncAny(0, func() {}) + require.NoError(t, err) + + time.Sleep(50 * time.Millisecond) // wait for peers to receive requests + + chunkRequestsMtx.Lock() + assert.Equal(t, map[uint32]int{0: 1, 1: 2, 2: 1}, chunkRequests) + chunkRequestsMtx.Unlock() + + expectState := state + + assert.Equal(t, expectState, newState) + assert.Equal(t, commit, lastCommit) + + connSnapshot.AssertExpectations(t) + connQuery.AssertExpectations(t) + peerA.AssertExpectations(t) + peerB.AssertExpectations(t) +} + +func TestSyncer_SyncAny_noSnapshots(t *testing.T) { + syncer, _ := setupOfferSyncer() + _, _, err := syncer.SyncAny(0, func() {}) + assert.Equal(t, errNoSnapshots, err) +} + +func TestSyncer_SyncAny_abort(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + + s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + _, err := syncer.AddSnapshot(simplePeer("id"), s) + require.NoError(t, err) + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil) + + _, _, err = syncer.SyncAny(0, func() {}) + assert.Equal(t, errAbort, err) + connSnapshot.AssertExpectations(t) +} + +func TestSyncer_SyncAny_reject(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + + // s22 is tried first, then s12, then s11, then errNoSnapshots + s22 := &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}} + s12 := &snapshot{Height: 1, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}} + s11 := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + _, err := syncer.AddSnapshot(simplePeer("id"), s22) + require.NoError(t, err) + _, err = syncer.AddSnapshot(simplePeer("id"), s12) + require.NoError(t, err) + _, err = syncer.AddSnapshot(simplePeer("id"), s11) + require.NoError(t, err) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s22), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s12), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s11), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil) + + _, _, err = syncer.SyncAny(0, func() {}) + assert.Equal(t, errNoSnapshots, err) + connSnapshot.AssertExpectations(t) +} + +func TestSyncer_SyncAny_reject_format(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + + // s22 is tried first, which reject s22 and s12, then s11 will abort. + s22 := &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}} + s12 := &snapshot{Height: 1, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}} + s11 := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + _, err := syncer.AddSnapshot(simplePeer("id"), s22) + require.NoError(t, err) + _, err = syncer.AddSnapshot(simplePeer("id"), s12) + require.NoError(t, err) + _, err = syncer.AddSnapshot(simplePeer("id"), s11) + require.NoError(t, err) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s22), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_FORMAT}, nil) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s11), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil) + + _, _, err = syncer.SyncAny(0, func() {}) + assert.Equal(t, errAbort, err) + connSnapshot.AssertExpectations(t) +} + +func TestSyncer_SyncAny_reject_sender(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + + peerA := simplePeer("a") + peerB := simplePeer("b") + peerC := simplePeer("c") + + // sbc will be offered first, which will be rejected with reject_sender, causing all snapshots + // submitted by both b and c (i.e. sb, sc, sbc) to be rejected. Finally, sa will reject and + // errNoSnapshots is returned. + sa := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + sb := &snapshot{Height: 2, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + sc := &snapshot{Height: 3, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + sbc := &snapshot{Height: 4, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + _, err := syncer.AddSnapshot(peerA, sa) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerB, sb) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerC, sc) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerB, sbc) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerC, sbc) + require.NoError(t, err) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(sbc), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_SENDER}, nil) + + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(sa), AppHash: []byte("app_hash"), + }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil) + + _, _, err = syncer.SyncAny(0, func() {}) + assert.Equal(t, errNoSnapshots, err) + connSnapshot.AssertExpectations(t) +} + +func TestSyncer_SyncAny_abciError(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + + errBoom := errors.New("boom") + s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}} + _, err := syncer.AddSnapshot(simplePeer("id"), s) + require.NoError(t, err) + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s), AppHash: []byte("app_hash"), + }).Once().Return(nil, errBoom) + + _, _, err = syncer.SyncAny(0, func() {}) + assert.True(t, errors.Is(err, errBoom)) + connSnapshot.AssertExpectations(t) +} + +func TestSyncer_offerSnapshot(t *testing.T) { + unknownErr := errors.New("unknown error") + boom := errors.New("boom") + + testcases := map[string]struct { + result abci.ResponseOfferSnapshot_Result + err error + expectErr error + }{ + "accept": {abci.ResponseOfferSnapshot_ACCEPT, nil, nil}, + "abort": {abci.ResponseOfferSnapshot_ABORT, nil, errAbort}, + "reject": {abci.ResponseOfferSnapshot_REJECT, nil, errRejectSnapshot}, + "reject_format": {abci.ResponseOfferSnapshot_REJECT_FORMAT, nil, errRejectFormat}, + "reject_sender": {abci.ResponseOfferSnapshot_REJECT_SENDER, nil, errRejectSender}, + "unknown": {abci.ResponseOfferSnapshot_UNKNOWN, nil, unknownErr}, + "error": {0, boom, boom}, + "unknown non-zero": {9, nil, unknownErr}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + syncer, connSnapshot := setupOfferSyncer() + s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}, trustedAppHash: []byte("app_hash")} + connSnapshot.On("OfferSnapshot", mock.Anything, &abci.RequestOfferSnapshot{ + Snapshot: toABCI(s), + AppHash: []byte("app_hash"), + }).Return(&abci.ResponseOfferSnapshot{Result: tc.result}, tc.err) + err := syncer.offerSnapshot(s) + if tc.expectErr == unknownErr { + require.Error(t, err) + } else { + unwrapped := errors.Unwrap(err) + if unwrapped != nil { + err = unwrapped + } + assert.Equal(t, tc.expectErr, err) + } + }) + } +} + +func TestSyncer_applyChunks_Results(t *testing.T) { + unknownErr := errors.New("unknown error") + boom := errors.New("boom") + + testcases := map[string]struct { + result abci.ResponseApplySnapshotChunk_Result + err error + expectErr error + }{ + "accept": {abci.ResponseApplySnapshotChunk_ACCEPT, nil, nil}, + "abort": {abci.ResponseApplySnapshotChunk_ABORT, nil, errAbort}, + "retry": {abci.ResponseApplySnapshotChunk_RETRY, nil, nil}, + "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT, nil, errRetrySnapshot}, + "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT, nil, errRejectSnapshot}, + "unknown": {abci.ResponseApplySnapshotChunk_UNKNOWN, nil, unknownErr}, + "error": {0, boom, boom}, + "unknown non-zero": {9, nil, unknownErr}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + connQuery := &proxymocks.AppConnQuery{} + connSnapshot := &proxymocks.AppConnSnapshot{} + stateProvider := &mocks.StateProvider{} + stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil) + + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + body := []byte{1, 2, 3} + chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 1}, "") + require.NoError(t, err) + _, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: body}) + require.NoError(t, err) + + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 0, Chunk: body, + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: tc.result}, tc.err) + if tc.result == abci.ResponseApplySnapshotChunk_RETRY { + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 0, Chunk: body, + }).Once().Return(&abci.ResponseApplySnapshotChunk{ + Result: abci.ResponseApplySnapshotChunk_ACCEPT, + }, nil) + } + + err = syncer.applyChunks(chunks) + if tc.expectErr == unknownErr { + require.Error(t, err) + } else { + unwrapped := errors.Unwrap(err) + if unwrapped != nil { + err = unwrapped + } + assert.Equal(t, tc.expectErr, err) + } + connSnapshot.AssertExpectations(t) + }) + } +} + +func TestSyncer_applyChunks_RefetchChunks(t *testing.T) { + // Discarding chunks via refetch_chunks should work the same for all results + testcases := map[string]struct { + result abci.ResponseApplySnapshotChunk_Result + }{ + "accept": {abci.ResponseApplySnapshotChunk_ACCEPT}, + "abort": {abci.ResponseApplySnapshotChunk_ABORT}, + "retry": {abci.ResponseApplySnapshotChunk_RETRY}, + "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT}, + "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + connQuery := &proxymocks.AppConnQuery{} + connSnapshot := &proxymocks.AppConnSnapshot{} + stateProvider := &mocks.StateProvider{} + stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil) + + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 3}, "") + require.NoError(t, err) + added, err := chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{0}}) + require.True(t, added) + require.NoError(t, err) + added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}}) + require.True(t, added) + require.NoError(t, err) + added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 2, Chunk: []byte{2}}) + require.True(t, added) + require.NoError(t, err) + + // The first two chunks are accepted, before the last one asks for 1 to be refetched + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 0, Chunk: []byte{0}, + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 1, Chunk: []byte{1}, + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 2, Chunk: []byte{2}, + }).Once().Return(&abci.ResponseApplySnapshotChunk{ + Result: tc.result, + RefetchChunks: []uint32{1}, + }, nil) + + // Since removing the chunk will cause Next() to block, we spawn a goroutine, then + // check the queue contents, and finally close the queue to end the goroutine. + // We don't really care about the result of applyChunks, since it has separate test. + go func() { + syncer.applyChunks(chunks) //nolint:errcheck // purposefully ignore error + }() + + time.Sleep(50 * time.Millisecond) + assert.True(t, chunks.Has(0)) + assert.False(t, chunks.Has(1)) + assert.True(t, chunks.Has(2)) + err = chunks.Close() + require.NoError(t, err) + }) + } +} + +func TestSyncer_applyChunks_RejectSenders(t *testing.T) { + // Banning chunks senders via ban_chunk_senders should work the same for all results + testcases := map[string]struct { + result abci.ResponseApplySnapshotChunk_Result + }{ + "accept": {abci.ResponseApplySnapshotChunk_ACCEPT}, + "abort": {abci.ResponseApplySnapshotChunk_ABORT}, + "retry": {abci.ResponseApplySnapshotChunk_RETRY}, + "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT}, + "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + connQuery := &proxymocks.AppConnQuery{} + connSnapshot := &proxymocks.AppConnSnapshot{} + stateProvider := &mocks.StateProvider{} + stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil) + + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + // Set up three peers across two snapshots, and ask for one of them to be banned. + // It should be banned from all snapshots. + peerA := simplePeer("a") + peerB := simplePeer("b") + peerC := simplePeer("c") + + s1 := &snapshot{Height: 1, Format: 1, Chunks: 3} + s2 := &snapshot{Height: 2, Format: 1, Chunks: 3} + _, err := syncer.AddSnapshot(peerA, s1) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerA, s2) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerB, s1) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerB, s2) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerC, s1) + require.NoError(t, err) + _, err = syncer.AddSnapshot(peerC, s2) + require.NoError(t, err) + + chunks, err := newChunkQueue(s1, "") + require.NoError(t, err) + added, err := chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{0}, Sender: peerA.ID()}) + require.True(t, added) + require.NoError(t, err) + added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}, Sender: peerB.ID()}) + require.True(t, added) + require.NoError(t, err) + added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 2, Chunk: []byte{2}, Sender: peerC.ID()}) + require.True(t, added) + require.NoError(t, err) + + // The first two chunks are accepted, before the last one asks for b sender to be rejected + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 0, Chunk: []byte{0}, Sender: "a", + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 1, Chunk: []byte{1}, Sender: "b", + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 2, Chunk: []byte{2}, Sender: "c", + }).Once().Return(&abci.ResponseApplySnapshotChunk{ + Result: tc.result, + RejectSenders: []string{string(peerB.ID())}, + }, nil) + + // On retry, the last chunk will be tried again, so we just accept it then. + if tc.result == abci.ResponseApplySnapshotChunk_RETRY { + connSnapshot.On("ApplySnapshotChunk", mock.Anything, &abci.RequestApplySnapshotChunk{ + Index: 2, Chunk: []byte{2}, Sender: "c", + }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + } + + // We don't really care about the result of applyChunks, since it has separate test. + // However, it will block on e.g. retry result, so we spawn a goroutine that will + // be shut down when the chunk queue closes. + go func() { + syncer.applyChunks(chunks) //nolint:errcheck // purposefully ignore error + }() + + time.Sleep(50 * time.Millisecond) + + s1peers := syncer.snapshots.GetPeers(s1) + assert.Len(t, s1peers, 2) + assert.EqualValues(t, "a", s1peers[0].ID()) + assert.EqualValues(t, "c", s1peers[1].ID()) + + syncer.snapshots.GetPeers(s1) + assert.Len(t, s1peers, 2) + assert.EqualValues(t, "a", s1peers[0].ID()) + assert.EqualValues(t, "c", s1peers[1].ID()) + + err = chunks.Close() + require.NoError(t, err) + }) + } +} + +func TestSyncer_verifyApp(t *testing.T) { + boom := errors.New("boom") + const appVersion = 9 + appVersionMismatchErr := errors.New("app version mismatch. Expected: 9, got: 2") + s := &snapshot{Height: 3, Format: 1, Chunks: 5, Hash: []byte{1, 2, 3}, trustedAppHash: []byte("app_hash")} + + testcases := map[string]struct { + response *abci.ResponseInfo + err error + expectErr error + }{ + "verified": {&abci.ResponseInfo{ + LastBlockHeight: 3, + LastBlockAppHash: []byte("app_hash"), + AppVersion: appVersion, + }, nil, nil}, + "invalid app version": {&abci.ResponseInfo{ + LastBlockHeight: 3, + LastBlockAppHash: []byte("app_hash"), + AppVersion: 2, + }, nil, appVersionMismatchErr}, + "invalid height": {&abci.ResponseInfo{ + LastBlockHeight: 5, + LastBlockAppHash: []byte("app_hash"), + AppVersion: appVersion, + }, nil, errVerifyFailed}, + "invalid hash": {&abci.ResponseInfo{ + LastBlockHeight: 3, + LastBlockAppHash: []byte("xxx"), + AppVersion: appVersion, + }, nil, errVerifyFailed}, + "error": {nil, boom, boom}, + } + for name, tc := range testcases { + tc := tc + t.Run(name, func(t *testing.T) { + connQuery := &proxymocks.AppConnQuery{} + connSnapshot := &proxymocks.AppConnSnapshot{} + stateProvider := &mocks.StateProvider{} + + cfg := config.DefaultStateSyncConfig() + syncer := newSyncer(*cfg, log.NewNopLogger(), connSnapshot, connQuery, stateProvider, "") + + connQuery.On("Info", mock.Anything, proxy.RequestInfo).Return(tc.response, tc.err) + err := syncer.verifyApp(s, appVersion) + unwrapped := errors.Unwrap(err) + if unwrapped != nil { + err = unwrapped + } + require.Equal(t, tc.expectErr, err) + }) + } +} + +func toABCI(s *snapshot) *abci.Snapshot { + return &abci.Snapshot{ + Height: s.Height, + Format: s.Format, + Chunks: s.Chunks, + Hash: s.Hash, + Metadata: s.Metadata, + } +} diff --git a/store/bench_test.go b/store/bench_test.go new file mode 100644 index 0000000..60b5713 --- /dev/null +++ b/store/bench_test.go @@ -0,0 +1,36 @@ +package store + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +// TestLoadBlockExtendedCommit tests loading the extended commit for a previously +// saved block. The load method should return nil when only a commit was saved and +// return the extended commit otherwise. +func BenchmarkRepeatedLoadSeenCommitSameBlock(b *testing.B) { + state, bs, cleanup := makeStateAndBlockStore() + defer cleanup() + h := bs.Height() + 1 + block, err := state.MakeBlock(h, test.MakeNTxs(h, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(b, err) + seenCommit := makeTestExtCommitWithNumSigs(block.Header.Height, cmttime.Now(), 100).ToCommit() + ps, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(b, err) + bs.SaveBlock(block, ps, seenCommit) + + // sanity check + res := bs.LoadSeenCommit(block.Height) + require.Equal(b, seenCommit, res) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res := bs.LoadSeenCommit(block.Height) + require.NotNil(b, res) + } +} diff --git a/store/store.go b/store/store.go new file mode 100644 index 0000000..7e0e211 --- /dev/null +++ b/store/store.go @@ -0,0 +1,765 @@ +package store + +import ( + "errors" + "fmt" + "strconv" + + "github.com/cosmos/gogoproto/proto" + lru "github.com/hashicorp/golang-lru/v2" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/evidence" + cmtsync "github.com/cometbft/cometbft/libs/sync" + cmtstore "github.com/cometbft/cometbft/proto/tendermint/store" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" +) + +// Assuming the length of a block part is 64kB (`types.BlockPartSizeBytes`), +// the maximum size of a block, that will be batch saved, is 640kB. The +// benchmarks have shown that `goleveldb` still performs well with blocks of +// this size. However, if the block is larger than 1MB, the performance degrades. +const maxBlockPartsToBatch = 10 + +/* +BlockStore is a simple low level store for blocks. + +There are three types of information stored: + - BlockMeta: Meta information about each block + - Block part: Parts of each block, aggregated w/ PartSet + - Commit: The commit part of each block, for gossiping precommit votes + +Currently the precommit signatures are duplicated in the Block parts as +well as the Commit. In the future this may change, perhaps by moving +the Commit data outside the Block. (TODO) + +The store can be assumed to contain all contiguous blocks between base and height (inclusive). + +// NOTE: BlockStore methods will panic if they encounter errors +// deserializing loaded data, indicating probable corruption on disk. +*/ +type BlockStore struct { + db dbm.DB + + // mtx guards access to the struct fields listed below it. Although we rely on the database + // to enforce fine-grained concurrency control for its data, we need to make sure that + // no external observer can get data from the database that is not in sync with the fields below, + // and vice-versa. Hence, when updating the fields below, we use the mutex to make sure + // that the database is also up to date. This prevents any concurrent external access from + // obtaining inconsistent data. + // The only reason for keeping these fields in the struct is that the data + // can't efficiently be queried from the database since the key encoding we use is not + // lexicographically ordered (see https://github.com/tendermint/tendermint/issues/4567). + mtx cmtsync.RWMutex + base int64 + height int64 + + seenCommitCache *lru.Cache[int64, *types.Commit] + blockCommitCache *lru.Cache[int64, *types.Commit] + blockExtendedCommitCache *lru.Cache[int64, *types.ExtendedCommit] +} + +// NewBlockStore returns a new BlockStore with the given DB, +// initialized to the last height that was committed to the DB. +func NewBlockStore(db dbm.DB) *BlockStore { + bs := LoadBlockStoreState(db) + bStore := &BlockStore{ + base: bs.Base, + height: bs.Height, + db: db, + } + bStore.addCaches() + return bStore +} + +func (bs *BlockStore) addCaches() { + var err error + // err can only occur if the argument is non-positive, so is impossible in context. + bs.blockCommitCache, err = lru.New[int64, *types.Commit](100) + if err != nil { + panic(err) + } + bs.blockExtendedCommitCache, err = lru.New[int64, *types.ExtendedCommit](100) + if err != nil { + panic(err) + } + bs.seenCommitCache, err = lru.New[int64, *types.Commit](100) + if err != nil { + panic(err) + } +} + +func (bs *BlockStore) IsEmpty() bool { + bs.mtx.RLock() + defer bs.mtx.RUnlock() + return bs.base == bs.height && bs.base == 0 +} + +// Base returns the first known contiguous block height, or 0 for empty block stores. +func (bs *BlockStore) Base() int64 { + bs.mtx.RLock() + defer bs.mtx.RUnlock() + return bs.base +} + +// Height returns the last known contiguous block height, or 0 for empty block stores. +func (bs *BlockStore) Height() int64 { + bs.mtx.RLock() + defer bs.mtx.RUnlock() + return bs.height +} + +// Size returns the number of blocks in the block store. +func (bs *BlockStore) Size() int64 { + bs.mtx.RLock() + defer bs.mtx.RUnlock() + if bs.height == 0 { + return 0 + } + return bs.height - bs.base + 1 +} + +// LoadBase atomically loads the base block meta, or returns nil if no base is found. +func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta { + bs.mtx.RLock() + defer bs.mtx.RUnlock() + if bs.base == 0 { + return nil + } + return bs.LoadBlockMeta(bs.base) +} + +// LoadBlock returns the block with the given height. +// If no block is found for that height, it returns nil. +func (bs *BlockStore) LoadBlock(height int64) *types.Block { + blockMeta := bs.LoadBlockMeta(height) + if blockMeta == nil { + return nil + } + + pbb := new(cmtproto.Block) + buf := []byte{} + for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ { + part := bs.LoadBlockPart(height, i) + // If the part is missing (e.g. since it has been deleted after we + // loaded the block meta) we consider the whole block to be missing. + if part == nil { + return nil + } + buf = append(buf, part.Bytes...) + } + err := proto.Unmarshal(buf, pbb) + if err != nil { + // NOTE: The existence of meta should imply the existence of the + // block. So, make sure meta is only saved after blocks are saved. + panic(fmt.Sprintf("Error reading block: %v", err)) + } + + block, err := types.BlockFromProto(pbb) + if err != nil { + panic(fmt.Errorf("error from proto block: %w", err)) + } + + return block +} + +// LoadBlockByHash returns the block with the given hash. +// If no block is found for that hash, it returns nil. +// Panics if it fails to parse height associated with the given hash. +func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block { + bz, err := bs.db.Get(calcBlockHashKey(hash)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil + } + + s := string(bz) + height, err := strconv.ParseInt(s, 10, 64) + if err != nil { + panic(fmt.Sprintf("failed to extract height from %s: %v", s, err)) + } + return bs.LoadBlock(height) +} + +// LoadBlockPart returns the Part at the given index +// from the block at the given height. +// If no part is found for the given height and index, it returns nil. +func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part { + pbpart := new(cmtproto.Part) + + bz, err := bs.db.Get(calcBlockPartKey(height, index)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil + } + + err = proto.Unmarshal(bz, pbpart) + if err != nil { + panic(fmt.Errorf("unmarshal to cmtproto.Part failed: %w", err)) + } + part, err := types.PartFromProto(pbpart) + if err != nil { + panic(fmt.Sprintf("Error reading block part: %v", err)) + } + + return part +} + +// LoadBlockMeta returns the BlockMeta for the given height. +// If no block is found for the given height, it returns nil. +func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { + pbbm := new(cmtproto.BlockMeta) + bz, err := bs.db.Get(calcBlockMetaKey(height)) + if err != nil { + panic(err) + } + + if len(bz) == 0 { + return nil + } + + err = proto.Unmarshal(bz, pbbm) + if err != nil { + panic(fmt.Errorf("unmarshal to cmtproto.BlockMeta: %w", err)) + } + + blockMeta, err := types.BlockMetaFromTrustedProto(pbbm) + if err != nil { + panic(fmt.Errorf("error from proto blockMeta: %w", err)) + } + + return blockMeta +} + +// LoadBlockMetaByHash returns the blockmeta who's header corresponds to the given +// hash. If none is found, returns nil. +func (bs *BlockStore) LoadBlockMetaByHash(hash []byte) *types.BlockMeta { + bz, err := bs.db.Get(calcBlockHashKey(hash)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil + } + + s := string(bz) + height, err := strconv.ParseInt(s, 10, 64) + if err != nil { + panic(fmt.Sprintf("failed to extract height from %s: %v", s, err)) + } + return bs.LoadBlockMeta(height) +} + +// LoadBlockCommit returns the Commit for the given height. +// This commit consists of the +2/3 and other Precommit-votes for block at `height`, +// and it comes from the block.LastCommit for `height+1`. +// If no commit is found for the given height, it returns nil. +func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit { + comm, ok := bs.blockCommitCache.Get(height) + if ok { + return comm.Clone() + } + pbc := new(cmtproto.Commit) + bz, err := bs.db.Get(calcBlockCommitKey(height)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil + } + err = proto.Unmarshal(bz, pbc) + if err != nil { + panic(fmt.Errorf("error reading block commit: %w", err)) + } + commit, err := types.CommitFromProto(pbc) + if err != nil { + panic(fmt.Errorf("converting commit to proto: %w", err)) + } + bs.blockCommitCache.Add(height, commit) + return commit.Clone() +} + +// LoadExtendedCommit returns the ExtendedCommit for the given height. +// The extended commit is not guaranteed to contain the same +2/3 precommits data +// as the commit in the block. +func (bs *BlockStore) LoadBlockExtendedCommit(height int64) *types.ExtendedCommit { + comm, ok := bs.blockExtendedCommitCache.Get(height) + if ok { + return comm.Clone() + } + pbec := new(cmtproto.ExtendedCommit) + bz, err := bs.db.Get(calcExtCommitKey(height)) + if err != nil { + panic(fmt.Errorf("fetching extended commit: %w", err)) + } + if len(bz) == 0 { + return nil + } + err = proto.Unmarshal(bz, pbec) + if err != nil { + panic(fmt.Errorf("decoding extended commit: %w", err)) + } + extCommit, err := types.ExtendedCommitFromProto(pbec) + if err != nil { + panic(fmt.Errorf("converting extended commit: %w", err)) + } + bs.blockExtendedCommitCache.Add(height, extCommit) + return extCommit.Clone() +} + +// LoadSeenCommit returns the locally seen Commit for the given height. +// This is useful when we've seen a commit, but there has not yet been +// a new block at `height + 1` that includes this commit in its block.LastCommit. +func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit { + comm, ok := bs.seenCommitCache.Get(height) + if ok { + return comm.Clone() + } + pbc := new(cmtproto.Commit) + bz, err := bs.db.Get(calcSeenCommitKey(height)) + if err != nil { + panic(err) + } + if len(bz) == 0 { + return nil + } + err = proto.Unmarshal(bz, pbc) + if err != nil { + panic(fmt.Sprintf("error reading block seen commit: %v", err)) + } + + commit, err := types.CommitFromProto(pbc) + if err != nil { + panic(fmt.Errorf("converting seen commit: %w", err)) + } + bs.seenCommitCache.Add(height, commit) + return commit.Clone() +} + +// PruneBlocks removes block up to (but not including) a height. It returns number of blocks pruned and the evidence retain height - the height at which data needed to prove evidence must not be removed. +func (bs *BlockStore) PruneBlocks(height int64, state sm.State) (uint64, int64, error) { + if height <= 0 { + return 0, -1, fmt.Errorf("height must be greater than 0") + } + bs.mtx.RLock() + if height > bs.height { + bs.mtx.RUnlock() + return 0, -1, fmt.Errorf("cannot prune beyond the latest height %v", bs.height) + } + base := bs.base + bs.mtx.RUnlock() + if height < base { + return 0, -1, fmt.Errorf("cannot prune to height %v, it is lower than base height %v", + height, base) + } + + pruned := uint64(0) + batch := bs.db.NewBatch() + defer batch.Close() + flush := func(batch dbm.Batch, base int64) error { + // We can't trust batches to be atomic, so update base first to make sure noone + // tries to access missing blocks. + bs.mtx.Lock() + defer batch.Close() + defer bs.mtx.Unlock() + bs.base = base + return bs.saveStateAndWriteDB(batch, "failed to prune") + } + + evidencePoint := height + for h := base; h < height; h++ { + + meta := bs.LoadBlockMeta(h) + if meta == nil { // assume already deleted + continue + } + + // This logic is in place to protect data that proves malicious behavior. + // If the height is within the evidence age, we continue to persist the header and commit data. + + if evidencePoint == height && !evidence.IsEvidenceExpired(state.LastBlockHeight, state.LastBlockTime, h, meta.Header.Time, state.ConsensusParams.Evidence) { + evidencePoint = h + } + + // if height is beyond the evidence point we dont delete the header + if h < evidencePoint { + if err := batch.Delete(calcBlockMetaKey(h)); err != nil { + return 0, -1, err + } + } + if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil { + return 0, -1, err + } + // if height is beyond the evidence point we dont delete the commit data + if h < evidencePoint { + if err := batch.Delete(calcBlockCommitKey(h)); err != nil { + return 0, -1, err + } + } + if err := batch.Delete(calcSeenCommitKey(h)); err != nil { + return 0, -1, err + } + + if h < evidencePoint { + if err := batch.Delete(calcExtCommitKey(h)); err != nil { + return 0, -1, err + } + bs.blockExtendedCommitCache.Remove(h) + } + + for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ { + if err := batch.Delete(calcBlockPartKey(h, p)); err != nil { + return 0, -1, err + } + } + pruned++ + + // flush every 1000 blocks to avoid batches becoming too large + if pruned%1000 == 0 && pruned > 0 { + err := flush(batch, h) + if err != nil { + return 0, -1, err + } + batch = bs.db.NewBatch() + defer batch.Close() + } + } + + err := flush(batch, height) + if err != nil { + return 0, -1, err + } + return pruned, evidencePoint, nil +} + +// SaveBlock persists the given block, blockParts, and seenCommit to the underlying db. +// blockParts: Must be parts of the block +// seenCommit: The +2/3 precommits that were seen which committed at height. +// +// If all the nodes restart after committing a block, +// we need this to reload the precommits to catch-up nodes to the +// most recent height. Otherwise they'd stall at H-1. +func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { + if block == nil { + panic("BlockStore can only save a non-nil block") + } + + batch := bs.db.NewBatch() + defer batch.Close() + + if err := bs.saveBlockToBatch(block, blockParts, seenCommit, batch); err != nil { + panic(err) + } + + bs.mtx.Lock() + defer bs.mtx.Unlock() + bs.height = block.Height + if bs.base == 0 { + bs.base = block.Height + } + + // Save new BlockStoreState descriptor. This also flushes the database. + err := bs.saveStateAndWriteDB(batch, "failed to save block") + if err != nil { + panic(err) + } +} + +// SaveBlockWithExtendedCommit persists the given block, blockParts, and +// seenExtendedCommit to the underlying db. seenExtendedCommit is stored under +// two keys in the database: as the seenCommit and as the ExtendedCommit data for the +// height. This allows the vote extension data to be persisted for all blocks +// that are saved. +func (bs *BlockStore) SaveBlockWithExtendedCommit(block *types.Block, blockParts *types.PartSet, seenExtendedCommit *types.ExtendedCommit) { + if block == nil { + panic("BlockStore can only save a non-nil block") + } + if err := seenExtendedCommit.EnsureExtensions(true); err != nil { + panic(fmt.Errorf("problems saving block with extensions: %w", err)) + } + + batch := bs.db.NewBatch() + defer batch.Close() + + if err := bs.saveBlockToBatch(block, blockParts, seenExtendedCommit.ToCommit(), batch); err != nil { + panic(err) + } + height := block.Height + + pbec := seenExtendedCommit.ToProto() + extCommitBytes := mustEncode(pbec) + if err := batch.Set(calcExtCommitKey(height), extCommitBytes); err != nil { + panic(err) + } + + bs.mtx.Lock() + defer bs.mtx.Unlock() + bs.height = height + if bs.base == 0 { + bs.base = height + } + + // Save new BlockStoreState descriptor. This also flushes the database. + err := bs.saveStateAndWriteDB(batch, "failed to save block with extended commit") + if err != nil { + panic(err) + } +} + +func (bs *BlockStore) saveBlockToBatch( + block *types.Block, + blockParts *types.PartSet, + seenCommit *types.Commit, + batch dbm.Batch, +) error { + if block == nil { + panic("BlockStore can only save a non-nil block") + } + + height := block.Height + hash := block.Hash() + + if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w { + return fmt.Errorf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g) + } + if !blockParts.IsComplete() { + return errors.New("BlockStore can only save complete block part sets") + } + if height != seenCommit.Height { + return fmt.Errorf("BlockStore cannot save seen commit of a different height (block: %d, commit: %d)", height, seenCommit.Height) + } + + // If the block is small, batch save the block parts. Otherwise, save the + // parts individually. + saveBlockPartsToBatch := blockParts.Count() <= maxBlockPartsToBatch + + // Save block parts. This must be done before the block meta, since callers + // typically load the block meta first as an indication that the block exists + // and then go on to load block parts - we must make sure the block is + // complete as soon as the block meta is written. + for i := 0; i < int(blockParts.Total()); i++ { + part := blockParts.GetPart(i) + bs.saveBlockPart(height, i, part, batch, saveBlockPartsToBatch) + } + + // Save block meta + blockMeta := types.NewBlockMeta(block, blockParts) + pbm := blockMeta.ToProto() + if pbm == nil { + return errors.New("nil blockmeta") + } + metaBytes := mustEncode(pbm) + if err := batch.Set(calcBlockMetaKey(height), metaBytes); err != nil { + return err + } + if err := batch.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil { + return err + } + + // Save block commit (duplicate and separate from the Block) + pbc := block.LastCommit.ToProto() + blockCommitBytes := mustEncode(pbc) + if err := batch.Set(calcBlockCommitKey(height-1), blockCommitBytes); err != nil { + return err + } + + // Save seen commit (seen +2/3 precommits for block) + // NOTE: we can delete this at a later height + pbsc := seenCommit.ToProto() + seenCommitBytes := mustEncode(pbsc) + if err := batch.Set(calcSeenCommitKey(height), seenCommitBytes); err != nil { + return err + } + + return nil +} + +func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part, batch dbm.Batch, saveBlockPartsToBatch bool) { + pbp, err := part.ToProto() + if err != nil { + panic(fmt.Errorf("unable to make part into proto: %w", err)) + } + partBytes := mustEncode(pbp) + if saveBlockPartsToBatch { + err = batch.Set(calcBlockPartKey(height, index), partBytes) + } else { + err = bs.db.Set(calcBlockPartKey(height, index), partBytes) + } + if err != nil { + panic(err) + } +} + +// Contract: the caller MUST have, at least, a read lock on `bs`. +func (bs *BlockStore) saveStateAndWriteDB(batch dbm.Batch, errMsg string) error { + bss := cmtstore.BlockStoreState{ + Base: bs.base, + Height: bs.height, + } + SaveBlockStoreStateBatch(&bss, batch) + + err := batch.WriteSync() + if err != nil { + return fmt.Errorf("error writing batch to DB %q: (base %d, height %d): %w", + errMsg, bs.base, bs.height, err) + } + return nil +} + +// SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node. +func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error { + pbc := seenCommit.ToProto() + seenCommitBytes, err := proto.Marshal(pbc) + if err != nil { + return fmt.Errorf("unable to marshal commit: %w", err) + } + return bs.db.Set(calcSeenCommitKey(height), seenCommitBytes) +} + +func (bs *BlockStore) Close() error { + return bs.db.Close() +} + +//----------------------------------------------------------------------------- + +func calcBlockMetaKey(height int64) []byte { + return []byte(fmt.Sprintf("H:%v", height)) +} + +func calcBlockPartKey(height int64, partIndex int) []byte { + return []byte(fmt.Sprintf("P:%v:%v", height, partIndex)) +} + +func calcBlockCommitKey(height int64) []byte { + return []byte(fmt.Sprintf("C:%v", height)) +} + +func calcSeenCommitKey(height int64) []byte { + return []byte(fmt.Sprintf("SC:%v", height)) +} + +func calcExtCommitKey(height int64) []byte { + return []byte(fmt.Sprintf("EC:%v", height)) +} + +func calcBlockHashKey(hash []byte) []byte { + return []byte(fmt.Sprintf("BH:%x", hash)) +} + +//----------------------------------------------------------------------------- + +var blockStoreKey = []byte("blockStore") + +// SaveBlockStoreState persists the blockStore state to the database. +// deprecated: still present in this version for API compatibility +func SaveBlockStoreState(bsj *cmtstore.BlockStoreState, db dbm.DB) { + saveBlockStoreStateBatchInternal(bsj, db, nil) +} + +// SaveBlockStoreStateBatch persists the blockStore state to the database. +// It uses the DB batch passed as parameter +func SaveBlockStoreStateBatch(bsj *cmtstore.BlockStoreState, batch dbm.Batch) { + saveBlockStoreStateBatchInternal(bsj, nil, batch) +} + +func saveBlockStoreStateBatchInternal(bsj *cmtstore.BlockStoreState, db dbm.DB, batch dbm.Batch) { + bytes, err := proto.Marshal(bsj) + if err != nil { + panic(fmt.Sprintf("could not marshal state bytes: %v", err)) + } + if batch != nil { + err = batch.Set(blockStoreKey, bytes) + } else { + if db == nil { + panic("both 'db' and 'batch' cannot be nil") + } + err = db.SetSync(blockStoreKey, bytes) + } + if err != nil { + panic(err) + } +} + +// LoadBlockStoreState returns the BlockStoreState as loaded from disk. +// If no BlockStoreState was previously persisted, it returns the zero value. +func LoadBlockStoreState(db dbm.DB) cmtstore.BlockStoreState { + bytes, err := db.Get(blockStoreKey) + if err != nil { + panic(err) + } + + if len(bytes) == 0 { + return cmtstore.BlockStoreState{ + Base: 0, + Height: 0, + } + } + + var bsj cmtstore.BlockStoreState + if err := proto.Unmarshal(bytes, &bsj); err != nil { + panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes)) + } + + // Backwards compatibility with persisted data from before Base existed. + if bsj.Height > 0 && bsj.Base == 0 { + bsj.Base = 1 + } + return bsj +} + +// mustEncode proto encodes a proto.message and panics if fails +func mustEncode(pb proto.Message) []byte { + bz, err := proto.Marshal(pb) + if err != nil { + panic(fmt.Errorf("unable to marshal: %w", err)) + } + return bz +} + +//----------------------------------------------------------------------------- + +// DeleteLatestBlock removes the block pointed to by height, +// lowering height by one. +func (bs *BlockStore) DeleteLatestBlock() error { + bs.mtx.RLock() + targetHeight := bs.height + bs.mtx.RUnlock() + + batch := bs.db.NewBatch() + defer batch.Close() + + // delete what we can, skipping what's already missing, to ensure partial + // blocks get deleted fully. + if meta := bs.LoadBlockMeta(targetHeight); meta != nil { + if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil { + return err + } + for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ { + if err := batch.Delete(calcBlockPartKey(targetHeight, p)); err != nil { + return err + } + } + } + if err := batch.Delete(calcBlockCommitKey(targetHeight)); err != nil { + return err + } + if err := batch.Delete(calcSeenCommitKey(targetHeight)); err != nil { + return err + } + // delete last, so as to not leave keys built on meta.BlockID dangling + if err := batch.Delete(calcBlockMetaKey(targetHeight)); err != nil { + return err + } + + bs.mtx.Lock() + defer bs.mtx.Unlock() + bs.height = targetHeight - 1 + return bs.saveStateAndWriteDB(batch, "failed to delete the latest block") +} diff --git a/store/store_test.go b/store/store_test.go new file mode 100644 index 0000000..854d873 --- /dev/null +++ b/store/store_test.go @@ -0,0 +1,781 @@ +package store + +import ( + "encoding/json" + "fmt" + "os" + "runtime/debug" + "strings" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/internal/test" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtstore "github.com/cometbft/cometbft/proto/tendermint/store" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + sm "github.com/cometbft/cometbft/state" + "github.com/cometbft/cometbft/types" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" +) + +// A cleanupFunc cleans up any config / test files created for a particular +// test. +type cleanupFunc func() + +// make an extended commit with a single vote containing just the height and a +// timestamp +func makeTestExtCommit(height int64, timestamp time.Time) *types.ExtendedCommit { + return makeTestExtCommitWithNumSigs(height, timestamp, 1) +} + +func makeTestExtCommitWithNumSigs(height int64, timestamp time.Time, numSigs int) *types.ExtendedCommit { + extCommitSigs := []types.ExtendedCommitSig{} + for i := 0; i < numSigs; i++ { + extCommitSigs = append(extCommitSigs, types.ExtendedCommitSig{ + CommitSig: types.CommitSig{ + BlockIDFlag: types.BlockIDFlagCommit, + ValidatorAddress: cmtrand.Bytes(crypto.AddressSize), + Timestamp: timestamp, + Signature: cmtrand.Bytes(64), + }, + ExtensionSignature: []byte("ExtensionSignature"), + }) + } + return &types.ExtendedCommit{ + Height: height, + BlockID: types.BlockID{ + Hash: crypto.CRandBytes(32), + PartSetHeader: types.PartSetHeader{Hash: crypto.CRandBytes(32), Total: 2}, + }, + ExtendedSignatures: extCommitSigs, + } +} + +func makeStateAndBlockStore() (sm.State, *BlockStore, cleanupFunc) { + config := test.ResetTestRoot("blockchain_reactor_test") + // blockDB := dbm.NewDebugDB("blockDB", dbm.NewMemDB()) + // stateDB := dbm.NewDebugDB("stateDB", dbm.NewMemDB()) + blockDB := dbm.NewMemDB() + stateDB := dbm.NewMemDB() + stateStore := sm.NewStore(stateDB, sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + if err != nil { + panic(fmt.Errorf("error constructing state from genesis file: %w", err)) + } + return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) } +} + +func TestLoadBlockStoreState(t *testing.T) { + type blockStoreTest struct { + testName string + bss *cmtstore.BlockStoreState + want cmtstore.BlockStoreState + } + + testCases := []blockStoreTest{ + { + "success", &cmtstore.BlockStoreState{Base: 100, Height: 1000}, + cmtstore.BlockStoreState{Base: 100, Height: 1000}, + }, + {"empty", &cmtstore.BlockStoreState{}, cmtstore.BlockStoreState{}}, + {"no base", &cmtstore.BlockStoreState{Height: 1000}, cmtstore.BlockStoreState{Base: 1, Height: 1000}}, + } + + for _, tc := range testCases { + db := dbm.NewMemDB() + batch := db.NewBatch() + SaveBlockStoreStateBatch(tc.bss, batch) + err := batch.WriteSync() + require.NoError(t, err) + retrBSJ := LoadBlockStoreState(db) + assert.Equal(t, tc.want, retrBSJ, "expected the retrieved DBs to match: %s", tc.testName) + err = batch.Close() + require.NoError(t, err) + } +} + +func TestNewBlockStore(t *testing.T) { + db := dbm.NewMemDB() + bss := cmtstore.BlockStoreState{Base: 100, Height: 10000} + bz, _ := proto.Marshal(&bss) + err := db.Set(blockStoreKey, bz) + require.NoError(t, err) + bs := NewBlockStore(db) + require.Equal(t, int64(100), bs.Base(), "failed to properly parse blockstore") + require.Equal(t, int64(10000), bs.Height(), "failed to properly parse blockstore") + + panicCausers := []struct { + data []byte + wantErr string + }{ + {[]byte("artful-doger"), "not unmarshal bytes"}, + {[]byte(" "), "unmarshal bytes"}, + } + + for i, tt := range panicCausers { + tt := tt + // Expecting a panic here on trying to parse an invalid blockStore + _, _, panicErr := doFn(func() (interface{}, error) { + err := db.Set(blockStoreKey, tt.data) + require.NoError(t, err) + _ = NewBlockStore(db) + return nil, nil + }) + require.NotNil(t, panicErr, "#%d panicCauser: %q expected a panic", i, tt.data) + assert.Contains(t, fmt.Sprintf("%#v", panicErr), tt.wantErr, "#%d data: %q", i, tt.data) + } + + err = db.Set(blockStoreKey, []byte{}) + require.NoError(t, err) + bs = NewBlockStore(db) + assert.Equal(t, bs.Height(), int64(0), "expecting empty bytes to be unmarshaled alright") +} + +func newInMemoryBlockStore() (*BlockStore, dbm.DB) { + db := dbm.NewMemDB() + return NewBlockStore(db), db +} + +// TODO: This test should be simplified ... + +func TestBlockStoreSaveLoadBlock(t *testing.T) { + state, bs, cleanup := makeStateAndBlockStore() + defer cleanup() + require.Equal(t, bs.Base(), int64(0), "initially the base should be zero") + require.Equal(t, bs.Height(), int64(0), "initially the height should be zero") + + // check there are no blocks at various heights + noBlockHeights := []int64{0, -1, 100, 1000, 2} + for i, height := range noBlockHeights { + if g := bs.LoadBlock(height); g != nil { + t.Errorf("#%d: height(%d) got a block; want nil", i, height) + } + } + + // save a block big enough to have two block parts + txs := []types.Tx{make([]byte, types.BlockPartSizeBytes)} // TX taking one block part alone + block, err := state.MakeBlock(bs.Height()+1, txs, new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + validPartSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + require.GreaterOrEqual(t, validPartSet.Total(), uint32(2)) + part2 := validPartSet.GetPart(1) + + seenCommit := makeTestExtCommit(block.Height, cmttime.Now()) + bs.SaveBlockWithExtendedCommit(block, validPartSet, seenCommit) + require.EqualValues(t, 1, bs.Base(), "expecting the new height to be changed") + require.EqualValues(t, block.Height, bs.Height(), "expecting the new height to be changed") + + incompletePartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 2}) + uncontiguousPartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 0}) + _, err = uncontiguousPartSet.AddPart(part2) + require.Error(t, err) + + header1 := types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol}, + Height: 1, + ChainID: "block_test", + Time: cmttime.Now(), + ProposerAddress: cmtrand.Bytes(crypto.AddressSize), + } + + // End of setup, test data + + commitAtH10 := makeTestExtCommit(10, cmttime.Now()).ToCommit() + tuples := []struct { + block *types.Block + parts *types.PartSet + seenCommit *types.ExtendedCommit + wantPanic string + wantErr bool + + corruptBlockInDB bool + corruptCommitInDB bool + corruptSeenCommitInDB bool + eraseCommitInDB bool + eraseSeenCommitInDB bool + }{ + { + block: newBlock(header1, commitAtH10), + parts: validPartSet, + seenCommit: seenCommit, + }, + + { + block: nil, + wantPanic: "only save a non-nil block", + }, + + { + block: newBlock( // New block at height 5 in empty block store is fine + types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol}, + Height: 5, + ChainID: "block_test", + Time: cmttime.Now(), + ProposerAddress: cmtrand.Bytes(crypto.AddressSize), + }, + makeTestExtCommit(5, cmttime.Now()).ToCommit(), + ), + parts: validPartSet, + seenCommit: makeTestExtCommit(5, cmttime.Now()), + }, + + { + block: newBlock(header1, commitAtH10), + parts: incompletePartSet, + wantPanic: "only save complete block", // incomplete parts + seenCommit: makeTestExtCommit(10, cmttime.Now()), + }, + + { + block: newBlock(header1, commitAtH10), + parts: validPartSet, + seenCommit: seenCommit, + corruptCommitInDB: true, // Corrupt the DB's commit entry + wantPanic: "error reading block commit", + }, + + { + block: newBlock(header1, commitAtH10), + parts: validPartSet, + seenCommit: seenCommit, + wantPanic: "unmarshal to cmtproto.BlockMeta", + corruptBlockInDB: true, // Corrupt the DB's block entry + }, + + { + block: newBlock(header1, commitAtH10), + parts: validPartSet, + seenCommit: seenCommit, + + // Expecting no error and we want a nil back + eraseSeenCommitInDB: true, + }, + + { + block: block, + parts: validPartSet, + seenCommit: seenCommit, + + corruptSeenCommitInDB: true, + wantPanic: "error reading block seen commit", + }, + + { + block: block, + parts: validPartSet, + seenCommit: seenCommit, + + // Expecting no error and we want a nil back + eraseCommitInDB: true, + }, + } + + type quad struct { + block *types.Block + commit *types.Commit + meta *types.BlockMeta + + seenCommit *types.Commit + } + + for i, tuple := range tuples { + tuple := tuple + bs, db := newInMemoryBlockStore() + // SaveBlock + res, err, panicErr := doFn(func() (interface{}, error) { + bs.SaveBlockWithExtendedCommit(tuple.block, tuple.parts, tuple.seenCommit) + if tuple.block == nil { + return nil, nil + } + + if tuple.corruptBlockInDB { + err := db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus")) + require.NoError(t, err) + } + bBlock := bs.LoadBlock(tuple.block.Height) + bBlockMeta := bs.LoadBlockMeta(tuple.block.Height) + + if tuple.eraseSeenCommitInDB { + err := db.Delete(calcSeenCommitKey(tuple.block.Height)) + require.NoError(t, err) + } + if tuple.corruptSeenCommitInDB { + err := db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit")) + require.NoError(t, err) + } + bSeenCommit := bs.LoadSeenCommit(tuple.block.Height) + + commitHeight := tuple.block.Height - 1 + if tuple.eraseCommitInDB { + err := db.Delete(calcBlockCommitKey(commitHeight)) + require.NoError(t, err) + } + if tuple.corruptCommitInDB { + err := db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus")) + require.NoError(t, err) + } + bCommit := bs.LoadBlockCommit(commitHeight) + return &quad{ + block: bBlock, seenCommit: bSeenCommit, commit: bCommit, + meta: bBlockMeta, + }, nil + }) + + if subStr := tuple.wantPanic; subStr != "" { + if panicErr == nil { + t.Errorf("#%d: want a non-nil panic", i) + } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) { + t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr) + } + continue + } + + if tuple.wantErr { + if err == nil { + t.Errorf("#%d: got nil error", i) + } + continue + } + + assert.Nil(t, panicErr, "#%d: unexpected panic", i) + assert.Nil(t, err, "#%d: expecting a non-nil error", i) + qua, ok := res.(*quad) + if !ok || qua == nil { + t.Errorf("#%d: got nil quad back; gotType=%T", i, res) + continue + } + if tuple.eraseSeenCommitInDB { + assert.Nil(t, qua.seenCommit, + "erased the seenCommit in the DB hence we should get back a nil seenCommit") + } + if tuple.eraseCommitInDB { + assert.Nil(t, qua.commit, + "erased the commit in the DB hence we should get back a nil commit") + } + } +} + +// stripExtensions removes all VoteExtension data from an ExtendedCommit. This +// is useful when dealing with an ExendedCommit but vote extension data is +// expected to be absent. +func stripExtensions(ec *types.ExtendedCommit) bool { + stripped := false + for idx := range ec.ExtendedSignatures { + if len(ec.ExtendedSignatures[idx].Extension) > 0 || len(ec.ExtendedSignatures[idx].ExtensionSignature) > 0 { + stripped = true + } + ec.ExtendedSignatures[idx].Extension = nil + ec.ExtendedSignatures[idx].ExtensionSignature = nil + } + return stripped +} + +// TestSaveBlockWithExtendedCommitPanicOnAbsentExtension tests that saving a +// block with an extended commit panics when the extension data is absent. +func TestSaveBlockWithExtendedCommitPanicOnAbsentExtension(t *testing.T) { + for _, testCase := range []struct { + name string + malleateCommit func(*types.ExtendedCommit) + shouldPanic bool + }{ + { + name: "basic save", + malleateCommit: func(_ *types.ExtendedCommit) {}, + shouldPanic: false, + }, + { + name: "save commit with no extensions", + malleateCommit: func(c *types.ExtendedCommit) { + stripExtensions(c) + }, + shouldPanic: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + state, bs, cleanup := makeStateAndBlockStore() + defer cleanup() + h := bs.Height() + 1 + block, err := state.MakeBlock(h, test.MakeNTxs(h, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + + seenCommit := makeTestExtCommit(block.Height, cmttime.Now()) + ps, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + testCase.malleateCommit(seenCommit) + if testCase.shouldPanic { + require.Panics(t, func() { + bs.SaveBlockWithExtendedCommit(block, ps, seenCommit) + }) + } else { + bs.SaveBlockWithExtendedCommit(block, ps, seenCommit) + } + }) + } +} + +// TestLoadBlockExtendedCommit tests loading the extended commit for a previously +// saved block. The load method should return nil when only a commit was saved and +// return the extended commit otherwise. +func TestLoadBlockExtendedCommit(t *testing.T) { + for _, testCase := range []struct { + name string + saveExtended bool + expectResult bool + }{ + { + name: "save commit", + saveExtended: false, + expectResult: false, + }, + { + name: "save extended commit", + saveExtended: true, + expectResult: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + state, bs, cleanup := makeStateAndBlockStore() + defer cleanup() + h := bs.Height() + 1 + block, err := state.MakeBlock(h, test.MakeNTxs(h, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + seenCommit := makeTestExtCommit(block.Height, cmttime.Now()) + ps, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + if testCase.saveExtended { + bs.SaveBlockWithExtendedCommit(block, ps, seenCommit) + } else { + bs.SaveBlock(block, ps, seenCommit.ToCommit()) + } + res := bs.LoadBlockExtendedCommit(block.Height) + if testCase.expectResult { + require.Equal(t, seenCommit, res) + } else { + require.Nil(t, res) + } + }) + } +} + +func TestLoadBaseMeta(t *testing.T) { + config := test.ResetTestRoot("blockchain_reactor_test") + defer os.RemoveAll(config.RootDir) + stateStore := sm.NewStore(dbm.NewMemDB(), sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + require.NoError(t, err) + bs := NewBlockStore(dbm.NewMemDB()) + + for h := int64(1); h <= 10; h++ { + block, err := state.MakeBlock(h, test.MakeNTxs(h, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + seenCommit := makeTestExtCommit(h, cmttime.Now()) + bs.SaveBlockWithExtendedCommit(block, partSet, seenCommit) + } + + _, _, err = bs.PruneBlocks(4, state) + require.NoError(t, err) + + baseBlock := bs.LoadBaseMeta() + assert.EqualValues(t, 4, baseBlock.Header.Height) + assert.EqualValues(t, 4, bs.Base()) + + require.NoError(t, bs.DeleteLatestBlock()) + require.EqualValues(t, 9, bs.Height()) +} + +func TestLoadBlockPart(t *testing.T) { + config := test.ResetTestRoot("blockchain_reactor_test") + + bs, db := newInMemoryBlockStore() + const height, index = 10, 1 + loadPart := func() (interface{}, error) { + part := bs.LoadBlockPart(height, index) + return part, nil + } + + state, err := sm.MakeGenesisStateFromFile(config.GenesisFile()) + require.NoError(t, err) + + // Initially no contents. + // 1. Requesting for a non-existent block shouldn't fail + res, _, panicErr := doFn(loadPart) + require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic") + require.Nil(t, res, "a non-existent block part should return nil") + + // 2. Next save a corrupted block then try to load it + err = db.Set(calcBlockPartKey(height, index), []byte("CometBFT")) + require.NoError(t, err) + res, _, panicErr = doFn(loadPart) + require.NotNil(t, panicErr, "expecting a non-nil panic") + require.Contains(t, panicErr.Error(), "unmarshal to cmtproto.Part failed") + + // 3. A good block serialized and saved to the DB should be retrievable + block, err := state.MakeBlock(height, nil, new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + part1 := partSet.GetPart(0) + + pb1, err := part1.ToProto() + require.NoError(t, err) + err = db.Set(calcBlockPartKey(height, index), mustEncode(pb1)) + require.NoError(t, err) + gotPart, _, panicErr := doFn(loadPart) + require.Nil(t, panicErr, "an existent and proper block should not panic") + require.Nil(t, res, "a properly saved block should return a proper block") + + // Having to do this because of https://github.com/stretchr/testify/issues/1141 + gotPartJSON, err := json.Marshal(gotPart.(*types.Part)) + require.NoError(t, err) + part1JSON, err := json.Marshal(part1) + require.NoError(t, err) + require.JSONEq(t, string(gotPartJSON), string(part1JSON), + "expecting successful retrieval of previously saved block") +} + +func TestPruneBlocks(t *testing.T) { + config := test.ResetTestRoot("blockchain_reactor_test") + defer os.RemoveAll(config.RootDir) + stateStore := sm.NewStore(dbm.NewMemDB(), sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + require.NoError(t, err) + db := dbm.NewMemDB() + bs := NewBlockStore(db) + assert.EqualValues(t, 0, bs.Base()) + assert.EqualValues(t, 0, bs.Height()) + assert.EqualValues(t, 0, bs.Size()) + + // pruning an empty store should error, even when pruning to 0 + _, _, err = bs.PruneBlocks(1, state) + require.Error(t, err) + + _, _, err = bs.PruneBlocks(0, state) + require.Error(t, err) + + // make more than 1000 blocks, to test batch deletions + for h := int64(1); h <= 1500; h++ { + block, err := state.MakeBlock(h, test.MakeNTxs(h, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + seenCommit := makeTestExtCommit(h, cmttime.Now()) + bs.SaveBlockWithExtendedCommit(block, partSet, seenCommit) + } + + assert.EqualValues(t, 1, bs.Base()) + assert.EqualValues(t, 1500, bs.Height()) + assert.EqualValues(t, 1500, bs.Size()) + + state.LastBlockTime = time.Date(2020, 1, 1, 1, 0, 0, 0, time.UTC) + state.LastBlockHeight = 1500 + + state.ConsensusParams.Evidence.MaxAgeNumBlocks = 400 + state.ConsensusParams.Evidence.MaxAgeDuration = 1 * time.Second + + // Check that basic pruning works + pruned, evidenceRetainHeight, err := bs.PruneBlocks(1200, state) + require.NoError(t, err) + assert.EqualValues(t, 1199, pruned) + assert.EqualValues(t, 1200, bs.Base()) + assert.EqualValues(t, 1500, bs.Height()) + assert.EqualValues(t, 301, bs.Size()) + assert.EqualValues(t, 1100, evidenceRetainHeight) + + require.NotNil(t, bs.LoadBlock(1200)) + require.Nil(t, bs.LoadBlock(1199)) + + // The header and commit for heights 1100 onwards + // need to remain to verify evidence + require.NotNil(t, bs.LoadBlockMeta(1100)) + require.Nil(t, bs.LoadBlockMeta(1099)) + require.NotNil(t, bs.LoadBlockCommit(1100)) + require.NotNil(t, bs.LoadBlockExtendedCommit(1100)) + // check for pruning + require.Nil(t, bs.LoadBlockCommit(1099)) + require.Nil(t, bs.LoadBlockExtendedCommit(1099)) + + for i := int64(1); i < 1200; i++ { + require.Nil(t, bs.LoadBlock(i)) + } + for i := int64(1200); i <= 1500; i++ { + require.NotNil(t, bs.LoadBlock(i)) + } + + // Pruning below the current base should error + _, _, err = bs.PruneBlocks(1199, state) + require.Error(t, err) + + // Pruning to the current base should work + pruned, _, err = bs.PruneBlocks(1200, state) + require.NoError(t, err) + assert.EqualValues(t, 0, pruned) + + // Pruning again should work + pruned, _, err = bs.PruneBlocks(1300, state) + require.NoError(t, err) + assert.EqualValues(t, 100, pruned) + assert.EqualValues(t, 1300, bs.Base()) + + // we should still have the header and the commit + // as they're needed for evidence + require.NotNil(t, bs.LoadBlockMeta(1100)) + require.Nil(t, bs.LoadBlockMeta(1099)) + require.NotNil(t, bs.LoadBlockCommit(1100)) + require.NotNil(t, bs.LoadBlockExtendedCommit(1100)) + // check for pruning + require.Nil(t, bs.LoadBlockCommit(1099)) + require.Nil(t, bs.LoadBlockExtendedCommit(1099)) + + // Pruning beyond the current height should error + _, _, err = bs.PruneBlocks(1501, state) + require.Error(t, err) + + // Pruning to the current height should work + pruned, _, err = bs.PruneBlocks(1500, state) + require.NoError(t, err) + assert.EqualValues(t, 200, pruned) + assert.Nil(t, bs.LoadBlock(1499)) + assert.NotNil(t, bs.LoadBlock(1500)) + assert.Nil(t, bs.LoadBlock(1501)) +} + +func TestLoadBlockMeta(t *testing.T) { + bs, db := newInMemoryBlockStore() + height := int64(10) + loadMeta := func() (interface{}, error) { + meta := bs.LoadBlockMeta(height) + return meta, nil + } + + // Initially no contents. + // 1. Requesting for a non-existent blockMeta shouldn't fail + res, _, panicErr := doFn(loadMeta) + require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic") + require.Nil(t, res, "a non-existent blockMeta should return nil") + + // 2. Next save a corrupted blockMeta then try to load it + err := db.Set(calcBlockMetaKey(height), []byte("CometBFT-Meta")) + require.NoError(t, err) + res, _, panicErr = doFn(loadMeta) + require.NotNil(t, panicErr, "expecting a non-nil panic") + require.Contains(t, panicErr.Error(), "unmarshal to cmtproto.BlockMeta") + + // 3. A good blockMeta serialized and saved to the DB should be retrievable + meta := &types.BlockMeta{Header: types.Header{ + Version: cmtversion.Consensus{ + Block: version.BlockProtocol, App: 0, + }, Height: 1, ProposerAddress: cmtrand.Bytes(crypto.AddressSize), + }} + pbm := meta.ToProto() + err = db.Set(calcBlockMetaKey(height), mustEncode(pbm)) + require.NoError(t, err) + gotMeta, _, panicErr := doFn(loadMeta) + require.Nil(t, panicErr, "an existent and proper block should not panic") + require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ") + pbmeta := meta.ToProto() + if gmeta, ok := gotMeta.(*types.BlockMeta); ok { + pbgotMeta := gmeta.ToProto() + require.Equal(t, mustEncode(pbmeta), mustEncode(pbgotMeta), + "expecting successful retrieval of previously saved blockMeta") + } +} + +func TestLoadBlockMetaByHash(t *testing.T) { + config := test.ResetTestRoot("blockchain_reactor_test") + defer os.RemoveAll(config.RootDir) + stateStore := sm.NewStore(dbm.NewMemDB(), sm.StoreOptions{ + DiscardABCIResponses: false, + }) + state, err := stateStore.LoadFromDBOrGenesisFile(config.GenesisFile()) + require.NoError(t, err) + bs := NewBlockStore(dbm.NewMemDB()) + + b1, err := state.MakeBlock(state.LastBlockHeight+1, test.MakeNTxs(state.LastBlockHeight+1, 10), new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + partSet, err := b1.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + seenCommit := makeTestExtCommit(1, cmttime.Now()) + bs.SaveBlock(b1, partSet, seenCommit.ToCommit()) + + baseBlock := bs.LoadBlockMetaByHash(b1.Hash()) + assert.EqualValues(t, b1.Height, baseBlock.Header.Height) + assert.EqualValues(t, b1.LastBlockID, baseBlock.Header.LastBlockID) + assert.EqualValues(t, b1.ChainID, baseBlock.Header.ChainID) +} + +func TestBlockFetchAtHeight(t *testing.T) { + state, bs, cleanup := makeStateAndBlockStore() + defer cleanup() + require.Equal(t, bs.Height(), int64(0), "initially the height should be zero") + block, err := state.MakeBlock(bs.Height()+1, nil, new(types.Commit), nil, state.Validators.GetProposer().Address) + require.NoError(t, err) + + partSet, err := block.MakePartSet(types.BlockPartSizeBytes) + require.NoError(t, err) + seenCommit := makeTestExtCommit(block.Height, cmttime.Now()) + bs.SaveBlockWithExtendedCommit(block, partSet, seenCommit) + require.Equal(t, bs.Height(), block.Height, "expecting the new height to be changed") + + blockAtHeight := bs.LoadBlock(bs.Height()) + b1, err := block.ToProto() + require.NoError(t, err) + b2, err := blockAtHeight.ToProto() + require.NoError(t, err) + bz1 := mustEncode(b1) + bz2 := mustEncode(b2) + require.Equal(t, bz1, bz2) + require.Equal(t, block.Hash(), blockAtHeight.Hash(), + "expecting a successful load of the last saved block") + + blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1) + require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1") + blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2) + require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2") +} + +func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) { + defer func() { + if r := recover(); r != nil { + switch e := r.(type) { + case error: + panicErr = e + case string: + panicErr = fmt.Errorf("%s", e) + default: + if st, ok := r.(fmt.Stringer); ok { + panicErr = fmt.Errorf("%s", st) + } else { + panicErr = fmt.Errorf("%s", debug.Stack()) + } + } + } + }() + + res, err = fn() + return res, err, panicErr +} + +func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block { + return &types.Block{ + Header: hdr, + LastCommit: lastCommit, + } +} diff --git a/test/README.md b/test/README.md new file mode 100644 index 0000000..aaff687 --- /dev/null +++ b/test/README.md @@ -0,0 +1,20 @@ +# CometBFT Tests + +The unit tests (ie. the `go test` s) can be run with `make test`. +The integration tests can be run with `make test_integrations`. + +Running the integrations test will build a docker container with local version of CometBFT +and run the following tests in docker containers: + +- go tests, with --race + - includes test coverage +- app tests + - kvstore app over socket +- persistence tests + - crash cometbft at each of many predefined points, restart, and ensure it syncs properly with the app + +## Fuzzing + +[Fuzzing](https://en.wikipedia.org/wiki/Fuzzing) of various system inputs. + +See `./fuzz/README.md` for more details. diff --git a/test/app/clean.sh b/test/app/clean.sh new file mode 100755 index 0000000..9b58f26 --- /dev/null +++ b/test/app/clean.sh @@ -0,0 +1,3 @@ +killall cometbft +killall abci-cli +rm -rf ~/.cometbft_app diff --git a/test/app/counter_test.sh b/test/app/counter_test.sh new file mode 100755 index 0000000..6665924 --- /dev/null +++ b/test/app/counter_test.sh @@ -0,0 +1,143 @@ +#! /bin/bash + +export GO111MODULE=on + +if [[ "$GRPC_BROADCAST_TX" == "" ]]; then + GRPC_BROADCAST_TX="" +fi + +set -u + +##################### +# counter over socket +##################### +TESTNAME=$1 + +# Send some txs + +function getCode() { + set +u + R=$1 + set -u + if [[ "$R" == "" ]]; then + echo -1 + fi + + if [[ $(echo $R | jq 'has("code")') == "true" ]]; then + # this wont actually work if theres an error ... + echo "$R" | jq ".code" + else + # protobuf auto adds `omitempty` to everything so code OK and empty data/log + # will not even show when marshalled into json + # apparently we can use github.com/golang/protobuf/jsonpb to do the marshalling ... + echo 0 + fi +} + +# build grpc client if needed +if [[ "$GRPC_BROADCAST_TX" != "" ]]; then + if [ -f test/app/grpc_client ]; then + rm test/app/grpc_client + fi + echo "... building grpc_client" + go build -mod=readonly -o test/app/grpc_client test/app/grpc_client.go +fi + +function sendTx() { + TX=$1 + set +u + SHOULD_ERR=$2 + if [ "$SHOULD_ERR" == "" ]; then + SHOULD_ERR=false + fi + set -u + if [[ "$GRPC_BROADCAST_TX" == "" ]]; then + RESPONSE=$(curl -s localhost:26657/broadcast_tx_commit?tx=0x"$TX") + IS_ERR=$(echo "$RESPONSE" | jq 'has("error")') + ERROR=$(echo "$RESPONSE" | jq '.error') + ERROR=$(echo "$ERROR" | tr -d '"') # remove surrounding quotes + + RESPONSE=$(echo "$RESPONSE" | jq '.result') + else + RESPONSE=$(./test/app/grpc_client "$TX") + IS_ERR=false + ERROR="" + fi + + echo "RESPONSE" + echo "$RESPONSE" + + echo "$RESPONSE" | jq . &> /dev/null + IS_JSON=$? + if [[ "$IS_JSON" != "0" ]]; then + IS_ERR=true + ERROR="$RESPONSE" + fi + APPEND_TX_RESPONSE=$(echo "$RESPONSE" | jq '.deliver_tx') + APPEND_TX_CODE=$(getCode "$APPEND_TX_RESPONSE") + CHECK_TX_RESPONSE=$(echo "$RESPONSE" | jq '.check_tx') + CHECK_TX_CODE=$(getCode "$CHECK_TX_RESPONSE") + + echo "-------" + echo "TX $TX" + echo "RESPONSE $RESPONSE" + echo "ERROR $ERROR" + echo "IS_ERR $IS_ERR" + echo "----" + + if $SHOULD_ERR; then + if [[ "$IS_ERR" != "true" ]]; then + echo "Expected error sending tx ($TX)" + exit 1 + fi + else + if [[ "$IS_ERR" == "true" ]]; then + echo "Unexpected error sending tx ($TX)" + exit 1 + fi + + fi +} + +echo "... sending tx. expect no error" + +# 0 should pass once and get in block, with no error +TX=00 +sendTx $TX +if [[ $APPEND_TX_CODE != 0 ]]; then + echo "Got non-zero exit code for $TX. $RESPONSE" + exit 1 +fi + + +echo "... sending tx. expect error" + +# second time should get rejected by the mempool (return error and non-zero code) +sendTx $TX true + + +echo "... sending tx. expect no error" + +# now, TX=01 should pass, with no error +TX=01 +sendTx $TX +if [[ $APPEND_TX_CODE != 0 ]]; then + echo "Got non-zero exit code for $TX. $RESPONSE" + exit 1 +fi + +echo "... sending tx. expect no error, but invalid" + +# now, TX=03 should get in a block (passes CheckTx, no error), but is invalid +TX=03 +sendTx $TX +if [[ "$CHECK_TX_CODE" != 0 ]]; then + echo "Got non-zero exit code for checktx on $TX. $RESPONSE" + exit 1 +fi +if [[ $APPEND_TX_CODE == 0 ]]; then + echo "Got zero exit code for $TX. Should have been bad nonce. $RESPONSE" + exit 1 +fi + +echo "Passed Test: $TESTNAME" diff --git a/test/app/grpc_client.go b/test/app/grpc_client.go new file mode 100644 index 0000000..48636bb --- /dev/null +++ b/test/app/grpc_client.go @@ -0,0 +1,42 @@ +package main + +import ( + "context" + "encoding/hex" + "fmt" + "os" + + cmtjson "github.com/cometbft/cometbft/libs/json" + coregrpc "github.com/cometbft/cometbft/rpc/grpc" +) + +var grpcAddr = "tcp://localhost:36656" + +func main() { + args := os.Args + if len(args) == 1 { + fmt.Println("Must enter a transaction to send (hex)") + os.Exit(1) + } + tx := args[1] + txBytes, err := hex.DecodeString(tx) + if err != nil { + fmt.Println("Invalid hex", err) + os.Exit(1) + } + + //nolint:staticcheck // SA1019: core_grpc.StartGRPCClient is deprecated: A new gRPC API will be introduced after v0.38. + clientGRPC := coregrpc.StartGRPCClient(grpcAddr) + res, err := clientGRPC.BroadcastTx(context.Background(), &coregrpc.RequestBroadcastTx{Tx: txBytes}) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + bz, err := cmtjson.Marshal(res) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + fmt.Println(string(bz)) +} diff --git a/test/app/kvstore_test.sh b/test/app/kvstore_test.sh new file mode 100755 index 0000000..89e5894 --- /dev/null +++ b/test/app/kvstore_test.sh @@ -0,0 +1,84 @@ +#! /bin/bash +set -ex + +function toHex() { + echo -n $1 | hexdump -ve '1/1 "%.2X"' | awk '{print "0x" $0}' + +} + +##################### +# kvstore with curl +##################### +TESTNAME=$1 + +# store key value pair +KEY="abcd" +VALUE="dcba" +echo $(toHex $KEY=$VALUE) +curl -s 127.0.0.1:26657/broadcast_tx_commit?tx=$(toHex $KEY=$VALUE) +echo $? +echo "" + + +########################### +# test using the abci-cli +########################### + +echo "... testing query with abci-cli" + +# we should be able to look up the key +RESPONSE=`abci-cli query \"$KEY\"` + +set +e +A=`echo $RESPONSE | grep "$VALUE"` +if [[ $? != 0 ]]; then + echo "Failed to find $VALUE for $KEY. Response:" + echo "$RESPONSE" + exit 1 +fi +set -e + +# we should not be able to look up the value +RESPONSE=`abci-cli query \"$VALUE\"` +set +e +A=`echo $RESPONSE | grep \"value: $VALUE\"` +if [[ $? == 0 ]]; then + echo "Found '$VALUE' for $VALUE when we should not have. Response:" + echo "$RESPONSE" + exit 1 +fi +set -e + +############################# +# test using the /abci_query +############################# + +echo "... testing query with /abci_query 2" + +# we should be able to look up the key +RESPONSE=`curl -s "127.0.0.1:26657/abci_query?path=\"\"&data=$(toHex $KEY)&prove=false"` +RESPONSE=`echo $RESPONSE | jq .result.response.log` + +set +e +A=`echo $RESPONSE | grep 'exists'` +if [[ $? != 0 ]]; then + echo "Failed to find 'exists' for $KEY. Response:" + echo "$RESPONSE" + exit 1 +fi +set -e + +# we should not be able to look up the value +RESPONSE=`curl -s "127.0.0.1:26657/abci_query?path=\"\"&data=$(toHex $VALUE)&prove=false"` +RESPONSE=`echo $RESPONSE | jq .result.response.log` +set +e +A=`echo $RESPONSE | grep 'exists'` +if [[ $? == 0 ]]; then + echo "Found 'exists' for $VALUE when we should not have. Response:" + echo "$RESPONSE" + exit 1 +fi +set -e + + +echo "Passed Test: $TESTNAME" diff --git a/test/app/test.sh b/test/app/test.sh new file mode 100755 index 0000000..de07c44 --- /dev/null +++ b/test/app/test.sh @@ -0,0 +1,58 @@ +#! /bin/bash +set -ex + +#- kvstore over socket, curl + +# TODO: install everything + +export PATH="$GOBIN:$PATH" +export CMTHOME=$HOME/.cometbft_app + +function kvstore_over_socket(){ + rm -rf $CMTHOME + cometbft init + echo "Starting kvstore_over_socket" + abci-cli kvstore > /dev/null & + pid_kvstore=$! + cometbft node > cometbft.log & + pid_cometbft=$! + sleep 5 + + echo "running test" + bash test/app/kvstore_test.sh "KVStore over Socket" + + kill -9 $pid_kvstore $pid_cometbft +} + +# start cometbft first +function kvstore_over_socket_reorder(){ + rm -rf $CMTHOME + cometbft init + echo "Starting kvstore_over_socket_reorder (ie. start cometbft first)" + cometbft node > cometbft.log & + pid_cometbft=$! + sleep 2 + abci-cli kvstore > /dev/null & + pid_kvstore=$! + sleep 5 + + echo "running test" + bash test/app/kvstore_test.sh "KVStore over Socket" + + kill -9 $pid_kvstore $pid_cometbft +} + +case "$1" in + "kvstore_over_socket") + kvstore_over_socket + ;; +"kvstore_over_socket_reorder") + kvstore_over_socket_reorder + ;; +*) + echo "Running all" + kvstore_over_socket + echo "" + kvstore_over_socket_reorder + echo "" +esac diff --git a/test/docker/Dockerfile b/test/docker/Dockerfile new file mode 100644 index 0000000..b416949 --- /dev/null +++ b/test/docker/Dockerfile @@ -0,0 +1,54 @@ +FROM golang:1.22 + +# Avoid interactive prompts during apt operations +ENV DEBIAN_FRONTEND=noninteractive + +# Grab deps (jq, hexdump, xxd, killall) +# - hexdump lives in bsdextrautils on bookworm +# - xxd is available as its own package (no need for vim-common) +# - netcat is virtual; pick netcat-openbsd +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + jq \ + bsdextrautils \ + xxd \ + psmisc \ + netcat-openbsd \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Setup CometBFT repo +ENV REPO=$GOPATH/src/github.com/cometbft/cometbft +ENV GOBIN=$GOPATH/bin +WORKDIR $REPO + +# (Optional cache boost) copy mod files first for better go mod caching +# Comment these two lines out if they don't exist in your tree +COPY go.mod go.sum ./ +RUN go mod download || true + +# Copy in the code +COPY . $REPO + +# install ABCI CLI +RUN make install_abci + +# install CometBFT +RUN make install + +RUN cometbft testnet \ + --config $REPO/test/docker/config-template.toml \ + --node-dir-prefix="mach" \ + --v=4 \ + --populate-persistent-peers=false \ + --o=$REPO/test/p2p/data + +# Now copy in the code +# NOTE: this will overwrite whatever is in vendor/ +COPY . $REPO + +# expose the volume for debugging +VOLUME $REPO + +EXPOSE 26656 +EXPOSE 26657 diff --git a/test/docker/build.sh b/test/docker/build.sh new file mode 100644 index 0000000..7e1efb7 --- /dev/null +++ b/test/docker/build.sh @@ -0,0 +1,3 @@ +#! /bin/bash + +docker build -t tester -f ./test/docker/Dockerfile . diff --git a/test/docker/config-template.toml b/test/docker/config-template.toml new file mode 100644 index 0000000..669e5fd --- /dev/null +++ b/test/docker/config-template.toml @@ -0,0 +1,2 @@ +[rpc] +laddr = "tcp://0.0.0.0:26657" diff --git a/test/e2e/Makefile b/test/e2e/Makefile new file mode 100644 index 0000000..8a63e06 --- /dev/null +++ b/test/e2e/Makefile @@ -0,0 +1,25 @@ +COMETBFT_BUILD_OPTIONS += badgerdb,boltdb,cleveldb,rocksdb + +include ../../common.mk + +all: docker generator runner + +docker: + @echo "Building E2E Docker image" + @docker build \ + --tag cometbft/e2e-node:local-version \ + -f docker/Dockerfile ../.. + +# We need to build support for database backends into the app in +# order to build a binary with a CometBFT node in it (for built-in +# ABCI testing). +node: + go build -race $(BUILD_FLAGS) -tags '$(BUILD_TAGS)' -o build/node ./node + +generator: + go build -o build/generator ./generator + +runner: + go build -o build/runner ./runner + +.PHONY: all node docker generator runner diff --git a/test/e2e/README.md b/test/e2e/README.md new file mode 100644 index 0000000..6a83080 --- /dev/null +++ b/test/e2e/README.md @@ -0,0 +1,219 @@ +# End-to-End Tests + +Spins up and tests CometBFT networks in Docker Compose based on a testnet manifest. To run the CI testnet: + +```sh +make +./build/runner -f networks/ci.toml +``` + +This creates and runs a testnet named `ci` under `networks/ci/`. + +## Conceptual Overview + +End-to-end testnets are used to test Tendermint functionality as a user would use it, by spinning up a set of nodes with various configurations and making sure the nodes and network behave correctly. The background for the E2E test suite is outlined in [RFC-001](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-066-e2e-testing.md). + +The end-to-end tests can be thought of in this manner: + +1. Does a certain (valid!) testnet configuration result in a block-producing network where all nodes eventually reach the latest height? + +2. If so, does each node in that network satisfy all invariants specified by the Go E2E tests? + +The above should hold for any arbitrary, valid network configuration, and that configuration space should be searched and tested by randomly generating testnets. + +A testnet configuration is specified as a TOML testnet manifest (see below). The testnet runner uses the manifest to configure a set of Docker containers and start them in some order. The manifests can be written manually (to test specific configurations) or generated randomly by the testnet generator (to test a wide range of configuration permutations). + +When running a testnet, the runner will first start the Docker nodes in some sequence, submit random transactions, and wait for the nodes to come online and the first blocks to be produced. This may involve e.g. waiting for nodes to block sync and/or state sync. If specified, it will then run any misbehaviors (e.g. double-signing) and perturbations (e.g. killing or disconnecting nodes). It then waits for the testnet to stabilize, with all nodes online and having reached the latest height. + +Once the testnet stabilizes, a set of Go end-to-end tests are run against the live testnet to verify network invariants (for example that blocks are identical across nodes). These use the RPC client to interact with the network, and should consider the entire network as a black box (i.e. it should not test any network or node internals, only externally visible behavior via RPC). The tests may use the `testNode()` helper to run parallel tests against each individual testnet node, and/or inspect the full blockchain history via `fetchBlockChain()`. + +The tests must take into account the network and/or node configuration, and tolerate that the network is still live and producing blocks. For example, validator tests should only run against nodes that are actually validators, and take into account the node's block retention and/or state sync configuration to not query blocks that don't exist. + +## Testnet Manifests + +Testnets are specified as TOML manifests. For an example see [`networks/ci.toml`](networks/ci.toml), and for documentation see [`pkg/manifest.go`](pkg/manifest.go). + +## Random Testnet Generation + +Random (but deterministic) combinations of testnets can be generated with `generator`: + +```sh +./build/generator -d networks/generated/ + +# Split networks into 8 groups (by filename) +./build/generator -g 8 -d networks/generated/ +``` + +Multiple testnets can be run with the `run-multiple.sh` script: + +```sh +./run-multiple.sh networks/generated/gen-group3-*.toml +``` + +Testnets running different versions of CometBFT can be generated by the +generator. For example: + +```sh +# Generate testnets randomly choosing between v0.34.21 (making up 1/3rd of the +# network) and v0.34.22 (making up 2/3rds of the network). +./build/generator -m "v0.34.21:1,v0.34.22:2" -d networks/generated/ + +# "local" refers to the current local code. The E2E node built from the local +# code will be run on 2/3rds of the network, whereas the v0.34.23 E2E node will +# be run on the remaining 1/3rd. +./build/generator -m "v0.34.23:1,local:2" -d networks/generated/ + +# Using "latest" will cause the generator to auto-detect the latest +# non-pre-release version tag in the current Git repository that is closest to +# the CometBFT version in the current local code (as specified in +# ../../version/version.go). +# +# In the example below, if the local version.TMCoreSemVer value is "v0.34.24", +# for example, and the latest official release is v0.34.23, then 1/3rd of the +# network will run v0.34.23 and the remaining 2/3rds will run the E2E node built +# from the local code. +./build/generator -m "latest:1,local:2" -d networks/generated/ +``` + +**NB**: The corresponding Docker images for the relevant versions of the E2E +node (the `cometbft/e2e-node` image) must be available on the local machine, +or via [Docker Hub](https://hub.docker.com/r/cometbft/e2e-node). + +Multiversion testnets can also perform uncoordinated upgrades. Nodes containing a +perturbation of type `upgrade` will upgrade to the target version specified in +testnet's attribute `upgrade_version` of the testnet manifest. +The generator generates this type of perturbation both on full nodes and on light nodes. +Perturbations of type `upgrade` are a noop if the node's version matches the +one in `upgrade_version`. + +## Test Stages + +The test runner has the following stages, which can also be executed explicitly by running `./build/runner -f `: + +* `setup`: generates configuration files. + +* `start`: starts Docker containers. + +* `load`: generates a transaction load against the testnet nodes. + +* `perturb`: runs any requested perturbations (e.g. node restarts or network disconnects). + +* `wait`: waits for a few blocks to be produced, and for all nodes to catch up to it. + +* `test`: runs test cases in `tests/` against all nodes in a running testnet. + +* `stop`: stops Docker containers. + +* `cleanup`: removes configuration files and Docker containers/networks. + +Auxiliary commands: + +* `logs`: outputs all node logs. + +* `tail`: tails (follows) node logs until canceled. + +## Tests + +Test cases are written as normal Go tests in `tests/`. They use a `testNode()` helper which executes each test as a parallel subtest for each node in the network. + +### Running Manual Tests + +To run tests manually, set the `E2E_MANIFEST` environment variable to the path of the testnet manifest (e.g. `networks/ci.toml`) and run them as normal, e.g.: + +```sh +./build/runner -f networks/ci.toml start +E2E_MANIFEST=networks/ci.toml go test -v ./tests/... +``` + +Optionally, `E2E_NODE` specifies the name of a single testnet node to test. + +These environment variables can also be specified in `tests/e2e_test.go` to run tests from an editor or IDE: + +```go +func init() { + // This can be used to manually specify a testnet manifest and/or node to + // run tests against. The testnet must have been started by the runner first. + os.Setenv("E2E_MANIFEST", "networks/ci.toml") + os.Setenv("E2E_NODE", "validator01") +} +``` + +### Debugging Failures + +If a command or test fails, the runner simply exits with an error message and +non-zero status code. The testnet is left running with data in the testnet +directory, and can be inspected with e.g. `docker ps`, `docker logs`, or +`./build/runner -f logs` or `tail`. To shut down and remove the +testnet, run `./build/runner -f cleanup`. + +If the standard `log_level` is not detailed enough (e.g. you want "debug" level +logging for certain modules), you can change it in the manifest file. + +Each node exposes a [pprof](https://golang.org/pkg/runtime/pprof/) server. To +find out the local port, run `docker port 6060 | awk -F: '{print +$2}'`. Then you may perform any queries supported by the pprof tool. Julia +Evans has a [great +post](https://jvns.ca/blog/2017/09/24/profiling-go-with-pprof/) on this +subject. + +```bash +export PORT=$(docker port full01 6060 | awk -F: '{print $2}') + +go tool pprof http://localhost:$PORT/debug/pprof/goroutine +go tool pprof http://localhost:$PORT/debug/pprof/heap +go tool pprof http://localhost:$PORT/debug/pprof/threadcreate +go tool pprof http://localhost:$PORT/debug/pprof/block +go tool pprof http://localhost:$PORT/debug/pprof/mutex +``` + +## Enabling IPv6 + +Docker does not enable IPv6 by default. To do so, enter the following in +`daemon.json` (or in the Docker for Mac UI under Preferences → Docker Engine): + +```json +{ + "ipv6": true, + "fixed-cidr-v6": "2001:db8:1::/64" +} +``` + +## Benchmarking Testnets + +It is also possible to run a simple benchmark on a testnet. This is done through the `benchmark` command. This manages the entire process: setting up the environment, starting the test net, waiting for a considerable amount of blocks to be used (currently 100), and then returning the following metrics from the sample of the blockchain: + +* Average time to produce a block +* Standard deviation of producing a block +* Minimum and maximum time to produce a block + +## Running Individual Nodes + +The E2E test harness is designed to run several nodes of varying configurations within docker. It is also possible to run a single node in the case of running larger, geographically-dispersed testnets. To run a single node you can either run: + +**Built-in** + +```bash +make node +cometbft init validator +CMTHOME=$HOME/.cometbft ./build/node ./node/built-in.toml +``` + +To make things simpler the e2e application can also be run in the `cometbft` binary +by running + +```bash +cometbft start --proxy-app e2e +``` + +However this won't offer the same level of configurability of the application. + +**Socket** + +```bash +make node +cometbft init validator +cometbft start +./build/node ./node.socket.toml +``` + +Check `node/config.go` to see how the settings of the test application can be tweaked. diff --git a/test/e2e/app/app.go b/test/e2e/app/app.go new file mode 100644 index 0000000..683cdee --- /dev/null +++ b/test/e2e/app/app.go @@ -0,0 +1,801 @@ +package app + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "math/rand" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/cometbft/cometbft/abci/example/kvstore" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/protoio" + cryptoproto "github.com/cometbft/cometbft/proto/tendermint/crypto" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttypes "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +const ( + appVersion = 1 + voteExtensionKey string = "extensionSum" + voteExtensionMaxVal int64 = 128 + prefixReservedKey string = "reservedTxKey_" + suffixChainID string = "ChainID" + suffixVoteExtHeight string = "VoteExtensionsHeight" + suffixInitialHeight string = "InitialHeight" +) + +// Application is an ABCI application for use by end-to-end tests. It is a +// simple key/value store for strings, storing data in memory and persisting +// to disk as JSON, taking state sync snapshots if requested. +type Application struct { + abci.BaseApplication + logger log.Logger + state *State + snapshots *SnapshotStore + cfg *Config + restoreSnapshot *abci.Snapshot + restoreChunks [][]byte +} + +// Config allows for the setting of high level parameters for running the e2e Application +// KeyType and ValidatorUpdates must be the same for all nodes running the same application. +type Config struct { + // The directory with which state.json will be persisted in. Usually $HOME/.cometbft/data + Dir string `toml:"dir"` + + // SnapshotInterval specifies the height interval at which the application + // will take state sync snapshots. Defaults to 0 (disabled). + SnapshotInterval uint64 `toml:"snapshot_interval"` + + // RetainBlocks specifies the number of recent blocks to retain. Defaults to + // 0, which retains all blocks. Must be greater that PersistInterval, + // SnapshotInterval and EvidenceAgeHeight. + RetainBlocks uint64 `toml:"retain_blocks"` + + // KeyType sets the curve that will be used by validators. + // Options are ed25519 & secp256k1 + KeyType string `toml:"key_type"` + + // PersistInterval specifies the height interval at which the application + // will persist state to disk. Defaults to 1 (every height), setting this to + // 0 disables state persistence. + PersistInterval uint64 `toml:"persist_interval"` + + // ValidatorUpdates is a map of heights to validator names and their power, + // and will be returned by the ABCI application. For example, the following + // changes the power of validator01 and validator02 at height 1000: + // + // [validator_update.1000] + // validator01 = 20 + // validator02 = 10 + // + // Specifying height 0 returns the validator update during InitChain. The + // application returns the validator updates as-is, i.e. removing a + // validator must be done by returning it with power 0, and any validators + // not specified are not changed. + // + // height <-> pubkey <-> voting power + ValidatorUpdates map[string]map[string]uint8 `toml:"validator_update"` + + // Add artificial delays to each of the main ABCI calls to mimic computation time + // of the application + PrepareProposalDelay time.Duration `toml:"prepare_proposal_delay"` + ProcessProposalDelay time.Duration `toml:"process_proposal_delay"` + CheckTxDelay time.Duration `toml:"check_tx_delay"` + FinalizeBlockDelay time.Duration `toml:"finalize_block_delay"` + VoteExtensionDelay time.Duration `toml:"vote_extension_delay"` + + // VoteExtensionsEnableHeight configures the first height during which + // the chain will use and require vote extension data to be present + // in precommit messages. + VoteExtensionsEnableHeight int64 `toml:"vote_extensions_enable_height"` + + // VoteExtensionsUpdateHeight configures the height at which consensus + // param VoteExtensionsEnableHeight will be set. + // -1 denotes it is set at genesis. + // 0 denotes it is set at InitChain. + VoteExtensionsUpdateHeight int64 `toml:"vote_extensions_update_height"` +} + +func DefaultConfig(dir string) *Config { + return &Config{ + PersistInterval: 1, + SnapshotInterval: 100, + Dir: dir, + } +} + +// NewApplication creates the application. +func NewApplication(cfg *Config) (*Application, error) { + state, err := NewState(cfg.Dir, cfg.PersistInterval) + if err != nil { + return nil, err + } + snapshots, err := NewSnapshotStore(filepath.Join(cfg.Dir, "snapshots")) + if err != nil { + return nil, err + } + return &Application{ + logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), + state: state, + snapshots: snapshots, + cfg: cfg, + }, nil +} + +// Info implements ABCI. +func (app *Application) Info(context.Context, *abci.RequestInfo) (*abci.ResponseInfo, error) { + height, hash := app.state.Info() + return &abci.ResponseInfo{ + Version: version.ABCIVersion, + AppVersion: appVersion, + LastBlockHeight: int64(height), + LastBlockAppHash: hash, + }, nil +} + +func (app *Application) updateVoteExtensionEnableHeight(currentHeight int64) *cmtproto.ConsensusParams { + var params *cmtproto.ConsensusParams + if app.cfg.VoteExtensionsUpdateHeight == currentHeight { + app.logger.Info("enabling vote extensions on the fly", + "current_height", currentHeight, + "enable_height", app.cfg.VoteExtensionsEnableHeight) + params = &cmtproto.ConsensusParams{ + Abci: &cmtproto.ABCIParams{ + VoteExtensionsEnableHeight: app.cfg.VoteExtensionsEnableHeight, + }, + } + app.logger.Info("updating VoteExtensionsHeight in app_state", "height", app.cfg.VoteExtensionsEnableHeight) + app.state.Set(prefixReservedKey+suffixVoteExtHeight, strconv.FormatInt(app.cfg.VoteExtensionsEnableHeight, 10)) + } + return params +} + +// Info implements ABCI. +func (app *Application) InitChain(_ context.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { + var err error + app.state.initialHeight = uint64(req.InitialHeight) + if len(req.AppStateBytes) > 0 { + err = app.state.Import(0, req.AppStateBytes) + if err != nil { + return nil, err + } + } + app.logger.Info("setting ChainID in app_state", "chainId", req.ChainId) + app.state.Set(prefixReservedKey+suffixChainID, req.ChainId) + app.logger.Info("setting VoteExtensionsHeight in app_state", "height", req.ConsensusParams.Abci.VoteExtensionsEnableHeight) + app.state.Set(prefixReservedKey+suffixVoteExtHeight, strconv.FormatInt(req.ConsensusParams.Abci.VoteExtensionsEnableHeight, 10)) + app.logger.Info("setting initial height in app_state", "initial_height", req.InitialHeight) + app.state.Set(prefixReservedKey+suffixInitialHeight, strconv.FormatInt(req.InitialHeight, 10)) + // Get validators from genesis + if req.Validators != nil { + for _, val := range req.Validators { + val := val + if err := app.storeValidator(&val); err != nil { + return nil, err + } + } + } + + params := app.updateVoteExtensionEnableHeight(0) + + resp := &abci.ResponseInitChain{ + ConsensusParams: params, + AppHash: app.state.GetHash(), + } + if resp.Validators, err = app.validatorUpdates(0); err != nil { + return nil, err + } + return resp, nil +} + +// CheckTx implements ABCI. +func (app *Application) CheckTx(_ context.Context, req *abci.RequestCheckTx) (*abci.ResponseCheckTx, error) { + key, _, err := parseTx(req.Tx) + if err != nil || key == prefixReservedKey { + return &abci.ResponseCheckTx{ + Code: kvstore.CodeTypeEncodingError, + Log: err.Error(), + }, nil + } + + if app.cfg.CheckTxDelay != 0 { + time.Sleep(app.cfg.CheckTxDelay) + } + + return &abci.ResponseCheckTx{Code: kvstore.CodeTypeOK, GasWanted: 1}, nil +} + +// FinalizeBlock implements ABCI. +func (app *Application) FinalizeBlock(_ context.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { + txs := make([]*abci.ExecTxResult, len(req.Txs)) + + for i, tx := range req.Txs { + key, value, err := parseTx(tx) + if err != nil { + panic(err) // shouldn't happen since we verified it in CheckTx and ProcessProposal + } + if key == prefixReservedKey { + panic(fmt.Errorf("detected a transaction with key %q; this key is reserved and should have been filtered out", prefixReservedKey)) + } + app.state.Set(key, value) + + txs[i] = &abci.ExecTxResult{Code: kvstore.CodeTypeOK} + } + + for _, ev := range req.Misbehavior { + app.logger.Info("Misbehavior. Slashing validator", + "validator_address", ev.GetValidator().Address, + "type", ev.GetType(), + "height", ev.GetHeight(), + "time", ev.GetTime(), + "total_voting_power", ev.GetTotalVotingPower(), + ) + } + + valUpdates, err := app.validatorUpdates(uint64(req.Height)) + if err != nil { + panic(err) + } + + params := app.updateVoteExtensionEnableHeight(req.Height) + + if app.cfg.FinalizeBlockDelay != 0 { + time.Sleep(app.cfg.FinalizeBlockDelay) + } + + return &abci.ResponseFinalizeBlock{ + TxResults: txs, + ValidatorUpdates: valUpdates, + AppHash: app.state.Finalize(), + ConsensusParamUpdates: params, + Events: []abci.Event{ + { + Type: "val_updates", + Attributes: []abci.EventAttribute{ + { + Key: "size", + Value: strconv.Itoa(valUpdates.Len()), + }, + { + Key: "height", + Value: strconv.Itoa(int(req.Height)), + }, + }, + }, + }, + }, nil +} + +// Commit implements ABCI. +func (app *Application) Commit(_ context.Context, _ *abci.RequestCommit) (*abci.ResponseCommit, error) { + height, err := app.state.Commit() + if err != nil { + panic(err) + } + if app.cfg.SnapshotInterval > 0 && height%app.cfg.SnapshotInterval == 0 { + snapshot, err := app.snapshots.Create(app.state) + if err != nil { + panic(err) + } + app.logger.Info("created state sync snapshot", "height", snapshot.Height) + err = app.snapshots.Prune(maxSnapshotCount) + if err != nil { + app.logger.Error("failed to prune snapshots", "err", err) + } + } + retainHeight := int64(0) + if app.cfg.RetainBlocks > 0 { + retainHeight = int64(height - app.cfg.RetainBlocks + 1) + } + return &abci.ResponseCommit{ + RetainHeight: retainHeight, + }, nil +} + +// Query implements ABCI. +func (app *Application) Query(_ context.Context, req *abci.RequestQuery) (*abci.ResponseQuery, error) { + value, height := app.state.Query(string(req.Data)) + return &abci.ResponseQuery{ + Height: int64(height), + Key: req.Data, + Value: []byte(value), + }, nil +} + +// ListSnapshots implements ABCI. +func (app *Application) ListSnapshots(context.Context, *abci.RequestListSnapshots) (*abci.ResponseListSnapshots, error) { + snapshots, err := app.snapshots.List() + if err != nil { + panic(err) + } + return &abci.ResponseListSnapshots{Snapshots: snapshots}, nil +} + +// LoadSnapshotChunk implements ABCI. +func (app *Application) LoadSnapshotChunk(_ context.Context, req *abci.RequestLoadSnapshotChunk) (*abci.ResponseLoadSnapshotChunk, error) { + chunk, err := app.snapshots.LoadChunk(req.Height, req.Format, req.Chunk) + if err != nil { + panic(err) + } + return &abci.ResponseLoadSnapshotChunk{Chunk: chunk}, nil +} + +// OfferSnapshot implements ABCI. +func (app *Application) OfferSnapshot(_ context.Context, req *abci.RequestOfferSnapshot) (*abci.ResponseOfferSnapshot, error) { + if app.restoreSnapshot != nil { + panic("A snapshot is already being restored") + } + app.restoreSnapshot = req.Snapshot + app.restoreChunks = [][]byte{} + return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}, nil +} + +// ApplySnapshotChunk implements ABCI. +func (app *Application) ApplySnapshotChunk(_ context.Context, req *abci.RequestApplySnapshotChunk) (*abci.ResponseApplySnapshotChunk, error) { + if app.restoreSnapshot == nil { + panic("No restore in progress") + } + app.restoreChunks = append(app.restoreChunks, req.Chunk) + if len(app.restoreChunks) == int(app.restoreSnapshot.Chunks) { + bz := []byte{} + for _, chunk := range app.restoreChunks { + bz = append(bz, chunk...) + } + err := app.state.Import(app.restoreSnapshot.Height, bz) + if err != nil { + panic(err) + } + app.restoreSnapshot = nil + app.restoreChunks = nil + } + return &abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil +} + +// PrepareProposal will take the given transactions and attempt to prepare a +// proposal from them when it's our turn to do so. If the current height has +// vote extension enabled, this method will use vote extensions from the previous +// height, passed from CometBFT as parameters to construct a special transaction +// whose value is the sum of all of the vote extensions from the previous round. +// +// Additionally, we verify the vote extension signatures passed from CometBFT and +// include all data necessary for such verification in the special transaction's +// payload so that ProcessProposal at other nodes can also verify the proposer +// constructed the special transaction correctly. +// +// If vote extensions are enabled for the current height, PrepareProposal makes +// sure there was at least one non-empty vote extension whose signature it could verify. +// If vote extensions are not enabled for the current height, PrepareProposal makes +// sure non-empty vote extensions are not present. +// +// The special vote extension-generated transaction must fit within an empty block +// and takes precedence over all other transactions coming from the mempool. +func (app *Application) PrepareProposal( + _ context.Context, req *abci.RequestPrepareProposal, +) (*abci.ResponsePrepareProposal, error) { + _, areExtensionsEnabled := app.checkHeightAndExtensions(true, req.Height, "PrepareProposal") + + txs := make([][]byte, 0, len(req.Txs)+1) + var totalBytes int64 + extTxPrefix := fmt.Sprintf("%s=", voteExtensionKey) + sum, err := app.verifyAndSum(areExtensionsEnabled, req.Height, &req.LocalLastCommit, "prepare_proposal") + if err != nil { + panic(fmt.Errorf("failed to sum and verify in PrepareProposal; err %w", err)) + } + if areExtensionsEnabled { + extCommitBytes, err := req.LocalLastCommit.Marshal() + if err != nil { + panic("unable to marshall extended commit") + } + extCommitHex := hex.EncodeToString(extCommitBytes) + extTx := []byte(fmt.Sprintf("%s%d|%s", extTxPrefix, sum, extCommitHex)) + extTxLen := cmttypes.ComputeProtoSizeForTxs([]cmttypes.Tx{extTx}) + app.logger.Info("preparing proposal with special transaction from vote extensions", "extTxLen", extTxLen) + if extTxLen > req.MaxTxBytes { + panic(fmt.Errorf("serious problem in the e2e app configuration; "+ + "the tx conveying the vote extension data does not fit in an empty block(%d > %d); "+ + "please review the app's configuration", + extTxLen, req.MaxTxBytes)) + } + txs = append(txs, extTx) + // Coherence: No need to call parseTx, as the check is stateless and has been performed by CheckTx + totalBytes = extTxLen + } + for _, tx := range req.Txs { + if areExtensionsEnabled && strings.HasPrefix(string(tx), extTxPrefix) { + // When vote extensions are enabled, our generated transaction takes precedence + // over any supplied transaction that attempts to modify the "extensionSum" value. + continue + } + if strings.HasPrefix(string(tx), prefixReservedKey) { + app.logger.Error("detected tx that should not come from the mempool", "tx", tx) + continue + } + txLen := cmttypes.ComputeProtoSizeForTxs([]cmttypes.Tx{tx}) + if totalBytes+txLen > req.MaxTxBytes { + break + } + totalBytes += txLen + // Coherence: No need to call parseTx, as the check is stateless and has been performed by CheckTx + txs = append(txs, tx) + } + + if app.cfg.PrepareProposalDelay != 0 { + time.Sleep(app.cfg.PrepareProposalDelay) + } + + return &abci.ResponsePrepareProposal{Txs: txs}, nil +} + +// ProcessProposal implements part of the Application interface. +// It accepts any proposal that does not contain a malformed transaction. +// NOTE It is up to real Applications to effect punitive behavior in the cases ProcessProposal +// returns ResponseProcessProposal_REJECT, as it is evidence of misbehavior. +func (app *Application) ProcessProposal(_ context.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { + _, areExtensionsEnabled := app.checkHeightAndExtensions(true, req.Height, "ProcessProposal") + + for _, tx := range req.Txs { + k, v, err := parseTx(tx) + if err != nil { + app.logger.Error("malformed transaction in ProcessProposal", "tx", tx, "err", err) + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + } + switch { + case areExtensionsEnabled && k == voteExtensionKey: + // Additional check for vote extension-related txs + if err := app.verifyExtensionTx(req.Height, v); err != nil { + app.logger.Error("vote extension transaction failed verification, rejecting proposal", k, v, "err", err) + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + } + case strings.HasPrefix(k, prefixReservedKey): + app.logger.Error("key prefix %q is reserved and cannot be used in transactions, rejecting proposal", k) + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + } + } + + if app.cfg.ProcessProposalDelay != 0 { + time.Sleep(app.cfg.ProcessProposalDelay) + } + + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil +} + +// ExtendVote will produce vote extensions in the form of random numbers to +// demonstrate vote extension nondeterminism. +// +// In the next block, if there are any vote extensions from the previous block, +// a new transaction will be proposed that updates a special value in the +// key/value store ("extensionSum") with the sum of all of the numbers collected +// from the vote extensions. +func (app *Application) ExtendVote(_ context.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + appHeight, areExtensionsEnabled := app.checkHeightAndExtensions(false, req.Height, "ExtendVote") + if !areExtensionsEnabled { + panic(fmt.Errorf("received call to ExtendVote at height %d, when vote extensions are disabled", appHeight)) + } + + ext := make([]byte, binary.MaxVarintLen64) + // We don't care that these values are generated by a weak random number + // generator. It's just for test purposes. + //nolint:gosec // G404: Use of weak random number generator + num := rand.Int63n(voteExtensionMaxVal) + extLen := binary.PutVarint(ext, num) + + if app.cfg.VoteExtensionDelay != 0 { + time.Sleep(app.cfg.VoteExtensionDelay) + } + + app.logger.Info("generated vote extension", "num", num, "ext", fmt.Sprintf("%x", ext[:extLen]), "height", appHeight) + return &abci.ResponseExtendVote{ + VoteExtension: ext[:extLen], + }, nil +} + +// VerifyVoteExtension simply validates vote extensions from other validators +// without doing anything about them. In this case, it just makes sure that the +// vote extension is a well-formed integer value. +func (app *Application) VerifyVoteExtension(_ context.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + appHeight, areExtensionsEnabled := app.checkHeightAndExtensions(false, req.Height, "VerifyVoteExtension") + if !areExtensionsEnabled { + panic(fmt.Errorf("received call to VerifyVoteExtension at height %d, when vote extensions are disabled", appHeight)) + } + // We don't allow vote extensions to be optional + if len(req.VoteExtension) == 0 { + app.logger.Error("received empty vote extension") + return &abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_REJECT, + }, nil + } + + num, err := parseVoteExtension(req.VoteExtension) + if err != nil { + app.logger.Error("failed to parse vote extension", "vote_extension", req.VoteExtension, "err", err) + return &abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_REJECT, + }, nil + } + + if app.cfg.VoteExtensionDelay != 0 { + time.Sleep(app.cfg.VoteExtensionDelay) + } + + app.logger.Info("verified vote extension value", "height", req.Height, "vote_extension", req.VoteExtension, "num", num) + return &abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT, + }, nil +} + +func (app *Application) Rollback() error { + return app.state.Rollback() +} + +func (app *Application) getAppHeight() int64 { + initialHeightStr, height := app.state.Query(prefixReservedKey + suffixInitialHeight) + if len(initialHeightStr) == 0 { + panic("initial height not set in database") + } + initialHeight, err := strconv.ParseInt(initialHeightStr, 10, 64) + if err != nil { + panic(fmt.Errorf("malformed initial height %q in database", initialHeightStr)) + } + + appHeight := int64(height) + if appHeight == 0 { + appHeight = initialHeight - 1 + } + return appHeight + 1 +} + +func (app *Application) checkHeightAndExtensions(isPrepareProcessProposal bool, height int64, callsite string) (int64, bool) { + appHeight := app.getAppHeight() + if height != appHeight { + panic(fmt.Errorf( + "got unexpected height in %s request; expected %d, actual %d", + callsite, appHeight, height, + )) + } + + voteExtHeightStr := app.state.Get(prefixReservedKey + suffixVoteExtHeight) + if len(voteExtHeightStr) == 0 { + panic("vote extension height not set in database") + } + voteExtHeight, err := strconv.ParseInt(voteExtHeightStr, 10, 64) + if err != nil { + panic(fmt.Errorf("malformed vote extension height %q in database", voteExtHeightStr)) + } + currentHeight := appHeight + if isPrepareProcessProposal { + currentHeight-- // at exactly voteExtHeight, PrepareProposal still has no extensions, see RFC100 + } + + return appHeight, voteExtHeight != 0 && currentHeight >= voteExtHeight +} + +func (app *Application) storeValidator(valUpdate *abci.ValidatorUpdate) error { + // Store validator data to verify extensions + pubKey, err := cryptoenc.PubKeyFromProto(valUpdate.PubKey) + if err != nil { + return err + } + addr := pubKey.Address().String() + if valUpdate.Power > 0 { + pubKeyBytes, err := valUpdate.PubKey.Marshal() + if err != nil { + return err + } + app.logger.Info("setting validator in app_state", "addr", addr) + app.state.Set(prefixReservedKey+addr, hex.EncodeToString(pubKeyBytes)) + } + return nil +} + +// validatorUpdates generates a validator set update. +func (app *Application) validatorUpdates(height uint64) (abci.ValidatorUpdates, error) { + updates := app.cfg.ValidatorUpdates[fmt.Sprintf("%v", height)] + if len(updates) == 0 { + return nil, nil + } + + valUpdates := abci.ValidatorUpdates{} + for keyString, power := range updates { + + keyBytes, err := base64.StdEncoding.DecodeString(keyString) + if err != nil { + return nil, fmt.Errorf("invalid base64 pubkey value %q: %w", keyString, err) + } + valUpdate := abci.UpdateValidator(keyBytes, int64(power), app.cfg.KeyType) + valUpdates = append(valUpdates, valUpdate) + if err := app.storeValidator(&valUpdate); err != nil { + return nil, err + } + } + return valUpdates, nil +} + +// parseTx parses a tx in 'key=value' format into a key and value. +func parseTx(tx []byte) (string, string, error) { + parts := bytes.Split(tx, []byte("=")) + if len(parts) != 2 { + return "", "", fmt.Errorf("invalid tx format: %q", string(tx)) + } + if len(parts[0]) == 0 { + return "", "", errors.New("key cannot be empty") + } + return string(parts[0]), string(parts[1]), nil +} + +func (app *Application) verifyAndSum( + areExtensionsEnabled bool, + currentHeight int64, + extCommit *abci.ExtendedCommitInfo, + callsite string, +) (int64, error) { + var sum int64 + var extCount int + for _, vote := range extCommit.Votes { + if vote.BlockIdFlag == cmtproto.BlockIDFlagUnknown || vote.BlockIdFlag > cmtproto.BlockIDFlagNil { + return 0, fmt.Errorf("vote with bad blockID flag value at height %d; blockID flag %d", currentHeight, vote.BlockIdFlag) + } + if vote.BlockIdFlag == cmtproto.BlockIDFlagAbsent || vote.BlockIdFlag == cmtproto.BlockIDFlagNil { + if len(vote.VoteExtension) != 0 { + return 0, fmt.Errorf("non-empty vote extension at height %d, for a vote with blockID flag %d", + currentHeight, vote.BlockIdFlag) + } + if len(vote.ExtensionSignature) != 0 { + return 0, fmt.Errorf("non-empty vote extension signature at height %d, for a vote with blockID flag %d", + currentHeight, vote.BlockIdFlag) + } + // Only interested in votes that can have extensions + continue + } + if !areExtensionsEnabled { + if len(vote.VoteExtension) != 0 { + return 0, fmt.Errorf("non-empty vote extension at height %d, which has extensions disabled", + currentHeight) + } + if len(vote.ExtensionSignature) != 0 { + return 0, fmt.Errorf("non-empty vote extension signature at height %d, which has extensions disabled", + currentHeight) + } + continue + } + if len(vote.VoteExtension) == 0 { + return 0, fmt.Errorf("received empty vote extension from %X at height %d (extensions enabled); "+ + "e2e app's logic does not allow it", vote.Validator, currentHeight) + } + // Vote extension signatures are always provided. Apps can use them to verify the integrity of extensions + if len(vote.ExtensionSignature) == 0 { + return 0, fmt.Errorf("empty vote extension signature at height %d (extensions enabled)", currentHeight) + } + + // Reconstruct vote extension's signed bytes... + chainID := app.state.Get(prefixReservedKey + suffixChainID) + if len(chainID) == 0 { + panic("chainID not set in database") + } + cve := cmtproto.CanonicalVoteExtension{ + Extension: vote.VoteExtension, + Height: currentHeight - 1, // the vote extension was signed in the previous height + Round: int64(extCommit.Round), + ChainId: chainID, + } + extSignBytes, err := protoio.MarshalDelimited(&cve) + if err != nil { + return 0, fmt.Errorf("error when marshaling signed bytes: %w", err) + } + + //... and verify + valAddr := crypto.Address(vote.Validator.Address).String() + pubKeyHex := app.state.Get(prefixReservedKey + valAddr) + if len(pubKeyHex) == 0 { + return 0, fmt.Errorf("received vote from unknown validator with address %q", valAddr) + } + pubKeyBytes, err := hex.DecodeString(pubKeyHex) + if err != nil { + return 0, fmt.Errorf("could not hex-decode public key for validator address %s, err %w", valAddr, err) + } + var pubKeyProto cryptoproto.PublicKey + err = pubKeyProto.Unmarshal(pubKeyBytes) + if err != nil { + return 0, fmt.Errorf("unable to unmarshal public key for validator address %s, err %w", valAddr, err) + } + pubKey, err := cryptoenc.PubKeyFromProto(pubKeyProto) + if err != nil { + return 0, fmt.Errorf("could not obtain a public key from its proto for validator address %s, err %w", valAddr, err) + } + if !pubKey.VerifySignature(extSignBytes, vote.ExtensionSignature) { + return 0, errors.New("received vote with invalid signature") + } + + extValue, err := parseVoteExtension(vote.VoteExtension) + // The extension's format should have been verified in VerifyVoteExtension + if err != nil { + return 0, fmt.Errorf("failed to parse vote extension: %w", err) + } + app.logger.Info( + "received and verified vote extension value", + "height", currentHeight, + "valAddr", valAddr, + "value", extValue, + "callsite", callsite, + ) + sum += extValue + extCount++ + } + + if areExtensionsEnabled && (extCount == 0) { + return 0, errors.New("bad extension data, at least one extended vote should be present when extensions are enabled") + } + return sum, nil +} + +// verifyExtensionTx parses and verifies the payload of a vote extension-generated tx +func (app *Application) verifyExtensionTx(height int64, payload string) error { + parts := strings.Split(payload, "|") + if len(parts) != 2 { + return fmt.Errorf("invalid payload format") + } + expSumStr := parts[0] + if len(expSumStr) == 0 { + return fmt.Errorf("sum cannot be empty in vote extension payload") + } + + expSum, err := strconv.Atoi(expSumStr) + if err != nil { + return fmt.Errorf("malformed sum %q in vote extension payload", expSumStr) + } + + extCommitHex := parts[1] + if len(extCommitHex) == 0 { + return fmt.Errorf("extended commit data cannot be empty in vote extension payload") + } + + extCommitBytes, err := hex.DecodeString(extCommitHex) + if err != nil { + return fmt.Errorf("could not hex-decode vote extension payload") + } + + var extCommit abci.ExtendedCommitInfo + if extCommit.Unmarshal(extCommitBytes) != nil { + return fmt.Errorf("unable to unmarshal extended commit") + } + + sum, err := app.verifyAndSum(true, height, &extCommit, "process_proposal") + if err != nil { + return fmt.Errorf("failed to sum and verify in process proposal: %w", err) + } + + // Final check that the proposer behaved correctly + if int64(expSum) != sum { + return fmt.Errorf("sum is not consistent with vote extension payload: %d!=%d", expSum, sum) + } + return nil +} + +// parseVoteExtension attempts to parse the given extension data into a positive +// integer value. +func parseVoteExtension(ext []byte) (int64, error) { + num, errVal := binary.Varint(ext) + if errVal == 0 { + return 0, errors.New("vote extension is too small to parse") + } + if errVal < 0 { + return 0, errors.New("vote extension value is too large") + } + if num >= voteExtensionMaxVal { + return 0, fmt.Errorf("vote extension value must be smaller than %d (was %d)", voteExtensionMaxVal, num) + } + return num, nil +} diff --git a/test/e2e/app/snapshots.go b/test/e2e/app/snapshots.go new file mode 100644 index 0000000..ac93e4d --- /dev/null +++ b/test/e2e/app/snapshots.go @@ -0,0 +1,174 @@ +package app + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "os" + "path/filepath" + "sync" + + abci "github.com/cometbft/cometbft/abci/types" +) + +const ( + snapshotChunkSize = 1e6 + + // Keep only the most recent 10 snapshots. Older snapshots are pruned + maxSnapshotCount = 10 +) + +// SnapshotStore stores state sync snapshots. Snapshots are stored simply as +// JSON files, and chunks are generated on-the-fly by splitting the JSON data +// into fixed-size chunks. +type SnapshotStore struct { + sync.RWMutex + dir string + metadata []abci.Snapshot +} + +// NewSnapshotStore creates a new snapshot store. +func NewSnapshotStore(dir string) (*SnapshotStore, error) { + store := &SnapshotStore{dir: dir} + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + if err := store.loadMetadata(); err != nil { + return nil, err + } + return store, nil +} + +// loadMetadata loads snapshot metadata. Does not take out locks, since it's +// called internally on construction. +func (s *SnapshotStore) loadMetadata() error { + file := filepath.Join(s.dir, "metadata.json") + metadata := []abci.Snapshot{} + + bz, err := os.ReadFile(file) + switch { + case errors.Is(err, os.ErrNotExist): + case err != nil: + return fmt.Errorf("failed to load snapshot metadata from %q: %w", file, err) + } + if len(bz) != 0 { + err = json.Unmarshal(bz, &metadata) + if err != nil { + return fmt.Errorf("invalid snapshot data in %q: %w", file, err) + } + } + s.metadata = metadata + return nil +} + +// saveMetadata saves snapshot metadata. Does not take out locks, since it's +// called internally from e.g. Create(). +func (s *SnapshotStore) saveMetadata() error { + bz, err := json.Marshal(s.metadata) + if err != nil { + return err + } + + // save the file to a new file and move it to make saving atomic. + newFile := filepath.Join(s.dir, "metadata.json.new") + file := filepath.Join(s.dir, "metadata.json") + err = os.WriteFile(newFile, bz, 0o644) //nolint: gosec + if err != nil { + return err + } + return os.Rename(newFile, file) +} + +// Create creates a snapshot of the given application state's key/value pairs. +func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) { + s.Lock() + defer s.Unlock() + bz, height, stateHash, err := state.Export() + if err != nil { + return abci.Snapshot{}, err + } + snapshot := abci.Snapshot{ + Height: height, + Format: 1, + Hash: stateHash, + Chunks: byteChunks(bz), + } + err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", height)), bz, 0o644) //nolint:gosec + if err != nil { + return abci.Snapshot{}, err + } + s.metadata = append(s.metadata, snapshot) + err = s.saveMetadata() + if err != nil { + return abci.Snapshot{}, err + } + return snapshot, nil +} + +// Prune removes old snapshots ensuring only the most recent n snapshots remain +func (s *SnapshotStore) Prune(n int) error { + s.Lock() + defer s.Unlock() + // snapshots are appended to the metadata struct, hence pruning removes from + // the front of the array + i := 0 + for ; i < len(s.metadata)-n; i++ { + h := s.metadata[i].Height + if err := os.Remove(filepath.Join(s.dir, fmt.Sprintf("%v.json", h))); err != nil { + return err + } + } + + // update metadata by removing the deleted snapshots + pruned := make([]abci.Snapshot, len(s.metadata[i:])) + copy(pruned, s.metadata[i:]) + s.metadata = pruned + return nil +} + +// List lists available snapshots. +func (s *SnapshotStore) List() ([]*abci.Snapshot, error) { + s.RLock() + defer s.RUnlock() + snapshots := make([]*abci.Snapshot, len(s.metadata)) + for idx := range s.metadata { + snapshots[idx] = &s.metadata[idx] + } + return snapshots, nil +} + +// LoadChunk loads a snapshot chunk. +func (s *SnapshotStore) LoadChunk(height uint64, format uint32, chunk uint32) ([]byte, error) { + s.RLock() + defer s.RUnlock() + for _, snapshot := range s.metadata { + if snapshot.Height == height && snapshot.Format == format { + bz, err := os.ReadFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", height))) + if err != nil { + return nil, err + } + return byteChunk(bz, chunk), nil + } + } + return nil, nil +} + +// byteChunk returns the chunk at a given index from the full byte slice. +func byteChunk(bz []byte, index uint32) []byte { + start := int(index * snapshotChunkSize) + end := int((index + 1) * snapshotChunkSize) + switch { + case start >= len(bz): + return nil + case end >= len(bz): + return bz[start:] + default: + return bz[start:end] + } +} + +// byteChunks calculates the number of chunks in the byte slice. +func byteChunks(bz []byte) uint32 { + return uint32(math.Ceil(float64(len(bz)) / snapshotChunkSize)) +} diff --git a/test/e2e/app/state.go b/test/e2e/app/state.go new file mode 100644 index 0000000..2435242 --- /dev/null +++ b/test/e2e/app/state.go @@ -0,0 +1,264 @@ +package app + +import ( + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "sync" +) + +const ( + stateFileName = "app_state.json" + prevStateFileName = "prev_app_state.json" +) + +// Intermediate type used exclusively in serialization/deserialization of +// State, such that State need not expose any of its internal values publicly. +type serializedState struct { + Height uint64 + Values map[string]string + Hash []byte +} + +// State is the application state. +type State struct { + sync.RWMutex + height uint64 + values map[string]string + hash []byte + + currentFile string + // app saves current and previous state for rollback functionality + previousFile string + persistInterval uint64 + initialHeight uint64 +} + +// NewState creates a new state. +func NewState(dir string, persistInterval uint64) (*State, error) { + state := &State{ + values: make(map[string]string), + currentFile: filepath.Join(dir, stateFileName), + previousFile: filepath.Join(dir, prevStateFileName), + persistInterval: persistInterval, + } + state.hash = hashItems(state.values, state.height) + err := state.load() + switch { + case errors.Is(err, os.ErrNotExist): + case err != nil: + return nil, err + } + return state, nil +} + +// load loads state from disk. It does not take out a lock, since it is called +// during construction. +func (s *State) load() error { + bz, err := os.ReadFile(s.currentFile) + if err != nil { + // if the current state doesn't exist then we try recover from the previous state + if errors.Is(err, os.ErrNotExist) { + bz, err = os.ReadFile(s.previousFile) + if err != nil { + return fmt.Errorf("failed to read both current and previous state (%q): %w", + s.previousFile, err) + } + } else { + return fmt.Errorf("failed to read state from %q: %w", s.currentFile, err) + } + } + if err := json.Unmarshal(bz, s); err != nil { + return fmt.Errorf("invalid state data in %q: %w", s.currentFile, err) + } + return nil +} + +// save saves the state to disk. It does not take out a lock since it is called +// internally by Commit which does lock. +func (s *State) save() error { + bz, err := json.Marshal(s) + if err != nil { + return fmt.Errorf("failed to marshal state: %w", err) + } + // We write the state to a separate file and move it to the destination, to + // make it atomic. + newFile := fmt.Sprintf("%v.new", s.currentFile) + err = os.WriteFile(newFile, bz, 0o644) //nolint:gosec + if err != nil { + return fmt.Errorf("failed to write state to %q: %w", s.currentFile, err) + } + // We take the current state and move it to the previous state, replacing it + if _, err := os.Stat(s.currentFile); err == nil { + if err := os.Rename(s.currentFile, s.previousFile); err != nil { + return fmt.Errorf("failed to replace previous state: %w", err) + } + } + // Finally, we take the new state and replace the current state. + return os.Rename(newFile, s.currentFile) +} + +// GetHash provides a thread-safe way of accessing a copy of the current state +// hash. +func (s *State) GetHash() []byte { + s.RLock() + defer s.RUnlock() + hash := make([]byte, len(s.hash)) + copy(hash, s.hash) + return hash +} + +// Info returns both the height and hash simultaneously, and is used in the +// ABCI Info call. +func (s *State) Info() (uint64, []byte) { + s.RLock() + defer s.RUnlock() + height := s.height + hash := make([]byte, len(s.hash)) + copy(hash, s.hash) + return height, hash +} + +// Export exports key/value pairs as JSON, used for state sync snapshots. +// Additionally returns the current height and hash of the state. +func (s *State) Export() ([]byte, uint64, []byte, error) { + s.RLock() + defer s.RUnlock() + bz, err := json.Marshal(s.values) + if err != nil { + return nil, 0, nil, err + } + height := s.height + stateHash := hashItems(s.values, height) + return bz, height, stateHash, nil +} + +// Import imports key/value pairs from JSON bytes, used for InitChain.AppStateBytes and +// state sync snapshots. It also saves the state once imported. +func (s *State) Import(height uint64, jsonBytes []byte) error { + s.Lock() + defer s.Unlock() + values := map[string]string{} + err := json.Unmarshal(jsonBytes, &values) + if err != nil { + return fmt.Errorf("failed to decode imported JSON data: %w", err) + } + s.height = height + s.values = values + s.hash = hashItems(values, height) + return s.save() +} + +// Get fetches a value. A missing value is returned as an empty string. +func (s *State) Get(key string) string { + s.RLock() + defer s.RUnlock() + return s.values[key] +} + +// Set sets a value. Setting an empty value is equivalent to deleting it. +func (s *State) Set(key, value string) { + s.Lock() + defer s.Unlock() + if value == "" { + delete(s.values, key) + } else { + s.values[key] = value + } +} + +// Query is used in the ABCI Query call, and provides both the current height +// and the value associated with the given key. +func (s *State) Query(key string) (string, uint64) { + s.RLock() + defer s.RUnlock() + height := s.height + value := s.values[key] + return value, height +} + +// Finalize is called after applying a block, updating the height and returning the new app_hash +func (s *State) Finalize() []byte { + s.Lock() + defer s.Unlock() + switch { + case s.height > 0: + s.height++ + case s.initialHeight > 0: + s.height = s.initialHeight + default: + s.height = 1 + } + s.hash = hashItems(s.values, s.height) + return s.hash +} + +// Commit commits the current state. +func (s *State) Commit() (uint64, error) { + s.Lock() + defer s.Unlock() + if s.persistInterval > 0 && s.height%s.persistInterval == 0 { + err := s.save() + if err != nil { + return 0, err + } + } + return s.height, nil +} + +func (s *State) Rollback() error { + bz, err := os.ReadFile(s.previousFile) + if err != nil { + return fmt.Errorf("failed to read state from %q: %w", s.previousFile, err) + } + if err := json.Unmarshal(bz, s); err != nil { + return fmt.Errorf("invalid state data in %q: %w", s.previousFile, err) + } + return nil +} + +func (s *State) UnmarshalJSON(b []byte) error { + var ss serializedState + if err := json.Unmarshal(b, &ss); err != nil { + return err + } + s.height = ss.Height + s.values = ss.Values + s.hash = ss.Hash + return nil +} + +func (s *State) MarshalJSON() ([]byte, error) { + ss := &serializedState{ + Height: s.height, + Values: s.values, + Hash: s.hash, + } + return json.Marshal(ss) +} + +// hashItems hashes a set of key/value items. +func hashItems(items map[string]string, height uint64) []byte { + keys := make([]string, 0, len(items)) + for key := range items { + keys = append(keys, key) + } + sort.Strings(keys) + + hasher := sha256.New() + var b [8]byte + binary.BigEndian.PutUint64(b[:], height) + _, _ = hasher.Write(b[:]) + for _, key := range keys { + _, _ = hasher.Write([]byte(key)) + _, _ = hasher.Write([]byte{0}) + _, _ = hasher.Write([]byte(items[key])) + _, _ = hasher.Write([]byte{0}) + } + return hasher.Sum(nil) +} diff --git a/test/e2e/docker/Dockerfile b/test/e2e/docker/Dockerfile new file mode 100644 index 0000000..23773d0 --- /dev/null +++ b/test/e2e/docker/Dockerfile @@ -0,0 +1,56 @@ +# Multi-stage build Dockerfile for CometBFT end-to-end testing +# Stage 1: Build environment - compiles the application and test node +FROM cometbft/cometbft-db-testing:v0.14.2 AS build + +WORKDIR /src/cometbft + +# Copy Go module files and download dependencies +# This is done before copying the rest of the code to leverage Docker's build cache +COPY go.mod go.sum ./ +RUN go mod download + +# Copy the entire codebase into the container +COPY . . + +# Set build options to include specific features and databases +ENV COMETBFT_BUILD_OPTIONS=badgerdb,boltdb,cleveldb,rocksdb +RUN make build +RUN cd test/e2e && make node + +# Stage 2: Final image - minimal runtime environment +FROM debian:bookworm-slim AS runtime + +# Update system packages and install network utilities +RUN apt-get -qq update -y && apt-get -qq upgrade -y >/dev/null +RUN apt-get -qq install -y iputils-ping iproute2 >/dev/null +RUN apt install libsnappy-dev libgflags-dev libleveldb-dev -y >/dev/null + +WORKDIR /cometbft +VOLUME /cometbft +ENV CMTHOME=/cometbft + +# Configure Go race detector to halt on error +ENV GORACE="halt_on_error=1" + +# Copy RocksDB shared libraries from the build stage +COPY --from=build /usr/local/lib/librocksdb.so* /lib/ + +# Copy executables from the build stage +# - entrypoint script for container initialization +# - cometbft binary for the blockchain node +# - app binary for the test application +COPY --from=build /src/cometbft/test/e2e/docker/entrypoint* /usr/bin/ +COPY --from=build /src/cometbft/build/cometbft /usr/bin/cometbft +COPY --from=build /src/cometbft/test/e2e/build/node /usr/bin/app + +# Expose ports: +# - 26656: P2P communication between nodes +# - 26657: RPC server for API requests +# - 26660: ABCI server for application communication +# - 6060: Prometheus metrics endpoint +EXPOSE 26656 26657 26660 6060 + +# Set the entrypoint script to initialize the container +ENTRYPOINT ["/usr/bin/entrypoint"] +# Default command to run when container starts (can be overridden) +CMD ["node"] diff --git a/test/e2e/docker/entrypoint b/test/e2e/docker/entrypoint new file mode 100755 index 0000000..1ebc3c9 --- /dev/null +++ b/test/e2e/docker/entrypoint @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Forcibly remove any stray UNIX sockets left behind from previous runs +rm -rf /var/run/privval.sock /var/run/app.sock + +/usr/bin/app /cometbft/config/app.toml & + +sleep 1 + +/usr/bin/cometbft "$@" diff --git a/test/e2e/docker/entrypoint-builtin b/test/e2e/docker/entrypoint-builtin new file mode 100755 index 0000000..2cd17f9 --- /dev/null +++ b/test/e2e/docker/entrypoint-builtin @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +# Forcibly remove any stray UNIX sockets left behind from previous runs +rm -rf /var/run/privval.sock /var/run/app.sock + +/usr/bin/app /cometbft/config/app.toml diff --git a/test/e2e/generator/generate.go b/test/e2e/generator/generate.go new file mode 100644 index 0000000..9784c6c --- /dev/null +++ b/test/e2e/generator/generate.go @@ -0,0 +1,458 @@ +package main + +import ( + "errors" + "fmt" + "math/rand" + "sort" + "strconv" + "strings" + "time" + + "github.com/Masterminds/semver/v3" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/version" + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing/object" +) + +var ( + // testnetCombinations defines global testnet options, where we generate a + // separate testnet for each combination (Cartesian product) of options. + testnetCombinations = map[string][]interface{}{ + "topology": {"single", "quad", "large"}, + "initialHeight": {0, 1000}, + "initialState": { + map[string]string{}, + map[string]string{"initial01": "a", "initial02": "b", "initial03": "c"}, + }, + "validators": {"genesis", "initchain"}, + } + nodeVersions = weightedChoice{ + "": 2, + } + + // The following specify randomly chosen values for testnet nodes. + nodeDatabases = uniformChoice{"goleveldb", "cleveldb", "rocksdb", "boltdb", "badgerdb"} + ipv6 = uniformChoice{false, true} + // FIXME: grpc disabled due to https://github.com/tendermint/tendermint/issues/5439 + nodeABCIProtocols = uniformChoice{"unix", "tcp", "builtin", "builtin_connsync"} // "grpc" + nodePrivvalProtocols = uniformChoice{"file", "unix", "tcp"} + nodeBlockSyncs = uniformChoice{"v0"} // "v2" + nodeStateSyncs = uniformChoice{false, true} + nodePersistIntervals = uniformChoice{0, 1, 5} + nodeSnapshotIntervals = uniformChoice{0, 3} + nodeRetainBlocks = uniformChoice{ + 0, + 2 * int(e2e.EvidenceAgeHeight), + 4 * int(e2e.EvidenceAgeHeight), + } + evidence = uniformChoice{0, 1, 10, 20, 200} + abciDelays = uniformChoice{"none", "small", "large"} + nodePerturbations = probSetChoice{ + "disconnect": 0.1, + "pause": 0.1, + "kill": 0.1, + "restart": 0.1, + "upgrade": 0.3, + } + lightNodePerturbations = probSetChoice{ + "upgrade": 0.3, + } + voteExtensionUpdateHeight = uniformChoice{int64(-1), int64(0), int64(1)} // -1: genesis, 0: InitChain, 1: (use offset) + voteExtensionEnabled = weightedChoice{true: 3, false: 1} + voteExtensionHeightOffset = uniformChoice{int64(0), int64(10), int64(100)} +) + +type generateConfig struct { + randSource *rand.Rand + outputDir string + multiVersion string + prometheus bool +} + +// Generate generates random testnets using the given RNG. +func Generate(cfg *generateConfig) ([]e2e.Manifest, error) { + upgradeVersion := "" + + if cfg.multiVersion != "" { + var err error + nodeVersions, upgradeVersion, err = parseWeightedVersions(cfg.multiVersion) + if err != nil { + return nil, err + } + if _, ok := nodeVersions["local"]; ok { + nodeVersions[""] = nodeVersions["local"] + delete(nodeVersions, "local") + if upgradeVersion == "local" { + upgradeVersion = "" + } + } + if _, ok := nodeVersions["latest"]; ok { + latestVersion, err := gitRepoLatestReleaseVersion(cfg.outputDir) + if err != nil { + return nil, err + } + nodeVersions[latestVersion] = nodeVersions["latest"] + delete(nodeVersions, "latest") + if upgradeVersion == "latest" { + upgradeVersion = latestVersion + } + } + } + fmt.Println("Generating testnet with weighted versions:") + for ver, wt := range nodeVersions { + if ver == "" { + fmt.Printf("- local: %d\n", wt) + } else { + fmt.Printf("- %s: %d\n", ver, wt) + } + } + manifests := []e2e.Manifest{} + for _, opt := range combinations(testnetCombinations) { + manifest, err := generateTestnet(cfg.randSource, opt, upgradeVersion, cfg.prometheus) + if err != nil { + return nil, err + } + manifests = append(manifests, manifest) + } + return manifests, nil +} + +// generateTestnet generates a single testnet with the given options. +func generateTestnet(r *rand.Rand, opt map[string]interface{}, upgradeVersion string, prometheus bool) (e2e.Manifest, error) { + manifest := e2e.Manifest{ + IPv6: ipv6.Choose(r).(bool), + ABCIProtocol: nodeABCIProtocols.Choose(r).(string), + InitialHeight: int64(opt["initialHeight"].(int)), + InitialState: opt["initialState"].(map[string]string), + Validators: &map[string]int64{}, + ValidatorUpdates: map[string]map[string]int64{}, + Evidence: evidence.Choose(r).(int), + Nodes: map[string]*e2e.ManifestNode{}, + UpgradeVersion: upgradeVersion, + Prometheus: prometheus, + } + + switch abciDelays.Choose(r).(string) { + case "none": + case "small": + manifest.PrepareProposalDelay = 100 * time.Millisecond + manifest.ProcessProposalDelay = 100 * time.Millisecond + manifest.VoteExtensionDelay = 20 * time.Millisecond + manifest.FinalizeBlockDelay = 200 * time.Millisecond + case "large": + manifest.PrepareProposalDelay = 200 * time.Millisecond + manifest.ProcessProposalDelay = 200 * time.Millisecond + manifest.CheckTxDelay = 20 * time.Millisecond + manifest.VoteExtensionDelay = 100 * time.Millisecond + manifest.FinalizeBlockDelay = 500 * time.Millisecond + } + manifest.VoteExtensionsUpdateHeight = voteExtensionUpdateHeight.Choose(r).(int64) + if manifest.VoteExtensionsUpdateHeight == 1 { + manifest.VoteExtensionsUpdateHeight = manifest.InitialHeight + voteExtensionHeightOffset.Choose(r).(int64) + } + if voteExtensionEnabled.Choose(r).(bool) { + baseHeight := max(manifest.VoteExtensionsUpdateHeight+1, manifest.InitialHeight) + manifest.VoteExtensionsEnableHeight = baseHeight + voteExtensionHeightOffset.Choose(r).(int64) + } + + var numSeeds, numValidators, numFulls, numLightClients int + switch opt["topology"].(string) { + case "single": + numValidators = 1 + case "quad": + numValidators = 4 + case "large": + // FIXME Networks are kept small since large ones use too much CPU. + numSeeds = r.Intn(2) + numLightClients = r.Intn(3) + numValidators = 4 + r.Intn(4) + numFulls = r.Intn(4) + default: + return manifest, fmt.Errorf("unknown topology %q", opt["topology"]) + } + + // First we generate seed nodes, starting at the initial height. + for i := 1; i <= numSeeds; i++ { + manifest.Nodes[fmt.Sprintf("seed%02d", i)] = generateNode( + r, e2e.ModeSeed, 0, false) + } + + // Next, we generate validators. We make sure a BFT quorum of validators start + // at the initial height, and that we have two archive nodes. We also set up + // the initial validator set, and validator set updates for delayed nodes. + nextStartAt := manifest.InitialHeight + 5 + quorum := numValidators*2/3 + 1 + for i := 1; i <= numValidators; i++ { + startAt := int64(0) + if i > quorum { + startAt = nextStartAt + nextStartAt += 5 + } + name := fmt.Sprintf("validator%02d", i) + manifest.Nodes[name] = generateNode( + r, e2e.ModeValidator, startAt, i <= 2) + + if startAt == 0 { + (*manifest.Validators)[name] = int64(30 + r.Intn(71)) + } else { + manifest.ValidatorUpdates[fmt.Sprint(startAt+5)] = map[string]int64{ + name: int64(30 + r.Intn(71)), + } + } + } + + // Move validators to InitChain if specified. + switch opt["validators"].(string) { + case "genesis": + case "initchain": + manifest.ValidatorUpdates["0"] = *manifest.Validators + manifest.Validators = &map[string]int64{} + default: + return manifest, fmt.Errorf("invalid validators option %q", opt["validators"]) + } + + // Finally, we generate random full nodes. + for i := 1; i <= numFulls; i++ { + startAt := int64(0) + if r.Float64() >= 0.5 { + startAt = nextStartAt + nextStartAt += 5 + } + manifest.Nodes[fmt.Sprintf("full%02d", i)] = generateNode( + r, e2e.ModeFull, startAt, false) + } + + // We now set up peer discovery for nodes. Seed nodes are fully meshed with + // each other, while non-seed nodes either use a set of random seeds or a + // set of random peers that start before themselves. + var seedNames, peerNames, lightProviders []string + for name, node := range manifest.Nodes { + if node.Mode == string(e2e.ModeSeed) { + seedNames = append(seedNames, name) + } else { + // if the full node or validator is an ideal candidate, it is added as a light provider. + // There are at least two archive nodes so there should be at least two ideal candidates + if (node.StartAt == 0 || node.StartAt == manifest.InitialHeight) && node.RetainBlocks == 0 { + lightProviders = append(lightProviders, name) + } + peerNames = append(peerNames, name) + } + } + + for _, name := range seedNames { + for _, otherName := range seedNames { + if name != otherName { + manifest.Nodes[name].Seeds = append(manifest.Nodes[name].Seeds, otherName) + } + } + } + + sort.Slice(peerNames, func(i, j int) bool { + iName, jName := peerNames[i], peerNames[j] + switch { + case manifest.Nodes[iName].StartAt < manifest.Nodes[jName].StartAt: + return true + case manifest.Nodes[iName].StartAt > manifest.Nodes[jName].StartAt: + return false + default: + return strings.Compare(iName, jName) == -1 + } + }) + for i, name := range peerNames { + if len(seedNames) > 0 && (i == 0 || r.Float64() >= 0.5) { + manifest.Nodes[name].Seeds = uniformSetChoice(seedNames).Choose(r) + } else if i > 0 { + manifest.Nodes[name].PersistentPeers = uniformSetChoice(peerNames[:i]).Choose(r) + } + } + + // lastly, set up the light clients + for i := 1; i <= numLightClients; i++ { + startAt := manifest.InitialHeight + 5 + manifest.Nodes[fmt.Sprintf("light%02d", i)] = generateLightNode( + r, startAt+(5*int64(i)), lightProviders, + ) + } + + return manifest, nil +} + +// generateNode randomly generates a node, with some constraints to avoid +// generating invalid configurations. We do not set Seeds or PersistentPeers +// here, since we need to know the overall network topology and startup +// sequencing. +func generateNode( + r *rand.Rand, mode e2e.Mode, startAt int64, forceArchive bool, +) *e2e.ManifestNode { + node := e2e.ManifestNode{ + Version: nodeVersions.Choose(r).(string), + Mode: string(mode), + StartAt: startAt, + Database: nodeDatabases.Choose(r).(string), + PrivvalProtocol: nodePrivvalProtocols.Choose(r).(string), + BlockSyncVersion: nodeBlockSyncs.Choose(r).(string), + StateSync: nodeStateSyncs.Choose(r).(bool) && startAt > 0, + PersistInterval: ptrUint64(uint64(nodePersistIntervals.Choose(r).(int))), + SnapshotInterval: uint64(nodeSnapshotIntervals.Choose(r).(int)), + RetainBlocks: uint64(nodeRetainBlocks.Choose(r).(int)), + Perturb: nodePerturbations.Choose(r), + } + + // If this node is forced to be an archive node, retain all blocks and + // enable state sync snapshotting. + if forceArchive { + node.RetainBlocks = 0 + node.SnapshotInterval = 3 + } + + // If a node which does not persist state also does not retain blocks, randomly + // choose to either persist state or retain all blocks. + if node.PersistInterval != nil && *node.PersistInterval == 0 && node.RetainBlocks > 0 { + if r.Float64() > 0.5 { + node.RetainBlocks = 0 + } else { + node.PersistInterval = ptrUint64(node.RetainBlocks) + } + } + + // If either PersistInterval or SnapshotInterval are greater than RetainBlocks, + // expand the block retention time. + if node.RetainBlocks > 0 { + if node.PersistInterval != nil && node.RetainBlocks < *node.PersistInterval { + node.RetainBlocks = *node.PersistInterval + } + if node.RetainBlocks < node.SnapshotInterval { + node.RetainBlocks = node.SnapshotInterval + } + } + + return &node +} + +func generateLightNode(r *rand.Rand, startAt int64, providers []string) *e2e.ManifestNode { + return &e2e.ManifestNode{ + Mode: string(e2e.ModeLight), + Version: nodeVersions.Choose(r).(string), + StartAt: startAt, + Database: nodeDatabases.Choose(r).(string), + PersistInterval: ptrUint64(0), + PersistentPeers: providers, + Perturb: lightNodePerturbations.Choose(r), + } +} + +func ptrUint64(i uint64) *uint64 { + return &i +} + +// Parses strings like "v0.34.21:1,v0.34.22:2" to represent two versions +// ("v0.34.21" and "v0.34.22") with weights of 1 and 2 respectively. +// Versions may be specified as cometbft/e2e-node:v0.34.27-alpha.1:1 or +// ghcr.io/informalsystems/tendermint:v0.34.26:1. +// If only the tag and weight are specified, cometbft/e2e-node is assumed. +// Also returns the last version in the list, which will be used for updates. +func parseWeightedVersions(s string) (weightedChoice, string, error) { + wc := make(weightedChoice) + lv := "" + wvs := strings.Split(strings.TrimSpace(s), ",") + for _, wv := range wvs { + parts := strings.Split(strings.TrimSpace(wv), ":") + var ver string + if len(parts) == 2 { + ver = strings.TrimSpace(strings.Join([]string{"cometbft/e2e-node", parts[0]}, ":")) + } else if len(parts) == 3 { + ver = strings.TrimSpace(strings.Join([]string{parts[0], parts[1]}, ":")) + } else { + return nil, "", fmt.Errorf("unexpected weight:version combination: %s", wv) + } + + wt, err := strconv.Atoi(strings.TrimSpace(parts[len(parts)-1])) + if err != nil { + return nil, "", fmt.Errorf("unexpected weight \"%s\": %w", parts[1], err) + } + + if wt < 1 { + return nil, "", errors.New("version weights must be >= 1") + } + wc[ver] = uint(wt) + lv = ver + } + return wc, lv, nil +} + +// Extracts the latest release version from the given Git repository. Uses the +// current version of CometBFT to establish the "major" version +// currently in use. +func gitRepoLatestReleaseVersion(gitRepoDir string) (string, error) { + opts := &git.PlainOpenOptions{ + DetectDotGit: true, + } + r, err := git.PlainOpenWithOptions(gitRepoDir, opts) + if err != nil { + return "", err + } + tags := make([]string, 0) + tagObjs, err := r.TagObjects() + if err != nil { + return "", err + } + err = tagObjs.ForEach(func(tagObj *object.Tag) error { + tags = append(tags, tagObj.Name) + return nil + }) + if err != nil { + return "", err + } + return findLatestReleaseTag(version.TMCoreSemVer, tags) +} + +func findLatestReleaseTag(baseVer string, tags []string) (string, error) { + baseSemVer, err := semver.NewVersion(strings.Split(baseVer, "-")[0]) + if err != nil { + return "", fmt.Errorf("failed to parse base version \"%s\": %w", baseVer, err) + } + compVer := fmt.Sprintf("%d.%d", baseSemVer.Major(), baseSemVer.Minor()) + // Build our version comparison string + // See https://github.com/Masterminds/semver#caret-range-comparisons-major for details + compStr := "^ " + compVer + verCon, err := semver.NewConstraint(compStr) + if err != nil { + return "", err + } + var latestVer *semver.Version + for _, tag := range tags { + if !strings.HasPrefix(tag, "v") { + continue + } + curVer, err := semver.NewVersion(tag) + // Skip tags that are not valid semantic versions + if err != nil { + continue + } + // Skip pre-releases + if len(curVer.Prerelease()) != 0 { + continue + } + // Skip versions that don't match our constraints + if !verCon.Check(curVer) { + continue + } + if latestVer == nil || curVer.GreaterThan(latestVer) { + latestVer = curVer + } + } + // No relevant latest version (will cause the generator to only use the tip + // of the current branch) + if latestVer == nil { + return "", nil + } + // Ensure the version string has a "v" prefix, because all CometBFT E2E + // node Docker images' versions have a "v" prefix. + vs := latestVer.String() + if !strings.HasPrefix(vs, "v") { + return "v" + vs, nil + } + return vs, nil +} diff --git a/test/e2e/generator/generate_test.go b/test/e2e/generator/generate_test.go new file mode 100644 index 0000000..2d6b11d --- /dev/null +++ b/test/e2e/generator/generate_test.go @@ -0,0 +1,70 @@ +package main + +import ( + "fmt" + "math/rand" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +// TestGenerator tests that only valid manifests are generated +func TestGenerator(t *testing.T) { + cfg := &generateConfig{ + randSource: rand.New(rand.NewSource(randomSeed)), + } + manifests, err := Generate(cfg) + require.NoError(t, err) + + for idx, m := range manifests { + t.Run(fmt.Sprintf("Case%04d", idx), func(t *testing.T) { + infra, err := e2e.NewDockerInfrastructureData(m) + require.NoError(t, err) + _, err = e2e.NewTestnetFromManifest(m, filepath.Join(t.TempDir(), fmt.Sprintf("Case%04d", idx)), infra) + require.NoError(t, err) + }) + } +} + +func TestVersionFinder(t *testing.T) { + testCases := []struct { + baseVer string + tags []string + expectedLatest string + }{ + { + baseVer: "v0.34.0", + tags: []string{"v0.34.0", "v0.34.1", "v0.34.2", "v0.34.3-rc1", "v0.34.3", "v0.35.0", "v0.35.1", "v0.36.0-rc1"}, + expectedLatest: "v0.34.3", + }, + { + baseVer: "v0.38.0-dev", + tags: []string{"v0.34.0", "v0.34.1", "v0.34.2", "v0.37.0-rc2", "dev-v0.38.0"}, + expectedLatest: "", + }, + { + baseVer: "v0.37.1-rc1", + tags: []string{"v0.36.0", "v0.37.0-rc1", "v0.37.0"}, + expectedLatest: "v0.37.0", + }, + { + baseVer: "v1.0.0", + tags: []string{"v0.34.0", "v0.35.0", "v1.0.0", "v1.0.1"}, + expectedLatest: "v1.0.1", + }, + { + baseVer: "v1.1.5", + tags: []string{"v0.35.0", "v1.0.0", "v1.0.1", "v1.1.1", "v1.1.2", "v1.1.3", "v1.1.4"}, + expectedLatest: "v1.1.4", + }, + } + for _, tc := range testCases { + actualLatest, err := findLatestReleaseTag(tc.baseVer, tc.tags) + require.NoError(t, err) + assert.Equal(t, tc.expectedLatest, actualLatest) + } +} diff --git a/test/e2e/generator/main.go b/test/e2e/generator/main.go new file mode 100644 index 0000000..40082cf --- /dev/null +++ b/test/e2e/generator/main.go @@ -0,0 +1,113 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/libs/log" +) + +const ( + randomSeed int64 = 4827085738 +) + +var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + +func main() { + NewCLI().Run() +} + +// CLI is the Cobra-based command-line interface. +type CLI struct { + root *cobra.Command +} + +// NewCLI sets up the CLI. +func NewCLI() *CLI { + cli := &CLI{} + cli.root = &cobra.Command{ + Use: "generator -d dir [-g int] [-m version_weight_csv] [-p]", + Short: "End-to-end testnet generator", + SilenceUsage: true, + SilenceErrors: true, // we'll output them ourselves in Run() + RunE: func(cmd *cobra.Command, args []string) error { + dir, err := cmd.Flags().GetString("dir") + if err != nil { + return err + } + groups, err := cmd.Flags().GetInt("groups") + if err != nil { + return err + } + multiVersion, err := cmd.Flags().GetString("multi-version") + if err != nil { + return err + } + prometheus, err := cmd.Flags().GetBool("prometheus") + if err != nil { + return err + } + return cli.generate(dir, groups, multiVersion, prometheus) + }, + } + + cli.root.PersistentFlags().StringP("dir", "d", "", "Output directory for manifests") + _ = cli.root.MarkPersistentFlagRequired("dir") + cli.root.PersistentFlags().StringP("multi-version", "m", "", "Comma-separated list of versions of CometBFT to test in the generated testnets, "+ + "or empty to only use this branch's version") + cli.root.PersistentFlags().IntP("groups", "g", 0, "Number of groups") + cli.root.PersistentFlags().BoolP("prometheus", "p", false, "Enable generation of Prometheus metrics on all manifests") + + return cli +} + +// generate generates manifests in a directory. +func (cli *CLI) generate(dir string, groups int, multiVersion string, prometheus bool) error { + err := os.MkdirAll(dir, 0o755) + if err != nil { + return err + } + + cfg := &generateConfig{ + randSource: rand.New(rand.NewSource(randomSeed)), //nolint:gosec + multiVersion: multiVersion, + prometheus: prometheus, + } + manifests, err := Generate(cfg) + if err != nil { + return err + } + if groups <= 0 { + for i, manifest := range manifests { + err = manifest.Save(filepath.Join(dir, fmt.Sprintf("gen-%04d.toml", i))) + if err != nil { + return err + } + } + } else { + groupSize := int(math.Ceil(float64(len(manifests)) / float64(groups))) + for g := 0; g < groups; g++ { + for i := 0; i < groupSize && g*groupSize+i < len(manifests); i++ { + manifest := manifests[g*groupSize+i] + err = manifest.Save(filepath.Join(dir, fmt.Sprintf("gen-group%02d-%04d.toml", g, i))) + if err != nil { + return err + } + } + } + } + return nil +} + +// Run runs the CLI. +func (cli *CLI) Run() { + if err := cli.root.Execute(); err != nil { + logger.Error(err.Error()) + os.Exit(1) + } +} diff --git a/test/e2e/generator/random.go b/test/e2e/generator/random.go new file mode 100644 index 0000000..44c75d4 --- /dev/null +++ b/test/e2e/generator/random.go @@ -0,0 +1,107 @@ +package main + +import ( + "math/rand" + "sort" +) + +// combinations takes input in the form of a map of item lists, and returns a +// list of all combinations of each item for each key. E.g.: +// +// {"foo": [1, 2, 3], "bar": [4, 5, 6]} +// +// Will return the following maps: +// +// {"foo": 1, "bar": 4} +// {"foo": 1, "bar": 5} +// {"foo": 1, "bar": 6} +// {"foo": 2, "bar": 4} +// {"foo": 2, "bar": 5} +// {"foo": 2, "bar": 6} +// {"foo": 3, "bar": 4} +// {"foo": 3, "bar": 5} +// {"foo": 3, "bar": 6} +func combinations(items map[string][]interface{}) []map[string]interface{} { + keys := []string{} + for key := range items { + keys = append(keys, key) + } + sort.Strings(keys) + return combiner(map[string]interface{}{}, keys, items) +} + +// combiner is a utility function for combinations. +func combiner(head map[string]interface{}, pending []string, items map[string][]interface{}) []map[string]interface{} { + if len(pending) == 0 { + return []map[string]interface{}{head} + } + key, pending := pending[0], pending[1:] + + result := []map[string]interface{}{} + for _, value := range items[key] { + path := map[string]interface{}{} + for k, v := range head { + path[k] = v + } + path[key] = value + result = append(result, combiner(path, pending, items)...) + } + return result +} + +// uniformChoice chooses a single random item from the argument list, uniformly weighted. +type uniformChoice []interface{} + +func (uc uniformChoice) Choose(r *rand.Rand) interface{} { + return uc[r.Intn(len(uc))] +} + +// probSetChoice picks a set of strings based on each string's probability (0-1). +type probSetChoice map[string]float64 + +func (pc probSetChoice) Choose(r *rand.Rand) []string { + choices := []string{} + for item, prob := range pc { + if r.Float64() <= prob { + choices = append(choices, item) + } + } + return choices +} + +// uniformSetChoice picks a set of strings with uniform probability, picking at least one. +type uniformSetChoice []string + +func (usc uniformSetChoice) Choose(r *rand.Rand) []string { + choices := []string{} + indexes := r.Perm(len(usc)) + if len(indexes) > 1 { + indexes = indexes[:1+r.Intn(len(indexes)-1)] + } + for _, i := range indexes { + choices = append(choices, usc[i]) + } + return choices +} + +// weightedChoice chooses a single random key from a map of keys and weights. +type weightedChoice map[interface{}]uint + +func (wc weightedChoice) Choose(r *rand.Rand) interface{} { + total := 0 + choices := make([]interface{}, 0, len(wc)) + for choice, weight := range wc { + total += int(weight) + choices = append(choices, choice) + } + + rem := r.Intn(total) + for _, choice := range choices { + rem -= int(wc[choice]) + if rem <= 0 { + return choice + } + } + + return nil +} diff --git a/test/e2e/generator/random_test.go b/test/e2e/generator/random_test.go new file mode 100644 index 0000000..c37aaf8 --- /dev/null +++ b/test/e2e/generator/random_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCombinations(t *testing.T) { + input := map[string][]interface{}{ + "bool": {false, true}, + "int": {1, 2, 3}, + "string": {"foo", "bar"}, + } + + c := combinations(input) + assert.Equal(t, []map[string]interface{}{ + {"bool": false, "int": 1, "string": "foo"}, + {"bool": false, "int": 1, "string": "bar"}, + {"bool": false, "int": 2, "string": "foo"}, + {"bool": false, "int": 2, "string": "bar"}, + {"bool": false, "int": 3, "string": "foo"}, + {"bool": false, "int": 3, "string": "bar"}, + {"bool": true, "int": 1, "string": "foo"}, + {"bool": true, "int": 1, "string": "bar"}, + {"bool": true, "int": 2, "string": "foo"}, + {"bool": true, "int": 2, "string": "bar"}, + {"bool": true, "int": 3, "string": "foo"}, + {"bool": true, "int": 3, "string": "bar"}, + }, c) +} diff --git a/test/e2e/networks/ci.toml b/test/e2e/networks/ci.toml new file mode 100644 index 0000000..7bacb96 --- /dev/null +++ b/test/e2e/networks/ci.toml @@ -0,0 +1,97 @@ +# This testnet is run by CI, and attempts to cover a broad range of +# functionality with a single network. + +ipv6 = true +initial_height = 1000 +vote_extensions_update_height = 1004 +vote_extensions_enable_height = 1007 +evidence = 5 +initial_state = { initial01 = "a", initial02 = "b", initial03 = "c" } +prepare_proposal_delay = "100ms" +process_proposal_delay = "100ms" +check_tx_delay = "0ms" +# The most common case (e.g. Cosmos SDK-based chains). +abci_protocol = "builtin" +prometheus = true + +[validators] +validator01 = 100 + +[validator_update.0] +validator01 = 10 +validator02 = 20 +validator03 = 30 +validator04 = 40 + +[validator_update.1010] +validator05 = 50 + +# validator03 gets killed and validator05 has lots of perturbations, so weight them low. +[validator_update.1020] +validator01 = 100 +validator02 = 100 +validator03 = 50 +validator04 = 100 +validator05 = 50 + +[node.seed01] +mode = "seed" +perturb = ["restart"] + +[node.validator01] +seeds = ["seed01"] +snapshot_interval = 5 +perturb = ["disconnect"] + +[node.validator02] +seeds = ["seed01"] +database = "boltdb" +privval_protocol = "tcp" +persist_interval = 0 +perturb = ["restart"] + +[node.validator03] +seeds = ["seed01"] +database = "badgerdb" +privval_protocol = "unix" +persist_interval = 3 +retain_blocks = 20 +perturb = ["kill"] +key_type = "secp256k1" + +[node.validator04] +persistent_peers = ["validator01"] +database = "rocksdb" +perturb = ["pause"] +key_type = "sr25519" + +[node.validator05] +start_at = 1005 # Becomes part of the validator set at 1010 +persistent_peers = ["validator01", "full01"] +database = "cleveldb" +privval_protocol = "tcp" +perturb = ["kill", "pause", "disconnect", "restart"] + +[node.full01] +start_at = 1010 +mode = "full" +persistent_peers = ["validator01", "validator02", "validator03", "validator04", "validator05"] +retain_blocks = 20 +perturb = ["restart"] + +[node.full02] +start_at = 1015 +mode = "full" +state_sync = true +seeds = ["seed01"] +perturb = ["restart"] + +[node.light01] +mode= "light" +start_at= 1005 +persistent_peers = ["validator01", "validator02", "validator03"] + +[node.light02] +mode= "light" +start_at= 1015 +persistent_peers = ["validator04", "full01", "validator05"] diff --git a/test/e2e/networks/long.toml b/test/e2e/networks/long.toml new file mode 100644 index 0000000..8bd9ebb --- /dev/null +++ b/test/e2e/networks/long.toml @@ -0,0 +1,254 @@ +ipv6 = true +initial_height = 2 +key_type = "" +abci_protocol = "tcp" +upgrade_version = "cometbft/e2e-node:local-version" +load_tx_size_bytes = 0 +load_tx_batch_size = 100 +load_tx_connections = 0 + +[initial_state] + initial01 = "a" + initial02 = "b" + initial03 = "c" + +[validators] + +[validator_update] + [validator_update.0] + validator01 = 97 + validator02 = 59 + validator03 = 85 + validator04 = 41 + validator05 = 65 + [validator_update.10] + validator06 = 66 + [validator_update.15] + validator07 = 39 + [validator_update.1005] + validator08 = 50 + [validator_update.1255] + validator09 = 50 + [validator_update.1505] + validator10 = 50 + +[node] + [node.full01] + mode = "full" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "badgerdb" + privval_protocol = "file" + start_at = 250 + fast_sync = "v0" + mempool_version = "v1" + state_sync = true + persist_interval = 0 + snapshot_interval = 0 + retain_blocks = 0 + perturb = ["upgrade"] + send_no_load = false + [node.full02] + mode = "full" + version = "cometbft/e2e-node:latest" + persistent_peers = ["validator03", "validator01", "validator06"] + database = "boltdb" + privval_protocol = "tcp" + start_at = 750 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = [] + send_no_load = false + [node.full03] + mode = "full" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "badgerdb" + privval_protocol = "unix" + start_at = 0 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 10 + perturb = ["upgrade"] + send_no_load = false + [node.seed01] + mode = "seed" + version = "cometbft/e2e-node:latest" + database = "badgerdb" + privval_protocol = "unix" + start_at = 0 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 5 + snapshot_interval = 0 + retain_blocks = 7 + perturb = ["upgrade"] + send_no_load = false + [node.validator01] + mode = "validator" + version = "cometbft/e2e-node:latest" + persistent_peers = ["full03"] + database = "rocksdb" + privval_protocol = "tcp" + start_at = 0 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 0 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["kill", "upgrade"] + send_no_load = false + [node.validator01.misbehaviors] + [node.validator02] + mode = "validator" + version = "cometbft/e2e-node:latest" + persistent_peers = ["validator01"] + database = "goleveldb" + privval_protocol = "file" + start_at = 0 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["upgrade", "restart"] + send_no_load = false + [node.validator02.misbehaviors] + [node.validator03] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "boltdb" + privval_protocol = "file" + start_at = 0 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 1 + snapshot_interval = 0 + retain_blocks = 12 + perturb = [] + send_no_load = false + [node.validator03.misbehaviors] + [node.validator04] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "cleveldb" + privval_protocol = "tcp" + start_at = 0 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 0 + snapshot_interval = 3 + retain_blocks = 0 + perturb = [] + send_no_load = false + [node.validator04.misbehaviors] + [node.validator05] + mode = "validator" + version = "cometbft/e2e-node:latest" + persistent_peers = ["validator03"] + database = "cleveldb" + privval_protocol = "unix" + start_at = 0 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 1 + snapshot_interval = 0 + retain_blocks = 0 + perturb = ["restart", "kill"] + send_no_load = false + [node.validator05.misbehaviors] + [node.validator06] + mode = "validator" + version = "cometbft/e2e-node:latest" + persistent_peers = ["full03", "validator02", "validator03"] + database = "boltdb" + privval_protocol = "tcp" + start_at = 5 + fast_sync = "v0" + mempool_version = "v1" + state_sync = false + persist_interval = 0 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["disconnect", "upgrade"] + send_no_load = false + [node.validator06.misbehaviors] + [node.validator07] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "cleveldb" + privval_protocol = "file" + start_at = 10 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["kill"] + send_no_load = false + [node.validator07.misbehaviors] + [node.validator08] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "cleveldb" + privval_protocol = "file" + start_at = 1000 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["kill", "upgrade"] + send_no_load = false + [node.validator08.misbehaviors] + [node.validator09] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "cleveldb" + privval_protocol = "file" + start_at = 1250 + fast_sync = "v0" + mempool_version = "v0" + state_sync = true + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["kill"] + send_no_load = false + [node.validator09.misbehaviors] + [node.validator10] + mode = "validator" + version = "cometbft/e2e-node:latest" + seeds = ["seed01"] + database = "cleveldb" + privval_protocol = "file" + start_at = 1500 + fast_sync = "v0" + mempool_version = "v0" + state_sync = false + persist_interval = 5 + snapshot_interval = 3 + retain_blocks = 0 + perturb = ["kill"] + send_no_load = false + [node.validator10.misbehaviors] diff --git a/test/e2e/networks/simple.toml b/test/e2e/networks/simple.toml new file mode 100644 index 0000000..16e3183 --- /dev/null +++ b/test/e2e/networks/simple.toml @@ -0,0 +1,4 @@ +[node.validator01] +[node.validator02] +[node.validator03] +[node.validator04] diff --git a/test/e2e/networks/single.toml b/test/e2e/networks/single.toml new file mode 100644 index 0000000..afcd913 --- /dev/null +++ b/test/e2e/networks/single.toml @@ -0,0 +1 @@ +[node.validator] diff --git a/test/e2e/networks_regressions/blocksync_blocked.toml b/test/e2e/networks_regressions/blocksync_blocked.toml new file mode 100644 index 0000000..47c7cb3 --- /dev/null +++ b/test/e2e/networks_regressions/blocksync_blocked.toml @@ -0,0 +1,11 @@ +vote_extensions_enable_height = 1 +pbts_enable_height = 1 + +[validators] +validator01 = 67 +validator02 = 33 + +[node.validator01] + +[node.validator02] +start_at = 5 diff --git a/test/e2e/networks_regressions/evidence_fail.toml b/test/e2e/networks_regressions/evidence_fail.toml new file mode 100644 index 0000000..d8a061f --- /dev/null +++ b/test/e2e/networks_regressions/evidence_fail.toml @@ -0,0 +1,16 @@ +evidence = 120 +prometheus = true +pbts_enable_height = 1 + +[validators] + validator01 = 33 + validator02 = 67 + +[node] + [node.validator01] + mode = "validator" + persistent_peers = ["validator02"] + clock_skew = "40s" + [node.validator02] + mode = "validator" + diff --git a/test/e2e/node/built-in.toml b/test/e2e/node/built-in.toml new file mode 100644 index 0000000..6184ff5 --- /dev/null +++ b/test/e2e/node/built-in.toml @@ -0,0 +1,4 @@ +snapshot_interval = 100 +persist_interval = 1 +chain_id = "test-chain" +protocol = "builtin" diff --git a/test/e2e/node/config.go b/test/e2e/node/config.go new file mode 100644 index 0000000..b91120c --- /dev/null +++ b/test/e2e/node/config.go @@ -0,0 +1,72 @@ +package main + +import ( + "errors" + "fmt" + + "github.com/BurntSushi/toml" + + "github.com/cometbft/cometbft/test/e2e/app" +) + +// Config is the application configuration. +type Config struct { + ChainID string `toml:"chain_id"` + Listen string `toml:"listen"` + Protocol string `toml:"protocol"` + Dir string `toml:"dir"` + Mode string `toml:"mode"` + PersistInterval uint64 `toml:"persist_interval"` + SnapshotInterval uint64 `toml:"snapshot_interval"` + RetainBlocks uint64 `toml:"retain_blocks"` + ValidatorUpdates map[string]map[string]uint8 `toml:"validator_update"` + PrivValServer string `toml:"privval_server"` + PrivValKey string `toml:"privval_key"` + PrivValState string `toml:"privval_state"` + KeyType string `toml:"key_type"` + VoteExtensionsEnableHeight int64 `toml:"vote_extensions_enable_height"` + VoteExtensionsUpdateHeight int64 `toml:"vote_extensions_update_height"` +} + +// App extracts out the application specific configuration parameters +func (cfg *Config) App() *app.Config { + return &app.Config{ + Dir: cfg.Dir, + SnapshotInterval: cfg.SnapshotInterval, + RetainBlocks: cfg.RetainBlocks, + KeyType: cfg.KeyType, + ValidatorUpdates: cfg.ValidatorUpdates, + PersistInterval: cfg.PersistInterval, + VoteExtensionsEnableHeight: cfg.VoteExtensionsEnableHeight, + VoteExtensionsUpdateHeight: cfg.VoteExtensionsUpdateHeight, + } +} + +// LoadConfig loads the configuration from disk. +func LoadConfig(file string) (*Config, error) { + cfg := &Config{ + Listen: "unix:///var/run/app.sock", + Protocol: "socket", + PersistInterval: 1, + } + _, err := toml.DecodeFile(file, &cfg) + if err != nil { + return nil, fmt.Errorf("failed to load config from %q: %w", file, err) + } + return cfg, cfg.Validate() +} + +// Validate validates the configuration. We don't do exhaustive config +// validation here, instead relying on Testnet.Validate() to handle it. +// + +func (cfg Config) Validate() error { + switch { + case cfg.ChainID == "": + return errors.New("chain_id parameter is required") + case cfg.Listen == "" && cfg.Protocol != "builtin" && cfg.Protocol != "builtin_connsync": + return errors.New("listen parameter is required") + default: + return nil + } +} diff --git a/test/e2e/node/main.go b/test/e2e/node/main.go new file mode 100644 index 0000000..4ce3822 --- /dev/null +++ b/test/e2e/node/main.go @@ -0,0 +1,293 @@ +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/spf13/viper" + + "github.com/cometbft/cometbft/abci/server" + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto/ed25519" + cmtflags "github.com/cometbft/cometbft/libs/cli/flags" + "github.com/cometbft/cometbft/libs/log" + cmtnet "github.com/cometbft/cometbft/libs/net" + "github.com/cometbft/cometbft/light" + lproxy "github.com/cometbft/cometbft/light/proxy" + lrpc "github.com/cometbft/cometbft/light/rpc" + dbs "github.com/cometbft/cometbft/light/store/db" + "github.com/cometbft/cometbft/node" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + "github.com/cometbft/cometbft/test/e2e/app" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + +// main is the binary entrypoint. +func main() { + if len(os.Args) != 2 { + fmt.Printf("Usage: %v ", os.Args[0]) + return + } + configFile := "" + if len(os.Args) == 2 { + configFile = os.Args[1] + } + + if err := run(configFile); err != nil { + logger.Error(err.Error()) + os.Exit(1) + } +} + +// run runs the application - basically like main() with error handling. +func run(configFile string) error { + cfg, err := LoadConfig(configFile) + if err != nil { + return err + } + + // Start remote signer (must start before node if running builtin). + if cfg.PrivValServer != "" { + if err = startSigner(cfg); err != nil { + return err + } + if cfg.Protocol == string(e2e.ProtocolBuiltin) || cfg.Protocol == string(e2e.ProtocolBuiltinConnSync) { + time.Sleep(1 * time.Second) + } + } + + // Start app server. + switch cfg.Protocol { + case "socket", "grpc": + err = startApp(cfg) + case string(e2e.ProtocolBuiltin), string(e2e.ProtocolBuiltinConnSync): + if cfg.Mode == string(e2e.ModeLight) { + err = startLightClient(cfg) + } else { + err = startNode(cfg) + } + default: + err = fmt.Errorf("invalid protocol %q", cfg.Protocol) + } + if err != nil { + return err + } + + // Apparently there's no way to wait for the server, so we just sleep + for { + time.Sleep(1 * time.Hour) + } +} + +// startApp starts the application server, listening for connections from CometBFT. +func startApp(cfg *Config) error { + app, err := app.NewApplication(cfg.App()) + if err != nil { + return err + } + server, err := server.NewServer(cfg.Listen, cfg.Protocol, app) + if err != nil { + return err + } + err = server.Start() + if err != nil { + return err + } + logger.Info("start app", "msg", log.NewLazySprintf("Server listening on %v (%v protocol)", cfg.Listen, cfg.Protocol)) + return nil +} + +// startNode starts a CometBFT node running the application directly. It assumes the CometBFT +// configuration is in $CMTHOME/config/cometbft.toml. +// +// FIXME There is no way to simply load the configuration from a file, so we need to pull in Viper. +func startNode(cfg *Config) error { + app, err := app.NewApplication(cfg.App()) + if err != nil { + return err + } + + cmtcfg, nodeLogger, nodeKey, err := setupNode() + if err != nil { + return fmt.Errorf("failed to setup config: %w", err) + } + + var clientCreator proxy.ClientCreator + if cfg.Protocol == string(e2e.ProtocolBuiltinConnSync) { + clientCreator = proxy.NewConnSyncLocalClientCreator(app) + nodeLogger.Info("Using connection-synchronized local client creator") + } else { + clientCreator = proxy.NewLocalClientCreator(app) + nodeLogger.Info("Using default (synchronized) local client creator") + } + + n, err := node.NewNode(cmtcfg, + privval.LoadOrGenFilePV(cmtcfg.PrivValidatorKeyFile(), cmtcfg.PrivValidatorStateFile()), + nodeKey, + clientCreator, + node.DefaultGenesisDocProviderFunc(cmtcfg), + config.DefaultDBProvider, + node.DefaultMetricsProvider(cmtcfg.Instrumentation), + nodeLogger, + ) + if err != nil { + return err + } + return n.Start() +} + +func startLightClient(cfg *Config) error { + cmtcfg, nodeLogger, _, err := setupNode() + if err != nil { + return err + } + + dbContext := &config.DBContext{ID: "light", Config: cmtcfg} + lightDB, err := config.DefaultDBProvider(dbContext) + if err != nil { + return err + } + + providers := rpcEndpoints(cmtcfg.P2P.PersistentPeers) + + c, err := light.NewHTTPClient( + context.Background(), + cfg.ChainID, + light.TrustOptions{ + Period: cmtcfg.StateSync.TrustPeriod, + Height: cmtcfg.StateSync.TrustHeight, + Hash: cmtcfg.StateSync.TrustHashBytes(), + }, + providers[0], + providers[1:], + dbs.New(lightDB, "light"), + light.Logger(nodeLogger), + ) + if err != nil { + return err + } + + rpccfg := rpcserver.DefaultConfig() + rpccfg.MaxBodyBytes = cmtcfg.RPC.MaxBodyBytes + rpccfg.MaxHeaderBytes = cmtcfg.RPC.MaxHeaderBytes + rpccfg.MaxOpenConnections = cmtcfg.RPC.MaxOpenConnections + // If necessary adjust global WriteTimeout to ensure it's greater than + // TimeoutBroadcastTxCommit. + // See https://github.com/tendermint/tendermint/issues/3435 + if rpccfg.WriteTimeout <= cmtcfg.RPC.TimeoutBroadcastTxCommit { + rpccfg.WriteTimeout = cmtcfg.RPC.TimeoutBroadcastTxCommit + 1*time.Second + } + + p, err := lproxy.NewProxy(c, cmtcfg.RPC.ListenAddress, providers[0], rpccfg, nodeLogger, + lrpc.KeyPathFn(lrpc.DefaultMerkleKeyPathFn())) + if err != nil { + return err + } + + logger.Info("Starting proxy...", "laddr", cmtcfg.RPC.ListenAddress) + if err := p.ListenAndServe(); err != http.ErrServerClosed { + // Error starting or closing listener: + logger.Error("proxy ListenAndServe", "err", err) + } + + return nil +} + +// startSigner starts a signer server connecting to the given endpoint. +func startSigner(cfg *Config) error { + filePV := privval.LoadFilePV(cfg.PrivValKey, cfg.PrivValState) + + protocol, address := cmtnet.ProtocolAndAddress(cfg.PrivValServer) + var dialFn privval.SocketDialer + switch protocol { + case "tcp": + dialFn = privval.DialTCPFn(address, 3*time.Second, ed25519.GenPrivKey()) + case "unix": + dialFn = privval.DialUnixFn(address) + default: + return fmt.Errorf("invalid privval protocol %q", protocol) + } + + endpoint := privval.NewSignerDialerEndpoint(logger, dialFn, + privval.SignerDialerEndpointRetryWaitInterval(1*time.Second), + privval.SignerDialerEndpointConnRetries(100)) + err := privval.NewSignerServer(endpoint, cfg.ChainID, filePV).Start() + if err != nil { + return err + } + logger.Info("start signer", "msg", log.NewLazySprintf("Remote signer connecting to %v", cfg.PrivValServer)) + return nil +} + +func setupNode() (*config.Config, log.Logger, *p2p.NodeKey, error) { + var cmtcfg *config.Config + + home := os.Getenv("CMTHOME") + if home == "" { + return nil, nil, nil, errors.New("CMTHOME not set") + } + + viper.AddConfigPath(filepath.Join(home, "config")) + viper.SetConfigName("config") + + if err := viper.ReadInConfig(); err != nil { + return nil, nil, nil, err + } + + cmtcfg = config.DefaultConfig() + + if err := viper.Unmarshal(cmtcfg); err != nil { + return nil, nil, nil, err + } + + cmtcfg.SetRoot(home) + + if err := cmtcfg.ValidateBasic(); err != nil { + return nil, nil, nil, fmt.Errorf("error in config file: %w", err) + } + + if cmtcfg.LogFormat == config.LogFormatJSON { + logger = log.NewTMJSONLogger(log.NewSyncWriter(os.Stdout)) + } + + nodeLogger, err := cmtflags.ParseLogLevel(cmtcfg.LogLevel, logger, config.DefaultLogLevel) + if err != nil { + return nil, nil, nil, err + } + + nodeLogger = nodeLogger.With("module", "main") + + nodeKey, err := p2p.LoadOrGenNodeKey(cmtcfg.NodeKeyFile()) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed to load or gen node key %s: %w", cmtcfg.NodeKeyFile(), err) + } + + return cmtcfg, nodeLogger, nodeKey, nil +} + +// rpcEndpoints takes a list of persistent peers and splits them into a list of rpc endpoints +// using 26657 as the port number +func rpcEndpoints(peers string) []string { + arr := strings.Split(peers, ",") + endpoints := make([]string, len(arr)) + for i, v := range arr { + urlString := strings.SplitAfter(v, "@")[1] + hostName := strings.Split(urlString, ":26656")[0] + // use RPC port instead + port := 26657 + rpcEndpoint := "http://" + hostName + ":" + fmt.Sprint(port) + endpoints[i] = rpcEndpoint + } + return endpoints +} diff --git a/test/e2e/node/socket.toml b/test/e2e/node/socket.toml new file mode 100644 index 0000000..44a6ae5 --- /dev/null +++ b/test/e2e/node/socket.toml @@ -0,0 +1,5 @@ +snapshot_interval = 100 +persist_interval = 1 +chain_id = "test-chain" +protocol = "socket" +listen = "tcp://127.0.0.1:26658" diff --git a/test/e2e/pkg/exec/exec.go b/test/e2e/pkg/exec/exec.go new file mode 100644 index 0000000..db529f6 --- /dev/null +++ b/test/e2e/pkg/exec/exec.go @@ -0,0 +1,40 @@ +package exec + +import ( + "context" + "fmt" + "os" + osexec "os/exec" +) + +// Command executes a shell command. +func Command(ctx context.Context, args ...string) error { + _, err := CommandOutput(ctx, args...) + return err +} + +// CommandOutput executes a shell command and returns the command's output. +func CommandOutput(ctx context.Context, args ...string) ([]byte, error) { + //nolint: gosec + // G204: Subprocess launched with a potential tainted input or cmd arguments + cmd := osexec.CommandContext(ctx, args[0], args[1:]...) + out, err := cmd.CombinedOutput() + switch err := err.(type) { + case nil: + return out, nil + case *osexec.ExitError: + return nil, fmt.Errorf("failed to run %q:\n%v", args, string(out)) + default: + return nil, err + } +} + +// CommandVerbose executes a shell command while displaying its output. +func CommandVerbose(ctx context.Context, args ...string) error { + //nolint: gosec + // G204: Subprocess launched with a potential tainted input or cmd arguments + cmd := osexec.CommandContext(ctx, args[0], args[1:]...) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} diff --git a/test/e2e/pkg/infra/digitalocean/digitalocean.go b/test/e2e/pkg/infra/digitalocean/digitalocean.go new file mode 100644 index 0000000..ad357ad --- /dev/null +++ b/test/e2e/pkg/infra/digitalocean/digitalocean.go @@ -0,0 +1,91 @@ +package digitalocean + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/exec" + "github.com/cometbft/cometbft/test/e2e/pkg/infra" +) + +var _ infra.Provider = (*Provider)(nil) + +// Provider implements a DigitalOcean-backed infrastructure provider. +type Provider struct { + infra.ProviderData +} + +// Noop currently. Setup is performed externally to the e2e test tool. +func (p *Provider) Setup() error { + return nil +} + +const ymlSystemd = "systemd-action.yml" + +func (p Provider) StartNodes(ctx context.Context, nodes ...*e2e.Node) error { + nodeIPs := make([]string, len(nodes)) + for i, n := range nodes { + nodeIPs[i] = n.ExternalIP.String() + } + if err := p.writePlaybook(ymlSystemd, true); err != nil { + return err + } + + return execAnsible(ctx, p.Testnet.Dir, ymlSystemd, nodeIPs) +} +func (p Provider) StopTestnet(ctx context.Context) error { + nodeIPs := make([]string, len(p.Testnet.Nodes)) + for i, n := range p.Testnet.Nodes { + nodeIPs[i] = n.ExternalIP.String() + } + + if err := p.writePlaybook(ymlSystemd, false); err != nil { + return err + } + return execAnsible(ctx, p.Testnet.Dir, ymlSystemd, nodeIPs) +} + +func (p Provider) writePlaybook(yaml string, starting bool) error { + playbook := ansibleSystemdBytes(starting) + //nolint: gosec + // G306: Expect WriteFile permissions to be 0600 or less + err := os.WriteFile(filepath.Join(p.Testnet.Dir, yaml), []byte(playbook), 0o644) + if err != nil { + return err + } + return nil +} + +// file as bytes to be written out to disk. +// ansibleStartBytes generates an Ansible playbook to start the network +func ansibleSystemdBytes(starting bool) string { + startStop := "stopped" + if starting { + startStop = "started" + } + playbook := fmt.Sprintf(`- name: start/stop testapp + hosts: all + gather_facts: yes + vars: + ansible_host_key_checking: false + + tasks: + - name: operate on the systemd-unit + ansible.builtin.systemd: + name: testappd + state: %s + enabled: yes`, startStop) + return playbook +} + +// ExecCompose runs a Docker Compose command for a testnet. +func execAnsible(ctx context.Context, dir, playbook string, nodeIPs []string, args ...string) error { + playbook = filepath.Join(dir, playbook) + return exec.CommandVerbose(ctx, append( + []string{"ansible-playbook", playbook, "-f", "50", "-u", "root", "--inventory", strings.Join(nodeIPs, ",") + ","}, + args...)...) +} diff --git a/test/e2e/pkg/infra/docker/docker.go b/test/e2e/pkg/infra/docker/docker.go new file mode 100644 index 0000000..d9eec4d --- /dev/null +++ b/test/e2e/pkg/infra/docker/docker.go @@ -0,0 +1,154 @@ +package docker + +import ( + "bytes" + "context" + "os" + "path/filepath" + "text/template" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/exec" + "github.com/cometbft/cometbft/test/e2e/pkg/infra" +) + +var _ infra.Provider = (*Provider)(nil) + +// Provider implements a docker-compose backed infrastructure provider. +type Provider struct { + infra.ProviderData +} + +// Setup generates the docker-compose file and write it to disk, erroring if +// any of these operations fail. +func (p *Provider) Setup() error { + compose, err := dockerComposeBytes(p.Testnet) + if err != nil { + return err + } + //nolint: gosec + // G306: Expect WriteFile permissions to be 0600 or less + err = os.WriteFile(filepath.Join(p.Testnet.Dir, "docker-compose.yml"), compose, 0o644) + if err != nil { + return err + } + return nil +} + +func (p Provider) StartNodes(ctx context.Context, nodes ...*e2e.Node) error { + nodeNames := make([]string, len(nodes)) + for i, n := range nodes { + nodeNames[i] = n.Name + } + return ExecCompose(ctx, p.Testnet.Dir, append([]string{"up", "-d"}, nodeNames...)...) +} + +func (p Provider) StopTestnet(ctx context.Context) error { + return ExecCompose(ctx, p.Testnet.Dir, "down") +} + +// dockerComposeBytes generates a Docker Compose config file for a testnet and returns the +// file as bytes to be written out to disk. +func dockerComposeBytes(testnet *e2e.Testnet) ([]byte, error) { + // Must use version 2 Docker Compose format, to support IPv6. + tmpl, err := template.New("docker-compose").Parse(`version: '2.4' +networks: + {{ .Name }}: + labels: + e2e: true + driver: bridge +{{- if .IPv6 }} + enable_ipv6: true +{{- end }} + ipam: + driver: default + config: + - subnet: {{ .IP }} + +services: +{{- range .Nodes }} + {{ .Name }}: + labels: + e2e: true + container_name: {{ .Name }} + image: {{ .Version }} +{{- if or (eq .ABCIProtocol "builtin") (eq .ABCIProtocol "builtin_connsync") }} + entrypoint: /usr/bin/entrypoint-builtin +{{- end }} + init: true + ports: + - 26656 + - {{ if .ProxyPort }}{{ .ProxyPort }}:{{ end }}26657 +{{- if .PrometheusProxyPort }} + - {{ .PrometheusProxyPort }}:26660 +{{- end }} + - 6060 + volumes: + - ./{{ .Name }}:/cometbft + - ./{{ .Name }}:/tendermint + networks: + {{ $.Name }}: + ipv{{ if $.IPv6 }}6{{ else }}4{{ end}}_address: {{ .InternalIP }} +{{- if ne .Version $.UpgradeVersion}} + + {{ .Name }}_u: + labels: + e2e: true + container_name: {{ .Name }}_u + image: {{ $.UpgradeVersion }} +{{- if or (eq .ABCIProtocol "builtin") (eq .ABCIProtocol "builtin_connsync") }} + entrypoint: /usr/bin/entrypoint-builtin +{{- end }} + init: true + ports: + - 26656 + - {{ if .ProxyPort }}{{ .ProxyPort }}:{{ end }}26657 +{{- if .PrometheusProxyPort }} + - {{ .PrometheusProxyPort }}:26660 +{{- end }} + - 6060 + volumes: + - ./{{ .Name }}:/cometbft + - ./{{ .Name }}:/tendermint + networks: + {{ $.Name }}: + ipv{{ if $.IPv6 }}6{{ else }}4{{ end}}_address: {{ .InternalIP }} +{{- end }} + +{{end}}`) + if err != nil { + return nil, err + } + var buf bytes.Buffer + err = tmpl.Execute(&buf, testnet) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// ExecCompose runs a Docker Compose command for a testnet. +func ExecCompose(ctx context.Context, dir string, args ...string) error { + return exec.Command(ctx, append( + []string{"docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml")}, + args...)...) +} + +// ExecCompose runs a Docker Compose command for a testnet and returns the command's output. +func ExecComposeOutput(ctx context.Context, dir string, args ...string) ([]byte, error) { + return exec.CommandOutput(ctx, append( + []string{"docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml")}, + args...)...) +} + +// ExecComposeVerbose runs a Docker Compose command for a testnet and displays its output. +func ExecComposeVerbose(ctx context.Context, dir string, args ...string) error { + return exec.CommandVerbose(ctx, append( + []string{"docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml")}, + args...)...) +} + +// Exec runs a Docker command. +func Exec(ctx context.Context, args ...string) error { + return exec.Command(ctx, append([]string{"docker"}, args...)...) +} diff --git a/test/e2e/pkg/infra/provider.go b/test/e2e/pkg/infra/provider.go new file mode 100644 index 0000000..9363859 --- /dev/null +++ b/test/e2e/pkg/infra/provider.go @@ -0,0 +1,37 @@ +package infra + +import ( + "context" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +// Provider defines an API for manipulating the infrastructure of a +// specific set of testnet infrastructure. +type Provider interface { + + // Setup generates any necessary configuration for the infrastructure + // provider during testnet setup. + Setup() error + + // Starts the nodes passed as parameter. A nodes MUST NOT + // be started twice before calling StopTestnet + // If no nodes are passed, start the whole network + StartNodes(context.Context, ...*e2e.Node) error + + // Stops the whole network + StopTestnet(context.Context) error + + // Returns the the provider's infrastructure data + GetInfrastructureData() *e2e.InfrastructureData +} + +type ProviderData struct { + Testnet *e2e.Testnet + InfrastructureData e2e.InfrastructureData +} + +// Returns the the provider's infrastructure data +func (pd ProviderData) GetInfrastructureData() *e2e.InfrastructureData { + return &pd.InfrastructureData +} diff --git a/test/e2e/pkg/infrastructure.go b/test/e2e/pkg/infrastructure.go new file mode 100644 index 0000000..b57c082 --- /dev/null +++ b/test/e2e/pkg/infrastructure.go @@ -0,0 +1,101 @@ +package e2e + +import ( + "encoding/json" + "fmt" + "net" + "os" + "sort" +) + +const ( + dockerIPv4CIDR = "10.186.73.0/24" + dockerIPv6CIDR = "fd80:b10c::/48" + + globalIPv4CIDR = "0.0.0.0/0" +) + +// InfrastructureData contains the relevant information for a set of existing +// infrastructure that is to be used for running a testnet. +type InfrastructureData struct { + Path string + + // Provider is the name of infrastructure provider backing the testnet. + // For example, 'docker' if it is running locally in a docker network or + // 'digital-ocean', 'aws', 'google', etc. if it is from a cloud provider. + Provider string `json:"provider"` + + // Instances is a map of all of the machine instances on which to run + // processes for a testnet. + // The key of the map is the name of the instance, which each must correspond + // to the names of one of the testnet nodes defined in the testnet manifest. + Instances map[string]InstanceData `json:"instances"` + + // Network is the CIDR notation range of IP addresses that all of the instances' + // IP addresses are expected to be within. + Network string `json:"network"` +} + +// InstanceData contains the relevant information for a machine instance backing +// one of the nodes in the testnet. +type InstanceData struct { + IPAddress net.IP `json:"ip_address"` + ExtIPAddress net.IP `json:"ext_ip_address"` + Port uint32 `json:"port"` +} + +func sortNodeNames(m Manifest) []string { + // Set up nodes, in alphabetical order (IPs and ports get same order). + nodeNames := []string{} + for name := range m.Nodes { + nodeNames = append(nodeNames, name) + } + sort.Strings(nodeNames) + return nodeNames +} + +func NewDockerInfrastructureData(m Manifest) (InfrastructureData, error) { + netAddress := dockerIPv4CIDR + if m.IPv6 { + netAddress = dockerIPv6CIDR + } + _, ipNet, err := net.ParseCIDR(netAddress) + if err != nil { + return InfrastructureData{}, fmt.Errorf("invalid IP network address %q: %w", netAddress, err) + } + + portGen := newPortGenerator(proxyPortFirst) + ipGen := newIPGenerator(ipNet) + ifd := InfrastructureData{ + Provider: "docker", + Instances: make(map[string]InstanceData), + Network: netAddress, + } + localHostIP := net.ParseIP("127.0.0.1") + for _, name := range sortNodeNames(m) { + ifd.Instances[name] = InstanceData{ + IPAddress: ipGen.Next(), + ExtIPAddress: localHostIP, + Port: portGen.Next(), + } + + } + return ifd, nil +} + +func InfrastructureDataFromFile(p string) (InfrastructureData, error) { + ifd := InfrastructureData{} + b, err := os.ReadFile(p) + if err != nil { + return InfrastructureData{}, err + } + err = json.Unmarshal(b, &ifd) + if err != nil { + return InfrastructureData{}, err + } + if ifd.Network == "" { + ifd.Network = globalIPv4CIDR + } + ifd.Path = p + return ifd, nil +} diff --git a/test/e2e/pkg/manifest.go b/test/e2e/pkg/manifest.go new file mode 100644 index 0000000..4a18b78 --- /dev/null +++ b/test/e2e/pkg/manifest.go @@ -0,0 +1,210 @@ +package e2e + +import ( + "fmt" + "os" + "time" + + "github.com/BurntSushi/toml" +) + +// Manifest represents a TOML testnet manifest. +type Manifest struct { + // IPv6 uses IPv6 networking instead of IPv4. Defaults to IPv4. + IPv6 bool `toml:"ipv6"` + + // InitialHeight specifies the initial block height, set in genesis. Defaults to 1. + InitialHeight int64 `toml:"initial_height"` + + // InitialState is an initial set of key/value pairs for the application, + // set in genesis. Defaults to nothing. + InitialState map[string]string `toml:"initial_state"` + + // Validators is the initial validator set in genesis, given as node names + // and power: + // + // validators = { validator01 = 10; validator02 = 20; validator03 = 30 } + // + // Defaults to all nodes that have mode=validator at power 100. Explicitly + // specifying an empty set will start with no validators in genesis, and + // the application must return the validator set in InitChain via the + // setting validator_update.0 (see below). + Validators *map[string]int64 `toml:"validators"` + + // ValidatorUpdates is a map of heights to validator names and their power, + // and will be returned by the ABCI application. For example, the following + // changes the power of validator01 and validator02 at height 1000: + // + // [validator_update.1000] + // validator01 = 20 + // validator02 = 10 + // + // Specifying height 0 returns the validator update during InitChain. The + // application returns the validator updates as-is, i.e. removing a + // validator must be done by returning it with power 0, and any validators + // not specified are not changed. + ValidatorUpdates map[string]map[string]int64 `toml:"validator_update"` + + // Nodes specifies the network nodes. At least one node must be given. + Nodes map[string]*ManifestNode `toml:"node"` + + // KeyType sets the curve that will be used by validators. + // Options are ed25519, secp256k1 and sr25519. + KeyType string `toml:"key_type"` + + // Evidence indicates the amount of evidence that will be injected into the + // testnet via the RPC endpoint of a random node. Default is 0 + Evidence int `toml:"evidence"` + + // ABCIProtocol specifies the protocol used to communicate with the ABCI + // application: "unix", "tcp", "grpc", "builtin" or "builtin_connsync". + // + // Defaults to "builtin". "builtin" will build a complete CometBFT node + // into the application and launch it instead of launching a separate + // CometBFT process. + // + // "builtin_connsync" is basically the same as "builtin", except that it + // uses a "connection-synchronized" local client creator, which attempts to + // replicate the same concurrency model locally as the socket client. + ABCIProtocol string `toml:"abci_protocol"` + + // Add artificial delays to each of the main ABCI calls to mimic computation time + // of the application + PrepareProposalDelay time.Duration `toml:"prepare_proposal_delay"` + ProcessProposalDelay time.Duration `toml:"process_proposal_delay"` + CheckTxDelay time.Duration `toml:"check_tx_delay"` + VoteExtensionDelay time.Duration `toml:"vote_extension_delay"` + FinalizeBlockDelay time.Duration `toml:"finalize_block_delay"` + + // UpgradeVersion specifies to which version nodes need to upgrade. + // Currently only uncoordinated upgrade is supported + UpgradeVersion string `toml:"upgrade_version"` + + LoadTxSizeBytes int `toml:"load_tx_size_bytes"` + LoadTxBatchSize int `toml:"load_tx_batch_size"` + LoadTxConnections int `toml:"load_tx_connections"` + LoadMaxTxs int `toml:"load_max_txs"` + + // LogLevel specifies the log level to be set on all nodes. + LogLevel string `toml:"log_level"` + + // LogFormat specifies the log format to be set on all nodes. + LogFormat string `toml:"log_format"` + + // Enable or disable Prometheus metrics on all nodes. + // Defaults to false (disabled). + Prometheus bool `toml:"prometheus"` + + // BlockMaxBytes specifies the maximum size in bytes of a block. This + // value will be written to the genesis file of all nodes. + BlockMaxBytes int64 `toml:"block_max_bytes"` + + // VoteExtensionsEnableHeight configures the first height during which + // the chain will use and require vote extension data to be present + // in precommit messages. + VoteExtensionsEnableHeight int64 `toml:"vote_extensions_enable_height"` + + // VoteExtensionsUpdateHeight configures the height at which consensus + // param VoteExtensionsEnableHeight will be set. + // -1 denotes it is set at genesis. + // 0 denotes it is set at InitChain. + VoteExtensionsUpdateHeight int64 `toml:"vote_extensions_update_height"` + // Maximum number of peers to which the node gossips transactions + ExperimentalMaxGossipConnectionsToPersistentPeers uint `toml:"experimental_max_gossip_connections_to_persistent_peers"` + ExperimentalMaxGossipConnectionsToNonPersistentPeers uint `toml:"experimental_max_gossip_connections_to_non_persistent_peers"` +} + +// ManifestNode represents a node in a testnet manifest. +type ManifestNode struct { + // Mode specifies the type of node: "validator", "full", "light" or "seed". + // Defaults to "validator". Full nodes do not get a signing key (a dummy key + // is generated), and seed nodes run in seed mode with the PEX reactor enabled. + Mode string `toml:"mode"` + + // Version specifies which version of CometBFT this node is. Specifying different + // versions for different nodes allows for testing the interaction of different + // node's compatibility. Note that in order to use a node at a particular version, + // there must be a docker image of the test app tagged with this version present + // on the machine where the test is being run. + Version string `toml:"version"` + + // Seeds is the list of node names to use as P2P seed nodes. Defaults to none. + Seeds []string `toml:"seeds"` + + // PersistentPeers is a list of node names to maintain persistent P2P + // connections to. If neither seeds nor persistent peers are specified, + // this defaults to all other nodes in the network. For light clients, + // this relates to the providers the light client is connected to. + PersistentPeers []string `toml:"persistent_peers"` + + // Database specifies the database backend: "goleveldb", "cleveldb", + // "rocksdb", "boltdb", or "badgerdb". Defaults to goleveldb. + Database string `toml:"database"` + + // PrivvalProtocol specifies the protocol used to sign consensus messages: + // "file", "unix", or "tcp". Defaults to "file". For unix and tcp, the ABCI + // application will launch a remote signer client in a separate goroutine. + // Only nodes with mode=validator will actually make use of this. + PrivvalProtocol string `toml:"privval_protocol"` + + // StartAt specifies the block height at which the node will be started. The + // runner will wait for the network to reach at least this block height. + StartAt int64 `toml:"start_at"` + + // BlockSyncVersion specifies which version of Block Sync to use (currently + // only "v0", the default value). + BlockSyncVersion string `toml:"block_sync_version"` + + // StateSync enables state sync. The runner automatically configures trusted + // block hashes and RPC servers. At least one node in the network must have + // SnapshotInterval set to non-zero, and the state syncing node must have + // StartAt set to an appropriate height where a snapshot is available. + StateSync bool `toml:"state_sync"` + + // PersistInterval specifies the height interval at which the application + // will persist state to disk. Defaults to 1 (every height), setting this to + // 0 disables state persistence. + PersistInterval *uint64 `toml:"persist_interval"` + + // SnapshotInterval specifies the height interval at which the application + // will take state sync snapshots. Defaults to 0 (disabled). + SnapshotInterval uint64 `toml:"snapshot_interval"` + + // RetainBlocks specifies the number of recent blocks to retain. Defaults to + // 0, which retains all blocks. Must be greater that PersistInterval, + // SnapshotInterval and EvidenceAgeHeight. + RetainBlocks uint64 `toml:"retain_blocks"` + + // Perturb lists perturbations to apply to the node after it has been + // started and synced with the network: + // + // disconnect: temporarily disconnects the node from the network + // kill: kills the node with SIGKILL then restarts it + // pause: temporarily pauses (freezes) the node + // restart: restarts the node, shutting it down with SIGTERM + Perturb []string `toml:"perturb"` + + // SendNoLoad determines if the e2e test should send load to this node. + // It defaults to false so unless the configured, the node will + // receive load. + SendNoLoad bool `toml:"send_no_load"` +} + +// Save saves the testnet manifest to a file. +func (m Manifest) Save(file string) error { + f, err := os.Create(file) + if err != nil { + return fmt.Errorf("failed to create manifest file %q: %w", file, err) + } + return toml.NewEncoder(f).Encode(m) +} + +// LoadManifest loads a testnet manifest from a file. +func LoadManifest(file string) (Manifest, error) { + manifest := Manifest{} + _, err := toml.DecodeFile(file, &manifest) + if err != nil { + return manifest, fmt.Errorf("failed to load testnet manifest %q: %w", file, err) + } + return manifest, nil +} diff --git a/test/e2e/pkg/templates/prometheus-yaml.tmpl b/test/e2e/pkg/templates/prometheus-yaml.tmpl new file mode 100644 index 0000000..95ee224 --- /dev/null +++ b/test/e2e/pkg/templates/prometheus-yaml.tmpl @@ -0,0 +1,9 @@ +global: + scrape_interval: 1s + +scrape_configs: +{{- range .Nodes }} + - job_name: '{{ .Name }}' + static_configs: + - targets: ['localhost:{{ .PrometheusProxyPort }}'] +{{end}} \ No newline at end of file diff --git a/test/e2e/pkg/testnet.go b/test/e2e/pkg/testnet.go new file mode 100644 index 0000000..0bbd585 --- /dev/null +++ b/test/e2e/pkg/testnet.go @@ -0,0 +1,685 @@ +package e2e + +import ( + "bytes" + "errors" + "fmt" + "io" + "math/rand" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "text/template" + "time" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/secp256k1" + "github.com/cometbft/cometbft/crypto/sr25519" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cometbft/cometbft/types" + + _ "embed" +) + +const ( + randomSeed int64 = 2308084734268 + proxyPortFirst uint32 = 5701 + prometheusProxyPortFirst uint32 = 6701 + + defaultBatchSize = 2 + defaultConnections = 1 + defaultTxSizeBytes = 1024 + + localVersion = "cometbft/e2e-node:local-version" +) + +type ( + Mode string + Protocol string + Perturbation string +) + +const ( + ModeValidator Mode = "validator" + ModeFull Mode = "full" + ModeLight Mode = "light" + ModeSeed Mode = "seed" + + ProtocolBuiltin Protocol = "builtin" + ProtocolBuiltinConnSync Protocol = "builtin_connsync" + ProtocolFile Protocol = "file" + ProtocolGRPC Protocol = "grpc" + ProtocolTCP Protocol = "tcp" + ProtocolUNIX Protocol = "unix" + + PerturbationDisconnect Perturbation = "disconnect" + PerturbationKill Perturbation = "kill" + PerturbationPause Perturbation = "pause" + PerturbationRestart Perturbation = "restart" + PerturbationUpgrade Perturbation = "upgrade" + + EvidenceAgeHeight int64 = 14 + EvidenceAgeTime time.Duration = 1500 * time.Millisecond +) + +// Testnet represents a single testnet. +type Testnet struct { + Name string + File string + Dir string + IP *net.IPNet + InitialHeight int64 + InitialState map[string]string + Validators map[*Node]int64 + ValidatorUpdates map[int64]map[*Node]int64 + Nodes []*Node + KeyType string + Evidence int + LoadTxSizeBytes int + LoadTxBatchSize int + LoadTxConnections int + LoadMaxTxs int + ABCIProtocol string + PrepareProposalDelay time.Duration + ProcessProposalDelay time.Duration + CheckTxDelay time.Duration + VoteExtensionDelay time.Duration + FinalizeBlockDelay time.Duration + UpgradeVersion string + LogLevel string + LogFormat string + Prometheus bool + BlockMaxBytes int64 + VoteExtensionsEnableHeight int64 + VoteExtensionsUpdateHeight int64 + ExperimentalMaxGossipConnectionsToPersistentPeers uint + ExperimentalMaxGossipConnectionsToNonPersistentPeers uint +} + +// Node represents a CometBFT node in a testnet. +type Node struct { + Name string + Version string + Testnet *Testnet + Mode Mode + PrivvalKey crypto.PrivKey + NodeKey crypto.PrivKey + InternalIP net.IP + ExternalIP net.IP + ProxyPort uint32 + StartAt int64 + BlockSyncVersion string + StateSync bool + Database string + ABCIProtocol Protocol + PrivvalProtocol Protocol + PersistInterval uint64 + SnapshotInterval uint64 + RetainBlocks uint64 + Seeds []*Node + PersistentPeers []*Node + Perturbations []Perturbation + SendNoLoad bool + Prometheus bool + PrometheusProxyPort uint32 +} + +// LoadTestnet loads a testnet from a manifest file, using the filename to +// determine the testnet name and directory (from the basename of the file). +// The testnet generation must be deterministic, since it is generated +// separately by the runner and the test cases. For this reason, testnets use a +// random seed to generate e.g. keys. +func LoadTestnet(file string, ifd InfrastructureData) (*Testnet, error) { + manifest, err := LoadManifest(file) + if err != nil { + return nil, err + } + return NewTestnetFromManifest(manifest, file, ifd) +} + +// NewTestnetFromManifest creates and validates a testnet from a manifest +func NewTestnetFromManifest(manifest Manifest, file string, ifd InfrastructureData) (*Testnet, error) { + dir := strings.TrimSuffix(file, filepath.Ext(file)) + + keyGen := newKeyGenerator(randomSeed) + prometheusProxyPortGen := newPortGenerator(prometheusProxyPortFirst) + _, ipNet, err := net.ParseCIDR(ifd.Network) + if err != nil { + return nil, fmt.Errorf("invalid IP network address %q: %w", ifd.Network, err) + } + + testnet := &Testnet{ + Name: filepath.Base(dir), + File: file, + Dir: dir, + IP: ipNet, + InitialHeight: 1, + InitialState: manifest.InitialState, + Validators: map[*Node]int64{}, + ValidatorUpdates: map[int64]map[*Node]int64{}, + Nodes: []*Node{}, + Evidence: manifest.Evidence, + LoadTxSizeBytes: manifest.LoadTxSizeBytes, + LoadTxBatchSize: manifest.LoadTxBatchSize, + LoadTxConnections: manifest.LoadTxConnections, + LoadMaxTxs: manifest.LoadMaxTxs, + ABCIProtocol: manifest.ABCIProtocol, + PrepareProposalDelay: manifest.PrepareProposalDelay, + ProcessProposalDelay: manifest.ProcessProposalDelay, + CheckTxDelay: manifest.CheckTxDelay, + VoteExtensionDelay: manifest.VoteExtensionDelay, + FinalizeBlockDelay: manifest.FinalizeBlockDelay, + UpgradeVersion: manifest.UpgradeVersion, + LogLevel: manifest.LogLevel, + LogFormat: manifest.LogFormat, + Prometheus: manifest.Prometheus, + BlockMaxBytes: manifest.BlockMaxBytes, + VoteExtensionsEnableHeight: manifest.VoteExtensionsEnableHeight, + VoteExtensionsUpdateHeight: manifest.VoteExtensionsUpdateHeight, + ExperimentalMaxGossipConnectionsToPersistentPeers: manifest.ExperimentalMaxGossipConnectionsToPersistentPeers, + ExperimentalMaxGossipConnectionsToNonPersistentPeers: manifest.ExperimentalMaxGossipConnectionsToNonPersistentPeers, + } + if len(manifest.KeyType) != 0 { + testnet.KeyType = manifest.KeyType + } + if manifest.InitialHeight > 0 { + testnet.InitialHeight = manifest.InitialHeight + } + if testnet.ABCIProtocol == "" { + testnet.ABCIProtocol = string(ProtocolBuiltin) + } + if testnet.UpgradeVersion == "" { + testnet.UpgradeVersion = localVersion + } + if testnet.LoadTxConnections == 0 { + testnet.LoadTxConnections = defaultConnections + } + if testnet.LoadTxBatchSize == 0 { + testnet.LoadTxBatchSize = defaultBatchSize + } + if testnet.LoadTxSizeBytes == 0 { + testnet.LoadTxSizeBytes = defaultTxSizeBytes + } + + for _, name := range sortNodeNames(manifest) { + nodeManifest := manifest.Nodes[name] + ind, ok := ifd.Instances[name] + if !ok { + return nil, fmt.Errorf("information for node '%s' missing from infrastructure data", name) + } + extIP := ind.ExtIPAddress + if len(extIP) == 0 { + extIP = ind.IPAddress + } + v := nodeManifest.Version + if v == "" { + v = localVersion + } + + node := &Node{ + Name: name, + Version: v, + Testnet: testnet, + PrivvalKey: keyGen.Generate(manifest.KeyType), + NodeKey: keyGen.Generate("ed25519"), + InternalIP: ind.IPAddress, + ExternalIP: extIP, + ProxyPort: ind.Port, + Mode: ModeValidator, + Database: "goleveldb", + ABCIProtocol: Protocol(testnet.ABCIProtocol), + PrivvalProtocol: ProtocolFile, + StartAt: nodeManifest.StartAt, + BlockSyncVersion: nodeManifest.BlockSyncVersion, + StateSync: nodeManifest.StateSync, + PersistInterval: 1, + SnapshotInterval: nodeManifest.SnapshotInterval, + RetainBlocks: nodeManifest.RetainBlocks, + Perturbations: []Perturbation{}, + SendNoLoad: nodeManifest.SendNoLoad, + Prometheus: testnet.Prometheus, + } + if node.StartAt == testnet.InitialHeight { + node.StartAt = 0 // normalize to 0 for initial nodes, since code expects this + } + if node.BlockSyncVersion == "" { + node.BlockSyncVersion = "v0" + } + if nodeManifest.Mode != "" { + node.Mode = Mode(nodeManifest.Mode) + } + if node.Mode == ModeLight { + node.ABCIProtocol = ProtocolBuiltin + } + if nodeManifest.Database != "" { + node.Database = nodeManifest.Database + } + if nodeManifest.PrivvalProtocol != "" { + node.PrivvalProtocol = Protocol(nodeManifest.PrivvalProtocol) + } + if nodeManifest.PersistInterval != nil { + node.PersistInterval = *nodeManifest.PersistInterval + } + if node.Prometheus { + node.PrometheusProxyPort = prometheusProxyPortGen.Next() + } + for _, p := range nodeManifest.Perturb { + node.Perturbations = append(node.Perturbations, Perturbation(p)) + } + testnet.Nodes = append(testnet.Nodes, node) + } + + // We do a second pass to set up seeds and persistent peers, which allows graph cycles. + for _, node := range testnet.Nodes { + nodeManifest, ok := manifest.Nodes[node.Name] + if !ok { + return nil, fmt.Errorf("failed to look up manifest for node %q", node.Name) + } + for _, seedName := range nodeManifest.Seeds { + seed := testnet.LookupNode(seedName) + if seed == nil { + return nil, fmt.Errorf("unknown seed %q for node %q", seedName, node.Name) + } + node.Seeds = append(node.Seeds, seed) + } + for _, peerName := range nodeManifest.PersistentPeers { + peer := testnet.LookupNode(peerName) + if peer == nil { + return nil, fmt.Errorf("unknown persistent peer %q for node %q", peerName, node.Name) + } + node.PersistentPeers = append(node.PersistentPeers, peer) + } + + // If there are no seeds or persistent peers specified, default to persistent + // connections to all other nodes. + if len(node.PersistentPeers) == 0 && len(node.Seeds) == 0 { + for _, peer := range testnet.Nodes { + if peer.Name == node.Name { + continue + } + node.PersistentPeers = append(node.PersistentPeers, peer) + } + } + } + + // Set up genesis validators. If not specified explicitly, use all validator nodes. + if manifest.Validators != nil { + for validatorName, power := range *manifest.Validators { + validator := testnet.LookupNode(validatorName) + if validator == nil { + return nil, fmt.Errorf("unknown validator %q", validatorName) + } + testnet.Validators[validator] = power + } + } else { + for _, node := range testnet.Nodes { + if node.Mode == ModeValidator { + testnet.Validators[node] = 100 + } + } + } + + // Set up validator updates. + for heightStr, validators := range manifest.ValidatorUpdates { + height, err := strconv.Atoi(heightStr) + if err != nil { + return nil, fmt.Errorf("invalid validator update height %q: %w", height, err) + } + valUpdate := map[*Node]int64{} + for name, power := range validators { + node := testnet.LookupNode(name) + if node == nil { + return nil, fmt.Errorf("unknown validator %q for update at height %v", name, height) + } + valUpdate[node] = power + } + testnet.ValidatorUpdates[int64(height)] = valUpdate + } + + return testnet, testnet.Validate() +} + +// Validate validates a testnet. +func (t Testnet) Validate() error { + if t.Name == "" { + return errors.New("network has no name") + } + if t.IP == nil { + return errors.New("network has no IP") + } + if len(t.Nodes) == 0 { + return errors.New("network has no nodes") + } + if t.BlockMaxBytes > types.MaxBlockSizeBytes { + return fmt.Errorf("value of BlockMaxBytes cannot be higher than %d", types.MaxBlockSizeBytes) + } + if t.VoteExtensionsUpdateHeight < -1 { + return fmt.Errorf("value of VoteExtensionsUpdateHeight must be positive, 0 (InitChain), "+ + "or -1 (Genesis); update height %d", t.VoteExtensionsUpdateHeight) + } + if t.VoteExtensionsEnableHeight < 0 { + return fmt.Errorf("value of VoteExtensionsEnableHeight must be positive, or 0 (disable); "+ + "enable height %d", t.VoteExtensionsEnableHeight) + } + if t.VoteExtensionsUpdateHeight > 0 && t.VoteExtensionsUpdateHeight < t.InitialHeight { + return fmt.Errorf("a value of VoteExtensionsUpdateHeight greater than 0 "+ + "must not be less than InitialHeight; "+ + "update height %d, initial height %d", + t.VoteExtensionsUpdateHeight, t.InitialHeight, + ) + } + if t.VoteExtensionsEnableHeight > 0 { + if t.VoteExtensionsEnableHeight < t.InitialHeight { + return fmt.Errorf("a value of VoteExtensionsEnableHeight greater than 0 "+ + "must not be less than InitialHeight; "+ + "enable height %d, initial height %d", + t.VoteExtensionsEnableHeight, t.InitialHeight, + ) + } + if t.VoteExtensionsEnableHeight <= t.VoteExtensionsUpdateHeight { + return fmt.Errorf("a value of VoteExtensionsEnableHeight greater than 0 "+ + "must be greater than VoteExtensionsUpdateHeight; "+ + "update height %d, enable height %d", + t.VoteExtensionsUpdateHeight, t.VoteExtensionsEnableHeight, + ) + } + } + for _, node := range t.Nodes { + if err := node.Validate(t); err != nil { + return fmt.Errorf("invalid node %q: %w", node.Name, err) + } + } + return nil +} + +// Validate validates a node. +func (n Node) Validate(testnet Testnet) error { + if n.Name == "" { + return errors.New("node has no name") + } + if n.InternalIP == nil { + return errors.New("node has no IP address") + } + if !testnet.IP.Contains(n.InternalIP) { + return fmt.Errorf("node IP %v is not in testnet network %v", n.InternalIP, testnet.IP) + } + if n.ProxyPort == n.PrometheusProxyPort { + return fmt.Errorf("node local port %v used also for Prometheus local port", n.ProxyPort) + } + if n.ProxyPort > 0 && n.ProxyPort <= 1024 { + return fmt.Errorf("local port %v must be >1024", n.ProxyPort) + } + if n.PrometheusProxyPort > 0 && n.PrometheusProxyPort <= 1024 { + return fmt.Errorf("local port %v must be >1024", n.PrometheusProxyPort) + } + for _, peer := range testnet.Nodes { + if peer.Name != n.Name && peer.ProxyPort == n.ProxyPort && peer.ExternalIP.Equal(n.ExternalIP) { + return fmt.Errorf("peer %q also has local port %v", peer.Name, n.ProxyPort) + } + if n.PrometheusProxyPort > 0 { + if peer.Name != n.Name && peer.PrometheusProxyPort == n.PrometheusProxyPort { + return fmt.Errorf("peer %q also has local port %v", peer.Name, n.PrometheusProxyPort) + } + } + } + switch n.BlockSyncVersion { + case "v0": + default: + return fmt.Errorf("invalid block sync setting %q", n.BlockSyncVersion) + } + switch n.Database { + case "goleveldb", "cleveldb", "boltdb", "rocksdb", "badgerdb": + default: + return fmt.Errorf("invalid database setting %q", n.Database) + } + switch n.ABCIProtocol { + case ProtocolBuiltin, ProtocolBuiltinConnSync, ProtocolUNIX, ProtocolTCP, ProtocolGRPC: + default: + return fmt.Errorf("invalid ABCI protocol setting %q", n.ABCIProtocol) + } + if n.Mode == ModeLight && n.ABCIProtocol != ProtocolBuiltin && n.ABCIProtocol != ProtocolBuiltinConnSync { + return errors.New("light client must use builtin protocol") + } + switch n.PrivvalProtocol { + case ProtocolFile, ProtocolUNIX, ProtocolTCP: + default: + return fmt.Errorf("invalid privval protocol setting %q", n.PrivvalProtocol) + } + + if n.StartAt > 0 && n.StartAt < n.Testnet.InitialHeight { + return fmt.Errorf("cannot start at height %v lower than initial height %v", + n.StartAt, n.Testnet.InitialHeight) + } + if n.StateSync && n.StartAt == 0 { + return errors.New("state synced nodes cannot start at the initial height") + } + if n.RetainBlocks != 0 && n.RetainBlocks < uint64(EvidenceAgeHeight) { + return fmt.Errorf("retain_blocks must be 0 or be greater or equal to max evidence age (%d)", + EvidenceAgeHeight) + } + if n.PersistInterval == 0 && n.RetainBlocks > 0 { + return errors.New("persist_interval=0 requires retain_blocks=0") + } + if n.PersistInterval > 1 && n.RetainBlocks > 0 && n.RetainBlocks < n.PersistInterval { + return errors.New("persist_interval must be less than or equal to retain_blocks") + } + if n.SnapshotInterval > 0 && n.RetainBlocks > 0 && n.RetainBlocks < n.SnapshotInterval { + return errors.New("snapshot_interval must be less than er equal to retain_blocks") + } + + var upgradeFound bool + for _, perturbation := range n.Perturbations { + switch perturbation { + case PerturbationUpgrade: + if upgradeFound { + return fmt.Errorf("'upgrade' perturbation can appear at most once per node") + } + upgradeFound = true + case PerturbationDisconnect, PerturbationKill, PerturbationPause, PerturbationRestart: + default: + return fmt.Errorf("invalid perturbation %q", perturbation) + } + } + + return nil +} + +// LookupNode looks up a node by name. For now, simply do a linear search. +func (t Testnet) LookupNode(name string) *Node { + for _, node := range t.Nodes { + if node.Name == name { + return node + } + } + return nil +} + +// ArchiveNodes returns a list of archive nodes that start at the initial height +// and contain the entire blockchain history. They are used e.g. as light client +// RPC servers. +func (t Testnet) ArchiveNodes() []*Node { + nodes := []*Node{} + for _, node := range t.Nodes { + if !node.Stateless() && node.StartAt == 0 && node.RetainBlocks == 0 { + nodes = append(nodes, node) + } + } + return nodes +} + +// RandomNode returns a random non-seed node. +func (t Testnet) RandomNode() *Node { + for { + node := t.Nodes[rand.Intn(len(t.Nodes))] //nolint:gosec + if node.Mode != ModeSeed { + return node + } + } +} + +// IPv6 returns true if the testnet is an IPv6 network. +func (t Testnet) IPv6() bool { + return t.IP.IP.To4() == nil +} + +// HasPerturbations returns whether the network has any perturbations. +func (t Testnet) HasPerturbations() bool { + for _, node := range t.Nodes { + if len(node.Perturbations) > 0 { + return true + } + } + return false +} + +//go:embed templates/prometheus-yaml.tmpl +var prometheusYamlTemplate string + +func (t Testnet) prometheusConfigBytes() ([]byte, error) { + tmpl, err := template.New("prometheus-yaml").Parse(prometheusYamlTemplate) + if err != nil { + return nil, err + } + var buf bytes.Buffer + err = tmpl.Execute(&buf, t) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func (t Testnet) WritePrometheusConfig() error { + bytes, err := t.prometheusConfigBytes() + if err != nil { + return err + } + err = os.WriteFile(filepath.Join(t.Dir, "prometheus.yaml"), bytes, 0o644) //nolint:gosec + if err != nil { + return err + } + return nil +} + +// Address returns a P2P endpoint address for the node. +func (n Node) AddressP2P(withID bool) string { + ip := n.InternalIP.String() + if n.InternalIP.To4() == nil { + // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator + ip = fmt.Sprintf("[%v]", ip) + } + addr := fmt.Sprintf("%v:26656", ip) + if withID { + addr = fmt.Sprintf("%x@%v", n.NodeKey.PubKey().Address().Bytes(), addr) + } + return addr +} + +// Address returns an RPC endpoint address for the node. +func (n Node) AddressRPC() string { + ip := n.InternalIP.String() + if n.InternalIP.To4() == nil { + // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator + ip = fmt.Sprintf("[%v]", ip) + } + return fmt.Sprintf("%v:26657", ip) +} + +// Client returns an RPC client for a node. +func (n Node) Client() (*rpchttp.HTTP, error) { + return rpchttp.New(fmt.Sprintf("http://%s:%v", n.ExternalIP, n.ProxyPort), "/websocket") +} + +// Stateless returns true if the node is either a seed node or a light node +func (n Node) Stateless() bool { + return n.Mode == ModeLight || n.Mode == ModeSeed +} + +// keyGenerator generates pseudorandom Ed25519 keys based on a seed. +type keyGenerator struct { + random *rand.Rand +} + +func newKeyGenerator(seed int64) *keyGenerator { + return &keyGenerator{ + random: rand.New(rand.NewSource(seed)), //nolint:gosec + } +} + +func (g *keyGenerator) Generate(keyType string) crypto.PrivKey { + seed := make([]byte, ed25519.SeedSize) + + _, err := io.ReadFull(g.random, seed) + if err != nil { + panic(err) // this shouldn't happen + } + switch keyType { + case "secp256k1": + return secp256k1.GenPrivKeySecp256k1(seed) + case "sr25519": + return sr25519.GenPrivKeyFromSecret(seed) + case "", "ed25519": + return ed25519.GenPrivKeyFromSecret(seed) + default: + panic("KeyType not supported") // should not make it this far + } +} + +// portGenerator generates local Docker proxy ports for each node. +type portGenerator struct { + nextPort uint32 +} + +func newPortGenerator(firstPort uint32) *portGenerator { + return &portGenerator{nextPort: firstPort} +} + +func (g *portGenerator) Next() uint32 { + port := g.nextPort + g.nextPort++ + if g.nextPort == 0 { + panic("port overflow") + } + return port +} + +// ipGenerator generates sequential IP addresses for each node, using a random +// network address. +type ipGenerator struct { + network *net.IPNet + nextIP net.IP +} + +func newIPGenerator(network *net.IPNet) *ipGenerator { + nextIP := make([]byte, len(network.IP)) + copy(nextIP, network.IP) + gen := &ipGenerator{network: network, nextIP: nextIP} + // Skip network and gateway addresses + gen.Next() + gen.Next() + return gen +} + +func (g *ipGenerator) Network() *net.IPNet { + n := &net.IPNet{ + IP: make([]byte, len(g.network.IP)), + Mask: make([]byte, len(g.network.Mask)), + } + copy(n.IP, g.network.IP) + copy(n.Mask, g.network.Mask) + return n +} + +func (g *ipGenerator) Next() net.IP { + ip := make([]byte, len(g.nextIP)) + copy(ip, g.nextIP) + for i := len(g.nextIP) - 1; i >= 0; i-- { + g.nextIP[i]++ + if g.nextIP[i] != 0 { + break + } + } + return ip +} diff --git a/test/e2e/run-multiple.sh b/test/e2e/run-multiple.sh new file mode 100755 index 0000000..abc498f --- /dev/null +++ b/test/e2e/run-multiple.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# +# This is a convenience script that takes a list of testnet manifests +# as arguments and runs each one of them sequentially. If a testnet +# fails, the container logs are dumped to stdout along with the testnet +# manifest, but the remaining testnets are still run. +# +# This is mostly used to run generated networks in nightly CI jobs. +# + +set -euo pipefail + +if [[ $# == 0 ]]; then + echo "Usage: $0 [MANIFEST...]" >&2 + exit 1 +fi + +FAILED=() + +for MANIFEST in "$@"; do + START=$SECONDS + echo "==> Running testnet: $MANIFEST" + echo "==> Manifest:" + cat "$MANIFEST" + + if ! ./build/runner -f "$MANIFEST"; then + echo "==> Testnet failed" + + echo "==> Dumping container logs for $MANIFEST..." + ./build/runner -f "$MANIFEST" logs + + echo "==> Cleaning up failed testnet $MANIFEST..." + ./build/runner -f "$MANIFEST" cleanup + + FAILED+=("$MANIFEST") + fi + + echo "==> Completed testnet $MANIFEST in $(( SECONDS - START ))s" + echo "" +done + +if [[ ${#FAILED[@]} -ne 0 ]]; then + echo "${#FAILED[@]} testnets failed:" + for MANIFEST in "${FAILED[@]}"; do + echo "- $MANIFEST" + done + exit 1 +else + echo "All testnets successful" +fi diff --git a/test/e2e/runner/benchmark.go b/test/e2e/runner/benchmark.go new file mode 100644 index 0000000..5551ada --- /dev/null +++ b/test/e2e/runner/benchmark.go @@ -0,0 +1,228 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "math" + "path/filepath" + "time" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" +) + +// Benchmark is a simple function for fetching, calculating and printing +// the following metrics: +// 1. Average block production time +// 2. Block interval standard deviation +// 3. Max block interval (slowest block) +// 4. Min block interval (fastest block) +// +// Metrics are based of the `benchmarkLength`, the amount of consecutive blocks +// sampled from in the testnet +func Benchmark(ctx context.Context, testnet *e2e.Testnet, benchmarkLength int64) error { + block, _, err := waitForHeight(ctx, testnet, 0) + if err != nil { + return err + } + + logger.Info("Beginning benchmark period...", "height", block.Height) + startAt := time.Now() + + // wait for the length of the benchmark period in blocks to pass. We allow 5 seconds for each block + // which should be sufficient. + waitingTime := time.Duration(benchmarkLength*5) * time.Second + endHeight, err := waitForAllNodes(ctx, testnet, block.Height+benchmarkLength, waitingTime) + if err != nil { + return err + } + dur := time.Since(startAt) + + logger.Info("Ending benchmark period", "height", endHeight) + + // fetch a sample of blocks + blocks, err := fetchBlockChainSample(ctx, testnet, benchmarkLength) + if err != nil { + return err + } + + // slice into time intervals and collate data + timeIntervals := splitIntoBlockIntervals(blocks) + testnetStats := extractTestnetStats(timeIntervals) + testnetStats.populateTxns(blocks) + testnetStats.totalTime = dur + testnetStats.startHeight = blocks[0].Header.Height + testnetStats.endHeight = blocks[len(blocks)-1].Header.Height + + // print and return + logger.Info(testnetStats.OutputJSON(testnet)) + return nil +} + +func (t *testnetStats) populateTxns(blocks []*types.BlockMeta) { + t.numtxns = 0 + for _, b := range blocks { + t.numtxns += int64(b.NumTxs) + } +} + +type testnetStats struct { + startHeight int64 + endHeight int64 + + numtxns int64 + totalTime time.Duration + // average time to produce a block + mean time.Duration + // standard deviation of block production + std float64 + // longest time to produce a block + max time.Duration + // shortest time to produce a block + min time.Duration +} + +func (t *testnetStats) OutputJSON(net *e2e.Testnet) string { + jsn, err := json.Marshal(map[string]interface{}{ + "case": filepath.Base(net.File), + "start_height": t.startHeight, + "end_height": t.endHeight, + "blocks": t.endHeight - t.startHeight, + "stddev": t.std, + "mean": t.mean.Seconds(), + "max": t.max.Seconds(), + "min": t.min.Seconds(), + "size": len(net.Nodes), + "txns": t.numtxns, + "dur": t.totalTime.Seconds(), + }) + + if err != nil { + return "" + } + + return string(jsn) +} + +func (t *testnetStats) String() string { + return fmt.Sprintf(`Benchmarked from height %v to %v + Mean Block Interval: %v + Standard Deviation: %f + Max Block Interval: %v + Min Block Interval: %v + `, + t.startHeight, + t.endHeight, + t.mean, + t.std, + t.max, + t.min, + ) +} + +// fetchBlockChainSample waits for `benchmarkLength` amount of blocks to pass, fetching +// all of the headers for these blocks from an archive node and returning it. +func fetchBlockChainSample(ctx context.Context, testnet *e2e.Testnet, benchmarkLength int64) ([]*types.BlockMeta, error) { + var blocks []*types.BlockMeta + + // Find the first archive node + archiveNode := testnet.ArchiveNodes()[0] + c, err := archiveNode.Client() + if err != nil { + return nil, err + } + + // find the latest height + s, err := c.Status(ctx) + if err != nil { + return nil, err + } + + to := s.SyncInfo.LatestBlockHeight + from := to - benchmarkLength + 1 + if from <= testnet.InitialHeight { + return nil, fmt.Errorf("tesnet was unable to reach required height for benchmarking (latest height %d)", to) + } + + // Fetch blocks + for from < to { + // fetch the blockchain metas. Currently we can only fetch 20 at a time + resp, err := c.BlockchainInfo(ctx, from, min(from+19, to)) + if err != nil { + return nil, err + } + + blockMetas := resp.BlockMetas + // we receive blocks in descending order so we have to add them in reverse + for i := len(blockMetas) - 1; i >= 0; i-- { + if blockMetas[i].Header.Height != from { + return nil, fmt.Errorf("node gave us another header. Wanted %d, got %d", + from, + blockMetas[i].Header.Height, + ) + } + from++ + blocks = append(blocks, blockMetas[i]) + } + } + + return blocks, nil +} + +func splitIntoBlockIntervals(blocks []*types.BlockMeta) []time.Duration { + intervals := make([]time.Duration, len(blocks)-1) + lastTime := blocks[0].Header.Time + for i, block := range blocks { + // skip the first block + if i == 0 { + continue + } + + intervals[i-1] = block.Header.Time.Sub(lastTime) + lastTime = block.Header.Time + } + return intervals +} + +func extractTestnetStats(intervals []time.Duration) testnetStats { + var ( + sum, mean time.Duration + std float64 + max = intervals[0] + min = intervals[0] + ) + + for _, interval := range intervals { + sum += interval + + if interval > max { + max = interval + } + + if interval < min { + min = interval + } + } + mean = sum / time.Duration(len(intervals)) + + for _, interval := range intervals { + diff := (interval - mean).Seconds() + std += diff * diff + } + std = math.Sqrt(std / float64(len(intervals))) + + return testnetStats{ + mean: mean, + std: std, + max: max, + min: min, + } +} + +func min(a, b int64) int64 { + if a > b { + return b + } + return a +} diff --git a/test/e2e/runner/cleanup.go b/test/e2e/runner/cleanup.go new file mode 100644 index 0000000..d5564c5 --- /dev/null +++ b/test/e2e/runner/cleanup.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/cometbft/cometbft/libs/log" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/exec" + "github.com/cometbft/cometbft/test/e2e/pkg/infra/docker" +) + +// Cleanup removes the Docker Compose containers and testnet directory. +func Cleanup(testnet *e2e.Testnet) error { + err := cleanupDocker() + if err != nil { + return err + } + err = cleanupDir(testnet.Dir) + if err != nil { + return err + } + return nil +} + +// cleanupDocker removes all E2E resources (with label e2e=True), regardless +// of testnet. +func cleanupDocker() error { + logger.Info("Removing Docker containers and networks") + + // GNU xargs requires the -r flag to not run when input is empty, macOS + // does this by default. Ugly, but works. + xargsR := `$(if [[ $OSTYPE == "linux-gnu"* ]]; then echo -n "-r"; fi)` + + err := exec.Command(context.Background(), "bash", "-c", fmt.Sprintf( + "docker container ls -qa --filter label=e2e | xargs %v docker container rm -f", xargsR)) + if err != nil { + return err + } + + err = exec.Command(context.Background(), "bash", "-c", fmt.Sprintf( + "docker network ls -q --filter label=e2e | xargs %v docker network rm", xargsR)) + if err != nil { + return err + } + + return nil +} + +// cleanupDir cleans up a testnet directory +func cleanupDir(dir string) error { + if dir == "" { + return errors.New("no directory set") + } + + _, err := os.Stat(dir) + if os.IsNotExist(err) { + return nil + } else if err != nil { + return err + } + + logger.Info("cleanup dir", "msg", log.NewLazySprintf("Removing testnet directory %q", dir)) + + // On Linux, some local files in the volume will be owned by root since CometBFT + // runs as root inside the container, so we need to clean them up from within a + // container running as root too. + absDir, err := filepath.Abs(dir) + if err != nil { + return err + } + err = docker.Exec(context.Background(), "run", "--rm", "--entrypoint", "", "-v", fmt.Sprintf("%v:/network", absDir), + "cometbft/e2e-node", "sh", "-c", "rm -rf /network/*/") + if err != nil { + return err + } + + err = os.RemoveAll(dir) + if err != nil { + return err + } + + return nil +} diff --git a/test/e2e/runner/evidence.go b/test/e2e/runner/evidence.go new file mode 100644 index 0000000..1c8dd40 --- /dev/null +++ b/test/e2e/runner/evidence.go @@ -0,0 +1,352 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "math/rand" + "os" + "path/filepath" + "time" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/internal/test" + cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/privval" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" + "github.com/cometbft/cometbft/version" +) + +// 1 in 4 evidence is light client evidence, the rest is duplicate vote evidence +const lightClientEvidenceRatio = 4 + +// InjectEvidence takes a running testnet and generates an amount of valid/invalid +// evidence and broadcasts it to a random node through the rpc endpoint `/broadcast_evidence`. +// Evidence is random and can be a mixture of LightClientAttackEvidence and +// DuplicateVoteEvidence. +func InjectEvidence(ctx context.Context, r *rand.Rand, testnet *e2e.Testnet, amount int) error { + // select a random node + var targetNode *e2e.Node + + for _, idx := range r.Perm(len(testnet.Nodes)) { + targetNode = testnet.Nodes[idx] + + if targetNode.Mode == e2e.ModeSeed || targetNode.Mode == e2e.ModeLight { + targetNode = nil + continue + } + + break + } + + if targetNode == nil { + return errors.New("could not find node to inject evidence into") + } + + logger.Info(fmt.Sprintf("Injecting evidence through %v (amount: %d)...", targetNode.Name, amount)) + + client, err := targetNode.Client() + if err != nil { + return err + } + + // request the latest block and validator set from the node + blockRes, err := client.Block(ctx, nil) + if err != nil { + return err + } + evidenceHeight := blockRes.Block.Height + waitHeight := blockRes.Block.Height + 3 + + nValidators := 100 + valRes, err := client.Validators(ctx, &evidenceHeight, nil, &nValidators) + if err != nil { + return err + } + + valSet, err := types.ValidatorSetFromExistingValidators(valRes.Validators) + if err != nil { + return err + } + + // get the private keys of all the validators in the network + privVals, err := getPrivateValidatorKeys(testnet) + if err != nil { + return err + } + + // wait for the node to reach the height above the forged height so that + // it is able to validate the evidence + _, err = waitForNode(ctx, targetNode, waitHeight, time.Minute) + if err != nil { + return err + } + + var ev types.Evidence + for i := 0; i < amount; i++ { + validEv := true + if i%lightClientEvidenceRatio == 0 { + validEv = i%(lightClientEvidenceRatio*2) != 0 // Alternate valid and invalid evidence + ev, err = generateLightClientAttackEvidence( + ctx, privVals, evidenceHeight, valSet, testnet.Name, blockRes.Block.Time, validEv, + ) + } else { + var dve *types.DuplicateVoteEvidence + dve, err = generateDuplicateVoteEvidence( + privVals, evidenceHeight, valSet, testnet.Name, blockRes.Block.Time, + ) + if dve.VoteA.Height < testnet.VoteExtensionsEnableHeight { + dve.VoteA.Extension = nil + dve.VoteA.ExtensionSignature = nil + dve.VoteB.Extension = nil + dve.VoteB.ExtensionSignature = nil + } + ev = dve + } + if err != nil { + return err + } + + _, err := client.BroadcastEvidence(ctx, ev) + if !validEv { + // The tests will count committed evidences later on, + // and only valid evidences will make it + amount++ + } + if validEv != (err == nil) { + if err == nil { + return errors.New("submitting invalid evidence didn't return an error") + } + return err + } + time.Sleep(5 * time.Second / time.Duration(amount)) + } + + // wait for the node to reach the height above the forged height so that + // it is able to validate the evidence + _, err = waitForNode(ctx, targetNode, blockRes.Block.Height+2, 30*time.Second) + if err != nil { + return err + } + + logger.Info(fmt.Sprintf("Finished sending evidence (height %d)", blockRes.Block.Height+2)) + + return nil +} + +func getPrivateValidatorKeys(testnet *e2e.Testnet) ([]types.MockPV, error) { + privVals := []types.MockPV{} + + for _, node := range testnet.Nodes { + if node.Mode == e2e.ModeValidator { + privKeyPath := filepath.Join(testnet.Dir, node.Name, PrivvalKeyFile) + privKey, err := readPrivKey(privKeyPath) + if err != nil { + return nil, err + } + // Create mock private validators from the validators private key. MockPV is + // stateless which means we can double vote and do other funky stuff + privVals = append(privVals, types.NewMockPVWithParams(privKey, false, false)) + } + } + + return privVals, nil +} + +// creates evidence of a lunatic attack. The height provided is the common height. +// The forged height happens 2 blocks later. +func generateLightClientAttackEvidence( + ctx context.Context, + privVals []types.MockPV, + height int64, + vals *types.ValidatorSet, + chainID string, + evTime time.Time, + validEvidence bool, +) (*types.LightClientAttackEvidence, error) { + // forge a random header + forgedHeight := height + 2 + forgedTime := evTime.Add(1 * time.Second) + header := makeHeaderRandom(chainID, forgedHeight) + header.Time = forgedTime + + // add a new bogus validator and remove an existing one to + // vary the validator set slightly + pv, conflictingVals, err := mutateValidatorSet(ctx, privVals, vals, !validEvidence) + if err != nil { + return nil, err + } + + header.ValidatorsHash = conflictingVals.Hash() + + // create a commit for the forged header + blockID := makeBlockID(header.Hash(), 1000, []byte("partshash")) + voteSet := types.NewVoteSet(chainID, forgedHeight, 0, cmtproto.SignedMsgType(2), conflictingVals) + commit, err := test.MakeCommitFromVoteSet(blockID, voteSet, pv, forgedTime) + if err != nil { + return nil, err + } + + // malleate the last signature of the commit by adding one to its first byte + if !validEvidence { + commit.Signatures[len(commit.Signatures)-1].Signature[0]++ + } + + ev := &types.LightClientAttackEvidence{ + ConflictingBlock: &types.LightBlock{ + SignedHeader: &types.SignedHeader{ + Header: header, + Commit: commit, + }, + ValidatorSet: conflictingVals, + }, + CommonHeight: height, + TotalVotingPower: vals.TotalVotingPower(), + Timestamp: evTime, + } + ev.ByzantineValidators = ev.GetByzantineValidators(vals, &types.SignedHeader{ + Header: makeHeaderRandom(chainID, forgedHeight), + }) + return ev, nil +} + +// generateDuplicateVoteEvidence picks a random validator from the val set and +// returns duplicate vote evidence against the validator +func generateDuplicateVoteEvidence( + privVals []types.MockPV, + height int64, + vals *types.ValidatorSet, + chainID string, + time time.Time, +) (*types.DuplicateVoteEvidence, error) { + privVal, valIdx, err := getRandomValidatorIndex(privVals, vals) + if err != nil { + return nil, err + } + voteA, err := types.MakeVote(privVal, chainID, valIdx, height, 0, 2, makeRandomBlockID(), time) + if err != nil { + return nil, err + } + voteB, err := types.MakeVote(privVal, chainID, valIdx, height, 0, 2, makeRandomBlockID(), time) + if err != nil { + return nil, err + } + ev, err := types.NewDuplicateVoteEvidence(voteA, voteB, time, vals) + if err != nil { + return nil, fmt.Errorf("could not generate evidence: %w", err) + } + + return ev, nil +} + +// getRandomValidatorIndex picks a random validator from a slice of mock PrivVals that's +// also part of the validator set, returning the PrivVal and its index in the validator set +func getRandomValidatorIndex(privVals []types.MockPV, vals *types.ValidatorSet) (types.MockPV, int32, error) { + for _, idx := range rand.Perm(len(privVals)) { + pv := privVals[idx] + valIdx, _ := vals.GetByAddress(pv.PrivKey.PubKey().Address()) + if valIdx >= 0 { + return pv, valIdx, nil + } + } + return types.MockPV{}, -1, errors.New("no private validator found in validator set") +} + +func readPrivKey(keyFilePath string) (crypto.PrivKey, error) { + keyJSONBytes, err := os.ReadFile(keyFilePath) + if err != nil { + return nil, err + } + pvKey := privval.FilePVKey{} + err = cmtjson.Unmarshal(keyJSONBytes, &pvKey) + if err != nil { + return nil, fmt.Errorf("error reading PrivValidator key from %v: %w", keyFilePath, err) + } + + return pvKey.PrivKey, nil +} + +func makeHeaderRandom(chainID string, height int64) *types.Header { + return &types.Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: chainID, + Height: height, + Time: time.Now(), + LastBlockID: makeBlockID([]byte("headerhash"), 1000, []byte("partshash")), + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: crypto.CRandBytes(tmhash.Size), + NextValidatorsHash: crypto.CRandBytes(tmhash.Size), + ConsensusHash: crypto.CRandBytes(tmhash.Size), + AppHash: crypto.CRandBytes(tmhash.Size), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + } +} + +func makeRandomBlockID() types.BlockID { + return makeBlockID(crypto.CRandBytes(tmhash.Size), 100, crypto.CRandBytes(tmhash.Size)) +} + +func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID { + var ( + h = make([]byte, tmhash.Size) + psH = make([]byte, tmhash.Size) + ) + copy(h, hash) + copy(psH, partSetHash) + return types.BlockID{ + Hash: h, + PartSetHeader: types.PartSetHeader{ + Total: partSetSize, + Hash: psH, + }, + } +} + +func mutateValidatorSet( + ctx context.Context, + privVals []types.MockPV, + vals *types.ValidatorSet, + nop bool, +) ([]types.PrivValidator, *types.ValidatorSet, error) { + newVal, newPrivVal, err := test.Validator(ctx, 10) + if err != nil { + return nil, nil, err + } + + var newVals *types.ValidatorSet + if nop { + newVals = types.NewValidatorSet(vals.Copy().Validators) + } else { + if vals.Size() > 2 { + newVals = types.NewValidatorSet(append(vals.Copy().Validators[:vals.Size()-1], newVal)) + } else { + newVals = types.NewValidatorSet(append(vals.Copy().Validators, newVal)) + } + } + + // we need to sort the priv validators with the same index as the validator set + pv := make([]types.PrivValidator, newVals.Size()) + for idx, val := range newVals.Validators { + found := false + for _, p := range append(privVals, newPrivVal.(types.MockPV)) { + if bytes.Equal(p.PrivKey.PubKey().Address(), val.Address) { + pv[idx] = p + found = true + break + } + } + if !found { + return nil, nil, fmt.Errorf("missing priv validator for %v", val.Address) + } + } + + return pv, newVals, nil +} diff --git a/test/e2e/runner/load.go b/test/e2e/runner/load.go new file mode 100644 index 0000000..91e9b68 --- /dev/null +++ b/test/e2e/runner/load.go @@ -0,0 +1,154 @@ +package main + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "github.com/cometbft/cometbft/libs/log" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/loadtime/payload" + "github.com/cometbft/cometbft/types" + "github.com/google/uuid" +) + +const workerPoolSize = 16 + +// Load generates transactions against the network until the given context is +// canceled. +func Load(ctx context.Context, testnet *e2e.Testnet) error { + initialTimeout := 1 * time.Minute + stallTimeout := 30 * time.Second + chSuccess := make(chan struct{}) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + logger.Info("load", "msg", log.NewLazySprintf("Starting transaction load (%v workers)...", workerPoolSize)) + started := time.Now() + u := [16]byte(uuid.New()) // generate run ID on startup + + txCh := make(chan types.Tx) + go loadGenerate(ctx, txCh, testnet, u[:]) + + for _, n := range testnet.Nodes { + if n.SendNoLoad { + continue + } + + for w := 0; w < testnet.LoadTxConnections; w++ { + go loadProcess(ctx, txCh, chSuccess, n) + } + } + + // Monitor successful transactions, and abort on stalls. + success := 0 + timeout := initialTimeout + for { + select { + case <-chSuccess: + success++ + if testnet.LoadMaxTxs > 0 && success >= testnet.LoadMaxTxs { + logger.Info("load", "msg", log.NewLazySprintf("Ending transaction load after reaching %v txs (%.1f tx/s)...", + success, float64(success)/time.Since(started).Seconds())) + return nil + } + timeout = stallTimeout + case <-time.After(timeout): + return fmt.Errorf("unable to submit transactions for %v", timeout) + case <-ctx.Done(): + if success == 0 { + return errors.New("failed to submit any transactions") + } + logger.Info("load", "msg", log.NewLazySprintf("Ending transaction load after %v txs (%.1f tx/s)...", + success, float64(success)/time.Since(started).Seconds())) + return nil + } + } +} + +// loadGenerate generates jobs until the context is canceled +func loadGenerate(ctx context.Context, txCh chan<- types.Tx, testnet *e2e.Testnet, id []byte) { + t := time.NewTimer(0) + defer t.Stop() + for { + select { + case <-t.C: + case <-ctx.Done(): + close(txCh) + return + } + t.Reset(time.Second) + + // A context with a timeout is created here to time the createTxBatch + // function out. If createTxBatch has not completed its work by the time + // the next batch is set to be sent out, then the context is canceled so that + // the current batch is halted, allowing the next batch to begin. + tctx, cf := context.WithTimeout(ctx, time.Second) + createTxBatch(tctx, txCh, testnet, id) + cf() + } +} + +// createTxBatch creates new transactions and sends them into the txCh. createTxBatch +// returns when either a full batch has been sent to the txCh or the context +// is canceled. +func createTxBatch(ctx context.Context, txCh chan<- types.Tx, testnet *e2e.Testnet, id []byte) { + wg := &sync.WaitGroup{} + genCh := make(chan struct{}) + for i := 0; i < workerPoolSize; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for range genCh { + tx, err := payload.NewBytes(&payload.Payload{ + Id: id, + Size: uint64(testnet.LoadTxSizeBytes), + Rate: uint64(testnet.LoadTxBatchSize), + Connections: uint64(testnet.LoadTxConnections), + }) + if err != nil { + panic(fmt.Sprintf("Failed to generate tx: %v", err)) + } + + select { + case txCh <- tx: + case <-ctx.Done(): + return + } + } + }() + } + for i := 0; i < testnet.LoadTxBatchSize; i++ { + select { + case genCh <- struct{}{}: + case <-ctx.Done(): + break + } + } + close(genCh) + wg.Wait() +} + +// loadProcess processes transactions by sending transactions received on the txCh +// to the client. +func loadProcess(ctx context.Context, txCh <-chan types.Tx, chSuccess chan<- struct{}, n *e2e.Node) { + var client *rpchttp.HTTP + var err error + s := struct{}{} + for tx := range txCh { + if client == nil { + client, err = n.Client() + if err != nil { + logger.Info("non-fatal error creating node client", "error", err) + continue + } + } + if _, err = client.BroadcastTxSync(ctx, tx); err != nil { + continue + } + chSuccess <- s + } +} diff --git a/test/e2e/runner/main.go b/test/e2e/runner/main.go new file mode 100644 index 0000000..ca74bd5 --- /dev/null +++ b/test/e2e/runner/main.go @@ -0,0 +1,358 @@ +package main + +import ( + "context" + "errors" + "fmt" + "math/rand" + "os" + "strconv" + + "github.com/spf13/cobra" + + "github.com/cometbft/cometbft/libs/log" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/infra" + "github.com/cometbft/cometbft/test/e2e/pkg/infra/digitalocean" + "github.com/cometbft/cometbft/test/e2e/pkg/infra/docker" +) + +const randomSeed = 2308084734268 + +var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + +func main() { + NewCLI().Run() +} + +// CLI is the Cobra-based command-line interface. +type CLI struct { + root *cobra.Command + testnet *e2e.Testnet + preserve bool + infp infra.Provider +} + +// NewCLI sets up the CLI. +func NewCLI() *CLI { + cli := &CLI{} + cli.root = &cobra.Command{ + Use: "runner", + Short: "End-to-end test runner", + SilenceUsage: true, + SilenceErrors: true, // we'll output them ourselves in Run() + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + file, err := cmd.Flags().GetString("file") + if err != nil { + return err + } + m, err := e2e.LoadManifest(file) + if err != nil { + return err + } + + inft, err := cmd.Flags().GetString("infrastructure-type") + if err != nil { + return err + } + + var ifd e2e.InfrastructureData + switch inft { + case "docker": + var err error + ifd, err = e2e.NewDockerInfrastructureData(m) + if err != nil { + return err + } + case "digital-ocean": + p, err := cmd.Flags().GetString("infrastructure-data") + if err != nil { + return err + } + if p == "" { + return errors.New("'--infrastructure-data' must be set when using the 'digital-ocean' infrastructure-type") + } + ifd, err = e2e.InfrastructureDataFromFile(p) + if err != nil { + return fmt.Errorf("parsing infrastructure data: %s", err) + } + default: + return fmt.Errorf("unknown infrastructure type '%s'", inft) + } + + testnet, err := e2e.LoadTestnet(file, ifd) + if err != nil { + return fmt.Errorf("loading testnet: %s", err) + } + + cli.testnet = testnet + switch inft { + case "docker": + cli.infp = &docker.Provider{ + ProviderData: infra.ProviderData{ + Testnet: testnet, + InfrastructureData: ifd, + }, + } + case "digital-ocean": + cli.infp = &digitalocean.Provider{ + ProviderData: infra.ProviderData{ + Testnet: testnet, + InfrastructureData: ifd, + }, + } + default: + return fmt.Errorf("bad infrastructure type: %s", inft) + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + if err := Cleanup(cli.testnet); err != nil { + return err + } + if err := Setup(cli.testnet, cli.infp); err != nil { + return err + } + + r := rand.New(rand.NewSource(randomSeed)) //nolint: gosec + + chLoadResult := make(chan error) + ctx, loadCancel := context.WithCancel(context.Background()) + defer loadCancel() + go func() { + err := Load(ctx, cli.testnet) + if err != nil { + logger.Error(fmt.Sprintf("Transaction load failed: %v", err.Error())) + } + chLoadResult <- err + }() + + if err := Start(cmd.Context(), cli.testnet, cli.infp); err != nil { + return err + } + + if err := Wait(cmd.Context(), cli.testnet, 5); err != nil { // allow some txs to go through + return err + } + + if cli.testnet.HasPerturbations() { + if err := Perturb(cmd.Context(), cli.testnet); err != nil { + return err + } + if err := Wait(cmd.Context(), cli.testnet, 5); err != nil { // allow some txs to go through + return err + } + } + + if cli.testnet.Evidence > 0 { + if err := InjectEvidence(ctx, r, cli.testnet, cli.testnet.Evidence); err != nil { + return err + } + if err := Wait(cmd.Context(), cli.testnet, 5); err != nil { // ensure chain progress + return err + } + } + + loadCancel() + if err := <-chLoadResult; err != nil { + return err + } + if err := Wait(cmd.Context(), cli.testnet, 5); err != nil { // wait for network to settle before tests + return err + } + if err := Test(cli.testnet, cli.infp.GetInfrastructureData()); err != nil { + return err + } + if !cli.preserve { + if err := Cleanup(cli.testnet); err != nil { + return err + } + } + return nil + }, + } + + cli.root.PersistentFlags().StringP("file", "f", "", "Testnet TOML manifest") + _ = cli.root.MarkPersistentFlagRequired("file") + + cli.root.PersistentFlags().StringP("infrastructure-type", "", "docker", "Backing infrastructure used to run the testnet. Either 'digital-ocean' or 'docker'") + + cli.root.PersistentFlags().StringP("infrastructure-data", "", "", "path to the json file containing the infrastructure data. Only used if the 'infrastructure-type' is set to a value other than 'docker'") + + cli.root.Flags().BoolVarP(&cli.preserve, "preserve", "p", false, + "Preserves the running of the test net after tests are completed") + + cli.root.AddCommand(&cobra.Command{ + Use: "setup", + Short: "Generates the testnet directory and configuration", + RunE: func(cmd *cobra.Command, args []string) error { + return Setup(cli.testnet, cli.infp) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "start", + Short: "Starts the testnet, waiting for nodes to become available", + RunE: func(cmd *cobra.Command, args []string) error { + _, err := os.Stat(cli.testnet.Dir) + if os.IsNotExist(err) { + err = Setup(cli.testnet, cli.infp) + } + if err != nil { + return err + } + return Start(cmd.Context(), cli.testnet, cli.infp) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "perturb", + Short: "Perturbs the testnet, e.g. by restarting or disconnecting nodes", + RunE: func(cmd *cobra.Command, args []string) error { + return Perturb(cmd.Context(), cli.testnet) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "wait", + Short: "Waits for a few blocks to be produced and all nodes to catch up", + RunE: func(cmd *cobra.Command, args []string) error { + return Wait(cmd.Context(), cli.testnet, 5) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "stop", + Short: "Stops the testnet", + RunE: func(cmd *cobra.Command, args []string) error { + logger.Info("Stopping testnet") + return cli.infp.StopTestnet(context.Background()) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "load", + Short: "Generates transaction load until the command is canceled", + RunE: func(cmd *cobra.Command, args []string) (err error) { + return Load(context.Background(), cli.testnet) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "evidence [amount]", + Args: cobra.MaximumNArgs(1), + Short: "Generates and broadcasts evidence to a random node", + RunE: func(cmd *cobra.Command, args []string) (err error) { + amount := 1 + + if len(args) == 1 { + amount, err = strconv.Atoi(args[0]) + if err != nil { + return err + } + } + + return InjectEvidence( + cmd.Context(), + rand.New(rand.NewSource(randomSeed)), //nolint: gosec + cli.testnet, + amount, + ) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "test", + Short: "Runs test cases against a running testnet", + RunE: func(cmd *cobra.Command, args []string) error { + return Test(cli.testnet, cli.infp.GetInfrastructureData()) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "cleanup", + Short: "Removes the testnet directory", + RunE: func(cmd *cobra.Command, args []string) error { + return Cleanup(cli.testnet) + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "logs", + Short: "Shows the testnet logs", + RunE: func(cmd *cobra.Command, args []string) error { + return docker.ExecComposeVerbose(context.Background(), cli.testnet.Dir, "logs") + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "tail", + Short: "Tails the testnet logs", + RunE: func(cmd *cobra.Command, args []string) error { + return docker.ExecComposeVerbose(context.Background(), cli.testnet.Dir, "logs", "--follow") + }, + }) + + cli.root.AddCommand(&cobra.Command{ + Use: "benchmark", + Short: "Benchmarks testnet", + Long: `Benchmarks the following metrics: + Mean Block Interval + Standard Deviation + Min Block Interval + Max Block Interval +over a 100 block sampling period. + +Does not run any perturbations. + `, + RunE: func(cmd *cobra.Command, args []string) error { + if err := Cleanup(cli.testnet); err != nil { + return err + } + if err := Setup(cli.testnet, cli.infp); err != nil { + return err + } + + chLoadResult := make(chan error) + ctx, loadCancel := context.WithCancel(cmd.Context()) + defer loadCancel() + go func() { + err := Load(ctx, cli.testnet) + if err != nil { + logger.Error(fmt.Sprintf("Transaction load errored: %v", err.Error())) + } + chLoadResult <- err + }() + + if err := Start(cmd.Context(), cli.testnet, cli.infp); err != nil { + return err + } + + if err := Wait(cmd.Context(), cli.testnet, 5); err != nil { // allow some txs to go through + return err + } + + // we benchmark performance over the next 100 blocks + if err := Benchmark(cmd.Context(), cli.testnet, 100); err != nil { + return err + } + + loadCancel() + if err := <-chLoadResult; err != nil { + return err + } + + return Cleanup(cli.testnet) + }, + }) + + return cli +} + +// Run runs the CLI. +func (cli *CLI) Run() { + if err := cli.root.Execute(); err != nil { + logger.Error(err.Error()) + os.Exit(1) + } +} diff --git a/test/e2e/runner/perturb.go b/test/e2e/runner/perturb.go new file mode 100644 index 0000000..6a77362 --- /dev/null +++ b/test/e2e/runner/perturb.go @@ -0,0 +1,119 @@ +package main + +import ( + "context" + "fmt" + "time" + + "github.com/cometbft/cometbft/libs/log" + rpctypes "github.com/cometbft/cometbft/rpc/core/types" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/infra/docker" +) + +// Perturbs a running testnet. +func Perturb(ctx context.Context, testnet *e2e.Testnet) error { + for _, node := range testnet.Nodes { + for _, perturbation := range node.Perturbations { + _, err := PerturbNode(ctx, node, perturbation) + if err != nil { + return err + } + time.Sleep(3 * time.Second) // give network some time to recover between each + } + } + return nil +} + +// PerturbNode perturbs a node with a given perturbation, returning its status +// after recovering. +func PerturbNode(ctx context.Context, node *e2e.Node, perturbation e2e.Perturbation) (*rpctypes.ResultStatus, error) { + testnet := node.Testnet + out, err := docker.ExecComposeOutput(context.Background(), testnet.Dir, "ps", "-q", node.Name) + if err != nil { + return nil, err + } + name := node.Name + upgraded := false + if len(out) == 0 { + name = name + "_u" + upgraded = true + logger.Info("perturb node", "msg", + log.NewLazySprintf("Node %v already upgraded, operating on alternate container %v", + node.Name, name)) + } + + switch perturbation { + case e2e.PerturbationDisconnect: + logger.Info("perturb node", "msg", log.NewLazySprintf("Disconnecting node %v...", node.Name)) + if err := docker.Exec(context.Background(), "network", "disconnect", testnet.Name+"_"+testnet.Name, name); err != nil { + return nil, err + } + time.Sleep(10 * time.Second) + if err := docker.Exec(context.Background(), "network", "connect", testnet.Name+"_"+testnet.Name, name); err != nil { + return nil, err + } + + case e2e.PerturbationKill: + logger.Info("perturb node", "msg", log.NewLazySprintf("Killing node %v...", node.Name)) + if err := docker.ExecCompose(context.Background(), testnet.Dir, "kill", "-s", "SIGKILL", name); err != nil { + return nil, err + } + if err := docker.ExecCompose(context.Background(), testnet.Dir, "start", name); err != nil { + return nil, err + } + + case e2e.PerturbationPause: + logger.Info("perturb node", "msg", log.NewLazySprintf("Pausing node %v...", node.Name)) + if err := docker.ExecCompose(context.Background(), testnet.Dir, "pause", name); err != nil { + return nil, err + } + time.Sleep(10 * time.Second) + if err := docker.ExecCompose(context.Background(), testnet.Dir, "unpause", name); err != nil { + return nil, err + } + + case e2e.PerturbationRestart: + logger.Info("perturb node", "msg", log.NewLazySprintf("Restarting node %v...", node.Name)) + if err := docker.ExecCompose(context.Background(), testnet.Dir, "restart", name); err != nil { + return nil, err + } + + case e2e.PerturbationUpgrade: + oldV := node.Version + newV := node.Testnet.UpgradeVersion + if upgraded { + return nil, fmt.Errorf("node %v can't be upgraded twice from version '%v' to version '%v'", + node.Name, oldV, newV) + } + if oldV == newV { + logger.Info("perturb node", "msg", + log.NewLazySprintf("Skipping upgrade of node %v to version '%v'; versions are equal.", + node.Name, newV)) + break + } + logger.Info("perturb node", "msg", + log.NewLazySprintf("Upgrading node %v from version '%v' to version '%v'...", + node.Name, oldV, newV)) + + if err := docker.ExecCompose(context.Background(), testnet.Dir, "stop", name); err != nil { + return nil, err + } + time.Sleep(10 * time.Second) + if err := docker.ExecCompose(context.Background(), testnet.Dir, "up", "-d", name+"_u"); err != nil { + return nil, err + } + + default: + return nil, fmt.Errorf("unexpected perturbation %q", perturbation) + } + + status, err := waitForNode(ctx, node, 0, 20*time.Second) + if err != nil { + return nil, err + } + logger.Info("perturb node", + "msg", + log.NewLazySprintf("Node %v recovered at height %v", node.Name, status.SyncInfo.LatestBlockHeight)) + return status, nil +} diff --git a/test/e2e/runner/rpc.go b/test/e2e/runner/rpc.go new file mode 100644 index 0000000..5a69058 --- /dev/null +++ b/test/e2e/runner/rpc.go @@ -0,0 +1,134 @@ +package main + +import ( + "context" + "errors" + "fmt" + "time" + + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + rpctypes "github.com/cometbft/cometbft/rpc/core/types" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" +) + +// waitForHeight waits for the network to reach a certain height (or above), +// returning the highest height seen. Errors if the network is not making +// progress at all. +func waitForHeight(ctx context.Context, testnet *e2e.Testnet, height int64) (*types.Block, *types.BlockID, error) { + var ( + err error + maxResult *rpctypes.ResultBlock + clients = map[string]*rpchttp.HTTP{} + lastIncrease = time.Now() + ) + + timer := time.NewTimer(0) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return nil, nil, ctx.Err() + case <-timer.C: + for _, node := range testnet.Nodes { + if node.Stateless() { + continue + } + client, ok := clients[node.Name] + if !ok { + client, err = node.Client() + if err != nil { + continue + } + clients[node.Name] = client + } + + subctx, cancel := context.WithTimeout(ctx, 1*time.Second) + defer cancel() + result, err := client.Block(subctx, nil) + if err == context.DeadlineExceeded || err == context.Canceled { + return nil, nil, ctx.Err() + } + if err != nil { + continue + } + if result.Block != nil && (maxResult == nil || result.Block.Height > maxResult.Block.Height) { + maxResult = result + lastIncrease = time.Now() + } + if maxResult != nil && maxResult.Block.Height >= height { + return maxResult.Block, &maxResult.BlockID, nil + } + } + + if len(clients) == 0 { + return nil, nil, errors.New("unable to connect to any network nodes") + } + if time.Since(lastIncrease) >= 20*time.Second { + if maxResult == nil { + return nil, nil, errors.New("chain stalled at unknown height") + } + return nil, nil, fmt.Errorf("chain stalled at height %v", maxResult.Block.Height) + } + timer.Reset(1 * time.Second) + } + + } +} + +// waitForNode waits for a node to become available and catch up to the given block height. +func waitForNode(ctx context.Context, node *e2e.Node, height int64, timeout time.Duration) (*rpctypes.ResultStatus, error) { + client, err := node.Client() + if err != nil { + return nil, err + } + + timer := time.NewTimer(0) + defer timer.Stop() + var curHeight int64 + lastChanged := time.Now() + for { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-timer.C: + status, err := client.Status(ctx) + switch { + case time.Since(lastChanged) > timeout: + return nil, fmt.Errorf("timed out waiting for %v to reach height %v", node.Name, height) + case err != nil: + case status.SyncInfo.LatestBlockHeight >= height && (height == 0 || !status.SyncInfo.CatchingUp): + return status, nil + case curHeight < status.SyncInfo.LatestBlockHeight: + curHeight = status.SyncInfo.LatestBlockHeight + lastChanged = time.Now() + } + + timer.Reset(300 * time.Millisecond) + } + } +} + +// waitForAllNodes waits for all nodes to become available and catch up to the given block height. +func waitForAllNodes(ctx context.Context, testnet *e2e.Testnet, height int64, timeout time.Duration) (int64, error) { + var lastHeight int64 + + deadline := time.Now().Add(timeout) + + for _, node := range testnet.Nodes { + if node.Mode == e2e.ModeSeed { + continue + } + + status, err := waitForNode(ctx, node, height, time.Until(deadline)) + if err != nil { + return 0, err + } + + if status.SyncInfo.LatestBlockHeight > lastHeight { + lastHeight = status.SyncInfo.LatestBlockHeight + } + } + + return lastHeight, nil +} diff --git a/test/e2e/runner/setup.go b/test/e2e/runner/setup.go new file mode 100644 index 0000000..6ad5613 --- /dev/null +++ b/test/e2e/runner/setup.go @@ -0,0 +1,356 @@ +package main + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "github.com/BurntSushi/toml" + + "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/infra" + "github.com/cometbft/cometbft/types" +) + +const ( + AppAddressTCP = "tcp://127.0.0.1:30000" + AppAddressUNIX = "unix:///var/run/app.sock" + + PrivvalAddressTCP = "tcp://0.0.0.0:27559" + PrivvalAddressUNIX = "unix:///var/run/privval.sock" + PrivvalKeyFile = "config/priv_validator_key.json" + PrivvalStateFile = "data/priv_validator_state.json" + PrivvalDummyKeyFile = "config/dummy_validator_key.json" + PrivvalDummyStateFile = "data/dummy_validator_state.json" +) + +// Setup sets up the testnet configuration. +func Setup(testnet *e2e.Testnet, infp infra.Provider) error { + logger.Info("setup", "msg", log.NewLazySprintf("Generating testnet files in %q", testnet.Dir)) + + if err := os.MkdirAll(testnet.Dir, os.ModePerm); err != nil { + return err + } + + if err := infp.Setup(); err != nil { + return err + } + + genesis, err := MakeGenesis(testnet) + if err != nil { + return err + } + + for _, node := range testnet.Nodes { + nodeDir := filepath.Join(testnet.Dir, node.Name) + + dirs := []string{ + filepath.Join(nodeDir, "config"), + filepath.Join(nodeDir, "data"), + filepath.Join(nodeDir, "data", "app"), + } + for _, dir := range dirs { + // light clients don't need an app directory + if node.Mode == e2e.ModeLight && strings.Contains(dir, "app") { + continue + } + err := os.MkdirAll(dir, 0o755) + if err != nil { + return err + } + } + + cfg, err := MakeConfig(node) + if err != nil { + return err + } + config.WriteConfigFile(filepath.Join(nodeDir, "config", "config.toml"), cfg) // panics + + appCfg, err := MakeAppConfig(node) + if err != nil { + return err + } + err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0o644) //nolint:gosec + if err != nil { + return err + } + + if node.Mode == e2e.ModeLight { + // stop early if a light client + continue + } + + err = genesis.SaveAs(filepath.Join(nodeDir, "config", "genesis.json")) + if err != nil { + return err + } + + err = (&p2p.NodeKey{PrivKey: node.NodeKey}).SaveAs(filepath.Join(nodeDir, "config", "node_key.json")) + if err != nil { + return err + } + + (privval.NewFilePV(node.PrivvalKey, + filepath.Join(nodeDir, PrivvalKeyFile), + filepath.Join(nodeDir, PrivvalStateFile), + )).Save() + + // Set up a dummy validator. CometBFT requires a file PV even when not used, so we + // give it a dummy such that it will fail if it actually tries to use it. + (privval.NewFilePV(ed25519.GenPrivKey(), + filepath.Join(nodeDir, PrivvalDummyKeyFile), + filepath.Join(nodeDir, PrivvalDummyStateFile), + )).Save() + } + + if testnet.Prometheus { + if err := testnet.WritePrometheusConfig(); err != nil { + return err + } + } + + return nil +} + +// MakeGenesis generates a genesis document. +func MakeGenesis(testnet *e2e.Testnet) (types.GenesisDoc, error) { + genesis := types.GenesisDoc{ + GenesisTime: time.Now(), + ChainID: testnet.Name, + ConsensusParams: types.DefaultConsensusParams(), + InitialHeight: testnet.InitialHeight, + } + // set the app version to 1 + genesis.ConsensusParams.Version.App = 1 + genesis.ConsensusParams.Evidence.MaxAgeNumBlocks = e2e.EvidenceAgeHeight + genesis.ConsensusParams.Evidence.MaxAgeDuration = e2e.EvidenceAgeTime + if testnet.BlockMaxBytes != 0 { + genesis.ConsensusParams.Block.MaxBytes = testnet.BlockMaxBytes + } + if testnet.VoteExtensionsUpdateHeight == -1 { + genesis.ConsensusParams.ABCI.VoteExtensionsEnableHeight = testnet.VoteExtensionsEnableHeight + } + for validator, power := range testnet.Validators { + genesis.Validators = append(genesis.Validators, types.GenesisValidator{ + Name: validator.Name, + Address: validator.PrivvalKey.PubKey().Address(), + PubKey: validator.PrivvalKey.PubKey(), + Power: power, + }) + } + // The validator set will be sorted internally by CometBFT ranked by power, + // but we sort it here as well so that all genesis files are identical. + sort.Slice(genesis.Validators, func(i, j int) bool { + return strings.Compare(genesis.Validators[i].Name, genesis.Validators[j].Name) == -1 + }) + if len(testnet.InitialState) > 0 { + appState, err := json.Marshal(testnet.InitialState) + if err != nil { + return genesis, err + } + genesis.AppState = appState + } + return genesis, genesis.ValidateAndComplete() +} + +// MakeConfig generates a CometBFT config for a node. +func MakeConfig(node *e2e.Node) (*config.Config, error) { + cfg := config.DefaultConfig() + cfg.Moniker = node.Name + cfg.ProxyApp = AppAddressTCP + cfg.RPC.ListenAddress = "tcp://0.0.0.0:26657" + cfg.RPC.PprofListenAddress = ":6060" + cfg.P2P.ExternalAddress = fmt.Sprintf("tcp://%v", node.AddressP2P(false)) + cfg.P2P.AddrBookStrict = false + cfg.DBBackend = node.Database + cfg.StateSync.DiscoveryTime = 5 * time.Second + cfg.BlockSync.Version = node.BlockSyncVersion + cfg.Mempool.ExperimentalMaxGossipConnectionsToNonPersistentPeers = int(node.Testnet.ExperimentalMaxGossipConnectionsToNonPersistentPeers) + cfg.Mempool.ExperimentalMaxGossipConnectionsToPersistentPeers = int(node.Testnet.ExperimentalMaxGossipConnectionsToPersistentPeers) + + switch node.ABCIProtocol { + case e2e.ProtocolUNIX: + cfg.ProxyApp = AppAddressUNIX + case e2e.ProtocolTCP: + cfg.ProxyApp = AppAddressTCP + case e2e.ProtocolGRPC: + cfg.ProxyApp = AppAddressTCP + cfg.ABCI = "grpc" + case e2e.ProtocolBuiltin, e2e.ProtocolBuiltinConnSync: + cfg.ProxyApp = "" + cfg.ABCI = "" + default: + return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol) + } + + // CometBFT errors if it does not have a privval key set up, regardless of whether + // it's actually needed (e.g. for remote KMS or non-validators). We set up a dummy + // key here by default, and use the real key for actual validators that should use + // the file privval. + cfg.PrivValidatorListenAddr = "" + cfg.PrivValidatorKey = PrivvalDummyKeyFile + cfg.PrivValidatorState = PrivvalDummyStateFile + + switch node.Mode { + case e2e.ModeValidator: + switch node.PrivvalProtocol { + case e2e.ProtocolFile: + cfg.PrivValidatorKey = PrivvalKeyFile + cfg.PrivValidatorState = PrivvalStateFile + case e2e.ProtocolUNIX: + cfg.PrivValidatorListenAddr = PrivvalAddressUNIX + case e2e.ProtocolTCP: + cfg.PrivValidatorListenAddr = PrivvalAddressTCP + default: + return nil, fmt.Errorf("invalid privval protocol setting %q", node.PrivvalProtocol) + } + case e2e.ModeSeed: + cfg.P2P.SeedMode = true + cfg.P2P.PexReactor = true + case e2e.ModeFull, e2e.ModeLight: + // Don't need to do anything, since we're using a dummy privval key by default. + default: + return nil, fmt.Errorf("unexpected mode %q", node.Mode) + } + + if node.StateSync { + cfg.StateSync.Enable = true + cfg.StateSync.RPCServers = []string{} + for _, peer := range node.Testnet.ArchiveNodes() { + if peer.Name == node.Name { + continue + } + cfg.StateSync.RPCServers = append(cfg.StateSync.RPCServers, peer.AddressRPC()) + } + if len(cfg.StateSync.RPCServers) < 2 { + return nil, errors.New("unable to find 2 suitable state sync RPC servers") + } + } + + cfg.P2P.Seeds = "" + for _, seed := range node.Seeds { + if len(cfg.P2P.Seeds) > 0 { + cfg.P2P.Seeds += "," + } + cfg.P2P.Seeds += seed.AddressP2P(true) + } + cfg.P2P.PersistentPeers = "" + for _, peer := range node.PersistentPeers { + if len(cfg.P2P.PersistentPeers) > 0 { + cfg.P2P.PersistentPeers += "," + } + cfg.P2P.PersistentPeers += peer.AddressP2P(true) + } + + if node.Testnet.LogLevel != "" { + cfg.LogLevel = node.Testnet.LogLevel + } + + if node.Testnet.LogFormat != "" { + cfg.LogFormat = node.Testnet.LogFormat + } + + if node.Prometheus { + cfg.Instrumentation.Prometheus = true + } + + return cfg, nil +} + +// MakeAppConfig generates an ABCI application config for a node. +func MakeAppConfig(node *e2e.Node) ([]byte, error) { + cfg := map[string]interface{}{ + "chain_id": node.Testnet.Name, + "dir": "data/app", + "listen": AppAddressUNIX, + "mode": node.Mode, + "protocol": "socket", + "persist_interval": node.PersistInterval, + "snapshot_interval": node.SnapshotInterval, + "retain_blocks": node.RetainBlocks, + "key_type": node.PrivvalKey.Type(), + "prepare_proposal_delay": node.Testnet.PrepareProposalDelay, + "process_proposal_delay": node.Testnet.ProcessProposalDelay, + "check_tx_delay": node.Testnet.CheckTxDelay, + "vote_extension_delay": node.Testnet.VoteExtensionDelay, + "finalize_block_delay": node.Testnet.FinalizeBlockDelay, + "vote_extensions_enable_height": node.Testnet.VoteExtensionsEnableHeight, + "vote_extensions_update_height": node.Testnet.VoteExtensionsUpdateHeight, + } + switch node.ABCIProtocol { + case e2e.ProtocolUNIX: + cfg["listen"] = AppAddressUNIX + case e2e.ProtocolTCP: + cfg["listen"] = AppAddressTCP + case e2e.ProtocolGRPC: + cfg["listen"] = AppAddressTCP + cfg["protocol"] = "grpc" + case e2e.ProtocolBuiltin, e2e.ProtocolBuiltinConnSync: + delete(cfg, "listen") + cfg["protocol"] = string(node.ABCIProtocol) + default: + return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol) + } + if node.Mode == e2e.ModeValidator { + switch node.PrivvalProtocol { + case e2e.ProtocolFile: + case e2e.ProtocolTCP: + cfg["privval_server"] = PrivvalAddressTCP + cfg["privval_key"] = PrivvalKeyFile + cfg["privval_state"] = PrivvalStateFile + case e2e.ProtocolUNIX: + cfg["privval_server"] = PrivvalAddressUNIX + cfg["privval_key"] = PrivvalKeyFile + cfg["privval_state"] = PrivvalStateFile + default: + return nil, fmt.Errorf("unexpected privval protocol setting %q", node.PrivvalProtocol) + } + } + + if len(node.Testnet.ValidatorUpdates) > 0 { + validatorUpdates := map[string]map[string]int64{} + for height, validators := range node.Testnet.ValidatorUpdates { + updateVals := map[string]int64{} + for node, power := range validators { + updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power + } + validatorUpdates[fmt.Sprintf("%v", height)] = updateVals + } + cfg["validator_update"] = validatorUpdates + } + + var buf bytes.Buffer + err := toml.NewEncoder(&buf).Encode(cfg) + if err != nil { + return nil, fmt.Errorf("failed to generate app config: %w", err) + } + return buf.Bytes(), nil +} + +// UpdateConfigStateSync updates the state sync config for a node. +func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error { + cfgPath := filepath.Join(node.Testnet.Dir, node.Name, "config", "config.toml") + + // FIXME Apparently there's no function to simply load a config file without + // involving the entire Viper apparatus, so we'll just resort to regexps. + bz, err := os.ReadFile(cfgPath) + if err != nil { + return err + } + bz = regexp.MustCompile(`(?m)^trust_height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_height = %v`, height))) + bz = regexp.MustCompile(`(?m)^trust_hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_hash = "%X"`, hash))) + return os.WriteFile(cfgPath, bz, 0o644) //nolint:gosec +} diff --git a/test/e2e/runner/start.go b/test/e2e/runner/start.go new file mode 100644 index 0000000..d73f381 --- /dev/null +++ b/test/e2e/runner/start.go @@ -0,0 +1,135 @@ +package main + +import ( + "context" + "fmt" + "sort" + "time" + + "github.com/cometbft/cometbft/libs/log" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/infra" +) + +func Start(ctx context.Context, testnet *e2e.Testnet, p infra.Provider) error { + if len(testnet.Nodes) == 0 { + return fmt.Errorf("no nodes in testnet") + } + + // Nodes are already sorted by name. Sort them by name then startAt, + // which gives the overall order startAt, mode, name. + nodeQueue := testnet.Nodes + sort.SliceStable(nodeQueue, func(i, j int) bool { + a, b := nodeQueue[i], nodeQueue[j] + switch { + case a.Mode == b.Mode: + return false + case a.Mode == e2e.ModeSeed: + return true + case a.Mode == e2e.ModeValidator && b.Mode == e2e.ModeFull: + return true + } + return false + }) + + sort.SliceStable(nodeQueue, func(i, j int) bool { + return nodeQueue[i].StartAt < nodeQueue[j].StartAt + }) + + if nodeQueue[0].StartAt > 0 { + return fmt.Errorf("no initial nodes in testnet") + } + + // Start initial nodes (StartAt: 0) + logger.Info("Starting initial network nodes...") + nodesAtZero := make([]*e2e.Node, 0) + for len(nodeQueue) > 0 && nodeQueue[0].StartAt == 0 { + nodesAtZero = append(nodesAtZero, nodeQueue[0]) + nodeQueue = nodeQueue[1:] + } + err := p.StartNodes(context.Background(), nodesAtZero...) + if err != nil { + return err + } + for _, node := range nodesAtZero { + if _, err := waitForNode(ctx, node, 0, 15*time.Second); err != nil { + return err + } + if node.PrometheusProxyPort > 0 { + logger.Info("start", "msg", + log.NewLazySprintf("Node %v up on http://%s:%v; with Prometheus on http://%s:%v/metrics", + node.Name, + node.ExternalIP, + node.ProxyPort, + node.ExternalIP, + node.PrometheusProxyPort, + ), + ) + } else { + logger.Info("start", "msg", log.NewLazySprintf("Node %v up on http://%s:%v", + node.Name, + node.ExternalIP, + node.ProxyPort, + )) + } + } + + networkHeight := testnet.InitialHeight + + // Wait for initial height + logger.Info("Waiting for initial height", + "height", networkHeight, + "nodes", len(testnet.Nodes)-len(nodeQueue), + "pending", len(nodeQueue)) + + block, blockID, err := waitForHeight(ctx, testnet, networkHeight) + if err != nil { + return err + } + + // Update any state sync nodes with a trusted height and hash + for _, node := range nodeQueue { + if node.StateSync || node.Mode == e2e.ModeLight { + err = UpdateConfigStateSync(node, block.Height, blockID.Hash.Bytes()) + if err != nil { + return err + } + } + } + + for _, node := range nodeQueue { + if node.StartAt > networkHeight { + // if we're starting a node that's ahead of + // the last known height of the network, then + // we should make sure that the rest of the + // network has reached at least the height + // that this node will start at before we + // start the node. + + networkHeight = node.StartAt + + logger.Info("Waiting for network to advance before starting catch up node", + "node", node.Name, + "height", networkHeight) + + if _, _, err := waitForHeight(ctx, testnet, networkHeight); err != nil { + return err + } + } + + logger.Info("Starting catch up node", "node", node.Name, "height", node.StartAt) + + err := p.StartNodes(context.Background(), node) + if err != nil { + return err + } + status, err := waitForNode(ctx, node, node.StartAt, 3*time.Minute) + if err != nil { + return err + } + logger.Info("start", "msg", log.NewLazySprintf("Node %v up on http://%s:%v at height %v", + node.Name, node.ExternalIP, node.ProxyPort, status.SyncInfo.LatestBlockHeight)) + } + + return nil +} diff --git a/test/e2e/runner/test.go b/test/e2e/runner/test.go new file mode 100644 index 0000000..4c2a3fb --- /dev/null +++ b/test/e2e/runner/test.go @@ -0,0 +1,31 @@ +package main + +import ( + "context" + "os" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/test/e2e/pkg/exec" +) + +// Test runs test cases under tests/ +func Test(testnet *e2e.Testnet, ifd *e2e.InfrastructureData) error { + logger.Info("Running tests in ./tests/...") + + err := os.Setenv("E2E_MANIFEST", testnet.File) + if err != nil { + return err + } + if p := ifd.Path; p != "" { + err = os.Setenv("INFRASTRUCTURE_FILE", p) + if err != nil { + return err + } + } + err = os.Setenv("INFRASTRUCTURE_TYPE", ifd.Provider) + if err != nil { + return err + } + + return exec.CommandVerbose(context.Background(), "go", "test", "-count", "1", "./tests/...") +} diff --git a/test/e2e/runner/wait.go b/test/e2e/runner/wait.go new file mode 100644 index 0000000..6006f82 --- /dev/null +++ b/test/e2e/runner/wait.go @@ -0,0 +1,35 @@ +package main + +import ( + "context" + "time" + + "github.com/cometbft/cometbft/libs/log" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +// Wait waits for a number of blocks to be produced, and for all nodes to catch +// up with it. +func Wait(ctx context.Context, testnet *e2e.Testnet, blocks int64) error { + block, _, err := waitForHeight(ctx, testnet, 0) + if err != nil { + return err + } + return WaitUntil(ctx, testnet, block.Height+blocks) +} + +// WaitUntil waits until a given height has been reached. +func WaitUntil(ctx context.Context, testnet *e2e.Testnet, height int64) error { + logger.Info("wait until", "msg", log.NewLazySprintf("Waiting for all nodes to reach height %v...", height)) + _, err := waitForAllNodes(ctx, testnet, height, waitingTime(len(testnet.Nodes), height)) + if err != nil { + return err + } + return nil +} + +// waitingTime estimates how long it should take for a node to reach the height. +// More nodes in a network implies we may expect a slower network and may have to wait longer. +func waitingTime(nodes int, height int64) time.Duration { + return time.Duration(20+(int64(nodes)*height)) * time.Second +} diff --git a/test/e2e/tests/app_test.go b/test/e2e/tests/app_test.go new file mode 100644 index 0000000..aa5afd8 --- /dev/null +++ b/test/e2e/tests/app_test.go @@ -0,0 +1,131 @@ +package e2e_test + +import ( + "bytes" + "fmt" + "math/rand" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" +) + +// Tests that any initial state given in genesis has made it into the app. +func TestApp_InitialState(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + if len(node.Testnet.InitialState) == 0 { + return + } + + client, err := node.Client() + require.NoError(t, err) + for k, v := range node.Testnet.InitialState { + resp, err := client.ABCIQuery(ctx, "", []byte(k)) + require.NoError(t, err) + assert.Equal(t, k, string(resp.Response.Key)) + assert.Equal(t, v, string(resp.Response.Value)) + } + }) +} + +// Tests that the app hash (as reported by the app) matches the last +// block and the node sync status. +func TestApp_Hash(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + client, err := node.Client() + require.NoError(t, err) + + info, err := client.ABCIInfo(ctx) + require.NoError(t, err) + require.NotEmpty(t, info.Response.LastBlockAppHash, "expected app to return app hash") + + // In next-block execution, the app hash is stored in the next block + requestedHeight := info.Response.LastBlockHeight + 1 + + require.Eventually(t, func() bool { + status, err := client.Status(ctx) + require.NoError(t, err) + require.NotZero(t, status.SyncInfo.LatestBlockHeight) + return status.SyncInfo.LatestBlockHeight >= requestedHeight + }, 5*time.Second, 500*time.Millisecond) + + block, err := client.Block(ctx, &requestedHeight) + require.NoError(t, err) + require.Equal(t, + fmt.Sprintf("%x", info.Response.LastBlockAppHash), + fmt.Sprintf("%x", block.Block.AppHash.Bytes()), + "app hash does not match last block's app hash") + }) +} + +// Tests that we can set a value and retrieve it. +func TestApp_Tx(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + client, err := node.Client() + require.NoError(t, err) + + // Generate a random value, to prevent duplicate tx errors when + // manually running the test multiple times for a testnet. + r := rand.New(rand.NewSource(time.Now().UnixNano())) + bz := make([]byte, 32) + _, err = r.Read(bz) + require.NoError(t, err) + + key := fmt.Sprintf("testapp-tx-%v", node.Name) + value := fmt.Sprintf("%x", bz) + tx := types.Tx(fmt.Sprintf("%v=%v", key, value)) + + _, err = client.BroadcastTxSync(ctx, tx) + require.NoError(t, err) + + hash := tx.Hash() + waitTime := 30 * time.Second + require.Eventuallyf(t, func() bool { + txResp, err := client.Tx(ctx, hash, false) + return err == nil && bytes.Equal(txResp.Tx, tx) + }, waitTime, time.Second, + "submitted tx wasn't committed after %v", waitTime, + ) + + // NOTE: we don't test abci query of the light client + if node.Mode == e2e.ModeLight { + return + } + + abciResp, err := client.ABCIQuery(ctx, "", []byte(key)) + require.NoError(t, err) + assert.Equal(t, key, string(abciResp.Response.Key)) + assert.Equal(t, value, string(abciResp.Response.Value)) + + }) +} + +func TestApp_VoteExtensions(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + client, err := node.Client() + require.NoError(t, err) + info, err := client.ABCIInfo(ctx) + require.NoError(t, err) + + // This special value should have been created by way of vote extensions + resp, err := client.ABCIQuery(ctx, "", []byte("extensionSum")) + require.NoError(t, err) + + // if extensions are not enabled on the network, we should expect + // the app to have any extension value set (via a normal tx). + if node.Testnet.VoteExtensionsEnableHeight != 0 && + info.Response.LastBlockHeight > node.Testnet.VoteExtensionsEnableHeight { + + parts := bytes.Split(resp.Response.Value, []byte("|")) + require.Len(t, parts, 2) + extSum, err := strconv.Atoi(string(parts[0])) + require.NoError(t, err) + require.GreaterOrEqual(t, extSum, 0) + } + }) +} diff --git a/test/e2e/tests/block_test.go b/test/e2e/tests/block_test.go new file mode 100644 index 0000000..884fbaf --- /dev/null +++ b/test/e2e/tests/block_test.go @@ -0,0 +1,95 @@ +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +// Tests that block headers are identical across nodes where present. +func TestBlock_Header(t *testing.T) { + blocks := fetchBlockChain(t) + testNode(t, func(t *testing.T, node e2e.Node) { + if node.Mode == e2e.ModeSeed { + return + } + + client, err := node.Client() + require.NoError(t, err) + status, err := client.Status(ctx) + require.NoError(t, err) + + first := status.SyncInfo.EarliestBlockHeight + last := status.SyncInfo.LatestBlockHeight + if node.RetainBlocks > 0 { + first++ // avoid race conditions with block pruning + } + + for _, block := range blocks { + if block.Height < first { + continue + } + if block.Height > last { + break + } + resp, err := client.Block(ctx, &block.Height) + require.NoError(t, err) + + require.Equal(t, block, resp.Block, + "block mismatch for height %d", block.Height) + + require.NoError(t, resp.Block.ValidateBasic(), + "block at height %d is invalid", block.Height) + } + }) +} + +// Tests that the node contains the expected block range. +func TestBlock_Range(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + if node.Mode == e2e.ModeSeed { + return + } + + client, err := node.Client() + require.NoError(t, err) + status, err := client.Status(ctx) + require.NoError(t, err) + + first := status.SyncInfo.EarliestBlockHeight + last := status.SyncInfo.LatestBlockHeight + + switch { + case node.StateSync: + assert.Greater(t, first, node.Testnet.InitialHeight, + "state synced nodes should not contain network's initial height") + + case node.RetainBlocks > 0 && int64(node.RetainBlocks) < (last-node.Testnet.InitialHeight+1): + // Delta handles race conditions in reading first/last heights. + assert.InDelta(t, node.RetainBlocks, last-first+1, 1, + "node not pruning expected blocks") + + default: + assert.Equal(t, node.Testnet.InitialHeight, first, + "node's first block should be network's initial height") + } + + for h := first; h <= last; h++ { + resp, err := client.Block(ctx, &(h)) + if err != nil && node.RetainBlocks > 0 && h == first { + // Ignore errors in first block if node is pruning blocks due to race conditions. + continue + } + require.NoError(t, err) + assert.Equal(t, h, resp.Block.Height) + } + + for h := node.Testnet.InitialHeight; h < first; h++ { + _, err := client.Block(ctx, &(h)) + require.Error(t, err) + } + }) +} diff --git a/test/e2e/tests/e2e_test.go b/test/e2e/tests/e2e_test.go new file mode 100644 index 0000000..b2fc087 --- /dev/null +++ b/test/e2e/tests/e2e_test.go @@ -0,0 +1,157 @@ +package e2e_test + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/stretchr/testify/require" + + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + rpctypes "github.com/cometbft/cometbft/rpc/core/types" + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" +) + +func init() { + // This can be used to manually specify a testnet manifest and/or node to + // run tests against. The testnet must have been started by the runner first. + // os.Setenv("E2E_MANIFEST", "networks/ci.toml") + // os.Setenv("E2E_NODE", "validator01") +} + +var ( + ctx = context.Background() + testnetCache = map[string]e2e.Testnet{} + testnetCacheMtx = sync.Mutex{} + blocksCache = map[string][]*types.Block{} + blocksCacheMtx = sync.Mutex{} +) + +// testNode runs tests for testnet nodes. The callback function is given a +// single node to test, running as a subtest in parallel with other subtests. +// +// The testnet manifest must be given as the envvar E2E_MANIFEST. If not set, +// these tests are skipped so that they're not picked up during normal unit +// test runs. If E2E_NODE is also set, only the specified node is tested, +// otherwise all nodes are tested. +func testNode(t *testing.T, testFunc func(*testing.T, e2e.Node)) { + t.Helper() + + testnet := loadTestnet(t) + nodes := testnet.Nodes + + if name := os.Getenv("E2E_NODE"); name != "" { + node := testnet.LookupNode(name) + require.NotNil(t, node, "node %q not found in testnet %q", name, testnet.Name) + nodes = []*e2e.Node{node} + } + + for _, node := range nodes { + if node.Stateless() { + continue + } + + node := *node + t.Run(node.Name, func(t *testing.T) { + t.Parallel() + testFunc(t, node) + }) + } +} + +// loadTestnet loads the testnet based on the E2E_MANIFEST envvar. +func loadTestnet(t *testing.T) e2e.Testnet { + t.Helper() + + manifestFile := os.Getenv("E2E_MANIFEST") + if manifestFile == "" { + t.Skip("E2E_MANIFEST not set, not an end-to-end test run") + } + if !filepath.IsAbs(manifestFile) { + manifestFile = filepath.Join("..", manifestFile) + } + ifdType := os.Getenv("INFRASTRUCTURE_TYPE") + ifdFile := os.Getenv("INFRASTRUCTURE_FILE") + if ifdType != "docker" && ifdFile == "" { + t.Fatalf("INFRASTRUCTURE_FILE not set and INFRASTRUCTURE_TYPE is not 'docker'") + } + testnetCacheMtx.Lock() + defer testnetCacheMtx.Unlock() + if testnet, ok := testnetCache[manifestFile]; ok { + return testnet + } + m, err := e2e.LoadManifest(manifestFile) + require.NoError(t, err) + + var ifd e2e.InfrastructureData + switch ifdType { + case "docker": + ifd, err = e2e.NewDockerInfrastructureData(m) + require.NoError(t, err) + case "digital-ocean": + ifd, err = e2e.InfrastructureDataFromFile(ifdFile) + require.NoError(t, err) + default: + } + require.NoError(t, err) + + testnet, err := e2e.LoadTestnet(manifestFile, ifd) + require.NoError(t, err) + testnetCache[manifestFile] = *testnet + return *testnet +} + +// fetchBlockChain fetches a complete, up-to-date block history from +// the freshest testnet archive node. +func fetchBlockChain(t *testing.T) []*types.Block { + t.Helper() + + testnet := loadTestnet(t) + + // Find the freshest archive node + var ( + client *rpchttp.HTTP + status *rpctypes.ResultStatus + ) + for _, node := range testnet.ArchiveNodes() { + c, err := node.Client() + require.NoError(t, err) + s, err := c.Status(ctx) + require.NoError(t, err) + if status == nil || s.SyncInfo.LatestBlockHeight > status.SyncInfo.LatestBlockHeight { + client = c + status = s + } + } + require.NotNil(t, client, "couldn't find an archive node") + + // Fetch blocks. Look for existing block history in the block cache, and + // extend it with any new blocks that have been produced. + blocksCacheMtx.Lock() + defer blocksCacheMtx.Unlock() + + from := status.SyncInfo.EarliestBlockHeight + to := status.SyncInfo.LatestBlockHeight + blocks, ok := blocksCache[testnet.Name] + if !ok { + blocks = make([]*types.Block, 0, to-from+1) + } + if len(blocks) > 0 { + from = blocks[len(blocks)-1].Height + 1 + } + + for h := from; h <= to; h++ { + resp, err := client.Block(ctx, &(h)) + require.NoError(t, err) + require.NotNil(t, resp.Block) + require.Equal(t, h, resp.Block.Height, "unexpected block height %v", resp.Block.Height) + blocks = append(blocks, resp.Block) + } + require.NotEmpty(t, blocks, "blockchain does not contain any blocks") + blocksCache[testnet.Name] = blocks + + return blocks +} diff --git a/test/e2e/tests/evidence_test.go b/test/e2e/tests/evidence_test.go new file mode 100644 index 0000000..617a4b8 --- /dev/null +++ b/test/e2e/tests/evidence_test.go @@ -0,0 +1,22 @@ +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// assert that all nodes that have blocks at the height of a misbehavior has evidence +// for that misbehavior +func TestEvidence_Misbehavior(t *testing.T) { + blocks := fetchBlockChain(t) + testnet := loadTestnet(t) + seenEvidence := 0 + for _, block := range blocks { + if len(block.Evidence.Evidence) != 0 { + seenEvidence += len(block.Evidence.Evidence) + } + } + require.Equal(t, testnet.Evidence, seenEvidence, + "difference between the amount of evidence produced and committed") +} diff --git a/test/e2e/tests/net_test.go b/test/e2e/tests/net_test.go new file mode 100644 index 0000000..756307b --- /dev/null +++ b/test/e2e/tests/net_test.go @@ -0,0 +1,46 @@ +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" +) + +// Tests that all nodes have peered with each other, regardless of discovery method. +func TestNet_Peers(t *testing.T) { + // FIXME Skip test since nodes aren't always able to fully mesh + t.SkipNow() + + testNode(t, func(t *testing.T, node e2e.Node) { + // Seed nodes shouldn't necessarily mesh with the entire network. + if node.Mode == e2e.ModeSeed { + return + } + + client, err := node.Client() + require.NoError(t, err) + netInfo, err := client.NetInfo(ctx) + require.NoError(t, err) + + require.Equal(t, len(node.Testnet.Nodes)-1, netInfo.NPeers, + "node is not fully meshed with peers") + + seen := map[string]bool{} + for _, n := range node.Testnet.Nodes { + seen[n.Name] = (n.Name == node.Name) // we've clearly seen ourself + } + for _, peerInfo := range netInfo.Peers { + peer := node.Testnet.LookupNode(peerInfo.NodeInfo.Moniker) + require.NotNil(t, peer, "unknown node %v", peerInfo.NodeInfo.Moniker) + require.Equal(t, peer.InternalIP.String(), peerInfo.RemoteIP, + "unexpected IP address for peer %v", peer.Name) + seen[peerInfo.NodeInfo.Moniker] = true + } + + for name := range seen { + require.True(t, seen[name], "node %v not peered with %v", node.Name, name) + } + }) +} diff --git a/test/e2e/tests/validator_test.go b/test/e2e/tests/validator_test.go new file mode 100644 index 0000000..92cd232 --- /dev/null +++ b/test/e2e/tests/validator_test.go @@ -0,0 +1,168 @@ +package e2e_test + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" + + e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/cometbft/cometbft/types" +) + +// Tests that validator sets are available and correct according to +// scheduled validator updates. +func TestValidator_Sets(t *testing.T) { + testNode(t, func(t *testing.T, node e2e.Node) { + if node.Mode == e2e.ModeSeed { + return + } + + client, err := node.Client() + require.NoError(t, err) + status, err := client.Status(ctx) + require.NoError(t, err) + + first := status.SyncInfo.EarliestBlockHeight + last := status.SyncInfo.LatestBlockHeight + + // skip first block if node is pruning blocks, to avoid race conditions + if node.RetainBlocks > 0 { + first++ + } + + valSchedule := newValidatorSchedule(*node.Testnet) + valSchedule.Increment(first - node.Testnet.InitialHeight) + + for h := first; h <= last; h++ { + validators := []*types.Validator{} + perPage := 100 + for page := 1; ; page++ { + resp, err := client.Validators(ctx, &(h), &(page), &perPage) + require.NoError(t, err) + validators = append(validators, resp.Validators...) + if len(validators) == resp.Total { + break + } + } + require.Equal(t, valSchedule.Set.Validators, validators, + "incorrect validator set at height %v", h) + valSchedule.Increment(1) + } + }) +} + +// Tests that a validator proposes blocks when it's supposed to. It tolerates some +// missed blocks, e.g. due to testnet perturbations. +func TestValidator_Propose(t *testing.T) { + blocks := fetchBlockChain(t) + testNode(t, func(t *testing.T, node e2e.Node) { + if node.Mode != e2e.ModeValidator { + return + } + address := node.PrivvalKey.PubKey().Address() + valSchedule := newValidatorSchedule(*node.Testnet) + + expectCount := 0 + proposeCount := 0 + for _, block := range blocks { + if bytes.Equal(valSchedule.Set.Proposer.Address, address) { + expectCount++ + if bytes.Equal(block.ProposerAddress, address) { + proposeCount++ + } + } + valSchedule.Increment(1) + } + + require.False(t, proposeCount == 0 && expectCount > 0, + "node did not propose any blocks (expected %v)", expectCount) + if expectCount > 5 { + require.GreaterOrEqual(t, proposeCount, 3, "validator didn't propose even 3 blocks") + } + }) +} + +// Tests that a validator signs blocks when it's supposed to. It tolerates some +// missed blocks, e.g. due to testnet perturbations. +func TestValidator_Sign(t *testing.T) { + blocks := fetchBlockChain(t) + testNode(t, func(t *testing.T, node e2e.Node) { + if node.Mode != e2e.ModeValidator { + return + } + address := node.PrivvalKey.PubKey().Address() + valSchedule := newValidatorSchedule(*node.Testnet) + + expectCount := 0 + signCount := 0 + for _, block := range blocks[1:] { // Skip first block, since it has no signatures + signed := false + for _, sig := range block.LastCommit.Signatures { + if bytes.Equal(sig.ValidatorAddress, address) { + signed = true + break + } + } + if valSchedule.Set.HasAddress(address) { + expectCount++ + if signed { + signCount++ + } + } else { + require.False(t, signed, "unexpected signature for block %v", block.LastCommit.Height) + } + valSchedule.Increment(1) + } + + require.False(t, signCount == 0 && expectCount > 0, + "validator did not sign any blocks (expected %v)", expectCount) + if expectCount > 7 { + require.GreaterOrEqual(t, signCount, 3, "validator didn't sign even 3 blocks (expected %v)", expectCount) + } + }) +} + +// validatorSchedule is a validator set iterator, which takes into account +// validator set updates. +type validatorSchedule struct { + Set *types.ValidatorSet + height int64 + updates map[int64]map[*e2e.Node]int64 +} + +func newValidatorSchedule(testnet e2e.Testnet) *validatorSchedule { + valMap := testnet.Validators // genesis validators + if v, ok := testnet.ValidatorUpdates[0]; ok { // InitChain validators + valMap = v + } + return &validatorSchedule{ + height: testnet.InitialHeight, + Set: types.NewValidatorSet(makeVals(valMap)), + updates: testnet.ValidatorUpdates, + } +} + +func (s *validatorSchedule) Increment(heights int64) { + for i := int64(0); i < heights; i++ { + s.height++ + if s.height > 2 { + // validator set updates are offset by 2, since they only take effect + // two blocks after they're returned. + if update, ok := s.updates[s.height-2]; ok { + if err := s.Set.UpdateWithChangeSet(makeVals(update)); err != nil { + panic(err) + } + } + } + s.Set.IncrementProposerPriority(1) + } +} + +func makeVals(valMap map[*e2e.Node]int64) []*types.Validator { + vals := make([]*types.Validator, 0, len(valMap)) + for node, power := range valMap { + vals = append(vals, types.NewValidator(node.PrivvalKey.PubKey(), power)) + } + return vals +} diff --git a/test/fuzz/README.md b/test/fuzz/README.md new file mode 100644 index 0000000..059c3d1 --- /dev/null +++ b/test/fuzz/README.md @@ -0,0 +1,22 @@ +# fuzz + +Fuzzing for various packages in Tendermint using the fuzzing infrastructure +included in Go 1.21. + +Inputs: + +- mempool `CheckTx` (using kvstore in-process ABCI app) +- p2p `SecretConnection#Read` and `SecretConnection#Write` +- rpc jsonrpc server + +## Running + +The fuzz tests are in native Go fuzzing format. Use the `go` tool to run them: + +```sh +go test -fuzz Mempool ./tests +go test -fuzz P2PSecretConnection ./tests +go test -fuzz RPCJSONRPCServer ./tests +``` + +See [the Go Fuzzing introduction](https://go.dev/doc/fuzz/) for more information. diff --git a/test/fuzz/mempool/checktx.go b/test/fuzz/mempool/checktx.go new file mode 100644 index 0000000..6db5d6e --- /dev/null +++ b/test/fuzz/mempool/checktx.go @@ -0,0 +1,33 @@ +package reactor + +import ( + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/config" + mempl "github.com/cometbft/cometbft/mempool" + "github.com/cometbft/cometbft/proxy" +) + +var mempool mempl.Mempool + +func init() { + app := kvstore.NewInMemoryApplication() + cc := proxy.NewLocalClientCreator(app) + appConnMem, _ := cc.NewABCIClient() + err := appConnMem.Start() + if err != nil { + panic(err) + } + + cfg := config.DefaultMempoolConfig() + cfg.Broadcast = false + mempool = mempl.NewCListMempool(cfg, appConnMem, 0) +} + +func Fuzz(data []byte) int { + err := mempool.CheckTx(data, nil, mempl.TxInfo{}) + if err != nil { + return 0 + } + + return 1 +} diff --git a/test/fuzz/mempool/fuzz_test.go b/test/fuzz/mempool/fuzz_test.go new file mode 100644 index 0000000..8b45787 --- /dev/null +++ b/test/fuzz/mempool/fuzz_test.go @@ -0,0 +1,34 @@ +package reactor_test + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + + mempl "github.com/cometbft/cometbft/test/fuzz/mempool" +) + +const testdataCasesDir = "testdata/cases" + +func TestMempoolTestdataCases(t *testing.T) { + entries, err := os.ReadDir(testdataCasesDir) + require.NoError(t, err) + + for _, e := range entries { + entry := e + t.Run(entry.Name(), func(t *testing.T) { + defer func() { + r := recover() + require.Nilf(t, r, "testdata/cases test panic") + }() + f, err := os.Open(filepath.Join(testdataCasesDir, entry.Name())) + require.NoError(t, err) + input, err := io.ReadAll(f) + require.NoError(t, err) + mempl.Fuzz(input) + }) + } +} diff --git a/test/fuzz/mempool/testdata/cases/empty b/test/fuzz/mempool/testdata/cases/empty new file mode 100644 index 0000000..473a0f4 diff --git a/test/fuzz/oss-fuzz-build.sh b/test/fuzz/oss-fuzz-build.sh new file mode 100755 index 0000000..1a3daa1 --- /dev/null +++ b/test/fuzz/oss-fuzz-build.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# This script is invoked by OSS-Fuzz to run fuzz tests against CometBFT. +# See https://github.com/google/oss-fuzz/blob/master/projects/tendermint/build.sh +set -euo pipefail + +export FUZZ_ROOT="github.com/cometbft/cometbft" + +build_go_fuzzer() { + local function="$1" + local fuzzer="$2" + + go run github.com/orijtech/otils/corpus2ossfuzz@latest -o "$OUT"/"$fuzzer"_seed_corpus.zip -corpus test/fuzz/tests/testdata/fuzz/"$function" + compile_native_go_fuzzer "$FUZZ_ROOT"/test/fuzz/tests "$function" "$fuzzer" +} + +go get github.com/AdamKorcz/go-118-fuzz-build/testing +go get github.com/prometheus/common/expfmt@v0.32.1 + +build_go_fuzzer FuzzP2PSecretConnection fuzz_p2p_secretconnection + +build_go_fuzzer FuzzMempool fuzz_mempool + +build_go_fuzzer FuzzRPCJSONRPCServer fuzz_rpc_jsonrpc_server diff --git a/test/fuzz/tests/mempool_test.go b/test/fuzz/tests/mempool_test.go new file mode 100644 index 0000000..e6cfd4c --- /dev/null +++ b/test/fuzz/tests/mempool_test.go @@ -0,0 +1,32 @@ +//go:build gofuzz || go1.21 + +package tests + +import ( + "testing" + + abciclient "github.com/cometbft/cometbft/abci/client" + "github.com/cometbft/cometbft/abci/example/kvstore" + "github.com/cometbft/cometbft/config" + cmtsync "github.com/cometbft/cometbft/libs/sync" + mempool "github.com/cometbft/cometbft/mempool" +) + +func FuzzMempool(f *testing.F) { + app := kvstore.NewInMemoryApplication() + mtx := new(cmtsync.Mutex) + conn := abciclient.NewLocalClient(mtx, app) + err := conn.Start() + if err != nil { + panic(err) + } + + cfg := config.DefaultMempoolConfig() + cfg.Broadcast = false + + mp := mempool.NewCListMempool(cfg, conn, 0) + + f.Fuzz(func(t *testing.T, data []byte) { + _ = mp.CheckTx(data, nil, mempool.TxInfo{}) + }) +} diff --git a/test/fuzz/tests/p2p_secretconnection_test.go b/test/fuzz/tests/p2p_secretconnection_test.go new file mode 100644 index 0000000..1162ffe --- /dev/null +++ b/test/fuzz/tests/p2p_secretconnection_test.go @@ -0,0 +1,135 @@ +//go:build gofuzz || go1.21 + +package tests + +import ( + "bytes" + "fmt" + "io" + "log" + "testing" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/libs/async" + sc "github.com/cometbft/cometbft/p2p/conn" +) + +func FuzzP2PSecretConnection(f *testing.F) { + f.Fuzz(func(t *testing.T, data []byte) { + fuzz(data) + }) +} + +func fuzz(data []byte) { + if len(data) == 0 { + return + } + + fooConn, barConn := makeSecretConnPair() + + // Run Write in a separate goroutine because if data is greater than 1024 + // bytes, each Write must be followed by Read (see io.Pipe documentation). + go func() { + // Copy data because Write modifies the slice. + dataToWrite := make([]byte, len(data)) + copy(dataToWrite, data) + + n, err := fooConn.Write(dataToWrite) + if err != nil { + panic(err) + } + if n < len(data) { + panic(fmt.Sprintf("wanted to write %d bytes, but %d was written", len(data), n)) + } + }() + + dataRead := make([]byte, len(data)) + totalRead := 0 + for totalRead < len(data) { + buf := make([]byte, len(data)-totalRead) + m, err := barConn.Read(buf) + if err != nil { + panic(err) + } + copy(dataRead[totalRead:], buf[:m]) + totalRead += m + } + + if !bytes.Equal(data, dataRead) { + panic("bytes written != read") + } +} + +type kvstoreConn struct { + *io.PipeReader + *io.PipeWriter +} + +func (drw kvstoreConn) Close() (err error) { + err2 := drw.PipeWriter.CloseWithError(io.EOF) + err1 := drw.PipeReader.Close() + if err2 != nil { + return err + } + return err1 +} + +// Each returned ReadWriteCloser is akin to a net.Connection +func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) { + barReader, fooWriter := io.Pipe() + fooReader, barWriter := io.Pipe() + return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter} +} + +func makeSecretConnPair() (fooSecConn, barSecConn *sc.SecretConnection) { + var ( + fooConn, barConn = makeKVStoreConnPair() + fooPrvKey = ed25519.GenPrivKey() + fooPubKey = fooPrvKey.PubKey() + barPrvKey = ed25519.GenPrivKey() + barPubKey = barPrvKey.PubKey() + ) + + // Make connections from both sides in parallel. + trs, ok := async.Parallel( + func(_ int) (val interface{}, abort bool, err error) { + fooSecConn, err = sc.MakeSecretConnection(fooConn, fooPrvKey) + if err != nil { + log.Printf("failed to establish SecretConnection for foo: %v", err) + return nil, true, err + } + remotePubBytes := fooSecConn.RemotePubKey() + if !remotePubBytes.Equals(barPubKey) { + err = fmt.Errorf("unexpected fooSecConn.RemotePubKey. Expected %v, got %v", + barPubKey, fooSecConn.RemotePubKey()) + log.Print(err) + return nil, true, err + } + return nil, false, nil + }, + func(_ int) (val interface{}, abort bool, err error) { + barSecConn, err = sc.MakeSecretConnection(barConn, barPrvKey) + if barSecConn == nil { + log.Printf("failed to establish SecretConnection for bar: %v", err) + return nil, true, err + } + remotePubBytes := barSecConn.RemotePubKey() + if !remotePubBytes.Equals(fooPubKey) { + err = fmt.Errorf("unexpected barSecConn.RemotePubKey. Expected %v, got %v", + fooPubKey, barSecConn.RemotePubKey()) + log.Print(err) + return nil, true, err + } + return nil, false, nil + }, + ) + + if trs.FirstError() != nil { + log.Fatalf("unexpected error: %v", trs.FirstError()) + } + if !ok { + log.Fatal("Unexpected task abortion") + } + + return fooSecConn, barSecConn +} diff --git a/test/fuzz/tests/rpc_jsonrpc_server_test.go b/test/fuzz/tests/rpc_jsonrpc_server_test.go new file mode 100644 index 0000000..c6847a5 --- /dev/null +++ b/test/fuzz/tests/rpc_jsonrpc_server_test.go @@ -0,0 +1,71 @@ +//go:build gofuzz || go1.21 + +package tests + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/cometbft/cometbft/libs/log" + rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" +) + +func FuzzRPCJSONRPCServer(f *testing.F) { + type args struct { + S string `json:"s"` + I int `json:"i"` + } + rpcFuncMap := map[string]*rpcserver.RPCFunc{ + "c": rpcserver.NewRPCFunc(func(ctx *rpctypes.Context, args *args, options ...rpcserver.Option) (string, error) { + return "foo", nil + }, "args"), + } + + mux := http.NewServeMux() + rpcserver.RegisterRPCFuncs(mux, rpcFuncMap, log.NewNopLogger()) + f.Fuzz(func(t *testing.T, data []byte) { + if len(data) == 0 { + return + } + + req, err := http.NewRequest("POST", "http://localhost/", bytes.NewReader(data)) + if err != nil { + panic(err) + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + res := rec.Result() + blob, err := io.ReadAll(res.Body) + if err != nil { + panic(err) + } + if err := res.Body.Close(); err != nil { + panic(err) + } + if len(blob) == 0 { + return + } + + if outputJSONIsSlice(blob) { + var recv []rpctypes.RPCResponse + if err := json.Unmarshal(blob, &recv); err != nil { + panic(err) + } + return + } + var recv rpctypes.RPCResponse + if err := json.Unmarshal(blob, &recv); err != nil { + panic(err) + } + }) +} + +func outputJSONIsSlice(input []byte) bool { + var slice []json.RawMessage + return json.Unmarshal(input, &slice) == nil +} diff --git a/test/fuzz/tests/testdata/fuzz/FuzzMempool/1daffc1033a0bfc7f0c2bccb7440674e67a9e2cc0a4531863076254ada059863 b/test/fuzz/tests/testdata/fuzz/FuzzMempool/1daffc1033a0bfc7f0c2bccb7440674e67a9e2cc0a4531863076254ada059863 new file mode 100644 index 0000000..9f85f19 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzMempool/1daffc1033a0bfc7f0c2bccb7440674e67a9e2cc0a4531863076254ada059863 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("S1") diff --git a/test/fuzz/tests/testdata/fuzz/FuzzMempool/582528ddfad69eb57775199a43e0f9fd5c94bba343ce7bb6724d4ebafe311ed4 b/test/fuzz/tests/testdata/fuzz/FuzzMempool/582528ddfad69eb57775199a43e0f9fd5c94bba343ce7bb6724d4ebafe311ed4 new file mode 100644 index 0000000..63e674b --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzMempool/582528ddfad69eb57775199a43e0f9fd5c94bba343ce7bb6724d4ebafe311ed4 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("0") diff --git a/test/fuzz/tests/testdata/fuzz/FuzzMempool/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d b/test/fuzz/tests/testdata/fuzz/FuzzMempool/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d new file mode 100644 index 0000000..e6cd984 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzMempool/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/0f1a3d10e4d642e42a3ccd9bad652d355431f5824327271aca6f648e8cd4e786 b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/0f1a3d10e4d642e42a3ccd9bad652d355431f5824327271aca6f648e8cd4e786 new file mode 100644 index 0000000..9b10917 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/0f1a3d10e4d642e42a3ccd9bad652d355431f5824327271aca6f648e8cd4e786 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte(" ") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/172c521d1c5e7a5cce55e39b235928fc1c8c4adbb4635913c204c4724cf47d20 b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/172c521d1c5e7a5cce55e39b235928fc1c8c4adbb4635913c204c4724cf47d20 new file mode 100644 index 0000000..c1eb272 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/172c521d1c5e7a5cce55e39b235928fc1c8c4adbb4635913c204c4724cf47d20 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"a\": 12, \"tsp\": 999, k: \"blue\"}") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/a9481542b8154bfe8fe868c8907cb66557347cb9b45709b17da861997d7cabea b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/a9481542b8154bfe8fe868c8907cb66557347cb9b45709b17da861997d7cabea new file mode 100644 index 0000000..ad5c792 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/a9481542b8154bfe8fe868c8907cb66557347cb9b45709b17da861997d7cabea @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\"\"") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/ba3758980fe724f83bdf1cb97caa73657b4a78d48e5fd6fc3b1590d24799e803 b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/ba3758980fe724f83bdf1cb97caa73657b4a78d48e5fd6fc3b1590d24799e803 new file mode 100644 index 0000000..e798d32 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/ba3758980fe724f83bdf1cb97caa73657b4a78d48e5fd6fc3b1590d24799e803 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("9999.999") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/c22ff3cdf5145a03ecc6a2c18a7ec4eb3c9e1384af92cfa14cf50951535b6c85 b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/c22ff3cdf5145a03ecc6a2c18a7ec4eb3c9e1384af92cfa14cf50951535b6c85 new file mode 100644 index 0000000..02c12e0 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/c22ff3cdf5145a03ecc6a2c18a7ec4eb3c9e1384af92cfa14cf50951535b6c85 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte(" a ") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d new file mode 100644 index 0000000..e6cd984 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/dc7304b2cddeadd08647d30b1d027f749960376c338e14a81e0396ffc6e6d6bd b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/dc7304b2cddeadd08647d30b1d027f749960376c338e14a81e0396ffc6e6d6bd new file mode 100644 index 0000000..b4ff69e --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzP2PSecretConnection/dc7304b2cddeadd08647d30b1d027f749960376c338e14a81e0396ffc6e6d6bd @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("Tendermint fuzzing") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/058ae08103537df220789dea46edb8b7cf7368e90da0cb35888a1452f4d114a2 b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/058ae08103537df220789dea46edb8b7cf7368e90da0cb35888a1452f4d114a2 new file mode 100644 index 0000000..d920313 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/058ae08103537df220789dea46edb8b7cf7368e90da0cb35888a1452f4d114a2 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("[{\"iD\":7},{\"iD\":7}]") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/2ab633cb322fca9e76fc965b430076844ebd0b3c4f30f5263b94a3d50f00bce6 b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/2ab633cb322fca9e76fc965b430076844ebd0b3c4f30f5263b94a3d50f00bce6 new file mode 100644 index 0000000..371f5d7 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/2ab633cb322fca9e76fc965b430076844ebd0b3c4f30f5263b94a3d50f00bce6 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("[0,0]") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/aadb440fa55da05c1185e3e64b33c804d994cce06781e8c39481411793a8a73f b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/aadb440fa55da05c1185e3e64b33c804d994cce06781e8c39481411793a8a73f new file mode 100644 index 0000000..edd9b4b --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/aadb440fa55da05c1185e3e64b33c804d994cce06781e8c39481411793a8a73f @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("[0]") \ No newline at end of file diff --git a/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d new file mode 100644 index 0000000..e6cd984 --- /dev/null +++ b/test/fuzz/tests/testdata/fuzz/FuzzRPCJSONRPCServer/d40a98862ed393eb712e47a91bcef18e6f24cf368bb4bd248c7a7101ef8e178d @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("") \ No newline at end of file diff --git a/test/loadtime/Makefile b/test/loadtime/Makefile new file mode 100644 index 0000000..e983d4d --- /dev/null +++ b/test/loadtime/Makefile @@ -0,0 +1,33 @@ +GOMOD="github.com/cometbft/cometbft/test/loadtime" +OUTPUT?=build/ + +build: + go build $(BUILD_FLAGS) -tags '$(BUILD_TAGS)' -o $(OUTPUT)load ./cmd/load/ + go build $(BUILD_FLAGS) -tags '$(BUILD_TAGS)' -o $(OUTPUT)report ./cmd/report/ +.PHONY: build + +check-proto-gen-deps: +ifeq (,$(shell which protoc)) + $(error "protoc is required for Protobuf generation. See instructions for your platform on how to install it.") +endif +ifeq (,$(shell which protoc-gen-go)) + $(error "protoc-gen-go is required for Protobuf generation. See instructions for your platform on how to install it.") +endif +.PHONY: check-proto-gen-deps + +check-proto-format-deps: +ifeq (,$(shell which clang-format)) + $(error "clang-format is required for Protobuf formatting. See instructions for your platform on how to install it.") +endif +.PHONY: check-proto-format-deps + +proto-format: check-proto-format-deps + @echo "Formatting Protobuf files" + @find . -name '*.proto' -exec clang-format -i {} \; +.PHONY: proto-format + +proto-gen: check-proto-gen-deps + @echo "Generating Protobuf files" + @find . -name '*.proto' -exec protoc \ + --go_out=paths=source_relative:. {} \; +.PHONY: proto-gen diff --git a/test/loadtime/README.md b/test/loadtime/README.md new file mode 100644 index 0000000..59bc6df --- /dev/null +++ b/test/loadtime/README.md @@ -0,0 +1,69 @@ +# loadtime + +This directory contains the `loadtime` tools, a set of tools for generating +transaction load against CometBFT and measuring their resulting latency. +`loadtime` generates transactions that contain the timestamp of when they were +generated as well as additional metadata to track the variables used when +generating the load. + + +## Building the tool set + +The `Makefile` contains a target for building the `loadtime` tools. + +The following command will build the tool and place the resulting binaries in `./build/`. + +```bash +make build +``` + +## `load` + +The `load` binary is built when `make build` is invoked. The `load` tool generates +transactions and broadcasts them to CometBFT. + +`load` leverages the [tm-load-test](https://github.com/informalsystems/tm-load-test) +framework. As a result, all flags and options specified on the `tm-load-test` apply to +`load`. + +Below is a basic invocation for generating load against a CometBFT websocket running +on `localhost:25567` + +```bash +./build/load \ + -c 1 -T 10 -r 1000 -s 1024 \ + --broadcast-tx-method sync \ + --endpoints ws://localhost:26657/websocket +``` + +## `report` + +The `report` binary is built when `make build` is invoked. The `report` tool +reads all of the blocks from the specified blockstore database and calculates +transaction latency metrics. `report` reads transactions generated by `load` +and uses the difference between the timestamp contained in the transaction and +the timestamp of the block the transaction was executed in to determine transaction latency. +`report` outputs a set of metrics calculated on the list of latencies, including +minimum, maximum, and average latency as well as the standard deviation. + +Below is a basic invocation of the report tool with a data directory under `/home/test/.cometbft/data/` +where the data was saved in a `goleveldb` database. + + +```bash +./build/report --database-type goleveldb --data-dir ~/.cometbft/data +``` + +The `report` tool also supports outputting the raw data as `csv`. This can be +useful if you want to use a more powerful tool to aggregate and analyze the data. + +Below is an invocation of the report tool that outputs the data to a `csv` file +in `out.csv` + +```bash +./build/report --database-type goleveldb --data-dir ~/.cometbft/data --csv out.csv +``` + +The `report` tool outputs the data for each experiment separately, identified +by the UUID generated by the `load` tool at the start of the experiment. It also +outputs the experimental values used for the run. diff --git a/test/loadtime/basic.sh b/test/loadtime/basic.sh new file mode 100755 index 0000000..983bbcb --- /dev/null +++ b/test/loadtime/basic.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +set -euo pipefail + +# A basic invocation of the loadtime tool. + +./build/load \ + -c 1 -T 10 -r 1000 -s 1024 \ + --broadcast-tx-method sync \ + --endpoints ws://localhost:26657/websocket + diff --git a/test/loadtime/cmd/load/main.go b/test/loadtime/cmd/load/main.go new file mode 100644 index 0000000..9b986bd --- /dev/null +++ b/test/loadtime/cmd/load/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + + "github.com/google/uuid" + "github.com/informalsystems/tm-load-test/pkg/loadtest" + + "github.com/cometbft/cometbft/test/loadtime/payload" +) + +// Ensure all of the interfaces are correctly satisfied. +var ( + _ loadtest.ClientFactory = (*ClientFactory)(nil) + _ loadtest.Client = (*TxGenerator)(nil) +) + +// ClientFactory implements the loadtest.ClientFactory interface. +type ClientFactory struct { + ID []byte +} + +// TxGenerator is responsible for generating transactions. +// TxGenerator holds the set of information that will be used to generate +// each transaction. +type TxGenerator struct { + id []byte + conns uint64 + rate uint64 + size uint64 +} + +func main() { + u := [16]byte(uuid.New()) // generate run ID on startup + if err := loadtest.RegisterClientFactory("loadtime-client", &ClientFactory{ID: u[:]}); err != nil { + panic(err) + } + loadtest.Run(&loadtest.CLIConfig{ + AppName: "loadtime", + AppShortDesc: "Generate timestamped transaction load.", + AppLongDesc: "loadtime generates transaction load for the purpose of measuring the end-to-end latency of a transaction from submission to execution in a CometBFT network.", + DefaultClientFactory: "loadtime-client", + }) +} + +func (f *ClientFactory) ValidateConfig(cfg loadtest.Config) error { + psb, err := payload.MaxUnpaddedSize() + if err != nil { + return err + } + if psb > cfg.Size { + return fmt.Errorf("payload size exceeds configured size") + } + return nil +} + +func (f *ClientFactory) NewClient(cfg loadtest.Config) (loadtest.Client, error) { + return &TxGenerator{ + id: f.ID, + conns: uint64(cfg.Connections), + rate: uint64(cfg.Rate), + size: uint64(cfg.Size), + }, nil +} + +func (c *TxGenerator) GenerateTx() ([]byte, error) { + return payload.NewBytes(&payload.Payload{ + Connections: c.conns, + Rate: c.rate, + Size: c.size, + Id: c.id, + }) +} diff --git a/test/loadtime/cmd/report/main.go b/test/loadtime/cmd/report/main.go new file mode 100644 index 0000000..d58b6c8 --- /dev/null +++ b/test/loadtime/cmd/report/main.go @@ -0,0 +1,103 @@ +package main + +import ( + "encoding/csv" + "flag" + "fmt" + "log" + "os" + "strconv" + "strings" + + dbm "github.com/cometbft/cometbft-db" + + "github.com/cometbft/cometbft/store" + "github.com/cometbft/cometbft/test/loadtime/report" +) + +var ( + db = flag.String("database-type", "goleveldb", "the type of database holding the blockstore") + dir = flag.String("data-dir", "", "path to the directory containing the CometBFT databases") + csvOut = flag.String("csv", "", "dump the extracted latencies as raw csv for use in additional tooling") +) + +func main() { + flag.Parse() + if *db == "" { + log.Fatalf("must specify a database-type") + } + if *dir == "" { + log.Fatalf("must specify a data-dir") + } + d := strings.TrimPrefix(*dir, "~/") + if d != *dir { + h, err := os.UserHomeDir() + if err != nil { + panic(err) + } + d = h + "/" + d + } + _, err := os.Stat(d) + if err != nil { + panic(err) + } + dbType := dbm.BackendType(*db) + db, err := dbm.NewDB("blockstore", dbType, d) + if err != nil { + panic(err) + } + s := store.NewBlockStore(db) + defer s.Close() + rs, err := report.GenerateFromBlockStore(s) + if err != nil { + panic(err) + } + if *csvOut != "" { + cf, err := os.Create(*csvOut) + if err != nil { + panic(err) + } + w := csv.NewWriter(cf) + err = w.WriteAll(toCSVRecords(rs.List())) + if err != nil { + panic(err) + } + return + } + for _, r := range rs.List() { + fmt.Printf(""+ + "Experiment ID: %s\n\n"+ + "\tConnections: %d\n"+ + "\tRate: %d\n"+ + "\tSize: %d\n\n"+ + "\tTotal Valid Tx: %d\n"+ + "\tTotal Negative Latencies: %d\n"+ + "\tMinimum Latency: %s\n"+ + "\tMaximum Latency: %s\n"+ + "\tAverage Latency: %s\n"+ + "\tStandard Deviation: %s\n\n", r.ID, r.Connections, r.Rate, r.Size, len(r.All), r.NegativeCount, r.Min, r.Max, r.Avg, r.StdDev) + } + fmt.Printf("Total Invalid Tx: %d\n", rs.ErrorCount()) +} + +func toCSVRecords(rs []report.Report) [][]string { + total := 0 + for _, v := range rs { + total += len(v.All) + } + res := make([][]string, total+1) + + res[0] = []string{"experiment_id", "block_time", "duration_ns", "tx_hash", "connections", "rate", "size"} + offset := 1 + for _, r := range rs { + idStr := r.ID.String() + connStr := strconv.FormatInt(int64(r.Connections), 10) + rateStr := strconv.FormatInt(int64(r.Rate), 10) + sizeStr := strconv.FormatInt(int64(r.Size), 10) + for i, v := range r.All { + res[offset+i] = []string{idStr, strconv.FormatInt(v.BlockTime.UnixNano(), 10), strconv.FormatInt(int64(v.Duration), 10), fmt.Sprintf("%X", v.Hash), connStr, rateStr, sizeStr} + } + offset += len(r.All) + } + return res +} diff --git a/test/loadtime/payload/payload.go b/test/loadtime/payload/payload.go new file mode 100644 index 0000000..1198311 --- /dev/null +++ b/test/loadtime/payload/payload.go @@ -0,0 +1,101 @@ +package payload + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "fmt" + "math" + + "google.golang.org/protobuf/proto" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" +) + +const keyPrefix = "a=" +const maxPayloadSize = 4 * 1024 * 1024 + +// NewBytes generates a new payload and returns the encoded representation of +// the payload as a slice of bytes. NewBytes uses the fields on the Options +// to create the payload. +func NewBytes(p *Payload) ([]byte, error) { + p.Padding = make([]byte, 1) + if p.Time == nil { + p.Time = timestamppb.Now() + } + us, err := CalculateUnpaddedSize(p) + if err != nil { + return nil, err + } + if p.Size > maxPayloadSize { + return nil, fmt.Errorf("configured size %d is too large (>%d)", p.Size, maxPayloadSize) + } + pSize := int(p.Size) // #nosec -- The "if" above makes this cast safe + if pSize < us { + return nil, fmt.Errorf("configured size %d not large enough to fit unpadded transaction of size %d", pSize, us) + } + + // We halve the padding size because we transform the TX to hex + p.Padding = make([]byte, (pSize-us)/2) + _, err = rand.Read(p.Padding) + if err != nil { + return nil, err + } + b, err := proto.Marshal(p) + if err != nil { + return nil, err + } + h := []byte(hex.EncodeToString(b)) + + // prepend a single key so that the kv store only ever stores a single + // transaction instead of storing all tx and ballooning in size. + return append([]byte(keyPrefix), h...), nil +} + +// FromBytes extracts a paylod from the byte representation of the payload. +// FromBytes leaves the padding untouched, returning it to the caller to handle +// or discard per their preference. +func FromBytes(b []byte) (*Payload, error) { + trH := bytes.TrimPrefix(b, []byte(keyPrefix)) + if bytes.Equal(b, trH) { + return nil, fmt.Errorf("payload bytes missing key prefix '%s'", keyPrefix) + } + trB, err := hex.DecodeString(string(trH)) + if err != nil { + return nil, err + } + + p := &Payload{} + err = proto.Unmarshal(trB, p) + if err != nil { + return nil, err + } + return p, nil +} + +// MaxUnpaddedSize returns the maximum size that a payload may be if no padding +// is included. +func MaxUnpaddedSize() (int, error) { + p := &Payload{ + Time: timestamppb.Now(), + Connections: math.MaxUint64, + Rate: math.MaxUint64, + Size: math.MaxUint64, + Padding: make([]byte, 1), + } + return CalculateUnpaddedSize(p) +} + +// CalculateUnpaddedSize calculates the size of the passed in payload for the +// purpose of determining how much padding to add to add to reach the target size. +// CalculateUnpaddedSize returns an error if the payload Padding field is longer than 1. +func CalculateUnpaddedSize(p *Payload) (int, error) { + if len(p.Padding) != 1 { + return 0, fmt.Errorf("expected length of padding to be 1, received %d", len(p.Padding)) + } + b, err := proto.Marshal(p) + if err != nil { + return 0, err + } + h := []byte(hex.EncodeToString(b)) + return len(h) + len(keyPrefix), nil +} diff --git a/test/loadtime/payload/payload.pb.go b/test/loadtime/payload/payload.pb.go new file mode 100644 index 0000000..a45d1ae --- /dev/null +++ b/test/loadtime/payload/payload.pb.go @@ -0,0 +1,202 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.20.1 +// source: payload/payload.proto + +package payload + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Payload is the structure of the loadtime transaction. Proto has a compact +// encoded representation, making it ideal for the loadtime usecase which aims to +// keep the generated transactions small. +type Payload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Connections uint64 `protobuf:"varint,1,opt,name=connections,proto3" json:"connections,omitempty"` + Rate uint64 `protobuf:"varint,2,opt,name=rate,proto3" json:"rate,omitempty"` + Size uint64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"` + Time *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=time,proto3" json:"time,omitempty"` + Id []byte `protobuf:"bytes,5,opt,name=id,proto3" json:"id,omitempty"` + Padding []byte `protobuf:"bytes,6,opt,name=padding,proto3" json:"padding,omitempty"` +} + +func (x *Payload) Reset() { + *x = Payload{} + if protoimpl.UnsafeEnabled { + mi := &file_payload_payload_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Payload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Payload) ProtoMessage() {} + +func (x *Payload) ProtoReflect() protoreflect.Message { + mi := &file_payload_payload_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Payload.ProtoReflect.Descriptor instead. +func (*Payload) Descriptor() ([]byte, []int) { + return file_payload_payload_proto_rawDescGZIP(), []int{0} +} + +func (x *Payload) GetConnections() uint64 { + if x != nil { + return x.Connections + } + return 0 +} + +func (x *Payload) GetRate() uint64 { + if x != nil { + return x.Rate + } + return 0 +} + +func (x *Payload) GetSize() uint64 { + if x != nil { + return x.Size + } + return 0 +} + +func (x *Payload) GetTime() *timestamppb.Timestamp { + if x != nil { + return x.Time + } + return nil +} + +func (x *Payload) GetId() []byte { + if x != nil { + return x.Id + } + return nil +} + +func (x *Payload) GetPadding() []byte { + if x != nil { + return x.Padding + } + return nil +} + +var File_payload_payload_proto protoreflect.FileDescriptor + +var file_payload_payload_proto_rawDesc = []byte{ + 0x0a, 0x15, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, + 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x10, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x69, 0x6d, + 0x65, 0x2e, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xad, 0x01, 0x0a, 0x07, 0x50, + 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x63, 0x6f, 0x6e, + 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x61, 0x74, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x04, 0x72, 0x61, 0x74, 0x65, 0x12, 0x12, 0x0a, 0x04, + 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x04, 0x73, 0x69, 0x7a, 0x65, + 0x12, 0x2e, 0x0a, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x04, 0x74, 0x69, 0x6d, 0x65, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x07, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x42, 0x38, 0x5a, 0x36, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x6d, + 0x69, 0x6e, 0x74, 0x2f, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x74, 0x2f, 0x74, + 0x65, 0x73, 0x74, 0x2f, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x69, 0x6d, 0x65, 0x2f, 0x70, 0x61, 0x79, + 0x6c, 0x6f, 0x61, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_payload_payload_proto_rawDescOnce sync.Once + file_payload_payload_proto_rawDescData = file_payload_payload_proto_rawDesc +) + +func file_payload_payload_proto_rawDescGZIP() []byte { + file_payload_payload_proto_rawDescOnce.Do(func() { + file_payload_payload_proto_rawDescData = protoimpl.X.CompressGZIP(file_payload_payload_proto_rawDescData) + }) + return file_payload_payload_proto_rawDescData +} + +var file_payload_payload_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_payload_payload_proto_goTypes = []interface{}{ + (*Payload)(nil), // 0: loadtime.payload.Payload + (*timestamppb.Timestamp)(nil), // 1: google.protobuf.Timestamp +} +var file_payload_payload_proto_depIdxs = []int32{ + 1, // 0: loadtime.payload.Payload.time:type_name -> google.protobuf.Timestamp + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_payload_payload_proto_init() } +func file_payload_payload_proto_init() { + if File_payload_payload_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_payload_payload_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Payload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_payload_payload_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_payload_payload_proto_goTypes, + DependencyIndexes: file_payload_payload_proto_depIdxs, + MessageInfos: file_payload_payload_proto_msgTypes, + }.Build() + File_payload_payload_proto = out.File + file_payload_payload_proto_rawDesc = nil + file_payload_payload_proto_goTypes = nil + file_payload_payload_proto_depIdxs = nil +} diff --git a/test/loadtime/payload/payload.proto b/test/loadtime/payload/payload.proto new file mode 100644 index 0000000..c223486 --- /dev/null +++ b/test/loadtime/payload/payload.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; +package loadtime.payload; + +option go_package = "github.com/cometbft/cometbft/test/loadtime/payload"; + +import "google/protobuf/timestamp.proto"; + +// Payload is the structure of the loadtime transaction. Proto has a compact +// encoded representation, making it ideal for the loadtime usecase which aims to +// keep the generated transactions small. +message Payload { + uint64 connections = 1; + uint64 rate = 2; + uint64 size = 3; + google.protobuf.Timestamp time = 4; + bytes id = 5; + bytes padding = 6; +} diff --git a/test/loadtime/payload/payload_test.go b/test/loadtime/payload/payload_test.go new file mode 100644 index 0000000..c889192 --- /dev/null +++ b/test/loadtime/payload/payload_test.go @@ -0,0 +1,58 @@ +package payload_test + +import ( + "bytes" + "testing" + + "github.com/google/uuid" + + "github.com/cometbft/cometbft/test/loadtime/payload" +) + +const payloadSizeTarget = 1024 // 1kb + +func TestSize(t *testing.T) { + s, err := payload.MaxUnpaddedSize() + if err != nil { + t.Fatalf("calculating max unpadded size %s", err) + } + if s > payloadSizeTarget { + t.Fatalf("unpadded payload size %d exceeds target %d", s, payloadSizeTarget) + } +} + +func TestRoundTrip(t *testing.T) { + const ( + testConns = 512 + testRate = 4 + ) + testID := [16]byte(uuid.New()) + b, err := payload.NewBytes(&payload.Payload{ + Size: payloadSizeTarget, + Connections: testConns, + Rate: testRate, + Id: testID[:], + }) + if err != nil { + t.Fatalf("generating payload %s", err) + } + if len(b) < payloadSizeTarget { + t.Fatalf("payload size in bytes %d less than expected %d", len(b), payloadSizeTarget) + } + p, err := payload.FromBytes(b) + if err != nil { + t.Fatalf("reading payload %s", err) + } + if p.Size != payloadSizeTarget { + t.Fatalf("payload size value %d does not match expected %d", p.Size, payloadSizeTarget) + } + if p.Connections != testConns { + t.Fatalf("payload connections value %d does not match expected %d", p.Connections, testConns) + } + if p.Rate != testRate { + t.Fatalf("payload rate value %d does not match expected %d", p.Rate, testRate) + } + if !bytes.Equal(p.Id, testID[:]) { + t.Fatalf("payload ID value %d does not match expected %d", p.Id, testID) + } +} diff --git a/test/loadtime/report/report.go b/test/loadtime/report/report.go new file mode 100644 index 0000000..ddf5db1 --- /dev/null +++ b/test/loadtime/report/report.go @@ -0,0 +1,229 @@ +package report + +import ( + "math" + "sort" + "sync" + "time" + + "github.com/gofrs/uuid" + "gonum.org/v1/gonum/stat" + + "github.com/cometbft/cometbft/test/loadtime/payload" + "github.com/cometbft/cometbft/types" +) + +// BlockStore defines the set of methods needed by the report generator from +// CometBFT's store.Blockstore type. Using an interface allows for tests to +// more easily simulate the required behavior without having to use the more +// complex real API. +type BlockStore interface { + Height() int64 + Base() int64 + LoadBlock(int64) *types.Block +} + +// DataPoint contains the set of data collected for each transaction. +type DataPoint struct { + Duration time.Duration + BlockTime time.Time + Hash []byte +} + +// Report contains the data calculated from reading the timestamped transactions +// of each block found in the blockstore. +type Report struct { + ID uuid.UUID + Rate, Connections, Size uint64 + Max, Min, Avg, StdDev time.Duration + + // NegativeCount is the number of negative durations encountered while + // reading the transaction data. A negative duration means that + // a transaction timestamp was greater than the timestamp of the block it + // was included in and likely indicates an issue with the experimental + // setup. + NegativeCount int + + // All contains all data points gathered from all valid transactions. + // The order of the contents of All is not guaranteed to be match the order of transactions + // in the chain. + All []DataPoint + + // used for calculating average during report creation. + sum int64 +} + +type Reports struct { + s map[uuid.UUID]Report + l []Report + + // errorCount is the number of parsing errors encountered while reading the + // transaction data. Parsing errors may occur if a transaction not generated + // by the payload package is submitted to the chain. + errorCount int +} + +func (rs *Reports) List() []Report { + return rs.l +} + +func (rs *Reports) ErrorCount() int { + return rs.errorCount +} + +func (rs *Reports) addDataPoint(id uuid.UUID, l time.Duration, bt time.Time, hash []byte, conns, rate, size uint64) { + r, ok := rs.s[id] + if !ok { + r = Report{ + Max: 0, + Min: math.MaxInt64, + ID: id, + Connections: conns, + Rate: rate, + Size: size, + } + rs.s[id] = r + } + r.All = append(r.All, DataPoint{Duration: l, BlockTime: bt, Hash: hash}) + if l > r.Max { + r.Max = l + } + if l < r.Min { + r.Min = l + } + if int64(l) < 0 { + r.NegativeCount++ + } + // Using an int64 here makes an assumption about the scale and quantity of the data we are processing. + // If all latencies were 2 seconds, we would need around 4 billion records to overflow this. + // We are therefore assuming that the data does not exceed these bounds. + r.sum += int64(l) + rs.s[id] = r +} + +func (rs *Reports) calculateAll() { + rs.l = make([]Report, 0, len(rs.s)) + for _, r := range rs.s { + if len(r.All) == 0 { + r.Min = 0 + rs.l = append(rs.l, r) + continue + } + r.Avg = time.Duration(r.sum / int64(len(r.All))) + r.StdDev = time.Duration(int64(stat.StdDev(toFloat(r.All), nil))) + rs.l = append(rs.l, r) + } + sort.Slice(rs.l, func(i, j int) bool { + if rs.l[i].Connections == rs.l[j].Connections { + return rs.l[i].Rate < rs.l[j].Rate + } + return rs.l[i].Connections < rs.l[j].Connections + }) + +} + +func (rs *Reports) addError() { + rs.errorCount++ +} + +// GenerateFromBlockStore creates a Report using the data in the provided +// BlockStore. +func GenerateFromBlockStore(s BlockStore) (*Reports, error) { + type payloadData struct { + id uuid.UUID + l time.Duration + bt time.Time + hash []byte + connections, rate, size uint64 + err error + } + type txData struct { + tx types.Tx + bt time.Time + } + reports := &Reports{ + s: make(map[uuid.UUID]Report), + } + + // Deserializing to proto can be slow but does not depend on other data + // and can therefore be done in parallel. + // Deserializing in parallel does mean that the resulting data is + // not guaranteed to be delivered in the same order it was given to the + // worker pool. + const poolSize = 16 + + txc := make(chan txData) + pdc := make(chan payloadData, poolSize) + + wg := &sync.WaitGroup{} + wg.Add(poolSize) + for i := 0; i < poolSize; i++ { + go func() { + defer wg.Done() + for b := range txc { + p, err := payload.FromBytes(b.tx) + if err != nil { + pdc <- payloadData{err: err} + continue + } + + l := b.bt.Sub(p.Time.AsTime()) + idb := (*[16]byte)(p.Id) + pdc <- payloadData{ + l: l, + bt: b.bt, + hash: b.tx.Hash(), + id: uuid.UUID(*idb), + connections: p.Connections, + rate: p.Rate, + size: p.Size, + } + } + }() + } + go func() { + wg.Wait() + close(pdc) + }() + + go func() { + base, height := s.Base(), s.Height() + prev := s.LoadBlock(base) + for i := base + 1; i < height; i++ { + // Data from two adjacent block are used here simultaneously, + // blocks of height H and H+1. The transactions of the block of + // height H are used with the timestamp from the block of height + // H+1. This is done because the timestamp from H+1 is calculated + // by using the precommits submitted at height H. The timestamp in + // block H+1 represents the time at which block H was committed. + // + // In the (very unlikely) event that the very last block of the + // chain contains payload transactions, those transactions will not + // be used in the latency calculations because the last block whose + // transactions are used is the block one before the last. + cur := s.LoadBlock(i) + for _, tx := range prev.Txs { + txc <- txData{tx: tx, bt: cur.Time} + } + prev = cur + } + close(txc) + }() + for pd := range pdc { + if pd.err != nil { + reports.addError() + continue + } + reports.addDataPoint(pd.id, pd.l, pd.bt, pd.hash, pd.connections, pd.rate, pd.size) + } + reports.calculateAll() + return reports, nil +} + +func toFloat(in []DataPoint) []float64 { + r := make([]float64, len(in)) + for i, v := range in { + r[i] = float64(int64(v.Duration)) + } + return r +} diff --git a/test/loadtime/report/report_test.go b/test/loadtime/report/report_test.go new file mode 100644 index 0000000..c37f1dd --- /dev/null +++ b/test/loadtime/report/report_test.go @@ -0,0 +1,125 @@ +package report_test + +import ( + "testing" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/cometbft/cometbft/test/loadtime/payload" + "github.com/cometbft/cometbft/test/loadtime/report" + "github.com/cometbft/cometbft/types" +) + +type mockBlockStore struct { + base int64 + blocks []*types.Block +} + +func (m *mockBlockStore) Height() int64 { + return m.base + int64(len(m.blocks)) +} + +func (m *mockBlockStore) Base() int64 { + return m.base +} + +func (m *mockBlockStore) LoadBlock(i int64) *types.Block { + return m.blocks[i-m.base] +} + +func TestGenerateReport(t *testing.T) { + t1 := time.Now() + u := [16]byte(uuid.New()) + b1, err := payload.NewBytes(&payload.Payload{ + Id: u[:], + Time: timestamppb.New(t1.Add(-10 * time.Second)), + Size: 1024, + }) + if err != nil { + t.Fatalf("generating payload %s", err) + } + b2, err := payload.NewBytes(&payload.Payload{ + Id: u[:], + Time: timestamppb.New(t1.Add(-4 * time.Second)), + Size: 1024, + }) + if err != nil { + t.Fatalf("generating payload %s", err) + } + b3, err := payload.NewBytes(&payload.Payload{ + Id: u[:], + Time: timestamppb.New(t1.Add(2 * time.Second)), + Size: 1024, + }) + t2 := t1.Add(time.Second) + if err != nil { + t.Fatalf("generating payload %s", err) + } + s := &mockBlockStore{ + blocks: []*types.Block{ + { + Data: types.Data{ + Txs: []types.Tx{b1, b2}, + }, + }, + { + // The timestamp from block H+1 is used to calculate the + // latency for the transactions in block H. + Header: types.Header{ + Time: t1, + }, + Data: types.Data{ + Txs: []types.Tx{[]byte("error")}, + }, + }, + { + Data: types.Data{ + Txs: []types.Tx{b3, b3}, + }, + }, + { + Header: types.Header{ + Time: t2, + }, + Data: types.Data{ + Txs: []types.Tx{}, + }, + }, + }, + } + rs, err := report.GenerateFromBlockStore(s) + if err != nil { + t.Fatalf("generating report %s", err) + } + if rs.ErrorCount() != 1 { + t.Fatalf("ErrorCount did not match expected. Expected %d but contained %d", 1, rs.ErrorCount()) + } + rl := rs.List() + if len(rl) != 1 { + t.Fatalf("number of reports did not match expected. Expected %d but contained %d", 1, len(rl)) + } + r := rl[0] + if len(r.All) != 4 { + t.Fatalf("report contained different number of data points from expected. Expected %d but contained %d", 4, len(r.All)) + } + if r.NegativeCount != 2 { + t.Fatalf("NegativeCount did not match expected. Expected %d but contained %d", 2, r.NegativeCount) + } + if r.Avg != 3*time.Second { + t.Fatalf("Avg did not match expected. Expected %s but contained %s", 3*time.Second, r.Avg) + } + if r.Min != -time.Second { + t.Fatalf("Min did not match expected. Expected %s but contained %s", time.Second, r.Min) + } + if r.Max != 10*time.Second { + t.Fatalf("Max did not match expected. Expected %s but contained %s", 10*time.Second, r.Max) + } + // Verified using online standard deviation calculator: + // https://www.calculator.net/standard-deviation-calculator.html?numberinputs=10%2C+4%2C+-1%2C+-1&ctype=s&x=45&y=12 + expectedStdDev := 5228129047 * time.Nanosecond + if r.StdDev != expectedStdDev { + t.Fatalf("StdDev did not match expected. Expected %s but contained %s", expectedStdDev, r.StdDev) + } +} diff --git a/test/test_cover.sh b/test/test_cover.sh new file mode 100644 index 0000000..0c01c88 --- /dev/null +++ b/test/test_cover.sh @@ -0,0 +1,14 @@ +#! /bin/bash + +PKGS=$(go list github.com/cometbft/cometbft/...) + +set -e + +echo "mode: atomic" > coverage.txt +for pkg in ${PKGS[@]}; do + go test -timeout 5m -race -coverprofile=profile.out -covermode=atomic "$pkg" + if [ -f profile.out ]; then + tail -n +2 profile.out >> coverage.txt; + rm profile.out + fi +done diff --git a/tests.mk b/tests.mk new file mode 100644 index 0000000..dc3f552 --- /dev/null +++ b/tests.mk @@ -0,0 +1,75 @@ +#!/usr/bin/make -f + +######################################## +### Testing + +BINDIR ?= $(GOPATH)/bin + +## required to be run first by most tests +build_docker_test_image: + docker build -t tester -f ./test/docker/Dockerfile . +.PHONY: build_docker_test_image + +### coverage, app, persistence, and libs tests +test_cover: + # run the go unit tests with coverage + bash test/test_cover.sh +.PHONY: test_cover + +test_apps: + # run the app tests using bash + # requires `abci-cli` and `cometbft` binaries installed + bash test/app/test.sh +.PHONY: test_apps + +test_abci_apps: + bash abci/tests/test_app/test.sh +.PHONY: test_abci_apps + +test_abci_cli: + # test the cli against the examples in the tutorial at: + # ./docs/abci-cli.md + # if test fails, update the docs ^ + @ bash abci/tests/test_cli/test.sh +.PHONY: test_abci_cli + +test_integrations: + make build_docker_test_image + make tools + make install + make install_abci + make test_cover + make test_apps + make test_abci_apps + make test_abci_cli + make test_libs +.PHONY: test_integrations + +test_release: + @go test -tags release $(PACKAGES) +.PHONY: test_release + +test100: + @for i in {1..100}; do make test; done +.PHONY: test100 + +vagrant_test: + vagrant up + vagrant ssh -c 'make test_integrations' +.PHONY: vagrant_test + +### go tests +test: + @echo "--> Running go test" + @go test -p 1 $(PACKAGES) +.PHONY: test + +test_race: + @echo "--> Running go test --race" + @go test -p 1 -v -race $(PACKAGES) +.PHONY: test_race + +test_deadlock: + @echo "--> Running go test --deadlock" + @go test -p 1 -v $(PACKAGES) -tags deadlock +.PHONY: test_race diff --git a/types/block.go b/types/block.go new file mode 100644 index 0000000..02ef879 --- /dev/null +++ b/types/block.go @@ -0,0 +1,1555 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + "strings" + "time" + + "github.com/cosmos/gogoproto/proto" + gogotypes "github.com/cosmos/gogoproto/types" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/bits" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtsync "github.com/cometbft/cometbft/libs/sync" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/version" +) + +const ( + // MaxHeaderBytes is a maximum header size. + // NOTE: Because app hash can be of arbitrary size, the header is therefore not + // capped in size and thus this number should be seen as a soft max + MaxHeaderBytes int64 = 626 + + // MaxOverheadForBlock - maximum overhead to encode a block (up to + // MaxBlockSizeBytes in size) not including it's parts except Data. + // This means it also excludes the overhead for individual transactions. + // + // Uvarint length of MaxBlockSizeBytes: 4 bytes + // 2 fields (2 embedded): 2 bytes + // Uvarint length of Data.Txs: 4 bytes + // Data.Txs field: 1 byte + MaxOverheadForBlock int64 = 11 +) + +// Block defines the atomic unit of a CometBFT blockchain. +type Block struct { + mtx cmtsync.Mutex + + verifiedHash cmtbytes.HexBytes // Verified block hash (not included in the struct hash) + Header `json:"header"` + Data `json:"data"` + Evidence EvidenceData `json:"evidence"` + LastCommit *Commit `json:"last_commit"` +} + +// ValidateBasic performs basic validation that doesn't involve state data. +// It checks the internal consistency of the block. +// Further validation is done using state#ValidateBlock. +func (b *Block) ValidateBasic() error { + if b == nil { + return errors.New("nil block") + } + + b.mtx.Lock() + defer b.mtx.Unlock() + + if err := b.Header.ValidateBasic(); err != nil { + return fmt.Errorf("invalid header: %w", err) + } + + // Validate the last commit and its hash. + if b.LastCommit == nil { + return errors.New("nil LastCommit") + } + if err := b.LastCommit.ValidateBasic(); err != nil { + return fmt.Errorf("wrong LastCommit: %v", err) + } + + if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) { + return fmt.Errorf("wrong Header.LastCommitHash. Expected %v, got %v", + b.LastCommit.Hash(), + b.LastCommitHash, + ) + } + + // NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine. + if !bytes.Equal(b.DataHash, b.Data.Hash()) { + return fmt.Errorf( + "wrong Header.DataHash. Expected %v, got %v", + b.Data.Hash(), + b.DataHash, + ) + } + + // NOTE: b.Evidence.Evidence may be nil, but we're just looping. + for i, ev := range b.Evidence.Evidence { + if err := ev.ValidateBasic(); err != nil { + return fmt.Errorf("invalid evidence (#%d): %v", i, err) + } + } + + if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) { + return fmt.Errorf("wrong Header.EvidenceHash. Expected %v, got %v", + b.EvidenceHash, + b.Evidence.Hash(), + ) + } + + return nil +} + +// fillHeader fills in any remaining header fields that are a function of the block data +func (b *Block) fillHeader() { + if b.LastCommitHash == nil { + b.LastCommitHash = b.LastCommit.Hash() + } + if b.DataHash == nil { + b.DataHash = b.Data.Hash() + } + if b.EvidenceHash == nil { + b.EvidenceHash = b.Evidence.Hash() + } +} + +// Hash computes and returns the block hash. +// If the block is incomplete, block hash is nil for safety. +func (b *Block) Hash() cmtbytes.HexBytes { + if b == nil { + return nil + } + b.mtx.Lock() + defer b.mtx.Unlock() + + if b.LastCommit == nil { + return nil + } + if b.verifiedHash != nil { + return b.verifiedHash + } + b.fillHeader() + hash := b.Header.Hash() + b.verifiedHash = hash + return hash +} + +// MakePartSet returns a PartSet containing parts of a serialized block. +// This is the form in which the block is gossipped to peers. +// CONTRACT: partSize is greater than zero. +func (b *Block) MakePartSet(partSize uint32) (*PartSet, error) { + if b == nil { + return nil, errors.New("nil block") + } + b.mtx.Lock() + defer b.mtx.Unlock() + + pbb, err := b.ToProto() + if err != nil { + return nil, err + } + bz, err := proto.Marshal(pbb) + if err != nil { + return nil, err + } + return NewPartSetFromData(bz, partSize), nil +} + +// HashesTo is a convenience function that checks if a block hashes to the given argument. +// Returns false if the block is nil or the hash is empty. +func (b *Block) HashesTo(hash []byte) bool { + if len(hash) == 0 { + return false + } + if b == nil { + return false + } + return bytes.Equal(b.Hash(), hash) +} + +// Size returns size of the block in bytes. +func (b *Block) Size() int { + pbb, err := b.ToProto() + if err != nil { + return 0 + } + + return pbb.Size() +} + +// String returns a string representation of the block +// +// See StringIndented. +func (b *Block) String() string { + return b.StringIndented("") +} + +// StringIndented returns an indented String. +// +// Header +// Data +// Evidence +// LastCommit +// Hash +func (b *Block) StringIndented(indent string) string { + if b == nil { + return "nil-Block" + } + return fmt.Sprintf(`Block{ +%s %v +%s %v +%s %v +%s %v +%s}#%v`, + indent, b.Header.StringIndented(indent+" "), + indent, b.Data.StringIndented(indent+" "), + indent, b.Evidence.StringIndented(indent+" "), + indent, b.LastCommit.StringIndented(indent+" "), + indent, b.Hash()) +} + +// StringShort returns a shortened string representation of the block. +func (b *Block) StringShort() string { + if b == nil { + return "nil-Block" + } + return fmt.Sprintf("Block#%X", b.Hash()) +} + +// ToProto converts Block to protobuf +func (b *Block) ToProto() (*cmtproto.Block, error) { + if b == nil { + return nil, errors.New("nil Block") + } + + pb := new(cmtproto.Block) + + pb.Header = *b.Header.ToProto() + pb.LastCommit = b.LastCommit.ToProto() + pb.Data = b.Data.ToProto() + + protoEvidence, err := b.Evidence.ToProto() + if err != nil { + return nil, err + } + pb.Evidence = *protoEvidence + + return pb, nil +} + +// FromProto sets a protobuf Block to the given pointer. +// It returns an error if the block is invalid. +func BlockFromProto(bp *cmtproto.Block) (*Block, error) { + if bp == nil { + return nil, errors.New("nil block") + } + + b := new(Block) + h, err := HeaderFromProto(&bp.Header) + if err != nil { + return nil, err + } + b.Header = h + data, err := DataFromProto(&bp.Data) + if err != nil { + return nil, err + } + b.Data = data + if err := b.Evidence.FromProto(&bp.Evidence); err != nil { + return nil, err + } + + if bp.LastCommit != nil { + lc, err := CommitFromProto(bp.LastCommit) + if err != nil { + return nil, err + } + b.LastCommit = lc + } + + return b, b.ValidateBasic() +} + +//----------------------------------------------------------------------------- + +// MaxDataBytes returns the maximum size of block's data. +// +// XXX: Panics on negative result. +func MaxDataBytes(maxBytes, evidenceBytes int64, valsCount int) int64 { + maxDataBytes := maxBytes - + MaxOverheadForBlock - + MaxHeaderBytes - + MaxCommitBytes(valsCount) - + evidenceBytes + + if maxDataBytes < 0 { + panic(fmt.Sprintf( + "Negative MaxDataBytes. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d", + maxBytes, + -(maxDataBytes - maxBytes), + )) + } + + return maxDataBytes +} + +// MaxDataBytesNoEvidence returns the maximum size of block's data when +// evidence count is unknown (will be assumed to be 0). +// +// XXX: Panics on negative result. +func MaxDataBytesNoEvidence(maxBytes int64, valsCount int) int64 { + maxDataBytes := maxBytes - + MaxOverheadForBlock - + MaxHeaderBytes - + MaxCommitBytes(valsCount) + + if maxDataBytes < 0 { + panic(fmt.Sprintf( + "Negative MaxDataBytesNoEvidence. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d", + maxBytes, + -(maxDataBytes - maxBytes), + )) + } + + return maxDataBytes +} + +//----------------------------------------------------------------------------- + +// Header defines the structure of a CometBFT block header. +// NOTE: changes to the Header should be duplicated in: +// - header.Hash() +// - abci.Header +// - https://github.com/cometbft/cometbft/blob/v0.38.x/spec/blockchain/blockchain.md +type Header struct { + // basic block info + Version cmtversion.Consensus `json:"version"` + ChainID string `json:"chain_id"` + Height int64 `json:"height"` + Time time.Time `json:"time"` + + // prev block info + LastBlockID BlockID `json:"last_block_id"` + + // hashes of block data + LastCommitHash cmtbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block + DataHash cmtbytes.HexBytes `json:"data_hash"` // transactions + + // hashes from the app output from the prev block + ValidatorsHash cmtbytes.HexBytes `json:"validators_hash"` // validators for the current block + NextValidatorsHash cmtbytes.HexBytes `json:"next_validators_hash"` // validators for the next block + ConsensusHash cmtbytes.HexBytes `json:"consensus_hash"` // consensus params for current block + AppHash cmtbytes.HexBytes `json:"app_hash"` // state after txs from the previous block + // root hash of all results from the txs from the previous block + // see `deterministicExecTxResult` to understand which parts of a tx is hashed into here + LastResultsHash cmtbytes.HexBytes `json:"last_results_hash"` + + // consensus info + EvidenceHash cmtbytes.HexBytes `json:"evidence_hash"` // evidence included in the block + ProposerAddress Address `json:"proposer_address"` // original proposer of the block +} + +// Populate the Header with state-derived data. +// Call this after MakeBlock to complete the Header. +func (h *Header) Populate( + version cmtversion.Consensus, chainID string, + timestamp time.Time, lastBlockID BlockID, + valHash, nextValHash []byte, + consensusHash, appHash, lastResultsHash []byte, + proposerAddress Address, +) { + h.Version = version + h.ChainID = chainID + h.Time = timestamp + h.LastBlockID = lastBlockID + h.ValidatorsHash = valHash + h.NextValidatorsHash = nextValHash + h.ConsensusHash = consensusHash + h.AppHash = appHash + h.LastResultsHash = lastResultsHash + h.ProposerAddress = proposerAddress +} + +// ValidateBasic performs stateless validation on a Header returning an error +// if any validation fails. +// +// NOTE: Timestamp validation is subtle and handled elsewhere. +func (h Header) ValidateBasic() error { + if h.Version.Block != version.BlockProtocol { + return fmt.Errorf("block protocol is incorrect: got: %d, want: %d ", h.Version.Block, version.BlockProtocol) + } + if len(h.ChainID) > MaxChainIDLen { + return fmt.Errorf("chainID is too long; got: %d, max: %d", len(h.ChainID), MaxChainIDLen) + } + + if h.Height < 0 { + return errors.New("negative Height") + } else if h.Height == 0 { + return errors.New("zero Height") + } + + if err := h.LastBlockID.ValidateBasic(); err != nil { + return fmt.Errorf("wrong LastBlockID: %w", err) + } + + if err := ValidateHash(h.LastCommitHash); err != nil { + return fmt.Errorf("wrong LastCommitHash: %v", err) + } + + if err := ValidateHash(h.DataHash); err != nil { + return fmt.Errorf("wrong DataHash: %v", err) + } + + if err := ValidateHash(h.EvidenceHash); err != nil { + return fmt.Errorf("wrong EvidenceHash: %v", err) + } + + if len(h.ProposerAddress) != crypto.AddressSize { + return fmt.Errorf( + "invalid ProposerAddress length; got: %d, expected: %d", + len(h.ProposerAddress), crypto.AddressSize, + ) + } + + // Basic validation of hashes related to application data. + // Will validate fully against state in state#ValidateBlock. + if err := ValidateHash(h.ValidatorsHash); err != nil { + return fmt.Errorf("wrong ValidatorsHash: %v", err) + } + if err := ValidateHash(h.NextValidatorsHash); err != nil { + return fmt.Errorf("wrong NextValidatorsHash: %v", err) + } + if err := ValidateHash(h.ConsensusHash); err != nil { + return fmt.Errorf("wrong ConsensusHash: %v", err) + } + // NOTE: AppHash is arbitrary length + if err := ValidateHash(h.LastResultsHash); err != nil { + return fmt.Errorf("wrong LastResultsHash: %v", err) + } + + return nil +} + +// Hash returns the hash of the header. +// It computes a Merkle tree from the header fields +// ordered as they appear in the Header. +// Returns nil if ValidatorHash is missing, +// since a Header is not valid unless there is +// a ValidatorsHash (corresponding to the validator set). +func (h *Header) Hash() cmtbytes.HexBytes { + if h == nil || len(h.ValidatorsHash) == 0 { + return nil + } + hbz, err := h.Version.Marshal() + if err != nil { + return nil + } + + pbt, err := gogotypes.StdTimeMarshal(h.Time) + if err != nil { + return nil + } + + pbbi := h.LastBlockID.ToProto() + bzbi, err := pbbi.Marshal() + if err != nil { + return nil + } + return merkle.HashFromByteSlices([][]byte{ + hbz, + cdcEncode(h.ChainID), + cdcEncode(h.Height), + pbt, + bzbi, + cdcEncode(h.LastCommitHash), + cdcEncode(h.DataHash), + cdcEncode(h.ValidatorsHash), + cdcEncode(h.NextValidatorsHash), + cdcEncode(h.ConsensusHash), + cdcEncode(h.AppHash), + cdcEncode(h.LastResultsHash), + cdcEncode(h.EvidenceHash), + cdcEncode(h.ProposerAddress), + }) +} + +// StringIndented returns an indented string representation of the header. +func (h *Header) StringIndented(indent string) string { + if h == nil { + return "nil-Header" + } + return fmt.Sprintf(`Header{ +%s Version: %v +%s ChainID: %v +%s Height: %v +%s Time: %v +%s LastBlockID: %v +%s LastCommit: %v +%s Data: %v +%s Validators: %v +%s NextValidators: %v +%s App: %v +%s Consensus: %v +%s Results: %v +%s Evidence: %v +%s Proposer: %v +%s}#%v`, + indent, h.Version, + indent, h.ChainID, + indent, h.Height, + indent, h.Time, + indent, h.LastBlockID, + indent, h.LastCommitHash, + indent, h.DataHash, + indent, h.ValidatorsHash, + indent, h.NextValidatorsHash, + indent, h.AppHash, + indent, h.ConsensusHash, + indent, h.LastResultsHash, + indent, h.EvidenceHash, + indent, h.ProposerAddress, + indent, h.Hash(), + ) +} + +// ToProto converts Header to protobuf +func (h *Header) ToProto() *cmtproto.Header { + if h == nil { + return nil + } + + return &cmtproto.Header{ + Version: h.Version, + ChainID: h.ChainID, + Height: h.Height, + Time: h.Time, + LastBlockId: h.LastBlockID.ToProto(), + ValidatorsHash: h.ValidatorsHash, + NextValidatorsHash: h.NextValidatorsHash, + ConsensusHash: h.ConsensusHash, + AppHash: h.AppHash, + DataHash: h.DataHash, + EvidenceHash: h.EvidenceHash, + LastResultsHash: h.LastResultsHash, + LastCommitHash: h.LastCommitHash, + ProposerAddress: h.ProposerAddress, + } +} + +// FromProto sets a protobuf Header to the given pointer. +// It returns an error if the header is invalid. +func HeaderFromProto(ph *cmtproto.Header) (Header, error) { + if ph == nil { + return Header{}, errors.New("nil Header") + } + + h := new(Header) + + bi, err := BlockIDFromProto(&ph.LastBlockId) + if err != nil { + return Header{}, err + } + + h.Version = ph.Version + h.ChainID = ph.ChainID + h.Height = ph.Height + h.Time = ph.Time + h.Height = ph.Height + h.LastBlockID = *bi + h.ValidatorsHash = ph.ValidatorsHash + h.NextValidatorsHash = ph.NextValidatorsHash + h.ConsensusHash = ph.ConsensusHash + h.AppHash = ph.AppHash + h.DataHash = ph.DataHash + h.EvidenceHash = ph.EvidenceHash + h.LastResultsHash = ph.LastResultsHash + h.LastCommitHash = ph.LastCommitHash + h.ProposerAddress = ph.ProposerAddress + + return *h, h.ValidateBasic() +} + +//------------------------------------- + +// BlockIDFlag indicates which BlockID the signature is for. +type BlockIDFlag byte + +const ( + // BlockIDFlagAbsent - no vote was received from a validator. + BlockIDFlagAbsent BlockIDFlag = iota + 1 + // BlockIDFlagCommit - voted for the Commit.BlockID. + BlockIDFlagCommit + // BlockIDFlagNil - voted for nil. + BlockIDFlagNil +) + +const ( + // Max size of commit without any commitSigs -> 82 for BlockID, 8 for Height, 4 for Round. + MaxCommitOverheadBytes int64 = 94 + // Commit sig size is made up of 64 bytes for the signature, 20 bytes for the address, + // 1 byte for the flag and 14 bytes for the timestamp + MaxCommitSigBytes int64 = 109 +) + +// CommitSig is a part of the Vote included in a Commit. +type CommitSig struct { + BlockIDFlag BlockIDFlag `json:"block_id_flag"` + ValidatorAddress Address `json:"validator_address"` + Timestamp time.Time `json:"timestamp"` + Signature []byte `json:"signature"` +} + +func MaxCommitBytes(valCount int) int64 { + // From the repeated commit sig field + var protoEncodingOverhead int64 = 2 + return MaxCommitOverheadBytes + ((MaxCommitSigBytes + protoEncodingOverhead) * int64(valCount)) +} + +// NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other +// fields are all empty. +func NewCommitSigAbsent() CommitSig { + return CommitSig{ + BlockIDFlag: BlockIDFlagAbsent, + } +} + +// CommitSig returns a string representation of CommitSig. +// +// 1. first 6 bytes of signature +// 2. first 6 bytes of validator address +// 3. block ID flag +// 4. timestamp +func (cs CommitSig) String() string { + return fmt.Sprintf("CommitSig{%X by %X on %v @ %s}", + cmtbytes.Fingerprint(cs.Signature), + cmtbytes.Fingerprint(cs.ValidatorAddress), + cs.BlockIDFlag, + CanonicalTime(cs.Timestamp)) +} + +// BlockID returns the Commit's BlockID if CommitSig indicates signing, +// otherwise - empty BlockID. +func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID { + var blockID BlockID + switch cs.BlockIDFlag { + case BlockIDFlagAbsent: + blockID = BlockID{} + case BlockIDFlagCommit: + blockID = commitBlockID + case BlockIDFlagNil: + blockID = BlockID{} + default: + panic(fmt.Sprintf("Unknown BlockIDFlag: %v", cs.BlockIDFlag)) + } + return blockID +} + +// ValidateBasic performs basic validation. +func (cs CommitSig) ValidateBasic() error { + switch cs.BlockIDFlag { + case BlockIDFlagAbsent: + case BlockIDFlagCommit: + case BlockIDFlagNil: + default: + return fmt.Errorf("unknown BlockIDFlag: %v", cs.BlockIDFlag) + } + + switch cs.BlockIDFlag { + case BlockIDFlagAbsent: + if len(cs.ValidatorAddress) != 0 { + return errors.New("validator address is present") + } + if !cs.Timestamp.IsZero() { + return errors.New("time is present") + } + if len(cs.Signature) != 0 { + return errors.New("signature is present") + } + default: + if len(cs.ValidatorAddress) != crypto.AddressSize { + return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes", + crypto.AddressSize, + len(cs.ValidatorAddress), + ) + } + // NOTE: Timestamp validation is subtle and handled elsewhere. + if len(cs.Signature) == 0 { + return errors.New("signature is missing") + } + if len(cs.Signature) > MaxSignatureSize { + return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize) + } + } + + return nil +} + +// ToProto converts CommitSig to protobuf +func (cs *CommitSig) ToProto() *cmtproto.CommitSig { + if cs == nil { + return nil + } + + return &cmtproto.CommitSig{ + BlockIdFlag: cmtproto.BlockIDFlag(cs.BlockIDFlag), + ValidatorAddress: cs.ValidatorAddress, + Timestamp: cs.Timestamp, + Signature: cs.Signature, + } +} + +// FromProto sets a protobuf CommitSig to the given pointer. +// It returns an error if the CommitSig is invalid. +func (cs *CommitSig) FromProto(csp cmtproto.CommitSig) error { + cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag) + cs.ValidatorAddress = csp.ValidatorAddress + cs.Timestamp = csp.Timestamp + cs.Signature = csp.Signature + + return cs.ValidateBasic() +} + +//------------------------------------- + +// ExtendedCommitSig contains a commit signature along with its corresponding +// vote extension and vote extension signature. +type ExtendedCommitSig struct { + CommitSig // Commit signature + Extension []byte // Vote extension + ExtensionSignature []byte // Vote extension signature +} + +// NewExtendedCommitSigAbsent returns new ExtendedCommitSig with +// BlockIDFlagAbsent. Other fields are all empty. +func NewExtendedCommitSigAbsent() ExtendedCommitSig { + return ExtendedCommitSig{CommitSig: NewCommitSigAbsent()} +} + +// String returns a string representation of an ExtendedCommitSig. +// +// 1. commit sig +// 2. first 6 bytes of vote extension +// 3. first 6 bytes of vote extension signature +func (ecs ExtendedCommitSig) String() string { + return fmt.Sprintf("ExtendedCommitSig{%s with %X %X}", + ecs.CommitSig, + cmtbytes.Fingerprint(ecs.Extension), + cmtbytes.Fingerprint(ecs.ExtensionSignature), + ) +} + +// ValidateBasic checks whether the structure is well-formed. +func (ecs ExtendedCommitSig) ValidateBasic() error { + if err := ecs.CommitSig.ValidateBasic(); err != nil { + return err + } + + if ecs.BlockIDFlag == BlockIDFlagCommit { + if len(ecs.Extension) > MaxVoteExtensionSize { + return fmt.Errorf("vote extension is too big (max: %d)", MaxVoteExtensionSize) + } + if len(ecs.ExtensionSignature) > MaxSignatureSize { + return fmt.Errorf("vote extension signature is too big (max: %d)", MaxSignatureSize) + } + return nil + } + + if len(ecs.ExtensionSignature) == 0 && len(ecs.Extension) != 0 { + return errors.New("vote extension signature absent on vote with extension") + } + return nil +} + +// EnsureExtensions validates that a vote extensions signature is present for +// this ExtendedCommitSig. +func (ecs ExtendedCommitSig) EnsureExtension(extEnabled bool) error { + if extEnabled { + if ecs.BlockIDFlag == BlockIDFlagCommit && len(ecs.ExtensionSignature) == 0 { + return fmt.Errorf("vote extension signature is missing; validator addr %s, timestamp %v", + ecs.ValidatorAddress.String(), + ecs.Timestamp, + ) + } + if ecs.BlockIDFlag != BlockIDFlagCommit && len(ecs.Extension) != 0 { + return fmt.Errorf("non-commit vote extension present; validator addr %s, timestamp %v", + ecs.ValidatorAddress.String(), + ecs.Timestamp, + ) + } + if ecs.BlockIDFlag != BlockIDFlagCommit && len(ecs.ExtensionSignature) != 0 { + return fmt.Errorf("non-commit vote extension signature present; validator addr %s, timestamp %v", + ecs.ValidatorAddress.String(), + ecs.Timestamp, + ) + } + } else { + if len(ecs.Extension) != 0 { + return fmt.Errorf("vote extension present but extensions disabled; validator addr %s, timestamp %v", + ecs.ValidatorAddress.String(), + ecs.Timestamp, + ) + } + if len(ecs.ExtensionSignature) != 0 { + return fmt.Errorf("vote extension signature present but extensions disabled; validator addr %s, timestamp %v", + ecs.ValidatorAddress.String(), + ecs.Timestamp, + ) + } + } + return nil +} + +// ToProto converts the ExtendedCommitSig to its Protobuf representation. +func (ecs *ExtendedCommitSig) ToProto() *cmtproto.ExtendedCommitSig { + if ecs == nil { + return nil + } + + return &cmtproto.ExtendedCommitSig{ + BlockIdFlag: cmtproto.BlockIDFlag(ecs.BlockIDFlag), + ValidatorAddress: ecs.ValidatorAddress, + Timestamp: ecs.Timestamp, + Signature: ecs.Signature, + Extension: ecs.Extension, + ExtensionSignature: ecs.ExtensionSignature, + } +} + +// FromProto populates the ExtendedCommitSig with values from the given +// Protobuf representation. Returns an error if the ExtendedCommitSig is +// invalid. +func (ecs *ExtendedCommitSig) FromProto(ecsp cmtproto.ExtendedCommitSig) error { + ecs.BlockIDFlag = BlockIDFlag(ecsp.BlockIdFlag) + ecs.ValidatorAddress = ecsp.ValidatorAddress + ecs.Timestamp = ecsp.Timestamp + ecs.Signature = ecsp.Signature + ecs.Extension = ecsp.Extension + ecs.ExtensionSignature = ecsp.ExtensionSignature + + return ecs.ValidateBasic() +} + +//------------------------------------- + +// Commit contains the evidence that a block was committed by a set of validators. +// NOTE: Commit is empty for height 1, but never nil. +type Commit struct { + // NOTE: The signatures are in order of address to preserve the bonded + // ValidatorSet order. + // Any peer with a block can gossip signatures by index with a peer without + // recalculating the active ValidatorSet. + Height int64 `json:"height"` + Round int32 `json:"round"` + BlockID BlockID `json:"block_id"` + Signatures []CommitSig `json:"signatures"` + + // Memoized in first call to corresponding method. + // NOTE: can't memoize in constructor because constructor isn't used for + // unmarshaling. + hash cmtbytes.HexBytes +} + +// Clone creates a deep copy of this commit. +func (commit *Commit) Clone() *Commit { + sigs := make([]CommitSig, len(commit.Signatures)) + copy(sigs, commit.Signatures) + commCopy := *commit + commCopy.Signatures = sigs + return &commCopy +} + +// GetVote converts the CommitSig for the given valIdx to a Vote. Commits do +// not contain vote extensions, so the vote extension and vote extension +// signature will not be present in the returned vote. +// Returns nil if the precommit at valIdx is nil. +// Panics if valIdx >= commit.Size(). +func (commit *Commit) GetVote(valIdx int32) *Vote { + commitSig := commit.Signatures[valIdx] + return &Vote{ + Type: cmtproto.PrecommitType, + Height: commit.Height, + Round: commit.Round, + BlockID: commitSig.BlockID(commit.BlockID), + Timestamp: commitSig.Timestamp, + ValidatorAddress: commitSig.ValidatorAddress, + ValidatorIndex: valIdx, + Signature: commitSig.Signature, + } +} + +// VoteSignBytes returns the bytes of the Vote corresponding to valIdx for +// signing. +// +// The only unique part is the Timestamp - all other fields signed over are +// otherwise the same for all validators. +// +// Panics if valIdx >= commit.Size(). +// +// See VoteSignBytes +func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte { + v := commit.GetVote(valIdx).ToProto() + return VoteSignBytes(chainID, v) +} + +// Size returns the number of signatures in the commit. +func (commit *Commit) Size() int { + if commit == nil { + return 0 + } + return len(commit.Signatures) +} + +// ValidateBasic performs basic validation that doesn't involve state data. +// Does not actually check the cryptographic signatures. +func (commit *Commit) ValidateBasic() error { + if commit.Height < 0 { + return errors.New("negative Height") + } + if commit.Round < 0 { + return errors.New("negative Round") + } + + if commit.Height >= 1 { + if commit.BlockID.IsZero() { + return errors.New("commit cannot be for nil block") + } + + if len(commit.Signatures) == 0 { + return errors.New("no signatures in commit") + } + for i, commitSig := range commit.Signatures { + if err := commitSig.ValidateBasic(); err != nil { + return fmt.Errorf("wrong CommitSig #%d: %v", i, err) + } + } + } + return nil +} + +// Hash returns the hash of the commit +func (commit *Commit) Hash() cmtbytes.HexBytes { + if commit == nil { + return nil + } + if commit.hash == nil { + bs := make([][]byte, len(commit.Signatures)) + for i, commitSig := range commit.Signatures { + pbcs := commitSig.ToProto() + bz, err := pbcs.Marshal() + if err != nil { + panic(err) + } + + bs[i] = bz + } + commit.hash = merkle.HashFromByteSlices(bs) + } + return commit.hash +} + +// WrappedExtendedCommit wraps a commit as an ExtendedCommit. +// The VoteExtension fields of the resulting value will by nil. +// Wrapping a Commit as an ExtendedCommit is useful when an API +// requires an ExtendedCommit wire type but does not +// need the VoteExtension data. +func (commit *Commit) WrappedExtendedCommit() *ExtendedCommit { + cs := make([]ExtendedCommitSig, len(commit.Signatures)) + for idx, s := range commit.Signatures { + cs[idx] = ExtendedCommitSig{ + CommitSig: s, + } + } + return &ExtendedCommit{ + Height: commit.Height, + Round: commit.Round, + BlockID: commit.BlockID, + ExtendedSignatures: cs, + } +} + +// StringIndented returns a string representation of the commit. +func (commit *Commit) StringIndented(indent string) string { + if commit == nil { + return "nil-Commit" + } + commitSigStrings := make([]string, len(commit.Signatures)) + for i, commitSig := range commit.Signatures { + commitSigStrings[i] = commitSig.String() + } + return fmt.Sprintf(`Commit{ +%s Height: %d +%s Round: %d +%s BlockID: %v +%s Signatures: +%s %v +%s}#%v`, + indent, commit.Height, + indent, commit.Round, + indent, commit.BlockID, + indent, + indent, strings.Join(commitSigStrings, "\n"+indent+" "), + indent, commit.hash) +} + +// ToProto converts Commit to protobuf +func (commit *Commit) ToProto() *cmtproto.Commit { + if commit == nil { + return nil + } + + c := new(cmtproto.Commit) + sigs := make([]cmtproto.CommitSig, len(commit.Signatures)) + for i := range commit.Signatures { + sigs[i] = *commit.Signatures[i].ToProto() + } + c.Signatures = sigs + + c.Height = commit.Height + c.Round = commit.Round + c.BlockID = commit.BlockID.ToProto() + + return c +} + +// FromProto sets a protobuf Commit to the given pointer. +// It returns an error if the commit is invalid. +func CommitFromProto(cp *cmtproto.Commit) (*Commit, error) { + if cp == nil { + return nil, errors.New("nil Commit") + } + + commit := new(Commit) + + bi, err := BlockIDFromProto(&cp.BlockID) + if err != nil { + return nil, err + } + + sigs := make([]CommitSig, len(cp.Signatures)) + for i := range cp.Signatures { + if err := sigs[i].FromProto(cp.Signatures[i]); err != nil { + return nil, err + } + } + commit.Signatures = sigs + + commit.Height = cp.Height + commit.Round = cp.Round + commit.BlockID = *bi + + return commit, commit.ValidateBasic() +} + +//------------------------------------- + +// ExtendedCommit is similar to Commit, except that its signatures also retain +// their corresponding vote extensions and vote extension signatures. +type ExtendedCommit struct { + Height int64 + Round int32 + BlockID BlockID + ExtendedSignatures []ExtendedCommitSig + + bitArray *bits.BitArray +} + +// Clone creates a deep copy of this extended commit. +func (ec *ExtendedCommit) Clone() *ExtendedCommit { + sigs := make([]ExtendedCommitSig, len(ec.ExtendedSignatures)) + copy(sigs, ec.ExtendedSignatures) + ecc := *ec + ecc.ExtendedSignatures = sigs + return &ecc +} + +// ToExtendedVoteSet constructs a VoteSet from the Commit and validator set. +// Panics if signatures from the ExtendedCommit can't be added to the voteset. +// Panics if any of the votes have invalid or absent vote extension data. +// Inverse of VoteSet.MakeExtendedCommit(). +func (ec *ExtendedCommit) ToExtendedVoteSet(chainID string, vals *ValidatorSet) *VoteSet { + voteSet := NewExtendedVoteSet(chainID, ec.Height, ec.Round, cmtproto.PrecommitType, vals) + ec.addSigsToVoteSet(voteSet) + return voteSet +} + +// addSigsToVoteSet adds all of the signature to voteSet. +func (ec *ExtendedCommit) addSigsToVoteSet(voteSet *VoteSet) { + for idx, ecs := range ec.ExtendedSignatures { + if ecs.BlockIDFlag == BlockIDFlagAbsent { + continue // OK, some precommits can be missing. + } + vote := ec.GetExtendedVote(int32(idx)) + if err := vote.ValidateBasic(); err != nil { + panic(fmt.Errorf("failed to validate vote reconstructed from LastCommit: %w", err)) + } + added, err := voteSet.AddVote(vote) + if !added || err != nil { + panic(fmt.Errorf("failed to reconstruct vote set from extended commit: %w", err)) + } + } +} + +// ToVoteSet constructs a VoteSet from the Commit and validator set. +// Panics if signatures from the commit can't be added to the voteset. +// Inverse of VoteSet.MakeCommit(). +func (commit *Commit) ToVoteSet(chainID string, vals *ValidatorSet) *VoteSet { + voteSet := NewVoteSet(chainID, commit.Height, commit.Round, cmtproto.PrecommitType, vals) + for idx, cs := range commit.Signatures { + if cs.BlockIDFlag == BlockIDFlagAbsent { + continue // OK, some precommits can be missing. + } + vote := commit.GetVote(int32(idx)) + if err := vote.ValidateBasic(); err != nil { + panic(fmt.Errorf("failed to validate vote reconstructed from commit: %w", err)) + } + added, err := voteSet.AddVote(vote) + if !added || err != nil { + panic(fmt.Errorf("failed to reconstruct vote set from commit: %w", err)) + } + } + return voteSet +} + +// EnsureExtensions validates that a vote extensions signature is present for +// every ExtendedCommitSig in the ExtendedCommit. +func (ec *ExtendedCommit) EnsureExtensions(extEnabled bool) error { + for _, ecs := range ec.ExtendedSignatures { + if err := ecs.EnsureExtension(extEnabled); err != nil { + return err + } + } + return nil +} + +// ToCommit converts an ExtendedCommit to a Commit by removing all vote +// extension-related fields. +func (ec *ExtendedCommit) ToCommit() *Commit { + cs := make([]CommitSig, len(ec.ExtendedSignatures)) + for idx, ecs := range ec.ExtendedSignatures { + cs[idx] = ecs.CommitSig + } + return &Commit{ + Height: ec.Height, + Round: ec.Round, + BlockID: ec.BlockID, + Signatures: cs, + } +} + +// GetExtendedVote converts the ExtendedCommitSig for the given validator +// index to a Vote with a vote extensions. +// It panics if valIndex is out of range. +func (ec *ExtendedCommit) GetExtendedVote(valIndex int32) *Vote { + ecs := ec.ExtendedSignatures[valIndex] + return &Vote{ + Type: cmtproto.PrecommitType, + Height: ec.Height, + Round: ec.Round, + BlockID: ecs.BlockID(ec.BlockID), + Timestamp: ecs.Timestamp, + ValidatorAddress: ecs.ValidatorAddress, + ValidatorIndex: valIndex, + Signature: ecs.Signature, + Extension: ecs.Extension, + ExtensionSignature: ecs.ExtensionSignature, + } +} + +// Type returns the vote type of the extended commit, which is always +// VoteTypePrecommit +// Implements VoteSetReader. +func (ec *ExtendedCommit) Type() byte { return byte(cmtproto.PrecommitType) } + +// GetHeight returns height of the extended commit. +// Implements VoteSetReader. +func (ec *ExtendedCommit) GetHeight() int64 { return ec.Height } + +// GetRound returns height of the extended commit. +// Implements VoteSetReader. +func (ec *ExtendedCommit) GetRound() int32 { return ec.Round } + +// Size returns the number of signatures in the extended commit. +// Implements VoteSetReader. +func (ec *ExtendedCommit) Size() int { + if ec == nil { + return 0 + } + return len(ec.ExtendedSignatures) +} + +// BitArray returns a BitArray of which validators voted for BlockID or nil in +// this extended commit. +// Implements VoteSetReader. +func (ec *ExtendedCommit) BitArray() *bits.BitArray { + if ec.bitArray == nil { + initialBitFn := func(i int) bool { + // TODO: need to check the BlockID otherwise we could be counting conflicts, + // not just the one with +2/3 ! + return ec.ExtendedSignatures[i].BlockIDFlag != BlockIDFlagAbsent + } + ec.bitArray = bits.NewBitArrayFromFn(len(ec.ExtendedSignatures), initialBitFn) + } + return ec.bitArray +} + +// GetByIndex returns the vote corresponding to a given validator index. +// Panics if `index >= extCommit.Size()`. +// Implements VoteSetReader. +func (ec *ExtendedCommit) GetByIndex(valIdx int32) *Vote { + return ec.GetExtendedVote(valIdx) +} + +// IsCommit returns true if there is at least one signature. +// Implements VoteSetReader. +func (ec *ExtendedCommit) IsCommit() bool { + return len(ec.ExtendedSignatures) != 0 +} + +// ValidateBasic checks whether the extended commit is well-formed. Does not +// actually check the cryptographic signatures. +func (ec *ExtendedCommit) ValidateBasic() error { + if ec.Height < 0 { + return errors.New("negative Height") + } + if ec.Round < 0 { + return errors.New("negative Round") + } + + if ec.Height >= 1 { + if ec.BlockID.IsZero() { + return errors.New("extended commit cannot be for nil block") + } + + if len(ec.ExtendedSignatures) == 0 { + return errors.New("no signatures in commit") + } + for i, extCommitSig := range ec.ExtendedSignatures { + if err := extCommitSig.ValidateBasic(); err != nil { + return fmt.Errorf("wrong ExtendedCommitSig #%d: %v", i, err) + } + } + } + return nil +} + +// ToProto converts ExtendedCommit to protobuf +func (ec *ExtendedCommit) ToProto() *cmtproto.ExtendedCommit { + if ec == nil { + return nil + } + + c := new(cmtproto.ExtendedCommit) + sigs := make([]cmtproto.ExtendedCommitSig, len(ec.ExtendedSignatures)) + for i := range ec.ExtendedSignatures { + sigs[i] = *ec.ExtendedSignatures[i].ToProto() + } + c.ExtendedSignatures = sigs + + c.Height = ec.Height + c.Round = ec.Round + c.BlockID = ec.BlockID.ToProto() + + return c +} + +// ExtendedCommitFromProto constructs an ExtendedCommit from the given Protobuf +// representation. It returns an error if the extended commit is invalid. +func ExtendedCommitFromProto(ecp *cmtproto.ExtendedCommit) (*ExtendedCommit, error) { + if ecp == nil { + return nil, errors.New("nil ExtendedCommit") + } + + extCommit := new(ExtendedCommit) + + bi, err := BlockIDFromProto(&ecp.BlockID) + if err != nil { + return nil, err + } + + sigs := make([]ExtendedCommitSig, len(ecp.ExtendedSignatures)) + for i := range ecp.ExtendedSignatures { + if err := sigs[i].FromProto(ecp.ExtendedSignatures[i]); err != nil { + return nil, err + } + } + extCommit.ExtendedSignatures = sigs + extCommit.Height = ecp.Height + extCommit.Round = ecp.Round + extCommit.BlockID = *bi + + return extCommit, extCommit.ValidateBasic() +} + +//------------------------------------- + +// Data contains the set of transactions included in the block +type Data struct { + // Txs that will be applied by state @ block.Height+1. + // NOTE: not all txs here are valid. We're just agreeing on the order first. + // This means that block.AppHash does not include these txs. + Txs Txs `json:"txs"` + + // Volatile + hash cmtbytes.HexBytes +} + +// Hash returns the hash of the data +func (data *Data) Hash() cmtbytes.HexBytes { + if data == nil { + return (Txs{}).Hash() + } + if data.hash == nil { + data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs + } + return data.hash +} + +// StringIndented returns an indented string representation of the transactions. +func (data *Data) StringIndented(indent string) string { + if data == nil { + return "nil-Data" + } + txStrings := make([]string, cmtmath.MinInt(len(data.Txs), 21)) + for i, tx := range data.Txs { + if i == 20 { + txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs)) + break + } + txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx)) + } + return fmt.Sprintf(`Data{ +%s %v +%s}#%v`, + indent, strings.Join(txStrings, "\n"+indent+" "), + indent, data.hash) +} + +// ToProto converts Data to protobuf +func (data *Data) ToProto() cmtproto.Data { + tp := new(cmtproto.Data) + + if len(data.Txs) > 0 { + txBzs := make([][]byte, len(data.Txs)) + for i := range data.Txs { + txBzs[i] = data.Txs[i] + } + tp.Txs = txBzs + } + + return *tp +} + +// DataFromProto takes a protobuf representation of Data & +// returns the native type. +func DataFromProto(dp *cmtproto.Data) (Data, error) { + if dp == nil { + return Data{}, errors.New("nil data") + } + data := new(Data) + + if len(dp.Txs) > 0 { + txBzs := make(Txs, len(dp.Txs)) + for i := range dp.Txs { + txBzs[i] = Tx(dp.Txs[i]) + } + data.Txs = txBzs + } else { + data.Txs = Txs{} + } + + return *data, nil +} + +//----------------------------------------------------------------------------- + +// EvidenceData contains any evidence of malicious wrong-doing by validators +type EvidenceData struct { + Evidence EvidenceList `json:"evidence"` + + // Volatile. Used as cache + hash cmtbytes.HexBytes + byteSize int64 +} + +// Hash returns the hash of the data. +func (data *EvidenceData) Hash() cmtbytes.HexBytes { + if data.hash == nil { + data.hash = data.Evidence.Hash() + } + return data.hash +} + +// ByteSize returns the total byte size of all the evidence +func (data *EvidenceData) ByteSize() int64 { + if data.byteSize == 0 && len(data.Evidence) != 0 { + pb, err := data.ToProto() + if err != nil { + panic(err) + } + data.byteSize = int64(pb.Size()) + } + return data.byteSize +} + +// StringIndented returns a string representation of the evidence. +func (data *EvidenceData) StringIndented(indent string) string { + if data == nil { + return "nil-Evidence" + } + evStrings := make([]string, cmtmath.MinInt(len(data.Evidence), 21)) + for i, ev := range data.Evidence { + if i == 20 { + evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence)) + break + } + evStrings[i] = fmt.Sprintf("Evidence:%v", ev) + } + return fmt.Sprintf(`EvidenceData{ +%s %v +%s}#%v`, + indent, strings.Join(evStrings, "\n"+indent+" "), + indent, data.hash) +} + +// ToProto converts EvidenceData to protobuf +func (data *EvidenceData) ToProto() (*cmtproto.EvidenceList, error) { + if data == nil { + return nil, errors.New("nil evidence data") + } + + evi := new(cmtproto.EvidenceList) + eviBzs := make([]cmtproto.Evidence, len(data.Evidence)) + for i := range data.Evidence { + protoEvi, err := EvidenceToProto(data.Evidence[i]) + if err != nil { + return nil, err + } + eviBzs[i] = *protoEvi + } + evi.Evidence = eviBzs + + return evi, nil +} + +// FromProto sets a protobuf EvidenceData to the given pointer. +func (data *EvidenceData) FromProto(eviData *cmtproto.EvidenceList) error { + if eviData == nil { + return errors.New("nil evidenceData") + } + + eviBzs := make(EvidenceList, len(eviData.Evidence)) + for i := range eviData.Evidence { + evi, err := EvidenceFromProto(&eviData.Evidence[i]) + if err != nil { + return err + } + eviBzs[i] = evi + } + data.Evidence = eviBzs + data.byteSize = int64(eviData.Size()) + + return nil +} + +//-------------------------------------------------------------------------------- + +// BlockID +type BlockID struct { + Hash cmtbytes.HexBytes `json:"hash"` + PartSetHeader PartSetHeader `json:"parts"` +} + +// Equals returns true if the BlockID matches the given BlockID +func (blockID BlockID) Equals(other BlockID) bool { + return bytes.Equal(blockID.Hash, other.Hash) && + blockID.PartSetHeader.Equals(other.PartSetHeader) +} + +// Key returns a machine-readable string representation of the BlockID +func (blockID BlockID) Key() string { + pbph := blockID.PartSetHeader.ToProto() + bz, err := pbph.Marshal() + if err != nil { + panic(err) + } + + return fmt.Sprint(string(blockID.Hash), string(bz)) +} + +// ValidateBasic performs basic validation. +func (blockID BlockID) ValidateBasic() error { + // Hash can be empty in case of POLBlockID in Proposal. + if err := ValidateHash(blockID.Hash); err != nil { + return fmt.Errorf("wrong Hash") + } + if err := blockID.PartSetHeader.ValidateBasic(); err != nil { + return fmt.Errorf("wrong PartSetHeader: %v", err) + } + return nil +} + +// IsZero returns true if this is the BlockID of a nil block. +func (blockID BlockID) IsZero() bool { + return len(blockID.Hash) == 0 && + blockID.PartSetHeader.IsZero() +} + +// IsComplete returns true if this is a valid BlockID of a non-nil block. +func (blockID BlockID) IsComplete() bool { + return len(blockID.Hash) == tmhash.Size && + blockID.PartSetHeader.Total > 0 && + len(blockID.PartSetHeader.Hash) == tmhash.Size +} + +// String returns a human readable string representation of the BlockID. +// +// 1. hash +// 2. part set header +// +// See PartSetHeader#String +func (blockID BlockID) String() string { + return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader) +} + +// ToProto converts BlockID to protobuf +func (blockID *BlockID) ToProto() cmtproto.BlockID { + if blockID == nil { + return cmtproto.BlockID{} + } + + return cmtproto.BlockID{ + Hash: blockID.Hash, + PartSetHeader: blockID.PartSetHeader.ToProto(), + } +} + +// FromProto sets a protobuf BlockID to the given pointer. +// It returns an error if the block id is invalid. +func BlockIDFromProto(bID *cmtproto.BlockID) (*BlockID, error) { + if bID == nil { + return nil, errors.New("nil BlockID") + } + + blockID := new(BlockID) + ph, err := PartSetHeaderFromProto(&bID.PartSetHeader) + if err != nil { + return nil, err + } + + blockID.PartSetHeader = *ph + blockID.Hash = bID.Hash + + return blockID, blockID.ValidateBasic() +} + +// ProtoBlockIDIsNil is similar to the IsNil function on BlockID, but for the +// Protobuf representation. +func ProtoBlockIDIsNil(bID *cmtproto.BlockID) bool { + return len(bID.Hash) == 0 && ProtoPartSetHeaderIsZero(&bID.PartSetHeader) +} diff --git a/types/block_meta.go b/types/block_meta.go new file mode 100644 index 0000000..dcc10a1 --- /dev/null +++ b/types/block_meta.go @@ -0,0 +1,86 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// BlockMeta contains meta information. +type BlockMeta struct { + BlockID BlockID `json:"block_id"` + BlockSize int `json:"block_size"` + Header Header `json:"header"` + NumTxs int `json:"num_txs"` +} + +// NewBlockMeta returns a new BlockMeta. +func NewBlockMeta(block *Block, blockParts *PartSet) *BlockMeta { + return &BlockMeta{ + BlockID: BlockID{block.Hash(), blockParts.Header()}, + BlockSize: block.Size(), + Header: block.Header, + NumTxs: len(block.Txs), + } +} + +func (bm *BlockMeta) ToProto() *cmtproto.BlockMeta { + if bm == nil { + return nil + } + + pb := &cmtproto.BlockMeta{ + BlockID: bm.BlockID.ToProto(), + BlockSize: int64(bm.BlockSize), + Header: *bm.Header.ToProto(), + NumTxs: int64(bm.NumTxs), + } + return pb +} + +func BlockMetaFromProto(pb *cmtproto.BlockMeta) (*BlockMeta, error) { + bm, err := BlockMetaFromTrustedProto(pb) + if err != nil { + return nil, err + } + return bm, bm.ValidateBasic() +} + +func BlockMetaFromTrustedProto(pb *cmtproto.BlockMeta) (*BlockMeta, error) { + if pb == nil { + return nil, errors.New("blockmeta is empty") + } + + bm := new(BlockMeta) + + bi, err := BlockIDFromProto(&pb.BlockID) + if err != nil { + return nil, err + } + + h, err := HeaderFromProto(&pb.Header) + if err != nil { + return nil, err + } + + bm.BlockID = *bi + bm.BlockSize = int(pb.BlockSize) + bm.Header = h + bm.NumTxs = int(pb.NumTxs) + + return bm, nil +} + +// ValidateBasic performs basic validation. +func (bm *BlockMeta) ValidateBasic() error { + if err := bm.BlockID.ValidateBasic(); err != nil { + return err + } + if !bytes.Equal(bm.BlockID.Hash, bm.Header.Hash()) { + return fmt.Errorf("expected BlockID#Hash and Header#Hash to be the same, got %X != %X", + bm.BlockID.Hash, bm.Header.Hash()) + } + return nil +} diff --git a/types/block_meta_test.go b/types/block_meta_test.go new file mode 100644 index 0000000..6c954d4 --- /dev/null +++ b/types/block_meta_test.go @@ -0,0 +1,95 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/tmhash" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +func TestBlockMeta_ToProto(t *testing.T) { + h := makeRandHeader() + bi := BlockID{Hash: h.Hash(), PartSetHeader: PartSetHeader{Total: 123, Hash: cmtrand.Bytes(tmhash.Size)}} + + bm := &BlockMeta{ + BlockID: bi, + BlockSize: 200, + Header: h, + NumTxs: 0, + } + + tests := []struct { + testName string + bm *BlockMeta + expErr bool + }{ + {"success", bm, false}, + {"failure nil", nil, true}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.testName, func(t *testing.T) { + pb := tt.bm.ToProto() + + bm, err := BlockMetaFromTrustedProto(pb) + + if !tt.expErr { + require.NoError(t, err, tt.testName) + require.Equal(t, tt.bm, bm, tt.testName) + } else { + require.Error(t, err, tt.testName) + } + }) + } +} + +func TestBlockMeta_ValidateBasic(t *testing.T) { + h := makeRandHeader() + bi := BlockID{Hash: h.Hash(), PartSetHeader: PartSetHeader{Total: 123, Hash: cmtrand.Bytes(tmhash.Size)}} + bi2 := BlockID{Hash: cmtrand.Bytes(tmhash.Size), + PartSetHeader: PartSetHeader{Total: 123, Hash: cmtrand.Bytes(tmhash.Size)}} + bi3 := BlockID{Hash: []byte("incorrect hash"), + PartSetHeader: PartSetHeader{Total: 123, Hash: []byte("incorrect hash")}} + + bm := &BlockMeta{ + BlockID: bi, + BlockSize: 200, + Header: h, + NumTxs: 0, + } + + bm2 := &BlockMeta{ + BlockID: bi2, + BlockSize: 200, + Header: h, + NumTxs: 0, + } + + bm3 := &BlockMeta{ + BlockID: bi3, + BlockSize: 200, + Header: h, + NumTxs: 0, + } + + tests := []struct { + name string + bm *BlockMeta + wantErr bool + }{ + {"success", bm, false}, + {"failure wrong blockID hash", bm2, true}, + {"failure wrong length blockID hash", bm3, true}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + if err := tt.bm.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("BlockMeta.ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/types/block_test.go b/types/block_test.go new file mode 100644 index 0000000..47ae8a7 --- /dev/null +++ b/types/block_test.go @@ -0,0 +1,988 @@ +package types + +import ( + // it is ok to use math/rand here: we do not need a cryptographically secure random + // number generator here and we can run the tests a bit faster + + "crypto/rand" + "encoding/hex" + "math" + "os" + "reflect" + "testing" + "time" + + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/bits" + "github.com/cometbft/cometbft/libs/bytes" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cometbft/cometbft/version" +) + +func TestMain(m *testing.M) { + code := m.Run() + os.Exit(code) +} + +func TestBlockAddEvidence(t *testing.T) { + txs := []Tx{Tx("foo"), Tx("bar")} + lastID := makeBlockIDRandom() + h := int64(3) + + voteSet, _, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, false) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), false) + require.NoError(t, err) + + ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain") + require.NoError(t, err) + evList := []Evidence{ev} + + block := MakeBlock(h, txs, extCommit.ToCommit(), evList) + require.NotNil(t, block) + require.Equal(t, 1, len(block.Evidence.Evidence)) + require.NotNil(t, block.EvidenceHash) +} + +func TestBlockValidateBasic(t *testing.T) { + require.Error(t, (*Block)(nil).ValidateBasic()) + + txs := []Tx{Tx("foo"), Tx("bar")} + lastID := makeBlockIDRandom() + h := int64(3) + + voteSet, valSet, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, false) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), false) + require.NoError(t, err) + commit := extCommit.ToCommit() + + ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain") + require.NoError(t, err) + evList := []Evidence{ev} + + testCases := []struct { + testName string + malleateBlock func(*Block) + expErr bool + }{ + {"Make Block", func(blk *Block) {}, false}, + {"Make Block w/ proposer Addr", func(blk *Block) { blk.ProposerAddress = valSet.GetProposer().Address }, false}, + {"Negative Height", func(blk *Block) { blk.Height = -1 }, true}, + {"Remove 1/2 the commits", func(blk *Block) { + blk.LastCommit.Signatures = commit.Signatures[:commit.Size()/2] + blk.LastCommit.hash = nil // clear hash or change wont be noticed + }, true}, + {"Remove LastCommitHash", func(blk *Block) { blk.LastCommitHash = []byte("something else") }, true}, + {"Tampered Data", func(blk *Block) { + blk.Txs[0] = Tx("something else") + blk.hash = nil // clear hash or change wont be noticed + }, true}, + {"Tampered DataHash", func(blk *Block) { + blk.DataHash = cmtrand.Bytes(len(blk.DataHash)) + }, true}, + {"Tampered EvidenceHash", func(blk *Block) { + blk.EvidenceHash = []byte("something else") + }, true}, + {"Incorrect block protocol version", func(blk *Block) { + blk.Version.Block = 1 + }, true}, + } + for i, tc := range testCases { + tc := tc + i := i + t.Run(tc.testName, func(t *testing.T) { + block := MakeBlock(h, txs, commit, evList) + block.ProposerAddress = valSet.GetProposer().Address + tc.malleateBlock(block) + err = block.ValidateBasic() + assert.Equal(t, tc.expErr, err != nil, "#%d: %v", i, err) + }) + } +} + +func TestBlockHash(t *testing.T) { + assert.Nil(t, (*Block)(nil).Hash()) + assert.Nil(t, MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Hash()) +} + +func TestBlockMakePartSet(t *testing.T) { + bps, err := (*Block)(nil).MakePartSet(2) + assert.Error(t, err) + assert.Nil(t, bps) + + partSet, err := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024) + require.NoError(t, err) + assert.NotNil(t, partSet) + assert.EqualValues(t, 1, partSet.Total()) +} + +func TestBlockMakePartSetWithEvidence(t *testing.T) { + bps, err := (*Block)(nil).MakePartSet(2) + assert.Error(t, err) + assert.Nil(t, bps) + + lastID := makeBlockIDRandom() + h := int64(3) + + voteSet, _, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, false) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), false) + require.NoError(t, err) + + ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain") + require.NoError(t, err) + evList := []Evidence{ev} + + partSet, err := MakeBlock(h, []Tx{Tx("Hello World")}, extCommit.ToCommit(), evList).MakePartSet(512) + require.NoError(t, err) + + assert.NotNil(t, partSet) + assert.EqualValues(t, 4, partSet.Total()) +} + +func TestBlockHashesTo(t *testing.T) { + assert.False(t, (*Block)(nil).HashesTo(nil)) + + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, valSet, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, false) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), false) + require.NoError(t, err) + + ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain") + require.NoError(t, err) + evList := []Evidence{ev} + + block := MakeBlock(h, []Tx{Tx("Hello World")}, extCommit.ToCommit(), evList) + block.ValidatorsHash = valSet.Hash() + assert.False(t, block.HashesTo([]byte{})) + assert.False(t, block.HashesTo([]byte("something else"))) + assert.True(t, block.HashesTo(block.Hash())) +} + +func TestBlockSize(t *testing.T) { + size := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Size() + if size <= 0 { + t.Fatal("Size of the block is zero or negative") + } +} + +func TestBlockString(t *testing.T) { + assert.Equal(t, "nil-Block", (*Block)(nil).String()) + assert.Equal(t, "nil-Block", (*Block)(nil).StringIndented("")) + assert.Equal(t, "nil-Block", (*Block)(nil).StringShort()) + + block := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil) + assert.NotEqual(t, "nil-Block", block.String()) + assert.NotEqual(t, "nil-Block", block.StringIndented("")) + assert.NotEqual(t, "nil-Block", block.StringShort()) +} + +func makeBlockIDRandom() BlockID { + var ( + blockHash = make([]byte, tmhash.Size) + partSetHash = make([]byte, tmhash.Size) + ) + rand.Read(blockHash) //nolint: errcheck // ignore errcheck for read + rand.Read(partSetHash) //nolint: errcheck // ignore errcheck for read + return BlockID{blockHash, PartSetHeader{123, partSetHash}} +} + +func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID { + var ( + h = make([]byte, tmhash.Size) + psH = make([]byte, tmhash.Size) + ) + copy(h, hash) + copy(psH, partSetHash) + return BlockID{ + Hash: h, + PartSetHeader: PartSetHeader{ + Total: partSetSize, + Hash: psH, + }, + } +} + +var nilBytes []byte + +// This follows RFC-6962, i.e. `echo -n ” | sha256sum` +var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, + 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, + 0x78, 0x52, 0xb8, 0x55} + +func TestNilHeaderHashDoesntCrash(t *testing.T) { + assert.Equal(t, nilBytes, []byte((*Header)(nil).Hash())) + assert.Equal(t, nilBytes, []byte((new(Header)).Hash())) +} + +func TestNilDataHashDoesntCrash(t *testing.T) { + assert.Equal(t, emptyBytes, []byte((*Data)(nil).Hash())) + assert.Equal(t, emptyBytes, []byte(new(Data).Hash())) +} + +func TestCommit(t *testing.T) { + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, _, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, true) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), true) + require.NoError(t, err) + + assert.Equal(t, h-1, extCommit.Height) + assert.EqualValues(t, 1, extCommit.Round) + assert.Equal(t, cmtproto.PrecommitType, cmtproto.SignedMsgType(extCommit.Type())) + if extCommit.Size() <= 0 { + t.Fatalf("commit %v has a zero or negative size: %d", extCommit, extCommit.Size()) + } + + require.NotNil(t, extCommit.BitArray()) + assert.Equal(t, bits.NewBitArray(10).Size(), extCommit.BitArray().Size()) + + assert.Equal(t, voteSet.GetByIndex(0), extCommit.GetByIndex(0)) + assert.True(t, extCommit.IsCommit()) +} + +func TestCommitValidateBasic(t *testing.T) { + testCases := []struct { + testName string + malleateCommit func(*Commit) + expectErr bool + }{ + {"Random Commit", func(com *Commit) {}, false}, + {"Incorrect signature", func(com *Commit) { com.Signatures[0].Signature = []byte{0} }, false}, + {"Incorrect height", func(com *Commit) { com.Height = int64(-100) }, true}, + {"Incorrect round", func(com *Commit) { com.Round = -100 }, true}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + com := randCommit(time.Now()) + tc.malleateCommit(com) + assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestMaxCommitBytes(t *testing.T) { + // time is varint encoded so need to pick the max. + // year int, month Month, day, hour, min, sec, nsec int, loc *Location + timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC) + + cs := CommitSig{ + BlockIDFlag: BlockIDFlagNil, + ValidatorAddress: crypto.AddressHash([]byte("validator_address")), + Timestamp: timestamp, + Signature: crypto.CRandBytes(MaxSignatureSize), + } + + pbSig := cs.ToProto() + // test that a single commit sig doesn't exceed max commit sig bytes + assert.EqualValues(t, MaxCommitSigBytes, pbSig.Size()) + + // check size with a single commit + commit := &Commit{ + Height: math.MaxInt64, + Round: math.MaxInt32, + BlockID: BlockID{ + Hash: tmhash.Sum([]byte("blockID_hash")), + PartSetHeader: PartSetHeader{ + Total: math.MaxInt32, + Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")), + }, + }, + Signatures: []CommitSig{cs}, + } + + pb := commit.ToProto() + + assert.EqualValues(t, MaxCommitBytes(1), int64(pb.Size())) + + // check the upper bound of the commit size + for i := 1; i < MaxVotesCount; i++ { + commit.Signatures = append(commit.Signatures, cs) + } + + pb = commit.ToProto() + + assert.EqualValues(t, MaxCommitBytes(MaxVotesCount), int64(pb.Size())) + +} + +func TestHeaderHash(t *testing.T) { + testCases := []struct { + desc string + header *Header + expectHash bytes.HexBytes + }{ + {"Generates expected hash", &Header{ + Version: cmtversion.Consensus{Block: 1, App: 2}, + ChainID: "chainId", + Height: 3, + Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC), + LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)), + LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), + DataHash: tmhash.Sum([]byte("data_hash")), + ValidatorsHash: tmhash.Sum([]byte("validators_hash")), + NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), + ConsensusHash: tmhash.Sum([]byte("consensus_hash")), + AppHash: tmhash.Sum([]byte("app_hash")), + LastResultsHash: tmhash.Sum([]byte("last_results_hash")), + EvidenceHash: tmhash.Sum([]byte("evidence_hash")), + ProposerAddress: crypto.AddressHash([]byte("proposer_address")), + }, hexBytesFromString("F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")}, + {"nil header yields nil", nil, nil}, + {"nil ValidatorsHash yields nil", &Header{ + Version: cmtversion.Consensus{Block: 1, App: 2}, + ChainID: "chainId", + Height: 3, + Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC), + LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)), + LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), + DataHash: tmhash.Sum([]byte("data_hash")), + ValidatorsHash: nil, + NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), + ConsensusHash: tmhash.Sum([]byte("consensus_hash")), + AppHash: tmhash.Sum([]byte("app_hash")), + LastResultsHash: tmhash.Sum([]byte("last_results_hash")), + EvidenceHash: tmhash.Sum([]byte("evidence_hash")), + ProposerAddress: crypto.AddressHash([]byte("proposer_address")), + }, nil}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.desc, func(t *testing.T) { + assert.Equal(t, tc.expectHash, tc.header.Hash()) + + // We also make sure that all fields are hashed in struct order, and that all + // fields in the test struct are non-zero. + if tc.header != nil && tc.expectHash != nil { + byteSlices := [][]byte{} + + s := reflect.ValueOf(*tc.header) + for i := 0; i < s.NumField(); i++ { + f := s.Field(i) + + assert.False(t, f.IsZero(), "Found zero-valued field %v", + s.Type().Field(i).Name) + + switch f := f.Interface().(type) { + case int64, bytes.HexBytes, string: + byteSlices = append(byteSlices, cdcEncode(f)) + case time.Time: + bz, err := gogotypes.StdTimeMarshal(f) + require.NoError(t, err) + byteSlices = append(byteSlices, bz) + case cmtversion.Consensus: + bz, err := f.Marshal() + require.NoError(t, err) + byteSlices = append(byteSlices, bz) + case BlockID: + pbbi := f.ToProto() + bz, err := pbbi.Marshal() + require.NoError(t, err) + byteSlices = append(byteSlices, bz) + default: + t.Errorf("unknown type %T", f) + } + } + assert.Equal(t, + bytes.HexBytes(merkle.HashFromByteSlices(byteSlices)), tc.header.Hash()) + } + }) + } +} + +func TestMaxHeaderBytes(t *testing.T) { + // Construct a UTF-8 string of MaxChainIDLen length using the supplementary + // characters. + // Each supplementary character takes 4 bytes. + // http://www.i18nguy.com/unicode/supplementary-test.html + maxChainID := "" + for i := 0; i < MaxChainIDLen; i++ { + maxChainID += "𠜎" + } + + // time is varint encoded so need to pick the max. + // year int, month Month, day, hour, min, sec, nsec int, loc *Location + timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC) + + h := Header{ + Version: cmtversion.Consensus{Block: math.MaxInt64, App: math.MaxInt64}, + ChainID: maxChainID, + Height: math.MaxInt64, + Time: timestamp, + LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt32, make([]byte, tmhash.Size)), + LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), + DataHash: tmhash.Sum([]byte("data_hash")), + ValidatorsHash: tmhash.Sum([]byte("validators_hash")), + NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), + ConsensusHash: tmhash.Sum([]byte("consensus_hash")), + AppHash: tmhash.Sum([]byte("app_hash")), + LastResultsHash: tmhash.Sum([]byte("last_results_hash")), + EvidenceHash: tmhash.Sum([]byte("evidence_hash")), + ProposerAddress: crypto.AddressHash([]byte("proposer_address")), + } + + bz, err := h.ToProto().Marshal() + require.NoError(t, err) + + assert.EqualValues(t, MaxHeaderBytes, int64(len(bz))) +} + +func randCommit(now time.Time) *Commit { + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, _, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, false) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, now, false) + if err != nil { + panic(err) + } + return extCommit.ToCommit() +} + +func hexBytesFromString(s string) bytes.HexBytes { + b, err := hex.DecodeString(s) + if err != nil { + panic(err) + } + return bytes.HexBytes(b) +} + +func TestBlockMaxDataBytes(t *testing.T) { + testCases := []struct { + maxBytes int64 + valsCount int + evidenceBytes int64 + panics bool + result int64 + }{ + 0: {-10, 1, 0, true, 0}, + 1: {10, 1, 0, true, 0}, + 2: {841, 1, 0, true, 0}, + 3: {842, 1, 0, false, 0}, + 4: {843, 1, 0, false, 1}, + 5: {954, 2, 0, false, 1}, + 6: {1053, 2, 100, false, 0}, + } + + for i, tc := range testCases { + tc := tc + if tc.panics { + assert.Panics(t, func() { + MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount) + }, "#%v", i) + } else { + assert.Equal(t, + tc.result, + MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount), + "#%v", i) + } + } +} + +func TestBlockMaxDataBytesNoEvidence(t *testing.T) { + testCases := []struct { + maxBytes int64 + valsCount int + panics bool + result int64 + }{ + 0: {-10, 1, true, 0}, + 1: {10, 1, true, 0}, + 2: {841, 1, true, 0}, + 3: {842, 1, false, 0}, + 4: {843, 1, false, 1}, + } + + for i, tc := range testCases { + tc := tc + if tc.panics { + assert.Panics(t, func() { + MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount) + }, "#%v", i) + } else { + assert.Equal(t, + tc.result, + MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount), + "#%v", i) + } + } +} + +// TestVoteSetToExtendedCommit tests that the extended commit produced from a +// vote set contains the same vote information as the vote set. The test ensures +// that the MakeExtendedCommit method behaves as expected, whether vote extensions +// are present in the original votes or not. +func TestVoteSetToExtendedCommit(t *testing.T) { + for _, testCase := range []struct { + name string + includeExtension bool + }{ + { + name: "no extensions", + includeExtension: false, + }, + { + name: "with extensions", + includeExtension: true, + }, + } { + + t.Run(testCase.name, func(t *testing.T) { + blockID := makeBlockIDRandom() + + valSet, vals := RandValidatorSet(10, 1) + var voteSet *VoteSet + if testCase.includeExtension { + voteSet = NewExtendedVoteSet("test_chain_id", 3, 1, cmtproto.PrecommitType, valSet) + } else { + voteSet = NewVoteSet("test_chain_id", 3, 1, cmtproto.PrecommitType, valSet) + } + for i := 0; i < len(vals); i++ { + pubKey, err := vals[i].GetPubKey() + require.NoError(t, err) + vote := &Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: int32(i), + Height: 3, + Round: 1, + Type: cmtproto.PrecommitType, + BlockID: blockID, + Timestamp: time.Now(), + } + v := vote.ToProto() + err = vals[i].SignVote(voteSet.ChainID(), v) + require.NoError(t, err) + vote.Signature = v.Signature + if testCase.includeExtension { + vote.ExtensionSignature = v.ExtensionSignature + } + added, err := voteSet.AddVote(vote) + require.NoError(t, err) + require.True(t, added) + } + var veHeight int64 + if testCase.includeExtension { + veHeight = 1 + } + ec := voteSet.MakeExtendedCommit(ABCIParams{VoteExtensionsEnableHeight: veHeight}) + + for i := int32(0); int(i) < len(vals); i++ { + vote1 := voteSet.GetByIndex(i) + vote2 := ec.GetExtendedVote(i) + + vote1bz, err := vote1.ToProto().Marshal() + require.NoError(t, err) + vote2bz, err := vote2.ToProto().Marshal() + require.NoError(t, err) + assert.Equal(t, vote1bz, vote2bz) + } + }) + } +} + +// toVoteSet constructs a VoteSet from the Commit and validator set. +// Panics if signatures from the ExtendedCommit can't be added to the voteset. +// Inverse of VoteSet.MakeExtendedCommit(). +func toVoteSet(ec *ExtendedCommit, chainID string, vals *ValidatorSet) *VoteSet { + voteSet := NewVoteSet(chainID, ec.Height, ec.Round, cmtproto.PrecommitType, vals) + ec.addSigsToVoteSet(voteSet) + return voteSet +} + +// TestExtendedCommitToVoteSet tests that the vote set produced from an extended commit +// contains the same vote information as the extended commit. The test ensures +// that the ToVoteSet method behaves as expected, whether vote extensions +// are present in the original votes or not. +func TestExtendedCommitToVoteSet(t *testing.T) { + for _, testCase := range []struct { + name string + includeExtension bool + }{ + { + name: "no extensions", + includeExtension: false, + }, + { + name: "with extensions", + includeExtension: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + lastID := makeBlockIDRandom() + h := int64(3) + + voteSet, valSet, vals := randVoteSet(h-1, 1, cmtproto.PrecommitType, 10, 1, true) + extCommit, err := MakeExtCommit(lastID, h-1, 1, voteSet, vals, time.Now(), true) + assert.NoError(t, err) + + if !testCase.includeExtension { + for i := 0; i < len(vals); i++ { + v := voteSet.GetByIndex(int32(i)) + v.Extension = nil + v.ExtensionSignature = nil + extCommit.ExtendedSignatures[i].Extension = nil + extCommit.ExtendedSignatures[i].ExtensionSignature = nil + } + } + + chainID := voteSet.ChainID() + var voteSet2 *VoteSet + if testCase.includeExtension { + voteSet2 = extCommit.ToExtendedVoteSet(chainID, valSet) + } else { + voteSet2 = toVoteSet(extCommit, chainID, valSet) + } + + for i := int32(0); int(i) < len(vals); i++ { + vote1 := voteSet.GetByIndex(i) + vote2 := voteSet2.GetByIndex(i) + vote3 := extCommit.GetExtendedVote(i) + + vote1bz, err := vote1.ToProto().Marshal() + require.NoError(t, err) + vote2bz, err := vote2.ToProto().Marshal() + require.NoError(t, err) + vote3bz, err := vote3.ToProto().Marshal() + require.NoError(t, err) + assert.Equal(t, vote1bz, vote2bz) + assert.Equal(t, vote1bz, vote3bz) + } + }) + } +} + +func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) { + blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash")) + + const ( + height = int64(3) + round = 0 + ) + + type commitVoteTest struct { + blockIDs []BlockID + numVotes []int // must sum to numValidators + numValidators int + valid bool + } + + testCases := []commitVoteTest{ + {[]BlockID{blockID, {}}, []int{67, 33}, 100, true}, + } + + for _, tc := range testCases { + voteSet, valSet, vals := randVoteSet(height-1, round, cmtproto.PrecommitType, tc.numValidators, 1, false) + + vi := int32(0) + for n := range tc.blockIDs { + for i := 0; i < tc.numVotes[n]; i++ { + pubKey, err := vals[vi].GetPubKey() + require.NoError(t, err) + vote := &Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: vi, + Height: height - 1, + Round: round, + Type: cmtproto.PrecommitType, + BlockID: tc.blockIDs[n], + Timestamp: cmttime.Now(), + } + + added, err := signAddVote(vals[vi], vote, voteSet) + assert.NoError(t, err) + assert.True(t, added) + + vi++ + } + } + + veHeightParam := ABCIParams{VoteExtensionsEnableHeight: 0} + if tc.valid { + extCommit := voteSet.MakeExtendedCommit(veHeightParam) // panics without > 2/3 valid votes + assert.NotNil(t, extCommit) + err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, extCommit.ToCommit()) + assert.Nil(t, err) + } else { + assert.Panics(t, func() { voteSet.MakeExtendedCommit(veHeightParam) }) + } + } +} + +func TestBlockIDValidateBasic(t *testing.T) { + validBlockID := BlockID{ + Hash: bytes.HexBytes{}, + PartSetHeader: PartSetHeader{ + Total: 1, + Hash: bytes.HexBytes{}, + }, + } + + invalidBlockID := BlockID{ + Hash: []byte{0}, + PartSetHeader: PartSetHeader{ + Total: 1, + Hash: []byte{0}, + }, + } + + testCases := []struct { + testName string + blockIDHash bytes.HexBytes + blockIDPartSetHeader PartSetHeader + expectErr bool + }{ + {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false}, + {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true}, + {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + blockID := BlockID{ + Hash: tc.blockIDHash, + PartSetHeader: tc.blockIDPartSetHeader, + } + assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestBlockProtoBuf(t *testing.T) { + h := cmtrand.Int63() + c1 := randCommit(time.Now()) + b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{}) + b1.ProposerAddress = cmtrand.Bytes(crypto.AddressSize) + + b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{}) + b2.ProposerAddress = cmtrand.Bytes(crypto.AddressSize) + evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + evi, err := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain") + require.NoError(t, err) + b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}} + b2.EvidenceHash = b2.Evidence.Hash() + + b3 := MakeBlock(h, []Tx{}, c1, []Evidence{}) + b3.ProposerAddress = cmtrand.Bytes(crypto.AddressSize) + testCases := []struct { + msg string + b1 *Block + expPass bool + expPass2 bool + }{ + {"nil block", nil, false, false}, + {"b1", b1, true, true}, + {"b2", b2, true, true}, + {"b3", b3, true, true}, + } + for _, tc := range testCases { + pb, err := tc.b1.ToProto() + if tc.expPass { + require.NoError(t, err, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + + block, err := BlockFromProto(pb) + if tc.expPass2 { + require.NoError(t, err, tc.msg) + require.EqualValues(t, tc.b1.Header, block.Header, tc.msg) + require.EqualValues(t, tc.b1.Data, block.Data, tc.msg) + require.EqualValues(t, tc.b1.Evidence.Evidence, block.Evidence.Evidence, tc.msg) + require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +func TestDataProtoBuf(t *testing.T) { + data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}} + data2 := &Data{Txs: Txs{}} + testCases := []struct { + msg string + data1 *Data + expPass bool + }{ + {"success", data, true}, + {"success data2", data2, true}, + } + for _, tc := range testCases { + protoData := tc.data1.ToProto() + d, err := DataFromProto(&protoData) + if tc.expPass { + require.NoError(t, err, tc.msg) + require.EqualValues(t, tc.data1, &d, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +// TestEvidenceDataProtoBuf ensures parity in converting to and from proto. +func TestEvidenceDataProtoBuf(t *testing.T) { + const chainID = "mychain" + ev, err := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID) + require.NoError(t, err) + data := &EvidenceData{Evidence: EvidenceList{ev}} + _ = data.ByteSize() + testCases := []struct { + msg string + data1 *EvidenceData + expPass1 bool + expPass2 bool + }{ + {"success", data, true, true}, + {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true}, + {"fail nil Data", nil, false, false}, + } + + for _, tc := range testCases { + protoData, err := tc.data1.ToProto() + if tc.expPass1 { + require.NoError(t, err, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + + eviD := new(EvidenceData) + err = eviD.FromProto(protoData) + if tc.expPass2 { + require.NoError(t, err, tc.msg) + require.Equal(t, tc.data1, eviD, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +func makeRandHeader() Header { + chainID := "test" + t := time.Now() + height := cmtrand.Int63() + randBytes := cmtrand.Bytes(tmhash.Size) + randAddress := cmtrand.Bytes(crypto.AddressSize) + h := Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: chainID, + Height: height, + Time: t, + LastBlockID: BlockID{}, + LastCommitHash: randBytes, + DataHash: randBytes, + ValidatorsHash: randBytes, + NextValidatorsHash: randBytes, + ConsensusHash: randBytes, + AppHash: randBytes, + + LastResultsHash: randBytes, + + EvidenceHash: randBytes, + ProposerAddress: randAddress, + } + + return h +} + +func TestHeaderProto(t *testing.T) { + h1 := makeRandHeader() + tc := []struct { + msg string + h1 *Header + expPass bool + }{ + {"success", &h1, true}, + {"failure empty Header", &Header{}, false}, + } + + for _, tt := range tc { + tt := tt + t.Run(tt.msg, func(t *testing.T) { + pb := tt.h1.ToProto() + h, err := HeaderFromProto(pb) + if tt.expPass { + require.NoError(t, err, tt.msg) + require.Equal(t, tt.h1, &h, tt.msg) + } else { + require.Error(t, err, tt.msg) + } + + }) + } +} + +func TestBlockIDProtoBuf(t *testing.T) { + blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash")) + testCases := []struct { + msg string + bid1 *BlockID + expPass bool + }{ + {"success", &blockID, true}, + {"success empty", &BlockID{}, true}, + {"failure BlockID nil", nil, false}, + } + for _, tc := range testCases { + protoBlockID := tc.bid1.ToProto() + + bi, err := BlockIDFromProto(&protoBlockID) + if tc.expPass { + require.NoError(t, err) + require.Equal(t, tc.bid1, bi, tc.msg) + } else { + require.NotEqual(t, tc.bid1, bi, tc.msg) + } + } +} + +func TestSignedHeaderProtoBuf(t *testing.T) { + commit := randCommit(time.Now()) + h := makeRandHeader() + + sh := SignedHeader{Header: &h, Commit: commit} + + testCases := []struct { + msg string + sh1 *SignedHeader + expPass bool + }{ + {"empty SignedHeader 2", &SignedHeader{}, true}, + {"success", &sh, true}, + {"failure nil", nil, false}, + } + for _, tc := range testCases { + protoSignedHeader := tc.sh1.ToProto() + + sh, err := SignedHeaderFromProto(protoSignedHeader) + + if tc.expPass { + require.NoError(t, err, tc.msg) + require.Equal(t, tc.sh1, sh, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +func TestBlockIDEquals(t *testing.T) { + var ( + blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash")) + blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash")) + blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash")) + blockIDEmpty = BlockID{} + ) + + assert.True(t, blockID.Equals(blockIDDuplicate)) + assert.False(t, blockID.Equals(blockIDDifferent)) + assert.False(t, blockID.Equals(blockIDEmpty)) + assert.True(t, blockIDEmpty.Equals(blockIDEmpty)) + assert.False(t, blockIDEmpty.Equals(blockIDDifferent)) +} diff --git a/types/canonical.go b/types/canonical.go new file mode 100644 index 0000000..b930e3e --- /dev/null +++ b/types/canonical.go @@ -0,0 +1,86 @@ +package types + +import ( + "time" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +// Canonical* wraps the structs in types for amino encoding them for use in SignBytes / the Signable interface. + +// TimeFormat is used for generating the sigs +const TimeFormat = time.RFC3339Nano + +//----------------------------------- +// Canonicalize the structs + +func CanonicalizeBlockID(bid cmtproto.BlockID) *cmtproto.CanonicalBlockID { + rbid, err := BlockIDFromProto(&bid) + if err != nil { + panic(err) + } + var cbid *cmtproto.CanonicalBlockID + if rbid == nil || rbid.IsZero() { + cbid = nil + } else { + cbid = &cmtproto.CanonicalBlockID{ + Hash: bid.Hash, + PartSetHeader: CanonicalizePartSetHeader(bid.PartSetHeader), + } + } + + return cbid +} + +// CanonicalizeVote transforms the given PartSetHeader to a CanonicalPartSetHeader. +func CanonicalizePartSetHeader(psh cmtproto.PartSetHeader) cmtproto.CanonicalPartSetHeader { + return cmtproto.CanonicalPartSetHeader(psh) +} + +// CanonicalizeVote transforms the given Proposal to a CanonicalProposal. +func CanonicalizeProposal(chainID string, proposal *cmtproto.Proposal) cmtproto.CanonicalProposal { + return cmtproto.CanonicalProposal{ + Type: cmtproto.ProposalType, + Height: proposal.Height, // encoded as sfixed64 + Round: int64(proposal.Round), // encoded as sfixed64 + POLRound: int64(proposal.PolRound), + BlockID: CanonicalizeBlockID(proposal.BlockID), + Timestamp: proposal.Timestamp, + ChainID: chainID, + } +} + +// CanonicalizeVote transforms the given Vote to a CanonicalVote, which does +// not contain ValidatorIndex and ValidatorAddress fields, or any fields +// relating to vote extensions. +func CanonicalizeVote(chainID string, vote *cmtproto.Vote) cmtproto.CanonicalVote { + return cmtproto.CanonicalVote{ + Type: vote.Type, + Height: vote.Height, // encoded as sfixed64 + Round: int64(vote.Round), // encoded as sfixed64 + BlockID: CanonicalizeBlockID(vote.BlockID), + Timestamp: vote.Timestamp, + ChainID: chainID, + } +} + +// CanonicalizeVoteExtension extracts the vote extension from the given vote +// and constructs a CanonicalizeVoteExtension struct, whose representation in +// bytes is what is signed in order to produce the vote extension's signature. +func CanonicalizeVoteExtension(chainID string, vote *cmtproto.Vote) cmtproto.CanonicalVoteExtension { + return cmtproto.CanonicalVoteExtension{ + Extension: vote.Extension, + Height: vote.Height, + Round: int64(vote.Round), + ChainId: chainID, + } +} + +// CanonicalTime can be used to stringify time in a canonical way. +func CanonicalTime(t time.Time) string { + // Note that sending time over amino resets it to + // local time, we need to force UTC here, so the + // signatures match + return cmttime.Canonical(t).Format(TimeFormat) +} diff --git a/types/canonical_test.go b/types/canonical_test.go new file mode 100644 index 0000000..bab935f --- /dev/null +++ b/types/canonical_test.go @@ -0,0 +1,39 @@ +package types + +import ( + "reflect" + "testing" + + "github.com/cometbft/cometbft/crypto/tmhash" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +func TestCanonicalizeBlockID(t *testing.T) { + randhash := cmtrand.Bytes(tmhash.Size) + block1 := cmtproto.BlockID{Hash: randhash, + PartSetHeader: cmtproto.PartSetHeader{Total: 5, Hash: randhash}} + block2 := cmtproto.BlockID{Hash: randhash, + PartSetHeader: cmtproto.PartSetHeader{Total: 10, Hash: randhash}} + cblock1 := cmtproto.CanonicalBlockID{Hash: randhash, + PartSetHeader: cmtproto.CanonicalPartSetHeader{Total: 5, Hash: randhash}} + cblock2 := cmtproto.CanonicalBlockID{Hash: randhash, + PartSetHeader: cmtproto.CanonicalPartSetHeader{Total: 10, Hash: randhash}} + + tests := []struct { + name string + args cmtproto.BlockID + want *cmtproto.CanonicalBlockID + }{ + {"first", block1, &cblock1}, + {"second", block2, &cblock2}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + if got := CanonicalizeBlockID(tt.args); !reflect.DeepEqual(got, tt.want) { + t.Errorf("CanonicalizeBlockID() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/types/encoding_helper.go b/types/encoding_helper.go new file mode 100644 index 0000000..9f74583 --- /dev/null +++ b/types/encoding_helper.go @@ -0,0 +1,47 @@ +package types + +import ( + gogotypes "github.com/cosmos/gogoproto/types" + + "github.com/cometbft/cometbft/libs/bytes" +) + +// cdcEncode returns nil if the input is nil, otherwise returns +// proto.Marshal(Value{Value: item}) +func cdcEncode(item interface{}) []byte { + if item != nil && !isTypedNil(item) && !isEmpty(item) { + switch item := item.(type) { + case string: + i := gogotypes.StringValue{ + Value: item, + } + bz, err := i.Marshal() + if err != nil { + return nil + } + return bz + case int64: + i := gogotypes.Int64Value{ + Value: item, + } + bz, err := i.Marshal() + if err != nil { + return nil + } + return bz + case bytes.HexBytes: + i := gogotypes.BytesValue{ + Value: item, + } + bz, err := i.Marshal() + if err != nil { + return nil + } + return bz + default: + return nil + } + } + + return nil +} diff --git a/types/errors.go b/types/errors.go new file mode 100644 index 0000000..dc5f2f0 --- /dev/null +++ b/types/errors.go @@ -0,0 +1,41 @@ +package types + +import "fmt" + +type ( + // ErrInvalidCommitHeight is returned when we encounter a commit with an + // unexpected height. + ErrInvalidCommitHeight struct { + Expected int64 + Actual int64 + } + + // ErrInvalidCommitSignatures is returned when we encounter a commit where + // the number of signatures doesn't match the number of validators. + ErrInvalidCommitSignatures struct { + Expected int + Actual int + } +) + +func NewErrInvalidCommitHeight(expected, actual int64) ErrInvalidCommitHeight { + return ErrInvalidCommitHeight{ + Expected: expected, + Actual: actual, + } +} + +func (e ErrInvalidCommitHeight) Error() string { + return fmt.Sprintf("Invalid commit -- wrong height: %v vs %v", e.Expected, e.Actual) +} + +func NewErrInvalidCommitSignatures(expected, actual int) ErrInvalidCommitSignatures { + return ErrInvalidCommitSignatures{ + Expected: expected, + Actual: actual, + } +} + +func (e ErrInvalidCommitSignatures) Error() string { + return fmt.Sprintf("Invalid commit -- wrong set size: %v vs %v", e.Expected, e.Actual) +} diff --git a/types/event_bus.go b/types/event_bus.go new file mode 100644 index 0000000..24cea50 --- /dev/null +++ b/types/event_bus.go @@ -0,0 +1,310 @@ +package types + +import ( + "context" + "fmt" + + "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + "github.com/cometbft/cometbft/libs/service" +) + +const defaultCapacity = 0 + +type EventBusSubscriber interface { + Subscribe(ctx context.Context, subscriber string, query cmtpubsub.Query, outCapacity ...int) (Subscription, error) + Unsubscribe(ctx context.Context, subscriber string, query cmtpubsub.Query) error + UnsubscribeAll(ctx context.Context, subscriber string) error + + NumClients() int + NumClientSubscriptions(clientID string) int +} + +type Subscription interface { + Out() <-chan cmtpubsub.Message + Canceled() <-chan struct{} + Err() error +} + +// EventBus is a common bus for all events going through the system. All calls +// are proxied to underlying pubsub server. All events must be published using +// EventBus to ensure correct data types. +type EventBus struct { + service.BaseService + pubsub *cmtpubsub.Server +} + +// NewEventBus returns a new event bus. +func NewEventBus() *EventBus { + return NewEventBusWithBufferCapacity(defaultCapacity) +} + +// NewEventBusWithBufferCapacity returns a new event bus with the given buffer capacity. +func NewEventBusWithBufferCapacity(cap int) *EventBus { + // capacity could be exposed later if needed + pubsub := cmtpubsub.NewServer(cmtpubsub.BufferCapacity(cap)) + b := &EventBus{pubsub: pubsub} + b.BaseService = *service.NewBaseService(nil, "EventBus", b) + return b +} + +func (b *EventBus) SetLogger(l log.Logger) { + b.BaseService.SetLogger(l) + b.pubsub.SetLogger(l.With("module", "pubsub")) +} + +func (b *EventBus) OnStart() error { + return b.pubsub.Start() +} + +func (b *EventBus) OnStop() { + if err := b.pubsub.Stop(); err != nil { + b.pubsub.Logger.Error("error trying to stop eventBus", "error", err) + } +} + +func (b *EventBus) NumClients() int { + return b.pubsub.NumClients() +} + +func (b *EventBus) NumClientSubscriptions(clientID string) int { + return b.pubsub.NumClientSubscriptions(clientID) +} + +func (b *EventBus) Subscribe( + ctx context.Context, + subscriber string, + query cmtpubsub.Query, + outCapacity ...int, +) (Subscription, error) { + return b.pubsub.Subscribe(ctx, subscriber, query, outCapacity...) +} + +// This method can be used for a local consensus explorer and synchronous +// testing. Do not use for for public facing / untrusted subscriptions! +func (b *EventBus) SubscribeUnbuffered( + ctx context.Context, + subscriber string, + query cmtpubsub.Query, +) (Subscription, error) { + return b.pubsub.SubscribeUnbuffered(ctx, subscriber, query) +} + +func (b *EventBus) Unsubscribe(ctx context.Context, subscriber string, query cmtpubsub.Query) error { + return b.pubsub.Unsubscribe(ctx, subscriber, query) +} + +func (b *EventBus) UnsubscribeAll(ctx context.Context, subscriber string) error { + return b.pubsub.UnsubscribeAll(ctx, subscriber) +} + +func (b *EventBus) Publish(eventType string, eventData TMEventData) error { + // no explicit deadline for publishing events + ctx := context.Background() + return b.pubsub.PublishWithEvents(ctx, eventData, map[string][]string{EventTypeKey: {eventType}}) +} + +// validateAndStringifyEvents takes a slice of event objects and creates a +// map of stringified events where each key is composed of the event +// type and each of the event's attributes keys in the form of +// "{event.Type}.{attribute.Key}" and the value is each attribute's value. +func (*EventBus) validateAndStringifyEvents(events []types.Event) map[string][]string { + result := make(map[string][]string) + for _, event := range events { + if len(event.Type) == 0 { + continue + } + + for _, attr := range event.Attributes { + if len(attr.Key) == 0 { + continue + } + + compositeTag := fmt.Sprintf("%s.%s", event.Type, attr.Key) + result[compositeTag] = append(result[compositeTag], attr.Value) + } + } + + return result +} + +func (b *EventBus) PublishEventNewBlock(data EventDataNewBlock) error { + // no explicit deadline for publishing events + ctx := context.Background() + events := b.validateAndStringifyEvents(data.ResultFinalizeBlock.Events) + + // add predefined new block event + events[EventTypeKey] = append(events[EventTypeKey], EventNewBlock) + + return b.pubsub.PublishWithEvents(ctx, data, events) +} + +func (b *EventBus) PublishEventNewBlockEvents(data EventDataNewBlockEvents) error { + // no explicit deadline for publishing events + ctx := context.Background() + + events := b.validateAndStringifyEvents(data.Events) + + // add predefined new block event + events[EventTypeKey] = append(events[EventTypeKey], EventNewBlockEvents) + + return b.pubsub.PublishWithEvents(ctx, data, events) +} + +func (b *EventBus) PublishEventNewBlockHeader(data EventDataNewBlockHeader) error { + return b.Publish(EventNewBlockHeader, data) +} + +func (b *EventBus) PublishEventNewEvidence(evidence EventDataNewEvidence) error { + return b.Publish(EventNewEvidence, evidence) +} + +func (b *EventBus) PublishEventVote(data EventDataVote) error { + return b.Publish(EventVote, data) +} + +func (b *EventBus) PublishEventValidBlock(data EventDataRoundState) error { + return b.Publish(EventValidBlock, data) +} + +// PublishEventTx publishes tx event with events from Result. Note it will add +// predefined keys (EventTypeKey, TxHashKey). Existing events with the same keys +// will be overwritten. +func (b *EventBus) PublishEventTx(data EventDataTx) error { + // no explicit deadline for publishing events + ctx := context.Background() + + events := b.validateAndStringifyEvents(data.Result.Events) + + // add predefined compositeKeys + events[EventTypeKey] = append(events[EventTypeKey], EventTx) + events[TxHashKey] = append(events[TxHashKey], fmt.Sprintf("%X", Tx(data.Tx).Hash())) + events[TxHeightKey] = append(events[TxHeightKey], fmt.Sprintf("%d", data.Height)) + + return b.pubsub.PublishWithEvents(ctx, data, events) +} + +func (b *EventBus) PublishEventNewRoundStep(data EventDataRoundState) error { + return b.Publish(EventNewRoundStep, data) +} + +func (b *EventBus) PublishEventTimeoutPropose(data EventDataRoundState) error { + return b.Publish(EventTimeoutPropose, data) +} + +func (b *EventBus) PublishEventTimeoutWait(data EventDataRoundState) error { + return b.Publish(EventTimeoutWait, data) +} + +func (b *EventBus) PublishEventNewRound(data EventDataNewRound) error { + return b.Publish(EventNewRound, data) +} + +func (b *EventBus) PublishEventCompleteProposal(data EventDataCompleteProposal) error { + return b.Publish(EventCompleteProposal, data) +} + +func (b *EventBus) PublishEventPolka(data EventDataRoundState) error { + return b.Publish(EventPolka, data) +} + +func (b *EventBus) PublishEventUnlock(data EventDataRoundState) error { + return b.Publish(EventUnlock, data) +} + +func (b *EventBus) PublishEventRelock(data EventDataRoundState) error { + return b.Publish(EventRelock, data) +} + +func (b *EventBus) PublishEventLock(data EventDataRoundState) error { + return b.Publish(EventLock, data) +} + +func (b *EventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpdates) error { + return b.Publish(EventValidatorSetUpdates, data) +} + +// ----------------------------------------------------------------------------- +type NopEventBus struct{} + +func (NopEventBus) Subscribe( + context.Context, + string, + cmtpubsub.Query, + chan<- interface{}, +) error { + return nil +} + +func (NopEventBus) Unsubscribe(context.Context, string, cmtpubsub.Query) error { + return nil +} + +func (NopEventBus) UnsubscribeAll(context.Context, string) error { + return nil +} + +func (NopEventBus) PublishEventNewBlock(EventDataNewBlock) error { + return nil +} + +func (NopEventBus) PublishEventNewBlockHeader(EventDataNewBlockHeader) error { + return nil +} + +func (NopEventBus) PublishEventNewBlockEvents(EventDataNewBlockEvents) error { + return nil +} + +func (NopEventBus) PublishEventNewEvidence(EventDataNewEvidence) error { + return nil +} + +func (NopEventBus) PublishEventVote(EventDataVote) error { + return nil +} + +func (NopEventBus) PublishEventTx(EventDataTx) error { + return nil +} + +func (NopEventBus) PublishEventNewRoundStep(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventTimeoutPropose(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventTimeoutWait(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventNewRound(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventCompleteProposal(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventPolka(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventUnlock(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventRelock(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventLock(EventDataRoundState) error { + return nil +} + +func (NopEventBus) PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates) error { + return nil +} diff --git a/types/event_bus_test.go b/types/event_bus_test.go new file mode 100644 index 0000000..bb4461d --- /dev/null +++ b/types/event_bus_test.go @@ -0,0 +1,532 @@ +package types + +import ( + "context" + "fmt" + "math/rand" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" +) + +func TestEventBusPublishEventTx(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + tx := Tx("foo") + result := abci.ExecTxResult{ + Data: []byte("bar"), + Events: []abci.Event{ + {Type: "testType", Attributes: []abci.EventAttribute{{Key: "baz", Value: "1"}}}, + }, + } + + // PublishEventTx adds 3 composite keys, so the query below should work + query := fmt.Sprintf("tm.event='Tx' AND tx.height=1 AND tx.hash='%X' AND testType.baz=1", tx.Hash()) + txsSub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.MustCompile(query)) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + msg := <-txsSub.Out() + edt := msg.Data().(EventDataTx) + assert.Equal(t, int64(1), edt.Height) + assert.Equal(t, uint32(0), edt.Index) + assert.EqualValues(t, tx, edt.Tx) + assert.Equal(t, result, edt.Result) + close(done) + }() + + err = eventBus.PublishEventTx(EventDataTx{abci.TxResult{ + Height: 1, + Index: 0, + Tx: tx, + Result: result, + }}) + assert.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatal("did not receive a transaction after 1 sec.") + } +} + +func TestEventBusPublishEventNewBlock(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + block := MakeBlock(0, []Tx{}, nil, []Evidence{}) + resultFinalizeBlock := abci.ResponseFinalizeBlock{ + Events: []abci.Event{ + {Type: "testType", Attributes: []abci.EventAttribute{{Key: "baz", Value: "1"}}}, + }, + } + + // PublishEventNewBlock adds the tm.event compositeKey, so the query below should work + query := "tm.event='NewBlock' AND testType.baz=1" + blocksSub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.MustCompile(query)) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + msg := <-blocksSub.Out() + edt := msg.Data().(EventDataNewBlock) + assert.Equal(t, block, edt.Block) + assert.Equal(t, resultFinalizeBlock, edt.ResultFinalizeBlock) + close(done) + }() + + var ps *PartSet + ps, err = block.MakePartSet(BlockPartSizeBytes) + require.NoError(t, err) + + err = eventBus.PublishEventNewBlock(EventDataNewBlock{ + Block: block, + BlockID: BlockID{ + Hash: block.Hash(), + PartSetHeader: ps.Header(), + }, + ResultFinalizeBlock: resultFinalizeBlock, + }) + assert.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatal("did not receive a block after 1 sec.") + } +} + +func TestEventBusPublishEventTxDuplicateKeys(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + tx := Tx("foo") + result := abci.ExecTxResult{ + Data: []byte("bar"), + Events: []abci.Event{ + { + Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: "sender", Value: "foo"}, + {Key: "recipient", Value: "bar"}, + {Key: "amount", Value: "5"}, + }, + }, + { + Type: "transfer", + Attributes: []abci.EventAttribute{ + {Key: "sender", Value: "baz"}, + {Key: "recipient", Value: "cat"}, + {Key: "amount", Value: "13"}, + }, + }, + { + Type: "withdraw.rewards", + Attributes: []abci.EventAttribute{ + {Key: "address", Value: "bar"}, + {Key: "source", Value: "iceman"}, + {Key: "amount", Value: "33"}, + }, + }, + }, + } + + testCases := []struct { + query string + expectResults bool + }{ + { + "tm.event='Tx' AND tx.height=1 AND transfer.sender='DoesNotExist'", + false, + }, + { + "tm.event='Tx' AND tx.height=1 AND transfer.sender='foo'", + true, + }, + { + "tm.event='Tx' AND tx.height=1 AND transfer.sender='baz'", + true, + }, + { + "tm.event='Tx' AND tx.height=1 AND transfer.sender='foo' AND transfer.sender='baz'", + true, + }, + { + "tm.event='Tx' AND tx.height=1 AND transfer.sender='foo' AND transfer.sender='DoesNotExist'", + false, + }, + } + + for i, tc := range testCases { + sub, err := eventBus.Subscribe(context.Background(), fmt.Sprintf("client-%d", i), cmtquery.MustCompile(tc.query)) + require.NoError(t, err) + + done := make(chan struct{}) + + go func() { + select { + case msg := <-sub.Out(): + data := msg.Data().(EventDataTx) + assert.Equal(t, int64(1), data.Height) + assert.Equal(t, uint32(0), data.Index) + assert.EqualValues(t, tx, data.Tx) + assert.Equal(t, result, data.Result) + close(done) + case <-time.After(1 * time.Second): + return + } + }() + + err = eventBus.PublishEventTx(EventDataTx{abci.TxResult{ + Height: 1, + Index: 0, + Tx: tx, + Result: result, + }}) + assert.NoError(t, err) + + select { + case <-done: + if !tc.expectResults { + require.Fail(t, "unexpected transaction result(s) from subscription") + } + case <-time.After(1 * time.Second): + if tc.expectResults { + require.Fail(t, "failed to receive a transaction after 1 second") + } + } + } +} + +func TestEventBusPublishEventNewBlockHeader(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + block := MakeBlock(0, []Tx{}, nil, []Evidence{}) + // PublishEventNewBlockHeader adds the tm.event compositeKey, so the query below should work + query := "tm.event='NewBlockHeader'" + headersSub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.MustCompile(query)) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + msg := <-headersSub.Out() + edt := msg.Data().(EventDataNewBlockHeader) + assert.Equal(t, block.Header, edt.Header) + close(done) + }() + + err = eventBus.PublishEventNewBlockHeader(EventDataNewBlockHeader{ + Header: block.Header, + }) + assert.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatal("did not receive a block header after 1 sec.") + } +} + +func TestEventBusPublishEventNewBlockEvents(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + // PublishEventNewBlockHeader adds the tm.event compositeKey, so the query below should work + query := "tm.event='NewBlockEvents'" + headersSub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.MustCompile(query)) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + msg := <-headersSub.Out() + edt := msg.Data().(EventDataNewBlockEvents) + assert.Equal(t, int64(1), edt.Height) + close(done) + }() + + err = eventBus.PublishEventNewBlockEvents(EventDataNewBlockEvents{ + Height: 1, + Events: []abci.Event{{ + Type: "transfer", + Attributes: []abci.EventAttribute{{ + Key: "currency", + Value: "ATOM", + }}, + }}, + }) + assert.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatal("did not receive a block header after 1 sec.") + } +} + +func TestEventBusPublishEventNewEvidence(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + ev, err := NewMockDuplicateVoteEvidence(1, time.Now(), "test-chain-id") + require.NoError(t, err) + + query := "tm.event='NewEvidence'" + evSub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.MustCompile(query)) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + msg := <-evSub.Out() + edt := msg.Data().(EventDataNewEvidence) + assert.Equal(t, ev, edt.Evidence) + assert.Equal(t, int64(4), edt.Height) + close(done) + }() + + err = eventBus.PublishEventNewEvidence(EventDataNewEvidence{ + Evidence: ev, + Height: 4, + }) + assert.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatal("did not receive a block header after 1 sec.") + } +} + +func TestEventBusPublish(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + t.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + t.Error(err) + } + }) + + const numEventsExpected = 15 + + sub, err := eventBus.Subscribe(context.Background(), "test", cmtquery.All, numEventsExpected) + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + numEvents := 0 + for range sub.Out() { + numEvents++ + if numEvents >= numEventsExpected { + close(done) + return + } + } + }() + + err = eventBus.Publish(EventNewBlockHeader, EventDataNewBlockHeader{}) + require.NoError(t, err) + err = eventBus.PublishEventNewBlock(EventDataNewBlock{Block: &Block{Header: Header{Height: 1}}}) + require.NoError(t, err) + err = eventBus.PublishEventNewBlockHeader(EventDataNewBlockHeader{}) + require.NoError(t, err) + err = eventBus.PublishEventNewBlockEvents(EventDataNewBlockEvents{Height: 1}) + require.NoError(t, err) + err = eventBus.PublishEventVote(EventDataVote{}) + require.NoError(t, err) + err = eventBus.PublishEventNewRoundStep(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventTimeoutPropose(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventTimeoutWait(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventNewRound(EventDataNewRound{}) + require.NoError(t, err) + err = eventBus.PublishEventCompleteProposal(EventDataCompleteProposal{}) + require.NoError(t, err) + err = eventBus.PublishEventPolka(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventUnlock(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventRelock(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventLock(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates{}) + require.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatalf("expected to receive %d events after 1 sec.", numEventsExpected) + } +} + +func BenchmarkEventBus(b *testing.B) { + benchmarks := []struct { + name string + numClients int + randQueries bool + randEvents bool + }{ + {"10Clients1Query1Event", 10, false, false}, + {"100Clients", 100, false, false}, + {"1000Clients", 1000, false, false}, + + {"10ClientsRandQueries1Event", 10, true, false}, + {"100Clients", 100, true, false}, + {"1000Clients", 1000, true, false}, + + {"10ClientsRandQueriesRandEvents", 10, true, true}, + {"100Clients", 100, true, true}, + {"1000Clients", 1000, true, true}, + + {"10Clients1QueryRandEvents", 10, false, true}, + {"100Clients", 100, false, true}, + {"1000Clients", 1000, false, true}, + } + + for _, bm := range benchmarks { + bm := bm + b.Run(bm.name, func(b *testing.B) { + benchmarkEventBus(bm.numClients, bm.randQueries, bm.randEvents, b) + }) + } +} + +func benchmarkEventBus(numClients int, randQueries bool, randEvents bool, b *testing.B) { + // for random* functions + rnd := rand.New(rand.NewSource(time.Now().Unix())) + + eventBus := NewEventBusWithBufferCapacity(0) // set buffer capacity to 0 so we are not testing cache + err := eventBus.Start() + if err != nil { + b.Error(err) + } + b.Cleanup(func() { + if err := eventBus.Stop(); err != nil { + b.Error(err) + } + }) + + ctx := context.Background() + q := EventQueryNewBlock + + for i := 0; i < numClients; i++ { + if randQueries { + q = randQuery(rnd) + } + sub, err := eventBus.Subscribe(ctx, fmt.Sprintf("client-%d", i), q) + if err != nil { + b.Fatal(err) + } + go func() { + for { + select { + case <-sub.Out(): + case <-sub.Canceled(): + return + } + } + }() + } + + eventType := EventNewBlock + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if randEvents { + eventType = randEvent(rnd) + } + + err := eventBus.Publish(eventType, EventDataString("Gamora")) + if err != nil { + b.Error(err) + } + } +} + +var events = []string{ + EventNewBlock, + EventNewBlockHeader, + EventNewBlockEvents, + EventNewRound, + EventNewRoundStep, + EventTimeoutPropose, + EventCompleteProposal, + EventPolka, + EventUnlock, + EventLock, + EventRelock, + EventTimeoutWait, + EventVote, +} + +func randEvent(r *rand.Rand) string { + return events[r.Intn(len(events))] +} + +var queries = []cmtpubsub.Query{ + EventQueryNewBlock, + EventQueryNewBlockHeader, + EventQueryNewBlockEvents, + EventQueryNewRound, + EventQueryNewRoundStep, + EventQueryTimeoutPropose, + EventQueryCompleteProposal, + EventQueryPolka, + EventQueryUnlock, + EventQueryLock, + EventQueryRelock, + EventQueryTimeoutWait, + EventQueryVote, +} + +func randQuery(r *rand.Rand) cmtpubsub.Query { + return queries[r.Intn(len(queries))] +} diff --git a/types/events.go b/types/events.go new file mode 100644 index 0000000..6f4988a --- /dev/null +++ b/types/events.go @@ -0,0 +1,188 @@ +package types + +import ( + "fmt" + + abci "github.com/cometbft/cometbft/abci/types" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtpubsub "github.com/cometbft/cometbft/libs/pubsub" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" +) + +// Reserved event types (alphabetically sorted). +const ( + // Block level events for mass consumption by users. + // These events are triggered from the state package, + // after a block has been committed. + // These are also used by the tx indexer for async indexing. + // All of this data can be fetched through the rpc. + EventNewBlock = "NewBlock" + EventNewBlockHeader = "NewBlockHeader" + EventNewBlockEvents = "NewBlockEvents" + EventNewEvidence = "NewEvidence" + EventTx = "Tx" + EventValidatorSetUpdates = "ValidatorSetUpdates" + + // Internal consensus events. + // These are used for testing the consensus state machine. + // They can also be used to build real-time consensus visualizers. + EventCompleteProposal = "CompleteProposal" + EventLock = "Lock" + EventNewRound = "NewRound" + EventNewRoundStep = "NewRoundStep" + EventPolka = "Polka" + EventRelock = "Relock" + EventTimeoutPropose = "TimeoutPropose" + EventTimeoutWait = "TimeoutWait" + EventUnlock = "Unlock" + EventValidBlock = "ValidBlock" + EventVote = "Vote" +) + +// ENCODING / DECODING + +// TMEventData implements events.EventData. +type TMEventData interface { + // empty interface +} + +func init() { + cmtjson.RegisterType(EventDataNewBlock{}, "tendermint/event/NewBlock") + cmtjson.RegisterType(EventDataNewBlockHeader{}, "tendermint/event/NewBlockHeader") + cmtjson.RegisterType(EventDataNewBlockEvents{}, "tendermint/event/NewBlockEvents") + cmtjson.RegisterType(EventDataNewEvidence{}, "tendermint/event/NewEvidence") + cmtjson.RegisterType(EventDataTx{}, "tendermint/event/Tx") + cmtjson.RegisterType(EventDataRoundState{}, "tendermint/event/RoundState") + cmtjson.RegisterType(EventDataNewRound{}, "tendermint/event/NewRound") + cmtjson.RegisterType(EventDataCompleteProposal{}, "tendermint/event/CompleteProposal") + cmtjson.RegisterType(EventDataVote{}, "tendermint/event/Vote") + cmtjson.RegisterType(EventDataValidatorSetUpdates{}, "tendermint/event/ValidatorSetUpdates") + cmtjson.RegisterType(EventDataString(""), "tendermint/event/ProposalString") +} + +// Most event messages are basic types (a block, a transaction) +// but some (an input to a call tx or a receive) are more exotic + +type EventDataNewBlock struct { + Block *Block `json:"block"` + BlockID BlockID `json:"block_id"` + ResultFinalizeBlock abci.ResponseFinalizeBlock `json:"result_finalize_block"` +} + +type EventDataNewBlockHeader struct { + Header Header `json:"header"` +} + +type EventDataNewBlockEvents struct { + Height int64 `json:"height"` + Events []abci.Event `json:"events"` + NumTxs int64 `json:"num_txs,string"` // Number of txs in a block +} + +type EventDataNewEvidence struct { + Height int64 `json:"height"` + Evidence Evidence `json:"evidence"` +} + +// All txs fire EventDataTx +type EventDataTx struct { + abci.TxResult +} + +// NOTE: This goes into the replay WAL +type EventDataRoundState struct { + Height int64 `json:"height"` + Round int32 `json:"round"` + Step string `json:"step"` +} + +type ValidatorInfo struct { + Address Address `json:"address"` + Index int32 `json:"index"` +} + +type EventDataNewRound struct { + Height int64 `json:"height"` + Round int32 `json:"round"` + Step string `json:"step"` + + Proposer ValidatorInfo `json:"proposer"` +} + +type EventDataCompleteProposal struct { + Height int64 `json:"height"` + Round int32 `json:"round"` + Step string `json:"step"` + + BlockID BlockID `json:"block_id"` +} + +type EventDataVote struct { + Vote *Vote +} + +type EventDataString string + +type EventDataValidatorSetUpdates struct { + ValidatorUpdates []*Validator `json:"validator_updates"` +} + +// PUBSUB + +const ( + // EventTypeKey is a reserved composite key for event name. + EventTypeKey = "tm.event" + + // TxHashKey is a reserved key, used to specify transaction's hash. + // see EventBus#PublishEventTx + TxHashKey = "tx.hash" + + // TxHeightKey is a reserved key, used to specify transaction block's height. + // see EventBus#PublishEventTx + TxHeightKey = "tx.height" + + // BlockHeightKey is a reserved key used for indexing FinalizeBlock events. + BlockHeightKey = "block.height" +) + +var ( + EventQueryCompleteProposal = QueryForEvent(EventCompleteProposal) + EventQueryLock = QueryForEvent(EventLock) + EventQueryNewBlock = QueryForEvent(EventNewBlock) + EventQueryNewBlockHeader = QueryForEvent(EventNewBlockHeader) + EventQueryNewBlockEvents = QueryForEvent(EventNewBlockEvents) + EventQueryNewEvidence = QueryForEvent(EventNewEvidence) + EventQueryNewRound = QueryForEvent(EventNewRound) + EventQueryNewRoundStep = QueryForEvent(EventNewRoundStep) + EventQueryPolka = QueryForEvent(EventPolka) + EventQueryRelock = QueryForEvent(EventRelock) + EventQueryTimeoutPropose = QueryForEvent(EventTimeoutPropose) + EventQueryTimeoutWait = QueryForEvent(EventTimeoutWait) + EventQueryTx = QueryForEvent(EventTx) + EventQueryUnlock = QueryForEvent(EventUnlock) + EventQueryValidatorSetUpdates = QueryForEvent(EventValidatorSetUpdates) + EventQueryValidBlock = QueryForEvent(EventValidBlock) + EventQueryVote = QueryForEvent(EventVote) +) + +func EventQueryTxFor(tx Tx) cmtpubsub.Query { + return cmtquery.MustCompile(fmt.Sprintf("%s='%s' AND %s='%X'", EventTypeKey, EventTx, TxHashKey, tx.Hash())) +} + +func QueryForEvent(eventType string) cmtpubsub.Query { + return cmtquery.MustCompile(fmt.Sprintf("%s='%s'", EventTypeKey, eventType)) +} + +// BlockEventPublisher publishes all block related events +type BlockEventPublisher interface { + PublishEventNewBlock(block EventDataNewBlock) error + PublishEventNewBlockHeader(header EventDataNewBlockHeader) error + PublishEventNewBlockEvents(events EventDataNewBlockEvents) error + PublishEventNewEvidence(evidence EventDataNewEvidence) error + PublishEventTx(EventDataTx) error + PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates) error +} + +type TxEventPublisher interface { + PublishEventTx(EventDataTx) error +} diff --git a/types/events_test.go b/types/events_test.go new file mode 100644 index 0000000..bf668e5 --- /dev/null +++ b/types/events_test.go @@ -0,0 +1,27 @@ +package types + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQueryTxFor(t *testing.T) { + tx := Tx("foo") + assert.Equal(t, + fmt.Sprintf("tm.event = 'Tx' AND tx.hash = '%X'", tx.Hash()), + EventQueryTxFor(tx).String(), + ) +} + +func TestQueryForEvent(t *testing.T) { + assert.Equal(t, + "tm.event = 'NewBlock'", + QueryForEvent(EventNewBlock).String(), + ) + assert.Equal(t, + "tm.event = 'NewEvidence'", + QueryForEvent(EventNewEvidence).String(), + ) +} diff --git a/types/evidence.go b/types/evidence.go new file mode 100644 index 0000000..cd3c822 --- /dev/null +++ b/types/evidence.go @@ -0,0 +1,637 @@ +package types + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "sort" + "strings" + "time" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// Evidence represents any provable malicious activity by a validator. +// Verification logic for each evidence is part of the evidence module. +type Evidence interface { + ABCI() []abci.Misbehavior // forms individual evidence to be sent to the application + Bytes() []byte // bytes which comprise the evidence + Hash() []byte // hash of the evidence + Height() int64 // height of the infraction + String() string // string format of the evidence + Time() time.Time // time of the infraction + ValidateBasic() error // basic consistency check +} + +//-------------------------------------------------------------------------------------- + +// DuplicateVoteEvidence contains evidence of a single validator signing two conflicting votes. +type DuplicateVoteEvidence struct { + VoteA *Vote `json:"vote_a"` + VoteB *Vote `json:"vote_b"` + + // abci specific information + TotalVotingPower int64 + ValidatorPower int64 + Timestamp time.Time +} + +var _ Evidence = &DuplicateVoteEvidence{} + +// NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given +// two conflicting votes. If either of the votes is nil, the val set is nil or the voter is +// not in the val set, an error is returned +func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet, +) (*DuplicateVoteEvidence, error) { + var voteA, voteB *Vote + if vote1 == nil || vote2 == nil { + return nil, errors.New("missing vote") + } + if valSet == nil { + return nil, errors.New("missing validator set") + } + idx, val := valSet.GetByAddress(vote1.ValidatorAddress) + if idx == -1 { + return nil, fmt.Errorf("validator %s not in validator set", vote1.ValidatorAddress.String()) + } + + if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 { + voteA = vote1 + voteB = vote2 + } else { + voteA = vote2 + voteB = vote1 + } + return &DuplicateVoteEvidence{ + VoteA: voteA, + VoteB: voteB, + TotalVotingPower: valSet.TotalVotingPower(), + ValidatorPower: val.VotingPower, + Timestamp: blockTime, + }, nil +} + +// ABCI returns the application relevant representation of the evidence +func (dve *DuplicateVoteEvidence) ABCI() []abci.Misbehavior { + return []abci.Misbehavior{{ + Type: abci.MisbehaviorType_DUPLICATE_VOTE, + Validator: abci.Validator{ + Address: dve.VoteA.ValidatorAddress, + Power: dve.ValidatorPower, + }, + Height: dve.VoteA.Height, + Time: dve.Timestamp, + TotalVotingPower: dve.TotalVotingPower, + }} +} + +// Bytes returns the proto-encoded evidence as a byte array. +func (dve *DuplicateVoteEvidence) Bytes() []byte { + pbe := dve.ToProto() + bz, err := pbe.Marshal() + if err != nil { + panic(err) + } + + return bz +} + +// Hash returns the hash of the evidence. +func (dve *DuplicateVoteEvidence) Hash() []byte { + return tmhash.Sum(dve.Bytes()) +} + +// Height returns the height of the infraction +func (dve *DuplicateVoteEvidence) Height() int64 { + return dve.VoteA.Height +} + +// String returns a string representation of the evidence. +func (dve *DuplicateVoteEvidence) String() string { + return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB) +} + +// Time returns the time of the infraction +func (dve *DuplicateVoteEvidence) Time() time.Time { + return dve.Timestamp +} + +// ValidateBasic performs basic validation. +func (dve *DuplicateVoteEvidence) ValidateBasic() error { + if dve == nil { + return errors.New("empty duplicate vote evidence") + } + + if dve.VoteA == nil || dve.VoteB == nil { + return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB) + } + if err := dve.VoteA.ValidateBasic(); err != nil { + return fmt.Errorf("invalid VoteA: %w", err) + } + if err := dve.VoteB.ValidateBasic(); err != nil { + return fmt.Errorf("invalid VoteB: %w", err) + } + // Enforce Votes are lexicographically sorted on blockID + if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 { + return errors.New("duplicate votes in invalid order") + } + return nil +} + +// ToProto encodes DuplicateVoteEvidence to protobuf +func (dve *DuplicateVoteEvidence) ToProto() *cmtproto.DuplicateVoteEvidence { + voteB := dve.VoteB.ToProto() + voteA := dve.VoteA.ToProto() + tp := cmtproto.DuplicateVoteEvidence{ + VoteA: voteA, + VoteB: voteB, + TotalVotingPower: dve.TotalVotingPower, + ValidatorPower: dve.ValidatorPower, + Timestamp: dve.Timestamp, + } + return &tp +} + +// DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence +func DuplicateVoteEvidenceFromProto(pb *cmtproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) { + if pb == nil { + return nil, errors.New("nil duplicate vote evidence") + } + + var vA *Vote + if pb.VoteA != nil { + var err error + vA, err = VoteFromProto(pb.VoteA) + if err != nil { + return nil, err + } + if err = vA.ValidateBasic(); err != nil { + return nil, err + } + } + + var vB *Vote + if pb.VoteB != nil { + var err error + vB, err = VoteFromProto(pb.VoteB) + if err != nil { + return nil, err + } + if err = vB.ValidateBasic(); err != nil { + return nil, err + } + } + + dve := &DuplicateVoteEvidence{ + VoteA: vA, + VoteB: vB, + TotalVotingPower: pb.TotalVotingPower, + ValidatorPower: pb.ValidatorPower, + Timestamp: pb.Timestamp, + } + + return dve, dve.ValidateBasic() +} + +//------------------------------------ LIGHT EVIDENCE -------------------------------------- + +// LightClientAttackEvidence is a generalized evidence that captures all forms of known attacks on +// a light client such that a full node can verify, propose and commit the evidence on-chain for +// punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation +// and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at +// cometbft/docs/architecture/adr-047-handling-evidence-from-light-client.md +type LightClientAttackEvidence struct { + ConflictingBlock *LightBlock + CommonHeight int64 + + // abci specific information + ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block + TotalVotingPower int64 // total voting power of the validator set at the common height + Timestamp time.Time // timestamp of the block at the common height +} + +var _ Evidence = &LightClientAttackEvidence{} + +// ABCI forms an array of abci.Misbehavior for each byzantine validator +func (l *LightClientAttackEvidence) ABCI() []abci.Misbehavior { + abciEv := make([]abci.Misbehavior, len(l.ByzantineValidators)) + for idx, val := range l.ByzantineValidators { + abciEv[idx] = abci.Misbehavior{ + Type: abci.MisbehaviorType_LIGHT_CLIENT_ATTACK, + Validator: TM2PB.Validator(val), + Height: l.Height(), + Time: l.Timestamp, + TotalVotingPower: l.TotalVotingPower, + } + } + return abciEv +} + +// Bytes returns the proto-encoded evidence as a byte array +func (l *LightClientAttackEvidence) Bytes() []byte { + pbe, err := l.ToProto() + if err != nil { + panic(err) + } + bz, err := pbe.Marshal() + if err != nil { + panic(err) + } + return bz +} + +// GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who +// the malicious validators were and returns them. This is used both for forming the ByzantineValidators +// field and for validating that it is correct. Validators are ordered based on validator power +func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet, + trusted *SignedHeader) []*Validator { + var validators []*Validator + // First check if the header is invalid. This means that it is a lunatic attack and therefore we take the + // validators who are in the commonVals and voted for the lunatic header + if l.ConflictingHeaderIsInvalid(trusted.Header) { + for _, commitSig := range l.ConflictingBlock.Commit.Signatures { + if commitSig.BlockIDFlag != BlockIDFlagCommit { + continue + } + + _, val := commonVals.GetByAddress(commitSig.ValidatorAddress) + if val == nil { + // validator wasn't in the common validator set + continue + } + validators = append(validators, val) + } + sort.Sort(ValidatorsByVotingPower(validators)) + return validators + } else if trusted.Commit.Round == l.ConflictingBlock.Commit.Round { + // This is an equivocation attack as both commits are in the same round. We then find the validators + // from the conflicting light block validator set that voted in both headers. + // Validator hashes are the same therefore the indexing order of validators are the same and thus we + // only need a single loop to find the validators that voted twice. + for i := 0; i < len(l.ConflictingBlock.Commit.Signatures); i++ { + sigA := l.ConflictingBlock.Commit.Signatures[i] + if sigA.BlockIDFlag != BlockIDFlagCommit { + continue + } + + sigB := trusted.Commit.Signatures[i] + if sigB.BlockIDFlag != BlockIDFlagCommit { + continue + } + + _, val := l.ConflictingBlock.ValidatorSet.GetByAddress(sigA.ValidatorAddress) + validators = append(validators, val) + } + sort.Sort(ValidatorsByVotingPower(validators)) + return validators + } + // if the rounds are different then this is an amnesia attack. Unfortunately, given the nature of the attack, + // we aren't able yet to deduce which are malicious validators and which are not hence we return an + // empty validator set. + return validators +} + +// ConflictingHeaderIsInvalid takes a trusted header and matches it againt a conflicting header +// to determine whether the conflicting header was the product of a valid state transition +// or not. If it is then all the deterministic fields of the header should be the same. +// If not, it is an invalid header and constitutes a lunatic attack. +func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *Header) bool { + return !bytes.Equal(trustedHeader.ValidatorsHash, l.ConflictingBlock.ValidatorsHash) || + !bytes.Equal(trustedHeader.NextValidatorsHash, l.ConflictingBlock.NextValidatorsHash) || + !bytes.Equal(trustedHeader.ConsensusHash, l.ConflictingBlock.ConsensusHash) || + !bytes.Equal(trustedHeader.AppHash, l.ConflictingBlock.AppHash) || + !bytes.Equal(trustedHeader.LastResultsHash, l.ConflictingBlock.LastResultsHash) + +} + +// Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions +// with evidence that have the same conflicting header and common height but different permutations +// of validator commit signatures. The reason for this is that we don't want to allow several +// permutations of the same evidence to be committed on chain. Ideally we commit the header with the +// most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is +// sufficient. +// TODO: We should change the hash to include the commit, header, total voting power, byzantine +// validators and timestamp +func (l *LightClientAttackEvidence) Hash() []byte { + buf := make([]byte, binary.MaxVarintLen64) + n := binary.PutVarint(buf, l.CommonHeight) + bz := make([]byte, tmhash.Size+n) + copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes()) + copy(bz[tmhash.Size:], buf) + return tmhash.Sum(bz) +} + +// Height returns the last height at which the primary provider and witness provider had the same header. +// We use this as the height of the infraction rather than the actual conflicting header because we know +// that the malicious validators were bonded at this height which is important for evidence expiry +func (l *LightClientAttackEvidence) Height() int64 { + return l.CommonHeight +} + +// String returns a string representation of LightClientAttackEvidence +func (l *LightClientAttackEvidence) String() string { + return fmt.Sprintf(`LightClientAttackEvidence{ + ConflictingBlock: %v, + CommonHeight: %d, + ByzatineValidators: %v, + TotalVotingPower: %d, + Timestamp: %v}#%X`, + l.ConflictingBlock.String(), l.CommonHeight, l.ByzantineValidators, + l.TotalVotingPower, l.Timestamp, l.Hash()) +} + +// Time returns the time of the common block where the infraction leveraged off. +func (l *LightClientAttackEvidence) Time() time.Time { + return l.Timestamp +} + +// ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification. +func (l *LightClientAttackEvidence) ValidateBasic() error { + if l.ConflictingBlock == nil { + return errors.New("conflicting block is nil") + } + + // this check needs to be done before we can run validate basic + if l.ConflictingBlock.Header == nil { + return errors.New("conflicting block missing header") + } + + if l.TotalVotingPower <= 0 { + return errors.New("negative or zero total voting power") + } + + if l.CommonHeight <= 0 { + return errors.New("negative or zero common height") + } + + // check that common height isn't ahead of the height of the conflicting block. It + // is possible that they are the same height if the light node witnesses either an + // amnesia or a equivocation attack. + if l.CommonHeight > l.ConflictingBlock.Height { + return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)", + l.CommonHeight, l.ConflictingBlock.Height) + } + + if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil { + return fmt.Errorf("invalid conflicting light block: %w", err) + } + + return nil +} + +// ToProto encodes LightClientAttackEvidence to protobuf +func (l *LightClientAttackEvidence) ToProto() (*cmtproto.LightClientAttackEvidence, error) { + conflictingBlock, err := l.ConflictingBlock.ToProto() + if err != nil { + return nil, err + } + + byzVals := make([]*cmtproto.Validator, len(l.ByzantineValidators)) + for idx, val := range l.ByzantineValidators { + valpb, err := val.ToProto() + if err != nil { + return nil, err + } + byzVals[idx] = valpb + } + + return &cmtproto.LightClientAttackEvidence{ + ConflictingBlock: conflictingBlock, + CommonHeight: l.CommonHeight, + ByzantineValidators: byzVals, + TotalVotingPower: l.TotalVotingPower, + Timestamp: l.Timestamp, + }, nil +} + +// LightClientAttackEvidenceFromProto decodes protobuf +func LightClientAttackEvidenceFromProto(lpb *cmtproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) { + if lpb == nil { + return nil, errors.New("empty light client attack evidence") + } + + conflictingBlock, err := LightBlockFromProto(lpb.ConflictingBlock) + if err != nil { + return nil, err + } + + byzVals := make([]*Validator, len(lpb.ByzantineValidators)) + for idx, valpb := range lpb.ByzantineValidators { + val, err := ValidatorFromProto(valpb) + if err != nil { + return nil, err + } + byzVals[idx] = val + } + + l := &LightClientAttackEvidence{ + ConflictingBlock: conflictingBlock, + CommonHeight: lpb.CommonHeight, + ByzantineValidators: byzVals, + TotalVotingPower: lpb.TotalVotingPower, + Timestamp: lpb.Timestamp, + } + + return l, l.ValidateBasic() +} + +//------------------------------------------------------------------------------------------ + +// EvidenceList is a list of Evidence. Evidences is not a word. +type EvidenceList []Evidence + +// Hash returns the simple merkle root hash of the EvidenceList. +func (evl EvidenceList) Hash() []byte { + // These allocations are required because Evidence is not of type Bytes, and + // golang slices can't be typed cast. This shouldn't be a performance problem since + // the Evidence size is capped. + evidenceBzs := make([][]byte, len(evl)) + for i := 0; i < len(evl); i++ { + // TODO: We should change this to the hash. Using bytes contains some unexported data that + // may cause different hashes + evidenceBzs[i] = evl[i].Bytes() + } + return merkle.HashFromByteSlices(evidenceBzs) +} + +func (evl EvidenceList) String() string { + s := "" + for _, e := range evl { + s += fmt.Sprintf("%s\t\t", e) + } + return s +} + +// Has returns true if the evidence is in the EvidenceList. +func (evl EvidenceList) Has(evidence Evidence) bool { + for _, ev := range evl { + if bytes.Equal(evidence.Hash(), ev.Hash()) { + return true + } + } + return false +} + +// ToABCI converts the evidence list to a slice of the ABCI protobuf messages +// for use when communicating the evidence to an application. +func (evl EvidenceList) ToABCI() []abci.Misbehavior { + var el []abci.Misbehavior + for _, e := range evl { + el = append(el, e.ABCI()...) + } + return el +} + +//------------------------------------------ PROTO -------------------------------------- + +// EvidenceToProto is a generalized function for encoding evidence that conforms to the +// evidence interface to protobuf +func EvidenceToProto(evidence Evidence) (*cmtproto.Evidence, error) { + if evidence == nil { + return nil, errors.New("nil evidence") + } + + switch evi := evidence.(type) { + case *DuplicateVoteEvidence: + pbev := evi.ToProto() + return &cmtproto.Evidence{ + Sum: &cmtproto.Evidence_DuplicateVoteEvidence{ + DuplicateVoteEvidence: pbev, + }, + }, nil + + case *LightClientAttackEvidence: + pbev, err := evi.ToProto() + if err != nil { + return nil, err + } + return &cmtproto.Evidence{ + Sum: &cmtproto.Evidence_LightClientAttackEvidence{ + LightClientAttackEvidence: pbev, + }, + }, nil + + default: + return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi) + } +} + +// EvidenceFromProto is a generalized function for decoding protobuf into the +// evidence interface +func EvidenceFromProto(evidence *cmtproto.Evidence) (Evidence, error) { + if evidence == nil { + return nil, errors.New("nil evidence") + } + + switch evi := evidence.Sum.(type) { + case *cmtproto.Evidence_DuplicateVoteEvidence: + return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence) + case *cmtproto.Evidence_LightClientAttackEvidence: + return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence) + default: + return nil, errors.New("evidence is not recognized") + } +} + +func init() { + cmtjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence") + cmtjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence") +} + +//-------------------------------------------- ERRORS -------------------------------------- + +// ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid. +type ErrInvalidEvidence struct { + Evidence Evidence + Reason error +} + +// NewErrInvalidEvidence returns a new EvidenceInvalid with the given err. +func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence { + return &ErrInvalidEvidence{ev, err} +} + +// Error returns a string representation of the error. +func (err *ErrInvalidEvidence) Error() string { + return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence) +} + +// ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes. +type ErrEvidenceOverflow struct { + Max int64 + Got int64 +} + +// NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max. +func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow { + return &ErrEvidenceOverflow{max, got} +} + +// Error returns a string representation of the error. +func (err *ErrEvidenceOverflow) Error() string { + return fmt.Sprintf("Too much evidence: Max %d, got %d", err.Max, err.Got) +} + +//-------------------------------------------- MOCKING -------------------------------------- + +// unstable - use only for testing + +// assumes the round to be 0 and the validator index to be 0 +func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) (*DuplicateVoteEvidence, error) { + val := NewMockPV() + return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID) +} + +// assumes voting power to be 10 and validator to be the only one in the set +func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time, + pv PrivValidator, chainID string) (*DuplicateVoteEvidence, error) { + pubKey, err := pv.GetPubKey() + if err != nil { + return nil, err + } + val := NewValidator(pubKey, 10) + voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time) + vA := voteA.ToProto() + err = pv.SignVote(chainID, vA) + if err != nil { + return nil, err + } + voteA.Signature = vA.Signature + voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time) + vB := voteB.ToProto() + err = pv.SignVote(chainID, vB) + if err != nil { + return nil, err + } + voteB.Signature = vB.Signature + return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val})) +} + +func makeMockVote(height int64, round, index int32, addr Address, + blockID BlockID, time time.Time) *Vote { + return &Vote{ + Type: cmtproto.SignedMsgType(2), + Height: height, + Round: round, + BlockID: blockID, + Timestamp: time, + ValidatorAddress: addr, + ValidatorIndex: index, + } +} + +func randBlockID() BlockID { + return BlockID{ + Hash: cmtrand.Bytes(tmhash.Size), + PartSetHeader: PartSetHeader{ + Total: 1, + Hash: cmtrand.Bytes(tmhash.Size), + }, + } +} diff --git a/types/evidence_test.go b/types/evidence_test.go new file mode 100644 index 0000000..d44fbc7 --- /dev/null +++ b/types/evidence_test.go @@ -0,0 +1,312 @@ +package types + +import ( + "math" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/version" +) + +var defaultVoteTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) + +func TestEvidenceList(t *testing.T) { + ev := randomDuplicateVoteEvidence(t) + evl := EvidenceList([]Evidence{ev}) + + assert.NotNil(t, evl.Hash()) + assert.True(t, evl.Has(ev)) + assert.False(t, evl.Has(&DuplicateVoteEvidence{})) +} + +func randomDuplicateVoteEvidence(t *testing.T) *DuplicateVoteEvidence { + val := NewMockPV() + blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash")) + blockID2 := makeBlockID([]byte("blockhash2"), 1000, []byte("partshash")) + const chainID = "mychain" + return &DuplicateVoteEvidence{ + VoteA: MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID, defaultVoteTime), + VoteB: MakeVoteNoError(t, val, chainID, 0, 10, 2, 1, blockID2, defaultVoteTime.Add(1*time.Minute)), + TotalVotingPower: 30, + ValidatorPower: 10, + Timestamp: defaultVoteTime, + } +} + +func TestDuplicateVoteEvidence(t *testing.T) { + const height = int64(13) + ev, err := NewMockDuplicateVoteEvidence(height, time.Now(), "mock-chain-id") + require.NoError(t, err) + assert.Equal(t, ev.Hash(), tmhash.Sum(ev.Bytes())) + assert.NotNil(t, ev.String()) + assert.Equal(t, ev.Height(), height) +} + +func TestDuplicateVoteEvidenceValidation(t *testing.T) { + val := NewMockPV() + blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + blockID2 := makeBlockID(tmhash.Sum([]byte("blockhash2")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + const chainID = "mychain" + + testCases := []struct { + testName string + malleateEvidence func(*DuplicateVoteEvidence) + expectErr bool + }{ + {"Good DuplicateVoteEvidence", func(ev *DuplicateVoteEvidence) {}, false}, + {"Nil vote A", func(ev *DuplicateVoteEvidence) { ev.VoteA = nil }, true}, + {"Nil vote B", func(ev *DuplicateVoteEvidence) { ev.VoteB = nil }, true}, + {"Nil votes", func(ev *DuplicateVoteEvidence) { + ev.VoteA = nil + ev.VoteB = nil + }, true}, + {"Invalid vote type", func(ev *DuplicateVoteEvidence) { + ev.VoteA = MakeVoteNoError(t, val, chainID, math.MaxInt32, math.MaxInt64, math.MaxInt32, 0, blockID2, defaultVoteTime) + }, true}, + {"Invalid vote order", func(ev *DuplicateVoteEvidence) { + swap := ev.VoteA.Copy() + ev.VoteA = ev.VoteB.Copy() + ev.VoteB = swap + }, true}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + vote1 := MakeVoteNoError(t, val, chainID, math.MaxInt32, math.MaxInt64, math.MaxInt32, 0x02, blockID, defaultVoteTime) + vote2 := MakeVoteNoError(t, val, chainID, math.MaxInt32, math.MaxInt64, math.MaxInt32, 0x02, blockID2, defaultVoteTime) + valSet := NewValidatorSet([]*Validator{val.ExtractIntoValidator(10)}) + ev, err := NewDuplicateVoteEvidence(vote1, vote2, defaultVoteTime, valSet) + require.NoError(t, err) + tc.malleateEvidence(ev) + assert.Equal(t, tc.expectErr, ev.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestLightClientAttackEvidenceBasic(t *testing.T) { + height := int64(5) + commonHeight := height - 1 + nValidators := 10 + voteSet, valSet, privVals := randVoteSet(height, 1, cmtproto.PrecommitType, nValidators, 1, false) + header := makeHeaderRandom() + header.Height = height + blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + extCommit, err := MakeExtCommit(blockID, height, 1, voteSet, privVals, defaultVoteTime, false) + require.NoError(t, err) + commit := extCommit.ToCommit() + + lcae := &LightClientAttackEvidence{ + ConflictingBlock: &LightBlock{ + SignedHeader: &SignedHeader{ + Header: header, + Commit: commit, + }, + ValidatorSet: valSet, + }, + CommonHeight: commonHeight, + TotalVotingPower: valSet.TotalVotingPower(), + Timestamp: header.Time, + ByzantineValidators: valSet.Validators[:nValidators/2], + } + assert.NotNil(t, lcae.String()) + assert.NotNil(t, lcae.Hash()) + assert.Equal(t, lcae.Height(), commonHeight) // Height should be the common Height + assert.NotNil(t, lcae.Bytes()) + + // maleate evidence to test hash uniqueness + testCases := []struct { + testName string + malleateEvidence func(*LightClientAttackEvidence) + }{ + {"Different header", func(ev *LightClientAttackEvidence) { ev.ConflictingBlock.Header = makeHeaderRandom() }}, + {"Different common height", func(ev *LightClientAttackEvidence) { + ev.CommonHeight = height + 1 + }}, + } + + for _, tc := range testCases { + lcae := &LightClientAttackEvidence{ + ConflictingBlock: &LightBlock{ + SignedHeader: &SignedHeader{ + Header: header, + Commit: commit, + }, + ValidatorSet: valSet, + }, + CommonHeight: commonHeight, + TotalVotingPower: valSet.TotalVotingPower(), + Timestamp: header.Time, + ByzantineValidators: valSet.Validators[:nValidators/2], + } + hash := lcae.Hash() + tc.malleateEvidence(lcae) + assert.NotEqual(t, hash, lcae.Hash(), tc.testName) + } +} + +func TestLightClientAttackEvidenceValidation(t *testing.T) { + height := int64(5) + commonHeight := height - 1 + nValidators := 10 + voteSet, valSet, privVals := randVoteSet(height, 1, cmtproto.PrecommitType, nValidators, 1, false) + header := makeHeaderRandom() + header.Height = height + header.ValidatorsHash = valSet.Hash() + blockID := makeBlockID(header.Hash(), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + extCommit, err := MakeExtCommit(blockID, height, 1, voteSet, privVals, time.Now(), false) + require.NoError(t, err) + commit := extCommit.ToCommit() + + lcae := &LightClientAttackEvidence{ + ConflictingBlock: &LightBlock{ + SignedHeader: &SignedHeader{ + Header: header, + Commit: commit, + }, + ValidatorSet: valSet, + }, + CommonHeight: commonHeight, + TotalVotingPower: valSet.TotalVotingPower(), + Timestamp: header.Time, + ByzantineValidators: valSet.Validators[:nValidators/2], + } + assert.NoError(t, lcae.ValidateBasic()) + + testCases := []struct { + testName string + malleateEvidence func(*LightClientAttackEvidence) + expectErr bool + }{ + {"Good LightClientAttackEvidence", func(ev *LightClientAttackEvidence) {}, false}, + {"Negative height", func(ev *LightClientAttackEvidence) { ev.CommonHeight = -10 }, true}, + {"Height is greater than divergent block", func(ev *LightClientAttackEvidence) { + ev.CommonHeight = height + 1 + }, true}, + {"Height is equal to the divergent block", func(ev *LightClientAttackEvidence) { + ev.CommonHeight = height + }, false}, + {"Nil conflicting header", func(ev *LightClientAttackEvidence) { ev.ConflictingBlock.Header = nil }, true}, + {"Nil conflicting blocl", func(ev *LightClientAttackEvidence) { ev.ConflictingBlock = nil }, true}, + {"Nil validator set", func(ev *LightClientAttackEvidence) { + ev.ConflictingBlock.ValidatorSet = &ValidatorSet{} + }, true}, + {"Negative total voting power", func(ev *LightClientAttackEvidence) { + ev.TotalVotingPower = -1 + }, true}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + lcae := &LightClientAttackEvidence{ + ConflictingBlock: &LightBlock{ + SignedHeader: &SignedHeader{ + Header: header, + Commit: commit, + }, + ValidatorSet: valSet, + }, + CommonHeight: commonHeight, + TotalVotingPower: valSet.TotalVotingPower(), + Timestamp: header.Time, + ByzantineValidators: valSet.Validators[:nValidators/2], + } + tc.malleateEvidence(lcae) + if tc.expectErr { + assert.Error(t, lcae.ValidateBasic(), tc.testName) + } else { + assert.NoError(t, lcae.ValidateBasic(), tc.testName) + } + }) + } + +} + +func TestMockEvidenceValidateBasic(t *testing.T) { + goodEvidence, err := NewMockDuplicateVoteEvidence(int64(1), time.Now(), "mock-chain-id") + require.NoError(t, err) + assert.Nil(t, goodEvidence.ValidateBasic()) +} + +func makeHeaderRandom() *Header { + return &Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 1}, + ChainID: cmtrand.Str(12), + Height: int64(cmtrand.Uint16()) + 1, + Time: time.Now(), + LastBlockID: makeBlockIDRandom(), + LastCommitHash: crypto.CRandBytes(tmhash.Size), + DataHash: crypto.CRandBytes(tmhash.Size), + ValidatorsHash: crypto.CRandBytes(tmhash.Size), + NextValidatorsHash: crypto.CRandBytes(tmhash.Size), + ConsensusHash: crypto.CRandBytes(tmhash.Size), + AppHash: crypto.CRandBytes(tmhash.Size), + LastResultsHash: crypto.CRandBytes(tmhash.Size), + EvidenceHash: crypto.CRandBytes(tmhash.Size), + ProposerAddress: crypto.CRandBytes(crypto.AddressSize), + } +} + +func TestEvidenceProto(t *testing.T) { + // -------- Votes -------- + val := NewMockPV() + blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + blockID2 := makeBlockID(tmhash.Sum([]byte("blockhash2")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + const chainID = "mychain" + v := MakeVoteNoError(t, val, chainID, math.MaxInt32, math.MaxInt64, 1, 0x01, blockID, defaultVoteTime) + v2 := MakeVoteNoError(t, val, chainID, math.MaxInt32, math.MaxInt64, 2, 0x01, blockID2, defaultVoteTime) + + // -------- SignedHeaders -------- + const height int64 = 37 + + var ( + header1 = makeHeaderRandom() + header2 = makeHeaderRandom() + ) + + header1.Height = height + header1.LastBlockID = blockID + header1.ChainID = chainID + + header2.Height = height + header2.LastBlockID = blockID + header2.ChainID = chainID + + tests := []struct { + testName string + evidence Evidence + toProtoErr bool + fromProtoErr bool + }{ + {"nil fail", nil, true, true}, + {"DuplicateVoteEvidence empty fail", &DuplicateVoteEvidence{}, false, true}, + {"DuplicateVoteEvidence nil voteB", &DuplicateVoteEvidence{VoteA: v, VoteB: nil}, false, true}, + {"DuplicateVoteEvidence nil voteA", &DuplicateVoteEvidence{VoteA: nil, VoteB: v}, false, true}, + {"DuplicateVoteEvidence success", &DuplicateVoteEvidence{VoteA: v2, VoteB: v}, false, false}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.testName, func(t *testing.T) { + pb, err := EvidenceToProto(tt.evidence) + if tt.toProtoErr { + assert.Error(t, err, tt.testName) + return + } + assert.NoError(t, err, tt.testName) + + evi, err := EvidenceFromProto(pb) + if tt.fromProtoErr { + assert.Error(t, err, tt.testName) + return + } + require.Equal(t, tt.evidence, evi, tt.testName) + }) + } +} diff --git a/types/genesis.go b/types/genesis.go new file mode 100644 index 0000000..e415142 --- /dev/null +++ b/types/genesis.go @@ -0,0 +1,137 @@ +package types + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "time" + + "github.com/cometbft/cometbft/crypto" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtos "github.com/cometbft/cometbft/libs/os" + cmttime "github.com/cometbft/cometbft/types/time" +) + +const ( + // MaxChainIDLen is a maximum length of the chain ID. + MaxChainIDLen = 50 +) + +//------------------------------------------------------------ +// core types for a genesis definition +// NOTE: any changes to the genesis definition should +// be reflected in the documentation: +// docs/core/using-cometbft.md + +// GenesisValidator is an initial validator. +type GenesisValidator struct { + Address Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` + Power int64 `json:"power"` + Name string `json:"name"` +} + +// GenesisDoc defines the initial conditions for a CometBFT blockchain, in particular its validator set. +type GenesisDoc struct { + GenesisTime time.Time `json:"genesis_time"` + ChainID string `json:"chain_id"` + InitialHeight int64 `json:"initial_height"` + ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` + Validators []GenesisValidator `json:"validators,omitempty"` + AppHash cmtbytes.HexBytes `json:"app_hash"` + AppState json.RawMessage `json:"app_state,omitempty"` +} + +// SaveAs is a utility method for saving GenensisDoc as a JSON file. +func (genDoc *GenesisDoc) SaveAs(file string) error { + genDocBytes, err := cmtjson.MarshalIndent(genDoc, "", " ") + if err != nil { + return err + } + return cmtos.WriteFile(file, genDocBytes, 0644) +} + +// ValidatorHash returns the hash of the validator set contained in the GenesisDoc +func (genDoc *GenesisDoc) ValidatorHash() []byte { + vals := make([]*Validator, len(genDoc.Validators)) + for i, v := range genDoc.Validators { + vals[i] = NewValidator(v.PubKey, v.Power) + } + vset := NewValidatorSet(vals) + return vset.Hash() +} + +// ValidateAndComplete checks that all necessary fields are present +// and fills in defaults for optional fields left empty +func (genDoc *GenesisDoc) ValidateAndComplete() error { + if genDoc.ChainID == "" { + return errors.New("genesis doc must include non-empty chain_id") + } + if len(genDoc.ChainID) > MaxChainIDLen { + return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen) + } + if genDoc.InitialHeight < 0 { + return fmt.Errorf("initial_height cannot be negative (got %v)", genDoc.InitialHeight) + } + if genDoc.InitialHeight == 0 { + genDoc.InitialHeight = 1 + } + + if genDoc.ConsensusParams == nil { + genDoc.ConsensusParams = DefaultConsensusParams() + } else if err := genDoc.ConsensusParams.ValidateBasic(); err != nil { + return err + } + + for i, v := range genDoc.Validators { + if v.Power == 0 { + return fmt.Errorf("the genesis file cannot contain validators with no voting power: %v", v) + } + if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) { + return fmt.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address()) + } + if len(v.Address) == 0 { + genDoc.Validators[i].Address = v.PubKey.Address() + } + } + + if genDoc.GenesisTime.IsZero() { + genDoc.GenesisTime = cmttime.Now() + } + + return nil +} + +//------------------------------------------------------------ +// Make genesis state from file + +// GenesisDocFromJSON unmarshalls JSON data into a GenesisDoc. +func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) { + genDoc := GenesisDoc{} + err := cmtjson.Unmarshal(jsonBlob, &genDoc) + if err != nil { + return nil, err + } + + if err := genDoc.ValidateAndComplete(); err != nil { + return nil, err + } + + return &genDoc, err +} + +// GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc. +func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) { + jsonBlob, err := os.ReadFile(genDocFile) + if err != nil { + return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err) + } + genDoc, err := GenesisDocFromJSON(jsonBlob) + if err != nil { + return nil, fmt.Errorf("error reading GenesisDoc at %s: %w", genDocFile, err) + } + return genDoc, nil +} diff --git a/types/genesis_test.go b/types/genesis_test.go new file mode 100644 index 0000000..d4485f8 --- /dev/null +++ b/types/genesis_test.go @@ -0,0 +1,164 @@ +package types + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmttime "github.com/cometbft/cometbft/types/time" +) + +func TestGenesisBad(t *testing.T) { + // test some bad ones from raw json + testCases := [][]byte{ + {}, // empty + {1, 1, 1, 1, 1}, // junk + []byte(`{}`), // empty + []byte(`{"chain_id":"mychain","validators":[{}]}`), // invalid validator + []byte(`{"chain_id":"chain","initial_height":"-1"}`), // negative initial height + // missing pub_key type + []byte( + `{"validators":[{"pub_key":{"value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="},"power":"10","name":""}]}`, + ), + // missing chain_id + []byte( + `{"validators":[` + + `{"pub_key":{` + + `"type":"tendermint/PubKeyEd25519","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="` + + `},"power":"10","name":""}` + + `]}`, + ), + // too big chain_id + []byte( + `{"chain_id": "Lorem ipsum dolor sit amet, consectetuer adipiscing", "validators": [` + + `{"pub_key":{` + + `"type":"tendermint/PubKeyEd25519","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="` + + `},"power":"10","name":""}` + + `]}`, + ), + // wrong address + []byte( + `{"chain_id":"mychain", "validators":[` + + `{"address": "A", "pub_key":{` + + `"type":"tendermint/PubKeyEd25519","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="` + + `},"power":"10","name":""}` + + `]}`, + ), + } + + for _, testCase := range testCases { + _, err := GenesisDocFromJSON(testCase) + assert.Error(t, err, "expected error for empty genDoc json") + } +} + +func TestGenesisGood(t *testing.T) { + // test a good one by raw json + genDocBytes := []byte( + `{ + "genesis_time": "0001-01-01T00:00:00Z", + "chain_id": "test-chain-QDKdJr", + "initial_height": "1000", + "consensus_params": null, + "validators": [{ + "pub_key":{"type":"tendermint/PubKeyEd25519","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="}, + "power":"10", + "name":"" + }], + "app_hash":"", + "app_state":{"account_owner": "Bob"} + }`, + ) + _, err := GenesisDocFromJSON(genDocBytes) + assert.NoError(t, err, "expected no error for good genDoc json") + + pubkey := ed25519.GenPrivKey().PubKey() + // create a base gendoc from struct + baseGenDoc := &GenesisDoc{ + ChainID: "abc", + Validators: []GenesisValidator{{pubkey.Address(), pubkey, 10, "myval"}}, + } + genDocBytes, err = cmtjson.Marshal(baseGenDoc) + assert.NoError(t, err, "error marshaling genDoc") + + // test base gendoc and check consensus params were filled + genDoc, err := GenesisDocFromJSON(genDocBytes) + assert.NoError(t, err, "expected no error for valid genDoc json") + assert.NotNil(t, genDoc.ConsensusParams, "expected consensus params to be filled in") + + // check validator's address is filled + assert.NotNil(t, genDoc.Validators[0].Address, "expected validator's address to be filled in") + + // create json with consensus params filled + genDocBytes, err = cmtjson.Marshal(genDoc) + assert.NoError(t, err, "error marshaling genDoc") + genDoc, err = GenesisDocFromJSON(genDocBytes) + assert.NoError(t, err, "expected no error for valid genDoc json") + + // test with invalid consensus params + genDoc.ConsensusParams.Block.MaxBytes = 0 + genDocBytes, err = cmtjson.Marshal(genDoc) + assert.NoError(t, err, "error marshaling genDoc") + _, err = GenesisDocFromJSON(genDocBytes) + assert.Error(t, err, "expected error for genDoc json with block size of 0") + + // Genesis doc from raw json + missingValidatorsTestCases := [][]byte{ + []byte(`{"chain_id":"mychain"}`), // missing validators + []byte(`{"chain_id":"mychain","validators":[]}`), // missing validators + []byte(`{"chain_id":"mychain","validators":null}`), // nil validator + []byte(`{"chain_id":"mychain"}`), // missing validators + } + + for _, tc := range missingValidatorsTestCases { + _, err := GenesisDocFromJSON(tc) + assert.NoError(t, err) + } +} + +func TestGenesisSaveAs(t *testing.T) { + tmpfile, err := os.CreateTemp("", "genesis") + require.NoError(t, err) + defer os.Remove(tmpfile.Name()) + + genDoc := randomGenesisDoc() + + // save + err = genDoc.SaveAs(tmpfile.Name()) + require.NoError(t, err) + stat, err := tmpfile.Stat() + require.NoError(t, err) + if err != nil && stat.Size() <= 0 { + t.Fatalf("SaveAs failed to write any bytes to %v", tmpfile.Name()) + } + + err = tmpfile.Close() + require.NoError(t, err) + + // load + genDoc2, err := GenesisDocFromFile(tmpfile.Name()) + require.NoError(t, err) + assert.EqualValues(t, genDoc2, genDoc) + assert.Equal(t, genDoc2.Validators, genDoc.Validators) +} + +func TestGenesisValidatorHash(t *testing.T) { + genDoc := randomGenesisDoc() + assert.NotEmpty(t, genDoc.ValidatorHash()) +} + +func randomGenesisDoc() *GenesisDoc { + pubkey := ed25519.GenPrivKey().PubKey() + return &GenesisDoc{ + GenesisTime: cmttime.Now(), + ChainID: "abc", + InitialHeight: 1000, + Validators: []GenesisValidator{{pubkey.Address(), pubkey, 10, "myval"}}, + ConsensusParams: DefaultConsensusParams(), + AppHash: []byte{1, 2, 3}, + } +} diff --git a/types/keys.go b/types/keys.go new file mode 100644 index 0000000..6fbff3c --- /dev/null +++ b/types/keys.go @@ -0,0 +1,6 @@ +package types + +// UNSTABLE +var ( + PeerStateKey = "ConsensusReactor.peerState" +) diff --git a/types/light.go b/types/light.go new file mode 100644 index 0000000..c6178b2 --- /dev/null +++ b/types/light.go @@ -0,0 +1,226 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// LightBlock is a SignedHeader and a ValidatorSet. +// It is the basis of the light client +type LightBlock struct { + *SignedHeader `json:"signed_header"` + ValidatorSet *ValidatorSet `json:"validator_set"` +} + +// ValidateBasic checks that the data is correct and consistent +// +// This does no verification of the signatures +func (lb LightBlock) ValidateBasic(chainID string) error { + if lb.SignedHeader == nil { + return errors.New("missing signed header") + } + if lb.ValidatorSet == nil { + return errors.New("missing validator set") + } + + if err := lb.SignedHeader.ValidateBasic(chainID); err != nil { + return fmt.Errorf("invalid signed header: %w", err) + } + if err := lb.ValidatorSet.ValidateBasic(); err != nil { + return fmt.Errorf("invalid validator set: %w", err) + } + + // make sure the validator set is consistent with the header + if valSetHash := lb.ValidatorSet.Hash(); !bytes.Equal(lb.ValidatorsHash, valSetHash) { + return fmt.Errorf("expected validator hash of header to match validator set hash (%X != %X)", + lb.ValidatorsHash, valSetHash, + ) + } + + return nil +} + +// String returns a string representation of the LightBlock +func (lb LightBlock) String() string { + return lb.StringIndented("") +} + +// StringIndented returns an indented string representation of the LightBlock +// +// SignedHeader +// ValidatorSet +func (lb LightBlock) StringIndented(indent string) string { + return fmt.Sprintf(`LightBlock{ +%s %v +%s %v +%s}`, + indent, lb.SignedHeader.StringIndented(indent+" "), + indent, lb.ValidatorSet.StringIndented(indent+" "), + indent) +} + +// ToProto converts the LightBlock to protobuf +func (lb *LightBlock) ToProto() (*cmtproto.LightBlock, error) { + if lb == nil { + return nil, nil + } + + lbp := new(cmtproto.LightBlock) + var err error + if lb.SignedHeader != nil { + lbp.SignedHeader = lb.SignedHeader.ToProto() + } + if lb.ValidatorSet != nil { + lbp.ValidatorSet, err = lb.ValidatorSet.ToProto() + if err != nil { + return nil, err + } + } + + return lbp, nil +} + +// LightBlockFromProto converts from protobuf back into the Lightblock. +// An error is returned if either the validator set or signed header are invalid +func LightBlockFromProto(pb *cmtproto.LightBlock) (*LightBlock, error) { + if pb == nil { + return nil, errors.New("nil light block") + } + + lb := new(LightBlock) + + if pb.SignedHeader != nil { + sh, err := SignedHeaderFromProto(pb.SignedHeader) + if err != nil { + return nil, err + } + lb.SignedHeader = sh + } + + if pb.ValidatorSet != nil { + vals, err := ValidatorSetFromProto(pb.ValidatorSet) + if err != nil { + return nil, err + } + lb.ValidatorSet = vals + } + + return lb, nil +} + +//----------------------------------------------------------------------------- + +// SignedHeader is a header along with the commits that prove it. +type SignedHeader struct { + *Header `json:"header"` + + Commit *Commit `json:"commit"` +} + +// IsEmpty returns true if both the header and commit are nil. +func (sh SignedHeader) IsEmpty() bool { + return sh.Header == nil && sh.Commit == nil +} + +// ValidateBasic does basic consistency checks and makes sure the header +// and commit are consistent. +// +// NOTE: This does not actually check the cryptographic signatures. Make sure +// to use a Verifier to validate the signatures actually provide a +// significantly strong proof for this header's validity. +func (sh SignedHeader) ValidateBasic(chainID string) error { + if sh.Header == nil { + return errors.New("missing header") + } + if sh.Commit == nil { + return errors.New("missing commit") + } + + if err := sh.Header.ValidateBasic(); err != nil { + return fmt.Errorf("invalid header: %w", err) + } + if err := sh.Commit.ValidateBasic(); err != nil { + return fmt.Errorf("invalid commit: %w", err) + } + + if sh.ChainID != chainID { + return fmt.Errorf("header belongs to another chain %q, not %q", sh.ChainID, chainID) + } + + // Make sure the header is consistent with the commit. + if sh.Commit.Height != sh.Height { + return fmt.Errorf("header and commit height mismatch: %d vs %d", sh.Height, sh.Commit.Height) + } + if hhash, chash := sh.Hash(), sh.Commit.BlockID.Hash; !bytes.Equal(hhash, chash) { + return fmt.Errorf("commit signs block %X, header is block %X", chash, hhash) + } + + return nil +} + +// String returns a string representation of SignedHeader. +func (sh SignedHeader) String() string { + return sh.StringIndented("") +} + +// StringIndented returns an indented string representation of SignedHeader. +// +// Header +// Commit +func (sh SignedHeader) StringIndented(indent string) string { + return fmt.Sprintf(`SignedHeader{ +%s %v +%s %v +%s}`, + indent, sh.Header.StringIndented(indent+" "), + indent, sh.Commit.StringIndented(indent+" "), + indent) +} + +// ToProto converts SignedHeader to protobuf +func (sh *SignedHeader) ToProto() *cmtproto.SignedHeader { + if sh == nil { + return nil + } + + psh := new(cmtproto.SignedHeader) + if sh.Header != nil { + psh.Header = sh.Header.ToProto() + } + if sh.Commit != nil { + psh.Commit = sh.Commit.ToProto() + } + + return psh +} + +// FromProto sets a protobuf SignedHeader to the given pointer. +// It returns an error if the header or the commit is invalid. +func SignedHeaderFromProto(shp *cmtproto.SignedHeader) (*SignedHeader, error) { + if shp == nil { + return nil, errors.New("nil SignedHeader") + } + + sh := new(SignedHeader) + + if shp.Header != nil { + h, err := HeaderFromProto(shp.Header) + if err != nil { + return nil, err + } + sh.Header = &h + } + + if shp.Commit != nil { + c, err := CommitFromProto(shp.Commit) + if err != nil { + return nil, err + } + sh.Commit = c + } + + return sh, nil +} diff --git a/types/light_test.go b/types/light_test.go new file mode 100644 index 0000000..9a30761 --- /dev/null +++ b/types/light_test.go @@ -0,0 +1,166 @@ +package types + +import ( + "math" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/cometbft/cometbft/crypto" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/version" +) + +func TestLightBlockValidateBasic(t *testing.T) { + header := makeRandHeader() + commit := randCommit(time.Now()) + vals, _ := RandValidatorSet(5, 1) + header.Height = commit.Height + header.LastBlockID = commit.BlockID + header.ValidatorsHash = vals.Hash() + header.Version.Block = version.BlockProtocol + vals2, _ := RandValidatorSet(3, 1) + vals3 := vals.Copy() + vals3.Proposer = &Validator{} + commit.BlockID.Hash = header.Hash() + + sh := &SignedHeader{ + Header: &header, + Commit: commit, + } + + testCases := []struct { + name string + sh *SignedHeader + vals *ValidatorSet + expectErr bool + }{ + {"valid light block", sh, vals, false}, + {"hashes don't match", sh, vals2, true}, + {"invalid validator set", sh, vals3, true}, + {"invalid signed header", &SignedHeader{Header: &header, Commit: randCommit(time.Now())}, vals, true}, + } + + for _, tc := range testCases { + lightBlock := LightBlock{ + SignedHeader: tc.sh, + ValidatorSet: tc.vals, + } + err := lightBlock.ValidateBasic(header.ChainID) + if tc.expectErr { + assert.Error(t, err, tc.name) + } else { + assert.NoError(t, err, tc.name) + } + } + +} + +func TestLightBlockProtobuf(t *testing.T) { + header := makeRandHeader() + commit := randCommit(time.Now()) + vals, _ := RandValidatorSet(5, 1) + header.Height = commit.Height + header.LastBlockID = commit.BlockID + header.Version.Block = version.BlockProtocol + header.ValidatorsHash = vals.Hash() + vals3 := vals.Copy() + vals3.Proposer = &Validator{} + commit.BlockID.Hash = header.Hash() + + sh := &SignedHeader{ + Header: &header, + Commit: commit, + } + + testCases := []struct { + name string + sh *SignedHeader + vals *ValidatorSet + toProtoErr bool + toBlockErr bool + }{ + {"valid light block", sh, vals, false, false}, + {"empty signed header", &SignedHeader{}, vals, false, false}, + {"empty validator set", sh, &ValidatorSet{}, false, true}, + {"empty light block", &SignedHeader{}, &ValidatorSet{}, false, true}, + } + + for _, tc := range testCases { + lightBlock := &LightBlock{ + SignedHeader: tc.sh, + ValidatorSet: tc.vals, + } + lbp, err := lightBlock.ToProto() + if tc.toProtoErr { + assert.Error(t, err, tc.name) + } else { + assert.NoError(t, err, tc.name) + } + + lb, err := LightBlockFromProto(lbp) + if tc.toBlockErr { + assert.Error(t, err, tc.name) + } else { + assert.NoError(t, err, tc.name) + assert.Equal(t, lightBlock, lb) + } + } + +} + +func TestSignedHeaderValidateBasic(t *testing.T) { + commit := randCommit(time.Now()) + chainID := "𠜎" + timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC) + h := Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: math.MaxInt64}, + ChainID: chainID, + Height: commit.Height, + Time: timestamp, + LastBlockID: commit.BlockID, + LastCommitHash: commit.Hash(), + DataHash: commit.Hash(), + ValidatorsHash: commit.Hash(), + NextValidatorsHash: commit.Hash(), + ConsensusHash: commit.Hash(), + AppHash: commit.Hash(), + LastResultsHash: commit.Hash(), + EvidenceHash: commit.Hash(), + ProposerAddress: crypto.AddressHash([]byte("proposer_address")), + } + + validSignedHeader := SignedHeader{Header: &h, Commit: commit} + validSignedHeader.Commit.BlockID.Hash = validSignedHeader.Hash() + invalidSignedHeader := SignedHeader{} + + testCases := []struct { + testName string + shHeader *Header + shCommit *Commit + expectErr bool + }{ + {"Valid Signed Header", validSignedHeader.Header, validSignedHeader.Commit, false}, + {"Invalid Signed Header", invalidSignedHeader.Header, validSignedHeader.Commit, true}, + {"Invalid Signed Header", validSignedHeader.Header, invalidSignedHeader.Commit, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + sh := SignedHeader{ + Header: tc.shHeader, + Commit: tc.shCommit, + } + err := sh.ValidateBasic(validSignedHeader.ChainID) + assert.Equalf( + t, + tc.expectErr, + err != nil, + "Validate Basic had an unexpected result", + err, + ) + }) + } +} diff --git a/types/params.go b/types/params.go new file mode 100644 index 0000000..c69297b --- /dev/null +++ b/types/params.go @@ -0,0 +1,370 @@ +package types + +import ( + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/secp256k1" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +const ( + // MaxBlockSizeBytes is the maximum permitted size of the blocks. + MaxBlockSizeBytes = 104857600 // 100MB + + // BlockPartSizeBytes is the size of one block part. + BlockPartSizeBytes uint32 = 65536 // 64kB + + // MaxBlockPartsCount is the maximum number of block parts. + MaxBlockPartsCount = (MaxBlockSizeBytes / BlockPartSizeBytes) + 1 + + ABCIPubKeyTypeEd25519 = ed25519.KeyType + ABCIPubKeyTypeSecp256k1 = secp256k1.KeyType +) + +var ABCIPubKeyTypesToNames = map[string]string{ + ABCIPubKeyTypeEd25519: ed25519.PubKeyName, + ABCIPubKeyTypeSecp256k1: secp256k1.PubKeyName, +} + +// ConsensusParams contains consensus critical parameters that determine the +// validity of blocks. +type ConsensusParams struct { + Block BlockParams `json:"block"` + Evidence EvidenceParams `json:"evidence"` + Validator ValidatorParams `json:"validator"` + Version VersionParams `json:"version"` + ABCI ABCIParams `json:"abci"` +} + +// BlockParams define limits on the block size and gas plus minimum time +// between blocks. +type BlockParams struct { + MaxBytes int64 `json:"max_bytes"` + MaxGas int64 `json:"max_gas"` +} + +// EvidenceParams determine how we handle evidence of malfeasance. +type EvidenceParams struct { + MaxAgeNumBlocks int64 `json:"max_age_num_blocks"` // only accept new evidence more recent than this + MaxAgeDuration time.Duration `json:"max_age_duration"` + MaxBytes int64 `json:"max_bytes"` +} + +// ValidatorParams restrict the public key types validators can use. +// NOTE: uses ABCI pubkey naming, not Amino names. +type ValidatorParams struct { + PubKeyTypes []string `json:"pub_key_types"` +} + +type VersionParams struct { + App uint64 `json:"app"` +} + +// ABCIParams configure ABCI functionality specific to the Application Blockchain +// Interface. +type ABCIParams struct { + VoteExtensionsEnableHeight int64 `json:"vote_extensions_enable_height"` +} + +// VoteExtensionsEnabled returns true if vote extensions are enabled at height h +// and false otherwise. +func (a ABCIParams) VoteExtensionsEnabled(h int64) bool { + if h < 1 { + panic(fmt.Errorf("cannot check if vote extensions enabled for height %d (< 1)", h)) + } + if a.VoteExtensionsEnableHeight == 0 { + return false + } + return a.VoteExtensionsEnableHeight <= h +} + +// DefaultConsensusParams returns a default ConsensusParams. +func DefaultConsensusParams() *ConsensusParams { + return &ConsensusParams{ + Block: DefaultBlockParams(), + Evidence: DefaultEvidenceParams(), + Validator: DefaultValidatorParams(), + Version: DefaultVersionParams(), + ABCI: DefaultABCIParams(), + } +} + +// DefaultBlockParams returns a default BlockParams. +func DefaultBlockParams() BlockParams { + return BlockParams{ + MaxBytes: 22020096, // 21MB + MaxGas: -1, + } +} + +// DefaultEvidenceParams returns a default EvidenceParams. +func DefaultEvidenceParams() EvidenceParams { + return EvidenceParams{ + MaxAgeNumBlocks: 100000, // 27.8 hrs at 1block/s + MaxAgeDuration: 48 * time.Hour, + MaxBytes: 1048576, // 1MB + } +} + +// DefaultValidatorParams returns a default ValidatorParams, which allows +// only ed25519 pubkeys. +func DefaultValidatorParams() ValidatorParams { + return ValidatorParams{ + PubKeyTypes: []string{ABCIPubKeyTypeEd25519}, + } +} + +func DefaultVersionParams() VersionParams { + return VersionParams{ + App: 0, + } +} + +func DefaultABCIParams() ABCIParams { + return ABCIParams{ + // When set to 0, vote extensions are not required. + VoteExtensionsEnableHeight: 0, + } +} + +func IsValidPubkeyType(params ValidatorParams, pubkeyType string) bool { + for i := 0; i < len(params.PubKeyTypes); i++ { + if params.PubKeyTypes[i] == pubkeyType { + return true + } + } + return false +} + +// Validate validates the ConsensusParams to ensure all values are within their +// allowed limits, and returns an error if they are not. +func (params ConsensusParams) ValidateBasic() error { + if params.Block.MaxBytes == 0 { + return fmt.Errorf("block.MaxBytes cannot be 0") + } + if params.Block.MaxBytes < -1 { + return fmt.Errorf("block.MaxBytes must be -1 or greater than 0. Got %d", + + params.Block.MaxBytes) + } + if params.Block.MaxBytes > MaxBlockSizeBytes { + return fmt.Errorf("block.MaxBytes is too big. %d > %d", + params.Block.MaxBytes, MaxBlockSizeBytes) + } + + if params.Block.MaxGas < -1 { + return fmt.Errorf("block.MaxGas must be greater or equal to -1. Got %d", + params.Block.MaxGas) + } + + if params.Evidence.MaxAgeNumBlocks <= 0 { + return fmt.Errorf("evidence.MaxAgeNumBlocks must be greater than 0. Got %d", + params.Evidence.MaxAgeNumBlocks) + } + + if params.Evidence.MaxAgeDuration <= 0 { + return fmt.Errorf("evidence.MaxAgeDuration must be grater than 0 if provided, Got %v", + params.Evidence.MaxAgeDuration) + } + + maxBytes := params.Block.MaxBytes + if maxBytes == -1 { + maxBytes = int64(MaxBlockSizeBytes) + } + if params.Evidence.MaxBytes > maxBytes { + return fmt.Errorf("evidence.MaxBytesEvidence is greater than upper bound, %d > %d", + params.Evidence.MaxBytes, params.Block.MaxBytes) + } + + if params.Evidence.MaxBytes < 0 { + return fmt.Errorf("evidence.MaxBytes must be non negative. Got: %d", + params.Evidence.MaxBytes) + } + + if params.ABCI.VoteExtensionsEnableHeight < 0 { + return fmt.Errorf("ABCI.VoteExtensionsEnableHeight cannot be negative. Got: %d", params.ABCI.VoteExtensionsEnableHeight) + } + + if len(params.Validator.PubKeyTypes) == 0 { + return errors.New("len(Validator.PubKeyTypes) must be greater than 0") + } + + // Check if keyType is a known ABCIPubKeyType + for i := 0; i < len(params.Validator.PubKeyTypes); i++ { + keyType := params.Validator.PubKeyTypes[i] + if _, ok := ABCIPubKeyTypesToNames[keyType]; !ok { + return fmt.Errorf("params.Validator.PubKeyTypes[%d], %s, is an unknown pubkey type", + i, keyType) + } + } + + return nil +} + +// ValidateUpdate validates the updated VoteExtensionsEnableHeight. +// | r | params...EnableHeight | updated...EnableHeight | result (nil == pass) +// | 1 | * | (nil) | nil +// | 2 | * | < 0 | VoteExtensionsEnableHeight must be positive +// | 3 | <=0 | 0 | nil +// | 4 | X | X (>=0) | nil +// | 5 | > 0; <=height | 0 | vote extensions cannot be disabled once enabled +// | 6 | > 0; > height | 0 | nil (disable a previous proposal) +// | 7 | * | <=height | vote extensions cannot be updated to a past height +// | 8 | <=0 | > height (*) | nil +// | 9 | (> 0) <=height | > height (*) | vote extensions cannot be modified once enabled +// | 10 | (> 0) > height | > height (*) | nil +func (params ConsensusParams) ValidateUpdate(updated *cmtproto.ConsensusParams, h int64) error { + // 1 + if updated == nil || updated.Abci == nil { + return nil + } + // 2 + if updated.Abci.VoteExtensionsEnableHeight < 0 { + return errors.New("VoteExtensionsEnableHeight must be positive") + } + // 3 + if params.ABCI.VoteExtensionsEnableHeight <= 0 && updated.Abci.VoteExtensionsEnableHeight == 0 { + return nil + } + // 4 (implicit: updated.Abci.VoteExtensionsEnableHeight >= 0) + if params.ABCI.VoteExtensionsEnableHeight == updated.Abci.VoteExtensionsEnableHeight { + return nil + } + // 5 & 6 + if params.ABCI.VoteExtensionsEnableHeight > 0 && updated.Abci.VoteExtensionsEnableHeight == 0 { + // 5 + if params.ABCI.VoteExtensionsEnableHeight <= h { + return fmt.Errorf("vote extensions cannot be disabled once enabled"+ + "old enable height: %d, current height %d", + params.ABCI.VoteExtensionsEnableHeight, h) + } + // 6 + return nil + } + // 7 (implicit: updated.Abci.VoteExtensionsEnableHeight > 0) + if updated.Abci.VoteExtensionsEnableHeight <= h { + return fmt.Errorf("vote extensions cannot be updated to a past or current height, "+ + "enable height: %d, current height %d", + updated.Abci.VoteExtensionsEnableHeight, h) + } + // 8 (implicit: updated.Abci.VoteExtensionsEnableHeight > h) + if params.ABCI.VoteExtensionsEnableHeight <= 0 { + return nil + } + // 9 (implicit: params.ABCI.VoteExtensionsEnableHeight > 0 && updated.Abci.VoteExtensionsEnableHeight > h) + if params.ABCI.VoteExtensionsEnableHeight <= h { + return fmt.Errorf("vote extensions cannot be modified once enabled"+ + "enable height: %d, current height %d", + params.ABCI.VoteExtensionsEnableHeight, h) + } + // 10 (implicit: params.ABCI.VoteExtensionsEnableHeight > h && updated.Abci.VoteExtensionsEnableHeight > h) + return nil +} + +// Hash returns a hash of a subset of the parameters to store in the block header. +// Only the Block.MaxBytes and Block.MaxGas are included in the hash. +// This allows the ConsensusParams to evolve more without breaking the block +// protocol. No need for a Merkle tree here, just a small struct to hash. +func (params ConsensusParams) Hash() []byte { + hasher := tmhash.New() + + hp := cmtproto.HashedParams{ + BlockMaxBytes: params.Block.MaxBytes, + BlockMaxGas: params.Block.MaxGas, + } + + bz, err := hp.Marshal() + if err != nil { + panic(err) + } + + _, err = hasher.Write(bz) + if err != nil { + panic(err) + } + return hasher.Sum(nil) +} + +// Update returns a copy of the params with updates from the non-zero fields of p2. +// NOTE: note: must not modify the original +func (params ConsensusParams) Update(params2 *cmtproto.ConsensusParams) ConsensusParams { + res := params // explicit copy + + if params2 == nil { + return res + } + + // we must defensively consider any structs may be nil + if params2.Block != nil { + res.Block.MaxBytes = params2.Block.MaxBytes + res.Block.MaxGas = params2.Block.MaxGas + } + if params2.Evidence != nil { + res.Evidence.MaxAgeNumBlocks = params2.Evidence.MaxAgeNumBlocks + res.Evidence.MaxAgeDuration = params2.Evidence.MaxAgeDuration + res.Evidence.MaxBytes = params2.Evidence.MaxBytes + } + if params2.Validator != nil { + // Copy params2.Validator.PubkeyTypes, and set result's value to the copy. + // This avoids having to initialize the slice to 0 values, and then write to it again. + res.Validator.PubKeyTypes = append([]string{}, params2.Validator.PubKeyTypes...) + } + if params2.Version != nil { + res.Version.App = params2.Version.App + } + if params2.Abci != nil { + res.ABCI.VoteExtensionsEnableHeight = params2.Abci.GetVoteExtensionsEnableHeight() + } + return res +} + +func (params *ConsensusParams) ToProto() cmtproto.ConsensusParams { + return cmtproto.ConsensusParams{ + Block: &cmtproto.BlockParams{ + MaxBytes: params.Block.MaxBytes, + MaxGas: params.Block.MaxGas, + }, + Evidence: &cmtproto.EvidenceParams{ + MaxAgeNumBlocks: params.Evidence.MaxAgeNumBlocks, + MaxAgeDuration: params.Evidence.MaxAgeDuration, + MaxBytes: params.Evidence.MaxBytes, + }, + Validator: &cmtproto.ValidatorParams{ + PubKeyTypes: params.Validator.PubKeyTypes, + }, + Version: &cmtproto.VersionParams{ + App: params.Version.App, + }, + Abci: &cmtproto.ABCIParams{ + VoteExtensionsEnableHeight: params.ABCI.VoteExtensionsEnableHeight, + }, + } +} + +func ConsensusParamsFromProto(pbParams cmtproto.ConsensusParams) ConsensusParams { + c := ConsensusParams{ + Block: BlockParams{ + MaxBytes: pbParams.Block.MaxBytes, + MaxGas: pbParams.Block.MaxGas, + }, + Evidence: EvidenceParams{ + MaxAgeNumBlocks: pbParams.Evidence.MaxAgeNumBlocks, + MaxAgeDuration: pbParams.Evidence.MaxAgeDuration, + MaxBytes: pbParams.Evidence.MaxBytes, + }, + Validator: ValidatorParams{ + PubKeyTypes: pbParams.Validator.PubKeyTypes, + }, + Version: VersionParams{ + App: pbParams.Version.App, + }, + } + if pbParams.Abci != nil { + c.ABCI.VoteExtensionsEnableHeight = pbParams.Abci.GetVoteExtensionsEnableHeight() + } + return c +} diff --git a/types/params_test.go b/types/params_test.go new file mode 100644 index 0000000..c4d0847 --- /dev/null +++ b/types/params_test.go @@ -0,0 +1,251 @@ +package types + +import ( + "bytes" + "sort" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +var ( + valEd25519 = []string{ABCIPubKeyTypeEd25519} + valSecp256k1 = []string{ABCIPubKeyTypeSecp256k1} +) + +func TestConsensusParamsValidation(t *testing.T) { + testCases := []struct { + params ConsensusParams + valid bool + }{ + // test block params + 0: {makeParams(1, 0, 2, 0, valEd25519, 0), true}, + 1: {makeParams(0, 0, 2, 0, valEd25519, 0), false}, + 2: {makeParams(47*1024*1024, 0, 2, 0, valEd25519, 0), true}, + 3: {makeParams(10, 0, 2, 0, valEd25519, 0), true}, + 4: {makeParams(100*1024*1024, 0, 2, 0, valEd25519, 0), true}, + 5: {makeParams(101*1024*1024, 0, 2, 0, valEd25519, 0), false}, + 6: {makeParams(1024*1024*1024, 0, 2, 0, valEd25519, 0), false}, + // test evidence params + 7: {makeParams(1, 0, 0, 0, valEd25519, 0), false}, + 8: {makeParams(1, 0, 2, 2, valEd25519, 0), false}, + 9: {makeParams(1000, 0, 2, 1, valEd25519, 0), true}, + 10: {makeParams(1, 0, -1, 0, valEd25519, 0), false}, + // test no pubkey type provided + 11: {makeParams(1, 0, 2, 0, []string{}, 0), false}, + // test invalid pubkey type provided + 12: {makeParams(1, 0, 2, 0, []string{"potatoes make good pubkeys"}, 0), false}, + 13: {makeParams(-1, 0, 2, 0, valEd25519, 0), true}, + 14: {makeParams(-2, 0, 2, 0, valEd25519, 0), false}, + } + for i, tc := range testCases { + if tc.valid { + assert.NoErrorf(t, tc.params.ValidateBasic(), "expected no error for valid params (#%d)", i) + } else { + assert.Errorf(t, tc.params.ValidateBasic(), "expected error for non valid params (#%d)", i) + } + } +} + +func makeParams( + blockBytes, blockGas int64, + evidenceAge int64, + maxEvidenceBytes int64, + pubkeyTypes []string, + abciExtensionHeight int64, +) ConsensusParams { + return ConsensusParams{ + Block: BlockParams{ + MaxBytes: blockBytes, + MaxGas: blockGas, + }, + Evidence: EvidenceParams{ + MaxAgeNumBlocks: evidenceAge, + MaxAgeDuration: time.Duration(evidenceAge), + MaxBytes: maxEvidenceBytes, + }, + Validator: ValidatorParams{ + PubKeyTypes: pubkeyTypes, + }, + ABCI: ABCIParams{ + VoteExtensionsEnableHeight: abciExtensionHeight, + }, + } +} + +func TestConsensusParamsHash(t *testing.T) { + params := []ConsensusParams{ + makeParams(4, 2, 3, 1, valEd25519, 0), + makeParams(1, 4, 3, 1, valEd25519, 0), + makeParams(1, 2, 4, 1, valEd25519, 0), + makeParams(2, 5, 7, 1, valEd25519, 0), + makeParams(1, 7, 6, 1, valEd25519, 0), + makeParams(9, 5, 4, 1, valEd25519, 0), + makeParams(7, 8, 9, 1, valEd25519, 0), + makeParams(4, 6, 5, 1, valEd25519, 0), + } + + hashes := make([][]byte, len(params)) + for i := range params { + hashes[i] = params[i].Hash() + } + + // make sure there are no duplicates... + // sort, then check in order for matches + sort.Slice(hashes, func(i, j int) bool { + return bytes.Compare(hashes[i], hashes[j]) < 0 + }) + for i := 0; i < len(hashes)-1; i++ { + assert.NotEqual(t, hashes[i], hashes[i+1]) + } +} + +func TestConsensusParamsUpdate(t *testing.T) { + testCases := []struct { + params ConsensusParams + updates *cmtproto.ConsensusParams + updatedParams ConsensusParams + }{ + // empty updates + { + makeParams(1, 2, 3, 0, valEd25519, 0), + &cmtproto.ConsensusParams{}, + makeParams(1, 2, 3, 0, valEd25519, 0), + }, + // fine updates + { + makeParams(1, 2, 3, 0, valEd25519, 0), + &cmtproto.ConsensusParams{ + Block: &cmtproto.BlockParams{ + MaxBytes: 100, + MaxGas: 200, + }, + Evidence: &cmtproto.EvidenceParams{ + MaxAgeNumBlocks: 300, + MaxAgeDuration: time.Duration(300), + MaxBytes: 50, + }, + Validator: &cmtproto.ValidatorParams{ + PubKeyTypes: valSecp256k1, + }, + }, + makeParams(100, 200, 300, 50, valSecp256k1, 0), + }, + } + + for _, tc := range testCases { + assert.Equal(t, tc.updatedParams, tc.params.Update(tc.updates)) + } +} + +func TestConsensusParamsUpdate_AppVersion(t *testing.T) { + params := makeParams(1, 2, 3, 0, valEd25519, 0) + + assert.EqualValues(t, 0, params.Version.App) + + updated := params.Update( + &cmtproto.ConsensusParams{Version: &cmtproto.VersionParams{App: 1}}) + + assert.EqualValues(t, 1, updated.Version.App) +} + +func TestConsensusParamsUpdate_VoteExtensionsEnableHeight(t *testing.T) { + const nilTest = -10000000 + testCases := []struct { + name string + current int64 + from int64 + to int64 + expectedErr bool + }{ + // no change + {"current: 3, 0 -> 0", 3, 0, 0, false}, + {"current: 3, 100 -> 100, ", 3, 100, 100, false}, + {"current: 100, 100 -> 100, ", 100, 100, 100, false}, + {"current: 300, 100 -> 100, ", 300, 100, 100, false}, + // set for the first time + {"current: 3, 0 -> 5, ", 3, 0, 5, false}, + {"current: 4, 0 -> 5, ", 4, 0, 5, false}, + {"current: 5, 0 -> 5, ", 5, 0, 5, true}, + {"current: 6, 0 -> 5, ", 6, 0, 5, true}, + {"current: 50, 0 -> 5, ", 50, 0, 5, true}, + // reset to 0 + {"current: 4, 5 -> 0, ", 4, 5, 0, false}, + {"current: 5, 5 -> 0, ", 5, 5, 0, true}, + {"current: 6, 5 -> 0, ", 6, 5, 0, true}, + {"current: 10, 5 -> 0, ", 10, 5, 0, true}, + // modify backwards + {"current: 1, 10 -> 5, ", 1, 10, 5, false}, + {"current: 4, 10 -> 5, ", 4, 10, 5, false}, + {"current: 5, 10 -> 5, ", 5, 10, 5, true}, + {"current: 6, 10 -> 5, ", 6, 10, 5, true}, + {"current: 9, 10 -> 5, ", 9, 10, 5, true}, + {"current: 10, 10 -> 5, ", 10, 10, 5, true}, + {"current: 11, 10 -> 5, ", 11, 10, 5, true}, + {"current: 100, 10 -> 5, ", 100, 10, 5, true}, + // modify forward + {"current: 3, 10 -> 15, ", 3, 10, 15, false}, + {"current: 9, 10 -> 15, ", 9, 10, 15, false}, + {"current: 10, 10 -> 15, ", 10, 10, 15, true}, + {"current: 11, 10 -> 15, ", 11, 10, 15, true}, + {"current: 14, 10 -> 15, ", 14, 10, 15, true}, + {"current: 15, 10 -> 15, ", 15, 10, 15, true}, + {"current: 16, 10 -> 15, ", 16, 10, 15, true}, + {"current: 100, 10 -> 15, ", 100, 10, 15, true}, + // negative values + {"current: 3, 0 -> -5", 3, 0, -5, true}, + {"current: 3, -5 -> 100, ", 3, -5, 100, false}, + {"current: 3, -10 -> 3, ", 3, -10, 3, true}, + {"current: 3, -3 -> -3", 3, -3, -3, true}, + {"current: 100, -8 -> -9, ", 100, -8, -9, true}, + {"current: 300, -10 -> -8, ", 300, -10, -8, true}, + // test for nil + {"current: 300, 400 -> nil, ", 300, 400, nilTest, false}, + {"current: 300, 200 -> nil, ", 300, 200, nilTest, false}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(*testing.T) { + initialParams := makeParams(1, 0, 2, 0, valEd25519, tc.from) + update := &cmtproto.ConsensusParams{} + if tc.to == nilTest { + update.Abci = nil + } else { + update.Abci = &cmtproto.ABCIParams{ + VoteExtensionsEnableHeight: tc.to, + } + } + if tc.expectedErr { + require.Error(t, initialParams.ValidateUpdate(update, tc.current)) + } else { + require.NoError(t, initialParams.ValidateUpdate(update, tc.current)) + } + }) + } +} + +func TestProto(t *testing.T) { + params := []ConsensusParams{ + makeParams(4, 2, 3, 1, valEd25519, 1), + makeParams(1, 4, 3, 1, valEd25519, 1), + makeParams(1, 2, 4, 1, valEd25519, 1), + makeParams(2, 5, 7, 1, valEd25519, 1), + makeParams(1, 7, 6, 1, valEd25519, 1), + makeParams(9, 5, 4, 1, valEd25519, 1), + makeParams(7, 8, 9, 1, valEd25519, 1), + makeParams(4, 6, 5, 1, valEd25519, 1), + } + + for i := range params { + pbParams := params[i].ToProto() + + oriParams := ConsensusParamsFromProto(pbParams) + + assert.Equal(t, params[i], oriParams) + + } +} diff --git a/types/part_set.go b/types/part_set.go new file mode 100644 index 0000000..917a770 --- /dev/null +++ b/types/part_set.go @@ -0,0 +1,412 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + "io" + + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/libs/bits" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtsync "github.com/cometbft/cometbft/libs/sync" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +var ( + ErrPartSetUnexpectedIndex = errors.New("error part set unexpected index") + ErrPartSetInvalidProof = errors.New("error part set invalid proof") + ErrPartTooBig = errors.New("error part size too big") + ErrPartInvalidSize = errors.New("error inner part with invalid size") +) + +// ErrInvalidPart is an error type for invalid parts. +type ErrInvalidPart struct { + Reason error +} + +func (e ErrInvalidPart) Error() string { + return fmt.Sprintf("invalid part: %v", e.Reason) +} + +func (e ErrInvalidPart) Unwrap() error { + return e.Reason +} + +type Part struct { + Index uint32 `json:"index"` + Bytes cmtbytes.HexBytes `json:"bytes"` + Proof merkle.Proof `json:"proof"` +} + +// ValidateBasic performs basic validation. +func (part *Part) ValidateBasic() error { + if len(part.Bytes) > int(BlockPartSizeBytes) { + return ErrPartTooBig + } + // All parts except the last one should have the same constant size. + if int64(part.Index) < part.Proof.Total-1 && len(part.Bytes) != int(BlockPartSizeBytes) { + return ErrPartInvalidSize + } + if int64(part.Index) != part.Proof.Index { + return ErrInvalidPart{Reason: fmt.Errorf("part index %d != proof index %d", part.Index, part.Proof.Index)} + } + if err := part.Proof.ValidateBasic(); err != nil { + return ErrInvalidPart{Reason: fmt.Errorf("wrong Proof: %w", err)} + } + return nil +} + +// String returns a string representation of Part. +// +// See StringIndented. +func (part *Part) String() string { + return part.StringIndented("") +} + +// StringIndented returns an indented Part. +// +// See merkle.Proof#StringIndented +func (part *Part) StringIndented(indent string) string { + return fmt.Sprintf(`Part{#%v +%s Bytes: %X... +%s Proof: %v +%s}`, + part.Index, + indent, cmtbytes.Fingerprint(part.Bytes), + indent, part.Proof.StringIndented(indent+" "), + indent) +} + +func (part *Part) ToProto() (*cmtproto.Part, error) { + if part == nil { + return nil, errors.New("nil part") + } + pb := new(cmtproto.Part) + proof := part.Proof.ToProto() + + pb.Index = part.Index + pb.Bytes = part.Bytes + pb.Proof = *proof + + return pb, nil +} + +func PartFromProto(pb *cmtproto.Part) (*Part, error) { + if pb == nil { + return nil, errors.New("nil part") + } + + part := new(Part) + proof, err := merkle.ProofFromProto(&pb.Proof) + if err != nil { + return nil, err + } + part.Index = pb.Index + part.Bytes = pb.Bytes + part.Proof = *proof + + return part, part.ValidateBasic() +} + +//------------------------------------- + +type PartSetHeader struct { + Total uint32 `json:"total"` + Hash cmtbytes.HexBytes `json:"hash"` +} + +// String returns a string representation of PartSetHeader. +// +// 1. total number of parts +// 2. first 6 bytes of the hash +func (psh PartSetHeader) String() string { + return fmt.Sprintf("%v:%X", psh.Total, cmtbytes.Fingerprint(psh.Hash)) +} + +func (psh PartSetHeader) IsZero() bool { + return psh.Total == 0 && len(psh.Hash) == 0 +} + +func (psh PartSetHeader) Equals(other PartSetHeader) bool { + return psh.Total == other.Total && bytes.Equal(psh.Hash, other.Hash) +} + +// ValidateBasic performs basic validation. +func (psh PartSetHeader) ValidateBasic() error { + // Hash can be empty in case of POLBlockID.PartSetHeader in Proposal. + if err := ValidateHash(psh.Hash); err != nil { + return fmt.Errorf("wrong Hash: %w", err) + } + return nil +} + +// ToProto converts PartSetHeader to protobuf +func (psh *PartSetHeader) ToProto() cmtproto.PartSetHeader { + if psh == nil { + return cmtproto.PartSetHeader{} + } + + return cmtproto.PartSetHeader{ + Total: psh.Total, + Hash: psh.Hash, + } +} + +// FromProto sets a protobuf PartSetHeader to the given pointer +func PartSetHeaderFromProto(ppsh *cmtproto.PartSetHeader) (*PartSetHeader, error) { + if ppsh == nil { + return nil, errors.New("nil PartSetHeader") + } + psh := new(PartSetHeader) + psh.Total = ppsh.Total + psh.Hash = ppsh.Hash + + return psh, psh.ValidateBasic() +} + +// ProtoPartSetHeaderIsZero is similar to the IsZero function for +// PartSetHeader, but for the Protobuf representation. +func ProtoPartSetHeaderIsZero(ppsh *cmtproto.PartSetHeader) bool { + return ppsh.Total == 0 && len(ppsh.Hash) == 0 +} + +//------------------------------------- + +type PartSet struct { + total uint32 + hash []byte + + mtx cmtsync.Mutex + parts []*Part + partsBitArray *bits.BitArray + count uint32 + // a count of the total size (in bytes). Used to ensure that the + // part set doesn't exceed the maximum block bytes + byteSize int64 +} + +// Returns an immutable, full PartSet from the data bytes. +// The data bytes are split into "partSize" chunks, and merkle tree computed. +// CONTRACT: partSize is greater than zero. +func NewPartSetFromData(data []byte, partSize uint32) *PartSet { + // divide data into 4kb parts. + total := (uint32(len(data)) + partSize - 1) / partSize + parts := make([]*Part, total) + partsBytes := make([][]byte, total) + partsBitArray := bits.NewBitArray(int(total)) + for i := uint32(0); i < total; i++ { + part := &Part{ + Index: i, + Bytes: data[i*partSize : cmtmath.MinInt(len(data), int((i+1)*partSize))], + } + parts[i] = part + partsBytes[i] = part.Bytes + partsBitArray.SetIndex(int(i), true) + } + // Compute merkle proofs + root, proofs := merkle.ProofsFromByteSlices(partsBytes) + for i := uint32(0); i < total; i++ { + parts[i].Proof = *proofs[i] + } + return &PartSet{ + total: total, + hash: root, + parts: parts, + partsBitArray: partsBitArray, + count: total, + byteSize: int64(len(data)), + } +} + +// Returns an empty PartSet ready to be populated. +func NewPartSetFromHeader(header PartSetHeader) *PartSet { + return &PartSet{ + total: header.Total, + hash: header.Hash, + parts: make([]*Part, header.Total), + partsBitArray: bits.NewBitArray(int(header.Total)), + count: 0, + byteSize: 0, + } +} + +func (ps *PartSet) Header() PartSetHeader { + if ps == nil { + return PartSetHeader{} + } + return PartSetHeader{ + Total: ps.total, + Hash: ps.hash, + } +} + +func (ps *PartSet) HasHeader(header PartSetHeader) bool { + if ps == nil { + return false + } + return ps.Header().Equals(header) +} + +func (ps *PartSet) BitArray() *bits.BitArray { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return ps.partsBitArray.Copy() +} + +func (ps *PartSet) Hash() []byte { + if ps == nil { + return merkle.HashFromByteSlices(nil) + } + return ps.hash +} + +func (ps *PartSet) HashesTo(hash []byte) bool { + if ps == nil { + return false + } + return bytes.Equal(ps.hash, hash) +} + +func (ps *PartSet) Count() uint32 { + if ps == nil { + return 0 + } + return ps.count +} + +func (ps *PartSet) ByteSize() int64 { + if ps == nil { + return 0 + } + return ps.byteSize +} + +func (ps *PartSet) Total() uint32 { + if ps == nil { + return 0 + } + return ps.total +} + +// CONTRACT: part is validated using ValidateBasic. +func (ps *PartSet) AddPart(part *Part) (bool, error) { + // TODO: remove this? would be preferable if this only returned (false, nil) + // when its a duplicate block part + if ps == nil { + return false, nil + } + + ps.mtx.Lock() + defer ps.mtx.Unlock() + + // Invalid part index + if part.Index >= ps.total { + return false, ErrPartSetUnexpectedIndex + } + + // If part already exists, return false. + if ps.parts[part.Index] != nil { + return false, nil + } + + // The proof should be compatible with the number of parts. + if part.Proof.Total != int64(ps.total) { + return false, ErrPartSetInvalidProof + } + + // Check hash proof + if part.Proof.Verify(ps.Hash(), part.Bytes) != nil { + return false, ErrPartSetInvalidProof + } + + // Add part + ps.parts[part.Index] = part + ps.partsBitArray.SetIndex(int(part.Index), true) + ps.count++ + ps.byteSize += int64(len(part.Bytes)) + return true, nil +} + +func (ps *PartSet) GetPart(index int) *Part { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return ps.parts[index] +} + +func (ps *PartSet) IsComplete() bool { + return ps.count == ps.total +} + +func (ps *PartSet) GetReader() io.Reader { + if !ps.IsComplete() { + panic("Cannot GetReader() on incomplete PartSet") + } + return NewPartSetReader(ps.parts) +} + +type PartSetReader struct { + i int + parts []*Part + reader *bytes.Reader +} + +func NewPartSetReader(parts []*Part) *PartSetReader { + return &PartSetReader{ + i: 0, + parts: parts, + reader: bytes.NewReader(parts[0].Bytes), + } +} + +func (psr *PartSetReader) Read(p []byte) (n int, err error) { + readerLen := psr.reader.Len() + if readerLen >= len(p) { + return psr.reader.Read(p) + } else if readerLen > 0 { + n1, err := psr.Read(p[:readerLen]) + if err != nil { + return n1, err + } + n2, err := psr.Read(p[readerLen:]) + return n1 + n2, err + } + + psr.i++ + if psr.i >= len(psr.parts) { + return 0, io.EOF + } + psr.reader = bytes.NewReader(psr.parts[psr.i].Bytes) + return psr.Read(p) +} + +// StringShort returns a short version of String. +// +// (Count of Total) +func (ps *PartSet) StringShort() string { + if ps == nil { + return "nil-PartSet" + } + ps.mtx.Lock() + defer ps.mtx.Unlock() + return fmt.Sprintf("(%v of %v)", ps.Count(), ps.Total()) +} + +func (ps *PartSet) MarshalJSON() ([]byte, error) { + if ps == nil { + return []byte("{}"), nil + } + + ps.mtx.Lock() + defer ps.mtx.Unlock() + + return cmtjson.Marshal(struct { + CountTotal string `json:"count/total"` + PartsBitArray *bits.BitArray `json:"parts_bit_array"` + }{ + fmt.Sprintf("%d/%d", ps.Count(), ps.Total()), + ps.partsBitArray, + }) +} diff --git a/types/part_set_test.go b/types/part_set_test.go new file mode 100644 index 0000000..65323f4 --- /dev/null +++ b/types/part_set_test.go @@ -0,0 +1,226 @@ +package types + +import ( + "io" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/merkle" + cmtrand "github.com/cometbft/cometbft/libs/rand" +) + +const ( + testPartSize = 65536 // 64KB ... 4096 // 4KB +) + +func TestBasicPartSet(t *testing.T) { + // Construct random data of size partSize * 100 + nParts := 100 + data := cmtrand.Bytes(testPartSize * nParts) + partSet := NewPartSetFromData(data, testPartSize) + + assert.NotEmpty(t, partSet.Hash()) + assert.EqualValues(t, nParts, partSet.Total()) + assert.Equal(t, nParts, partSet.BitArray().Size()) + assert.True(t, partSet.HashesTo(partSet.Hash())) + assert.True(t, partSet.IsComplete()) + assert.EqualValues(t, nParts, partSet.Count()) + assert.EqualValues(t, testPartSize*nParts, partSet.ByteSize()) + + // Test adding parts to a new partSet. + partSet2 := NewPartSetFromHeader(partSet.Header()) + + assert.True(t, partSet2.HasHeader(partSet.Header())) + for i := 0; i < int(partSet.Total()); i++ { + part := partSet.GetPart(i) + // t.Logf("\n%v", part) + added, err := partSet2.AddPart(part) + if !added || err != nil { + t.Errorf("failed to add part %v, error: %v", i, err) + } + } + // adding part with invalid index + added, err := partSet2.AddPart(&Part{Index: 10000}) + assert.False(t, added) + assert.Error(t, err) + // adding existing part + added, err = partSet2.AddPart(partSet2.GetPart(0)) + assert.False(t, added) + assert.Nil(t, err) + + assert.Equal(t, partSet.Hash(), partSet2.Hash()) + assert.EqualValues(t, nParts, partSet2.Total()) + assert.EqualValues(t, nParts*testPartSize, partSet.ByteSize()) + assert.True(t, partSet2.IsComplete()) + + // Reconstruct data, assert that they are equal. + data2Reader := partSet2.GetReader() + data2, err := io.ReadAll(data2Reader) + require.NoError(t, err) + + assert.Equal(t, data, data2) +} + +func TestWrongProof(t *testing.T) { + // Construct random data of size partSize * 100 + data := cmtrand.Bytes(testPartSize * 100) + partSet := NewPartSetFromData(data, testPartSize) + + // Test adding a part with wrong data. + partSet2 := NewPartSetFromHeader(partSet.Header()) + + // Test adding a part with wrong trail. + part := partSet.GetPart(0) + part.Proof.Aunts[0][0] += byte(0x01) + added, err := partSet2.AddPart(part) + if added || err == nil { + t.Errorf("expected to fail adding a part with bad trail.") + } + + // Test adding a part with wrong bytes. + part = partSet.GetPart(1) + part.Bytes[0] += byte(0x01) + added, err = partSet2.AddPart(part) + if added || err == nil { + t.Errorf("expected to fail adding a part with bad bytes.") + } + + // Test adding a part with wrong proof index. + part = partSet.GetPart(2) + part.Proof.Index = 1 + added, err = partSet2.AddPart(part) + if added || err == nil { + t.Errorf("expected to fail adding a part with bad proof index.") + } + + // Test adding a part with wrong proof total. + part = partSet.GetPart(3) + part.Proof.Total = int64(partSet.Total() - 1) + added, err = partSet2.AddPart(part) + if added || err == nil { + t.Errorf("expected to fail adding a part with bad proof total.") + } +} + +func TestPartSetHeaderValidateBasic(t *testing.T) { + testCases := []struct { + testName string + malleatePartSetHeader func(*PartSetHeader) + expectErr bool + }{ + {"Good PartSet", func(psHeader *PartSetHeader) {}, false}, + {"Invalid Hash", func(psHeader *PartSetHeader) { psHeader.Hash = make([]byte, 1) }, true}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + data := cmtrand.Bytes(testPartSize * 100) + ps := NewPartSetFromData(data, testPartSize) + psHeader := ps.Header() + tc.malleatePartSetHeader(&psHeader) + assert.Equal(t, tc.expectErr, psHeader.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestPart_ValidateBasic(t *testing.T) { + testCases := []struct { + testName string + malleatePart func(*Part) + expectErr bool + }{ + {"Good Part", func(pt *Part) {}, false}, + {"Too big part", func(pt *Part) { pt.Bytes = make([]byte, BlockPartSizeBytes+1) }, true}, + {"Good small last part", func(pt *Part) { + pt.Index = 1 + pt.Bytes = make([]byte, BlockPartSizeBytes-1) + pt.Proof.Total = 2 + pt.Proof.Index = 1 + }, false}, + {"Too small inner part", func(pt *Part) { + pt.Index = 0 + pt.Bytes = make([]byte, BlockPartSizeBytes-1) + pt.Proof.Total = 2 + }, true}, + {"Too big proof", func(pt *Part) { + pt.Proof = merkle.Proof{ + Total: 2, + Index: 1, + LeafHash: make([]byte, 1024*1024), + } + pt.Index = 1 + }, true}, + {"Index mismatch", func(pt *Part) { + pt.Index = 1 + pt.Proof.Index = 0 + }, true}, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + data := cmtrand.Bytes(testPartSize * 100) + ps := NewPartSetFromData(data, testPartSize) + part := ps.GetPart(0) + tc.malleatePart(part) + assert.Equal(t, tc.expectErr, part.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestParSetHeaderProtoBuf(t *testing.T) { + testCases := []struct { + msg string + ps1 *PartSetHeader + expPass bool + }{ + {"success empty", &PartSetHeader{}, true}, + {"success", + &PartSetHeader{Total: 1, Hash: []byte("hash")}, true}, + } + + for _, tc := range testCases { + protoBlockID := tc.ps1.ToProto() + + psh, err := PartSetHeaderFromProto(&protoBlockID) + if tc.expPass { + require.Equal(t, tc.ps1, psh, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +func TestPartProtoBuf(t *testing.T) { + + proof := merkle.Proof{ + Total: 1, + Index: 1, + LeafHash: cmtrand.Bytes(32), + } + testCases := []struct { + msg string + ps1 *Part + expPass bool + }{ + {"failure empty", &Part{}, false}, + {"failure nil", nil, false}, + {"success", + &Part{Index: 1, Bytes: cmtrand.Bytes(32), Proof: proof}, true}, + } + + for _, tc := range testCases { + proto, err := tc.ps1.ToProto() + if tc.expPass { + require.NoError(t, err, tc.msg) + } + + p, err := PartFromProto(proto) + if tc.expPass { + require.NoError(t, err) + require.Equal(t, tc.ps1, p, tc.msg) + } + } +} diff --git a/types/priv_validator.go b/types/priv_validator.go new file mode 100644 index 0000000..9d5491b --- /dev/null +++ b/types/priv_validator.go @@ -0,0 +1,158 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// PrivValidator defines the functionality of a local CometBFT validator +// that signs votes and proposals, and never double signs. +type PrivValidator interface { + GetPubKey() (crypto.PubKey, error) + + SignVote(chainID string, vote *cmtproto.Vote) error + SignProposal(chainID string, proposal *cmtproto.Proposal) error +} + +type PrivValidatorsByAddress []PrivValidator + +func (pvs PrivValidatorsByAddress) Len() int { + return len(pvs) +} + +func (pvs PrivValidatorsByAddress) Less(i, j int) bool { + pvi, err := pvs[i].GetPubKey() + if err != nil { + panic(err) + } + pvj, err := pvs[j].GetPubKey() + if err != nil { + panic(err) + } + + return bytes.Compare(pvi.Address(), pvj.Address()) == -1 +} + +func (pvs PrivValidatorsByAddress) Swap(i, j int) { + pvs[i], pvs[j] = pvs[j], pvs[i] +} + +//---------------------------------------- +// MockPV + +// MockPV implements PrivValidator without any safety or persistence. +// Only use it for testing. +type MockPV struct { + PrivKey crypto.PrivKey + breakProposalSigning bool + breakVoteSigning bool +} + +func NewMockPV() MockPV { + return MockPV{ed25519.GenPrivKey(), false, false} +} + +// NewMockPVWithParams allows one to create a MockPV instance, but with finer +// grained control over the operation of the mock validator. This is useful for +// mocking test failures. +func NewMockPVWithParams(privKey crypto.PrivKey, breakProposalSigning, breakVoteSigning bool) MockPV { + return MockPV{privKey, breakProposalSigning, breakVoteSigning} +} + +// Implements PrivValidator. +func (pv MockPV) GetPubKey() (crypto.PubKey, error) { + return pv.PrivKey.PubKey(), nil +} + +// Implements PrivValidator. +func (pv MockPV) SignVote(chainID string, vote *cmtproto.Vote) error { + useChainID := chainID + if pv.breakVoteSigning { + useChainID = "incorrect-chain-id" + } + + signBytes := VoteSignBytes(useChainID, vote) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } + vote.Signature = sig + + var extSig []byte + // We only sign vote extensions for non-nil precommits + if vote.Type == cmtproto.PrecommitType && !ProtoBlockIDIsNil(&vote.BlockID) { + extSignBytes := VoteExtensionSignBytes(useChainID, vote) + extSig, err = pv.PrivKey.Sign(extSignBytes) + if err != nil { + return err + } + } else if len(vote.Extension) > 0 { + return errors.New("unexpected vote extension - vote extensions are only allowed in non-nil precommits") + } + vote.ExtensionSignature = extSig + return nil +} + +// Implements PrivValidator. +func (pv MockPV) SignProposal(chainID string, proposal *cmtproto.Proposal) error { + useChainID := chainID + if pv.breakProposalSigning { + useChainID = "incorrect-chain-id" + } + + signBytes := ProposalSignBytes(useChainID, proposal) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } + proposal.Signature = sig + return nil +} + +func (pv MockPV) ExtractIntoValidator(votingPower int64) *Validator { + pubKey, _ := pv.GetPubKey() + return &Validator{ + Address: pubKey.Address(), + PubKey: pubKey, + VotingPower: votingPower, + } +} + +// String returns a string representation of the MockPV. +func (pv MockPV) String() string { + mpv, _ := pv.GetPubKey() // mockPV will never return an error, ignored here + return fmt.Sprintf("MockPV{%v}", mpv.Address()) +} + +// XXX: Implement. +func (pv MockPV) DisableChecks() { + // Currently this does nothing, + // as MockPV has no safety checks at all. +} + +type ErroringMockPV struct { + MockPV +} + +var ErroringMockPVErr = errors.New("erroringMockPV always returns an error") + +// Implements PrivValidator. +func (pv *ErroringMockPV) SignVote(string, *cmtproto.Vote) error { + return ErroringMockPVErr +} + +// Implements PrivValidator. +func (pv *ErroringMockPV) SignProposal(string, *cmtproto.Proposal) error { + return ErroringMockPVErr +} + +// NewErroringMockPV returns a MockPV that fails on each signing request. Again, for testing only. + +func NewErroringMockPV() *ErroringMockPV { + return &ErroringMockPV{MockPV{ed25519.GenPrivKey(), false, false}} +} diff --git a/types/proposal.go b/types/proposal.go new file mode 100644 index 0000000..ebbe569 --- /dev/null +++ b/types/proposal.go @@ -0,0 +1,177 @@ +package types + +import ( + "errors" + "fmt" + "time" + + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/protoio" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +var ( + ErrInvalidBlockPartSignature = errors.New("error invalid block part signature") + ErrInvalidBlockPartHash = errors.New("error invalid block part hash") +) + +// Proposal defines a block proposal for the consensus. +// It refers to the block by BlockID field. +// It must be signed by the correct proposer for the given Height/Round +// to be considered valid. It may depend on votes from a previous round, +// a so-called Proof-of-Lock (POL) round, as noted in the POLRound. +// If POLRound >= 0, then BlockID corresponds to the block that is locked in POLRound. +type Proposal struct { + Type cmtproto.SignedMsgType + Height int64 `json:"height"` + Round int32 `json:"round"` // there can not be greater than 2_147_483_647 rounds + POLRound int32 `json:"pol_round"` // -1 if null. + BlockID BlockID `json:"block_id"` + Timestamp time.Time `json:"timestamp"` + Signature []byte `json:"signature"` +} + +// NewProposal returns a new Proposal. +// If there is no POLRound, polRound should be -1. +func NewProposal(height int64, round int32, polRound int32, blockID BlockID) *Proposal { + return &Proposal{ + Type: cmtproto.ProposalType, + Height: height, + Round: round, + BlockID: blockID, + POLRound: polRound, + Timestamp: cmttime.Now(), + } +} + +// ValidateBasic performs basic validation. +func (p *Proposal) ValidateBasic() error { + if p.Type != cmtproto.ProposalType { + return errors.New("invalid Type") + } + if p.Height < 0 { + return errors.New("negative Height") + } + if p.Round < 0 { + return errors.New("negative Round") + } + if p.POLRound < -1 { + return errors.New("negative POLRound (exception: -1)") + } + if err := p.BlockID.ValidateBasic(); err != nil { + return fmt.Errorf("wrong BlockID: %v", err) + } + // ValidateBasic above would pass even if the BlockID was empty: + if !p.BlockID.IsComplete() { + return fmt.Errorf("expected a complete, non-empty BlockID, got: %v", p.BlockID) + } + + // NOTE: Timestamp validation is subtle and handled elsewhere. + + if len(p.Signature) == 0 { + return errors.New("signature is missing") + } + + if len(p.Signature) > MaxSignatureSize { + return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize) + } + return nil +} + +// ValidateBlockSize block size ensures that a proposal block is not larger +// than a maximum number of bytes, based on the total amount of parts reported +// in the PartSetHeader. If -1 is passed as the maxBlockSizeBytes, +// types.MaxBlockSizeBytes will be used as the maximum. +func (p *Proposal) ValidateBlockSize(maxBlockSizeBytes int64) error { + if maxBlockSizeBytes == -1 { + maxBlockSizeBytes = int64(MaxBlockSizeBytes) + } + totalParts := int64(p.BlockID.PartSetHeader.Total) + maxParts := (maxBlockSizeBytes-1)/int64(BlockPartSizeBytes) + 1 + if totalParts > maxParts { + return fmt.Errorf("proposal has too many parts %d (max: %d)", totalParts, maxParts) + } + return nil +} + +// String returns a string representation of the Proposal. +// +// 1. height +// 2. round +// 3. block ID +// 4. POL round +// 5. first 6 bytes of signature +// 6. timestamp +// +// See BlockID#String. +func (p *Proposal) String() string { + return fmt.Sprintf("Proposal{%v/%v (%v, %v) %X @ %s}", + p.Height, + p.Round, + p.BlockID, + p.POLRound, + cmtbytes.Fingerprint(p.Signature), + CanonicalTime(p.Timestamp)) +} + +// ProposalSignBytes returns the proto-encoding of the canonicalized Proposal, +// for signing. Panics if the marshaling fails. +// +// The encoded Protobuf message is varint length-prefixed (using MarshalDelimited) +// for backwards-compatibility with the Amino encoding, due to e.g. hardware +// devices that rely on this encoding. +// +// See CanonicalizeProposal +func ProposalSignBytes(chainID string, p *cmtproto.Proposal) []byte { + pb := CanonicalizeProposal(chainID, p) + bz, err := protoio.MarshalDelimited(&pb) + if err != nil { + panic(err) + } + + return bz +} + +// ToProto converts Proposal to protobuf +func (p *Proposal) ToProto() *cmtproto.Proposal { + if p == nil { + return &cmtproto.Proposal{} + } + pb := new(cmtproto.Proposal) + + pb.BlockID = p.BlockID.ToProto() + pb.Type = p.Type + pb.Height = p.Height + pb.Round = p.Round + pb.PolRound = p.POLRound + pb.Timestamp = p.Timestamp + pb.Signature = p.Signature + + return pb +} + +// FromProto sets a protobuf Proposal to the given pointer. +// It returns an error if the proposal is invalid. +func ProposalFromProto(pp *cmtproto.Proposal) (*Proposal, error) { + if pp == nil { + return nil, errors.New("nil proposal") + } + + p := new(Proposal) + + blockID, err := BlockIDFromProto(&pp.BlockID) + if err != nil { + return nil, err + } + + p.BlockID = *blockID + p.Type = pp.Type + p.Height = pp.Height + p.Round = pp.Round + p.POLRound = pp.PolRound + p.Timestamp = pp.Timestamp + p.Signature = pp.Signature + + return p, p.ValidateBasic() +} diff --git a/types/proposal_test.go b/types/proposal_test.go new file mode 100644 index 0000000..359f5ff --- /dev/null +++ b/types/proposal_test.go @@ -0,0 +1,219 @@ +package types + +import ( + "math" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/protoio" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +var ( + testProposal *Proposal + pbp *cmtproto.Proposal +) + +func init() { + var stamp, err = time.Parse(TimeFormat, "2018-02-11T07:09:22.765Z") + if err != nil { + panic(err) + } + testProposal = &Proposal{ + Height: 12345, + Round: 23456, + BlockID: BlockID{Hash: []byte("--June_15_2020_amino_was_removed"), + PartSetHeader: PartSetHeader{Total: 111, Hash: []byte("--June_15_2020_amino_was_removed")}}, + POLRound: -1, + Timestamp: stamp, + } + pbp = testProposal.ToProto() +} + +func TestProposalSignable(t *testing.T) { + chainID := "test_chain_id" + signBytes := ProposalSignBytes(chainID, pbp) + pb := CanonicalizeProposal(chainID, pbp) + + expected, err := protoio.MarshalDelimited(&pb) + require.NoError(t, err) + require.Equal(t, expected, signBytes, "Got unexpected sign bytes for Proposal") +} + +func TestProposalString(t *testing.T) { + str := testProposal.String() + expected := `Proposal{12345/23456 (2D2D4A756E655F31355F323032305F616D696E6F5F7761735F72656D6F766564:111:2D2D4A756E65, -1) 000000000000 @ 2018-02-11T07:09:22.765Z}` //nolint:lll // ignore line length for tests + if str != expected { + t.Errorf("got unexpected string for Proposal. Expected:\n%v\nGot:\n%v", expected, str) + } +} + +func TestProposalVerifySignature(t *testing.T) { + privVal := NewMockPV() + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) + + prop := NewProposal( + 4, 2, 2, + BlockID{cmtrand.Bytes(tmhash.Size), PartSetHeader{777, cmtrand.Bytes(tmhash.Size)}}) + p := prop.ToProto() + signBytes := ProposalSignBytes("test_chain_id", p) + + // sign it + err = privVal.SignProposal("test_chain_id", p) + require.NoError(t, err) + prop.Signature = p.Signature + + // verify the same proposal + valid := pubKey.VerifySignature(signBytes, prop.Signature) + require.True(t, valid) + + // serialize, deserialize and verify again.... + newProp := new(cmtproto.Proposal) + pb := prop.ToProto() + + bs, err := proto.Marshal(pb) + require.NoError(t, err) + + err = proto.Unmarshal(bs, newProp) + require.NoError(t, err) + + np, err := ProposalFromProto(newProp) + require.NoError(t, err) + + // verify the transmitted proposal + newSignBytes := ProposalSignBytes("test_chain_id", pb) + require.Equal(t, string(signBytes), string(newSignBytes)) + valid = pubKey.VerifySignature(newSignBytes, np.Signature) + require.True(t, valid) +} + +func BenchmarkProposalWriteSignBytes(b *testing.B) { + for i := 0; i < b.N; i++ { + ProposalSignBytes("test_chain_id", pbp) + } +} + +func BenchmarkProposalSign(b *testing.B) { + privVal := NewMockPV() + for i := 0; i < b.N; i++ { + err := privVal.SignProposal("test_chain_id", pbp) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkProposalVerifySignature(b *testing.B) { + privVal := NewMockPV() + err := privVal.SignProposal("test_chain_id", pbp) + require.NoError(b, err) + pubKey, err := privVal.GetPubKey() + require.NoError(b, err) + + for i := 0; i < b.N; i++ { + pubKey.VerifySignature(ProposalSignBytes("test_chain_id", pbp), testProposal.Signature) + } +} + +func TestProposalValidateBasic(t *testing.T) { + + privVal := NewMockPV() + testCases := []struct { + testName string + malleateProposal func(*Proposal) + expectErr bool + }{ + {"Good Proposal", func(p *Proposal) {}, false}, + {"Invalid Type", func(p *Proposal) { p.Type = cmtproto.PrecommitType }, true}, + {"Invalid Height", func(p *Proposal) { p.Height = -1 }, true}, + {"Invalid Round", func(p *Proposal) { p.Round = -1 }, true}, + {"Invalid POLRound", func(p *Proposal) { p.POLRound = -2 }, true}, + {"Invalid BlockId", func(p *Proposal) { + p.BlockID = BlockID{[]byte{1, 2, 3}, PartSetHeader{111, []byte("blockparts")}} + }, true}, + {"Invalid Signature", func(p *Proposal) { + p.Signature = make([]byte, 0) + }, true}, + {"Too big Signature", func(p *Proposal) { + p.Signature = make([]byte, MaxSignatureSize+1) + }, true}, + } + blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash"))) + + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + prop := NewProposal( + 4, 2, 2, + blockID) + p := prop.ToProto() + err := privVal.SignProposal("test_chain_id", p) + prop.Signature = p.Signature + require.NoError(t, err) + tc.malleateProposal(prop) + assert.Equal(t, tc.expectErr, prop.ValidateBasic() != nil, "Validate Basic had an unexpected result") + }) + } +} + +func TestProposalProtoBuf(t *testing.T) { + proposal := NewProposal(1, 2, 3, makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))) + proposal.Signature = []byte("sig") + proposal2 := NewProposal(1, 2, 3, BlockID{}) + + testCases := []struct { + msg string + p1 *Proposal + expPass bool + }{ + {"success", proposal, true}, + {"success", proposal2, false}, // blcokID cannot be empty + {"empty proposal failure validatebasic", &Proposal{}, false}, + {"nil proposal", nil, false}, + } + for _, tc := range testCases { + protoProposal := tc.p1.ToProto() + + p, err := ProposalFromProto(protoProposal) + if tc.expPass { + require.NoError(t, err) + require.Equal(t, tc.p1, p, tc.msg) + } else { + require.Error(t, err) + } + } +} + +func TestProposalValidateBlockSize(t *testing.T) { + testCases := []struct { + testName string + maxBlockSize int64 + proposal *Proposal + expectPass bool + }{ + {"10 chunk max, 5 chunk proposal, success", int64(10 * BlockPartSizeBytes), NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: 5}}), true}, + {"10 chunk max, 20 chunk proposal, fail", int64(10 * BlockPartSizeBytes), NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: 20}}), false}, + {"10 chunk max, max uint32 chunk proposal, fail", int64(10 * BlockPartSizeBytes), NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: math.MaxUint32}}), false}, + {"-1 chunk max, max uint32 chunk proposal, fail", -1, NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: math.MaxUint32}}), false}, + {"0 chunk max, max uint32 chunk proposal, fail", -1, NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: math.MaxUint32}}), false}, + {"total parts equals chunk max, success", -1, NewProposal(0, 0, 0, BlockID{PartSetHeader: PartSetHeader{Total: 1600}}), true}, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.testName, func(t *testing.T) { + err := tc.proposal.ValidateBlockSize(tc.maxBlockSize) + if tc.expectPass { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/types/protobuf.go b/types/protobuf.go new file mode 100644 index 0000000..4ad3a13 --- /dev/null +++ b/types/protobuf.go @@ -0,0 +1,113 @@ +package types + +import ( + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +//------------------------------------------------------- + +// TM2PB is used for converting CometBFT ABCI to protobuf ABCI. +// UNSTABLE +var TM2PB = tm2pb{} + +type tm2pb struct{} + +func (tm2pb) Header(header *Header) cmtproto.Header { + return cmtproto.Header{ + Version: header.Version, + ChainID: header.ChainID, + Height: header.Height, + Time: header.Time, + + LastBlockId: header.LastBlockID.ToProto(), + + LastCommitHash: header.LastCommitHash, + DataHash: header.DataHash, + + ValidatorsHash: header.ValidatorsHash, + NextValidatorsHash: header.NextValidatorsHash, + ConsensusHash: header.ConsensusHash, + AppHash: header.AppHash, + LastResultsHash: header.LastResultsHash, + + EvidenceHash: header.EvidenceHash, + ProposerAddress: header.ProposerAddress, + } +} + +func (tm2pb) Validator(val *Validator) abci.Validator { + return abci.Validator{ + Address: val.PubKey.Address(), + Power: val.VotingPower, + } +} + +func (tm2pb) BlockID(blockID BlockID) cmtproto.BlockID { + return cmtproto.BlockID{ + Hash: blockID.Hash, + PartSetHeader: TM2PB.PartSetHeader(blockID.PartSetHeader), + } +} + +func (tm2pb) PartSetHeader(header PartSetHeader) cmtproto.PartSetHeader { + return cmtproto.PartSetHeader{ + Total: header.Total, + Hash: header.Hash, + } +} + +// XXX: panics on unknown pubkey type +func (tm2pb) ValidatorUpdate(val *Validator) abci.ValidatorUpdate { + pk, err := cryptoenc.PubKeyToProto(val.PubKey) + if err != nil { + panic(err) + } + return abci.ValidatorUpdate{ + PubKey: pk, + Power: val.VotingPower, + } +} + +// XXX: panics on nil or unknown pubkey type +func (tm2pb) ValidatorUpdates(vals *ValidatorSet) []abci.ValidatorUpdate { + validators := make([]abci.ValidatorUpdate, vals.Size()) + for i, val := range vals.Validators { + validators[i] = TM2PB.ValidatorUpdate(val) + } + return validators +} + +// XXX: panics on nil or unknown pubkey type +func (tm2pb) NewValidatorUpdate(pubkey crypto.PubKey, power int64) abci.ValidatorUpdate { + pubkeyABCI, err := cryptoenc.PubKeyToProto(pubkey) + if err != nil { + panic(err) + } + return abci.ValidatorUpdate{ + PubKey: pubkeyABCI, + Power: power, + } +} + +//---------------------------------------------------------------------------- + +// PB2TM is used for converting protobuf ABCI to CometBFT ABCI. +// UNSTABLE +var PB2TM = pb2tm{} + +type pb2tm struct{} + +func (pb2tm) ValidatorUpdates(vals []abci.ValidatorUpdate) ([]*Validator, error) { + cmtVals := make([]*Validator, len(vals)) + for i, v := range vals { + pub, err := cryptoenc.PubKeyFromProto(v.PubKey) + if err != nil { + return nil, err + } + cmtVals[i] = NewValidator(pub, v.Power) + } + return cmtVals, nil +} diff --git a/types/protobuf_test.go b/types/protobuf_test.go new file mode 100644 index 0000000..1a974c0 --- /dev/null +++ b/types/protobuf_test.go @@ -0,0 +1,86 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" +) + +func TestABCIPubKey(t *testing.T) { + pkEd := ed25519.GenPrivKey().PubKey() + err := testABCIPubKey(t, pkEd) + assert.NoError(t, err) +} + +func testABCIPubKey(t *testing.T, pk crypto.PubKey) error { + abciPubKey, err := cryptoenc.PubKeyToProto(pk) + require.NoError(t, err) + pk2, err := cryptoenc.PubKeyFromProto(abciPubKey) + require.NoError(t, err) + require.Equal(t, pk, pk2) + return nil +} + +func TestABCIValidators(t *testing.T) { + pkEd := ed25519.GenPrivKey().PubKey() + + // correct validator + cmtValExpected := NewValidator(pkEd, 10) + + cmtVal := NewValidator(pkEd, 10) + + abciVal := TM2PB.ValidatorUpdate(cmtVal) + cmtVals, err := PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{abciVal}) + assert.Nil(t, err) + assert.Equal(t, cmtValExpected, cmtVals[0]) + + abciVals := TM2PB.ValidatorUpdates(NewValidatorSet(cmtVals)) + assert.Equal(t, []abci.ValidatorUpdate{abciVal}, abciVals) + + // val with address + cmtVal.Address = pkEd.Address() + + abciVal = TM2PB.ValidatorUpdate(cmtVal) + cmtVals, err = PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{abciVal}) + assert.Nil(t, err) + assert.Equal(t, cmtValExpected, cmtVals[0]) +} + +type pubKeyEddie struct{} + +func (pubKeyEddie) Address() Address { return []byte{} } +func (pubKeyEddie) Bytes() []byte { return []byte{} } +func (pubKeyEddie) VerifySignature([]byte, []byte) bool { return false } +func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } +func (pubKeyEddie) String() string { return "" } +func (pubKeyEddie) Type() string { return "pubKeyEddie" } + +func TestABCIValidatorFromPubKeyAndPower(t *testing.T) { + pubkey := ed25519.GenPrivKey().PubKey() + + abciVal := TM2PB.NewValidatorUpdate(pubkey, 10) + assert.Equal(t, int64(10), abciVal.Power) + + assert.Panics(t, func() { TM2PB.NewValidatorUpdate(nil, 10) }) + assert.Panics(t, func() { TM2PB.NewValidatorUpdate(pubKeyEddie{}, 10) }) +} + +func TestABCIValidatorWithoutPubKey(t *testing.T) { + pkEd := ed25519.GenPrivKey().PubKey() + + abciVal := TM2PB.Validator(NewValidator(pkEd, 10)) + + // pubkey must be nil + cmtValExpected := abci.Validator{ + Address: pkEd.Address(), + Power: 10, + } + + assert.Equal(t, cmtValExpected, abciVal) +} diff --git a/types/results.go b/types/results.go new file mode 100644 index 0000000..a401979 --- /dev/null +++ b/types/results.go @@ -0,0 +1,54 @@ +package types + +import ( + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/crypto/merkle" +) + +// ABCIResults wraps the deliver tx results to return a proof. +type ABCIResults []*abci.ExecTxResult + +// NewResults strips non-deterministic fields from ExecTxResult responses +// and returns ABCIResults. +func NewResults(responses []*abci.ExecTxResult) ABCIResults { + res := make(ABCIResults, len(responses)) + for i, d := range responses { + res[i] = deterministicExecTxResult(d) + } + return res +} + +// Hash returns a merkle hash of all results. +func (a ABCIResults) Hash() []byte { + return merkle.HashFromByteSlices(a.toByteSlices()) +} + +// ProveResult returns a merkle proof of one result from the set +func (a ABCIResults) ProveResult(i int) merkle.Proof { + _, proofs := merkle.ProofsFromByteSlices(a.toByteSlices()) + return *proofs[i] +} + +func (a ABCIResults) toByteSlices() [][]byte { + l := len(a) + bzs := make([][]byte, l) + for i := 0; i < l; i++ { + bz, err := a[i].Marshal() + if err != nil { + panic(err) + } + bzs[i] = bz + } + return bzs +} + +// deterministicExecTxResult strips non-deterministic fields from +// ExecTxResult and returns another ExecTxResult. +func deterministicExecTxResult(response *abci.ExecTxResult) *abci.ExecTxResult { + return &abci.ExecTxResult{ + Code: response.Code, + Data: response.Data, + GasWanted: response.GasWanted, + GasUsed: response.GasUsed, + } +} diff --git a/types/results_test.go b/types/results_test.go new file mode 100644 index 0000000..d1c8ede --- /dev/null +++ b/types/results_test.go @@ -0,0 +1,54 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" +) + +func TestABCIResults(t *testing.T) { + a := &abci.ExecTxResult{Code: 0, Data: nil} + b := &abci.ExecTxResult{Code: 0, Data: []byte{}} + c := &abci.ExecTxResult{Code: 0, Data: []byte("one")} + d := &abci.ExecTxResult{Code: 14, Data: nil} + e := &abci.ExecTxResult{Code: 14, Data: []byte("foo")} + f := &abci.ExecTxResult{Code: 14, Data: []byte("bar")} + + // Nil and []byte{} should produce the same bytes + bzA, err := a.Marshal() + require.NoError(t, err) + bzB, err := b.Marshal() + require.NoError(t, err) + + require.Equal(t, bzA, bzB) + + // a and b should be the same, don't go in results. + results := ABCIResults{a, c, d, e, f} + + // Make sure each result serializes differently + last := []byte{} + assert.Equal(t, last, bzA) // first one is empty + for i, res := range results[1:] { + bz, err := res.Marshal() + require.NoError(t, err) + + assert.NotEqual(t, last, bz, "%d", i) + last = bz + } + + // Make sure that we can get a root hash from results and verify proofs. + root := results.Hash() + assert.NotEmpty(t, root) + + for i, res := range results { + bz, err := res.Marshal() + require.NoError(t, err) + + proof := results.ProveResult(i) + valid := proof.Verify(root, bz) + assert.NoError(t, valid, "%d", i) + } +} diff --git a/types/signable.go b/types/signable.go new file mode 100644 index 0000000..c7f5683 --- /dev/null +++ b/types/signable.go @@ -0,0 +1,23 @@ +package types + +import ( + "github.com/cometbft/cometbft/crypto/ed25519" + cmtmath "github.com/cometbft/cometbft/libs/math" +) + +var ( + // MaxSignatureSize is a maximum allowed signature size for the Proposal + // and Vote. + // XXX: secp256k1 does not have Size nor MaxSize defined. + MaxSignatureSize = cmtmath.MaxInt(ed25519.SignatureSize, 64) +) + +// Signable is an interface for all signable things. +// It typically removes signatures before serializing. +// SignBytes returns the bytes to be signed +// NOTE: chainIDs are part of the SignBytes but not +// necessarily the object themselves. +// NOTE: Expected to panic if there is an error marshaling. +type Signable interface { + SignBytes(chainID string) []byte +} diff --git a/types/signed_msg_type.go b/types/signed_msg_type.go new file mode 100644 index 0000000..63a50ee --- /dev/null +++ b/types/signed_msg_type.go @@ -0,0 +1,28 @@ +package types + +import cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + +// IsVoteTypeValid returns true if t is a valid vote type. +func IsVoteTypeValid(t cmtproto.SignedMsgType) bool { + switch t { + case cmtproto.PrevoteType, cmtproto.PrecommitType: + return true + default: + return false + } +} + +var signedMsgTypeToShortName = map[cmtproto.SignedMsgType]string{ + cmtproto.UnknownType: "unknown", + cmtproto.PrevoteType: "prevote", + cmtproto.PrecommitType: "precommit", + cmtproto.ProposalType: "proposal", +} + +// Returns a short lowercase descriptor for a signed message type. +func SignedMsgTypeToShortString(t cmtproto.SignedMsgType) string { + if shortName, ok := signedMsgTypeToShortName[t]; ok { + return shortName + } + return "unknown" +} diff --git a/types/test_util.go b/types/test_util.go new file mode 100644 index 0000000..d284bfd --- /dev/null +++ b/types/test_util.go @@ -0,0 +1,123 @@ +package types + +import ( + "fmt" + "testing" + "time" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmtversion "github.com/cometbft/cometbft/proto/tendermint/version" + "github.com/cometbft/cometbft/version" + "github.com/stretchr/testify/require" +) + +func MakeExtCommit(blockID BlockID, height int64, round int32, + voteSet *VoteSet, validators []PrivValidator, now time.Time, extEnabled bool) (*ExtendedCommit, error) { + + // all sign + for i := 0; i < len(validators); i++ { + pubKey, err := validators[i].GetPubKey() + if err != nil { + return nil, fmt.Errorf("can't get pubkey: %w", err) + } + vote := &Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: int32(i), + Height: height, + Round: round, + Type: cmtproto.PrecommitType, + BlockID: blockID, + Timestamp: now, + } + + _, err = signAddVote(validators[i], vote, voteSet) + if err != nil { + return nil, err + } + } + + var enableHeight int64 + if extEnabled { + enableHeight = height + } + + return voteSet.MakeExtendedCommit(ABCIParams{VoteExtensionsEnableHeight: enableHeight}), nil +} + +func signAddVote(privVal PrivValidator, vote *Vote, voteSet *VoteSet) (bool, error) { + if vote.Type != voteSet.signedMsgType { + return false, fmt.Errorf("vote and voteset are of different types; %d != %d", vote.Type, voteSet.signedMsgType) + } + if _, err := SignAndCheckVote(vote, privVal, voteSet.ChainID(), voteSet.extensionsEnabled); err != nil { + return false, err + } + return voteSet.AddVote(vote) +} + +func MakeVote( + val PrivValidator, + chainID string, + valIndex int32, + height int64, + round int32, + step cmtproto.SignedMsgType, + blockID BlockID, + time time.Time, +) (*Vote, error) { + pubKey, err := val.GetPubKey() + if err != nil { + return nil, err + } + + vote := &Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: valIndex, + Height: height, + Round: round, + Type: step, + BlockID: blockID, + Timestamp: time, + } + + extensionsEnabled := step == cmtproto.PrecommitType + if _, err := SignAndCheckVote(vote, val, chainID, extensionsEnabled); err != nil { + return nil, err + } + + return vote, nil +} + +func MakeVoteNoError( + t *testing.T, + val PrivValidator, + chainID string, + valIndex int32, + height int64, + round int32, + step cmtproto.SignedMsgType, + blockID BlockID, + time time.Time, +) *Vote { + vote, err := MakeVote(val, chainID, valIndex, height, round, step, blockID, time) + require.NoError(t, err) + return vote +} + +// MakeBlock returns a new block with an empty header, except what can be +// computed from itself. +// It populates the same set of fields validated by ValidateBasic. +func MakeBlock(height int64, txs []Tx, lastCommit *Commit, evidence []Evidence) *Block { + block := &Block{ + Header: Header{ + Version: cmtversion.Consensus{Block: version.BlockProtocol, App: 0}, + Height: height, + }, + Data: Data{ + Txs: txs, + }, + Evidence: EvidenceData{Evidence: evidence}, + LastCommit: lastCommit, + } + block.fillHeader() + return block +} diff --git a/types/time/time.go b/types/time/time.go new file mode 100644 index 0000000..edb5948 --- /dev/null +++ b/types/time/time.go @@ -0,0 +1,58 @@ +package time + +import ( + "sort" + "time" +) + +// Now returns the current time in UTC with no monotonic component. +func Now() time.Time { + return Canonical(time.Now()) +} + +// Canonical returns UTC time with no monotonic component. +// Stripping the monotonic component is for time equality. +// See https://github.com/tendermint/tendermint/pull/2203#discussion_r215064334 +func Canonical(t time.Time) time.Time { + return t.Round(0).UTC() +} + +// WeightedTime for computing a median. +type WeightedTime struct { + Time time.Time + Weight int64 +} + +// NewWeightedTime with time and weight. +func NewWeightedTime(time time.Time, weight int64) *WeightedTime { + return &WeightedTime{ + Time: time, + Weight: weight, + } +} + +// WeightedMedian computes weighted median time for a given array of WeightedTime and the total voting power. +func WeightedMedian(weightedTimes []*WeightedTime, totalVotingPower int64) (res time.Time) { + median := totalVotingPower / 2 + + sort.Slice(weightedTimes, func(i, j int) bool { + if weightedTimes[i] == nil { + return false + } + if weightedTimes[j] == nil { + return true + } + return weightedTimes[i].Time.UnixNano() < weightedTimes[j].Time.UnixNano() + }) + + for _, weightedTime := range weightedTimes { + if weightedTime != nil { + if median <= weightedTime.Weight { + res = weightedTime.Time + break + } + median -= weightedTime.Weight + } + } + return +} diff --git a/types/time/time_test.go b/types/time/time_test.go new file mode 100644 index 0000000..6007394 --- /dev/null +++ b/types/time/time_test.go @@ -0,0 +1,56 @@ +package time + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestWeightedMedian(t *testing.T) { + m := make([]*WeightedTime, 3) + + t1 := Now() + t2 := t1.Add(5 * time.Second) + t3 := t1.Add(10 * time.Second) + + m[2] = NewWeightedTime(t1, 33) // faulty processes + m[0] = NewWeightedTime(t2, 40) // correct processes + m[1] = NewWeightedTime(t3, 27) // correct processes + totalVotingPower := int64(100) + + median := WeightedMedian(m, totalVotingPower) + assert.Equal(t, t2, median) + // median always returns value between values of correct processes + assert.Equal(t, true, (median.After(t1) || median.Equal(t1)) && + (median.Before(t3) || median.Equal(t3))) + + m[1] = NewWeightedTime(t1, 40) // correct processes + m[2] = NewWeightedTime(t2, 27) // correct processes + m[0] = NewWeightedTime(t3, 33) // faulty processes + totalVotingPower = int64(100) + + median = WeightedMedian(m, totalVotingPower) + assert.Equal(t, t2, median) + // median always returns value between values of correct processes + assert.Equal(t, true, (median.After(t1) || median.Equal(t1)) && + (median.Before(t2) || median.Equal(t2))) + + m = make([]*WeightedTime, 8) + t4 := t1.Add(15 * time.Second) + t5 := t1.Add(60 * time.Second) + + m[3] = NewWeightedTime(t1, 10) // correct processes + m[1] = NewWeightedTime(t2, 10) // correct processes + m[5] = NewWeightedTime(t2, 10) // correct processes + m[4] = NewWeightedTime(t3, 23) // faulty processes + m[0] = NewWeightedTime(t4, 20) // correct processes + m[7] = NewWeightedTime(t5, 10) // faulty processes + totalVotingPower = int64(83) + + median = WeightedMedian(m, totalVotingPower) + assert.Equal(t, t3, median) + // median always returns value between values of correct processes + assert.Equal(t, true, (median.After(t1) || median.Equal(t1)) && + (median.Before(t4) || median.Equal(t4))) +} diff --git a/types/tx.go b/types/tx.go new file mode 100644 index 0000000..65ef197 --- /dev/null +++ b/types/tx.go @@ -0,0 +1,192 @@ +package types + +import ( + "bytes" + "crypto/sha256" + "errors" + "fmt" + + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// TxKeySize is the size of the transaction key index +const TxKeySize = sha256.Size + +type ( + // Tx is an arbitrary byte array. + // NOTE: Tx has no types at this level, so when wire encoded it's just length-prefixed. + // Might we want types here ? + Tx []byte + + // TxKey is the fixed length array key used as an index. + TxKey [TxKeySize]byte +) + +// Hash computes the TMHASH hash of the wire encoded transaction. +func (tx Tx) Hash() []byte { + return tmhash.Sum(tx) +} + +func (tx Tx) Key() TxKey { + return sha256.Sum256(tx) +} + +// String returns the hex-encoded transaction as a string. +func (tx Tx) String() string { + return fmt.Sprintf("Tx{%X}", []byte(tx)) +} + +// Txs is a slice of Tx. +type Txs []Tx + +// Hash returns the Merkle root hash of the transaction hashes. +// i.e. the leaves of the tree are the hashes of the txs. +func (txs Txs) Hash() []byte { + hl := txs.hashList() + return merkle.HashFromByteSlices(hl) +} + +// Index returns the index of this transaction in the list, or -1 if not found +func (txs Txs) Index(tx Tx) int { + for i := range txs { + if bytes.Equal(txs[i], tx) { + return i + } + } + return -1 +} + +// IndexByHash returns the index of this transaction hash in the list, or -1 if not found +func (txs Txs) IndexByHash(hash []byte) int { + for i := range txs { + if bytes.Equal(txs[i].Hash(), hash) { + return i + } + } + return -1 +} + +func (txs Txs) Proof(i int) TxProof { + hl := txs.hashList() + root, proofs := merkle.ProofsFromByteSlices(hl) + + return TxProof{ + RootHash: root, + Data: txs[i], + Proof: *proofs[i], + } +} + +func (txs Txs) hashList() [][]byte { + hl := make([][]byte, len(txs)) + for i := 0; i < len(txs); i++ { + hl[i] = txs[i].Hash() + } + return hl +} + +// Txs is a slice of transactions. Sorting a Txs value orders the transactions +// lexicographically. +func (txs Txs) Len() int { return len(txs) } +func (txs Txs) Swap(i, j int) { txs[i], txs[j] = txs[j], txs[i] } +func (txs Txs) Less(i, j int) bool { + return bytes.Compare(txs[i], txs[j]) == -1 +} + +func ToTxs(txl [][]byte) Txs { + txs := make([]Tx, 0, len(txl)) + for _, tx := range txl { + txs = append(txs, tx) + } + return txs +} + +func (txs Txs) Validate(maxSizeBytes int64) error { + var size int64 + for _, tx := range txs { + size += ComputeProtoSizeForTxs([]Tx{tx}) + if size > maxSizeBytes { + return fmt.Errorf("transaction data size exceeds maximum %d", maxSizeBytes) + } + } + return nil +} + +// ToSliceOfBytes converts a Txs to slice of byte slices. +func (txs Txs) ToSliceOfBytes() [][]byte { + txBzs := make([][]byte, len(txs)) + for i := 0; i < len(txs); i++ { + txBzs[i] = txs[i] + } + return txBzs +} + +// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree. +type TxProof struct { + RootHash cmtbytes.HexBytes `json:"root_hash"` + Data Tx `json:"data"` + Proof merkle.Proof `json:"proof"` +} + +// Leaf returns the hash(tx), which is the leaf in the merkle tree which this proof refers to. +func (tp TxProof) Leaf() []byte { + return tp.Data.Hash() +} + +// Validate verifies the proof. It returns nil if the RootHash matches the dataHash argument, +// and if the proof is internally consistent. Otherwise, it returns a sensible error. +func (tp TxProof) Validate(dataHash []byte) error { + if !bytes.Equal(dataHash, tp.RootHash) { + return errors.New("proof matches different data hash") + } + if tp.Proof.Index < 0 { + return errors.New("proof index cannot be negative") + } + if tp.Proof.Total <= 0 { + return errors.New("proof total must be positive") + } + valid := tp.Proof.Verify(tp.RootHash, tp.Leaf()) + if valid != nil { + return errors.New("proof is not internally consistent") + } + return nil +} + +func (tp TxProof) ToProto() cmtproto.TxProof { + + pbProof := tp.Proof.ToProto() + + pbtp := cmtproto.TxProof{ + RootHash: tp.RootHash, + Data: tp.Data, + Proof: pbProof, + } + + return pbtp +} +func TxProofFromProto(pb cmtproto.TxProof) (TxProof, error) { + + pbProof, err := merkle.ProofFromProto(pb.Proof) + if err != nil { + return TxProof{}, err + } + + pbtp := TxProof{ + RootHash: pb.RootHash, + Data: pb.Data, + Proof: *pbProof, + } + + return pbtp, nil +} + +// ComputeProtoSizeForTxs wraps the transactions in cmtproto.Data{} and calculates the size. +// https://developers.google.com/protocol-buffers/docs/encoding +func ComputeProtoSizeForTxs(txs []Tx) int64 { + data := Data{Txs: txs} + pdData := data.ToProto() + return int64(pdData.Size()) +} diff --git a/types/tx_test.go b/types/tx_test.go new file mode 100644 index 0000000..222d78b --- /dev/null +++ b/types/tx_test.go @@ -0,0 +1,151 @@ +package types + +import ( + "bytes" + "math/rand" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtrand "github.com/cometbft/cometbft/libs/rand" + ctest "github.com/cometbft/cometbft/libs/test" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +func makeTxs(cnt, size int) Txs { + txs := make(Txs, cnt) + for i := 0; i < cnt; i++ { + txs[i] = cmtrand.Bytes(size) + } + return txs +} + +func TestTxIndex(t *testing.T) { + for i := 0; i < 20; i++ { + txs := makeTxs(15, 60) + for j := 0; j < len(txs); j++ { + tx := txs[j] + idx := txs.Index(tx) + assert.Equal(t, j, idx) + } + assert.Equal(t, -1, txs.Index(nil)) + assert.Equal(t, -1, txs.Index(Tx("foodnwkf"))) + } +} + +func TestTxIndexByHash(t *testing.T) { + for i := 0; i < 20; i++ { + txs := makeTxs(15, 60) + for j := 0; j < len(txs); j++ { + tx := txs[j] + idx := txs.IndexByHash(tx.Hash()) + assert.Equal(t, j, idx) + } + assert.Equal(t, -1, txs.IndexByHash(nil)) + assert.Equal(t, -1, txs.IndexByHash(Tx("foodnwkf").Hash())) + } +} + +func TestValidTxProof(t *testing.T) { + cases := []struct { + txs Txs + }{ + {Txs{{1, 4, 34, 87, 163, 1}}}, + {Txs{{5, 56, 165, 2}, {4, 77}}}, + {Txs{Tx("foo"), Tx("bar"), Tx("baz")}}, + {makeTxs(20, 5)}, + {makeTxs(7, 81)}, + {makeTxs(61, 15)}, + } + + for h, tc := range cases { + txs := tc.txs + root := txs.Hash() + // make sure valid proof for every tx + for i := range txs { + tx := []byte(txs[i]) + proof := txs.Proof(i) + assert.EqualValues(t, i, proof.Proof.Index, "%d: %d", h, i) + assert.EqualValues(t, len(txs), proof.Proof.Total, "%d: %d", h, i) + assert.EqualValues(t, root, proof.RootHash, "%d: %d", h, i) + assert.EqualValues(t, tx, proof.Data, "%d: %d", h, i) + assert.EqualValues(t, txs[i].Hash(), proof.Leaf(), "%d: %d", h, i) + assert.Nil(t, proof.Validate(root), "%d: %d", h, i) + assert.NotNil(t, proof.Validate([]byte("foobar")), "%d: %d", h, i) + + // read-write must also work + var ( + p2 TxProof + pb2 cmtproto.TxProof + ) + pbProof := proof.ToProto() + bin, err := pbProof.Marshal() + require.NoError(t, err) + + err = pb2.Unmarshal(bin) + require.NoError(t, err) + + p2, err = TxProofFromProto(pb2) + if assert.Nil(t, err, "%d: %d: %+v", h, i, err) { + assert.Nil(t, p2.Validate(root), "%d: %d", h, i) + } + } + } +} + +func TestTxProofUnchangable(t *testing.T) { + // run the other test a bunch... + for i := 0; i < 40; i++ { + testTxProofUnchangable(t) + } +} + +func testTxProofUnchangable(t *testing.T) { + // make some proof + txs := makeTxs(randInt(2, 100), randInt(16, 128)) + root := txs.Hash() + i := randInt(0, len(txs)-1) + proof := txs.Proof(i) + + // make sure it is valid to start with + assert.Nil(t, proof.Validate(root)) + pbProof := proof.ToProto() + bin, err := pbProof.Marshal() + require.NoError(t, err) + + // try mutating the data and make sure nothing breaks + for j := 0; j < 500; j++ { + bad := ctest.MutateByteSlice(bin) + if !bytes.Equal(bad, bin) { + assertBadProof(t, root, bad, proof) + } + } +} + +// This makes sure that the proof doesn't deserialize into something valid. +func assertBadProof(t *testing.T, root []byte, bad []byte, good TxProof) { + + var ( + proof TxProof + pbProof cmtproto.TxProof + ) + err := pbProof.Unmarshal(bad) + if err == nil { + proof, err = TxProofFromProto(pbProof) + if err == nil { + err = proof.Validate(root) + if err == nil { + // XXX Fix simple merkle proofs so the following is *not* OK. + // This can happen if we have a slightly different total (where the + // path ends up the same). If it is something else, we have a real + // problem. + assert.NotEqual(t, proof.Proof.Total, good.Proof.Total, "bad: %#v\ngood: %#v", proof, good) + } + } + } +} + +func randInt(low, high int) int { + return rand.Intn(high-low) + low +} diff --git a/types/utils.go b/types/utils.go new file mode 100644 index 0000000..ee31121 --- /dev/null +++ b/types/utils.go @@ -0,0 +1,29 @@ +package types + +import "reflect" + +// Go lacks a simple and safe way to see if something is a typed nil. +// See: +// - https://dave.cheney.net/2017/08/09/typed-nils-in-go-2 +// - https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion +// - https://github.com/golang/go/issues/21538 +func isTypedNil(o interface{}) bool { + rv := reflect.ValueOf(o) + switch rv.Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice: + return rv.IsNil() + default: + return false + } +} + +// Returns true if it has zero length. +func isEmpty(o interface{}) bool { + rv := reflect.ValueOf(o) + switch rv.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: + return rv.Len() == 0 + default: + return false + } +} diff --git a/types/validation.go b/types/validation.go new file mode 100644 index 0000000..4ce5bdc --- /dev/null +++ b/types/validation.go @@ -0,0 +1,436 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + + "github.com/cometbft/cometbft/crypto/batch" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtmath "github.com/cometbft/cometbft/libs/math" +) + +const batchVerifyThreshold = 2 + +func shouldBatchVerify(vals *ValidatorSet, commit *Commit) bool { + return len(commit.Signatures) >= batchVerifyThreshold && + batch.SupportsBatchVerifier(vals.GetProposer().PubKey) && + vals.AllKeysHaveSameType() +} + +// VerifyCommit verifies +2/3 of the set had signed the given commit. +// +// It checks all the signatures! While it's safe to exit as soon as we have +// 2/3+ signatures, doing so would impact incentivization logic in the ABCI +// application that depends on the LastCommitInfo sent in FinalizeBlock, which +// includes which validators signed. For instance, Gaia incentivizes proposers +// with a bonus for including more than +2/3 of the signatures. +func VerifyCommit(chainID string, vals *ValidatorSet, blockID BlockID, + height int64, commit *Commit) error { + // run a basic validation of the arguments + if err := verifyBasicValsAndCommit(vals, commit, height, blockID); err != nil { + return err + } + + // calculate voting power needed. Note that total voting power is capped to + // 1/8th of max int64 so this operation should never overflow + votingPowerNeeded := vals.TotalVotingPower() * 2 / 3 + + // ignore all absent signatures + ignore := func(c CommitSig) bool { return c.BlockIDFlag == BlockIDFlagAbsent } + + // only count the signatures that are for the block + count := func(c CommitSig) bool { return c.BlockIDFlag == BlockIDFlagCommit } + + // attempt to batch verify + if shouldBatchVerify(vals, commit) { + return verifyCommitBatch(chainID, vals, commit, + votingPowerNeeded, ignore, count, true, true) + } + + // if verification failed or is not supported then fallback to single verification + return verifyCommitSingle(chainID, vals, commit, votingPowerNeeded, + ignore, count, true, true) +} + +// LIGHT CLIENT VERIFICATION METHODS + +// VerifyCommitLight verifies +2/3 of the set had signed the given commit. +// +// This method is primarily used by the light client and does NOT check all the +// signatures. +func VerifyCommitLight( + chainID string, + vals *ValidatorSet, + blockID BlockID, + height int64, + commit *Commit, +) error { + return verifyCommitLightInternal(chainID, vals, blockID, height, commit, false) +} + +// VerifyCommitLightAllSignatures verifies +2/3 of the set had signed the given commit. +// +// This method DOES check all the signatures. +func VerifyCommitLightAllSignatures( + chainID string, + vals *ValidatorSet, + blockID BlockID, + height int64, + commit *Commit, +) error { + return verifyCommitLightInternal(chainID, vals, blockID, height, commit, true) +} + +func verifyCommitLightInternal( + chainID string, + vals *ValidatorSet, + blockID BlockID, + height int64, + commit *Commit, + countAllSignatures bool, +) error { + // run a basic validation of the arguments + if err := verifyBasicValsAndCommit(vals, commit, height, blockID); err != nil { + return err + } + + // calculate voting power needed + votingPowerNeeded := vals.TotalVotingPower() * 2 / 3 + + // ignore all commit signatures that are not for the block + ignore := func(c CommitSig) bool { return c.BlockIDFlag != BlockIDFlagCommit } + + // count all the remaining signatures + count := func(c CommitSig) bool { return true } + + // attempt to batch verify + if shouldBatchVerify(vals, commit) { + return verifyCommitBatch(chainID, vals, commit, + votingPowerNeeded, ignore, count, countAllSignatures, true) + } + + // if verification failed or is not supported then fallback to single verification + return verifyCommitSingle(chainID, vals, commit, votingPowerNeeded, + ignore, count, countAllSignatures, true) +} + +// VerifyCommitLightTrusting verifies that trustLevel of the validator set signed +// this commit. +// +// NOTE the given validators do not necessarily correspond to the validator set +// for this commit, but there may be some intersection. +// +// This method is primarily used by the light client and does NOT check all the +// signatures. +func VerifyCommitLightTrusting( + chainID string, + vals *ValidatorSet, + commit *Commit, + trustLevel cmtmath.Fraction, +) error { + return verifyCommitLightTrustingInternal(chainID, vals, commit, trustLevel, false) +} + +// VerifyCommitLightTrustingAllSignatures verifies that trustLevel of the validator +// set signed this commit. +// +// NOTE the given validators do not necessarily correspond to the validator set +// for this commit, but there may be some intersection. +// +// This method DOES check all the signatures. +func VerifyCommitLightTrustingAllSignatures( + chainID string, + vals *ValidatorSet, + commit *Commit, + trustLevel cmtmath.Fraction, +) error { + return verifyCommitLightTrustingInternal(chainID, vals, commit, trustLevel, true) +} + +func verifyCommitLightTrustingInternal( + chainID string, + vals *ValidatorSet, + commit *Commit, + trustLevel cmtmath.Fraction, + countAllSignatures bool, +) error { + // sanity checks + if vals == nil { + return errors.New("nil validator set") + } + if trustLevel.Denominator == 0 { + return errors.New("trustLevel has zero Denominator") + } + if commit == nil { + return errors.New("nil commit") + } + + // safely calculate voting power needed. + totalVotingPowerMulByNumerator, overflow := safeMul(vals.TotalVotingPower(), int64(trustLevel.Numerator)) + if overflow { + return errors.New("int64 overflow while calculating voting power needed. please provide smaller trustLevel numerator") + } + votingPowerNeeded := totalVotingPowerMulByNumerator / int64(trustLevel.Denominator) + + // ignore all commit signatures that are not for the block + ignore := func(c CommitSig) bool { return c.BlockIDFlag != BlockIDFlagCommit } + + // count all the remaining signatures + count := func(c CommitSig) bool { return true } + + // attempt to batch verify commit. As the validator set doesn't necessarily + // correspond with the validator set that signed the block we need to look + // up by address rather than index. + if shouldBatchVerify(vals, commit) { + return verifyCommitBatch(chainID, vals, commit, + votingPowerNeeded, ignore, count, countAllSignatures, false) + } + + // attempt with single verification + return verifyCommitSingle(chainID, vals, commit, votingPowerNeeded, + ignore, count, countAllSignatures, false) +} + +// ValidateHash returns an error if the hash is not empty, but its +// size != tmhash.Size. +func ValidateHash(h []byte) error { + if len(h) > 0 && len(h) != tmhash.Size { + return fmt.Errorf("expected size to be %d bytes, got %d bytes", + tmhash.Size, + len(h), + ) + } + return nil +} + +// Batch verification + +// verifyCommitBatch batch verifies commits. This routine is equivalent +// to verifyCommitSingle in behavior, just faster iff every signature in the +// batch is valid. +// +// Note: The caller is responsible for checking to see if this routine is +// usable via `shouldVerifyBatch(vals, commit)`. +func verifyCommitBatch( + chainID string, + vals *ValidatorSet, + commit *Commit, + votingPowerNeeded int64, + ignoreSig func(CommitSig) bool, + countSig func(CommitSig) bool, + countAllSignatures bool, + lookUpByIndex bool, +) error { + var ( + val *Validator + valIdx int32 + seenVals = make(map[int32]int, len(commit.Signatures)) + batchSigIdxs = make([]int, 0, len(commit.Signatures)) + talliedVotingPower int64 + ) + // attempt to create a batch verifier + bv, ok := batch.CreateBatchVerifier(vals.GetProposer().PubKey) + // re-check if batch verification is supported + if !ok || len(commit.Signatures) < batchVerifyThreshold { + // This should *NEVER* happen. + return fmt.Errorf("unsupported signature algorithm or insufficient signatures for batch verification") + } + + for idx, commitSig := range commit.Signatures { + // skip over signatures that should be ignored + if ignoreSig(commitSig) { + continue + } + + // If the vals and commit have a 1-to-1 correspondance we can retrieve + // them by index else we need to retrieve them by address + if lookUpByIndex { + val = vals.Validators[idx] + if !bytes.Equal(val.Address, commitSig.ValidatorAddress) { + return fmt.Errorf("validator address mismatch at index %d: expected %X, got %X", + idx, val.Address, commitSig.ValidatorAddress) + } + } else { + valIdx, val = vals.GetByAddress(commitSig.ValidatorAddress) + + // if the signature doesn't belong to anyone in the validator set + // then we just skip over it + if val == nil { + continue + } + + // because we are getting validators by address we need to make sure + // that the same validator doesn't commit twice + if firstIndex, ok := seenVals[valIdx]; ok { + secondIndex := idx + return fmt.Errorf("double vote from %v (%d and %d)", val, firstIndex, secondIndex) + } + seenVals[valIdx] = idx + } + + // Validate signature. + voteSignBytes := commit.VoteSignBytes(chainID, int32(idx)) + + // add the key, sig and message to the verifier + if err := bv.Add(val.PubKey, voteSignBytes, commitSig.Signature); err != nil { + return err + } + batchSigIdxs = append(batchSigIdxs, idx) + + // If this signature counts then add the voting power of the validator + // to the tally + if countSig(commitSig) { + talliedVotingPower += val.VotingPower + } + + // if we don't need to verify all signatures and already have sufficient + // voting power we can break from batching and verify all the signatures + if !countAllSignatures && talliedVotingPower > votingPowerNeeded { + break + } + } + + // ensure that we have batched together enough signatures to exceed the + // voting power needed else there is no need to even verify + if got, needed := talliedVotingPower, votingPowerNeeded; got <= needed { + return ErrNotEnoughVotingPowerSigned{Got: got, Needed: needed} + } + + // attempt to verify the batch. + ok, validSigs := bv.Verify() + if ok { + // success + return nil + } + + // one or more of the signatures is invalid, find and return the first + // invalid signature. + for i, ok := range validSigs { + if !ok { + // go back from the batch index to the commit.Signatures index + idx := batchSigIdxs[i] + sig := commit.Signatures[idx] + return fmt.Errorf("wrong signature (#%d): %X", idx, sig) + } + } + + // execution reaching here is a bug, and one of the following has + // happened: + // * non-zero tallied voting power, empty batch (impossible?) + // * bv.Verify() returned `false, []bool{true, ..., true}` (BUG) + return fmt.Errorf("BUG: batch verification failed with no invalid signatures") +} + +// Single Verification + +// verifyCommitSingle single verifies commits. +// If a key does not support batch verification, or batch verification fails this will be used +// This method is used to check all the signatures included in a commit. +// It is used in consensus for validating a block LastCommit. +// CONTRACT: both commit and validator set should have passed validate basic +func verifyCommitSingle( + chainID string, + vals *ValidatorSet, + commit *Commit, + votingPowerNeeded int64, + ignoreSig func(CommitSig) bool, + countSig func(CommitSig) bool, + countAllSignatures bool, + lookUpByIndex bool, +) error { + var ( + val *Validator + valIdx int32 + seenVals = make(map[int32]int, len(commit.Signatures)) + talliedVotingPower int64 + voteSignBytes []byte + ) + for idx, commitSig := range commit.Signatures { + if ignoreSig(commitSig) { + continue + } + + if commitSig.ValidateBasic() != nil { + return fmt.Errorf("invalid signatures from %v at index %d", val, idx) + } + + // If the vals and commit have a 1-to-1 correspondence we can retrieve + // them by index else we need to retrieve them by address + if lookUpByIndex { + val = vals.Validators[idx] + if !bytes.Equal(val.Address, commitSig.ValidatorAddress) { + return fmt.Errorf("validator address mismatch at index %d: expected %X, got %X", + idx, val.Address, commitSig.ValidatorAddress) + } + } else { + valIdx, val = vals.GetByAddress(commitSig.ValidatorAddress) + + // if the signature doesn't belong to anyone in the validator set + // then we just skip over it + if val == nil { + continue + } + + // because we are getting validators by address we need to make sure + // that the same validator doesn't commit twice + if firstIndex, ok := seenVals[valIdx]; ok { + secondIndex := idx + return fmt.Errorf("double vote from %v (%d and %d)", val, firstIndex, secondIndex) + } + seenVals[valIdx] = idx + } + + if val.PubKey == nil { + return fmt.Errorf("validator %v has a nil PubKey at index %d", val, idx) + } + + voteSignBytes = commit.VoteSignBytes(chainID, int32(idx)) + + if !val.PubKey.VerifySignature(voteSignBytes, commitSig.Signature) { + return fmt.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature) + } + + // If this signature counts then add the voting power of the validator + // to the tally + if countSig(commitSig) { + talliedVotingPower += val.VotingPower + } + + // check if we have enough signatures and can thus exit early + if !countAllSignatures && talliedVotingPower > votingPowerNeeded { + return nil + } + } + + if got, needed := talliedVotingPower, votingPowerNeeded; got <= needed { + return ErrNotEnoughVotingPowerSigned{Got: got, Needed: needed} + } + + return nil +} + +func verifyBasicValsAndCommit(vals *ValidatorSet, commit *Commit, height int64, blockID BlockID) error { + if vals == nil { + return errors.New("nil validator set") + } + + if commit == nil { + return errors.New("nil commit") + } + + if vals.Size() != len(commit.Signatures) { + return NewErrInvalidCommitSignatures(vals.Size(), len(commit.Signatures)) + } + + // Validate Height and BlockID. + if height != commit.Height { + return NewErrInvalidCommitHeight(height, commit.Height) + } + if !blockID.Equals(commit.BlockID) { + return fmt.Errorf("invalid commit -- wrong block ID: want %v, got %v", + blockID, commit.BlockID) + } + + return nil +} diff --git a/types/validation_test.go b/types/validation_test.go new file mode 100644 index 0000000..e835405 --- /dev/null +++ b/types/validation_test.go @@ -0,0 +1,310 @@ +package types + +import ( + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// Check VerifyCommit, VerifyCommitLight and VerifyCommitLightTrusting basic +// verification. +func TestValidatorSet_VerifyCommit_All(t *testing.T) { + var ( + round = int32(0) + height = int64(100) + + blockID = makeBlockID([]byte("blockhash"), 1000, []byte("partshash")) + chainID = "Lalande21185" + trustLevel = cmtmath.Fraction{Numerator: 2, Denominator: 3} + ) + + testCases := []struct { + description, description2 string // description2, if not empty, is checked against VerifyCommitLightTrusting + // vote chainID + chainID string + // vote blockID + blockID BlockID + valSize int + + // height of the commit + height int64 + + // votes + blockVotes int + nilVotes int + absentVotes int + + expErr bool + }{ + {"good (batch verification)", "", chainID, blockID, 3, height, 3, 0, 0, false}, + {"good (single verification)", "", chainID, blockID, 1, height, 1, 0, 0, false}, + + {"wrong signature (#0)", "", "EpsilonEridani", blockID, 2, height, 2, 0, 0, true}, + {"wrong block ID", "", chainID, makeBlockIDRandom(), 2, height, 2, 0, 0, true}, + {"wrong height", "", chainID, blockID, 1, height - 1, 1, 0, 0, true}, + + {"wrong set size: 4 vs 3", "", chainID, blockID, 4, height, 3, 0, 0, true}, + {"wrong set size: 1 vs 2", "double vote from Validator", chainID, blockID, 1, height, 2, 0, 0, true}, + + {"insufficient voting power: got 30, needed more than 66", "", chainID, blockID, 10, height, 3, 2, 5, true}, + {"insufficient voting power: got 0, needed more than 6", "", chainID, blockID, 1, height, 0, 0, 1, true}, // absent + {"insufficient voting power: got 0, needed more than 6", "", chainID, blockID, 1, height, 0, 1, 0, true}, // nil + {"insufficient voting power: got 60, needed more than 60", "", chainID, blockID, 9, height, 6, 3, 0, true}, + } + + for _, tc := range testCases { + tc := tc + countAllSignatures := false + f := func(t *testing.T) { + _, valSet, vals := randVoteSet(tc.height, round, cmtproto.PrecommitType, tc.valSize, 10, false) + totalVotes := tc.blockVotes + tc.absentVotes + tc.nilVotes + sigs := make([]CommitSig, totalVotes) + vi := 0 + // add absent sigs first + for i := 0; i < tc.absentVotes; i++ { + sigs[vi] = NewCommitSigAbsent() + vi++ + } + for i := 0; i < tc.blockVotes+tc.nilVotes; i++ { + + pubKey, err := vals[vi%len(vals)].GetPubKey() + require.NoError(t, err) + vote := &Vote{ + ValidatorAddress: pubKey.Address(), + ValidatorIndex: int32(vi), + Height: tc.height, + Round: round, + Type: cmtproto.PrecommitType, + BlockID: tc.blockID, + Timestamp: time.Now(), + } + if i >= tc.blockVotes { + vote.BlockID = BlockID{} + } + + v := vote.ToProto() + + require.NoError(t, vals[vi%len(vals)].SignVote(tc.chainID, v)) + vote.Signature = v.Signature + + sigs[vi] = vote.CommitSig() + + vi++ + } + commit := &Commit{ + Height: tc.height, + Round: round, + BlockID: tc.blockID, + Signatures: sigs, + } + + err := valSet.VerifyCommit(chainID, blockID, height, commit) + if tc.expErr { + if assert.Error(t, err, "VerifyCommit") { + assert.Contains(t, err.Error(), tc.description, "VerifyCommit") + } + } else { + assert.NoError(t, err, "VerifyCommit") + } + + if countAllSignatures { + err = valSet.VerifyCommitLightAllSignatures(chainID, blockID, height, commit) + } else { + err = valSet.VerifyCommitLight(chainID, blockID, height, commit) + } + if tc.expErr { + if assert.Error(t, err, "VerifyCommitLight") { + assert.Contains(t, err.Error(), tc.description, "VerifyCommitLight") + } + } else { + assert.NoError(t, err, "VerifyCommitLight") + } + + // only a subsection of the tests apply to VerifyCommitLightTrusting + expErr := tc.expErr + if (!countAllSignatures && totalVotes != tc.valSize) || totalVotes < tc.valSize || !tc.blockID.Equals(blockID) || tc.height != height { + expErr = false + } + if countAllSignatures { + err = valSet.VerifyCommitLightTrustingAllSignatures(chainID, commit, trustLevel) + } else { + err = valSet.VerifyCommitLightTrusting(chainID, commit, trustLevel) + } + if expErr { + if assert.Error(t, err, "VerifyCommitLightTrusting") { + errStr := tc.description2 + if len(errStr) == 0 { + errStr = tc.description + } + assert.Contains(t, err.Error(), errStr, "VerifyCommitLightTrusting") + } + } else { + assert.NoError(t, err, "VerifyCommitLightTrusting") + } + } + t.Run(tc.description+"/"+strconv.FormatBool(countAllSignatures), f) + countAllSignatures = true + t.Run(tc.description+"/"+strconv.FormatBool(countAllSignatures), f) + } +} + +func TestValidatorSet_VerifyCommit_CheckAllSignatures(t *testing.T) { + var ( + chainID = "test_chain_id" + h = int64(3) + blockID = makeBlockIDRandom() + ) + + voteSet, valSet, vals := randVoteSet(h, 0, cmtproto.PrecommitType, 4, 10, false) + extCommit, err := MakeExtCommit(blockID, h, 0, voteSet, vals, time.Now(), false) + require.NoError(t, err) + commit := extCommit.ToCommit() + require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit)) + + // malleate 4th signature + vote := voteSet.GetByIndex(3) + v := vote.ToProto() + err = vals[3].SignVote("CentaurusA", v) + require.NoError(t, err) + vote.Signature = v.Signature + vote.ExtensionSignature = v.ExtensionSignature + commit.Signatures[3] = vote.CommitSig() + + err = valSet.VerifyCommit(chainID, blockID, h, commit) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), "wrong signature (#3)") + } +} + +func TestValidatorSet_VerifyCommitLight_ReturnsAsSoonAsMajOfVotingPowerSignedIffNotAllSigs(t *testing.T) { + var ( + chainID = "test_chain_id" + h = int64(3) + blockID = makeBlockIDRandom() + ) + + voteSet, valSet, vals := randVoteSet(h, 0, cmtproto.PrecommitType, 4, 10, false) + extCommit, err := MakeExtCommit(blockID, h, 0, voteSet, vals, time.Now(), false) + require.NoError(t, err) + commit := extCommit.ToCommit() + require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit)) + + err = valSet.VerifyCommitLightAllSignatures(chainID, blockID, h, commit) + assert.NoError(t, err) + + // malleate 4th signature (3 signatures are enough for 2/3+) + vote := voteSet.GetByIndex(3) + v := vote.ToProto() + err = vals[3].SignVote("CentaurusA", v) + require.NoError(t, err) + vote.Signature = v.Signature + vote.ExtensionSignature = v.ExtensionSignature + commit.Signatures[3] = vote.CommitSig() + + err = valSet.VerifyCommitLight(chainID, blockID, h, commit) + assert.NoError(t, err) + err = valSet.VerifyCommitLightAllSignatures(chainID, blockID, h, commit) + assert.Error(t, err) // counting all signatures detects the malleated signature +} + +func TestValidatorSet_VerifyCommitLightTrusting_ReturnsAsSoonAsTrustLevelSignedIffNotAllSigs(t *testing.T) { + var ( + chainID = "test_chain_id" + h = int64(3) + blockID = makeBlockIDRandom() + ) + + voteSet, valSet, vals := randVoteSet(h, 0, cmtproto.PrecommitType, 4, 10, false) + extCommit, err := MakeExtCommit(blockID, h, 0, voteSet, vals, time.Now(), false) + require.NoError(t, err) + commit := extCommit.ToCommit() + require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit)) + + err = valSet.VerifyCommitLightTrustingAllSignatures( + chainID, + commit, + cmtmath.Fraction{Numerator: 1, Denominator: 3}, + ) + assert.NoError(t, err) + + // malleate 3rd signature (2 signatures are enough for 1/3+ trust level) + vote := voteSet.GetByIndex(2) + v := vote.ToProto() + err = vals[2].SignVote("CentaurusA", v) + require.NoError(t, err) + vote.Signature = v.Signature + vote.ExtensionSignature = v.ExtensionSignature + commit.Signatures[2] = vote.CommitSig() + + err = valSet.VerifyCommitLightTrusting(chainID, commit, cmtmath.Fraction{Numerator: 1, Denominator: 3}) + assert.NoError(t, err) + err = valSet.VerifyCommitLightTrustingAllSignatures( + chainID, + commit, + cmtmath.Fraction{Numerator: 1, Denominator: 3}, + ) + assert.Error(t, err) // counting all signatures detects the malleated signature +} + +func TestValidatorSet_VerifyCommitLightTrusting(t *testing.T) { + var ( + blockID = makeBlockIDRandom() + voteSet, originalValset, vals = randVoteSet(1, 1, cmtproto.PrecommitType, 6, 1, false) + extCommit, err = MakeExtCommit(blockID, 1, 1, voteSet, vals, time.Now(), false) + newValSet, _ = RandValidatorSet(2, 1) + ) + require.NoError(t, err) + commit := extCommit.ToCommit() + + testCases := []struct { + valSet *ValidatorSet + err bool + }{ + // good + 0: { + valSet: originalValset, + err: false, + }, + // bad - no overlap between validator sets + 1: { + valSet: newValSet, + err: true, + }, + // good - first two are different but the rest of the same -> >1/3 + 2: { + valSet: NewValidatorSet(append(newValSet.Validators, originalValset.Validators...)), + err: false, + }, + } + + for _, tc := range testCases { + err = tc.valSet.VerifyCommitLightTrusting("test_chain_id", commit, + cmtmath.Fraction{Numerator: 1, Denominator: 3}) + if tc.err { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + } +} + +func TestValidatorSet_VerifyCommitLightTrustingErrorsOnOverflow(t *testing.T) { + var ( + blockID = makeBlockIDRandom() + voteSet, valSet, vals = randVoteSet(1, 1, cmtproto.PrecommitType, 1, MaxTotalVotingPower, false) + extCommit, err = MakeExtCommit(blockID, 1, 1, voteSet, vals, time.Now(), false) + ) + require.NoError(t, err) + + err = valSet.VerifyCommitLightTrusting("test_chain_id", extCommit.ToCommit(), + cmtmath.Fraction{Numerator: 25, Denominator: 55}) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), "int64 overflow") + } +} diff --git a/types/validator.go b/types/validator.go new file mode 100644 index 0000000..98d33e2 --- /dev/null +++ b/types/validator.go @@ -0,0 +1,194 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + "strings" + + "github.com/cometbft/cometbft/crypto" + ce "github.com/cometbft/cometbft/crypto/encoding" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +// Volatile state for each Validator +// NOTE: The ProposerPriority is not included in Validator.Hash(); +// make sure to update that method if changes are made here +type Validator struct { + Address Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` + VotingPower int64 `json:"voting_power"` + + ProposerPriority int64 `json:"proposer_priority"` +} + +// NewValidator returns a new validator with the given pubkey and voting power. +func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator { + return &Validator{ + Address: pubKey.Address(), + PubKey: pubKey, + VotingPower: votingPower, + ProposerPriority: 0, + } +} + +// ValidateBasic performs basic validation. +func (v *Validator) ValidateBasic() error { + if v == nil { + return errors.New("nil validator") + } + if v.PubKey == nil { + return errors.New("validator does not have a public key") + } + + if v.VotingPower < 0 { + return errors.New("validator has negative voting power") + } + + addr := v.PubKey.Address() + if !bytes.Equal(v.Address, addr) { + return fmt.Errorf("validator address is incorrectly derived from pubkey. Exp: %v, got %v", addr, v.Address) + } + + return nil +} + +// Creates a new copy of the validator so we can mutate ProposerPriority. +// Panics if the validator is nil. +func (v *Validator) Copy() *Validator { + vCopy := *v + return &vCopy +} + +// Returns the one with higher ProposerPriority. +func (v *Validator) CompareProposerPriority(other *Validator) *Validator { + if v == nil { + return other + } + switch { + case v.ProposerPriority > other.ProposerPriority: + return v + case v.ProposerPriority < other.ProposerPriority: + return other + default: + result := bytes.Compare(v.Address, other.Address) + switch { + case result < 0: + return v + case result > 0: + return other + default: + panic("Cannot compare identical validators") + } + } +} + +// String returns a string representation of String. +// +// 1. address +// 2. public key +// 3. voting power +// 4. proposer priority +func (v *Validator) String() string { + if v == nil { + return "nil-Validator" + } + return fmt.Sprintf("Validator{%v %v VP:%v A:%v}", + v.Address, + v.PubKey, + v.VotingPower, + v.ProposerPriority) +} + +// ValidatorListString returns a prettified validator list for logging purposes. +func ValidatorListString(vals []*Validator) string { + chunks := make([]string, len(vals)) + for i, val := range vals { + chunks[i] = fmt.Sprintf("%s:%d", val.Address, val.VotingPower) + } + + return strings.Join(chunks, ",") +} + +// Bytes computes the unique encoding of a validator with a given voting power. +// These are the bytes that gets hashed in consensus. It excludes address +// as its redundant with the pubkey. This also excludes ProposerPriority +// which changes every round. +func (v *Validator) Bytes() []byte { + pk, err := ce.PubKeyToProto(v.PubKey) + if err != nil { + panic(err) + } + + pbv := cmtproto.SimpleValidator{ + PubKey: &pk, + VotingPower: v.VotingPower, + } + + bz, err := pbv.Marshal() + if err != nil { + panic(err) + } + return bz +} + +// ToProto converts Valiator to protobuf +func (v *Validator) ToProto() (*cmtproto.Validator, error) { + if v == nil { + return nil, errors.New("nil validator") + } + + pk, err := ce.PubKeyToProto(v.PubKey) + if err != nil { + return nil, err + } + + vp := cmtproto.Validator{ + Address: v.Address, + PubKey: pk, + VotingPower: v.VotingPower, + ProposerPriority: v.ProposerPriority, + } + + return &vp, nil +} + +// FromProto sets a protobuf Validator to the given pointer. +// It returns an error if the public key is invalid. +func ValidatorFromProto(vp *cmtproto.Validator) (*Validator, error) { + if vp == nil { + return nil, errors.New("nil validator") + } + + pk, err := ce.PubKeyFromProto(vp.PubKey) + if err != nil { + return nil, err + } + v := new(Validator) + v.Address = vp.GetAddress() + v.PubKey = pk + v.VotingPower = vp.GetVotingPower() + v.ProposerPriority = vp.GetProposerPriority() + + return v, nil +} + +//---------------------------------------- +// RandValidator + +// RandValidator returns a randomized validator, useful for testing. +// UNSTABLE +func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) { + privVal := NewMockPV() + votePower := minPower + if randPower { + votePower += int64(cmtrand.Uint32()) + } + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(fmt.Errorf("could not retrieve pubkey %w", err)) + } + val := NewValidator(pubKey, votePower) + return val, privVal +} diff --git a/types/validator_set.go b/types/validator_set.go new file mode 100644 index 0000000..5f147d0 --- /dev/null +++ b/types/validator_set.go @@ -0,0 +1,1071 @@ +package types + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "math" + "math/big" + "sort" + "strings" + + "github.com/cometbft/cometbft/crypto/merkle" + "github.com/cometbft/cometbft/crypto/tmhash" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +const ( + // MaxTotalVotingPower - the maximum allowed total voting power. + // It needs to be sufficiently small to, in all cases: + // 1. prevent clipping in incrementProposerPriority() + // 2. let (diff+diffMax-1) not overflow in IncrementProposerPriority() + // (Proof of 1 is tricky, left to the reader). + // It could be higher, but this is sufficiently large for our purposes, + // and leaves room for defensive purposes. + MaxTotalVotingPower = int64(math.MaxInt64) / 8 + + // PriorityWindowSizeFactor - is a constant that when multiplied with the + // total voting power gives the maximum allowed distance between validator + // priorities. + PriorityWindowSizeFactor = 2 +) + +// ErrTotalVotingPowerOverflow is returned if the total voting power of the +// resulting validator set exceeds MaxTotalVotingPower. +var ErrTotalVotingPowerOverflow = fmt.Errorf("total voting power of resulting valset exceeds max %d", + MaxTotalVotingPower) + +// ErrProposerNotInVals is returned if the proposer is not in the validator set. +var ErrProposerNotInVals = errors.New("proposer not in validator set") + +// ValidatorSet represent a set of *Validator at a given height. +// +// The validators can be fetched by address or index. +// The index is in order of .VotingPower, so the indices are fixed for all +// rounds of a given blockchain height - ie. the validators are sorted by their +// voting power (descending). Secondary index - .Address (ascending). +// +// On the other hand, the .ProposerPriority of each validator and the +// designated .GetProposer() of a set changes every round, upon calling +// .IncrementProposerPriority(). +// +// NOTE: Not goroutine-safe. +// NOTE: All get/set to validators should copy the value for safety. +type ValidatorSet struct { + // NOTE: persisted via reflect, must be exported. + Validators []*Validator `json:"validators"` + Proposer *Validator `json:"proposer"` + + // cached (unexported) + totalVotingPower int64 + // true if all validators have the same type of public key or if the set is empty. + allKeysHaveSameType bool +} + +// NewValidatorSet initializes a ValidatorSet by copying over the values from +// `valz`, a list of Validators. If valz is nil or empty, the new ValidatorSet +// will have an empty list of Validators. +// +// The addresses of validators in `valz` must be unique otherwise the function +// panics. +// +// Note the validator set size has an implied limit equal to that of the +// MaxVotesCount - commits by a validator set larger than this will fail +// validation. +func NewValidatorSet(valz []*Validator) *ValidatorSet { + vals := &ValidatorSet{ + allKeysHaveSameType: true, + } + err := vals.updateWithChangeSet(valz, false) + if err != nil { + panic(fmt.Sprintf("Cannot create validator set: %v", err)) + } + if len(valz) > 0 { + vals.IncrementProposerPriority(1) + } + return vals +} + +func (vals *ValidatorSet) ValidateBasic() error { + if vals.IsNilOrEmpty() { + return errors.New("validator set is nil or empty") + } + + for idx, val := range vals.Validators { + if err := val.ValidateBasic(); err != nil { + return fmt.Errorf("invalid validator #%d: %w", idx, err) + } + } + + if err := vals.Proposer.ValidateBasic(); err != nil { + return fmt.Errorf("proposer failed validate basic, error: %w", err) + } + + for _, val := range vals.Validators { + if bytes.Equal(val.Address, vals.Proposer.Address) { + return nil + } + } + + return ErrProposerNotInVals +} + +// IsNilOrEmpty returns true if validator set is nil or empty. +func (vals *ValidatorSet) IsNilOrEmpty() bool { + return vals == nil || len(vals.Validators) == 0 +} + +// CopyIncrementProposerPriority increments ProposerPriority and updates the +// proposer on a copy, and returns it. +func (vals *ValidatorSet) CopyIncrementProposerPriority(times int32) *ValidatorSet { + cp := vals.Copy() + cp.IncrementProposerPriority(times) + return cp +} + +// IncrementProposerPriority increments ProposerPriority of each validator and +// updates the proposer. Panics if validator set is empty. +// `times` must be positive. +func (vals *ValidatorSet) IncrementProposerPriority(times int32) { + if vals.IsNilOrEmpty() { + panic("empty validator set") + } + if times <= 0 { + panic("Cannot call IncrementProposerPriority with non-positive times") + } + + // Cap the difference between priorities to be proportional to 2*totalPower by + // re-normalizing priorities, i.e., rescale all priorities by multiplying with: + // 2*totalVotingPower/(maxPriority - minPriority) + diffMax := PriorityWindowSizeFactor * vals.TotalVotingPower() + vals.RescalePriorities(diffMax) + vals.shiftByAvgProposerPriority() + + var proposer *Validator + // Call IncrementProposerPriority(1) times times. + for i := int32(0); i < times; i++ { + proposer = vals.incrementProposerPriority() + } + + vals.Proposer = proposer +} + +// RescalePriorities rescales the priorities such that the distance between the +// maximum and minimum is smaller than `diffMax`. Panics if validator set is +// empty. +func (vals *ValidatorSet) RescalePriorities(diffMax int64) { + if vals.IsNilOrEmpty() { + panic("empty validator set") + } + // NOTE: This check is merely a sanity check which could be + // removed if all tests would init. voting power appropriately; + // i.e. diffMax should always be > 0 + if diffMax <= 0 { + return + } + + // Calculating ceil(diff/diffMax): + // Re-normalization is performed by dividing by an integer for simplicity. + // NOTE: This may make debugging priority issues easier as well. + diff := computeMaxMinPriorityDiff(vals) + ratio := (diff + diffMax - 1) / diffMax + if diff > diffMax { + for _, val := range vals.Validators { + val.ProposerPriority /= ratio + } + } +} + +func (vals *ValidatorSet) incrementProposerPriority() *Validator { + for _, val := range vals.Validators { + // Check for overflow for sum. + newPrio := safeAddClip(val.ProposerPriority, val.VotingPower) + val.ProposerPriority = newPrio + } + // Decrement the validator with most ProposerPriority. + mostest := vals.getValWithMostPriority() + // Mind the underflow. + mostest.ProposerPriority = safeSubClip(mostest.ProposerPriority, vals.TotalVotingPower()) + + return mostest +} + +// Should not be called on an empty validator set. +func (vals *ValidatorSet) computeAvgProposerPriority() int64 { + n := int64(len(vals.Validators)) + sum := big.NewInt(0) + for _, val := range vals.Validators { + sum.Add(sum, big.NewInt(val.ProposerPriority)) + } + avg := sum.Div(sum, big.NewInt(n)) + if avg.IsInt64() { + return avg.Int64() + } + + // This should never happen: each val.ProposerPriority is in bounds of int64. + panic(fmt.Sprintf("Cannot represent avg ProposerPriority as an int64 %v", avg)) +} + +// Compute the difference between the max and min ProposerPriority of that set. +func computeMaxMinPriorityDiff(vals *ValidatorSet) int64 { + if vals.IsNilOrEmpty() { + panic("empty validator set") + } + max := int64(math.MinInt64) + min := int64(math.MaxInt64) + for _, v := range vals.Validators { + if v.ProposerPriority < min { + min = v.ProposerPriority + } + if v.ProposerPriority > max { + max = v.ProposerPriority + } + } + diff := max - min + if diff < 0 { + return -1 * diff + } + return diff +} + +func (vals *ValidatorSet) getValWithMostPriority() *Validator { + var res *Validator + for _, val := range vals.Validators { + res = res.CompareProposerPriority(val) + } + return res +} + +func (vals *ValidatorSet) shiftByAvgProposerPriority() { + if vals.IsNilOrEmpty() { + panic("empty validator set") + } + avgProposerPriority := vals.computeAvgProposerPriority() + for _, val := range vals.Validators { + val.ProposerPriority = safeSubClip(val.ProposerPriority, avgProposerPriority) + } +} + +// Makes a copy of the validator list. +func validatorListCopy(valsList []*Validator) []*Validator { + if valsList == nil { + return nil + } + valsCopy := make([]*Validator, len(valsList)) + for i, val := range valsList { + valsCopy[i] = val.Copy() + } + return valsCopy +} + +// Copy each validator into a new ValidatorSet. +func (vals *ValidatorSet) Copy() *ValidatorSet { + return &ValidatorSet{ + Validators: validatorListCopy(vals.Validators), + Proposer: vals.Proposer, + totalVotingPower: vals.totalVotingPower, + allKeysHaveSameType: vals.allKeysHaveSameType, + } +} + +// HasAddress returns true if address given is in the validator set, false - +// otherwise. +func (vals *ValidatorSet) HasAddress(address []byte) bool { + for _, val := range vals.Validators { + if bytes.Equal(val.Address, address) { + return true + } + } + return false +} + +// GetByAddress returns an index of the validator with address and validator +// itself (copy) if found. Otherwise, -1 and nil are returned. +func (vals *ValidatorSet) GetByAddress(address []byte) (index int32, val *Validator) { + for idx, val := range vals.Validators { + if bytes.Equal(val.Address, address) { + return int32(idx), val.Copy() + } + } + return -1, nil +} + +// GetByIndex returns the validator's address and validator itself (copy) by +// index. +// It returns nil values if index is less than 0 or greater or equal to +// len(ValidatorSet.Validators). +func (vals *ValidatorSet) GetByIndex(index int32) (address []byte, val *Validator) { + if index < 0 || int(index) >= len(vals.Validators) { + return nil, nil + } + val = vals.Validators[index] + return val.Address, val.Copy() +} + +// Size returns the length of the validator set. +func (vals *ValidatorSet) Size() int { + return len(vals.Validators) +} + +// Forces recalculation of the set's total voting power. +// Returns an error if total voting power exceeds MaxTotalVotingPower. +func (vals *ValidatorSet) updateTotalVotingPower() error { + sum := int64(0) + for _, val := range vals.Validators { + // mind overflow + sum = safeAddClip(sum, val.VotingPower) + if sum > MaxTotalVotingPower { + return fmt.Errorf("total voting power %d exceeds maximum %d", sum, MaxTotalVotingPower) + } + } + + vals.totalVotingPower = sum + return nil +} + +// TotalVotingPowerSafe returns the sum of the voting powers of all validators, +// or an error if the total exceeds MaxTotalVotingPower. +func (vals *ValidatorSet) TotalVotingPowerSafe() (int64, error) { + if vals.totalVotingPower == 0 { + if err := vals.updateTotalVotingPower(); err != nil { + return 0, err + } + } + return vals.totalVotingPower, nil +} + +// TotalVotingPower returns the sum of the voting powers of all validators. +// It recomputes the total voting power if required. +func (vals *ValidatorSet) TotalVotingPower() int64 { + if vals.totalVotingPower == 0 { + if err := vals.updateTotalVotingPower(); err != nil { + panic(err) + } + } + return vals.totalVotingPower +} + +// GetProposer returns the current proposer. If the validator set is empty, nil +// is returned. +func (vals *ValidatorSet) GetProposer() (proposer *Validator) { + if len(vals.Validators) == 0 { + return nil + } + if vals.Proposer == nil { + vals.Proposer = vals.findProposer() + } + return vals.Proposer.Copy() +} + +func (vals *ValidatorSet) findProposer() *Validator { + var proposer *Validator + for _, val := range vals.Validators { + if proposer == nil || !bytes.Equal(val.Address, proposer.Address) { + proposer = proposer.CompareProposerPriority(val) + } + } + return proposer +} + +// Hash returns the Merkle root hash build using validators (as leaves) in the +// set. +// +// See merkle.HashFromByteSlices. +func (vals *ValidatorSet) Hash() []byte { + bzs := make([][]byte, len(vals.Validators)) + for i, val := range vals.Validators { + bzs[i] = val.Bytes() + } + return merkle.HashFromByteSlices(bzs) +} + +// ProposerPriorityHash returns the tmhash of the proposer priorities. +// Validator set must be sorted to get the same hash. +// If the validator set is empty, nil is returned. +func (vals *ValidatorSet) ProposerPriorityHash() []byte { + if len(vals.Validators) == 0 { + return nil + } + + buf := make([]byte, binary.MaxVarintLen64*len(vals.Validators)) + total := 0 + for _, val := range vals.Validators { + n := binary.PutVarint(buf, val.ProposerPriority) + total += n + } + return tmhash.Sum(buf[:total]) +} + +// Iterate will run the given function over the set. +func (vals *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { + for i, val := range vals.Validators { + stop := fn(i, val.Copy()) + if stop { + break + } + } +} + +// Checks changes against duplicates, splits the changes in updates and +// removals, sorts them by address. +// +// Returns: +// updates, removals - the sorted lists of updates and removals +// err - non-nil if duplicate entries or entries with negative voting power are seen +// +// No changes are made to 'origChanges'. +func processChanges(origChanges []*Validator) (updates, removals []*Validator, err error) { + // Make a deep copy of the changes and sort by address. + changes := validatorListCopy(origChanges) + sort.Sort(ValidatorsByAddress(changes)) + + removals = make([]*Validator, 0, len(changes)) + updates = make([]*Validator, 0, len(changes)) + var prevAddr Address + + // Scan changes by address and append valid validators to updates or removals lists. + for _, valUpdate := range changes { + if bytes.Equal(valUpdate.Address, prevAddr) { + err = fmt.Errorf("duplicate entry %v in %v", valUpdate, changes) + return nil, nil, err + } + + switch { + case valUpdate.VotingPower < 0: + err = fmt.Errorf("voting power can't be negative: %d", valUpdate.VotingPower) + return nil, nil, err + case valUpdate.VotingPower > MaxTotalVotingPower: + err = fmt.Errorf("to prevent clipping/overflow, voting power can't be higher than %d, got %d", + MaxTotalVotingPower, valUpdate.VotingPower) + return nil, nil, err + case valUpdate.VotingPower == 0: + removals = append(removals, valUpdate) + default: + updates = append(updates, valUpdate) + } + + prevAddr = valUpdate.Address + } + + return updates, removals, err +} + +// verifyUpdates verifies a list of updates against a validator set, making sure the allowed +// total voting power would not be exceeded if these updates would be applied to the set. +// +// Inputs: +// updates - a list of proper validator changes, i.e. they have been verified by processChanges for duplicates +// +// and invalid values. +// +// vals - the original validator set. Note that vals is NOT modified by this function. +// removedPower - the total voting power that will be removed after the updates are verified and applied. +// +// Returns: +// tvpAfterUpdatesBeforeRemovals - the new total voting power if these updates would be applied without the removals. +// +// Note that this will be < 2 * MaxTotalVotingPower in case high power validators are removed and +// validators are added/ updated with high power values. +// +// err - non-nil if the maximum allowed total voting power would be exceeded +func verifyUpdates( + updates []*Validator, + vals *ValidatorSet, + removedPower int64, +) (tvpAfterUpdatesBeforeRemovals int64, err error) { + delta := func(update *Validator, vals *ValidatorSet) int64 { + _, val := vals.GetByAddress(update.Address) + if val != nil { + return update.VotingPower - val.VotingPower + } + return update.VotingPower + } + + updatesCopy := validatorListCopy(updates) + sort.Slice(updatesCopy, func(i, j int) bool { + return delta(updatesCopy[i], vals) < delta(updatesCopy[j], vals) + }) + + tvpAfterRemovals := vals.TotalVotingPower() - removedPower + for _, upd := range updatesCopy { + tvpAfterRemovals += delta(upd, vals) + if tvpAfterRemovals > MaxTotalVotingPower { + return 0, ErrTotalVotingPowerOverflow + } + } + return tvpAfterRemovals + removedPower, nil +} + +func numNewValidators(updates []*Validator, vals *ValidatorSet) int { + numNewValidators := 0 + for _, valUpdate := range updates { + if !vals.HasAddress(valUpdate.Address) { + numNewValidators++ + } + } + return numNewValidators +} + +// computeNewPriorities computes the proposer priority for the validators not present in the set based on +// 'updatedTotalVotingPower'. +// Leaves unchanged the priorities of validators that are changed. +// +// 'updates' parameter must be a list of unique validators to be added or updated. +// +// 'updatedTotalVotingPower' is the total voting power of a set where all updates would be applied but +// +// not the removals. It must be < 2*MaxTotalVotingPower and may be close to this limit if close to +// MaxTotalVotingPower will be removed. This is still safe from overflow since MaxTotalVotingPower is maxInt64/8. +// +// No changes are made to the validator set 'vals'. +func computeNewPriorities(updates []*Validator, vals *ValidatorSet, updatedTotalVotingPower int64) { + for _, valUpdate := range updates { + address := valUpdate.Address + _, val := vals.GetByAddress(address) + if val == nil { + // add val + // Set ProposerPriority to -C*totalVotingPower (with C ~= 1.125) to make sure validators can't + // un-bond and then re-bond to reset their (potentially previously negative) ProposerPriority to zero. + // + // Contract: updatedVotingPower < 2 * MaxTotalVotingPower to ensure ProposerPriority does + // not exceed the bounds of int64. + // + // Compute ProposerPriority = -1.125*totalVotingPower == -(updatedVotingPower + (updatedVotingPower >> 3)). + valUpdate.ProposerPriority = -(updatedTotalVotingPower + (updatedTotalVotingPower >> 3)) + } else { + valUpdate.ProposerPriority = val.ProposerPriority + } + } +} + +// Merges the vals' validator list with the updates list. +// When two elements with same address are seen, the one from updates is selected. +// Expects updates to be a list of updates sorted by address with no duplicates or errors, +// must have been validated with verifyUpdates() and priorities computed with computeNewPriorities(). +func (vals *ValidatorSet) applyUpdates(updates []*Validator) { + existing := vals.Validators + sort.Sort(ValidatorsByAddress(existing)) + + merged := make([]*Validator, len(existing)+len(updates)) + i := 0 + + for len(existing) > 0 && len(updates) > 0 { + if bytes.Compare(existing[0].Address, updates[0].Address) < 0 { // unchanged validator + merged[i] = existing[0] + existing = existing[1:] + } else { + // Apply add or update. + merged[i] = updates[0] + if bytes.Equal(existing[0].Address, updates[0].Address) { + // Validator is present in both, advance existing. + existing = existing[1:] + } + updates = updates[1:] + } + i++ + } + + // Add the elements which are left. + for j := 0; j < len(existing); j++ { + merged[i] = existing[j] + i++ + } + // OR add updates which are left. + for j := 0; j < len(updates); j++ { + merged[i] = updates[j] + i++ + } + + vals.Validators = merged[:i] +} + +// Checks that the validators to be removed are part of the validator set. +// No changes are made to the validator set 'vals'. +func verifyRemovals(deletes []*Validator, vals *ValidatorSet) (votingPower int64, err error) { + removedVotingPower := int64(0) + for _, valUpdate := range deletes { + address := valUpdate.Address + _, val := vals.GetByAddress(address) + if val == nil { + return removedVotingPower, fmt.Errorf("failed to find validator %X to remove", address) + } + removedVotingPower += val.VotingPower + } + if len(deletes) > len(vals.Validators) { + panic("more deletes than validators") + } + return removedVotingPower, nil +} + +// Removes the validators specified in 'deletes' from validator set 'vals'. +// Should not fail as verification has been done before. +// Expects vals to be sorted by address (done by applyUpdates). +func (vals *ValidatorSet) applyRemovals(deletes []*Validator) { + existing := vals.Validators + + merged := make([]*Validator, len(existing)-len(deletes)) + i := 0 + + // Loop over deletes until we removed all of them. + for len(deletes) > 0 { + if bytes.Equal(existing[0].Address, deletes[0].Address) { + deletes = deletes[1:] + } else { // Leave it in the resulting slice. + merged[i] = existing[0] + i++ + } + existing = existing[1:] + } + + // Add the elements which are left. + for j := 0; j < len(existing); j++ { + merged[i] = existing[j] + i++ + } + + vals.Validators = merged[:i] +} + +// Main function used by UpdateWithChangeSet() and NewValidatorSet(). +// If 'allowDeletes' is false then delete operations (identified by validators with voting power 0) +// are not allowed and will trigger an error if present in 'changes'. +// The 'allowDeletes' flag is set to false by NewValidatorSet() and to true by UpdateWithChangeSet(). +func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes bool) error { + if len(changes) == 0 { + return nil + } + + // Check for duplicates within changes, split in 'updates' and 'deletes' lists (sorted). + updates, deletes, err := processChanges(changes) + if err != nil { + return err + } + + if !allowDeletes && len(deletes) != 0 { + return fmt.Errorf("cannot process validators with voting power 0: %v", deletes) + } + + // Check that the resulting set will not be empty. + if numNewValidators(updates, vals) == 0 && len(vals.Validators) == len(deletes) { + return errors.New("applying the validator changes would result in empty set") + } + + // Verify that applying the 'deletes' against 'vals' will not result in error. + // Get the voting power that is going to be removed. + removedVotingPower, err := verifyRemovals(deletes, vals) + if err != nil { + return err + } + + // Verify that applying the 'updates' against 'vals' will not result in error. + // Get the updated total voting power before removal. Note that this is < 2 * MaxTotalVotingPower + tvpAfterUpdatesBeforeRemovals, err := verifyUpdates(updates, vals, removedVotingPower) + if err != nil { + return err + } + + // Compute the priorities for updates. + computeNewPriorities(updates, vals, tvpAfterUpdatesBeforeRemovals) + + // Apply updates and removals. + vals.applyUpdates(updates) + vals.applyRemovals(deletes) + + // Should go after additions. + vals.checkAllKeysHaveSameType() + + if err = vals.updateTotalVotingPower(); err != nil { + panic(err) + } + + // Scale and center. + vals.RescalePriorities(PriorityWindowSizeFactor * vals.TotalVotingPower()) + vals.shiftByAvgProposerPriority() + + sort.Sort(ValidatorsByVotingPower(vals.Validators)) + + return nil +} + +// UpdateWithChangeSet attempts to update the validator set with 'changes'. +// It performs the following steps: +// - validates the changes making sure there are no duplicates and splits them in updates and deletes +// - verifies that applying the changes will not result in errors +// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities +// across old and newly added validators are fair +// - computes the priorities of new validators against the final set +// - applies the updates against the validator set +// - applies the removals against the validator set +// - performs scaling and centering of priority values +// +// If an error is detected during verification steps, it is returned and the validator set +// is not changed. +func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error { + return vals.updateWithChangeSet(changes, true) +} + +// VerifyCommit verifies +2/3 of the set had signed the given commit and all +// other signatures are valid +func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, + height int64, commit *Commit, +) error { + return VerifyCommit(chainID, vals, blockID, height, commit) +} + +// LIGHT CLIENT VERIFICATION METHODS + +// VerifyCommitLight verifies +2/3 of the set had signed the given commit. +// It does NOT count all signatures. +func (vals *ValidatorSet) VerifyCommitLight(chainID string, blockID BlockID, + height int64, commit *Commit, +) error { + return VerifyCommitLight(chainID, vals, blockID, height, commit) +} + +// VerifyCommitLight verifies +2/3 of the set had signed the given commit. +// It DOES count all signatures. +func (vals *ValidatorSet) VerifyCommitLightAllSignatures(chainID string, blockID BlockID, + height int64, commit *Commit, +) error { + return VerifyCommitLightAllSignatures(chainID, vals, blockID, height, commit) +} + +// VerifyCommitLightTrusting verifies that trustLevel of the validator set signed +// this commit. +// It does NOT count all signatures. +func (vals *ValidatorSet) VerifyCommitLightTrusting( + chainID string, + commit *Commit, + trustLevel cmtmath.Fraction, +) error { + return VerifyCommitLightTrusting(chainID, vals, commit, trustLevel) +} + +// VerifyCommitLightTrusting verifies that trustLevel of the validator set signed +// this commit. +// It DOES count all signatures. +func (vals *ValidatorSet) VerifyCommitLightTrustingAllSignatures( + chainID string, + commit *Commit, + trustLevel cmtmath.Fraction, +) error { + return VerifyCommitLightTrustingAllSignatures(chainID, vals, commit, trustLevel) +} + +// findPreviousProposer reverses the compare proposer priority function to find the validator +// with the lowest proposer priority which would have been the previous proposer. +// +// Is used when recreating a validator set from an existing array of validators. +func (vals *ValidatorSet) findPreviousProposer() *Validator { + var previousProposer *Validator + for _, val := range vals.Validators { + if previousProposer == nil { + previousProposer = val + continue + } + if previousProposer == previousProposer.CompareProposerPriority(val) { + previousProposer = val + } + } + return previousProposer +} + +func (vals *ValidatorSet) checkAllKeysHaveSameType() { + if vals.Size() == 0 { + vals.allKeysHaveSameType = true + return + } + + firstKeyType := "" + for _, val := range vals.Validators { + if firstKeyType == "" { + // XXX: Should only be the case in tests. + if val.PubKey == nil { + continue + } + firstKeyType = val.PubKey.Type() + } + if val.PubKey.Type() != firstKeyType { + vals.allKeysHaveSameType = false + return + } + } + + vals.allKeysHaveSameType = true +} + +// AllKeysHaveSameType returns true if all validators have the same type of +// public key or if the set is empty. +func (vals *ValidatorSet) AllKeysHaveSameType() bool { + return vals.allKeysHaveSameType +} + +// ----------------- + +// IsErrNotEnoughVotingPowerSigned returns true if err is +// ErrNotEnoughVotingPowerSigned. +func IsErrNotEnoughVotingPowerSigned(err error) bool { + return errors.As(err, &ErrNotEnoughVotingPowerSigned{}) +} + +// ErrNotEnoughVotingPowerSigned is returned when not enough validators signed +// a commit. +type ErrNotEnoughVotingPowerSigned struct { + Got int64 + Needed int64 +} + +func (e ErrNotEnoughVotingPowerSigned) Error() string { + return fmt.Sprintf("invalid commit -- insufficient voting power: got %d, needed more than %d", e.Got, e.Needed) +} + +//---------------- + +// String returns a string representation of ValidatorSet. +// +// See StringIndented. +func (vals *ValidatorSet) String() string { + return vals.StringIndented("") +} + +// StringIndented returns an intended String. +// +// See Validator#String. +func (vals *ValidatorSet) StringIndented(indent string) string { + if vals == nil { + return "nil-ValidatorSet" + } + var valStrings []string + vals.Iterate(func(index int, val *Validator) bool { + valStrings = append(valStrings, val.String()) + return false + }) + return fmt.Sprintf(`ValidatorSet{ +%s Proposer: %v +%s Validators: +%s %v +%s}`, + indent, vals.GetProposer().String(), + indent, + indent, strings.Join(valStrings, "\n"+indent+" "), + indent) +} + +//------------------------------------- + +// ValidatorsByVotingPower implements sort.Interface for []*Validator based on +// the VotingPower and Address fields. +type ValidatorsByVotingPower []*Validator + +func (valz ValidatorsByVotingPower) Len() int { return len(valz) } + +func (valz ValidatorsByVotingPower) Less(i, j int) bool { + if valz[i].VotingPower == valz[j].VotingPower { + return bytes.Compare(valz[i].Address, valz[j].Address) == -1 + } + return valz[i].VotingPower > valz[j].VotingPower +} + +func (valz ValidatorsByVotingPower) Swap(i, j int) { + valz[i], valz[j] = valz[j], valz[i] +} + +// ValidatorsByAddress implements sort.Interface for []*Validator based on +// the Address field. +type ValidatorsByAddress []*Validator + +func (valz ValidatorsByAddress) Len() int { return len(valz) } + +func (valz ValidatorsByAddress) Less(i, j int) bool { + return bytes.Compare(valz[i].Address, valz[j].Address) == -1 +} + +func (valz ValidatorsByAddress) Swap(i, j int) { + valz[i], valz[j] = valz[j], valz[i] +} + +// ToProto converts ValidatorSet to protobuf +func (vals *ValidatorSet) ToProto() (*cmtproto.ValidatorSet, error) { + if vals.IsNilOrEmpty() { + return &cmtproto.ValidatorSet{}, nil // validator set should never be nil + } + + vp := new(cmtproto.ValidatorSet) + valsProto := make([]*cmtproto.Validator, len(vals.Validators)) + for i := 0; i < len(vals.Validators); i++ { + valp, err := vals.Validators[i].ToProto() + if err != nil { + return nil, err + } + valsProto[i] = valp + } + vp.Validators = valsProto + + valProposer, err := vals.Proposer.ToProto() + if err != nil { + return nil, fmt.Errorf("toProto: validatorSet proposer error: %w", err) + } + vp.Proposer = valProposer + + // NOTE: Sometimes we use the bytes of the proto form as a hash. This means that we need to + // be consistent with cached data + vp.TotalVotingPower = 0 + + return vp, nil +} + +// ValidatorSetFromProto sets a protobuf ValidatorSet to the given pointer. +// It returns an error if any of the validators from the set or the proposer +// is invalid +func ValidatorSetFromProto(vp *cmtproto.ValidatorSet) (*ValidatorSet, error) { + if vp == nil { + return nil, errors.New("nil validator set") // validator set should never be nil, bigger issues are at play if empty + } + vals := new(ValidatorSet) + + valsProto := make([]*Validator, len(vp.Validators)) + for i := 0; i < len(vp.Validators); i++ { + v, err := ValidatorFromProto(vp.Validators[i]) + if err != nil { + return nil, err + } + valsProto[i] = v + } + vals.Validators = valsProto + vals.checkAllKeysHaveSameType() + + p, err := ValidatorFromProto(vp.GetProposer()) + if err != nil { + return nil, fmt.Errorf("fromProto: validatorSet proposer error: %w", err) + } + + vals.Proposer = p + + // NOTE: We can't trust the total voting power given to us by other peers. If someone were to + // inject a non-zeo value that wasn't the correct voting power we could assume a wrong total + // power hence we need to recompute it. + // FIXME: We should look to remove TotalVotingPower from proto or add it in the validators hash + // so we don't have to do this + // NOTE: Use TotalVotingPowerSafe to return error instead of panicking on invalid input. + if _, err := vals.TotalVotingPowerSafe(); err != nil { + return nil, err + } + + return vals, vals.ValidateBasic() +} + +// ValidatorSetFromExistingValidators takes an existing array of validators and +// rebuilds the exact same validator set that corresponds to it without +// changing the proposer priority or power if any of the validators fail +// validate basic then an empty set is returned. +func ValidatorSetFromExistingValidators(valz []*Validator) (*ValidatorSet, error) { + if len(valz) == 0 { + return nil, errors.New("validator set is empty") + } + for _, val := range valz { + err := val.ValidateBasic() + if err != nil { + return nil, fmt.Errorf("can't create validator set: %w", err) + } + } + + vals := &ValidatorSet{ + Validators: valz, + } + vals.checkAllKeysHaveSameType() + vals.Proposer = vals.findPreviousProposer() + if err := vals.updateTotalVotingPower(); err != nil { + return nil, err + } + sort.Sort(ValidatorsByVotingPower(vals.Validators)) + return vals, nil +} + +//---------------------------------------- + +// RandValidatorSet returns a randomized validator set (size: +numValidators+), +// where each validator has a voting power of +votingPower+. +// +// EXPOSED FOR TESTING. +func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []PrivValidator) { + var ( + valz = make([]*Validator, numValidators) + privValidators = make([]PrivValidator, numValidators) + ) + + for i := 0; i < numValidators; i++ { + val, privValidator := RandValidator(false, votingPower) + valz[i] = val + privValidators[i] = privValidator + } + + sort.Sort(PrivValidatorsByAddress(privValidators)) + + return NewValidatorSet(valz), privValidators +} + +// safe addition/subtraction/multiplication + +func safeAdd(a, b int64) (int64, bool) { + if b > 0 && a > math.MaxInt64-b { + return -1, true + } else if b < 0 && a < math.MinInt64-b { + return -1, true + } + return a + b, false +} + +func safeSub(a, b int64) (int64, bool) { + if b > 0 && a < math.MinInt64+b { + return -1, true + } else if b < 0 && a > math.MaxInt64+b { + return -1, true + } + return a - b, false +} + +func safeAddClip(a, b int64) int64 { + c, overflow := safeAdd(a, b) + if overflow { + if b < 0 { + return math.MinInt64 + } + return math.MaxInt64 + } + return c +} + +func safeSubClip(a, b int64) int64 { + c, overflow := safeSub(a, b) + if overflow { + if b > 0 { + return math.MinInt64 + } + return math.MaxInt64 + } + return c +} + +func safeMul(a, b int64) (int64, bool) { + if a == 0 || b == 0 { + return 0, false + } + + absOfB := b + if b < 0 { + absOfB = -b + } + + absOfA := a + if a < 0 { + absOfA = -a + } + + if absOfA > math.MaxInt64/absOfB { + return 0, true + } + + return a * b, false +} diff --git a/types/validator_set_test.go b/types/validator_set_test.go new file mode 100644 index 0000000..1673233 --- /dev/null +++ b/types/validator_set_test.go @@ -0,0 +1,1837 @@ +package types + +import ( + "bytes" + "fmt" + "math" + "sort" + "strings" + "testing" + "testing/quick" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + cryptoenc "github.com/cometbft/cometbft/crypto/encoding" + "github.com/cometbft/cometbft/crypto/sr25519" + cmtmath "github.com/cometbft/cometbft/libs/math" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +func TestValidatorSetBasic(t *testing.T) { + // empty or nil validator lists are allowed, + // but attempting to IncrementProposerPriority on them will panic. + vset := NewValidatorSet([]*Validator{}) + assert.Panics(t, func() { vset.IncrementProposerPriority(1) }) + + vset = NewValidatorSet(nil) + assert.Panics(t, func() { vset.IncrementProposerPriority(1) }) + + assert.EqualValues(t, vset, vset.Copy()) + assert.False(t, vset.HasAddress([]byte("some val"))) + idx, val := vset.GetByAddress([]byte("some val")) + assert.EqualValues(t, -1, idx) + assert.Nil(t, val) + addr, val := vset.GetByIndex(-100) + assert.Nil(t, addr) + assert.Nil(t, val) + addr, val = vset.GetByIndex(0) + assert.Nil(t, addr) + assert.Nil(t, val) + addr, val = vset.GetByIndex(100) + assert.Nil(t, addr) + assert.Nil(t, val) + assert.Zero(t, vset.Size()) + assert.Equal(t, int64(0), vset.TotalVotingPower()) + assert.Nil(t, vset.GetProposer()) + assert.Equal(t, []byte{ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, + 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, + 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, + }, vset.Hash()) + // add + val = randValidator(vset.TotalVotingPower()) + assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val})) + + assert.True(t, vset.HasAddress(val.Address)) + idx, _ = vset.GetByAddress(val.Address) + assert.EqualValues(t, 0, idx) + addr, _ = vset.GetByIndex(0) + assert.Equal(t, []byte(val.Address), addr) + assert.Equal(t, 1, vset.Size()) + assert.Equal(t, val.VotingPower, vset.TotalVotingPower()) + assert.NotNil(t, vset.Hash()) + assert.NotPanics(t, func() { vset.IncrementProposerPriority(1) }) + assert.Equal(t, val.Address, vset.GetProposer().Address) + + // update + val = randValidator(vset.TotalVotingPower()) + assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val})) + _, val = vset.GetByAddress(val.Address) + val.VotingPower += 100 + proposerPriority := val.ProposerPriority + + val.ProposerPriority = 0 + assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val})) + _, val = vset.GetByAddress(val.Address) + assert.Equal(t, proposerPriority, val.ProposerPriority) +} + +func TestValidatorSet_ValidateBasic(t *testing.T) { + val, _ := RandValidator(false, 1) + badVal := &Validator{} + val2, _ := RandValidator(false, 1) + + testCases := []struct { + vals ValidatorSet + err bool + msg string + }{ + { + vals: ValidatorSet{}, + err: true, + msg: "validator set is nil or empty", + }, + { + vals: ValidatorSet{ + Validators: []*Validator{}, + }, + err: true, + msg: "validator set is nil or empty", + }, + { + vals: ValidatorSet{ + Validators: []*Validator{val}, + }, + err: true, + msg: "proposer failed validate basic, error: nil validator", + }, + { + vals: ValidatorSet{ + Validators: []*Validator{badVal}, + }, + err: true, + msg: "invalid validator #0: validator does not have a public key", + }, + { + vals: ValidatorSet{ + Validators: []*Validator{val}, + Proposer: val, + }, + err: false, + msg: "", + }, + { + vals: ValidatorSet{ + Validators: []*Validator{val}, + Proposer: val2, + }, + err: true, + msg: ErrProposerNotInVals.Error(), + }, + } + + for _, tc := range testCases { + err := tc.vals.ValidateBasic() + if tc.err { + if assert.Error(t, err) { + assert.Equal(t, tc.msg, err.Error()) + } + } else { + assert.NoError(t, err) + } + } +} + +func TestCopy(t *testing.T) { + vset := randValidatorSet(10) + vsetHash := vset.Hash() + if len(vsetHash) == 0 { + t.Fatalf("ValidatorSet had unexpected zero hash") + } + + vsetCopy := vset.Copy() + vsetCopyHash := vsetCopy.Hash() + + if !bytes.Equal(vsetHash, vsetCopyHash) { + t.Fatalf("ValidatorSet copy had wrong hash. Orig: %X, Copy: %X", vsetHash, vsetCopyHash) + } +} + +func TestValidatorSet_ProposerPriorityHash(t *testing.T) { + vset := NewValidatorSet(nil) + assert.Equal(t, []byte(nil), vset.ProposerPriorityHash()) + + vset = randValidatorSet(3) + assert.NotNil(t, vset.ProposerPriorityHash()) + + // Marshaling and unmarshalling do not affect ProposerPriorityHash + bz, err := vset.ToProto() + assert.NoError(t, err) + vsetProto, err := ValidatorSetFromProto(bz) + assert.NoError(t, err) + assert.Equal(t, vset.ProposerPriorityHash(), vsetProto.ProposerPriorityHash()) + + // Copy does not affect ProposerPriorityHash + vsetCopy := vset.Copy() + assert.Equal(t, vset.ProposerPriorityHash(), vsetCopy.ProposerPriorityHash()) + + // Incrementing priorities changes ProposerPriorityHash() but not Hash() + vset.IncrementProposerPriority(1) + assert.Equal(t, vset.Hash(), vsetCopy.Hash()) + assert.NotEqual(t, vset.ProposerPriorityHash(), vsetCopy.ProposerPriorityHash()) +} + +// Test that IncrementProposerPriority requires positive times. +func TestIncrementProposerPriorityPositiveTimes(t *testing.T) { + vset := NewValidatorSet([]*Validator{ + newValidator([]byte("foo"), 1000), + newValidator([]byte("bar"), 300), + newValidator([]byte("baz"), 330), + }) + + assert.Panics(t, func() { vset.IncrementProposerPriority(-1) }) + assert.Panics(t, func() { vset.IncrementProposerPriority(0) }) + vset.IncrementProposerPriority(1) +} + +func BenchmarkValidatorSetCopy(b *testing.B) { + b.StopTimer() + vset := NewValidatorSet([]*Validator{}) + for i := 0; i < 1000; i++ { + privKey := ed25519.GenPrivKey() + pubKey := privKey.PubKey() + val := NewValidator(pubKey, 10) + err := vset.UpdateWithChangeSet([]*Validator{val}) + if err != nil { + panic("Failed to add validator") + } + } + b.StartTimer() + + for i := 0; i < b.N; i++ { + vset.Copy() + } +} + +//------------------------------------------------------------------- + +func TestProposerSelection1(t *testing.T) { + vset := NewValidatorSet([]*Validator{ + newValidator([]byte("foo"), 1000), + newValidator([]byte("bar"), 300), + newValidator([]byte("baz"), 330), + }) + var proposers []string + for i := 0; i < 99; i++ { + val := vset.GetProposer() + proposers = append(proposers, string(val.Address)) + vset.IncrementProposerPriority(1) + } + expected := `foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` + + ` foo foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` + + ` foo baz foo foo bar foo baz foo foo bar foo baz foo foo foo baz bar foo foo foo baz` + + ` foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo` + + ` foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo` + if expected != strings.Join(proposers, " ") { + t.Errorf("expected sequence of proposers was\n%v\nbut got \n%v", expected, strings.Join(proposers, " ")) + } +} + +func TestProposerSelection2(t *testing.T) { + addr0 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + addr1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} + addr2 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2} + + // when all voting power is same, we go in order of addresses + val0, val1, val2 := newValidator(addr0, 100), newValidator(addr1, 100), newValidator(addr2, 100) + valList := []*Validator{val0, val1, val2} + vals := NewValidatorSet(valList) + for i := 0; i < len(valList)*5; i++ { + ii := (i) % len(valList) + prop := vals.GetProposer() + if !bytes.Equal(prop.Address, valList[ii].Address) { + t.Fatalf("(%d): Expected %X. Got %X", i, valList[ii].Address, prop.Address) + } + vals.IncrementProposerPriority(1) + } + + // One validator has more than the others, but not enough to propose twice in a row + *val2 = *newValidator(addr2, 400) + vals = NewValidatorSet(valList) + // vals.IncrementProposerPriority(1) + prop := vals.GetProposer() + if !bytes.Equal(prop.Address, addr2) { + t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address) + } + vals.IncrementProposerPriority(1) + prop = vals.GetProposer() + if !bytes.Equal(prop.Address, addr0) { + t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address) + } + + // One validator has more than the others, and enough to be proposer twice in a row + *val2 = *newValidator(addr2, 401) + vals = NewValidatorSet(valList) + prop = vals.GetProposer() + if !bytes.Equal(prop.Address, addr2) { + t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address) + } + vals.IncrementProposerPriority(1) + prop = vals.GetProposer() + if !bytes.Equal(prop.Address, addr2) { + t.Fatalf("Expected address with highest voting power to be second proposer. Got %X", prop.Address) + } + vals.IncrementProposerPriority(1) + prop = vals.GetProposer() + if !bytes.Equal(prop.Address, addr0) { + t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address) + } + + // each validator should be the proposer a proportional number of times + val0, val1, val2 = newValidator(addr0, 4), newValidator(addr1, 5), newValidator(addr2, 3) + valList = []*Validator{val0, val1, val2} + propCount := make([]int, 3) + vals = NewValidatorSet(valList) + N := 1 + for i := 0; i < 120*N; i++ { + prop := vals.GetProposer() + ii := prop.Address[19] + propCount[ii]++ + vals.IncrementProposerPriority(1) + } + + if propCount[0] != 40*N { + t.Fatalf( + "Expected prop count for validator with 4/12 of voting power to be %d/%d. Got %d/%d", + 40*N, + 120*N, + propCount[0], + 120*N, + ) + } + if propCount[1] != 50*N { + t.Fatalf( + "Expected prop count for validator with 5/12 of voting power to be %d/%d. Got %d/%d", + 50*N, + 120*N, + propCount[1], + 120*N, + ) + } + if propCount[2] != 30*N { + t.Fatalf( + "Expected prop count for validator with 3/12 of voting power to be %d/%d. Got %d/%d", + 30*N, + 120*N, + propCount[2], + 120*N, + ) + } +} + +func TestProposerSelection3(t *testing.T) { + vals := []*Validator{ + newValidator([]byte("avalidator_address12"), 1), + newValidator([]byte("bvalidator_address12"), 1), + newValidator([]byte("cvalidator_address12"), 1), + newValidator([]byte("dvalidator_address12"), 1), + } + + for i := 0; i < 4; i++ { + pk := ed25519.GenPrivKey().PubKey() + vals[i].PubKey = pk + vals[i].Address = pk.Address() + } + sort.Sort(ValidatorsByAddress(vals)) + vset := NewValidatorSet(vals) + proposerOrder := make([]*Validator, 4) + for i := 0; i < 4; i++ { + proposerOrder[i] = vset.GetProposer() + vset.IncrementProposerPriority(1) + } + + // i for the loop + // j for the times + // we should go in order for ever, despite some IncrementProposerPriority with times > 1 + var ( + i int + j int32 + ) + for ; i < 10000; i++ { + got := vset.GetProposer().Address + expected := proposerOrder[j%4].Address + if !bytes.Equal(got, expected) { + t.Fatalf("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j) + } + + // serialize, deserialize, check proposer + b := vset.toBytes() + vset = vset.fromBytes(b) + + computed := vset.GetProposer() // findGetProposer() + if i != 0 { + if !bytes.Equal(got, computed.Address) { + t.Fatalf( + "vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)", + got, + computed.Address, + i, + j, + ) + } + } + + // times is usually 1 + times := int32(1) + mod := (cmtrand.Int() % 5) + 1 + if cmtrand.Int()%mod > 0 { + // sometimes its up to 5 + times = (cmtrand.Int31() % 4) + 1 + } + vset.IncrementProposerPriority(times) + + j += times + } +} + +func newValidator(address []byte, power int64) *Validator { + return &Validator{Address: address, VotingPower: power} +} + +func randPubKey() crypto.PubKey { + pubKey := make(ed25519.PubKey, ed25519.PubKeySize) + copy(pubKey, cmtrand.Bytes(32)) + return ed25519.PubKey(cmtrand.Bytes(32)) +} + +func randValidator(totalVotingPower int64) *Validator { + // this modulo limits the ProposerPriority/VotingPower to stay in the + // bounds of MaxTotalVotingPower minus the already existing voting power: + val := NewValidator(randPubKey(), int64(cmtrand.Uint64()%uint64(MaxTotalVotingPower-totalVotingPower))) + val.ProposerPriority = cmtrand.Int64() % (MaxTotalVotingPower - totalVotingPower) + return val +} + +func randValidatorSet(numValidators int) *ValidatorSet { + validators := make([]*Validator, numValidators) + totalVotingPower := int64(0) + for i := 0; i < numValidators; i++ { + validators[i] = randValidator(totalVotingPower) + totalVotingPower += validators[i].VotingPower + } + return NewValidatorSet(validators) +} + +func (vals *ValidatorSet) toBytes() []byte { + pbvs, err := vals.ToProto() + if err != nil { + panic(err) + } + + bz, err := pbvs.Marshal() + if err != nil { + panic(err) + } + + return bz +} + +func (vals *ValidatorSet) fromBytes(b []byte) *ValidatorSet { + pbvs := new(cmtproto.ValidatorSet) + err := pbvs.Unmarshal(b) + if err != nil { + // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED + panic(err) + } + + vs, err := ValidatorSetFromProto(pbvs) + if err != nil { + panic(err) + } + + return vs +} + +//------------------------------------------------------------------- + +func TestValidatorSetTotalVotingPowerPanicsOnOverflow(t *testing.T) { + // NewValidatorSet calls IncrementProposerPriority which calls TotalVotingPower() + // which should panic on overflows: + shouldPanic := func() { + NewValidatorSet([]*Validator{ + {Address: []byte("a"), VotingPower: math.MaxInt64, ProposerPriority: 0}, + {Address: []byte("b"), VotingPower: math.MaxInt64, ProposerPriority: 0}, + {Address: []byte("c"), VotingPower: math.MaxInt64, ProposerPriority: 0}, + }) + } + + assert.Panics(t, shouldPanic) +} + +func TestValidatorSetFromProtoReturnsErrorOnOverflow(t *testing.T) { + // ValidatorSetFromProto should return an error instead of panicking when total voting power exceeds MaxTotalVotingPower. + pubKey := ed25519.GenPrivKey().PubKey() + pkProto, err := cryptoenc.PubKeyToProto(pubKey) + require.NoError(t, err) + + protoVals := &cmtproto.ValidatorSet{ + Validators: []*cmtproto.Validator{ + {Address: pubKey.Address(), PubKey: pkProto, VotingPower: math.MaxInt64, ProposerPriority: 0}, + {Address: pubKey.Address(), PubKey: pkProto, VotingPower: math.MaxInt64, ProposerPriority: 0}, + }, + Proposer: &cmtproto.Validator{Address: pubKey.Address(), PubKey: pkProto, VotingPower: math.MaxInt64, ProposerPriority: 0}, + } + + _, err = ValidatorSetFromProto(protoVals) + require.Error(t, err) + assert.Contains(t, err.Error(), "exceeds maximum") +} + +func TestAvgProposerPriority(t *testing.T) { + // Create Validator set without calling IncrementProposerPriority: + tcs := []struct { + vs ValidatorSet + want int64 + }{ + 0: {ValidatorSet{Validators: []*Validator{{ProposerPriority: 0}, {ProposerPriority: 0}, {ProposerPriority: 0}}}, 0}, + 1: { + ValidatorSet{ + Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}, {ProposerPriority: 0}}, + }, math.MaxInt64 / 3, + }, + 2: { + ValidatorSet{ + Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}}, + }, math.MaxInt64 / 2, + }, + 3: { + ValidatorSet{ + Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: math.MaxInt64}}, + }, math.MaxInt64, + }, + 4: { + ValidatorSet{ + Validators: []*Validator{{ProposerPriority: math.MinInt64}, {ProposerPriority: math.MinInt64}}, + }, math.MinInt64, + }, + } + for i, tc := range tcs { + got := tc.vs.computeAvgProposerPriority() + assert.Equal(t, tc.want, got, "test case: %v", i) + } +} + +func TestAveragingInIncrementProposerPriority(t *testing.T) { + // Test that the averaging works as expected inside of IncrementProposerPriority. + // Each validator comes with zero voting power which simplifies reasoning about + // the expected ProposerPriority. + tcs := []struct { + vs ValidatorSet + times int32 + avg int64 + }{ + 0: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 1}, + {Address: []byte("b"), ProposerPriority: 2}, + {Address: []byte("c"), ProposerPriority: 3}, + }, + }, + 1, 2, + }, + 1: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 10}, + {Address: []byte("b"), ProposerPriority: -10}, + {Address: []byte("c"), ProposerPriority: 1}, + }, + }, + // this should average twice but the average should be 0 after the first iteration + // (voting power is 0 -> no changes) + 11, + 0, // 1 / 3 + }, + 2: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 100}, + {Address: []byte("b"), ProposerPriority: -10}, + {Address: []byte("c"), ProposerPriority: 1}, + }, + }, + 1, 91 / 3, + }, + } + for i, tc := range tcs { + // work on copy to have the old ProposerPriorities: + newVset := tc.vs.CopyIncrementProposerPriority(tc.times) + for _, val := range tc.vs.Validators { + _, updatedVal := newVset.GetByAddress(val.Address) + assert.Equal(t, updatedVal.ProposerPriority, val.ProposerPriority-tc.avg, "test case: %v", i) + } + } +} + +func TestAveragingInIncrementProposerPriorityWithVotingPower(t *testing.T) { + // Other than TestAveragingInIncrementProposerPriority this is a more complete test showing + // how each ProposerPriority changes in relation to the validator's voting power respectively. + // average is zero in each round: + vp0 := int64(10) + vp1 := int64(1) + vp2 := int64(1) + total := vp0 + vp1 + vp2 + avg := (vp0 + vp1 + vp2 - total) / 3 + vals := ValidatorSet{Validators: []*Validator{ + {Address: []byte{0}, ProposerPriority: 0, VotingPower: vp0}, + {Address: []byte{1}, ProposerPriority: 0, VotingPower: vp1}, + {Address: []byte{2}, ProposerPriority: 0, VotingPower: vp2}, + }} + tcs := []struct { + vals *ValidatorSet + wantProposerPrioritys []int64 + times int32 + wantProposer *Validator + }{ + 0: { + vals.Copy(), + []int64{ + // Acumm+VotingPower-Avg: + 0 + vp0 - total - avg, // mostest will be subtracted by total voting power (12) + 0 + vp1, + 0 + vp2, + }, + 1, + vals.Validators[0], + }, + 1: { + vals.Copy(), + []int64{ + (0 + vp0 - total) + vp0 - total - avg, // this will be mostest on 2nd iter, too + (0 + vp1) + vp1, + (0 + vp2) + vp2, + }, + 2, + vals.Validators[0], + }, // increment twice -> expect average to be subtracted twice + 2: { + vals.Copy(), + []int64{ + 0 + 3*(vp0-total) - avg, // still mostest + 0 + 3*vp1, + 0 + 3*vp2, + }, + 3, + vals.Validators[0], + }, + 3: { + vals.Copy(), + []int64{ + 0 + 4*(vp0-total), // still mostest + 0 + 4*vp1, + 0 + 4*vp2, + }, + 4, + vals.Validators[0], + }, + 4: { + vals.Copy(), + []int64{ + 0 + 4*(vp0-total) + vp0, // 4 iters was mostest + 0 + 5*vp1 - total, // now this val is mostest for the 1st time (hence -12==totalVotingPower) + 0 + 5*vp2, + }, + 5, + vals.Validators[1], + }, + 5: { + vals.Copy(), + []int64{ + 0 + 6*vp0 - 5*total, // mostest again + 0 + 6*vp1 - total, // mostest once up to here + 0 + 6*vp2, + }, + 6, + vals.Validators[0], + }, + 6: { + vals.Copy(), + []int64{ + 0 + 7*vp0 - 6*total, // in 7 iters this val is mostest 6 times + 0 + 7*vp1 - total, // in 7 iters this val is mostest 1 time + 0 + 7*vp2, + }, + 7, + vals.Validators[0], + }, + 7: { + vals.Copy(), + []int64{ + 0 + 8*vp0 - 7*total, // mostest again + 0 + 8*vp1 - total, + 0 + 8*vp2, + }, + 8, + vals.Validators[0], + }, + 8: { + vals.Copy(), + []int64{ + 0 + 9*vp0 - 7*total, + 0 + 9*vp1 - total, + 0 + 9*vp2 - total, + }, // mostest + 9, + vals.Validators[2], + }, + 9: { + vals.Copy(), + []int64{ + 0 + 10*vp0 - 8*total, // after 10 iters this is mostest again + 0 + 10*vp1 - total, // after 6 iters this val is "mostest" once and not in between + 0 + 10*vp2 - total, + }, // in between 10 iters this val is "mostest" once + 10, + vals.Validators[0], + }, + 10: { + vals.Copy(), + []int64{ + 0 + 11*vp0 - 9*total, + 0 + 11*vp1 - total, // after 6 iters this val is "mostest" once and not in between + 0 + 11*vp2 - total, + }, // after 10 iters this val is "mostest" once + 11, + vals.Validators[0], + }, + } + for i, tc := range tcs { + tc.vals.IncrementProposerPriority(tc.times) + + assert.Equal(t, tc.wantProposer.Address, tc.vals.GetProposer().Address, + "test case: %v", + i) + + for valIdx, val := range tc.vals.Validators { + assert.Equal(t, + tc.wantProposerPrioritys[valIdx], + val.ProposerPriority, + "test case: %v, validator: %v", + i, + valIdx) + } + } +} + +func TestSafeAdd(t *testing.T) { + f := func(a, b int64) bool { + c, overflow := safeAdd(a, b) + return overflow || (!overflow && c == a+b) + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestSafeAddClip(t *testing.T) { + assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, 10)) + assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, math.MaxInt64)) + assert.EqualValues(t, math.MinInt64, safeAddClip(math.MinInt64, -10)) +} + +func TestSafeSubClip(t *testing.T) { + assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, 10)) + assert.EqualValues(t, 0, safeSubClip(math.MinInt64, math.MinInt64)) + assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, math.MaxInt64)) + assert.EqualValues(t, math.MaxInt64, safeSubClip(math.MaxInt64, -10)) +} + +//------------------------------------------------------------------- + +func TestEmptySet(t *testing.T) { + var valList []*Validator + valSet := NewValidatorSet(valList) + assert.Panics(t, func() { valSet.IncrementProposerPriority(1) }) + assert.Panics(t, func() { valSet.RescalePriorities(100) }) + assert.Panics(t, func() { valSet.shiftByAvgProposerPriority() }) + assert.Panics(t, func() { assert.Zero(t, computeMaxMinPriorityDiff(valSet)) }) + valSet.GetProposer() + + // Add to empty set + v1 := newValidator([]byte("v1"), 100) + v2 := newValidator([]byte("v2"), 100) + valList = []*Validator{v1, v2} + assert.NoError(t, valSet.UpdateWithChangeSet(valList)) + verifyValidatorSet(t, valSet) + + // Delete all validators from set + v1 = newValidator([]byte("v1"), 0) + v2 = newValidator([]byte("v2"), 0) + delList := []*Validator{v1, v2} + assert.Error(t, valSet.UpdateWithChangeSet(delList)) + + // Attempt delete from empty set + assert.Error(t, valSet.UpdateWithChangeSet(delList)) +} + +func TestUpdatesForNewValidatorSet(t *testing.T) { + v1 := newValidator([]byte("v1"), 100) + v2 := newValidator([]byte("v2"), 100) + valList := []*Validator{v1, v2} + valSet := NewValidatorSet(valList) + verifyValidatorSet(t, valSet) + + // Verify duplicates are caught in NewValidatorSet() and it panics + v111 := newValidator([]byte("v1"), 100) + v112 := newValidator([]byte("v1"), 123) + v113 := newValidator([]byte("v1"), 234) + valList = []*Validator{v111, v112, v113} + assert.Panics(t, func() { NewValidatorSet(valList) }) + + // Verify set including validator with voting power 0 cannot be created + v1 = newValidator([]byte("v1"), 0) + v2 = newValidator([]byte("v2"), 22) + v3 := newValidator([]byte("v3"), 33) + valList = []*Validator{v1, v2, v3} + assert.Panics(t, func() { NewValidatorSet(valList) }) + + // Verify set including validator with negative voting power cannot be created + v1 = newValidator([]byte("v1"), 10) + v2 = newValidator([]byte("v2"), -20) + v3 = newValidator([]byte("v3"), 30) + valList = []*Validator{v1, v2, v3} + assert.Panics(t, func() { NewValidatorSet(valList) }) +} + +type testVal struct { + name string + power int64 +} + +func permutation(valList []testVal) []testVal { + if len(valList) == 0 { + return nil + } + permList := make([]testVal, len(valList)) + perm := cmtrand.Perm(len(valList)) + for i, v := range perm { + permList[v] = valList[i] + } + return permList +} + +func createNewValidatorList(testValList []testVal) []*Validator { + valList := make([]*Validator, 0, len(testValList)) + for _, val := range testValList { + valList = append(valList, newValidator([]byte(val.name), val.power)) + } + return valList +} + +func createNewValidatorSet(testValList []testVal) *ValidatorSet { + return NewValidatorSet(createNewValidatorList(testValList)) +} + +func valSetTotalProposerPriority(valSet *ValidatorSet) int64 { + sum := int64(0) + for _, val := range valSet.Validators { + // mind overflow + sum = safeAddClip(sum, val.ProposerPriority) + } + return sum +} + +func verifyValidatorSet(t *testing.T, valSet *ValidatorSet) { + // verify that the capacity and length of validators is the same + assert.Equal(t, len(valSet.Validators), cap(valSet.Validators)) + + // verify that the set's total voting power has been updated + tvp := valSet.totalVotingPower + err := valSet.updateTotalVotingPower() + require.NoError(t, err) + expectedTvp := valSet.TotalVotingPower() + assert.Equal(t, expectedTvp, tvp, + "expected TVP %d. Got %d, valSet=%s", expectedTvp, tvp, valSet) + + // verify that validator priorities are centered + valsCount := int64(len(valSet.Validators)) + tpp := valSetTotalProposerPriority(valSet) + assert.True(t, tpp < valsCount && tpp > -valsCount, + "expected total priority in (-%d, %d). Got %d", valsCount, valsCount, tpp) + + // verify that priorities are scaled + dist := computeMaxMinPriorityDiff(valSet) + assert.True(t, dist <= PriorityWindowSizeFactor*tvp, + "expected priority distance < %d. Got %d", PriorityWindowSizeFactor*tvp, dist) +} + +func toTestValList(valList []*Validator) []testVal { + testList := make([]testVal, len(valList)) + for i, val := range valList { + testList[i].name = string(val.Address) + testList[i].power = val.VotingPower + } + return testList +} + +func testValSet(nVals int, power int64) []testVal { + vals := make([]testVal, nVals) + for i := 0; i < nVals; i++ { + vals[i] = testVal{fmt.Sprintf("v%d", i+1), power} + } + return vals +} + +type valSetErrTestCase struct { + startVals []testVal + updateVals []testVal +} + +func executeValSetErrTestCase(t *testing.T, idx int, tt valSetErrTestCase) { + // create a new set and apply updates, keeping copies for the checks + valSet := createNewValidatorSet(tt.startVals) + valSetCopy := valSet.Copy() + valList := createNewValidatorList(tt.updateVals) + valListCopy := validatorListCopy(valList) + err := valSet.UpdateWithChangeSet(valList) + + // for errors check the validator set has not been changed + assert.Error(t, err, "test %d", idx) + assert.Equal(t, valSet, valSetCopy, "test %v", idx) + + // check the parameter list has not changed + assert.Equal(t, valList, valListCopy, "test %v", idx) +} + +func TestValSetUpdatesDuplicateEntries(t *testing.T) { + testCases := []valSetErrTestCase{ + // Duplicate entries in changes + { // first entry is duplicated change + testValSet(2, 10), + []testVal{{"v1", 11}, {"v1", 22}}, + }, + { // second entry is duplicated change + testValSet(2, 10), + []testVal{{"v2", 11}, {"v2", 22}}, + }, + { // change duplicates are separated by a valid change + testValSet(2, 10), + []testVal{{"v1", 11}, {"v2", 22}, {"v1", 12}}, + }, + { // change duplicates are separated by a valid change + testValSet(3, 10), + []testVal{{"v1", 11}, {"v3", 22}, {"v1", 12}}, + }, + + // Duplicate entries in remove + { // first entry is duplicated remove + testValSet(2, 10), + []testVal{{"v1", 0}, {"v1", 0}}, + }, + { // second entry is duplicated remove + testValSet(2, 10), + []testVal{{"v2", 0}, {"v2", 0}}, + }, + { // remove duplicates are separated by a valid remove + testValSet(2, 10), + []testVal{{"v1", 0}, {"v2", 0}, {"v1", 0}}, + }, + { // remove duplicates are separated by a valid remove + testValSet(3, 10), + []testVal{{"v1", 0}, {"v3", 0}, {"v1", 0}}, + }, + + { // remove and update same val + testValSet(2, 10), + []testVal{{"v1", 0}, {"v2", 20}, {"v1", 30}}, + }, + { // duplicate entries in removes + changes + testValSet(2, 10), + []testVal{{"v1", 0}, {"v2", 20}, {"v2", 30}, {"v1", 0}}, + }, + { // duplicate entries in removes + changes + testValSet(3, 10), + []testVal{{"v1", 0}, {"v3", 5}, {"v2", 20}, {"v2", 30}, {"v1", 0}}, + }, + } + + for i, tt := range testCases { + executeValSetErrTestCase(t, i, tt) + } +} + +func TestValSetUpdatesOverflows(t *testing.T) { + maxVP := MaxTotalVotingPower + testCases := []valSetErrTestCase{ + { // single update leading to overflow + testValSet(2, 10), + []testVal{{"v1", math.MaxInt64}}, + }, + { // single update leading to overflow + testValSet(2, 10), + []testVal{{"v2", math.MaxInt64}}, + }, + { // add validator leading to overflow + testValSet(1, maxVP), + []testVal{{"v2", math.MaxInt64}}, + }, + { // add validator leading to exceed Max + testValSet(1, maxVP-1), + []testVal{{"v2", 5}}, + }, + { // add validator leading to exceed Max + testValSet(2, maxVP/3), + []testVal{{"v3", maxVP / 2}}, + }, + { // add validator leading to exceed Max + testValSet(1, maxVP), + []testVal{{"v2", maxVP}}, + }, + } + + for i, tt := range testCases { + executeValSetErrTestCase(t, i, tt) + } +} + +func TestValSetUpdatesOtherErrors(t *testing.T) { + testCases := []valSetErrTestCase{ + { // update with negative voting power + testValSet(2, 10), + []testVal{{"v1", -123}}, + }, + { // update with negative voting power + testValSet(2, 10), + []testVal{{"v2", -123}}, + }, + { // remove non-existing validator + testValSet(2, 10), + []testVal{{"v3", 0}}, + }, + { // delete all validators + []testVal{{"v1", 10}, {"v2", 20}, {"v3", 30}}, + []testVal{{"v1", 0}, {"v2", 0}, {"v3", 0}}, + }, + } + + for i, tt := range testCases { + executeValSetErrTestCase(t, i, tt) + } +} + +func TestValSetUpdatesBasicTestsExecute(t *testing.T) { + valSetUpdatesBasicTests := []struct { + startVals []testVal + updateVals []testVal + expectedVals []testVal + }{ + { // no changes + testValSet(2, 10), + []testVal{}, + testValSet(2, 10), + }, + { // voting power changes + testValSet(2, 10), + []testVal{{"v2", 22}, {"v1", 11}}, + []testVal{{"v2", 22}, {"v1", 11}}, + }, + { // add new validators + []testVal{{"v2", 20}, {"v1", 10}}, + []testVal{{"v4", 40}, {"v3", 30}}, + []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}}, + }, + { // add new validator to middle + []testVal{{"v3", 20}, {"v1", 10}}, + []testVal{{"v2", 30}}, + []testVal{{"v2", 30}, {"v3", 20}, {"v1", 10}}, + }, + { // add new validator to beginning + []testVal{{"v3", 20}, {"v2", 10}}, + []testVal{{"v1", 30}}, + []testVal{{"v1", 30}, {"v3", 20}, {"v2", 10}}, + }, + { // delete validators + []testVal{{"v3", 30}, {"v2", 20}, {"v1", 10}}, + []testVal{{"v2", 0}}, + []testVal{{"v3", 30}, {"v1", 10}}, + }, + } + + for i, tt := range valSetUpdatesBasicTests { + // create a new set and apply updates, keeping copies for the checks + valSet := createNewValidatorSet(tt.startVals) + valList := createNewValidatorList(tt.updateVals) + err := valSet.UpdateWithChangeSet(valList) + assert.NoError(t, err, "test %d", i) + + valListCopy := validatorListCopy(valSet.Validators) + // check that the voting power in the set's validators is not changing if the voting power + // is changed in the list of validators previously passed as parameter to UpdateWithChangeSet. + // this is to make sure copies of the validators are made by UpdateWithChangeSet. + if len(valList) > 0 { + valList[0].VotingPower++ + assert.Equal(t, toTestValList(valListCopy), toTestValList(valSet.Validators), "test %v", i) + + } + + // check the final validator list is as expected and the set is properly scaled and centered. + assert.Equal(t, tt.expectedVals, toTestValList(valSet.Validators), "test %v", i) + verifyValidatorSet(t, valSet) + } +} + +// Test that different permutations of an update give the same result. +func TestValSetUpdatesOrderIndependenceTestsExecute(t *testing.T) { + // startVals - initial validators to create the set with + // updateVals - a sequence of updates to be applied to the set. + // updateVals is shuffled a number of times during testing to check for same resulting validator set. + valSetUpdatesOrderTests := []struct { + startVals []testVal + updateVals []testVal + }{ + 0: { // order of changes should not matter, the final validator sets should be the same + []testVal{{"v4", 40}, {"v3", 30}, {"v2", 10}, {"v1", 10}}, + []testVal{{"v4", 44}, {"v3", 33}, {"v2", 22}, {"v1", 11}}, + }, + + 1: { // order of additions should not matter + []testVal{{"v2", 20}, {"v1", 10}}, + []testVal{{"v3", 30}, {"v4", 40}, {"v5", 50}, {"v6", 60}}, + }, + + 2: { // order of removals should not matter + []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}}, + []testVal{{"v1", 0}, {"v3", 0}, {"v4", 0}}, + }, + + 3: { // order of mixed operations should not matter + []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}}, + []testVal{{"v1", 0}, {"v3", 0}, {"v2", 22}, {"v5", 50}, {"v4", 44}}, + }, + } + + for i, tt := range valSetUpdatesOrderTests { + // create a new set and apply updates + valSet := createNewValidatorSet(tt.startVals) + valSetCopy := valSet.Copy() + valList := createNewValidatorList(tt.updateVals) + assert.NoError(t, valSetCopy.UpdateWithChangeSet(valList)) + + // save the result as expected for next updates + valSetExp := valSetCopy.Copy() + + // perform at most 20 permutations on the updates and call UpdateWithChangeSet() + n := len(tt.updateVals) + maxNumPerms := cmtmath.MinInt(20, n*n) + for j := 0; j < maxNumPerms; j++ { + // create a copy of original set and apply a random permutation of updates + valSetCopy := valSet.Copy() + valList := createNewValidatorList(permutation(tt.updateVals)) + + // check there was no error and the set is properly scaled and centered. + assert.NoError(t, valSetCopy.UpdateWithChangeSet(valList), + "test %v failed for permutation %v", i, valList) + verifyValidatorSet(t, valSetCopy) + + // verify the resulting test is same as the expected + assert.Equal(t, valSetCopy, valSetExp, + "test %v failed for permutation %v", i, valList) + } + } +} + +// This tests the private function validator_set.go:applyUpdates() function, used only for additions and changes. +// Should perform a proper merge of updatedVals and startVals +func TestValSetApplyUpdatesTestsExecute(t *testing.T) { + valSetUpdatesBasicTests := []struct { + startVals []testVal + updateVals []testVal + expectedVals []testVal + }{ + // additions + 0: { // prepend + []testVal{{"v4", 44}, {"v5", 55}}, + []testVal{{"v1", 11}}, + []testVal{{"v1", 11}, {"v4", 44}, {"v5", 55}}, + }, + 1: { // append + []testVal{{"v4", 44}, {"v5", 55}}, + []testVal{{"v6", 66}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}, + }, + 2: { // insert + []testVal{{"v4", 44}, {"v6", 66}}, + []testVal{{"v5", 55}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}, + }, + 3: { // insert multi + []testVal{{"v4", 44}, {"v6", 66}, {"v9", 99}}, + []testVal{{"v5", 55}, {"v7", 77}, {"v8", 88}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}, {"v7", 77}, {"v8", 88}, {"v9", 99}}, + }, + // changes + 4: { // head + []testVal{{"v1", 111}, {"v2", 22}}, + []testVal{{"v1", 11}}, + []testVal{{"v1", 11}, {"v2", 22}}, + }, + 5: { // tail + []testVal{{"v1", 11}, {"v2", 222}}, + []testVal{{"v2", 22}}, + []testVal{{"v1", 11}, {"v2", 22}}, + }, + 6: { // middle + []testVal{{"v1", 11}, {"v2", 222}, {"v3", 33}}, + []testVal{{"v2", 22}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, + }, + 7: { // multi + []testVal{{"v1", 111}, {"v2", 222}, {"v3", 333}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, + }, + // additions and changes + 8: { + []testVal{{"v1", 111}, {"v2", 22}}, + []testVal{{"v1", 11}, {"v3", 33}, {"v4", 44}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}, {"v4", 44}}, + }, + } + + for i, tt := range valSetUpdatesBasicTests { + // create a new validator set with the start values + valSet := createNewValidatorSet(tt.startVals) + + // applyUpdates() with the update values + valList := createNewValidatorList(tt.updateVals) + valSet.applyUpdates(valList) + + // check the new list of validators for proper merge + assert.Equal(t, toTestValList(valSet.Validators), tt.expectedVals, "test %v", i) + } +} + +type testVSetCfg struct { + name string + startVals []testVal + deletedVals []testVal + updatedVals []testVal + addedVals []testVal + expectedVals []testVal + expErr error +} + +func randTestVSetCfg(nBase, nAddMax int) testVSetCfg { + if nBase <= 0 || nAddMax < 0 { + panic(fmt.Sprintf("bad parameters %v %v", nBase, nAddMax)) + } + + const maxPower = 1000 + var nOld, nDel, nChanged, nAdd int + + nOld = int(cmtrand.Uint()%uint(nBase)) + 1 + if nBase-nOld > 0 { + nDel = int(cmtrand.Uint() % uint(nBase-nOld)) + } + nChanged = nBase - nOld - nDel + + if nAddMax > 0 { + nAdd = cmtrand.Int()%nAddMax + 1 + } + + cfg := testVSetCfg{} + + cfg.startVals = make([]testVal, nBase) + cfg.deletedVals = make([]testVal, nDel) + cfg.addedVals = make([]testVal, nAdd) + cfg.updatedVals = make([]testVal, nChanged) + cfg.expectedVals = make([]testVal, nBase-nDel+nAdd) + + for i := 0; i < nBase; i++ { + cfg.startVals[i] = testVal{fmt.Sprintf("v%d", i), int64(cmtrand.Uint()%maxPower + 1)} + if i < nOld { + cfg.expectedVals[i] = cfg.startVals[i] + } + if i >= nOld && i < nOld+nChanged { + cfg.updatedVals[i-nOld] = testVal{fmt.Sprintf("v%d", i), int64(cmtrand.Uint()%maxPower + 1)} + cfg.expectedVals[i] = cfg.updatedVals[i-nOld] + } + if i >= nOld+nChanged { + cfg.deletedVals[i-nOld-nChanged] = testVal{fmt.Sprintf("v%d", i), 0} + } + } + + for i := nBase; i < nBase+nAdd; i++ { + cfg.addedVals[i-nBase] = testVal{fmt.Sprintf("v%d", i), int64(cmtrand.Uint()%maxPower + 1)} + cfg.expectedVals[i-nDel] = cfg.addedVals[i-nBase] + } + + sort.Sort(testValsByVotingPower(cfg.startVals)) + sort.Sort(testValsByVotingPower(cfg.deletedVals)) + sort.Sort(testValsByVotingPower(cfg.updatedVals)) + sort.Sort(testValsByVotingPower(cfg.addedVals)) + sort.Sort(testValsByVotingPower(cfg.expectedVals)) + + return cfg +} + +func applyChangesToValSet(t *testing.T, expErr error, valSet *ValidatorSet, valsLists ...[]testVal) { + changes := make([]testVal, 0) + for _, valsList := range valsLists { + changes = append(changes, valsList...) + } + valList := createNewValidatorList(changes) + err := valSet.UpdateWithChangeSet(valList) + if expErr != nil { + assert.Equal(t, expErr, err) + } else { + assert.NoError(t, err) + } +} + +func TestValSetUpdatePriorityOrderTests(t *testing.T) { + const nMaxElections int32 = 5000 + + testCases := []testVSetCfg{ + 0: { // remove high power validator, keep old equal lower power validators + startVals: []testVal{{"v3", 1000}, {"v1", 1}, {"v2", 1}}, + deletedVals: []testVal{{"v3", 0}}, + updatedVals: []testVal{}, + addedVals: []testVal{}, + expectedVals: []testVal{{"v1", 1}, {"v2", 1}}, + }, + 1: { // remove high power validator, keep old different power validators + startVals: []testVal{{"v3", 1000}, {"v2", 10}, {"v1", 1}}, + deletedVals: []testVal{{"v3", 0}}, + updatedVals: []testVal{}, + addedVals: []testVal{}, + expectedVals: []testVal{{"v2", 10}, {"v1", 1}}, + }, + 2: { // remove high power validator, add new low power validators, keep old lower power + startVals: []testVal{{"v3", 1000}, {"v2", 2}, {"v1", 1}}, + deletedVals: []testVal{{"v3", 0}}, + updatedVals: []testVal{{"v2", 1}}, + addedVals: []testVal{{"v5", 50}, {"v4", 40}}, + expectedVals: []testVal{{"v5", 50}, {"v4", 40}, {"v1", 1}, {"v2", 1}}, + }, + + // generate a configuration with 100 validators, + // randomly select validators for updates and deletes, and + // generate 10 new validators to be added + 3: randTestVSetCfg(100, 10), + + 4: randTestVSetCfg(1000, 100), + + 5: randTestVSetCfg(10, 100), + + 6: randTestVSetCfg(100, 1000), + + 7: randTestVSetCfg(1000, 1000), + } + + for _, cfg := range testCases { + + // create a new validator set + valSet := createNewValidatorSet(cfg.startVals) + verifyValidatorSet(t, valSet) + + // run election up to nMaxElections times, apply changes and verify that the priority order is correct + verifyValSetUpdatePriorityOrder(t, valSet, cfg, nMaxElections) + } +} + +func verifyValSetUpdatePriorityOrder(t *testing.T, valSet *ValidatorSet, cfg testVSetCfg, nMaxElections int32) { + // Run election up to nMaxElections times, sort validators by priorities + valSet.IncrementProposerPriority(cmtrand.Int31()%nMaxElections + 1) + + // apply the changes, get the updated validators, sort by priorities + applyChangesToValSet(t, nil, valSet, cfg.addedVals, cfg.updatedVals, cfg.deletedVals) + + // basic checks + assert.Equal(t, cfg.expectedVals, toTestValList(valSet.Validators)) + verifyValidatorSet(t, valSet) + + // verify that the added validators have the smallest priority: + // - they should be at the beginning of updatedValsPriSorted since it is + // sorted by priority + if len(cfg.addedVals) > 0 { + updatedValsPriSorted := validatorListCopy(valSet.Validators) + sort.Sort(validatorsByPriority(updatedValsPriSorted)) + + addedValsPriSlice := updatedValsPriSorted[:len(cfg.addedVals)] + sort.Sort(ValidatorsByVotingPower(addedValsPriSlice)) + assert.Equal(t, cfg.addedVals, toTestValList(addedValsPriSlice)) + + // - and should all have the same priority + expectedPri := addedValsPriSlice[0].ProposerPriority + for _, val := range addedValsPriSlice[1:] { + assert.Equal(t, expectedPri, val.ProposerPriority) + } + } +} + +func TestNewValidatorSetFromExistingValidators(t *testing.T) { + size := 5 + vals := make([]*Validator, size) + for i := 0; i < size; i++ { + pv := NewMockPV() + vals[i] = pv.ExtractIntoValidator(int64(i + 1)) + } + valSet := NewValidatorSet(vals) + valSet.IncrementProposerPriority(5) + + newValSet := NewValidatorSet(valSet.Validators) + assert.NotEqual(t, valSet, newValSet) + + existingValSet, err := ValidatorSetFromExistingValidators(valSet.Validators) + assert.NoError(t, err) + assert.Equal(t, valSet, existingValSet) + assert.Equal(t, valSet.CopyIncrementProposerPriority(3), existingValSet.CopyIncrementProposerPriority(3)) +} + +func TestValSetUpdateOverflowRelated(t *testing.T) { + testCases := []testVSetCfg{ + { + name: "1 no false overflow error messages for updates", + startVals: []testVal{{"v2", MaxTotalVotingPower - 1}, {"v1", 1}}, + updatedVals: []testVal{{"v1", MaxTotalVotingPower - 1}, {"v2", 1}}, + expectedVals: []testVal{{"v1", MaxTotalVotingPower - 1}, {"v2", 1}}, + expErr: nil, + }, + { + // this test shows that it is important to apply the updates in the order of the change in power + // i.e. apply first updates with decreases in power, v2 change in this case. + name: "2 no false overflow error messages for updates", + startVals: []testVal{{"v2", MaxTotalVotingPower - 1}, {"v1", 1}}, + updatedVals: []testVal{{"v1", MaxTotalVotingPower/2 - 1}, {"v2", MaxTotalVotingPower / 2}}, + expectedVals: []testVal{{"v2", MaxTotalVotingPower / 2}, {"v1", MaxTotalVotingPower/2 - 1}}, + expErr: nil, + }, + { + name: "3 no false overflow error messages for deletes", + startVals: []testVal{{"v1", MaxTotalVotingPower - 2}, {"v2", 1}, {"v3", 1}}, + deletedVals: []testVal{{"v1", 0}}, + addedVals: []testVal{{"v4", MaxTotalVotingPower - 2}}, + expectedVals: []testVal{{"v4", MaxTotalVotingPower - 2}, {"v2", 1}, {"v3", 1}}, + expErr: nil, + }, + { + name: "4 no false overflow error messages for adds, updates and deletes", + startVals: []testVal{ + {"v1", MaxTotalVotingPower / 4}, + {"v2", MaxTotalVotingPower / 4}, + {"v3", MaxTotalVotingPower / 4}, + {"v4", MaxTotalVotingPower / 4}, + }, + deletedVals: []testVal{{"v2", 0}}, + updatedVals: []testVal{ + {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v4", 2}, + }, + addedVals: []testVal{{"v5", 3}}, + expectedVals: []testVal{ + {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v5", 3}, {"v4", 2}, + }, + expErr: nil, + }, + { + name: "5 check panic on overflow is prevented: update 8 validators with power int64(math.MaxInt64)/8", + startVals: []testVal{ + {"v1", 1}, + {"v2", 1}, + {"v3", 1}, + {"v4", 1}, + {"v5", 1}, + {"v6", 1}, + {"v7", 1}, + {"v8", 1}, + {"v9", 1}, + }, + updatedVals: []testVal{ + {"v1", MaxTotalVotingPower}, + {"v2", MaxTotalVotingPower}, + {"v3", MaxTotalVotingPower}, + {"v4", MaxTotalVotingPower}, + {"v5", MaxTotalVotingPower}, + {"v6", MaxTotalVotingPower}, + {"v7", MaxTotalVotingPower}, + {"v8", MaxTotalVotingPower}, + {"v9", 8}, + }, + expectedVals: []testVal{ + {"v1", 1}, + {"v2", 1}, + {"v3", 1}, + {"v4", 1}, + {"v5", 1}, + {"v6", 1}, + {"v7", 1}, + {"v8", 1}, + {"v9", 1}, + }, + expErr: ErrTotalVotingPowerOverflow, + }, + } + + for _, tt := range testCases { + tt := tt + t.Run(tt.name, func(t *testing.T) { + valSet := createNewValidatorSet(tt.startVals) + verifyValidatorSet(t, valSet) + + // execute update and verify returned error is as expected + applyChangesToValSet(t, tt.expErr, valSet, tt.addedVals, tt.updatedVals, tt.deletedVals) + + // verify updated validator set is as expected + assert.Equal(t, tt.expectedVals, toTestValList(valSet.Validators)) + verifyValidatorSet(t, valSet) + }) + } +} + +func TestSafeMul(t *testing.T) { + testCases := []struct { + a int64 + b int64 + c int64 + overflow bool + }{ + 0: {0, 0, 0, false}, + 1: {1, 0, 0, false}, + 2: {2, 3, 6, false}, + 3: {2, -3, -6, false}, + 4: {-2, -3, 6, false}, + 5: {-2, 3, -6, false}, + 6: {math.MaxInt64, 1, math.MaxInt64, false}, + 7: {math.MaxInt64 / 2, 2, math.MaxInt64 - 1, false}, + 8: {math.MaxInt64 / 2, 3, 0, true}, + 9: {math.MaxInt64, 2, 0, true}, + } + + for i, tc := range testCases { + c, overflow := safeMul(tc.a, tc.b) + assert.Equal(t, tc.c, c, "#%d", i) + assert.Equal(t, tc.overflow, overflow, "#%d", i) + } +} + +func TestValidatorSetProtoBuf(t *testing.T) { + valset, _ := RandValidatorSet(10, 100) + valset2, _ := RandValidatorSet(10, 100) + valset2.Validators[0] = &Validator{} + + valset3, _ := RandValidatorSet(10, 100) + valset3.Proposer = nil + + valset4, _ := RandValidatorSet(10, 100) + valset4.Proposer = &Validator{} + + testCases := []struct { + msg string + v1 *ValidatorSet + expPass1 bool + expPass2 bool + }{ + {"success", valset, true, true}, + {"fail valSet2, pubkey empty", valset2, false, false}, + {"fail nil Proposer", valset3, false, false}, + {"fail empty Proposer", valset4, false, false}, + {"fail empty valSet", &ValidatorSet{}, true, false}, + {"false nil", nil, true, false}, + } + for _, tc := range testCases { + protoValSet, err := tc.v1.ToProto() + if tc.expPass1 { + require.NoError(t, err, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + + valSet, err := ValidatorSetFromProto(protoValSet) + if tc.expPass2 { + require.NoError(t, err, tc.msg) + require.EqualValues(t, tc.v1, valSet, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +// --------------------- +// Sort validators by priority and address +type validatorsByPriority []*Validator + +func (valz validatorsByPriority) Len() int { + return len(valz) +} + +func (valz validatorsByPriority) Less(i, j int) bool { + if valz[i].ProposerPriority < valz[j].ProposerPriority { + return true + } + if valz[i].ProposerPriority > valz[j].ProposerPriority { + return false + } + return bytes.Compare(valz[i].Address, valz[j].Address) < 0 +} + +func (valz validatorsByPriority) Swap(i, j int) { + valz[i], valz[j] = valz[j], valz[i] +} + +//------------------------------------- + +type testValsByVotingPower []testVal + +func (tvals testValsByVotingPower) Len() int { + return len(tvals) +} + +func (tvals testValsByVotingPower) Less(i, j int) bool { + if tvals[i].power == tvals[j].power { + return bytes.Compare([]byte(tvals[i].name), []byte(tvals[j].name)) == -1 + } + return tvals[i].power > tvals[j].power +} + +func (tvals testValsByVotingPower) Swap(i, j int) { + tvals[i], tvals[j] = tvals[j], tvals[i] +} + +// ------------------------------------- +// Benchmark tests +func BenchmarkUpdates(b *testing.B) { + const ( + n = 100 + m = 2000 + ) + // Init with n validators + vs := make([]*Validator, n) + for j := 0; j < n; j++ { + vs[j] = newValidator([]byte(fmt.Sprintf("v%d", j)), 100) + } + valSet := NewValidatorSet(vs) + l := len(valSet.Validators) + + // Make m new validators + newValList := make([]*Validator, m) + for j := 0; j < m; j++ { + newValList[j] = newValidator([]byte(fmt.Sprintf("v%d", j+l)), 1000) + } + b.ResetTimer() + + for i := 0; i < b.N; i++ { + // Add m validators to valSetCopy + valSetCopy := valSet.Copy() + assert.NoError(b, valSetCopy.UpdateWithChangeSet(newValList)) + } +} + +func TestVerifyCommitWithInvalidProposerKey(t *testing.T) { + vs := &ValidatorSet{ + Validators: []*Validator{{}, {}}, + } + commit := &Commit{ + Height: 100, + Signatures: []CommitSig{{}, {}}, + } + var bid BlockID + cid := "" + err := vs.VerifyCommit(cid, bid, 100, commit) + assert.Error(t, err) +} + +func TestVerifyCommitSingleWithInvalidSignatures(t *testing.T) { + vs := &ValidatorSet{ + Validators: []*Validator{{}, {}}, + } + commit := &Commit{ + Height: 100, + Signatures: []CommitSig{{}, {}}, + } + cid := "" + votingPowerNeeded := vs.TotalVotingPower() * 2 / 3 + + // ignore all absent signatures + ignore := func(c CommitSig) bool { return c.BlockIDFlag == BlockIDFlagAbsent } + + // only count the signatures that are for the block + count := func(c CommitSig) bool { return c.BlockIDFlag == BlockIDFlagCommit } + + err := verifyCommitSingle(cid, vs, commit, votingPowerNeeded, ignore, count, true, true) + assert.Error(t, err) +} + +func TestValidatorSet_AllKeysHaveSameType(t *testing.T) { + testCases := []struct { + vals *ValidatorSet + sameType bool + }{ + { + vals: NewValidatorSet([]*Validator{}), + sameType: true, + }, + { + vals: randValidatorSet(1), + sameType: true, + }, + { + vals: randValidatorSet(2), + sameType: true, + }, + { + vals: NewValidatorSet([]*Validator{randValidator(100), NewValidator(sr25519.GenPrivKey().PubKey(), 200)}), + sameType: false, + }, + } + + for i, tc := range testCases { + if tc.sameType { + assert.True(t, tc.vals.AllKeysHaveSameType(), "test %d", i) + } else { + assert.False(t, tc.vals.AllKeysHaveSameType(), "test %d", i) + } + } +} + +func TestValidatorSet_TotalVotingPowerSafe(t *testing.T) { + testCases := []struct { + name string + validators []*Validator + expectedPower int64 + expectError bool + errorContains string + }{ + { + name: "happy path - normal validators", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), 100), + NewValidator(ed25519.GenPrivKey().PubKey(), 200), + NewValidator(ed25519.GenPrivKey().PubKey(), 300), + }, + expectedPower: 600, + expectError: false, + }, + { + name: "zero state - empty validator set", + validators: []*Validator{}, + expectedPower: 0, + expectError: false, + }, + { + name: "zero state - nil validator set", + validators: nil, + expectedPower: 0, + expectError: false, + }, + { + name: "single validator", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), 1000), + }, + expectedPower: 1000, + expectError: false, + }, + { + name: "boundary - exactly at MaxTotalVotingPower", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), MaxTotalVotingPower), + }, + expectedPower: MaxTotalVotingPower, + expectError: false, + }, + { + name: "boundary - sum equals MaxTotalVotingPower", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), MaxTotalVotingPower-100), + NewValidator(ed25519.GenPrivKey().PubKey(), 100), + }, + expectedPower: MaxTotalVotingPower, + expectError: false, + }, + { + name: "overflow - exceeds MaxTotalVotingPower", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), MaxTotalVotingPower/2+1), + NewValidator(ed25519.GenPrivKey().PubKey(), MaxTotalVotingPower/2+1), + }, + expectedPower: 0, + expectError: true, + errorContains: "exceeds maximum", + }, + { + name: "overflow - multiple validators exceeding MaxTotalVotingPower", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), MaxTotalVotingPower), + NewValidator(ed25519.GenPrivKey().PubKey(), 1), + }, + expectedPower: 0, + expectError: true, + errorContains: "exceeds maximum", + }, + { + name: "overflow - three large validators", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), math.MaxInt64/2), + NewValidator(ed25519.GenPrivKey().PubKey(), math.MaxInt64/2), + NewValidator(ed25519.GenPrivKey().PubKey(), 100), + }, + expectedPower: 0, + expectError: true, + errorContains: "exceeds maximum", + }, + { + name: "validators with zero voting power", + validators: []*Validator{ + NewValidator(ed25519.GenPrivKey().PubKey(), 100), + NewValidator(ed25519.GenPrivKey().PubKey(), 0), + NewValidator(ed25519.GenPrivKey().PubKey(), 200), + }, + expectedPower: 300, + expectError: false, + }, + { + name: "large number of validators - within limit", + validators: func() []*Validator { + vals := make([]*Validator, 100) + for i := 0; i < 100; i++ { + vals[i] = NewValidator(ed25519.GenPrivKey().PubKey(), 1000) + } + return vals + }(), + expectedPower: 100000, + expectError: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Create validator set without using NewValidatorSet to avoid panic on overflow + valSet := &ValidatorSet{ + Validators: tc.validators, + } + + // Call TotalVotingPowerSafe + totalPower, err := valSet.TotalVotingPowerSafe() + + // Assert expectations + if tc.expectError { + require.Error(t, err, "expected error but got none") + if tc.errorContains != "" { + require.Contains(t, err.Error(), tc.errorContains, + "error message should contain expected text") + } + require.Equal(t, tc.expectedPower, totalPower, + "power should be %d when error occurs", tc.expectedPower) + } else { + require.NoError(t, err, "unexpected error: %v", err) + require.Equal(t, tc.expectedPower, totalPower, + "total voting power should be %d", tc.expectedPower) + } + }) + } +} diff --git a/types/validator_test.go b/types/validator_test.go new file mode 100644 index 0000000..910eb00 --- /dev/null +++ b/types/validator_test.go @@ -0,0 +1,100 @@ +package types + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestValidatorProtoBuf(t *testing.T) { + val, _ := RandValidator(true, 100) + testCases := []struct { + msg string + v1 *Validator + expPass1 bool + expPass2 bool + }{ + {"success validator", val, true, true}, + {"failure empty", &Validator{}, false, false}, + {"failure nil", nil, false, false}, + } + for _, tc := range testCases { + protoVal, err := tc.v1.ToProto() + + if tc.expPass1 { + require.NoError(t, err, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + + val, err := ValidatorFromProto(protoVal) + if tc.expPass2 { + require.NoError(t, err, tc.msg) + require.Equal(t, tc.v1, val, tc.msg) + } else { + require.Error(t, err, tc.msg) + } + } +} + +func TestValidatorValidateBasic(t *testing.T) { + priv := NewMockPV() + pubKey, _ := priv.GetPubKey() + testCases := []struct { + val *Validator + err bool + msg string + }{ + { + val: NewValidator(pubKey, 1), + err: false, + msg: "", + }, + { + val: nil, + err: true, + msg: "nil validator", + }, + { + val: &Validator{ + PubKey: nil, + }, + err: true, + msg: "validator does not have a public key", + }, + { + val: NewValidator(pubKey, -1), + err: true, + msg: "validator has negative voting power", + }, + { + val: &Validator{ + PubKey: pubKey, + Address: nil, + }, + err: true, + msg: fmt.Sprintf("validator address is incorrectly derived from pubkey. Exp: %v, got ", pubKey.Address()), + }, + { + val: &Validator{ + PubKey: pubKey, + Address: []byte{'a'}, + }, + err: true, + msg: fmt.Sprintf("validator address is incorrectly derived from pubkey. Exp: %v, got 61", pubKey.Address()), + }, + } + + for _, tc := range testCases { + err := tc.val.ValidateBasic() + if tc.err { + if assert.Error(t, err) { + assert.Equal(t, tc.msg, err.Error()) + } + } else { + assert.NoError(t, err) + } + } +} diff --git a/types/vote.go b/types/vote.go new file mode 100644 index 0000000..db3f340 --- /dev/null +++ b/types/vote.go @@ -0,0 +1,454 @@ +package types + +import ( + "bytes" + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/crypto" + cmtbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/cometbft/cometbft/libs/protoio" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +const ( + nilVoteStr string = "nil-Vote" + + // The maximum supported number of bytes in a vote extension. + MaxVoteExtensionSize int = 1024 * 1024 +) + +var ( + ErrVoteUnexpectedStep = errors.New("unexpected step") + ErrVoteInvalidValidatorIndex = errors.New("invalid validator index") + ErrVoteInvalidValidatorAddress = errors.New("invalid validator address") + ErrVoteInvalidSignature = errors.New("invalid signature") + ErrVoteInvalidBlockHash = errors.New("invalid block hash") + ErrVoteNonDeterministicSignature = errors.New("non-deterministic signature") + ErrVoteNil = errors.New("nil vote") + ErrVoteExtensionAbsent = errors.New("vote extension absent") + ErrInvalidVoteExtension = errors.New("invalid vote extension") +) + +type ErrVoteConflictingVotes struct { + VoteA *Vote + VoteB *Vote +} + +func (err *ErrVoteConflictingVotes) Error() string { + return fmt.Sprintf("conflicting votes from validator %X", err.VoteA.ValidatorAddress) +} + +func NewConflictingVoteError(vote1, vote2 *Vote) *ErrVoteConflictingVotes { + return &ErrVoteConflictingVotes{ + VoteA: vote1, + VoteB: vote2, + } +} + +// The vote extension is only valid for non-nil precommits. +type ErrVoteExtensionInvalid struct { + ExtSignature []byte +} + +func (err *ErrVoteExtensionInvalid) Error() string { + return fmt.Sprintf("extensions must be present IFF vote is a non-nil Precommit; extension signature: %X", err.ExtSignature) +} + +// Address is hex bytes. +type Address = crypto.Address + +// Vote represents a prevote, precommit, or commit vote from validators for +// consensus. +type Vote struct { + Type cmtproto.SignedMsgType `json:"type"` + Height int64 `json:"height"` + Round int32 `json:"round"` // assume there will not be greater than 2_147_483_647 rounds + BlockID BlockID `json:"block_id"` // zero if vote is nil. + Timestamp time.Time `json:"timestamp"` + ValidatorAddress Address `json:"validator_address"` + ValidatorIndex int32 `json:"validator_index"` + Signature []byte `json:"signature"` + Extension []byte `json:"extension"` + ExtensionSignature []byte `json:"extension_signature"` +} + +// VoteFromProto attempts to convert the given serialization (Protobuf) type to +// our Vote domain type. No validation is performed on the resulting vote - +// this is left up to the caller to decide whether to call ValidateBasic or +// ValidateWithExtension. +func VoteFromProto(pv *cmtproto.Vote) (*Vote, error) { + blockID, err := BlockIDFromProto(&pv.BlockID) + if err != nil { + return nil, err + } + + return &Vote{ + Type: pv.Type, + Height: pv.Height, + Round: pv.Round, + BlockID: *blockID, + Timestamp: pv.Timestamp, + ValidatorAddress: pv.ValidatorAddress, + ValidatorIndex: pv.ValidatorIndex, + Signature: pv.Signature, + Extension: pv.Extension, + ExtensionSignature: pv.ExtensionSignature, + }, nil +} + +// CommitSig converts the Vote to a CommitSig. +func (vote *Vote) CommitSig() CommitSig { + if vote == nil { + return NewCommitSigAbsent() + } + + var blockIDFlag BlockIDFlag + switch { + case vote.BlockID.IsComplete(): + blockIDFlag = BlockIDFlagCommit + case vote.BlockID.IsZero(): + blockIDFlag = BlockIDFlagNil + default: + panic(fmt.Sprintf("Invalid vote %v - expected BlockID to be either empty or complete", vote)) + } + + return CommitSig{ + BlockIDFlag: blockIDFlag, + ValidatorAddress: vote.ValidatorAddress, + Timestamp: vote.Timestamp, + Signature: vote.Signature, + } +} + +// ExtendedCommitSig attempts to construct an ExtendedCommitSig from this vote. +// Panics if either the vote extension signature is missing or if the block ID +// is not either empty or complete. +func (vote *Vote) ExtendedCommitSig() ExtendedCommitSig { + if vote == nil { + return NewExtendedCommitSigAbsent() + } + + return ExtendedCommitSig{ + CommitSig: vote.CommitSig(), + Extension: vote.Extension, + ExtensionSignature: vote.ExtensionSignature, + } +} + +// VoteSignBytes returns the proto-encoding of the canonicalized Vote, for +// signing. Panics if the marshaling fails. +// +// The encoded Protobuf message is varint length-prefixed (using MarshalDelimited) +// for backwards-compatibility with the Amino encoding, due to e.g. hardware +// devices that rely on this encoding. +// +// See CanonicalizeVote +func VoteSignBytes(chainID string, vote *cmtproto.Vote) []byte { + pb := CanonicalizeVote(chainID, vote) + bz, err := protoio.MarshalDelimited(&pb) + if err != nil { + panic(err) + } + + return bz +} + +// VoteExtensionSignBytes returns the proto-encoding of the canonicalized vote +// extension for signing. Panics if the marshaling fails. +// +// Similar to VoteSignBytes, the encoded Protobuf message is varint +// length-prefixed for backwards-compatibility with the Amino encoding. +func VoteExtensionSignBytes(chainID string, vote *cmtproto.Vote) []byte { + pb := CanonicalizeVoteExtension(chainID, vote) + bz, err := protoio.MarshalDelimited(&pb) + if err != nil { + panic(err) + } + + return bz +} + +func (vote *Vote) Copy() *Vote { + voteCopy := *vote + return &voteCopy +} + +// String returns a string representation of Vote. +// +// 1. validator index +// 2. first 6 bytes of validator address +// 3. height +// 4. round, +// 5. type byte +// 6. type string +// 7. first 6 bytes of block hash +// 8. first 6 bytes of signature +// 9. first 6 bytes of vote extension +// 10. timestamp +func (vote *Vote) String() string { + if vote == nil { + return nilVoteStr + } + + var typeString string + switch vote.Type { + case cmtproto.PrevoteType: + typeString = "Prevote" + case cmtproto.PrecommitType: + typeString = "Precommit" + default: + panic("Unknown vote type") + } + + return fmt.Sprintf("Vote{%v:%X %v/%02d/%v(%v) %X %X %X @ %s}", + vote.ValidatorIndex, + cmtbytes.Fingerprint(vote.ValidatorAddress), + vote.Height, + vote.Round, + vote.Type, + typeString, + cmtbytes.Fingerprint(vote.BlockID.Hash), + cmtbytes.Fingerprint(vote.Signature), + cmtbytes.Fingerprint(vote.Extension), + CanonicalTime(vote.Timestamp), + ) +} + +func (vote *Vote) verifyAndReturnProto(chainID string, pubKey crypto.PubKey) (*cmtproto.Vote, error) { + if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) { + return nil, ErrVoteInvalidValidatorAddress + } + v := vote.ToProto() + if !pubKey.VerifySignature(VoteSignBytes(chainID, v), vote.Signature) { + return nil, ErrVoteInvalidSignature + } + return v, nil +} + +// Verify checks whether the signature associated with this vote corresponds to +// the given chain ID and public key. This function does not validate vote +// extension signatures - to do so, use VerifyWithExtension instead. +func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error { + _, err := vote.verifyAndReturnProto(chainID, pubKey) + return err +} + +// VerifyVoteAndExtension performs the same verification as Verify, but +// additionally checks whether the vote extension signature corresponds to the +// given chain ID and public key. We only verify vote extension signatures for +// precommits. +func (vote *Vote) VerifyVoteAndExtension(chainID string, pubKey crypto.PubKey) error { + v, err := vote.verifyAndReturnProto(chainID, pubKey) + if err != nil { + return err + } + // We only verify vote extension signatures for non-nil precommits. + if vote.Type == cmtproto.PrecommitType && !ProtoBlockIDIsNil(&v.BlockID) { + if len(vote.ExtensionSignature) == 0 { + return errors.New("expected vote extension signature") + } + + extSignBytes := VoteExtensionSignBytes(chainID, v) + if !pubKey.VerifySignature(extSignBytes, vote.ExtensionSignature) { + return ErrVoteInvalidSignature + } + } + return nil +} + +// VerifyExtension checks whether the vote extension signature corresponds to the +// given chain ID and public key. +func (vote *Vote) VerifyExtension(chainID string, pubKey crypto.PubKey) error { + if vote.Type != cmtproto.PrecommitType || vote.BlockID.IsZero() { + return nil + } + v := vote.ToProto() + extSignBytes := VoteExtensionSignBytes(chainID, v) + if !pubKey.VerifySignature(extSignBytes, vote.ExtensionSignature) { + return ErrVoteInvalidSignature + } + return nil +} + +// ValidateBasic checks whether the vote is well-formed. It does not, however, +// check vote extensions - for vote validation with vote extension validation, +// use ValidateWithExtension. +func (vote *Vote) ValidateBasic() error { + if !IsVoteTypeValid(vote.Type) { + return errors.New("invalid Type") + } + + if vote.Height <= 0 { + return errors.New("negative or zero Height") + } + + if vote.Round < 0 { + return errors.New("negative Round") + } + + // NOTE: Timestamp validation is subtle and handled elsewhere. + + if err := vote.BlockID.ValidateBasic(); err != nil { + return fmt.Errorf("wrong BlockID: %v", err) + } + + // BlockID.ValidateBasic would not err if we for instance have an empty hash but a + // non-empty PartsSetHeader: + if !vote.BlockID.IsZero() && !vote.BlockID.IsComplete() { + return fmt.Errorf("blockID must be either empty or complete, got: %v", vote.BlockID) + } + + if len(vote.ValidatorAddress) != crypto.AddressSize { + return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes", + crypto.AddressSize, + len(vote.ValidatorAddress), + ) + } + if vote.ValidatorIndex < 0 { + return errors.New("negative ValidatorIndex") + } + if len(vote.Signature) == 0 { + return errors.New("signature is missing") + } + + if len(vote.Signature) > MaxSignatureSize { + return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize) + } + + // We should only ever see vote extensions in non-nil precommits, otherwise + // this is a violation of the specification. + // https://github.com/tendermint/tendermint/issues/8487 + if vote.Type != cmtproto.PrecommitType || vote.BlockID.IsZero() { + if len(vote.Extension) > 0 { + return fmt.Errorf( + "unexpected vote extension; vote type %d, isNil %t", + vote.Type, vote.BlockID.IsZero(), + ) + } + if len(vote.ExtensionSignature) > 0 { + return errors.New("unexpected vote extension signature") + } + } + + if vote.Type == cmtproto.PrecommitType && !vote.BlockID.IsZero() { + // It's possible that this vote has vote extensions but + // they could also be disabled and thus not present thus + // we can't do all checks + if len(vote.ExtensionSignature) > MaxSignatureSize { + return fmt.Errorf("vote extension signature is too big (max: %d)", MaxSignatureSize) + } + + // NOTE: extended votes should have a signature regardless of + // of whether there is any data in the extension or not however + // we don't know if extensions are enabled so we can only + // enforce the signature when extension size is not nil + if len(vote.ExtensionSignature) == 0 && len(vote.Extension) != 0 { + return fmt.Errorf("vote extension signature absent on vote with extension") + } + } + + return nil +} + +// EnsureExtension checks for the presence of extensions signature data +// on precommit vote types. +func (vote *Vote) EnsureExtension() error { + // We should always see vote extension signatures in non-nil precommits + if vote.Type != cmtproto.PrecommitType { + return nil + } + if vote.BlockID.IsZero() { + return nil + } + if len(vote.ExtensionSignature) > 0 { + return nil + } + return ErrVoteExtensionAbsent +} + +// ToProto converts the handwritten type to proto generated type +// return type, nil if everything converts safely, otherwise nil, error +func (vote *Vote) ToProto() *cmtproto.Vote { + if vote == nil { + return nil + } + + return &cmtproto.Vote{ + Type: vote.Type, + Height: vote.Height, + Round: vote.Round, + BlockID: vote.BlockID.ToProto(), + Timestamp: vote.Timestamp, + ValidatorAddress: vote.ValidatorAddress, + ValidatorIndex: vote.ValidatorIndex, + Signature: vote.Signature, + Extension: vote.Extension, + ExtensionSignature: vote.ExtensionSignature, + } +} + +func VotesToProto(votes []*Vote) []*cmtproto.Vote { + if votes == nil { + return nil + } + + res := make([]*cmtproto.Vote, 0, len(votes)) + for _, vote := range votes { + v := vote.ToProto() + // protobuf crashes when serializing "repeated" fields with nil elements + if v != nil { + res = append(res, v) + } + } + return res +} + +// SignAndCheckVote signs the vote with the given privVal and checks the vote. +// It returns an error if the vote is invalid and a boolean indicating if the +// error is recoverable or not. +func SignAndCheckVote( + vote *Vote, + privVal PrivValidator, + chainID string, + extensionsEnabled bool, +) (bool, error) { + v := vote.ToProto() + if err := privVal.SignVote(chainID, v); err != nil { + // Failing to sign a vote has always been a recoverable error, this + // function keeps it that way. + return true, err + } + vote.Signature = v.Signature + + isPrecommit := vote.Type == cmtproto.PrecommitType + if !isPrecommit && extensionsEnabled { + // Non-recoverable because the caller passed parameters that don't make sense + return false, &ErrVoteExtensionInvalid{ExtSignature: v.ExtensionSignature} + } + + isNil := vote.BlockID.IsZero() + extSignature := (len(v.ExtensionSignature) > 0) + + // Error if prevote contains an extension signature + if extSignature && (!isPrecommit || isNil) { + // Non-recoverable because the vote is malformed + return false, &ErrVoteExtensionInvalid{ExtSignature: v.ExtensionSignature} + } + + vote.ExtensionSignature = nil + if extensionsEnabled { + // Error if missing extension signature for non-nil Precommit + if !extSignature && isPrecommit && !isNil { + // Non-recoverable because the vote is malformed + return false, &ErrVoteExtensionInvalid{ExtSignature: v.ExtensionSignature} + } + + vote.ExtensionSignature = v.ExtensionSignature + } + + vote.Timestamp = v.Timestamp + + return true, nil +} diff --git a/types/vote_set.go b/types/vote_set.go new file mode 100644 index 0000000..c30e590 --- /dev/null +++ b/types/vote_set.go @@ -0,0 +1,724 @@ +package types + +import ( + "bytes" + "fmt" + "strings" + + "github.com/cometbft/cometbft/libs/bits" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtsync "github.com/cometbft/cometbft/libs/sync" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" +) + +const ( + // MaxVotesCount is the maximum number of votes in a set. Used in ValidateBasic funcs for + // protection against DOS attacks. Note this implies a corresponding equal limit to + // the number of validators. + MaxVotesCount = 10000 +) + +// UNSTABLE +// XXX: duplicate of p2p.ID to avoid dependence between packages. +// Perhaps we can have a minimal types package containing this (and other things?) +// that both `types` and `p2p` import ? +type P2PID string + +/* +VoteSet helps collect signatures from validators at each height+round for a +predefined vote type. + +We need VoteSet to be able to keep track of conflicting votes when validators +double-sign. Yet, we can't keep track of *all* the votes seen, as that could +be a DoS attack vector. + +There are two storage areas for votes. +1. voteSet.votes +2. voteSet.votesByBlock + +`.votes` is the "canonical" list of votes. It always has at least one vote, +if a vote from a validator had been seen at all. Usually it keeps track of +the first vote seen, but when a 2/3 majority is found, votes for that get +priority and are copied over from `.votesByBlock`. + +`.votesByBlock` keeps track of a list of votes for a particular block. There +are two ways a &blockVotes{} gets created in `.votesByBlock`. +1. the first vote seen by a validator was for the particular block. +2. a peer claims to have seen 2/3 majority for the particular block. + +Since the first vote from a validator will always get added in `.votesByBlock` +, all votes in `.votes` will have a corresponding entry in `.votesByBlock`. + +When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its +votes are copied into `.votes`. + +All this is memory bounded because conflicting votes only get added if a peer +told us to track that block, each peer only gets to tell us 1 such block, and, +there's only a limited number of peers. + +NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64. +*/ +type VoteSet struct { + chainID string + height int64 + round int32 + signedMsgType cmtproto.SignedMsgType + valSet *ValidatorSet + extensionsEnabled bool + + mtx cmtsync.Mutex + votesBitArray *bits.BitArray + votes []*Vote // Primary votes to share + sum int64 // Sum of voting power for seen votes, discounting conflicts + maj23 *BlockID // First 2/3 majority seen + votesByBlock map[string]*blockVotes // string(blockHash|blockParts) -> blockVotes + peerMaj23s map[P2PID]BlockID // Maj23 for each peer +} + +// NewVoteSet instantiates all fields of a new vote set. This constructor requires +// that no vote extension data be present on the votes that are added to the set. +func NewVoteSet(chainID string, height int64, round int32, + signedMsgType cmtproto.SignedMsgType, valSet *ValidatorSet) *VoteSet { + if height == 0 { + panic("Cannot make VoteSet for height == 0, doesn't make sense.") + } + return &VoteSet{ + chainID: chainID, + height: height, + round: round, + signedMsgType: signedMsgType, + valSet: valSet, + votesBitArray: bits.NewBitArray(valSet.Size()), + votes: make([]*Vote, valSet.Size()), + sum: 0, + maj23: nil, + votesByBlock: make(map[string]*blockVotes, valSet.Size()), + peerMaj23s: make(map[P2PID]BlockID), + } +} + +// NewExtendedVoteSet constructs a vote set with additional vote verification logic. +// The VoteSet constructed with NewExtendedVoteSet verifies the vote extension +// data for every vote added to the set. +func NewExtendedVoteSet(chainID string, height int64, round int32, + signedMsgType cmtproto.SignedMsgType, valSet *ValidatorSet) *VoteSet { + vs := NewVoteSet(chainID, height, round, signedMsgType, valSet) + vs.extensionsEnabled = true + return vs +} + +func (voteSet *VoteSet) ChainID() string { + return voteSet.chainID +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) GetHeight() int64 { + if voteSet == nil { + return 0 + } + return voteSet.height +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) GetRound() int32 { + if voteSet == nil { + return -1 + } + return voteSet.round +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) Type() byte { + if voteSet == nil { + return 0x00 + } + return byte(voteSet.signedMsgType) +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) Size() int { + if voteSet == nil { + return 0 + } + return voteSet.valSet.Size() +} + +// Returns added=true if vote is valid and new. +// Otherwise returns err=ErrVote[ +// +// UnexpectedStep | InvalidIndex | InvalidAddress | +// InvalidSignature | InvalidBlockHash | ConflictingVotes ] +// +// Duplicate votes return added=false, err=nil. +// Conflicting votes return added=*, err=ErrVoteConflictingVotes. +// NOTE: vote should not be mutated after adding. +// NOTE: VoteSet must not be nil +// NOTE: Vote must not be nil +func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) { + if voteSet == nil { + panic("AddVote() on nil VoteSet") + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + + return voteSet.addVote(vote) +} + +// NOTE: Validates as much as possible before attempting to verify the signature. +func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) { + if vote == nil { + return false, ErrVoteNil + } + valIndex := vote.ValidatorIndex + valAddr := vote.ValidatorAddress + blockKey := vote.BlockID.Key() + + // Ensure that validator index was set + if valIndex < 0 { + return false, fmt.Errorf("index < 0: %w", ErrVoteInvalidValidatorIndex) + } else if len(valAddr) == 0 { + return false, fmt.Errorf("empty address: %w", ErrVoteInvalidValidatorAddress) + } + + // Make sure the step matches. + if (vote.Height != voteSet.height) || + (vote.Round != voteSet.round) || + (vote.Type != voteSet.signedMsgType) { + return false, fmt.Errorf("expected %d/%d/%d, but got %d/%d/%d: %w", + voteSet.height, voteSet.round, voteSet.signedMsgType, + vote.Height, vote.Round, vote.Type, ErrVoteUnexpectedStep) + } + + // Ensure that signer is a validator. + lookupAddr, val := voteSet.valSet.GetByIndex(valIndex) + if val == nil { + return false, fmt.Errorf( + "cannot find validator %d in valSet of size %d: %w", + valIndex, voteSet.valSet.Size(), ErrVoteInvalidValidatorIndex) + } + + // Ensure that the signer has the right address. + if !bytes.Equal(valAddr, lookupAddr) { + return false, fmt.Errorf( + "vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\n"+ + "Ensure the genesis file is correct across all validators: %w", + valAddr, lookupAddr, valIndex, ErrVoteInvalidValidatorAddress) + } + + // If we already know of this vote, return false. + if existing, ok := voteSet.getVote(valIndex, blockKey); ok { + if bytes.Equal(existing.Signature, vote.Signature) { + return false, nil // duplicate + } + return false, fmt.Errorf("existing vote: %v; new vote: %v: %w", existing, vote, ErrVoteNonDeterministicSignature) + } + + // Check signature. + if voteSet.extensionsEnabled { + if err := vote.VerifyVoteAndExtension(voteSet.chainID, val.PubKey); err != nil { + return false, fmt.Errorf("failed to verify extended vote with ChainID %s and PubKey %s: %w", voteSet.chainID, val.PubKey, err) + } + } else { + if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil { + return false, fmt.Errorf("failed to verify vote with ChainID %s and PubKey %s: %w", voteSet.chainID, val.PubKey, err) + } + if len(vote.ExtensionSignature) > 0 || len(vote.Extension) > 0 { + return false, fmt.Errorf("unexpected vote extension data present in vote; ext_len %d, sig_len %d", + len(vote.Extension), + len(vote.ExtensionSignature), + ) + } + } + + // Add vote and get conflicting vote if any. + added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower) + if conflicting != nil { + return added, NewConflictingVoteError(conflicting, vote) + } + if !added { + panic("Expected to add non-conflicting vote") + } + return added, nil +} + +// Returns (vote, true) if vote exists for valIndex and blockKey. +func (voteSet *VoteSet) getVote(valIndex int32, blockKey string) (vote *Vote, ok bool) { + if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey { + return existing, true + } + if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil { + return existing, true + } + return nil, false +} + +// Assumes signature is valid. +// If conflicting vote exists, returns it. +func (voteSet *VoteSet) addVerifiedVote( + vote *Vote, + blockKey string, + votingPower int64, +) (added bool, conflicting *Vote) { + valIndex := vote.ValidatorIndex + + // Already exists in voteSet.votes? + if existing := voteSet.votes[valIndex]; existing != nil { + if existing.BlockID.Equals(vote.BlockID) { + panic("addVerifiedVote does not expect duplicate votes") + } + conflicting = existing + // Replace vote if blockKey matches voteSet.maj23. + if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey { + voteSet.votes[valIndex] = vote + voteSet.votesBitArray.SetIndex(int(valIndex), true) + } + // Otherwise don't add it to voteSet.votes + } else { + // Add to voteSet.votes and incr .sum + voteSet.votes[valIndex] = vote + voteSet.votesBitArray.SetIndex(int(valIndex), true) + voteSet.sum += votingPower + } + + votesByBlock, ok := voteSet.votesByBlock[blockKey] + if ok { + if conflicting != nil && !votesByBlock.peerMaj23 { + // There's a conflict and no peer claims that this block is special. + return false, conflicting + } + // We'll add the vote in a bit. + } else { + // .votesByBlock doesn't exist... + if conflicting != nil { + // ... and there's a conflicting vote. + // We're not even tracking this blockKey, so just forget it. + return false, conflicting + } + // ... and there's no conflicting vote. + // Start tracking this blockKey + votesByBlock = newBlockVotes(false, voteSet.valSet.Size()) + voteSet.votesByBlock[blockKey] = votesByBlock + // We'll add the vote in a bit. + } + + // Before adding to votesByBlock, see if we'll exceed quorum + origSum := votesByBlock.sum + quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1 + + // Add vote to votesByBlock + votesByBlock.addVerifiedVote(vote, votingPower) + + // If we just crossed the quorum threshold and have 2/3 majority... + if origSum < quorum && quorum <= votesByBlock.sum { + // Only consider the first quorum reached + if voteSet.maj23 == nil { + maj23BlockID := vote.BlockID + voteSet.maj23 = &maj23BlockID + // And also copy votes over to voteSet.votes + for i, vote := range votesByBlock.votes { + if vote != nil { + voteSet.votes[i] = vote + } + } + } + } + + return true, conflicting +} + +// If a peer claims that it has 2/3 majority for given blockKey, call this. +// NOTE: if there are too many peers, or too much peer churn, +// this can cause memory issues. +// TODO: implement ability to remove peers too +// NOTE: VoteSet must not be nil +func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error { + if voteSet == nil { + panic("SetPeerMaj23() on nil VoteSet") + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + + blockKey := blockID.Key() + + // Make sure peer hasn't already told us something. + if existing, ok := voteSet.peerMaj23s[peerID]; ok { + if existing.Equals(blockID) { + return nil // Nothing to do + } + return fmt.Errorf("setPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v", + peerID, blockID, existing) + } + voteSet.peerMaj23s[peerID] = blockID + + // Create .votesByBlock entry if needed. + votesByBlock, ok := voteSet.votesByBlock[blockKey] + if ok { + if votesByBlock.peerMaj23 { + return nil // Nothing to do + } + votesByBlock.peerMaj23 = true + // No need to copy votes, already there. + } else { + votesByBlock = newBlockVotes(true, voteSet.valSet.Size()) + voteSet.votesByBlock[blockKey] = votesByBlock + // No need to copy votes, no votes to copy over. + } + return nil +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) BitArray() *bits.BitArray { + if voteSet == nil { + return nil + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.votesBitArray.Copy() +} + +func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *bits.BitArray { + if voteSet == nil { + return nil + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + votesByBlock, ok := voteSet.votesByBlock[blockID.Key()] + if ok { + return votesByBlock.bitArray.Copy() + } + return nil +} + +// NOTE: if validator has conflicting votes, returns "canonical" vote +// Implements VoteSetReader. +func (voteSet *VoteSet) GetByIndex(valIndex int32) *Vote { + if voteSet == nil { + return nil + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.votes[valIndex] +} + +// List returns a copy of the list of votes stored by the VoteSet. +func (voteSet *VoteSet) List() []Vote { + if voteSet == nil || voteSet.votes == nil { + return nil + } + votes := make([]Vote, 0, len(voteSet.votes)) + for i := range voteSet.votes { + if voteSet.votes[i] != nil { + votes = append(votes, *voteSet.votes[i]) + } + } + return votes +} + +func (voteSet *VoteSet) GetByAddress(address []byte) *Vote { + if voteSet == nil { + return nil + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + valIndex, val := voteSet.valSet.GetByAddress(address) + if val == nil { + panic("GetByAddress(address) returned nil") + } + return voteSet.votes[valIndex] +} + +func (voteSet *VoteSet) HasTwoThirdsMajority() bool { + if voteSet == nil { + return false + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.maj23 != nil +} + +// Implements VoteSetReader. +func (voteSet *VoteSet) IsCommit() bool { + if voteSet == nil { + return false + } + if voteSet.signedMsgType != cmtproto.PrecommitType { + return false + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.maj23 != nil +} + +func (voteSet *VoteSet) HasTwoThirdsAny() bool { + if voteSet == nil { + return false + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3 +} + +func (voteSet *VoteSet) HasAll() bool { + if voteSet == nil { + return false + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.sum == voteSet.valSet.TotalVotingPower() +} + +// If there was a +2/3 majority for blockID, return blockID and true. +// Else, return the empty BlockID{} and false. +func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) { + if voteSet == nil { + return BlockID{}, false + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + if voteSet.maj23 != nil { + return *voteSet.maj23, true + } + return BlockID{}, false +} + +//-------------------------------------------------------------------------------- +// Strings and JSON + +const nilVoteSetString = "nil-VoteSet" + +// String returns a string representation of VoteSet. +// +// See StringIndented. +func (voteSet *VoteSet) String() string { + if voteSet == nil { + return nilVoteSetString + } + return voteSet.StringIndented("") +} + +// StringIndented returns an indented String. +// +// Height Round Type +// Votes +// Votes bit array +// 2/3+ majority +// +// See Vote#String. +func (voteSet *VoteSet) StringIndented(indent string) string { + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + + voteStrings := make([]string, len(voteSet.votes)) + for i, vote := range voteSet.votes { + if vote == nil { + voteStrings[i] = nilVoteStr + } else { + voteStrings[i] = vote.String() + } + } + return fmt.Sprintf(`VoteSet{ +%s H:%v R:%v T:%v +%s %v +%s %v +%s %v +%s}`, + indent, voteSet.height, voteSet.round, voteSet.signedMsgType, + indent, strings.Join(voteStrings, "\n"+indent+" "), + indent, voteSet.votesBitArray, + indent, voteSet.peerMaj23s, + indent) +} + +// Marshal the VoteSet to JSON. Same as String(), just in JSON, +// and without the height/round/signedMsgType (since its already included in the votes). +func (voteSet *VoteSet) MarshalJSON() ([]byte, error) { + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return cmtjson.Marshal(VoteSetJSON{ + voteSet.voteStrings(), + voteSet.bitArrayString(), + voteSet.peerMaj23s, + }) +} + +// More human readable JSON of the vote set +// NOTE: insufficient for unmarshalling from (compressed votes) +// TODO: make the peerMaj23s nicer to read (eg just the block hash) +type VoteSetJSON struct { + Votes []string `json:"votes"` + VotesBitArray string `json:"votes_bit_array"` + PeerMaj23s map[P2PID]BlockID `json:"peer_maj_23s"` +} + +// Return the bit-array of votes including +// the fraction of power that has voted like: +// "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66" +func (voteSet *VoteSet) BitArrayString() string { + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.bitArrayString() +} + +func (voteSet *VoteSet) bitArrayString() string { + bAString := voteSet.votesBitArray.String() + voted, total, fracVoted := voteSet.sumTotalFrac() + return fmt.Sprintf("%s %d/%d = %.2f", bAString, voted, total, fracVoted) +} + +// Returns a list of votes compressed to more readable strings. +func (voteSet *VoteSet) VoteStrings() []string { + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + return voteSet.voteStrings() +} + +func (voteSet *VoteSet) voteStrings() []string { + voteStrings := make([]string, len(voteSet.votes)) + for i, vote := range voteSet.votes { + if vote == nil { + voteStrings[i] = nilVoteStr + } else { + voteStrings[i] = vote.String() + } + } + return voteStrings +} + +// StringShort returns a short representation of VoteSet. +// +// 1. height +// 2. round +// 3. signed msg type +// 4. first 2/3+ majority +// 5. fraction of voted power +// 6. votes bit array +// 7. 2/3+ majority for each peer +func (voteSet *VoteSet) StringShort() string { + if voteSet == nil { + return nilVoteSetString + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + _, _, frac := voteSet.sumTotalFrac() + return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v(%v) %v %v}`, + voteSet.height, voteSet.round, voteSet.signedMsgType, voteSet.maj23, frac, voteSet.votesBitArray, voteSet.peerMaj23s) +} + +// LogString produces a logging suitable string representation of the +// vote set. +func (voteSet *VoteSet) LogString() string { + if voteSet == nil { + return nilVoteSetString + } + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + voted, total, frac := voteSet.sumTotalFrac() + + return fmt.Sprintf("Votes:%d/%d(%.3f)", voted, total, frac) +} + +// return the power voted, the total, and the fraction +func (voteSet *VoteSet) sumTotalFrac() (int64, int64, float64) { + voted, total := voteSet.sum, voteSet.valSet.TotalVotingPower() + fracVoted := float64(voted) / float64(total) + return voted, total, fracVoted +} + +//-------------------------------------------------------------------------------- +// Commit + +// MakeExtendedCommit constructs a Commit from the VoteSet. It only includes +// precommits for the block, which has 2/3+ majority, and nil. +// +// Panics if the vote type is not PrecommitType or if there's no +2/3 votes for +// a single block. +func (voteSet *VoteSet) MakeExtendedCommit(ap ABCIParams) *ExtendedCommit { + voteSet.mtx.Lock() + defer voteSet.mtx.Unlock() + + if voteSet.signedMsgType != cmtproto.PrecommitType { + panic("Cannot MakeExtendCommit() unless VoteSet.Type is PrecommitType") + } + + // Make sure we have a 2/3 majority + if voteSet.maj23 == nil { + panic("Cannot MakeExtendCommit() unless a blockhash has +2/3") + } + + // For every validator, get the precommit with extensions + sigs := make([]ExtendedCommitSig, len(voteSet.votes)) + for i, v := range voteSet.votes { + sig := v.ExtendedCommitSig() + // if block ID exists but doesn't match, exclude sig + if sig.BlockIDFlag == BlockIDFlagCommit && !v.BlockID.Equals(*voteSet.maj23) { + sig = NewExtendedCommitSigAbsent() + } + + sigs[i] = sig + } + + ec := &ExtendedCommit{ + Height: voteSet.GetHeight(), + Round: voteSet.GetRound(), + BlockID: *voteSet.maj23, + ExtendedSignatures: sigs, + } + if err := ec.EnsureExtensions(ap.VoteExtensionsEnabled(ec.Height)); err != nil { + panic(fmt.Errorf("problem with vote extension data when making extended commit of height %d; %w", + ec.Height, err)) + } + return ec +} + +//-------------------------------------------------------------------------------- + +/* +Votes for a particular block +There are two ways a *blockVotes gets created for a blockKey. +1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false) +2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true) +*/ +type blockVotes struct { + peerMaj23 bool // peer claims to have maj23 + bitArray *bits.BitArray // valIndex -> hasVote? + votes []*Vote // valIndex -> *Vote + sum int64 // vote sum +} + +func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes { + return &blockVotes{ + peerMaj23: peerMaj23, + bitArray: bits.NewBitArray(numValidators), + votes: make([]*Vote, numValidators), + sum: 0, + } +} + +func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) { + valIndex := vote.ValidatorIndex + if existing := vs.votes[valIndex]; existing == nil { + vs.bitArray.SetIndex(int(valIndex), true) + vs.votes[valIndex] = vote + vs.sum += votingPower + } +} + +func (vs *blockVotes) getByIndex(index int32) *Vote { + if vs == nil { + return nil + } + return vs.votes[index] +} + +//-------------------------------------------------------------------------------- + +// Common interface between *consensus.VoteSet and types.Commit +type VoteSetReader interface { + GetHeight() int64 + GetRound() int32 + Type() byte + Size() int + BitArray() *bits.BitArray + GetByIndex(int32) *Vote + IsCommit() bool +} diff --git a/types/vote_set_test.go b/types/vote_set_test.go new file mode 100644 index 0000000..810921b --- /dev/null +++ b/types/vote_set_test.go @@ -0,0 +1,622 @@ +package types + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + cmtrand "github.com/cometbft/cometbft/libs/rand" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +func TestVoteSet_AddVote_Good(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrevoteType, 10, 1, false) + val0 := privValidators[0] + + val0p, err := val0.GetPubKey() + require.NoError(t, err) + val0Addr := val0p.Address() + + assert.Nil(t, voteSet.GetByAddress(val0Addr)) + assert.False(t, voteSet.BitArray().GetIndex(0)) + blockID, ok := voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), "there should be no 2/3 majority") + + vote := &Vote{ + ValidatorAddress: val0Addr, + ValidatorIndex: 0, // since privValidators are in order + Height: height, + Round: round, + Type: cmtproto.PrevoteType, + Timestamp: cmttime.Now(), + BlockID: BlockID{nil, PartSetHeader{}}, + } + _, err = signAddVote(val0, vote, voteSet) + require.NoError(t, err) + + assert.NotNil(t, voteSet.GetByAddress(val0Addr)) + assert.True(t, voteSet.BitArray().GetIndex(0)) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), "there should be no 2/3 majority") +} + +func TestVoteSet_AddVote_Bad(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrevoteType, 10, 1, false) + + voteProto := &Vote{ + ValidatorAddress: nil, + ValidatorIndex: -1, + Height: height, + Round: round, + Timestamp: cmttime.Now(), + Type: cmtproto.PrevoteType, + BlockID: BlockID{nil, PartSetHeader{}}, + } + + // val0 votes for nil. + { + pubKey, err := privValidators[0].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 0) + added, err := signAddVote(privValidators[0], vote, voteSet) + if !added || err != nil { + t.Errorf("expected VoteSet.Add to succeed") + } + } + + // val0 votes again for some block. + { + pubKey, err := privValidators[0].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 0) + added, err := signAddVote(privValidators[0], withBlockHash(vote, cmtrand.Bytes(32)), voteSet) + if added || err == nil { + t.Errorf("expected VoteSet.Add to fail, conflicting vote.") + } + } + + // val1 votes on another height + { + pubKey, err := privValidators[1].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 1) + added, err := signAddVote(privValidators[1], withHeight(vote, height+1), voteSet) + if added || err == nil { + t.Errorf("expected VoteSet.Add to fail, wrong height") + } + } + + // val2 votes on another round + { + pubKey, err := privValidators[2].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 2) + added, err := signAddVote(privValidators[2], withRound(vote, round+1), voteSet) + if added || err == nil { + t.Errorf("expected VoteSet.Add to fail, wrong round") + } + } + + // val3 votes of another type. + { + pubKey, err := privValidators[3].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 3) + added, err := signAddVote(privValidators[3], withType(vote, byte(cmtproto.PrecommitType)), voteSet) + if added || err == nil { + t.Errorf("expected VoteSet.Add to fail, wrong type") + } + } + +} + +func TestVoteSet_2_3Majority(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrevoteType, 10, 1, false) + + voteProto := &Vote{ + ValidatorAddress: nil, // NOTE: must fill in + ValidatorIndex: -1, // NOTE: must fill in + Height: height, + Round: round, + Type: cmtproto.PrevoteType, + Timestamp: cmttime.Now(), + BlockID: BlockID{nil, PartSetHeader{}}, + } + // 6 out of 10 voted for nil. + for i := int32(0); i < 6; i++ { + pubKey, err := privValidators[i].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, i) + _, err = signAddVote(privValidators[i], vote, voteSet) + require.NoError(t, err) + } + blockID, ok := voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), "there should be no 2/3 majority") + + // 7th validator voted for some blockhash + { + pubKey, err := privValidators[6].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 6) + _, err = signAddVote(privValidators[6], withBlockHash(vote, cmtrand.Bytes(32)), voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), "there should be no 2/3 majority") + } + + // 8th validator voted for nil. + { + pubKey, err := privValidators[7].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 7) + _, err = signAddVote(privValidators[7], vote, voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.True(t, ok || blockID.IsZero(), "there should be 2/3 majority for nil") + } +} + +func TestVoteSet_2_3MajorityRedux(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrevoteType, 100, 1, false) + + blockHash := crypto.CRandBytes(32) + blockPartsTotal := uint32(123) + blockPartSetHeader := PartSetHeader{blockPartsTotal, crypto.CRandBytes(32)} + + voteProto := &Vote{ + ValidatorAddress: nil, // NOTE: must fill in + ValidatorIndex: -1, // NOTE: must fill in + Height: height, + Round: round, + Timestamp: cmttime.Now(), + Type: cmtproto.PrevoteType, + BlockID: BlockID{blockHash, blockPartSetHeader}, + } + + // 66 out of 100 voted for nil. + for i := int32(0); i < 66; i++ { + pubKey, err := privValidators[i].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, i) + _, err = signAddVote(privValidators[i], vote, voteSet) + require.NoError(t, err) + } + blockID, ok := voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), + "there should be no 2/3 majority") + + // 67th validator voted for nil + { + pubKey, err := privValidators[66].GetPubKey() + require.NoError(t, err) + adrr := pubKey.Address() + vote := withValidator(voteProto, adrr, 66) + _, err = signAddVote(privValidators[66], withBlockHash(vote, nil), voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), + "there should be no 2/3 majority: last vote added was nil") + } + + // 68th validator voted for a different BlockParts PartSetHeader + { + pubKey, err := privValidators[67].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 67) + blockPartsHeader := PartSetHeader{blockPartsTotal, crypto.CRandBytes(32)} + _, err = signAddVote(privValidators[67], withBlockPartSetHeader(vote, blockPartsHeader), voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), + "there should be no 2/3 majority: last vote added had different PartSetHeader Hash") + } + + // 69th validator voted for different BlockParts Total + { + pubKey, err := privValidators[68].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 68) + blockPartsHeader := PartSetHeader{blockPartsTotal + 1, blockPartSetHeader.Hash} + _, err = signAddVote(privValidators[68], withBlockPartSetHeader(vote, blockPartsHeader), voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), + "there should be no 2/3 majority: last vote added had different PartSetHeader Total") + } + + // 70th validator voted for different BlockHash + { + pubKey, err := privValidators[69].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 69) + _, err = signAddVote(privValidators[69], withBlockHash(vote, cmtrand.Bytes(32)), voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.False(t, ok || !blockID.IsZero(), + "there should be no 2/3 majority: last vote added had different BlockHash") + } + + // 71st validator voted for the right BlockHash & BlockPartSetHeader + { + pubKey, err := privValidators[70].GetPubKey() + require.NoError(t, err) + addr := pubKey.Address() + vote := withValidator(voteProto, addr, 70) + _, err = signAddVote(privValidators[70], vote, voteSet) + require.NoError(t, err) + blockID, ok = voteSet.TwoThirdsMajority() + assert.True(t, ok && blockID.Equals(BlockID{blockHash, blockPartSetHeader}), + "there should be 2/3 majority") + } +} + +func TestVoteSet_Conflicts(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrevoteType, 4, 1, false) + blockHash1 := cmtrand.Bytes(32) + blockHash2 := cmtrand.Bytes(32) + + voteProto := &Vote{ + ValidatorAddress: nil, + ValidatorIndex: -1, + Height: height, + Round: round, + Timestamp: cmttime.Now(), + Type: cmtproto.PrevoteType, + BlockID: BlockID{nil, PartSetHeader{}}, + } + + val0, err := privValidators[0].GetPubKey() + require.NoError(t, err) + val0Addr := val0.Address() + + // val0 votes for nil. + { + vote := withValidator(voteProto, val0Addr, 0) + added, err := signAddVote(privValidators[0], vote, voteSet) + if !added || err != nil { + t.Errorf("expected VoteSet.Add to succeed") + } + } + + // val0 votes again for blockHash1. + { + vote := withValidator(voteProto, val0Addr, 0) + added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) + assert.False(t, added, "conflicting vote") + assert.Error(t, err, "conflicting vote") + } + + // start tracking blockHash1 + err = voteSet.SetPeerMaj23("peerA", BlockID{blockHash1, PartSetHeader{}}) + require.NoError(t, err) + + // val0 votes again for blockHash1. + { + vote := withValidator(voteProto, val0Addr, 0) + added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) + assert.True(t, added, "called SetPeerMaj23()") + assert.Error(t, err, "conflicting vote") + } + + // attempt tracking blockHash2, should fail because already set for peerA. + err = voteSet.SetPeerMaj23("peerA", BlockID{blockHash2, PartSetHeader{}}) + require.Error(t, err) + + // val0 votes again for blockHash1. + { + vote := withValidator(voteProto, val0Addr, 0) + added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash2), voteSet) + assert.False(t, added, "duplicate SetPeerMaj23() from peerA") + assert.Error(t, err, "conflicting vote") + } + + // val1 votes for blockHash1. + { + pv, err := privValidators[1].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 1) + added, err := signAddVote(privValidators[1], withBlockHash(vote, blockHash1), voteSet) + if !added || err != nil { + t.Errorf("expected VoteSet.Add to succeed") + } + } + + // check + if voteSet.HasTwoThirdsMajority() { + t.Errorf("we shouldn't have 2/3 majority yet") + } + if voteSet.HasTwoThirdsAny() { + t.Errorf("we shouldn't have 2/3 if any votes yet") + } + + // val2 votes for blockHash2. + { + pv, err := privValidators[2].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 2) + added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash2), voteSet) + if !added || err != nil { + t.Errorf("expected VoteSet.Add to succeed") + } + } + + // check + if voteSet.HasTwoThirdsMajority() { + t.Errorf("we shouldn't have 2/3 majority yet") + } + if !voteSet.HasTwoThirdsAny() { + t.Errorf("we should have 2/3 if any votes") + } + + // now attempt tracking blockHash1 + err = voteSet.SetPeerMaj23("peerB", BlockID{blockHash1, PartSetHeader{}}) + require.NoError(t, err) + + // val2 votes for blockHash1. + { + pv, err := privValidators[2].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 2) + added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash1), voteSet) + assert.True(t, added) + assert.Error(t, err, "conflicting vote") + } + + // check + if !voteSet.HasTwoThirdsMajority() { + t.Errorf("we should have 2/3 majority for blockHash1") + } + blockIDMaj23, _ := voteSet.TwoThirdsMajority() + if !bytes.Equal(blockIDMaj23.Hash, blockHash1) { + t.Errorf("got the wrong 2/3 majority blockhash") + } + if !voteSet.HasTwoThirdsAny() { + t.Errorf("we should have 2/3 if any votes") + } +} + +func TestVoteSet_MakeCommit(t *testing.T) { + height, round := int64(1), int32(0) + voteSet, _, privValidators := randVoteSet(height, round, cmtproto.PrecommitType, 10, 1, true) + blockHash, blockPartSetHeader := crypto.CRandBytes(32), PartSetHeader{123, crypto.CRandBytes(32)} + + voteProto := &Vote{ + ValidatorAddress: nil, + ValidatorIndex: -1, + Height: height, + Round: round, + Timestamp: cmttime.Now(), + Type: cmtproto.PrecommitType, + BlockID: BlockID{blockHash, blockPartSetHeader}, + } + + // 6 out of 10 voted for some block. + for i := int32(0); i < 6; i++ { + pv, err := privValidators[i].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, i) + _, err = signAddVote(privValidators[i], vote, voteSet) + if err != nil { + t.Error(err) + } + } + + // MakeCommit should fail. + veHeightParam := ABCIParams{VoteExtensionsEnableHeight: height} + assert.Panics(t, func() { voteSet.MakeExtendedCommit(veHeightParam) }, "Doesn't have +2/3 majority") + + // 7th voted for some other block. + { + pv, err := privValidators[6].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 6) + vote = withBlockHash(vote, cmtrand.Bytes(32)) + vote = withBlockPartSetHeader(vote, PartSetHeader{123, cmtrand.Bytes(32)}) + + _, err = signAddVote(privValidators[6], vote, voteSet) + require.NoError(t, err) + } + + // The 8th voted like everyone else. + { + pv, err := privValidators[7].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 7) + _, err = signAddVote(privValidators[7], vote, voteSet) + require.NoError(t, err) + } + + // The 9th voted for nil. + { + pv, err := privValidators[8].GetPubKey() + assert.NoError(t, err) + addr := pv.Address() + vote := withValidator(voteProto, addr, 8) + vote.BlockID = BlockID{} + + _, err = signAddVote(privValidators[8], vote, voteSet) + require.NoError(t, err) + } + + extCommit := voteSet.MakeExtendedCommit(veHeightParam) + + // Commit should have 10 elements + assert.Equal(t, 10, len(extCommit.ExtendedSignatures)) + + // Ensure that Commit is good. + if err := extCommit.ValidateBasic(); err != nil { + t.Errorf("error in Commit.ValidateBasic(): %v", err) + } +} + +// TestVoteSet_VoteExtensionsEnabled tests that the vote set correctly validates +// vote extension data when either required or not required. +func TestVoteSet_VoteExtensionsEnabled(t *testing.T) { + for _, tc := range []struct { + name string + requireExtensions bool + addExtension bool + exepectError bool + }{ + { + name: "no extension but expected", + requireExtensions: true, + addExtension: false, + exepectError: true, + }, + { + name: "invalid extensions but not expected", + requireExtensions: true, + addExtension: false, + exepectError: true, + }, + { + name: "no extension and not expected", + requireExtensions: false, + addExtension: false, + exepectError: false, + }, + { + name: "extension and expected", + requireExtensions: true, + addExtension: true, + exepectError: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + height, round := int64(1), int32(0) + valSet, privValidators := RandValidatorSet(5, 10) + var voteSet *VoteSet + if tc.requireExtensions { + voteSet = NewExtendedVoteSet("test_chain_id", height, round, cmtproto.PrecommitType, valSet) + } else { + voteSet = NewVoteSet("test_chain_id", height, round, cmtproto.PrecommitType, valSet) + } + + val0 := privValidators[0] + + val0p, err := val0.GetPubKey() + require.NoError(t, err) + val0Addr := val0p.Address() + blockHash := crypto.CRandBytes(32) + blockPartsTotal := uint32(123) + blockPartSetHeader := PartSetHeader{blockPartsTotal, crypto.CRandBytes(32)} + + vote := &Vote{ + ValidatorAddress: val0Addr, + ValidatorIndex: 0, + Height: height, + Round: round, + Type: cmtproto.PrecommitType, + Timestamp: cmttime.Now(), + BlockID: BlockID{blockHash, blockPartSetHeader}, + } + v := vote.ToProto() + err = val0.SignVote(voteSet.ChainID(), v) + require.NoError(t, err) + vote.Signature = v.Signature + + if tc.addExtension { + vote.ExtensionSignature = v.ExtensionSignature + } + + added, err := voteSet.AddVote(vote) + if tc.exepectError { + require.Error(t, err) + require.False(t, added) + } else { + require.NoError(t, err) + require.True(t, added) + } + }) + } +} + +// NOTE: privValidators are in order +func randVoteSet( + height int64, + round int32, + signedMsgType cmtproto.SignedMsgType, + numValidators int, + votingPower int64, + extEnabled bool, +) (*VoteSet, *ValidatorSet, []PrivValidator) { + valSet, privValidators := RandValidatorSet(numValidators, votingPower) + if extEnabled { + if signedMsgType != cmtproto.PrecommitType { + return nil, nil, nil + } + return NewExtendedVoteSet("test_chain_id", height, round, signedMsgType, valSet), valSet, privValidators + } + return NewVoteSet("test_chain_id", height, round, signedMsgType, valSet), valSet, privValidators +} + +// Convenience: Return new vote with different validator address/index +func withValidator(vote *Vote, addr []byte, idx int32) *Vote { + vote = vote.Copy() + vote.ValidatorAddress = addr + vote.ValidatorIndex = idx + return vote +} + +// Convenience: Return new vote with different height +func withHeight(vote *Vote, height int64) *Vote { + vote = vote.Copy() + vote.Height = height + return vote +} + +// Convenience: Return new vote with different round +func withRound(vote *Vote, round int32) *Vote { + vote = vote.Copy() + vote.Round = round + return vote +} + +// Convenience: Return new vote with different type +func withType(vote *Vote, signedMsgType byte) *Vote { + vote = vote.Copy() + vote.Type = cmtproto.SignedMsgType(signedMsgType) + return vote +} + +// Convenience: Return new vote with different blockHash +func withBlockHash(vote *Vote, blockHash []byte) *Vote { + vote = vote.Copy() + vote.BlockID.Hash = blockHash + return vote +} + +// Convenience: Return new vote with different blockParts +func withBlockPartSetHeader(vote *Vote, blockPartsHeader PartSetHeader) *Vote { + vote = vote.Copy() + vote.BlockID.PartSetHeader = blockPartsHeader + return vote +} diff --git a/types/vote_test.go b/types/vote_test.go new file mode 100644 index 0000000..389ed9a --- /dev/null +++ b/types/vote_test.go @@ -0,0 +1,600 @@ +package types + +import ( + "fmt" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/cometbft/cometbft/libs/protoio" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttime "github.com/cometbft/cometbft/types/time" +) + +func examplePrevote() *Vote { + return exampleVote(byte(cmtproto.PrevoteType)) +} + +func examplePrecommit() *Vote { + vote := exampleVote(byte(cmtproto.PrecommitType)) + vote.Extension = []byte("extension") + vote.ExtensionSignature = []byte("signature") + return vote +} + +func exampleVote(t byte) *Vote { + stamp, err := time.Parse(TimeFormat, "2017-12-25T03:00:01.234Z") + if err != nil { + panic(err) + } + + return &Vote{ + Type: cmtproto.SignedMsgType(t), + Height: 12345, + Round: 2, + Timestamp: stamp, + BlockID: BlockID{ + Hash: tmhash.Sum([]byte("blockID_hash")), + PartSetHeader: PartSetHeader{ + Total: 1000000, + Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")), + }, + }, + ValidatorAddress: crypto.AddressHash([]byte("validator_address")), + ValidatorIndex: 56789, + } +} + +func TestVoteSignable(t *testing.T) { + vote := examplePrecommit() + v := vote.ToProto() + signBytes := VoteSignBytes("test_chain_id", v) + pb := CanonicalizeVote("test_chain_id", v) + expected, err := protoio.MarshalDelimited(&pb) + require.NoError(t, err) + + require.Equal(t, expected, signBytes, "Got unexpected sign bytes for Vote.") +} + +func TestVoteSignBytesTestVectors(t *testing.T) { + tests := []struct { + chainID string + vote *Vote + want []byte + }{ + 0: { + "", &Vote{}, + // NOTE: Height and Round are skipped here. This case needs to be considered while parsing. + []byte{0xd, 0x2a, 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1}, + }, + // with proper (fixed size) height and round (PreCommit): + 1: { + "", &Vote{Height: 1, Round: 1, Type: cmtproto.PrecommitType}, + []byte{ + 0x21, // length + 0x8, // (field_number << 3) | wire_type + 0x2, // PrecommitType + 0x11, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height + 0x19, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round + 0x2a, // (field_number << 3) | wire_type + // remaining fields (timestamp): + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, + }, + // with proper (fixed size) height and round (PreVote): + 2: { + "", &Vote{Height: 1, Round: 1, Type: cmtproto.PrevoteType}, + []byte{ + 0x21, // length + 0x8, // (field_number << 3) | wire_type + 0x1, // PrevoteType + 0x11, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height + 0x19, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round + 0x2a, // (field_number << 3) | wire_type + // remaining fields (timestamp): + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, + }, + 3: { + "", &Vote{Height: 1, Round: 1}, + []byte{ + 0x1f, // length + 0x11, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height + 0x19, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round + // remaining fields (timestamp): + 0x2a, + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, + }, + // containing non-empty chain_id: + 4: { + "test_chain_id", &Vote{Height: 1, Round: 1}, + []byte{ + 0x2e, // length + 0x11, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height + 0x19, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round + // remaining fields: + 0x2a, // (field_number << 3) | wire_type + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, // timestamp + // (field_number << 3) | wire_type + 0x32, + 0xd, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, + }, // chainID + }, + // containing vote extension + 5: { + "test_chain_id", &Vote{ + Height: 1, + Round: 1, + Extension: []byte("extension"), + }, + []byte{ + 0x2e, // length + 0x11, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height + 0x19, // (field_number << 3) | wire_type + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round + // remaning fields: + 0x2a, // (field_number << 3) | wire_type + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, // timestamp + // (field_number << 3) | wire_type + 0x32, + 0xd, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, // chainID + }, // chainID + }, + } + for i, tc := range tests { + v := tc.vote.ToProto() + got := VoteSignBytes(tc.chainID, v) + assert.Equal(t, len(tc.want), len(got), "test case #%v: got unexpected sign bytes length for Vote.", i) + assert.Equal(t, tc.want, got, "test case #%v: got unexpected sign bytes for Vote.", i) + } +} + +func TestVoteProposalNotEq(t *testing.T) { + cv := CanonicalizeVote("", &cmtproto.Vote{Height: 1, Round: 1}) + p := CanonicalizeProposal("", &cmtproto.Proposal{Height: 1, Round: 1}) + vb, err := proto.Marshal(&cv) + require.NoError(t, err) + pb, err := proto.Marshal(&p) + require.NoError(t, err) + require.NotEqual(t, vb, pb) +} + +func TestVoteVerifySignature(t *testing.T) { + privVal := NewMockPV() + pubkey, err := privVal.GetPubKey() + require.NoError(t, err) + + vote := examplePrecommit() + v := vote.ToProto() + signBytes := VoteSignBytes("test_chain_id", v) + + // sign it + err = privVal.SignVote("test_chain_id", v) + require.NoError(t, err) + + // verify the same vote + valid := pubkey.VerifySignature(VoteSignBytes("test_chain_id", v), v.Signature) + require.True(t, valid) + + // serialize, deserialize and verify again.... + precommit := new(cmtproto.Vote) + bs, err := proto.Marshal(v) + require.NoError(t, err) + err = proto.Unmarshal(bs, precommit) + require.NoError(t, err) + + // verify the transmitted vote + newSignBytes := VoteSignBytes("test_chain_id", precommit) + require.Equal(t, string(signBytes), string(newSignBytes)) + valid = pubkey.VerifySignature(newSignBytes, precommit.Signature) + require.True(t, valid) +} + +// TestVoteExtension tests that the vote verification behaves correctly in each case +// of vote extension being set on the vote. +func TestVoteExtension(t *testing.T) { + testCases := []struct { + name string + extension []byte + includeSignature bool + expectError bool + }{ + { + name: "all fields present", + extension: []byte("extension"), + includeSignature: true, + expectError: false, + }, + { + name: "no extension signature", + extension: []byte("extension"), + includeSignature: false, + expectError: true, + }, + { + name: "empty extension", + includeSignature: true, + expectError: false, + }, + { + name: "no extension and no signature", + includeSignature: false, + expectError: true, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + height, round := int64(1), int32(0) + privVal := NewMockPV() + pk, err := privVal.GetPubKey() + require.NoError(t, err) + vote := &Vote{ + ValidatorAddress: pk.Address(), + ValidatorIndex: 0, + Height: height, + Round: round, + Timestamp: cmttime.Now(), + Type: cmtproto.PrecommitType, + BlockID: makeBlockIDRandom(), + } + + v := vote.ToProto() + err = privVal.SignVote("test_chain_id", v) + require.NoError(t, err) + vote.Signature = v.Signature + if tc.includeSignature { + vote.ExtensionSignature = v.ExtensionSignature + } + err = vote.VerifyExtension("test_chain_id", pk) + if tc.expectError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestIsVoteTypeValid(t *testing.T) { + tc := []struct { + name string + in cmtproto.SignedMsgType + out bool + }{ + {"Prevote", cmtproto.PrevoteType, true}, + {"Precommit", cmtproto.PrecommitType, true}, + {"InvalidType", cmtproto.SignedMsgType(0x3), false}, + } + + for _, tt := range tc { + tt := tt + t.Run(tt.name, func(st *testing.T) { + if rs := IsVoteTypeValid(tt.in); rs != tt.out { + t.Errorf("got unexpected Vote type. Expected:\n%v\nGot:\n%v", rs, tt.out) + } + }) + } +} + +func TestVoteVerify(t *testing.T) { + privVal := NewMockPV() + pubkey, err := privVal.GetPubKey() + require.NoError(t, err) + + vote := examplePrevote() + vote.ValidatorAddress = pubkey.Address() + + err = vote.Verify("test_chain_id", ed25519.GenPrivKey().PubKey()) + if assert.Error(t, err) { + assert.Equal(t, ErrVoteInvalidValidatorAddress, err) + } + + err = vote.Verify("test_chain_id", pubkey) + if assert.Error(t, err) { + assert.Equal(t, ErrVoteInvalidSignature, err) + } +} + +func TestVoteString(t *testing.T) { + str := examplePrecommit().String() + expected := `Vote{56789:6AF1F4111082 12345/02/SIGNED_MSG_TYPE_PRECOMMIT(Precommit) 8B01023386C3 000000000000 657874656E73 @ 2017-12-25T03:00:01.234Z}` //nolint:lll //ignore line length for tests + if str != expected { + t.Errorf("got unexpected string for Vote. Expected:\n%v\nGot:\n%v", expected, str) + } + + str2 := examplePrevote().String() + expected = `Vote{56789:6AF1F4111082 12345/02/SIGNED_MSG_TYPE_PREVOTE(Prevote) 8B01023386C3 000000000000 000000000000 @ 2017-12-25T03:00:01.234Z}` //nolint:lll //ignore line length for tests + if str2 != expected { + t.Errorf("got unexpected string for Vote. Expected:\n%v\nGot:\n%v", expected, str2) + } +} + +func signVote(t *testing.T, pv PrivValidator, chainID string, vote *Vote) { + t.Helper() + + v := vote.ToProto() + require.NoError(t, pv.SignVote(chainID, v)) + vote.Signature = v.Signature + vote.ExtensionSignature = v.ExtensionSignature +} + +func TestValidVotes(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + vote *Vote + malleateVote func(*Vote) + }{ + {"good prevote", examplePrevote(), func(v *Vote) {}}, + {"good precommit without vote extension", examplePrecommit(), func(v *Vote) { v.Extension = nil }}, + {"good precommit with vote extension", examplePrecommit(), func(v *Vote) { v.Extension = []byte("extension") }}, + } + for _, tc := range testCases { + signVote(t, privVal, "test_chain_id", tc.vote) + tc.malleateVote(tc.vote) + require.NoError(t, tc.vote.ValidateBasic(), "ValidateBasic for %s", tc.name) + require.NoError(t, tc.vote.EnsureExtension(), "EnsureExtension for %s", tc.name) + } +} + +func TestInvalidVotes(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + malleateVote func(*Vote) + }{ + {"negative height", func(v *Vote) { v.Height = -1 }}, + {"negative round", func(v *Vote) { v.Round = -1 }}, + {"zero Height", func(v *Vote) { v.Height = 0 }}, + {"invalid block ID", func(v *Vote) { v.BlockID = BlockID{[]byte{1, 2, 3}, PartSetHeader{111, []byte("blockparts")}} }}, + {"invalid address", func(v *Vote) { v.ValidatorAddress = make([]byte, 1) }}, + {"invalid validator index", func(v *Vote) { v.ValidatorIndex = -1 }}, + {"invalid signature", func(v *Vote) { v.Signature = nil }}, + {"oversized signature", func(v *Vote) { v.Signature = make([]byte, MaxSignatureSize+1) }}, + } + for _, tc := range testCases { + prevote := examplePrevote() + signVote(t, privVal, "test_chain_id", prevote) + tc.malleateVote(prevote) + require.Error(t, prevote.ValidateBasic(), "ValidateBasic for %s in invalid prevote", tc.name) + require.NoError(t, prevote.EnsureExtension(), "EnsureExtension for %s in invalid prevote", tc.name) + + precommit := examplePrecommit() + signVote(t, privVal, "test_chain_id", precommit) + tc.malleateVote(precommit) + require.Error(t, precommit.ValidateBasic(), "ValidateBasic for %s in invalid precommit", tc.name) + require.NoError(t, precommit.EnsureExtension(), "EnsureExtension for %s in invalid precommit", tc.name) + } +} + +func TestInvalidPrevotes(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + malleateVote func(*Vote) + }{ + {"vote extension present", func(v *Vote) { v.Extension = []byte("extension") }}, + {"vote extension signature present", func(v *Vote) { v.ExtensionSignature = []byte("signature") }}, + } + for _, tc := range testCases { + prevote := examplePrevote() + signVote(t, privVal, "test_chain_id", prevote) + tc.malleateVote(prevote) + require.Error(t, prevote.ValidateBasic(), "ValidateBasic for %s", tc.name) + require.NoError(t, prevote.EnsureExtension(), "EnsureExtension for %s", tc.name) + } +} + +func TestInvalidPrecommitExtensions(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + malleateVote func(*Vote) + }{ + {"vote extension present without signature", func(v *Vote) { + v.Extension = []byte("extension") + v.ExtensionSignature = nil + }}, + {"oversized vote extension signature", func(v *Vote) { v.ExtensionSignature = make([]byte, MaxSignatureSize+1) }}, + } + for _, tc := range testCases { + precommit := examplePrecommit() + signVote(t, privVal, "test_chain_id", precommit) + tc.malleateVote(precommit) + // ValidateBasic ensures that vote extensions, if present, are well formed + require.Error(t, precommit.ValidateBasic(), "ValidateBasic for %s", tc.name) + } +} + +func TestEnsureVoteExtension(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + malleateVote func(*Vote) + expectError bool + }{ + {"vote extension signature absent", func(v *Vote) { + v.Extension = nil + v.ExtensionSignature = nil + }, true}, + {"vote extension signature present", func(v *Vote) { + v.ExtensionSignature = []byte("extension signature") + }, false}, + } + for _, tc := range testCases { + precommit := examplePrecommit() + signVote(t, privVal, "test_chain_id", precommit) + tc.malleateVote(precommit) + if tc.expectError { + require.Error(t, precommit.EnsureExtension(), "EnsureExtension for %s", tc.name) + } else { + require.NoError(t, precommit.EnsureExtension(), "EnsureExtension for %s", tc.name) + } + } +} + +func TestVoteProtobuf(t *testing.T) { + privVal := NewMockPV() + vote := examplePrecommit() + v := vote.ToProto() + err := privVal.SignVote("test_chain_id", v) + vote.Signature = v.Signature + require.NoError(t, err) + + testCases := []struct { + msg string + vote *Vote + convertsOk bool + passesValidateBasic bool + }{ + {"success", vote, true, true}, + {"fail vote validate basic", &Vote{}, true, false}, + } + for _, tc := range testCases { + protoProposal := tc.vote.ToProto() + + v, err := VoteFromProto(protoProposal) + if tc.convertsOk { + require.NoError(t, err) + } else { + require.Error(t, err) + } + + err = v.ValidateBasic() + if tc.passesValidateBasic { + require.NoError(t, err) + require.Equal(t, tc.vote, v, tc.msg) + } else { + require.Error(t, err) + } + } +} + +func TestSignAndCheckVote(t *testing.T) { + privVal := NewMockPV() + + testCases := []struct { + name string + extensionsEnabled bool + vote *Vote + expectError bool + }{ + { + name: "precommit with extension signature", + extensionsEnabled: true, + vote: examplePrecommit(), + expectError: false, + }, + { + name: "precommit with extension signature", + extensionsEnabled: false, + vote: examplePrecommit(), + expectError: false, + }, + { + name: "precommit with extension signature for a nil block", + extensionsEnabled: true, + vote: func() *Vote { + v := examplePrecommit() + v.BlockID = BlockID{make([]byte, 0), PartSetHeader{0, make([]byte, 0)}} + return v + }(), + expectError: true, + }, + { + name: "precommit with extension signature for a nil block", + extensionsEnabled: false, + vote: func() *Vote { + v := examplePrecommit() + v.BlockID = BlockID{make([]byte, 0), PartSetHeader{0, make([]byte, 0)}} + return v + }(), + expectError: true, + }, + { + name: "precommit without extension", + extensionsEnabled: true, + vote: func() *Vote { + v := examplePrecommit() + v.Extension = make([]byte, 0) + return v + }(), + expectError: false, + }, + { + name: "precommit without extension", + extensionsEnabled: false, + vote: func() *Vote { + v := examplePrecommit() + v.Extension = make([]byte, 0) + return v + }(), + expectError: false, + }, + { + name: "prevote", + extensionsEnabled: true, + vote: examplePrevote(), + expectError: true, + }, + { + name: "prevote", + extensionsEnabled: false, + vote: examplePrevote(), + expectError: false, + }, + { + name: "prevote with extension", + extensionsEnabled: true, + vote: func() *Vote { + v := examplePrevote() + v.Extension = []byte("extension") + return v + }(), + expectError: true, + }, + { + name: "prevote with extension", + extensionsEnabled: false, + vote: func() *Vote { + v := examplePrevote() + v.Extension = []byte("extension") + return v + }(), + expectError: true, + }, + } + + for _, tc := range testCases { + t.Run(fmt.Sprintf("%s (extensionsEnabled: %t) ", tc.name, tc.extensionsEnabled), func(t *testing.T) { + _, err := SignAndCheckVote(tc.vote, privVal, "test_chain_id", tc.extensionsEnabled) + if tc.expectError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..5867d7d --- /dev/null +++ b/version/version.go @@ -0,0 +1,21 @@ +package version + +const ( + // TMCoreSemVer is the used as the fallback version of CometBFT + // when not using git describe. It is formatted with semantic versioning. + TMCoreSemVer = "0.38.19" + // ABCISemVer is the semantic version of the ABCI protocol + ABCISemVer = "2.0.0" + ABCIVersion = ABCISemVer + // P2PProtocol versions all p2p behavior and msgs. + // This includes proposer selection. + P2PProtocol uint64 = 8 + + // BlockProtocol versions all block data structures and processing. + // This includes validity of blocks and state updates. + BlockProtocol uint64 = 11 +) + +// TMGitCommitHash uses git rev-parse HEAD to find commit hash which is helpful +// for the engineering team when working with the cometbft binary. See Makefile +var TMGitCommitHash = ""